|
| 1 | +import os |
| 2 | +import subprocess |
| 3 | +from typing import Any, Mapping |
| 4 | + |
| 5 | +import tomlkit |
| 6 | +from arclet.alconna import Alconna, Arparma, CommandMeta, Option, Args |
| 7 | +from clilte import BasePlugin, PluginMetadata, register |
| 8 | +from clilte.core import Next |
| 9 | +from colorama.ansi import Fore, Style, code_to_chars |
| 10 | +from platformdirs import user_config_path |
| 11 | + |
| 12 | +from entari_cli import i18n_ |
| 13 | +from entari_cli.project import get_project_root |
| 14 | +from entari_cli.setting import DEFAULT, del_item, get_item, set_item, print_flattened |
| 15 | + |
| 16 | + |
| 17 | +ITALIC = code_to_chars(3) |
| 18 | + |
| 19 | + |
| 20 | +def get_editor() -> str: |
| 21 | + for key in "VISUAL", "EDITOR": |
| 22 | + rv = os.getenv(key) |
| 23 | + if rv: |
| 24 | + return rv |
| 25 | + if os.name == "nt": |
| 26 | + return "notepad" |
| 27 | + for editor in "sensible-editor", "vim", "nano": |
| 28 | + if os.system(f"which {editor} >/dev/null 2>&1") == 0: |
| 29 | + return editor |
| 30 | + return "vi" |
| 31 | + |
| 32 | + |
| 33 | +@register("entari_cli.plugins") |
| 34 | +class SelfSetting(BasePlugin): |
| 35 | + def init(self): |
| 36 | + return Alconna( |
| 37 | + "setting", |
| 38 | + Args["key/?#Config key", str]["value/?#Config value", str], |
| 39 | + Option("-l|--local", help_text="Set config in the local configuration file"), |
| 40 | + Option("-d|--delete", help_text="Unset a configuration key"), |
| 41 | + Option("-e|--edit", help_text="Open the configuration file in the editor(defined by EDITOR env var)"), |
| 42 | + meta=CommandMeta("Display the entari-cli configuration") |
| 43 | + ) |
| 44 | + |
| 45 | + def meta(self) -> PluginMetadata: |
| 46 | + return PluginMetadata( |
| 47 | + name="generate", |
| 48 | + description=i18n_.commands.generate.description(), |
| 49 | + version="0.1.0", |
| 50 | + priority=1, |
| 51 | + ) |
| 52 | + |
| 53 | + def get_setting(self, local: bool): |
| 54 | + setting_dir = get_project_root() if local else user_config_path("entari-cli", appauthor=False) |
| 55 | + setting_file = setting_dir / (".entari_cli.toml" if local else "config.toml") |
| 56 | + if not setting_file.exists(): |
| 57 | + return None |
| 58 | + with setting_file.open("r", encoding="utf-8") as f: |
| 59 | + return tomlkit.load(f) |
| 60 | + |
| 61 | + def get_config(self, key: str): |
| 62 | + value = None |
| 63 | + local_cfg = self.get_setting(True) |
| 64 | + global_cfg = self.get_setting(False) |
| 65 | + if local_cfg: |
| 66 | + value = get_item(local_cfg, key) |
| 67 | + if global_cfg and value is None: |
| 68 | + value = get_item(global_cfg, key) |
| 69 | + if value is None: |
| 70 | + return DEFAULT[key] |
| 71 | + return value |
| 72 | + |
| 73 | + def dispatch(self, result: Arparma, next_: Next): |
| 74 | + if result.find("setting.edit"): |
| 75 | + if result.find("setting.args.key"): |
| 76 | + return f"{Fore.RED}Cannot specify an argument when `--edit` is given{Fore.RESET}" |
| 77 | + if result.find("setting.delete"): |
| 78 | + return f"{Fore.RED}`--delete` doesn't work when `--edit` is given{Fore.RESET}" |
| 79 | + setting_dir = get_project_root() if result.find("setting.local") else user_config_path("entari-cli", appauthor=False) |
| 80 | + setting_file = setting_dir / (".entari_cli.toml" if result.find("setting.local") else "config.toml") |
| 81 | + setting_dir.mkdir(parents=True, exist_ok=True) |
| 82 | + editor = get_editor() |
| 83 | + proc = subprocess.Popen(f"{editor} {setting_file!s}", shell=True) |
| 84 | + |
| 85 | + if proc.wait() == 0: |
| 86 | + return f"{Fore.GREEN}Configuration file edited successfully.{Fore.RESET}" |
| 87 | + return f"{Fore.RED}Editor {editor} exited abnormally{Fore.RESET}" |
| 88 | + if result.find("setting.delete"): |
| 89 | + key = result.query[str]("setting.args.key") |
| 90 | + if not key: |
| 91 | + return f"{Fore.RED}Please specify the configuration key to unset{Fore.RESET}" |
| 92 | + setting_dir = get_project_root() if result.find("setting.local") else user_config_path("entari-cli", appauthor=False) |
| 93 | + setting_file = setting_dir / (".entari_cli.toml" if result.find("setting.local") else "config.toml") |
| 94 | + with setting_file.open("r", encoding="utf-8") as f: |
| 95 | + cfg = tomlkit.load(f) |
| 96 | + del_item(cfg, key) |
| 97 | + with setting_file.open("w", encoding="utf-8") as f: |
| 98 | + tomlkit.dump(cfg, f) |
| 99 | + return f"{Fore.GREEN}Configuration key '{key}' unset.{Fore.RESET}" |
| 100 | + if result.find("setting.args.value"): |
| 101 | + key = result.query[str]("setting.args.key") |
| 102 | + if not key: |
| 103 | + return f"{Fore.RED}Please specify the configuration key to unset{Fore.RESET}" |
| 104 | + value = result.query[str]("setting.args.value") |
| 105 | + setting_dir = get_project_root() if result.find("setting.local") else user_config_path("entari-cli", appauthor=False) |
| 106 | + setting_file = setting_dir / (".entari_cli.toml" if result.find("setting.local") else "config.toml") |
| 107 | + setting_dir.mkdir(parents=True, exist_ok=True) |
| 108 | + with setting_file.open("a+", encoding="utf-8") as f: |
| 109 | + f.seek(0) |
| 110 | + try: |
| 111 | + cfg = tomlkit.load(f) |
| 112 | + except Exception: |
| 113 | + cfg = tomlkit.document() |
| 114 | + set_item(cfg, key, value) # type: ignore |
| 115 | + f.truncate(0) |
| 116 | + tomlkit.dump(cfg, f) |
| 117 | + return f"{Fore.GREEN}Configuration key '{key}' set to '{value}'.{Fore.RESET}" |
| 118 | + if result.find("setting.args.key"): |
| 119 | + query = result.query[str]("setting.args.key", "") |
| 120 | + local_cfg = self.get_setting(True) |
| 121 | + global_cfg = self.get_setting(False) |
| 122 | + lines = [] |
| 123 | + if local_cfg: |
| 124 | + for key, value in print_flattened(local_cfg): |
| 125 | + if not key.startswith(query): |
| 126 | + continue |
| 127 | + if key.endswith(".password") or key.endswith(".token") or key.endswith(".secret"): |
| 128 | + value = f"{ITALIC}<hidden>{Fore.RESET}" |
| 129 | + lines.append(f"{Fore.CYAN}{key}{Fore.RESET} = {value}") |
| 130 | + # value = get_item(local_cfg, key) |
| 131 | + if global_cfg: |
| 132 | + for key, value in print_flattened(global_cfg): |
| 133 | + if not key.startswith(query): |
| 134 | + continue |
| 135 | + if key.endswith(".password") or key.endswith(".token") or key.endswith(".secret"): |
| 136 | + value = f"{ITALIC}<hidden>{Fore.RESET}" |
| 137 | + lines.append(f"{Fore.CYAN}{key}{Fore.RESET} = {value}") |
| 138 | + if not lines: |
| 139 | + return f"{Fore.RED}Configuration key '{query}' not found.{Fore.RESET}" |
| 140 | + return "\n".join(lines) |
| 141 | + if result.find("setting"): |
| 142 | + local_cfg = self.get_setting(True) |
| 143 | + global_cfg = self.get_setting(False) |
| 144 | + print(f"{Style.BRIGHT}Site/default setting{Style.RESET_ALL}") |
| 145 | + self._show_config(DEFAULT, { |
| 146 | + **dict(print_flattened(global_cfg) if global_cfg else ()), |
| 147 | + **dict(print_flattened(local_cfg) if local_cfg else ()), |
| 148 | + }) |
| 149 | + if global_cfg: |
| 150 | + print(f"\n{Style.BRIGHT}Global configuration file ({Fore.GREEN}{user_config_path('entari-cli', appauthor=False) / 'config.toml'}{Fore.RESET}){Style.RESET_ALL}") |
| 151 | + self._show_config(dict(print_flattened(global_cfg)),{}) |
| 152 | + if local_cfg: |
| 153 | + print(f"\n{Style.BRIGHT}Local configuration file ({Fore.GREEN}{get_project_root() / '.entari_cli.toml'}{Fore.RESET}){Style.RESET_ALL}") |
| 154 | + self._show_config(dict(print_flattened(local_cfg)),{}) |
| 155 | + # lines = [] |
| 156 | + # if local_cfg: |
| 157 | + # lines.append(f"# Local Configuration File ({Fore.GREEN}{get_project_root() / '.entari_cli.toml'}{Fore.RESET})") |
| 158 | + # for key, value in print_flattened(local_cfg): |
| 159 | + # if key.endswith(".password") or key.endswith(".token") or key.endswith(".secret"): |
| 160 | + # value = f"{ITALIC}<hidden>{Fore.RESET}" |
| 161 | + # lines.append(f"{Fore.CYAN}{key}{Fore.RESET} = {value}") |
| 162 | + # lines.append("") |
| 163 | + # if global_cfg: |
| 164 | + # lines.append(f"# Global Configuration File ({Fore.GREEN}{user_config_path('entari-cli', appauthor=False) / 'config.toml'}{Fore.RESET})") |
| 165 | + # for key, value in print_flattened(local_cfg): |
| 166 | + # if key.endswith(".password") or key.endswith(".token") or key.endswith(".secret"): |
| 167 | + # value = f"{ITALIC}<hidden>{Fore.RESET}" |
| 168 | + # lines.append(f"{Fore.CYAN}{key}{Fore.RESET} = {value}") |
| 169 | + # lines.append("") |
| 170 | + # return "\n".join(lines) if lines else f"{Fore.YELLOW}No configuration found.{Fore.RESET}" |
| 171 | + return next_(None) |
| 172 | + |
| 173 | + def _show_config(self, config: Mapping[str, Any], supersedes: Mapping[str, Any]): |
| 174 | + for key in sorted(config): |
| 175 | + superseded = key in supersedes |
| 176 | + if key.endswith(".password") or key.endswith(".token") or key.endswith(".secret"): |
| 177 | + value = f"{ITALIC}<hidden>" |
| 178 | + else: |
| 179 | + value = config[key] |
| 180 | + print( |
| 181 | + f"{Style.DIM if superseded else ''}{Fore.CYAN}{key}{Fore.RESET} = {value}{Style.RESET_ALL}" |
| 182 | + ) |
0 commit comments