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.
@@ -0,0 +1,474 @@
1
+ #!/usr/bin/env python3
2
+ ## @file config_render.py
3
+ # @brief Deterministic tree renderer and table formatter for the
4
+ # configuration CLI `--print` and `--info` commands.
5
+ # @details One shared data-driven renderer (DES-012) emits UTF-8
6
+ # box-drawing trees from typed `ConfigNode` values for both
7
+ # display commands; only heading and detail formatters differ.
8
+ # Structural edges (`|-- `, `` -- `` box glyphs) mark real
9
+ # configuration nodes only; metadata and tables are attached
10
+ # detail lines carrying the owning node continuation prefix
11
+ # (DES-013). Tree topology never depends on text width.
12
+ import json
13
+ import sys
14
+ import unicodedata
15
+ from dataclasses import dataclass, field
16
+ from typing import Any
17
+
18
+ from githubtemplateastraluv import config
19
+
20
+ ## @brief Ancestor continuation segment: vertical bar plus three spaces.
21
+ _PREFIX_CONTINUE = "│ "
22
+ ## @brief Ancestor indent segment: exactly four ASCII spaces.
23
+ _PREFIX_INDENT = " "
24
+ ## @brief Tree edge marker for a node with a later real sibling.
25
+ _EDGE_BRANCH = "├── "
26
+ ## @brief Tree edge marker for the final real sibling at a depth.
27
+ _EDGE_LAST = "└── "
28
+
29
+ ## @brief Display heading of the virtual whole-tree root (never a CLI path).
30
+ _ROOT_HEADING_PRINT = "Application_Configuration - Current configuration"
31
+ ## @brief Display heading of the virtual root in `--info` mode.
32
+ _ROOT_HEADING_INFO = "Application_Configuration - Configuration schema and command reference"
33
+
34
+
35
+ @dataclass
36
+ class ConfigNode:
37
+ """@brief Typed tree node of one real configuration element.
38
+
39
+ @details `kind` distinguishes section/dictionary branches from
40
+ parameters; `children` holds only real configuration nodes
41
+ while metadata and tables live in `details` as logical text
42
+ lines (never rendered with structural edge markers).
43
+ """
44
+ ## @brief Canonical schema/CLI token, byte-exact (REQ-022).
45
+ token: str
46
+ ## @brief Full canonical path; None for the virtual display root.
47
+ canonical_path: str | None
48
+ ## @brief Node kind: `virtual-root`, `section`, or `parameter`.
49
+ kind: str
50
+ ## @brief Fully formatted heading line (no tree prefix).
51
+ heading: str
52
+ ## @brief Attached detail logical lines, in display order.
53
+ details: list[str] = field(default_factory=list)
54
+ ## @brief Ordered real child nodes.
55
+ children: list["ConfigNode"] = field(default_factory=list)
56
+
57
+
58
+ def display_width(text: str) -> int:
59
+ """@brief Measure the terminal display width of a string.
60
+
61
+ @details Combining characters count zero; East Asian wide and
62
+ fullwidth characters count two; all others count one.
63
+ @param text {str} Text to measure.
64
+ @return {int} Display width in terminal cells.
65
+ """
66
+ width = 0
67
+ for character in text:
68
+ if unicodedata.combining(character):
69
+ continue
70
+ if unicodedata.east_asian_width(character) in ("F", "W"):
71
+ width += 2
72
+ else:
73
+ width += 1
74
+ return width
75
+
76
+
77
+ def format_table(headers: list[str], rows: list[list[str]]) -> list[str]:
78
+ """@brief Render a rectangular box-drawing table (DES-013).
79
+
80
+ @details Column widths derive from the maximum display width of the
81
+ header and all cells plus one space of padding on each side;
82
+ every border and row shares identical column boundaries, so
83
+ `┬`, `┼`, and `┴` align vertically with the `│` separators.
84
+ Glyph contract (DES-053..DES-056): rounded outer corners
85
+ `╭`/`╮`/`╰`/`╯`; single-line borders built from `─` with
86
+ `┬`/`┴` top/bottom junctions and `├`/`┼`/`┤` row-separator
87
+ junctions; double-line header separator `╞═..╪..═╡` between
88
+ the header row and the content rows.
89
+ @param headers {list[str]} Column header cells.
90
+ @param rows {list[list[str]]} Data rows, each with len(headers) cells.
91
+ @return {list[str]} Physical table lines (borders and rows).
92
+ @satisfies DES-013, DES-053, DES-054, DES-055, DES-056
93
+ """
94
+ widths = [
95
+ max(display_width(headers[column]), *(display_width(row[column]) for row in rows))
96
+ if rows
97
+ else display_width(headers[column])
98
+ for column in range(len(headers))
99
+ ]
100
+
101
+ def border(left: str, horizontal: str, middle: str, right: str) -> str:
102
+ """@brief Render one horizontal border line.
103
+
104
+ @param left {str} Left corner glyph.
105
+ @param horizontal {str} Horizontal fill glyph: `─` for single
106
+ lines, `═` for the double header separator.
107
+ @param middle {str} Column junction glyph.
108
+ @param right {str} Right corner glyph.
109
+ @return {str} Complete border line.
110
+ """
111
+ segments = (horizontal * (width + 2) for width in widths)
112
+ return left + middle.join(segments) + right
113
+
114
+ def data_row(cells: list[str]) -> str:
115
+ """@brief Render one padded data row line.
116
+
117
+ @param cells {list[str]} Row cells; display-padded to column width.
118
+ @return {str} Complete row line sharing the border boundaries.
119
+ """
120
+ padded = " │ ".join(
121
+ cell + " " * (widths[column] - display_width(cell))
122
+ for column, cell in enumerate(cells)
123
+ )
124
+ return f"│ {padded} │"
125
+
126
+ lines = [
127
+ border("╭", "─", "┬", "╮"),
128
+ data_row(headers),
129
+ border("╞", "═", "╪", "╡"),
130
+ ]
131
+ for index, row in enumerate(rows):
132
+ if index:
133
+ lines.append(border("├", "─", "┼", "┤"))
134
+ lines.append(data_row(row))
135
+ lines.append(border("╰", "─", "┴", "╯"))
136
+ return lines
137
+
138
+
139
+ def render_tree(root: ConfigNode) -> str:
140
+ """@brief Render a node hierarchy with the canonical prefix algorithm.
141
+
142
+ @details Implements the normative traversal: the display root prints
143
+ without a marker and its attached details use a four-space
144
+ indent; every real child receives exactly one `├── `/`└── `
145
+ edge preceded by one four-character segment per ancestor
146
+ that has a later sibling; attached details prepend the same
147
+ ancestor segments plus exactly one own continuation segment
148
+ (`│ ` when the node has a later sibling, four spaces
149
+ otherwise). Detail lines never carry structural edge markers
150
+ and never add structural depth (DES-012).
151
+ @param root {ConfigNode} Display root (virtual root or requested
152
+ subtree root).
153
+ @return {str} Complete multi-line rendering without trailing newline.
154
+ """
155
+ lines: list[str] = [root.heading]
156
+ for detail in root.details:
157
+ lines.append(_PREFIX_INDENT + detail)
158
+ for index, child in enumerate(root.children):
159
+ _emit_node(
160
+ child,
161
+ ancestor_has_next=[],
162
+ is_last=index == len(root.children) - 1,
163
+ lines=lines,
164
+ )
165
+ return "\n".join(lines)
166
+
167
+
168
+ def _emit_node(
169
+ node: ConfigNode,
170
+ ancestor_has_next: list[bool],
171
+ is_last: bool,
172
+ lines: list[str],
173
+ ) -> None:
174
+ """@brief Emit one real node, its details, then its child nodes.
175
+
176
+ @details Recursive worker of `render_tree`; `ancestor_has_next` holds
177
+ one entry per actual ancestor recording whether that
178
+ ancestor has a later sibling (REQ-019 connector grammar).
179
+ @param node {ConfigNode} Real configuration node to emit.
180
+ @param ancestor_has_next {list[bool]} Later-sibling flags of ancestors.
181
+ @param is_last {bool} True when `node` is the final sibling at depth.
182
+ @param lines {list[str]} Output accumulator, mutated in place.
183
+ @return {None}
184
+ """
185
+ prefix = "".join(
186
+ _PREFIX_CONTINUE if has_next else _PREFIX_INDENT
187
+ for has_next in ancestor_has_next
188
+ )
189
+ edge = _EDGE_LAST if is_last else _EDGE_BRANCH
190
+ lines.append(prefix + edge + node.heading)
191
+ detail_prefix = prefix + (_PREFIX_INDENT if is_last else _PREFIX_CONTINUE)
192
+ for detail in node.details:
193
+ lines.append(detail_prefix + detail)
194
+ for index, child in enumerate(node.children):
195
+ _emit_node(
196
+ child,
197
+ ancestor_has_next=ancestor_has_next + [not is_last],
198
+ is_last=index == len(node.children) - 1,
199
+ lines=lines,
200
+ )
201
+
202
+
203
+ def _selection_rows(param: config.ParamSpec, current: str) -> list[list[str]]:
204
+ """@brief Build `Sel | Value` rows with exactly one active marker.
205
+
206
+ @param param {config.ParamSpec} Selection parameter descriptor.
207
+ @param current {str} Active value token.
208
+ @return {list[list[str]]} One `[*]` row and `[ ]` rows in enum order.
209
+ """
210
+ return [
211
+ ["[*]" if token == current else "[ ]", json.dumps(token)]
212
+ for token in param.enum
213
+ ]
214
+
215
+
216
+ def _color_meaning(token: str) -> str:
217
+ """@brief Build the Meaning cell text for one enum color token.
218
+
219
+ @param token {str} Selection enum token present in `COLOR_ANSI`.
220
+ @return {str} Text naming the ANSI SGR code and human-readable color.
221
+ """
222
+ sgr = config.COLOR_ANSI[token][2:-1]
223
+ return f"ANSI SGR {sgr} ({token.replace('_', ' ')})"
224
+
225
+
226
+ def _build_print_section(
227
+ section: config.SectionSpec,
228
+ payload: dict[str, Any],
229
+ ) -> ConfigNode:
230
+ """@brief Build a `--print` node for one section with parameter children.
231
+
232
+ @param section {config.SectionSpec} Section schema descriptor.
233
+ @param payload {dict[str, Any]} Current configuration values.
234
+ @return {ConfigNode} Section node carrying parameter child nodes.
235
+ """
236
+ branch = payload[section.token]
237
+ children = [
238
+ _build_print_parameter(section, param, branch[param.token])
239
+ for param in section.params
240
+ ]
241
+ return ConfigNode(
242
+ token=section.token,
243
+ canonical_path=section.token,
244
+ kind="section",
245
+ heading=(
246
+ f"{section.token} - [Path: {section.token}] "
247
+ f"{section.description}"
248
+ ),
249
+ children=children,
250
+ )
251
+
252
+
253
+ def _build_print_parameter(
254
+ section: config.SectionSpec,
255
+ param: config.ParamSpec,
256
+ value: str,
257
+ ) -> ConfigNode:
258
+ """@brief Build a `--print` node for one selection parameter.
259
+
260
+ @details Heading shows `Token = <JSON value>` plus `(default)` or
261
+ `(custom | default: <JSON default>)`; the attached
262
+ `Sel | Value` table lists exactly one `[*]` active row
263
+ (REQ-019).
264
+ @param section {config.SectionSpec} Owning section descriptor.
265
+ @param param {config.ParamSpec} Parameter schema descriptor.
266
+ @param value {str} Current value token.
267
+ @return {ConfigNode} Parameter node with table detail lines.
268
+ """
269
+ canonical_path = f"{section.token}:{param.token}"
270
+ if value == param.default:
271
+ status = "(default)"
272
+ else:
273
+ status = f"(custom | default: {json.dumps(param.default)})"
274
+ heading = f"{param.token} = {json.dumps(value)} {status}"
275
+ return ConfigNode(
276
+ token=param.token,
277
+ canonical_path=canonical_path,
278
+ kind="parameter",
279
+ heading=heading,
280
+ details=format_table(["Sel", "Value"], _selection_rows(param, value)),
281
+ )
282
+
283
+
284
+ def _build_info_section(section: config.SectionSpec) -> ConfigNode:
285
+ """@brief Build an `--info` node for one fixed-schema section.
286
+
287
+ @details Metadata precedes real children: a complete `Full overwrite`
288
+ command with a schema-valid sample object and a complete
289
+ `Reset block` command (REQ-020).
290
+ @param section {config.SectionSpec} Section schema descriptor.
291
+ @return {ConfigNode} Section node with metadata details and children.
292
+ """
293
+ defaults = config.default_config()[section.token]
294
+ overwrite_sample = json.dumps(defaults, separators=(",", ":"))
295
+ details = [
296
+ f"Full overwrite : --set {section.token} '{overwrite_sample}'",
297
+ f"Reset block : --unset {section.token}",
298
+ ]
299
+ children = [
300
+ _build_info_parameter(section, param) for param in section.params
301
+ ]
302
+ return ConfigNode(
303
+ token=section.token,
304
+ canonical_path=section.token,
305
+ kind="section",
306
+ heading=(
307
+ f"{section.token} - [Path: {section.token}] "
308
+ f"{section.description}"
309
+ ),
310
+ details=details,
311
+ children=children,
312
+ )
313
+
314
+
315
+ def _build_info_parameter(
316
+ section: config.SectionSpec,
317
+ param: config.ParamSpec,
318
+ ) -> ConfigNode:
319
+ """@brief Build an `--info` node for one selection parameter.
320
+
321
+ @details Heading reads `Token - [Type: constraints] description`;
322
+ attached details are the Default line with its restore
323
+ command, a complete shell-valid `Set cmd` using a real
324
+ schema-valid example value, and the `Allowed Values` table
325
+ (REQ-020).
326
+ @param section {config.SectionSpec} Owning section descriptor.
327
+ @param param {config.ParamSpec} Parameter schema descriptor.
328
+ @return {ConfigNode} Parameter node with documentation details.
329
+ """
330
+ canonical_path = f"{section.token}:{param.token}"
331
+ heading = (
332
+ f"{param.token} - [{param.type_label}: {param.constraints}] "
333
+ f"{param.description}"
334
+ )
335
+ allowed_rows = [
336
+ [
337
+ token,
338
+ "default" if token == param.default else "",
339
+ _color_meaning(token),
340
+ ]
341
+ for token in param.enum
342
+ ]
343
+ details = [
344
+ f"Default : {json.dumps(param.default)} (restored via: "
345
+ f"--unset {canonical_path})",
346
+ f"Set cmd : --set {canonical_path} {param.default}",
347
+ "Allowed Values:",
348
+ ]
349
+ details.extend(
350
+ format_table(["Value", "Default", "Meaning"], allowed_rows)
351
+ )
352
+ return ConfigNode(
353
+ token=param.token,
354
+ canonical_path=canonical_path,
355
+ kind="parameter",
356
+ heading=heading,
357
+ details=details,
358
+ )
359
+
360
+
361
+ def build_print_root(
362
+ payload: dict[str, Any],
363
+ path: str | None,
364
+ ) -> ConfigNode:
365
+ """@brief Build the display root for `--print`.
366
+
367
+ @details Without a path the virtual `Application_Configuration` root
368
+ carries the schema sections as children; with a canonical
369
+ path the requested node becomes the unconnected display root
370
+ followed by its real descendants, without invented ancestors
371
+ (REQ-019).
372
+ @param payload {dict[str, Any]} Current validated configuration.
373
+ @param path {str | None} Raw canonical path or None for whole tree.
374
+ @return {ConfigNode} Display root node.
375
+ """
376
+ if path is None:
377
+ return ConfigNode(
378
+ token="Application_Configuration",
379
+ canonical_path=None,
380
+ kind="virtual-root",
381
+ heading=_ROOT_HEADING_PRINT,
382
+ children=[
383
+ _build_print_section(section, payload) for section in config.SCHEMA
384
+ ],
385
+ )
386
+ segments = config.resolve_segments(path)
387
+ if len(segments) == 1:
388
+ return _build_print_section(
389
+ config._SECTIONS_BY_TOKEN[segments[0]], payload
390
+ )
391
+ section = config._SECTIONS_BY_TOKEN[segments[0]]
392
+ param = section.param(segments[1])
393
+ if param is None:
394
+ raise config.ConfigError(f"unknown parameter in path {path!r}")
395
+ return _build_print_parameter(
396
+ section, param, payload[section.token][param.token]
397
+ )
398
+
399
+
400
+ def build_info_root(payload: dict[str, Any], path: str | None) -> ConfigNode:
401
+ """@brief Build the display root for `--info`.
402
+
403
+ @details Same node set as `--print` with documentation heading and
404
+ detail formatters; a requested path renders that node as the
405
+ unconnected display root with its descendants (REQ-020).
406
+ @param payload {dict[str, Any]} Current validated configuration.
407
+ @param path {str | None} Raw canonical path or None for whole schema.
408
+ @return {ConfigNode} Display root node.
409
+ """
410
+ if path is None:
411
+ return ConfigNode(
412
+ token="Application_Configuration",
413
+ canonical_path=None,
414
+ kind="virtual-root",
415
+ heading=_ROOT_HEADING_INFO,
416
+ children=[_build_info_section(section) for section in config.SCHEMA],
417
+ )
418
+ segments = config.resolve_segments(path)
419
+ if len(segments) == 1:
420
+ return _build_info_section(config._SECTIONS_BY_TOKEN[segments[0]])
421
+ section = config._SECTIONS_BY_TOKEN[segments[0]]
422
+ param = section.param(segments[1])
423
+ if param is None:
424
+ raise config.ConfigError(f"unknown parameter in path {path!r}")
425
+ return _build_info_parameter(section, param)
426
+
427
+
428
+ def _fail(error: config.ConfigError) -> int:
429
+ """@brief Report a rendering-command failure on stderr.
430
+
431
+ @param error {config.ConfigError} Failure carrying the diagnostic.
432
+ @return {int} Always 1 (REQ-023).
433
+ """
434
+ print(f"Error: {error}", file=sys.stderr)
435
+ return 1
436
+
437
+
438
+ def handle_print(args: list[str]) -> int:
439
+ """@brief Execute `--print [Path]` (REQ-019).
440
+
441
+ @details Bootstraps storage, loads strictly, builds the display tree,
442
+ and prints the rendering on stdout; failures print nothing
443
+ on stdout and report one stderr diagnostic with exit 1.
444
+ @param args {list[str]} CLI argument tokens excluding program name.
445
+ @return {int} 0 on success; 1 on failure.
446
+ """
447
+ try:
448
+ operands = config.operand_values(args, "--print", 0, 1)
449
+ config.ensure_bootstrapped()
450
+ payload = config.load_strict()
451
+ root = build_print_root(payload, operands[0] if operands else None)
452
+ except config.ConfigError as error:
453
+ return _fail(error)
454
+ print(render_tree(root))
455
+ return 0
456
+
457
+
458
+ def handle_info(args: list[str]) -> int:
459
+ """@brief Execute `--info [Path]` (REQ-020).
460
+
461
+ @details Shares the renderer with `--print`; renders schema
462
+ documentation with defaults and complete command examples.
463
+ @param args {list[str]} CLI argument tokens excluding program name.
464
+ @return {int} 0 on success; 1 on failure.
465
+ """
466
+ try:
467
+ operands = config.operand_values(args, "--info", 0, 1)
468
+ config.ensure_bootstrapped()
469
+ payload = config.load_strict()
470
+ root = build_info_root(payload, operands[0] if operands else None)
471
+ except config.ConfigError as error:
472
+ return _fail(error)
473
+ print(render_tree(root))
474
+ return 0
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env python3
2
+ ## @file core.py
3
+ # @brief Core command dispatch and githubtemplateastraluv CLI runtime
4
+ # orchestration.
5
+ # @details Runs the automatic online version check before argument dispatch,
6
+ # then routes management and configuration commands to dedicated
7
+ # handlers and propagates exit codes to the process boundary.
8
+ import sys
9
+
10
+ from githubtemplateastraluv import (
11
+ __version__,
12
+ config,
13
+ config_render,
14
+ management,
15
+ version_check,
16
+ )
17
+ # `__version__` is the single version source (package __init__, skeleton
18
+ # schema); mirrored by pyproject.toml, scripts/templateastraluv.sh,
19
+ # README.md, and uv.lock per .g.conf ver_rules.
20
+
21
+
22
+ def main(argv: list[str] | None = None) -> int:
23
+ """@brief Execute the gated version check, then dispatch commands.
24
+
25
+ @details Dispatch order: `--help` or no arguments -> help screen;
26
+ `--ver` / `--version` -> aligned three-row version report
27
+ fetching PyPI and GitHub with the gate bypassed (REQ-002,
28
+ REQ-027..REQ-031); then `--upgrade`, optionally with the
29
+ `--develop` source modifier selecting the GitHub development
30
+ source (REQ-032..REQ-034) and the `--force` auxiliary
31
+ modifier forcing the full re-download and reinstallation
32
+ (REQ-035..REQ-038); then `--uninstall`; then the additive
33
+ configuration CLI commands `--get`, `--set`, `--unset`,
34
+ `--print-raw`, `--print`, `--info` (PRJ-006); unknown input
35
+ falls back to the help screen. Non-forced invocations
36
+ execute the gated PyPI check before dispatch (REQ-007).
37
+ Existing management dispatch and observable behavior are
38
+ unchanged by the configuration branches (REQ-016..REQ-021).
39
+ @param argv {list[str] | None} CLI arguments excluding the program
40
+ name; None resolves to `sys.argv[1:]`.
41
+ @return {int} Process exit code: 0 on handled dispatch, or the return
42
+ code of the spawned `uv` subprocess for `--upgrade` /
43
+ `--uninstall`, or 1 for configuration CLI failures
44
+ (REQ-023).
45
+ @satisfies REQ-001 REQ-002 REQ-007 REQ-016 REQ-017 REQ-018 REQ-019
46
+ REQ-020 REQ-021 REQ-027 REQ-028 REQ-029 REQ-030 REQ-031
47
+ REQ-032 REQ-033 REQ-034 REQ-035 REQ-036 REQ-037 REQ-038
48
+ A-06 PRJ-006
49
+ """
50
+ args = list(sys.argv[1:]) if argv is None else list(argv)
51
+ forced = "--ver" in args or "--version" in args
52
+ if not forced:
53
+ version_check.run_version_check(__version__, False)
54
+ if not args or ("--help" in args and not forced):
55
+ return management.print_help(__version__)
56
+ if forced:
57
+ version_check.run_version_report(__version__)
58
+ return 0
59
+ if "--upgrade" in args:
60
+ develop = "--develop" in args
61
+ force = "--force" in args
62
+ return management.cmd_upgrade(develop, force)
63
+ if "--uninstall" in args:
64
+ return management.cmd_uninstall()
65
+ if "--get" in args:
66
+ return config.handle_get(args)
67
+ if "--set" in args:
68
+ return config.handle_set(args)
69
+ if "--unset" in args:
70
+ return config.handle_unset(args)
71
+ if "--print-raw" in args:
72
+ return config.handle_print_raw(args)
73
+ if "--print" in args:
74
+ return config_render.handle_print(args)
75
+ if "--info" in args:
76
+ return config_render.handle_info(args)
77
+ return management.print_help(__version__)