githubtemplateastraluv 0.0.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- githubtemplateastraluv/__init__.py +18 -0
- githubtemplateastraluv/__main__.py +15 -0
- githubtemplateastraluv/config.py +662 -0
- githubtemplateastraluv/config_render.py +474 -0
- githubtemplateastraluv/core.py +77 -0
- githubtemplateastraluv/management.py +247 -0
- githubtemplateastraluv/version_check.py +389 -0
- githubtemplateastraluv-0.0.2.dist-info/METADATA +196 -0
- githubtemplateastraluv-0.0.2.dist-info/RECORD +13 -0
- githubtemplateastraluv-0.0.2.dist-info/WHEEL +5 -0
- githubtemplateastraluv-0.0.2.dist-info/entry_points.txt +3 -0
- githubtemplateastraluv-0.0.2.dist-info/licenses/LICENSE +674 -0
- githubtemplateastraluv-0.0.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
## @file __init__.py
|
|
2
|
+
# @brief Expose package-level metadata and public CLI entrypoint symbols.
|
|
3
|
+
# @details Defines stable module exports for downstream imports and
|
|
4
|
+
# runtime version checks, mirroring the skeleton schema.
|
|
5
|
+
|
|
6
|
+
## @brief Store semantic version string for package metadata.
|
|
7
|
+
# @details Used by CLI usage/version output and by release automation
|
|
8
|
+
# checks; single source of truth consumed by core.main dispatch
|
|
9
|
+
# and mirrored in pyproject.toml, scripts/templateastraluv.sh,
|
|
10
|
+
# README.md, and uv.lock per .g.conf ver_rules.
|
|
11
|
+
__version__ = "0.0.2"
|
|
12
|
+
|
|
13
|
+
from githubtemplateastraluv.core import main # noqa: F401
|
|
14
|
+
|
|
15
|
+
## @brief Enumerate public symbols exported by package root.
|
|
16
|
+
# @details Constrains wildcard-import surface to the version constant and
|
|
17
|
+
# the CLI main callable.
|
|
18
|
+
__all__ = ["__version__", "main"]
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
## @file __main__.py
|
|
2
|
+
# @brief Execute githubtemplateastraluv CLI when module is invoked with
|
|
3
|
+
# `python -m`.
|
|
4
|
+
# @details Imports the canonical `main` dispatcher and forwards process
|
|
5
|
+
# exit status to the interpreter.
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from githubtemplateastraluv.core import main
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
## @brief Trigger CLI dispatcher for module-execution entrypoint.
|
|
12
|
+
# @details Invokes `main()` and propagates returned exit code via
|
|
13
|
+
# `sys.exit(...)`.
|
|
14
|
+
if __name__ == "__main__":
|
|
15
|
+
sys.exit(main())
|
|
@@ -0,0 +1,662 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
## @file config.py
|
|
3
|
+
# @brief Configuration subsystem: canonical schema, strict validation,
|
|
4
|
+
# atomic JSON persistence, path resolution, and CLI handlers.
|
|
5
|
+
# @details Single source of truth driving parsing, validation, defaults,
|
|
6
|
+
# path discovery, and configuration output (DES-010). State
|
|
7
|
+
# persists as JSON at `$HOME/.config/githubtemplateastraluv/
|
|
8
|
+
# config.json`. Version-check transport parameters stay hardcoded
|
|
9
|
+
# (CTN-008) and are not part of the schema. Handlers emit valid
|
|
10
|
+
# output on stdout only, report failures on stderr with exit
|
|
11
|
+
# status 1, and never mutate state on rejected operations
|
|
12
|
+
# (REQ-023).
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import sys
|
|
16
|
+
import tempfile
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
## @brief Ordered mapping of Selection enum token to ANSI SGR prefix.
|
|
22
|
+
# @details Insertion order defines enum display order (REQ-025).
|
|
23
|
+
COLOR_ANSI: dict[str, str] = {
|
|
24
|
+
"bright_green": "\033[92m",
|
|
25
|
+
"bright_red": "\033[91m",
|
|
26
|
+
"bright_yellow": "\033[93m",
|
|
27
|
+
"bright_blue": "\033[94m",
|
|
28
|
+
"bright_magenta": "\033[95m",
|
|
29
|
+
"bright_cyan": "\033[96m",
|
|
30
|
+
"bright_white": "\033[97m",
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
## @brief Ordered Selection enum tokens shared by both parameters (REQ-025).
|
|
34
|
+
_SELECTION_ENUM: tuple[str, ...] = tuple(COLOR_ANSI)
|
|
35
|
+
|
|
36
|
+
## @brief Global configuration directory segments relative to `$HOME`.
|
|
37
|
+
_CONFIG_DIR_SEGMENTS: tuple[str, ...] = (
|
|
38
|
+
".config",
|
|
39
|
+
"githubtemplateastraluv",
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
## @brief Global configuration JSON file name.
|
|
43
|
+
_CONFIG_FILE_NAME = "config.json"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class ParamSpec:
|
|
48
|
+
"""@brief Immutable schema descriptor of one configuration parameter.
|
|
49
|
+
|
|
50
|
+
@details `token` equals the CLI path token byte for byte (REQ-022);
|
|
51
|
+
drives parsing, validation, defaults, display, and
|
|
52
|
+
documentation (DES-010).
|
|
53
|
+
"""
|
|
54
|
+
## @brief Canonical CLI path token of the parameter.
|
|
55
|
+
token: str
|
|
56
|
+
## @brief Schema type label rendered in `--info` headings.
|
|
57
|
+
type_label: str
|
|
58
|
+
## @brief Concise English description rendered in `--info`.
|
|
59
|
+
description: str
|
|
60
|
+
## @brief Schema default value restored by `--unset` (REQ-018).
|
|
61
|
+
default: str
|
|
62
|
+
## @brief Ordered allowed values for Selection parameters (REQ-025).
|
|
63
|
+
enum: tuple[str, ...]
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def constraints(self) -> str:
|
|
67
|
+
"""@brief Constraints fragment rendered after the type label.
|
|
68
|
+
|
|
69
|
+
@return {str} Constraint summary, e.g. `7 allowed values`.
|
|
70
|
+
"""
|
|
71
|
+
return f"{len(self.enum)} allowed values"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True)
|
|
75
|
+
class SectionSpec:
|
|
76
|
+
"""@brief Immutable schema descriptor of one fixed-schema section.
|
|
77
|
+
|
|
78
|
+
@details Fixed-schema dictionary branch; whole-section `--set`
|
|
79
|
+
replaces the branch with a schema-compatible JSON object and
|
|
80
|
+
`--unset` restores all parameter defaults (REQ-018).
|
|
81
|
+
"""
|
|
82
|
+
## @brief Canonical CLI path token of the section.
|
|
83
|
+
token: str
|
|
84
|
+
## @brief Concise English description rendered in `--print`/`--info`.
|
|
85
|
+
description: str
|
|
86
|
+
## @brief Ordered parameter descriptors of the section.
|
|
87
|
+
params: tuple[ParamSpec, ...]
|
|
88
|
+
|
|
89
|
+
def param(self, token: str) -> ParamSpec | None:
|
|
90
|
+
"""@brief Look up a parameter descriptor by canonical token.
|
|
91
|
+
|
|
92
|
+
@param token {str} Exact parameter path token (case-sensitive).
|
|
93
|
+
@return {ParamSpec | None} Matching descriptor; None if absent.
|
|
94
|
+
"""
|
|
95
|
+
for candidate in self.params:
|
|
96
|
+
if candidate.token == token:
|
|
97
|
+
return candidate
|
|
98
|
+
return None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
## @brief Canonical configuration schema (DES-010, REQ-024).
|
|
102
|
+
# @details Insertion order defines canonical display order.
|
|
103
|
+
SCHEMA: tuple[SectionSpec, ...] = (
|
|
104
|
+
SectionSpec(
|
|
105
|
+
token="Notifications",
|
|
106
|
+
description="Version-check notification appearance.",
|
|
107
|
+
params=(
|
|
108
|
+
ParamSpec(
|
|
109
|
+
token="new_version_color",
|
|
110
|
+
type_label="Selection",
|
|
111
|
+
description="ANSI color of the new-version availability note.",
|
|
112
|
+
default="bright_green",
|
|
113
|
+
enum=_SELECTION_ENUM,
|
|
114
|
+
),
|
|
115
|
+
ParamSpec(
|
|
116
|
+
token="error_color",
|
|
117
|
+
type_label="Selection",
|
|
118
|
+
description="ANSI color of the version-check failure note.",
|
|
119
|
+
default="bright_red",
|
|
120
|
+
enum=_SELECTION_ENUM,
|
|
121
|
+
),
|
|
122
|
+
),
|
|
123
|
+
),
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
## @brief Schema token to SectionSpec index for O(1) path resolution.
|
|
127
|
+
_SECTIONS_BY_TOKEN: dict[str, SectionSpec] = {
|
|
128
|
+
section.token: section for section in SCHEMA
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class ConfigError(Exception):
|
|
133
|
+
"""@brief Configuration error carrying a user-facing diagnostic.
|
|
134
|
+
|
|
135
|
+
@details Raised for invalid paths, values, JSON, validation failures,
|
|
136
|
+
and unrecoverable filesystem conditions; handlers render the
|
|
137
|
+
message on stderr and exit 1 (REQ-023).
|
|
138
|
+
"""
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def config_path() -> Path:
|
|
142
|
+
"""@brief Resolve the absolute global configuration file path.
|
|
143
|
+
|
|
144
|
+
@details Prefers the `HOME` environment variable (CTN-008 consistency
|
|
145
|
+
with the version-check cache); falls back to `Path.home()`
|
|
146
|
+
when unset. No project-local configuration layer exists.
|
|
147
|
+
@return {Path} Absolute path of the global configuration JSON file.
|
|
148
|
+
"""
|
|
149
|
+
if "HOME" in os.environ:
|
|
150
|
+
base = Path(os.environ["HOME"])
|
|
151
|
+
else:
|
|
152
|
+
base = Path.home()
|
|
153
|
+
return base.joinpath(*_CONFIG_DIR_SEGMENTS, _CONFIG_FILE_NAME)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def default_config() -> dict[str, dict[str, str]]:
|
|
157
|
+
"""@brief Build the schema-default configuration payload.
|
|
158
|
+
|
|
159
|
+
@return {dict[str, dict[str, str]]} Section token to parameter token
|
|
160
|
+
to default value, in canonical schema order.
|
|
161
|
+
"""
|
|
162
|
+
return {
|
|
163
|
+
section.token: {param.token: param.default for param in section.params}
|
|
164
|
+
for section in SCHEMA
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def validate_config(payload: Any) -> None:
|
|
169
|
+
"""@brief Validate a complete configuration against the schema.
|
|
170
|
+
|
|
171
|
+
@details Strict validation: JSON object root, exact section key set,
|
|
172
|
+
exact parameter key set per section, and Selection values
|
|
173
|
+
restricted to the schema enum (REQ-025). Raises without
|
|
174
|
+
mutation; callers reject the operation on error.
|
|
175
|
+
@param payload {Any} Parsed JSON configuration payload.
|
|
176
|
+
@return {None}
|
|
177
|
+
@throws {ConfigError} On root-type, section-key, parameter-key, or
|
|
178
|
+
enum-membership mismatch; message names the offending path.
|
|
179
|
+
"""
|
|
180
|
+
if not isinstance(payload, dict):
|
|
181
|
+
raise ConfigError(
|
|
182
|
+
"configuration root must be a JSON object; "
|
|
183
|
+
f"got {type(payload).__name__}"
|
|
184
|
+
)
|
|
185
|
+
expected_sections = set(_SECTIONS_BY_TOKEN)
|
|
186
|
+
actual_sections = set(payload)
|
|
187
|
+
unknown = sorted(actual_sections - expected_sections)
|
|
188
|
+
missing = sorted(expected_sections - actual_sections)
|
|
189
|
+
if unknown or missing:
|
|
190
|
+
raise ConfigError(
|
|
191
|
+
"configuration sections mismatch"
|
|
192
|
+
+ (f"; unknown sections: {unknown}" if unknown else "")
|
|
193
|
+
+ (f"; missing sections: {missing}" if missing else "")
|
|
194
|
+
)
|
|
195
|
+
for section in SCHEMA:
|
|
196
|
+
branch = payload[section.token]
|
|
197
|
+
if not isinstance(branch, dict):
|
|
198
|
+
raise ConfigError(
|
|
199
|
+
f"section {section.token} must be a JSON object; "
|
|
200
|
+
f"got {type(branch).__name__}"
|
|
201
|
+
)
|
|
202
|
+
expected_params = {param.token for param in section.params}
|
|
203
|
+
actual_params = set(branch)
|
|
204
|
+
unknown_params = sorted(actual_params - expected_params)
|
|
205
|
+
missing_params = sorted(expected_params - actual_params)
|
|
206
|
+
if unknown_params or missing_params:
|
|
207
|
+
raise ConfigError(
|
|
208
|
+
f"section {section.token} parameters mismatch"
|
|
209
|
+
+ (f"; unknown: {unknown_params}" if unknown_params else "")
|
|
210
|
+
+ (f"; missing: {missing_params}" if missing_params else "")
|
|
211
|
+
)
|
|
212
|
+
for param in section.params:
|
|
213
|
+
value = branch[param.token]
|
|
214
|
+
if not isinstance(value, str) or value not in param.enum:
|
|
215
|
+
raise ConfigError(
|
|
216
|
+
f"invalid value for {section.token}:{param.token}: "
|
|
217
|
+
f"{value!r}; allowed values: {', '.join(param.enum)}"
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def atomic_write_json(path: Path, payload: dict[str, Any]) -> None:
|
|
222
|
+
"""@brief Persist a validated payload atomically (DES-014).
|
|
223
|
+
|
|
224
|
+
@details Writes a same-directory temporary file, flushes and fsyncs
|
|
225
|
+
it, preserves the prior target file mode, atomically replaces
|
|
226
|
+
the target with `os.replace`, and fsyncs the parent
|
|
227
|
+
directory where the platform supports it. The prior valid
|
|
228
|
+
file survives any failure before the replace; on failure the
|
|
229
|
+
temporary file is removed.
|
|
230
|
+
@param path {Path} Target configuration file path.
|
|
231
|
+
@param payload {dict[str, Any]} Schema-validated payload to store.
|
|
232
|
+
@return {None}
|
|
233
|
+
@throws {ConfigError} When directory creation or the write/replace
|
|
234
|
+
sequence fails; the original file stays untouched.
|
|
235
|
+
@post On success the file holds exactly the serialized payload with
|
|
236
|
+
two-space indentation and a trailing newline.
|
|
237
|
+
"""
|
|
238
|
+
text = json.dumps(payload, indent=2) + "\n"
|
|
239
|
+
try:
|
|
240
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
241
|
+
prior_mode = (
|
|
242
|
+
path.stat().st_mode & 0o777 if path.exists() else None
|
|
243
|
+
)
|
|
244
|
+
descriptor, temporary_name = tempfile.mkstemp(
|
|
245
|
+
dir=str(path.parent),
|
|
246
|
+
prefix=path.name + ".",
|
|
247
|
+
suffix=".tmp",
|
|
248
|
+
)
|
|
249
|
+
except OSError as error:
|
|
250
|
+
raise ConfigError(f"cannot prepare configuration write: {error}")
|
|
251
|
+
try:
|
|
252
|
+
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
|
|
253
|
+
handle.write(text)
|
|
254
|
+
handle.flush()
|
|
255
|
+
os.fsync(handle.fileno())
|
|
256
|
+
if prior_mode is not None:
|
|
257
|
+
os.chmod(temporary_name, prior_mode)
|
|
258
|
+
os.replace(temporary_name, path)
|
|
259
|
+
except OSError as error:
|
|
260
|
+
try:
|
|
261
|
+
os.unlink(temporary_name)
|
|
262
|
+
except OSError:
|
|
263
|
+
pass
|
|
264
|
+
raise ConfigError(f"cannot persist configuration: {error}")
|
|
265
|
+
try:
|
|
266
|
+
directory_fd = os.open(str(path.parent), os.O_RDONLY)
|
|
267
|
+
try:
|
|
268
|
+
os.fsync(directory_fd)
|
|
269
|
+
finally:
|
|
270
|
+
os.close(directory_fd)
|
|
271
|
+
except OSError:
|
|
272
|
+
pass
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def ensure_bootstrapped() -> None:
|
|
276
|
+
"""@brief Create missing directories and initialize missing defaults.
|
|
277
|
+
|
|
278
|
+
@details Applicable configuration commands call this before executing
|
|
279
|
+
(REQ-024 storage lifecycle). Never overwrites an existing
|
|
280
|
+
file, valid or not; strict loaders surface invalid files as
|
|
281
|
+
errors.
|
|
282
|
+
@return {None}
|
|
283
|
+
@throws {ConfigError} When directories cannot be created or the
|
|
284
|
+
default file cannot be written.
|
|
285
|
+
"""
|
|
286
|
+
path = config_path()
|
|
287
|
+
try:
|
|
288
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
289
|
+
if not path.exists():
|
|
290
|
+
atomic_write_json(path, default_config())
|
|
291
|
+
except ConfigError:
|
|
292
|
+
raise
|
|
293
|
+
except OSError as error:
|
|
294
|
+
raise ConfigError(f"cannot initialize configuration: {error}")
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def load_strict() -> dict[str, dict[str, str]]:
|
|
298
|
+
"""@brief Load and strictly validate the global configuration.
|
|
299
|
+
|
|
300
|
+
@details Reads the file selected by `config_path`, parses JSON, and
|
|
301
|
+
applies `validate_config`; every failure raises instead of
|
|
302
|
+
partially succeeding (REQ-022, REQ-023).
|
|
303
|
+
@return {dict[str, dict[str, str]]} Validated configuration payload.
|
|
304
|
+
@throws {ConfigError} When the file is absent, unreadable, malformed
|
|
305
|
+
JSON, or schema-invalid.
|
|
306
|
+
"""
|
|
307
|
+
path = config_path()
|
|
308
|
+
if not path.exists():
|
|
309
|
+
raise ConfigError(f"configuration file not found: {path}")
|
|
310
|
+
try:
|
|
311
|
+
text = path.read_text(encoding="utf-8")
|
|
312
|
+
except OSError as error:
|
|
313
|
+
raise ConfigError(f"cannot read configuration file: {error}")
|
|
314
|
+
try:
|
|
315
|
+
payload = json.loads(text)
|
|
316
|
+
except ValueError as error:
|
|
317
|
+
raise ConfigError(f"invalid JSON in {path}: {error}")
|
|
318
|
+
validate_config(payload)
|
|
319
|
+
return payload
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def load_tolerant() -> dict[str, dict[str, str]]:
|
|
323
|
+
"""@brief Load the configuration, falling back to schema defaults.
|
|
324
|
+
|
|
325
|
+
@details Used by the version-check notification path (REQ-026): any
|
|
326
|
+
load or validation failure silently selects schema defaults
|
|
327
|
+
so existing non-configuration behavior never breaks and no
|
|
328
|
+
extra output is produced.
|
|
329
|
+
@return {dict[str, dict[str, str]]} Validated payload or defaults.
|
|
330
|
+
"""
|
|
331
|
+
try:
|
|
332
|
+
return load_strict()
|
|
333
|
+
except ConfigError:
|
|
334
|
+
return default_config()
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def resolve_segments(path: str) -> tuple[str, ...]:
|
|
338
|
+
"""@brief Resolve a canonical configuration path against the schema.
|
|
339
|
+
|
|
340
|
+
@details Case-sensitive colon-separated tokens (REQ-022). This schema
|
|
341
|
+
defines exactly two depths: `Section` and
|
|
342
|
+
`Section:Parameter`; no array or map parameters exist, so
|
|
343
|
+
deeper segments and reserved operation tokens (`append`,
|
|
344
|
+
`+`, `insert`) are rejected as unknown or misplaced.
|
|
345
|
+
@param path {str} Raw canonical path from the CLI.
|
|
346
|
+
@return {tuple[str, ...]} One or two resolved path tokens.
|
|
347
|
+
@throws {ConfigError} On empty paths, empty tokens, unknown section
|
|
348
|
+
or parameter tokens, and excessive depth; messages list valid
|
|
349
|
+
alternatives.
|
|
350
|
+
"""
|
|
351
|
+
if not path:
|
|
352
|
+
raise ConfigError("configuration path must not be empty")
|
|
353
|
+
segments = tuple(path.split(":"))
|
|
354
|
+
if any(segment == "" for segment in segments):
|
|
355
|
+
raise ConfigError(
|
|
356
|
+
f"invalid configuration path {path!r}: empty path token"
|
|
357
|
+
)
|
|
358
|
+
section = _SECTIONS_BY_TOKEN.get(segments[0])
|
|
359
|
+
if section is None:
|
|
360
|
+
raise ConfigError(
|
|
361
|
+
f"unknown configuration section {segments[0]!r} in path "
|
|
362
|
+
f"{path!r}; valid sections: {', '.join(_SECTIONS_BY_TOKEN)}"
|
|
363
|
+
)
|
|
364
|
+
if len(segments) == 1:
|
|
365
|
+
return segments
|
|
366
|
+
if len(segments) == 2:
|
|
367
|
+
if section.param(segments[1]) is None:
|
|
368
|
+
raise ConfigError(
|
|
369
|
+
f"unknown parameter {segments[1]!r} in section "
|
|
370
|
+
f"{section.token}; valid parameters: "
|
|
371
|
+
f"{', '.join(param.token for param in section.params)}"
|
|
372
|
+
)
|
|
373
|
+
return segments
|
|
374
|
+
raise ConfigError(
|
|
375
|
+
f"invalid configuration path {path!r}: the schema defines at "
|
|
376
|
+
"most Section:Parameter; array, map, and index tokens are not "
|
|
377
|
+
"part of this schema"
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def get_value(payload: dict[str, Any], segments: tuple[str, ...]) -> Any:
|
|
382
|
+
"""@brief Extract the JSON-serializable value at a resolved path.
|
|
383
|
+
|
|
384
|
+
@param payload {dict[str, Any]} Validated configuration payload.
|
|
385
|
+
@param segments {tuple[str, ...]} Tokens from `resolve_segments`.
|
|
386
|
+
@return {Any} Section dict copy for depth 1; parameter string for
|
|
387
|
+
depth 2.
|
|
388
|
+
"""
|
|
389
|
+
section = payload[segments[0]]
|
|
390
|
+
if len(segments) == 1:
|
|
391
|
+
return dict(section)
|
|
392
|
+
return section[segments[1]]
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def parse_value(spec: ParamSpec, raw: str) -> str:
|
|
396
|
+
"""@brief Parse a raw CLI operand into the schema type of `spec`.
|
|
397
|
+
|
|
398
|
+
@details Selection parameters accept exactly one enum token; JSON
|
|
399
|
+
quoting is not stripped, so quoted input is rejected
|
|
400
|
+
(REQ-017 typed parsing before write).
|
|
401
|
+
@param spec {ParamSpec} Target parameter descriptor.
|
|
402
|
+
@param raw {str} Raw operand string from the CLI.
|
|
403
|
+
@return {str} Validated enum token.
|
|
404
|
+
@throws {ConfigError} When `raw` is not an allowed value; the message
|
|
405
|
+
enumerates valid values.
|
|
406
|
+
"""
|
|
407
|
+
if raw not in spec.enum:
|
|
408
|
+
raise ConfigError(
|
|
409
|
+
f"invalid value for {spec.token}: {raw!r}; allowed values: "
|
|
410
|
+
f"{', '.join(spec.enum)}"
|
|
411
|
+
)
|
|
412
|
+
return raw
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def set_value(
|
|
416
|
+
payload: dict[str, Any],
|
|
417
|
+
path: str,
|
|
418
|
+
raw: str,
|
|
419
|
+
) -> dict[str, dict[str, str]]:
|
|
420
|
+
"""@brief Apply a validated `--set` mutation and return the result.
|
|
421
|
+
|
|
422
|
+
@details Depth 1 replaces the whole section with a parsed
|
|
423
|
+
schema-compatible JSON object; depth 2 parses the operand
|
|
424
|
+
into the parameter schema type (REQ-017). The resulting
|
|
425
|
+
configuration is validated in full before returning; the
|
|
426
|
+
input payload is never mutated.
|
|
427
|
+
@param payload {dict[str, Any]} Current validated configuration.
|
|
428
|
+
@param path {str} Raw canonical target path.
|
|
429
|
+
@param raw {str} Raw value operand from the CLI.
|
|
430
|
+
@return {dict[str, dict[str, str]]} New validated configuration.
|
|
431
|
+
@throws {ConfigError} On path, JSON, type, enum, or whole-config
|
|
432
|
+
validation failure; no persisted mutation occurs.
|
|
433
|
+
"""
|
|
434
|
+
segments = resolve_segments(path)
|
|
435
|
+
updated = {token: dict(branch) for token, branch in payload.items()}
|
|
436
|
+
if len(segments) == 1:
|
|
437
|
+
section = _SECTIONS_BY_TOKEN[segments[0]]
|
|
438
|
+
try:
|
|
439
|
+
replacement = json.loads(raw)
|
|
440
|
+
except ValueError as error:
|
|
441
|
+
raise ConfigError(
|
|
442
|
+
f"value for section {section.token} is not valid JSON: "
|
|
443
|
+
f"{error}"
|
|
444
|
+
)
|
|
445
|
+
updated[section.token] = replacement
|
|
446
|
+
else:
|
|
447
|
+
param = _SECTIONS_BY_TOKEN[segments[0]].param(segments[1])
|
|
448
|
+
if param is None:
|
|
449
|
+
raise ConfigError(f"unknown parameter in path {path!r}")
|
|
450
|
+
updated[segments[0]][param.token] = parse_value(param, raw)
|
|
451
|
+
validate_config(updated)
|
|
452
|
+
return updated
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def unset_value(
|
|
456
|
+
payload: dict[str, Any],
|
|
457
|
+
path: str,
|
|
458
|
+
) -> dict[str, dict[str, str]]:
|
|
459
|
+
"""@brief Apply a `--unset` restore-to-default mutation.
|
|
460
|
+
|
|
461
|
+
@details Depth 1 restores all section parameter defaults; depth 2
|
|
462
|
+
restores one parameter default (REQ-018). The resulting
|
|
463
|
+
configuration is validated before returning; the input
|
|
464
|
+
payload is never mutated.
|
|
465
|
+
@param payload {dict[str, Any]} Current validated configuration.
|
|
466
|
+
@param path {str} Raw canonical target path.
|
|
467
|
+
@return {dict[str, dict[str, str]]} New validated configuration.
|
|
468
|
+
@throws {ConfigError} On path resolution or validation failure.
|
|
469
|
+
"""
|
|
470
|
+
segments = resolve_segments(path)
|
|
471
|
+
updated = {token: dict(branch) for token, branch in payload.items()}
|
|
472
|
+
defaults = default_config()
|
|
473
|
+
if len(segments) == 1:
|
|
474
|
+
updated[segments[0]] = dict(defaults[segments[0]])
|
|
475
|
+
else:
|
|
476
|
+
updated[segments[0]][segments[1]] = defaults[segments[0]][segments[1]]
|
|
477
|
+
validate_config(updated)
|
|
478
|
+
return updated
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def notification_colors() -> dict[str, str]:
|
|
482
|
+
"""@brief Resolve configured ANSI color prefixes for notifications.
|
|
483
|
+
|
|
484
|
+
@details Tolerant read (REQ-026): any load or validation failure
|
|
485
|
+
selects schema defaults, keeping the version check non-fatal
|
|
486
|
+
and silent about configuration problems.
|
|
487
|
+
@return {dict[str, str]} Mapping with `new_version_color` and
|
|
488
|
+
`error_color` ANSI SGR prefix strings.
|
|
489
|
+
"""
|
|
490
|
+
payload = load_tolerant()
|
|
491
|
+
return {
|
|
492
|
+
"new_version_color": COLOR_ANSI[
|
|
493
|
+
payload["Notifications"]["new_version_color"]
|
|
494
|
+
],
|
|
495
|
+
"error_color": COLOR_ANSI[payload["Notifications"]["error_color"]],
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def operand_values(
|
|
500
|
+
args: list[str],
|
|
501
|
+
flag: str,
|
|
502
|
+
minimum: int,
|
|
503
|
+
maximum: int,
|
|
504
|
+
) -> list[str]:
|
|
505
|
+
"""@brief Extract the operand tokens following one CLI flag.
|
|
506
|
+
|
|
507
|
+
@details Operands are every token after the first flag occurrence;
|
|
508
|
+
the count must lie within `[minimum, maximum]`, otherwise a
|
|
509
|
+
usage diagnostic with complete canonical path examples is
|
|
510
|
+
raised (REQ-022).
|
|
511
|
+
@param args {list[str]} CLI argument tokens excluding program name.
|
|
512
|
+
@param flag {str} Exact flag token to locate (e.g. `--set`).
|
|
513
|
+
@param minimum {int} Minimum acceptable operand count.
|
|
514
|
+
@param maximum {int} Maximum acceptable operand count.
|
|
515
|
+
@return {list[str]} Operand tokens in original order.
|
|
516
|
+
@throws {ConfigError} When the operand count is out of range; the
|
|
517
|
+
message embeds schema-valid usage examples.
|
|
518
|
+
"""
|
|
519
|
+
index = args.index(flag)
|
|
520
|
+
values = args[index + 1:]
|
|
521
|
+
if not minimum <= len(values) <= maximum:
|
|
522
|
+
expected = (
|
|
523
|
+
f"exactly {minimum}"
|
|
524
|
+
if minimum == maximum
|
|
525
|
+
else f"{minimum} or {maximum}"
|
|
526
|
+
)
|
|
527
|
+
raise ConfigError(
|
|
528
|
+
f"{flag} expects {expected} operand(s); usage examples: "
|
|
529
|
+
+ _usage_examples(flag)
|
|
530
|
+
)
|
|
531
|
+
return values
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def _usage_examples(flag: str) -> str:
|
|
535
|
+
"""@brief Build schema-valid usage examples for one config flag.
|
|
536
|
+
|
|
537
|
+
@details Examples always carry complete canonical paths (REQ-022) and
|
|
538
|
+
real schema-valid values.
|
|
539
|
+
@param flag {str} Exact flag token (e.g. `--set`).
|
|
540
|
+
@return {str} Semicolon-separated example command tails.
|
|
541
|
+
"""
|
|
542
|
+
if flag == "--get":
|
|
543
|
+
return (
|
|
544
|
+
"'--get Notifications' or "
|
|
545
|
+
"'--get Notifications:new_version_color'"
|
|
546
|
+
)
|
|
547
|
+
if flag == "--set":
|
|
548
|
+
section_example = (
|
|
549
|
+
"--set Notifications "
|
|
550
|
+
'{"new_version_color":"bright_green",'
|
|
551
|
+
'"error_color":"bright_red"}'
|
|
552
|
+
)
|
|
553
|
+
return (
|
|
554
|
+
"'--set Notifications:new_version_color bright_green' or "
|
|
555
|
+
f"'{section_example}'"
|
|
556
|
+
)
|
|
557
|
+
if flag == "--unset":
|
|
558
|
+
return (
|
|
559
|
+
"'--unset Notifications:new_version_color' or "
|
|
560
|
+
"'--unset Notifications'"
|
|
561
|
+
)
|
|
562
|
+
if flag in ("--print", "--info"):
|
|
563
|
+
return (
|
|
564
|
+
f"'{flag}' or '{flag} Notifications' or "
|
|
565
|
+
f"'{flag} Notifications:new_version_color'"
|
|
566
|
+
)
|
|
567
|
+
return f"'{flag}'"
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def _fail(error: ConfigError) -> int:
|
|
571
|
+
"""@brief Report a configuration failure and yield the exit status.
|
|
572
|
+
|
|
573
|
+
@details Diagnostics go to stderr with an `Error:` prefix; stdout
|
|
574
|
+
stays untouched so no partial success output exists
|
|
575
|
+
(REQ-023).
|
|
576
|
+
@param error {ConfigError} Failure carrying the diagnostic message.
|
|
577
|
+
@return {int} Always 1.
|
|
578
|
+
"""
|
|
579
|
+
print(f"Error: {error}", file=sys.stderr)
|
|
580
|
+
return 1
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def handle_get(args: list[str]) -> int:
|
|
584
|
+
"""@brief Execute `--get Path` (REQ-016).
|
|
585
|
+
|
|
586
|
+
@details Bootstraps storage, loads strictly, resolves the canonical
|
|
587
|
+
path, and prints the resolved value as one valid JSON
|
|
588
|
+
document on stdout without decoration (JSON-quoted strings,
|
|
589
|
+
objects for sections).
|
|
590
|
+
@param args {list[str]} CLI argument tokens excluding program name.
|
|
591
|
+
@return {int} 0 on success; 1 with a stderr diagnostic on failure.
|
|
592
|
+
"""
|
|
593
|
+
try:
|
|
594
|
+
(path,) = operand_values(args, "--get", 1, 1)
|
|
595
|
+
ensure_bootstrapped()
|
|
596
|
+
payload = load_strict()
|
|
597
|
+
value = get_value(payload, resolve_segments(path))
|
|
598
|
+
except ConfigError as error:
|
|
599
|
+
return _fail(error)
|
|
600
|
+
print(json.dumps(value))
|
|
601
|
+
return 0
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def handle_set(args: list[str]) -> int:
|
|
605
|
+
"""@brief Execute `--set Path Value` (REQ-017, DES-014).
|
|
606
|
+
|
|
607
|
+
@details Parses Value into the schema type, validates the entire
|
|
608
|
+
resulting configuration, and persists atomically; success is
|
|
609
|
+
silent and any rejection leaves the stored file untouched.
|
|
610
|
+
@param args {list[str]} CLI argument tokens excluding program name.
|
|
611
|
+
@return {int} 0 on success; 1 with a stderr diagnostic on failure.
|
|
612
|
+
"""
|
|
613
|
+
try:
|
|
614
|
+
path, raw = operand_values(args, "--set", 2, 2)
|
|
615
|
+
ensure_bootstrapped()
|
|
616
|
+
payload = load_strict()
|
|
617
|
+
updated = set_value(payload, path, raw)
|
|
618
|
+
atomic_write_json(config_path(), updated)
|
|
619
|
+
except ConfigError as error:
|
|
620
|
+
return _fail(error)
|
|
621
|
+
return 0
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
def handle_unset(args: list[str]) -> int:
|
|
625
|
+
"""@brief Execute `--unset Path` (REQ-018, DES-014).
|
|
626
|
+
|
|
627
|
+
@details Restores the targeted parameter or section to schema
|
|
628
|
+
defaults and persists atomically; success is silent.
|
|
629
|
+
@param args {list[str]} CLI argument tokens excluding program name.
|
|
630
|
+
@return {int} 0 on success; 1 with a stderr diagnostic on failure.
|
|
631
|
+
"""
|
|
632
|
+
try:
|
|
633
|
+
(path,) = operand_values(args, "--unset", 1, 1)
|
|
634
|
+
ensure_bootstrapped()
|
|
635
|
+
payload = load_strict()
|
|
636
|
+
updated = unset_value(payload, path)
|
|
637
|
+
atomic_write_json(config_path(), updated)
|
|
638
|
+
except ConfigError as error:
|
|
639
|
+
return _fail(error)
|
|
640
|
+
return 0
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
def handle_print_raw(args: list[str]) -> int:
|
|
644
|
+
"""@brief Execute `--print-raw` (REQ-021).
|
|
645
|
+
|
|
646
|
+
@details Emits the exact bytes of the global configuration JSON file
|
|
647
|
+
without parsing, reformatting, headings, or trailing text;
|
|
648
|
+
no tree formatting is ever applied (on-disk debugging view).
|
|
649
|
+
@param args {list[str]} CLI argument tokens excluding program name.
|
|
650
|
+
@return {int} 0 on success; 1 with a stderr diagnostic on failure.
|
|
651
|
+
"""
|
|
652
|
+
try:
|
|
653
|
+
operand_values(args, "--print-raw", 0, 0)
|
|
654
|
+
ensure_bootstrapped()
|
|
655
|
+
data = config_path().read_bytes()
|
|
656
|
+
except ConfigError as error:
|
|
657
|
+
return _fail(error)
|
|
658
|
+
except OSError as error:
|
|
659
|
+
return _fail(ConfigError(f"cannot read configuration file: {error}"))
|
|
660
|
+
sys.stdout.buffer.write(data)
|
|
661
|
+
sys.stdout.buffer.flush()
|
|
662
|
+
return 0
|