|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import logging |
| 4 | +import pathlib |
| 5 | +import tomllib |
| 6 | +from typing import Any, cast |
| 7 | + |
| 8 | +from steamlayer import TOOL_HOME |
| 9 | + |
| 10 | +from .defaults import DEFAULTS, VALID_LANGUAGES, ConfigError |
| 11 | + |
| 12 | +log = logging.getLogger("steamlayer.config.resolver") |
| 13 | + |
| 14 | + |
| 15 | +class ConfigResolver: |
| 16 | + def __init__(self, game_dir: pathlib.Path | None = None) -> None: |
| 17 | + self._game_dir = game_dir |
| 18 | + self._global_config = self._load_toml(TOOL_HOME / "config.toml") |
| 19 | + self._game_config = self._load_toml(self._game_dir / ".steamlayer.toml") if self._game_dir else {} |
| 20 | + self._merged_config = self.deep_merge(self._global_config, self._game_config) |
| 21 | + self.validate(self._merged_config) |
| 22 | + |
| 23 | + def _load_toml(self, path: pathlib.Path | None) -> dict[str, Any]: |
| 24 | + if not path or not path.exists(): |
| 25 | + return {} |
| 26 | + try: |
| 27 | + with open(path, "rb") as f: |
| 28 | + return tomllib.load(f) |
| 29 | + except Exception as e: |
| 30 | + log.warning(f"Could not load config from '{path}': {e}") |
| 31 | + return {} |
| 32 | + |
| 33 | + def deep_merge(self, base: dict, override: dict) -> dict: |
| 34 | + """ |
| 35 | + Recursively merge override into base, respecting section boundaries. |
| 36 | +
|
| 37 | + Each top-level section ([steamlayer], [goldberg], etc.) is merged |
| 38 | + independently — a missing [goldberg] in override doesn't erase base [goldberg]. |
| 39 | + """ |
| 40 | + result = {k: v.copy() if isinstance(v, dict) else v for k, v in base.items()} |
| 41 | + for key, val in override.items(): |
| 42 | + if key in result and isinstance(result[key], dict) and isinstance(val, dict): |
| 43 | + result[key].update(val) |
| 44 | + else: |
| 45 | + result[key] = val |
| 46 | + return result |
| 47 | + |
| 48 | + def validate(self, cfg: dict) -> None: |
| 49 | + """ |
| 50 | + Validate configuration structure and values. |
| 51 | +
|
| 52 | + Raises ConfigError if: |
| 53 | + - Unknown keys present in [steamlayer] or [goldberg] |
| 54 | + - Type mismatch for any known key |
| 55 | + - Unrecognised language value in [goldberg] |
| 56 | + """ |
| 57 | + steamlayer_cfg = cfg.get("steamlayer", {}) |
| 58 | + goldberg_cfg = cfg.get("goldberg", {}) |
| 59 | + sl_defaults: dict[str, Any] = cast(dict[str, Any], DEFAULTS["steamlayer"]) |
| 60 | + gb_defaults: dict[str, Any] = cast(dict[str, Any], DEFAULTS["goldberg"]) |
| 61 | + |
| 62 | + valid_sl_keys = set(sl_defaults.keys()) |
| 63 | + unknown_sl = set(steamlayer_cfg.keys()) - valid_sl_keys |
| 64 | + if unknown_sl: |
| 65 | + raise ConfigError(f"Unknown keys in [steamlayer]: {unknown_sl}") |
| 66 | + |
| 67 | + for key, val in steamlayer_cfg.items(): |
| 68 | + expected_type = type(sl_defaults[key]) |
| 69 | + if not isinstance(val, expected_type): |
| 70 | + raise ConfigError( |
| 71 | + f"[steamlayer] {key}: expected {expected_type.__name__}, got {type(val).__name__}" |
| 72 | + ) |
| 73 | + |
| 74 | + valid_gb_keys = set(gb_defaults.keys()) |
| 75 | + unknown_gb = set(goldberg_cfg.keys()) - valid_gb_keys |
| 76 | + if unknown_gb: |
| 77 | + raise ConfigError(f"Unknown keys in [goldberg]: {unknown_gb}") |
| 78 | + |
| 79 | + for key, val in goldberg_cfg.items(): |
| 80 | + if key == "dlcs": |
| 81 | + continue |
| 82 | + |
| 83 | + expected_type = type(gb_defaults[key]) |
| 84 | + if not isinstance(val, expected_type): |
| 85 | + raise ConfigError(f"[goldberg] {key}: expected {expected_type.__name__}, got {type(val).__name__}") |
| 86 | + |
| 87 | + language = goldberg_cfg.get("language", gb_defaults["language"]) |
| 88 | + if language.lower() not in VALID_LANGUAGES: |
| 89 | + raise ConfigError( |
| 90 | + f"[goldberg] language '{language}' not recognized. " |
| 91 | + f"Valid options: {', '.join(sorted(VALID_LANGUAGES))}" |
| 92 | + ) |
| 93 | + |
| 94 | + log.debug("Configuration validation passed.") |
| 95 | + |
| 96 | + def resolve_config(self) -> dict[str, Any]: |
| 97 | + """ |
| 98 | + Return the fully-resolved config: DEFAULTS < global config < game config. |
| 99 | +
|
| 100 | + 1. Start from DEFAULTS for every known section. |
| 101 | + 2. Overlay the already-merged (global + game) config on top. |
| 102 | + 3. Return. |
| 103 | +
|
| 104 | + The result is guaranteed to contain every key in DEFAULTS, which means |
| 105 | + callers can safely do cfg["steamlayer"]["dry_run"] without KeyError even |
| 106 | + if the user's config file is empty or absent. |
| 107 | +
|
| 108 | + Validation was already performed during __init__; a ConfigError raised |
| 109 | + there will have prevented construction, so by the time this method is |
| 110 | + called the config is known-good. |
| 111 | + """ |
| 112 | + result: dict[str, Any] = {} |
| 113 | + flat_defaults = cast(dict[str, dict[str, Any]], DEFAULTS) |
| 114 | + for section, section_defaults in flat_defaults.items(): |
| 115 | + result[section] = dict(section_defaults) |
| 116 | + merged_section = self._merged_config.get(section, {}) |
| 117 | + result[section].update(merged_section) |
| 118 | + |
| 119 | + log.debug("Resolved config: %s", result) |
| 120 | + return result |
0 commit comments