|
| 1 | +import os |
| 2 | +import platform |
| 3 | +import sys |
| 4 | +import tomllib |
| 5 | +from dataclasses import dataclass, field, fields |
| 6 | +from pathlib import Path |
| 7 | + |
| 8 | +import dacite |
| 9 | + |
| 10 | +from . import paths |
| 11 | +from .log import error, or_phrase |
| 12 | + |
| 13 | +DEFAULT_CONFIG_FILE = Path(__file__).parent / "config.toml" |
| 14 | + |
| 15 | + |
| 16 | +@dataclass(kw_only=True) |
| 17 | +class Config: |
| 18 | + config_py_template: str | None = None |
| 19 | + qutebrowser_config_directory: Path | None = None |
| 20 | + profile_directory: Path = field(default_factory=paths.default_profile_dir) |
| 21 | + generate_desktop_file: bool = platform.system() == "Linux" |
| 22 | + desktop_file_directory: Path = field( |
| 23 | + default_factory=paths.default_qbpm_application_dir |
| 24 | + ) |
| 25 | + menu: str | list[str] = field(default_factory=list) |
| 26 | + menu_prompt: str = "qutebrowser" |
| 27 | + |
| 28 | + @classmethod |
| 29 | + def load(cls, config_file: Path | None) -> "Config": |
| 30 | + config_file = config_file or DEFAULT_CONFIG_FILE |
| 31 | + try: |
| 32 | + data = tomllib.loads(config_file.read_text(encoding="utf-8")) |
| 33 | + if extra := data.keys() - {field.name for field in fields(Config)}: |
| 34 | + raise RuntimeError(f'unknown config value: "{next(iter(extra))}"') |
| 35 | + return dacite.from_dict( |
| 36 | + data_class=Config, |
| 37 | + data=data, |
| 38 | + config=dacite.Config( |
| 39 | + type_hooks={Path: lambda val: Path(val).expanduser()} |
| 40 | + ), |
| 41 | + ) |
| 42 | + except Exception as e: |
| 43 | + error(f"loading {config_file} failed with error '{e}'") |
| 44 | + sys.exit(1) |
| 45 | + |
| 46 | + |
| 47 | +def find_config(config_path: Path | None) -> Config: |
| 48 | + if not config_path: |
| 49 | + default = paths.default_qbpm_config_dir() / "config.toml" |
| 50 | + if default.is_file(): |
| 51 | + config_path = default |
| 52 | + elif config_path == Path(os.devnull): |
| 53 | + config_path = None |
| 54 | + elif not config_path.is_file(): |
| 55 | + error(f"{config_path} is not a file") |
| 56 | + sys.exit(1) |
| 57 | + return Config.load(config_path) |
| 58 | + |
| 59 | + |
| 60 | +def find_qutebrowser_config_dir(qb_config_dir: Path | None) -> Path | None: |
| 61 | + dirs = ( |
| 62 | + [qb_config_dir, qb_config_dir / "config"] |
| 63 | + if qb_config_dir |
| 64 | + else list(paths.qutebrowser_config_dirs()) |
| 65 | + ) |
| 66 | + for config_dir in dirs: |
| 67 | + if (config_dir / "config.py").exists(): |
| 68 | + return config_dir.absolute() |
| 69 | + error(f"couldn't find config.py in {or_phrase(dirs)}") |
| 70 | + return None |
0 commit comments