|
| 1 | +import toml |
| 2 | +from dataclasses import dataclass |
| 3 | +from toml import TomlDecodeError |
| 4 | + |
| 5 | +CONFIG_FILE_NAME = "pyproject.toml" |
| 6 | + |
| 7 | +@dataclass |
| 8 | +class CliConfig: |
| 9 | + """Handles loading and storing the config from disk""" |
| 10 | + |
| 11 | + @property |
| 12 | + def module_site(self): |
| 13 | + if not self._config_loaded: |
| 14 | + self.load_config() |
| 15 | + self._config_loaded = True |
| 16 | + return self._module_site |
| 17 | + |
| 18 | + @property |
| 19 | + def collection(self): |
| 20 | + if not self._config_loaded: |
| 21 | + self.load_config() |
| 22 | + self._config_loaded = True |
| 23 | + return self._collection |
| 24 | + |
| 25 | + @property |
| 26 | + def editor(self): |
| 27 | + if not self._config_loaded: |
| 28 | + self.load_config() |
| 29 | + self._config_loaded = True |
| 30 | + return self._editor |
| 31 | + |
| 32 | + # Initialize the arguments and default values |
| 33 | + _module_site: str = None |
| 34 | + _collection: str = None |
| 35 | + default_module_site: str = None |
| 36 | + default_collection: str = None |
| 37 | + _editor: str = None |
| 38 | + _config_loaded: bool = False |
| 39 | + |
| 40 | + def load_config(self, config_file: str = CONFIG_FILE_NAME): |
| 41 | + """Load the config from the file""" |
| 42 | + stored_config = {} |
| 43 | + try: |
| 44 | + with open(config_file) as stored_config_file: |
| 45 | + try: |
| 46 | + stored_config = ( |
| 47 | + toml.load(stored_config_file).get("tool", {}).get("render-engine", {}).get("cli", {}) |
| 48 | + ) |
| 49 | + except TomlDecodeError as exc: |
| 50 | + click.echo( |
| 51 | + f"{click.style(f'Encountered an error while parsing {config_file}', fg='red')}\n{exc}\n", |
| 52 | + err=True, |
| 53 | + ) |
| 54 | + else: |
| 55 | + click.echo(f"Config loaded from {config_file}") |
| 56 | + except FileNotFoundError: |
| 57 | + click.echo(f"No config file found at {config_file}") |
| 58 | + |
| 59 | + self._editor = stored_config.get("editor", getenv("EDITOR")) |
| 60 | + if stored_config: |
| 61 | + # Populate the argument variables and default values from the config |
| 62 | + if (module := stored_config.get("module")) and (site := stored_config.get("site")): |
| 63 | + self._module_site = f"{module}:{site}" |
| 64 | + if default_collection := stored_config.get("collection"): |
| 65 | + self._collection = default_collection |
| 66 | + |
0 commit comments