-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathconfig_loader.py
More file actions
212 lines (181 loc) · 7.49 KB
/
config_loader.py
File metadata and controls
212 lines (181 loc) · 7.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
"""User configuration loader and runtime resolver for Affinity CLI."""
from __future__ import annotations
import json
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Optional
import os
from affinity_cli import config
try: # Python 3.11+
import tomllib # type: ignore
except ModuleNotFoundError: # pragma: no cover
try:
import tomli as tomllib # type: ignore
except ModuleNotFoundError: # pragma: no cover
tomllib = None # type: ignore
try: # Optional dependency for YAML configs
import yaml # type: ignore
except Exception: # pragma: no cover
yaml = None # type: ignore
class ConfigError(RuntimeError):
"""Raised when the configuration file cannot be processed."""
@dataclass(frozen=True)
class UserConfig:
installers_path: Optional[Path] = None
wine_prefix: Optional[Path] = None
default_version: Optional[str] = None
@dataclass(frozen=True)
class ResolvedConfig:
installers_path: Path
wine_prefix: Path
default_version: str
def to_display_dict(self) -> Dict[str, str]:
return {
"Installers path": str(self.installers_path),
"Wine prefix": str(self.wine_prefix),
"Default installer version": self.default_version,
}
class ConfigLoader:
"""Loads configuration from ~/.config/affinity-cli, an explicit path, or environment."""
CONFIG_FILES = (
"config.toml",
"config.yaml",
"config.yml",
"config.json",
)
ENV_INSTALLERS = "AFFINITY_INSTALLERS_PATH"
ENV_PREFIX = "AFFINITY_WINE_PREFIX"
ENV_VERSION = "AFFINITY_DEFAULT_VERSION"
def __init__(self, explicit_path: Optional[str] = None, config_file: Optional[str] = None) -> None:
"""
Args:
explicit_path: Backwards-compatible path argument (kept for callers)
config_file: Preferred keyword accepted by tests/CLI
"""
chosen = config_file or explicit_path
self.explicit_path = Path(chosen).expanduser() if chosen else None
self.config_path: Optional[Path] = None
self._raw_data: Dict[str, Any] = {}
self.user_config = UserConfig()
self._load()
def load(self) -> ResolvedConfig:
"""
Public helper used by tests and CLI entrypoint.
Mirrors `derive` with no overrides.
"""
return self.derive()
def derive(
self,
*,
installers_path: Optional[str] = None,
prefix_path: Optional[str] = None,
version: Optional[str] = None,
) -> ResolvedConfig:
"""
Resolve configuration using precedence:
explicit args > environment > user config file > defaults
"""
env_installers = os.getenv(self.ENV_INSTALLERS)
env_prefix = os.getenv(self.ENV_PREFIX)
env_version = os.getenv(self.ENV_VERSION)
installers = self._normalize_path(
installers_path
or env_installers
or (self.user_config.installers_path and str(self.user_config.installers_path))
or str(config.DEFAULT_INSTALLERS_PATH)
)
prefix = self._normalize_path(
prefix_path
or env_prefix
or (self.user_config.wine_prefix and str(self.user_config.wine_prefix))
or str(config.DEFAULT_WINE_PREFIX)
)
version_choice = (
(version or env_version or self.user_config.default_version or config.DEFAULT_INSTALLER_VERSION)
)
version_choice = version_choice.lower()
if version_choice not in config.SUPPORTED_INSTALLER_VERSIONS:
raise ConfigError(
f"Invalid installer version '{version_choice}'. Supported values:"
f" {', '.join(config.SUPPORTED_INSTALLER_VERSIONS)}"
)
return ResolvedConfig(installers_path=installers, wine_prefix=prefix, default_version=version_choice)
def _load(self) -> None:
if self.explicit_path:
# If the caller asked for a specific path but it does not exist,
# fall back to defaults instead of crashing (friendlier UX/tests).
if self.explicit_path.exists():
self.config_path = self.explicit_path
self._raw_data = self._read_file(self.explicit_path)
self.user_config = self._parse_user_config(self._raw_data)
return
else:
self._raw_data = {}
self.user_config = UserConfig()
return
for candidate in self.CONFIG_FILES:
path = config.CONFIG_DIR / candidate
if path.exists():
self.config_path = path
self._raw_data = self._read_file(path)
self.user_config = self._parse_user_config(self._raw_data)
return
self._raw_data = {}
self.user_config = UserConfig()
def _parse_user_config(self, payload: Dict[str, Any]) -> UserConfig:
if not payload:
return UserConfig()
allowed = {"installers_path", "wine_prefix", "default_version"}
unexpected = set(payload.keys()) - allowed
if unexpected:
raise ConfigError(f"Unknown configuration field(s): {', '.join(sorted(unexpected))}")
installers = self._optional_path(payload.get("installers_path"))
prefix = self._optional_path(payload.get("wine_prefix"))
default_version = payload.get("default_version")
if default_version is not None:
if not isinstance(default_version, str):
raise ConfigError("default_version must be a string (v1 or v2)")
default_version = default_version.lower().strip()
if default_version not in config.SUPPORTED_INSTALLER_VERSIONS:
raise ConfigError(
f"default_version must be one of {', '.join(config.SUPPORTED_INSTALLER_VERSIONS)}"
)
return UserConfig(
installers_path=installers,
wine_prefix=prefix,
default_version=default_version,
)
def _read_file(self, path: Path) -> Dict[str, Any]:
suffix = path.suffix.lower()
text = path.read_text(encoding="utf-8").strip()
if not text:
return {}
if suffix == ".json":
return self._as_dict(json.loads(text), path)
if suffix == ".toml":
if tomllib is None:
raise ConfigError("Reading TOML configs requires the 'tomli' package on Python < 3.11")
return self._as_dict(tomllib.loads(text), path)
if suffix in {".yaml", ".yml"}:
if yaml is None:
raise ConfigError("PyYAML is required to parse YAML configuration files")
return self._as_dict(yaml.safe_load(text) or {}, path)
raise ConfigError(f"Unsupported config format: {path.suffix}")
@staticmethod
def _as_dict(value: Any, path: Path) -> Dict[str, Any]:
if value is None:
return {}
if not isinstance(value, dict):
raise ConfigError(f"Configuration file {path} must be a mapping")
return value
@staticmethod
def _normalize_path(raw_path: str) -> Path:
return Path(raw_path).expanduser()
@staticmethod
def _optional_path(value: Any) -> Optional[Path]:
if value is None:
return None
if not isinstance(value, str):
raise ConfigError("Path values must be strings")
return Path(value).expanduser()
__all__ = ["ConfigLoader", "ConfigError", "ResolvedConfig", "UserConfig"]