cells-cli 0.2.1__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.
- cells/cli/__init__.py +65 -0
- cells/cli/app.py +336 -0
- cells/cli/banner.py +117 -0
- cells/cli/command.py +147 -0
- cells/cli/converters.py +73 -0
- cells/cli/env.py +100 -0
- cells/cli/errors.py +30 -0
- cells/cli/menu.py +110 -0
- cells/cli/parser.py +129 -0
- cells/cli/prompt.py +98 -0
- cells/cli/render.py +135 -0
- cells/cli/resolver.py +167 -0
- cells/cli/session.py +185 -0
- cells/cli/style.py +46 -0
- cells/cli/text.py +136 -0
- cells/cli/version.py +3 -0
- cells_cli-0.2.1.dist-info/METADATA +205 -0
- cells_cli-0.2.1.dist-info/RECORD +21 -0
- cells_cli-0.2.1.dist-info/WHEEL +5 -0
- cells_cli-0.2.1.dist-info/licenses/LICENSE +21 -0
- cells_cli-0.2.1.dist-info/top_level.txt +1 -0
cells/cli/converters.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Reusable parameter converters; independent of argparse and presentation."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from decimal import ROUND_HALF_EVEN, Decimal, localcontext
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
TRUTHY_VALUES = frozenset({"1", "true", "yes", "on", "y", "t", "enabled"})
|
|
8
|
+
FALSY_VALUES = frozenset({"0", "false", "no", "off", "n", "f", "disabled"})
|
|
9
|
+
_HUMAN_INT_RE = re.compile(r"([0-9]+(?:\.[0-9]+)?)\s*([KMGTP]I?)?", re.IGNORECASE | re.ASCII)
|
|
10
|
+
_UNITS = {
|
|
11
|
+
"": 1,
|
|
12
|
+
**{s: 1000**i for i, s in enumerate("KMGTP", 1)},
|
|
13
|
+
**{s + "I": 1024**i for i, s in enumerate("KMGTP", 1)},
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def parse_bool(value: str | bool | int) -> bool:
|
|
18
|
+
"""Parse recognized boolean tokens, raising ValueError for unknown values."""
|
|
19
|
+
if isinstance(value, bool):
|
|
20
|
+
return value
|
|
21
|
+
if isinstance(value, (str, int)):
|
|
22
|
+
normalized = str(value).strip().lower()
|
|
23
|
+
if normalized in TRUTHY_VALUES:
|
|
24
|
+
return True
|
|
25
|
+
if normalized in FALSY_VALUES:
|
|
26
|
+
return False
|
|
27
|
+
raise ValueError("expected a boolean (true/false, yes/no, on/off, 1/0)")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def parse_human_int(value: str | int | float) -> int:
|
|
31
|
+
"""Decimal K/M/G/T/P, binary Ki/Mi/Gi/Ti/Pi; truncate toward zero."""
|
|
32
|
+
# bool subclasses int, but a boolean is not a quantity.
|
|
33
|
+
if isinstance(value, bool):
|
|
34
|
+
raise ValueError("boolean is not an integer quantity")
|
|
35
|
+
if isinstance(value, int):
|
|
36
|
+
return value
|
|
37
|
+
if isinstance(value, float):
|
|
38
|
+
try:
|
|
39
|
+
return int(value)
|
|
40
|
+
except (OverflowError, ValueError) as exc:
|
|
41
|
+
raise ValueError("expected a finite quantity") from exc
|
|
42
|
+
if not isinstance(value, str) or not (match := _HUMAN_INT_RE.fullmatch(value.strip())):
|
|
43
|
+
raise ValueError("invalid integer quantity")
|
|
44
|
+
number, suffix = match.groups()
|
|
45
|
+
# @AI: Exact integer arithmetic; float and Decimal context rounding would lose large digits.
|
|
46
|
+
whole, _, fraction = number.partition(".")
|
|
47
|
+
return int(whole + fraction) * _UNITS[(suffix or "").upper()] // 10 ** len(fraction)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def format_human_int(value: int) -> str:
|
|
51
|
+
"""Human-readable decimal quantity; intentionally approximate to one decimal."""
|
|
52
|
+
if value < 1000:
|
|
53
|
+
return str(value)
|
|
54
|
+
for suffix in reversed("KMGTP"):
|
|
55
|
+
unit = _UNITS[suffix]
|
|
56
|
+
if value >= unit:
|
|
57
|
+
if value % unit == 0:
|
|
58
|
+
return f"{value // unit}{suffix}"
|
|
59
|
+
with localcontext() as ctx:
|
|
60
|
+
ctx.prec = len(str(value)) + 2
|
|
61
|
+
quotient = (Decimal(value) / unit).quantize(
|
|
62
|
+
Decimal("0.1"), rounding=ROUND_HALF_EVEN
|
|
63
|
+
)
|
|
64
|
+
return f"{quotient:.1f}".removesuffix(".0") + suffix
|
|
65
|
+
return str(value)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def parse_human_int_or_default(value: str | int | float | None, default: int) -> int:
|
|
69
|
+
"""Parse a human-readable integer, returning the default if absent or invalid."""
|
|
70
|
+
try:
|
|
71
|
+
return parse_human_int(value) if value is not None else default
|
|
72
|
+
except ValueError:
|
|
73
|
+
return default
|
cells/cli/env.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Explicit dotenv utilities. App resolution never modifies process environment."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from .converters import TRUTHY_VALUES
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
_ENV_LINE_RE = re.compile(r"^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def get_env[T](key: str, default: T | None = None) -> str | T | None:
|
|
14
|
+
"""Read a trimmed environment value; missing or blank values use the default."""
|
|
15
|
+
return os.getenv(key, "").strip() or default
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def is_env_true(key: str, default: bool = False) -> bool:
|
|
19
|
+
"""Test a truthy environment value; unknown nonblank tokens are false."""
|
|
20
|
+
return (get_env(key, default=str(default)) or "").lower() in TRUTHY_VALUES
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def parse_env_file(path: str | Path, *, strict: bool = False) -> dict[str, str]:
|
|
24
|
+
"""Simple KEY=VALUE format, optional export and surrounding quotes; no shell evaluation."""
|
|
25
|
+
result = {}
|
|
26
|
+
for lineno, raw in enumerate(Path(path).read_text(encoding="utf-8").splitlines(), 1):
|
|
27
|
+
if not raw.strip() or raw.lstrip().startswith("#"):
|
|
28
|
+
continue
|
|
29
|
+
match = _ENV_LINE_RE.fullmatch(raw)
|
|
30
|
+
if not match:
|
|
31
|
+
if strict:
|
|
32
|
+
raise ValueError(f"{path}:{lineno}: expected KEY=VALUE")
|
|
33
|
+
continue
|
|
34
|
+
key, value = match.groups()
|
|
35
|
+
value = value.strip()
|
|
36
|
+
if value.startswith(('"', "'")):
|
|
37
|
+
if len(value) >= 2 and value[0] == value[-1]:
|
|
38
|
+
value = value[1:-1]
|
|
39
|
+
elif strict:
|
|
40
|
+
raise ValueError(f"{path}:{lineno}: unclosed quote")
|
|
41
|
+
result[key] = value
|
|
42
|
+
return result
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def load_env_file(
|
|
46
|
+
path: str | Path,
|
|
47
|
+
*,
|
|
48
|
+
override: bool = False,
|
|
49
|
+
update_process_env: bool = True,
|
|
50
|
+
strict: bool = False,
|
|
51
|
+
) -> dict[str, str]:
|
|
52
|
+
"""Parse one dotenv file and optionally update the process environment.
|
|
53
|
+
|
|
54
|
+
Existing environment values win unless override is True. The returned
|
|
55
|
+
mapping contains the parsed file values, even when mutation is disabled.
|
|
56
|
+
"""
|
|
57
|
+
result = parse_env_file(path, strict=strict)
|
|
58
|
+
if update_process_env:
|
|
59
|
+
for key, value in result.items():
|
|
60
|
+
if override or key not in os.environ:
|
|
61
|
+
os.environ[key] = value
|
|
62
|
+
return result
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def find_env_files(
|
|
66
|
+
root: str | Path = ".", *, patterns: tuple[str, ...] = (".env", "*.env"), recursive: bool = True
|
|
67
|
+
) -> list[Path]:
|
|
68
|
+
"""Find matching dotenv files in deterministic resolved-path order."""
|
|
69
|
+
root = Path(root)
|
|
70
|
+
return sorted(
|
|
71
|
+
{
|
|
72
|
+
path.resolve()
|
|
73
|
+
for pattern in patterns
|
|
74
|
+
for path in (root.rglob(pattern) if recursive else root.glob(pattern))
|
|
75
|
+
if path.is_file()
|
|
76
|
+
}
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def load_env_files(
|
|
81
|
+
root: str | Path = ".",
|
|
82
|
+
*,
|
|
83
|
+
patterns: tuple[str, ...] = (".env", "*.env"),
|
|
84
|
+
recursive: bool = True,
|
|
85
|
+
override: bool = False,
|
|
86
|
+
update_process_env: bool = True,
|
|
87
|
+
strict: bool = False,
|
|
88
|
+
) -> dict[str, str]:
|
|
89
|
+
"""Discover and load dotenv files below root in deterministic path order."""
|
|
90
|
+
merged = {}
|
|
91
|
+
for path in find_env_files(root, patterns=patterns, recursive=recursive):
|
|
92
|
+
for key, value in parse_env_file(path, strict=strict).items():
|
|
93
|
+
if override or key not in merged:
|
|
94
|
+
merged[key] = value
|
|
95
|
+
# Resolve file precedence before mutating the environment, if requested.
|
|
96
|
+
if update_process_env:
|
|
97
|
+
for key, value in merged.items():
|
|
98
|
+
if override or key not in os.environ:
|
|
99
|
+
os.environ[key] = value
|
|
100
|
+
return merged
|
cells/cli/errors.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Navigation is distinct from validation and application failures."""
|
|
2
|
+
|
|
3
|
+
from enum import StrEnum
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
CANCELLED_EXIT_CODE = 130
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class PromptFlow(StrEnum):
|
|
10
|
+
"""Represent navigation back to a menu or out of the entire session."""
|
|
11
|
+
|
|
12
|
+
BACK = "back"
|
|
13
|
+
QUIT_ALL = "quit_all"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class PromptInterruptError(Exception):
|
|
17
|
+
"""Navigation control signal, not a business failure."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, flow: PromptFlow):
|
|
20
|
+
"""Attach the requested navigation flow to the interruption."""
|
|
21
|
+
self.flow = flow
|
|
22
|
+
super().__init__(flow.value)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class PromptUnavailableError(RuntimeError):
|
|
26
|
+
"""Interactive input was requested in a noninteractive entry."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ValidationError(ValueError):
|
|
30
|
+
"""A user-correctable form validation failure."""
|
cells/cli/menu.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""One declaration model for static and runtime menus."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import TextIO
|
|
6
|
+
|
|
7
|
+
from .errors import PromptFlow, PromptInterruptError
|
|
8
|
+
from .prompt import parse_navigation, read_prompt_input
|
|
9
|
+
from .render import render_section
|
|
10
|
+
from .style import Tone, paint
|
|
11
|
+
from .text import display_width, pad_to_width
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _normalize_token(value: str) -> str:
|
|
15
|
+
"""Normalize a menu token for case-insensitive matching."""
|
|
16
|
+
return value.strip().casefold()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True, slots=True)
|
|
20
|
+
class MenuItem:
|
|
21
|
+
"""Describe a selectable action, its display number and accepted aliases."""
|
|
22
|
+
|
|
23
|
+
number: str
|
|
24
|
+
key: str
|
|
25
|
+
label: str
|
|
26
|
+
description: str = ""
|
|
27
|
+
aliases: tuple[str, ...] = ()
|
|
28
|
+
|
|
29
|
+
def __post_init__(self) -> None:
|
|
30
|
+
"""Freeze aliases to keep accepted selection tokens stable."""
|
|
31
|
+
object.__setattr__(self, "aliases", tuple(self.aliases))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True, slots=True)
|
|
35
|
+
class MenuSpec:
|
|
36
|
+
"""Describe an immutable menu and reject ambiguous or reserved selection tokens."""
|
|
37
|
+
|
|
38
|
+
title: str
|
|
39
|
+
items: Sequence[MenuItem]
|
|
40
|
+
subtitle_lines: tuple[str, ...] = ()
|
|
41
|
+
q_label: str = "back"
|
|
42
|
+
invalid_hint: str = "Unknown selection; enter a number or action name."
|
|
43
|
+
|
|
44
|
+
def __post_init__(self) -> None:
|
|
45
|
+
"""Freeze menu sequences and validate the accepted token index."""
|
|
46
|
+
object.__setattr__(self, "items", tuple(self.items))
|
|
47
|
+
object.__setattr__(self, "subtitle_lines", tuple(self.subtitle_lines))
|
|
48
|
+
# Reject ambiguous navigation before the first menu is displayed.
|
|
49
|
+
self._build_token_index()
|
|
50
|
+
|
|
51
|
+
def _build_token_index(self) -> dict[str, str]:
|
|
52
|
+
"""Map accepted input tokens to unique action keys."""
|
|
53
|
+
index: dict[str, str] = {}
|
|
54
|
+
keys: set[str] = set()
|
|
55
|
+
for item in self.items:
|
|
56
|
+
if _normalize_token(item.key) in keys:
|
|
57
|
+
raise ValueError(f"Duplicate menu key: {item.key!r}")
|
|
58
|
+
keys.add(_normalize_token(item.key))
|
|
59
|
+
for raw in (item.number, item.key, item.label, *item.aliases):
|
|
60
|
+
token = _normalize_token(raw)
|
|
61
|
+
if not token or parse_navigation(token) is not None:
|
|
62
|
+
raise ValueError(f"Empty or reserved menu token: {raw!r}")
|
|
63
|
+
if token in index and index[token] != item.key:
|
|
64
|
+
raise ValueError(f"Ambiguous menu token: {raw!r}")
|
|
65
|
+
index[token] = item.key
|
|
66
|
+
return index
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass(frozen=True, slots=True)
|
|
70
|
+
class MenuChoice:
|
|
71
|
+
"""Represent either a selected action key or a navigation request."""
|
|
72
|
+
|
|
73
|
+
key: str | None = None
|
|
74
|
+
flow: PromptFlow | None = None
|
|
75
|
+
|
|
76
|
+
def __post_init__(self) -> None:
|
|
77
|
+
"""Require exactly one action key or navigation request."""
|
|
78
|
+
if (self.key is None) == (self.flow is None):
|
|
79
|
+
raise ValueError("exactly one of key and flow is required")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def run_menu(spec: MenuSpec, input: TextIO, output: TextIO, *, color: bool = False) -> MenuChoice:
|
|
83
|
+
"""Display a menu and read one valid selection or navigation request."""
|
|
84
|
+
index = spec._build_token_index()
|
|
85
|
+
output.write(render_section(spec.title, spec.subtitle_lines, color=color) + "\n")
|
|
86
|
+
number_width = max((display_width(i.number) for i in spec.items), default=1)
|
|
87
|
+
label_width = max((display_width(i.label) for i in spec.items), default=0)
|
|
88
|
+
for item in spec.items:
|
|
89
|
+
number = " " * (number_width - display_width(item.number)) + item.number
|
|
90
|
+
output.write(
|
|
91
|
+
f" {paint(number, Tone.WARN, bold=True, color=color)} {pad_to_width(item.label, label_width)} {paint(item.description, Tone.MUTED, color=color)}\n"
|
|
92
|
+
)
|
|
93
|
+
navigation = "q/qq=exit" if spec.q_label == "exit" else f"q={spec.q_label} · qq=exit"
|
|
94
|
+
output.write(
|
|
95
|
+
"\n "
|
|
96
|
+
+ paint(
|
|
97
|
+
f"{navigation} | Select a number or action name",
|
|
98
|
+
Tone.MUTED,
|
|
99
|
+
color=color,
|
|
100
|
+
)
|
|
101
|
+
+ "\n"
|
|
102
|
+
)
|
|
103
|
+
while True:
|
|
104
|
+
try:
|
|
105
|
+
token = _normalize_token(read_prompt_input(input, output, "Select: "))
|
|
106
|
+
except PromptInterruptError as interrupt:
|
|
107
|
+
return MenuChoice(flow=interrupt.flow)
|
|
108
|
+
if token in index:
|
|
109
|
+
return MenuChoice(key=index[token])
|
|
110
|
+
output.write(paint(spec.invalid_hint, Tone.WARN, color=color) + "\n")
|
cells/cli/parser.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Argparse adapter. Missing values are kept missing for the resolver."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
from collections.abc import Sequence
|
|
5
|
+
from functools import partial
|
|
6
|
+
from typing import TextIO
|
|
7
|
+
|
|
8
|
+
from .command import MISSING, CommandSpec
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ParserExitError(Exception):
|
|
12
|
+
"""Carry an argparse exit status without terminating the embedding process."""
|
|
13
|
+
|
|
14
|
+
def __init__(self, status: int):
|
|
15
|
+
"""Store the exit status requested by argparse."""
|
|
16
|
+
self.status = status
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class VersionAction(argparse.Action):
|
|
20
|
+
"""Write version text to the parser's configured output stream."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, option_strings, dest, *, version, **kwargs):
|
|
23
|
+
"""Configure a zero-argument action that prints the version."""
|
|
24
|
+
super().__init__(option_strings, dest, nargs=0, **kwargs)
|
|
25
|
+
self.version = version
|
|
26
|
+
|
|
27
|
+
def __call__(self, parser, namespace, values, option_string=None):
|
|
28
|
+
"""Print the configured version and request successful parser exit."""
|
|
29
|
+
parser.output.write(self.version + "\n")
|
|
30
|
+
parser.exit()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Parser(argparse.ArgumentParser):
|
|
34
|
+
"""Adapt argparse to explicit streams and application-owned exit handling."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, *args, output: TextIO, error_output: TextIO, **kwargs):
|
|
37
|
+
"""Bind parser output streams and disable abbreviated option matching."""
|
|
38
|
+
self.output, self.error_output = output, error_output
|
|
39
|
+
super().__init__(*args, allow_abbrev=False, **kwargs)
|
|
40
|
+
|
|
41
|
+
def print_help(self, file=None):
|
|
42
|
+
"""Write help to the configured output unless a stream is supplied."""
|
|
43
|
+
super().print_help(self.output if file is None else file)
|
|
44
|
+
|
|
45
|
+
def print_usage(self, file=None):
|
|
46
|
+
"""Write usage to the configured output unless a stream is supplied."""
|
|
47
|
+
super().print_usage(self.output if file is None else file)
|
|
48
|
+
|
|
49
|
+
def _print_message(self, message, file=None):
|
|
50
|
+
"""Write argparse messages to the selected stream without global output."""
|
|
51
|
+
if message:
|
|
52
|
+
(self.output if file is None else file).write(message)
|
|
53
|
+
|
|
54
|
+
def exit(self, status=0, message=None):
|
|
55
|
+
"""Raise a parser exit signal after writing any diagnostic message."""
|
|
56
|
+
# Keep argparse from terminating an embedding process; App owns exit status.
|
|
57
|
+
if message:
|
|
58
|
+
(self.error_output if status else self.output).write(message)
|
|
59
|
+
raise ParserExitError(status)
|
|
60
|
+
|
|
61
|
+
def error(self, message):
|
|
62
|
+
"""Report usage and an input error with exit status 2."""
|
|
63
|
+
self.print_usage(self.error_output)
|
|
64
|
+
self.exit(2, f"{self.prog}: error: {message}\n")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def build_parser(
|
|
68
|
+
name: str,
|
|
69
|
+
description: str,
|
|
70
|
+
version: str,
|
|
71
|
+
commands: Sequence[CommandSpec],
|
|
72
|
+
output: TextIO,
|
|
73
|
+
error_output: TextIO,
|
|
74
|
+
) -> Parser:
|
|
75
|
+
"""Build an argparse command tree while preserving absent argument values."""
|
|
76
|
+
factory = partial(Parser, output=output, error_output=error_output)
|
|
77
|
+
root = factory(prog=name, description=description)
|
|
78
|
+
root.add_argument(
|
|
79
|
+
"--version",
|
|
80
|
+
action=VersionAction,
|
|
81
|
+
version=version or name,
|
|
82
|
+
help="show program version and exit",
|
|
83
|
+
)
|
|
84
|
+
root.add_argument("--color", choices=("auto", "always", "never"), default=argparse.SUPPRESS)
|
|
85
|
+
root.set_defaults(_active_parser=root)
|
|
86
|
+
groups = {(): root}
|
|
87
|
+
subparsers = {}
|
|
88
|
+
for command in commands:
|
|
89
|
+
parent = ()
|
|
90
|
+
parts = command.name.split()
|
|
91
|
+
for i, part in enumerate(parts, 1):
|
|
92
|
+
path = tuple(parts[:i])
|
|
93
|
+
if path not in groups:
|
|
94
|
+
if parent not in subparsers:
|
|
95
|
+
subparsers[parent] = groups[parent].add_subparsers(
|
|
96
|
+
parser_class=factory, metavar="COMMAND"
|
|
97
|
+
)
|
|
98
|
+
leaf = i == len(parts)
|
|
99
|
+
child = subparsers[parent].add_parser(
|
|
100
|
+
part,
|
|
101
|
+
help=command.description if leaf else f"{part} commands",
|
|
102
|
+
description=command.description if leaf else None,
|
|
103
|
+
)
|
|
104
|
+
child.set_defaults(_active_parser=child)
|
|
105
|
+
groups[path] = child
|
|
106
|
+
parent = path
|
|
107
|
+
parser = groups[parent]
|
|
108
|
+
parser.set_defaults(_command=command.name)
|
|
109
|
+
for spec in command.arguments:
|
|
110
|
+
a = spec.argument
|
|
111
|
+
details = [a.help] if a.help else []
|
|
112
|
+
if a.env:
|
|
113
|
+
details.append(f"env: {a.env}")
|
|
114
|
+
if a.config:
|
|
115
|
+
details.append(f"config: {a.config}")
|
|
116
|
+
if a.default is not MISSING:
|
|
117
|
+
details.append(f"default: {a.default}")
|
|
118
|
+
if a.choices:
|
|
119
|
+
details.append("choices: " + ", ".join(map(str, a.choices)))
|
|
120
|
+
# @AI: Preserve absence so lower-priority configuration remains visible.
|
|
121
|
+
kwargs = {"default": argparse.SUPPRESS, "help": "; ".join(details)}
|
|
122
|
+
if a.positional:
|
|
123
|
+
parser.add_argument(spec.name, nargs="?", **kwargs)
|
|
124
|
+
else:
|
|
125
|
+
flags = [spec.cli_name] + ([a.short] if a.short else [])
|
|
126
|
+
if spec.annotation is bool:
|
|
127
|
+
kwargs["action"] = argparse.BooleanOptionalAction
|
|
128
|
+
parser.add_argument(*flags, dest=spec.name, **kwargs)
|
|
129
|
+
return root
|
cells/cli/prompt.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Line-mode input, validation and navigation. No global I/O."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable, Sequence
|
|
4
|
+
from typing import TextIO
|
|
5
|
+
|
|
6
|
+
from .errors import PromptFlow, PromptInterruptError
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def parse_navigation(value: str) -> PromptFlow | None:
|
|
10
|
+
"""Recognize reserved navigation tokens, returning None for ordinary input."""
|
|
11
|
+
match value.strip().lower():
|
|
12
|
+
case "q" | "back" | "cancel":
|
|
13
|
+
return PromptFlow.BACK
|
|
14
|
+
case "qq" | "quit" | "exit":
|
|
15
|
+
return PromptFlow.QUIT_ALL
|
|
16
|
+
return None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def read_prompt_input(input: TextIO, output: TextIO, prompt: str) -> str:
|
|
20
|
+
"""Read trimmed input and raise a navigation interrupt for reserved commands or EOF."""
|
|
21
|
+
output.write(prompt)
|
|
22
|
+
output.flush()
|
|
23
|
+
value = input.readline()
|
|
24
|
+
# EOF is different from an empty line, which may accept a default.
|
|
25
|
+
if value == "":
|
|
26
|
+
raise PromptInterruptError(PromptFlow.QUIT_ALL)
|
|
27
|
+
value = value.strip()
|
|
28
|
+
if (flow := parse_navigation(value)) is not None:
|
|
29
|
+
raise PromptInterruptError(flow)
|
|
30
|
+
return value
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def ask_text(input: TextIO, output: TextIO, label: str, default: str | None = None) -> str:
|
|
34
|
+
"""Read nonempty text or accept the supplied default on Enter."""
|
|
35
|
+
while True:
|
|
36
|
+
value = read_prompt_input(
|
|
37
|
+
input, output, f"{label} [{default}]: " if default else f"{label}: "
|
|
38
|
+
)
|
|
39
|
+
if value:
|
|
40
|
+
return value
|
|
41
|
+
if default is not None:
|
|
42
|
+
return default
|
|
43
|
+
output.write("Please enter a value, or type 'q' to cancel.\n")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def ask_yes_no(input: TextIO, output: TextIO, label: str, default_yes: bool = False) -> bool:
|
|
47
|
+
"""Read a yes/no answer, accepting the configured default on Enter."""
|
|
48
|
+
suffix = "[Y/n]" if default_yes else "[y/N]"
|
|
49
|
+
while True:
|
|
50
|
+
value = read_prompt_input(input, output, f"{label} {suffix}: ").lower()
|
|
51
|
+
if not value:
|
|
52
|
+
return default_yes
|
|
53
|
+
if value in ("y", "yes"):
|
|
54
|
+
return True
|
|
55
|
+
if value in ("n", "no"):
|
|
56
|
+
return False
|
|
57
|
+
output.write("Please answer yes or no, or type 'q' to cancel.\n")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def select_one(input: TextIO, output: TextIO, label: str, items: Sequence[str]) -> str:
|
|
61
|
+
"""Return a choice by number or exact name; empty choices request navigation back."""
|
|
62
|
+
if not items:
|
|
63
|
+
output.write(f"No selectable items available for {label}.\n")
|
|
64
|
+
raise PromptInterruptError(PromptFlow.BACK)
|
|
65
|
+
output.write(f"{label}:\n")
|
|
66
|
+
for i, item in enumerate(items, 1):
|
|
67
|
+
output.write(f" {i}) {item}\n")
|
|
68
|
+
while True:
|
|
69
|
+
value = read_prompt_input(input, output, "> ")
|
|
70
|
+
if value.isascii() and value.isdecimal():
|
|
71
|
+
# Avoid int() limits for arbitrarily large input.
|
|
72
|
+
number = value.lstrip("0") or "0"
|
|
73
|
+
if len(number) <= len(str(len(items))) and 1 <= int(number) <= len(items):
|
|
74
|
+
return items[int(number) - 1]
|
|
75
|
+
if value in items:
|
|
76
|
+
return value
|
|
77
|
+
output.write("Choose an item by number or exact name, or type 'q' to cancel.\n")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def ask_parsed[T](
|
|
81
|
+
input: TextIO,
|
|
82
|
+
output: TextIO,
|
|
83
|
+
label: str,
|
|
84
|
+
parse: Callable[[str], T],
|
|
85
|
+
*,
|
|
86
|
+
default: str | None = None,
|
|
87
|
+
) -> T:
|
|
88
|
+
"""Read and convert input, retrying ValueError while preserving other failures."""
|
|
89
|
+
while True:
|
|
90
|
+
value = read_prompt_input(
|
|
91
|
+
input, output, f"{label}: " if default is None else f"{label} [{default}]: "
|
|
92
|
+
)
|
|
93
|
+
candidate = default if value == "" and default is not None else value
|
|
94
|
+
try:
|
|
95
|
+
return parse(candidate)
|
|
96
|
+
# Only user-correctable conversion failures should retry.
|
|
97
|
+
except ValueError as error:
|
|
98
|
+
output.write(f"Invalid value: {error}. Try again, or type 'q' to cancel.\n")
|
cells/cli/render.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""Pure line-mode renderers; formatting does not own I/O."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping, Sequence
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
|
|
6
|
+
from .style import Tone, paint
|
|
7
|
+
from .text import display_width, strip_ansi
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True, slots=True)
|
|
11
|
+
class KvRow:
|
|
12
|
+
"""Represent a single key/value display row."""
|
|
13
|
+
|
|
14
|
+
key: str
|
|
15
|
+
value: str
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def kv(key: object, value: object) -> KvRow:
|
|
19
|
+
"""Convert arbitrary objects to the strings of a key/value row."""
|
|
20
|
+
return KvRow(str(key), str(value))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def render_kv_rows(rows: Sequence[KvRow], *, color: bool = False) -> str:
|
|
24
|
+
"""Align keys by terminal cell width and render rows without stream I/O."""
|
|
25
|
+
widths = [display_width(row.key) for row in rows]
|
|
26
|
+
width = max(widths, default=0)
|
|
27
|
+
return "\n".join(
|
|
28
|
+
(row.key if color else strip_ansi(row.key))
|
|
29
|
+
+ " " * (width - actual)
|
|
30
|
+
+ " "
|
|
31
|
+
+ (row.value if color else strip_ansi(row.value))
|
|
32
|
+
for row, actual in zip(rows, widths, strict=True)
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(slots=True)
|
|
37
|
+
class Table:
|
|
38
|
+
"""Accumulate mutable rows and render them against the declared headers."""
|
|
39
|
+
|
|
40
|
+
# Intentionally mutable: handlers append rows incrementally before rendering.
|
|
41
|
+
headers: Sequence[str]
|
|
42
|
+
rows: list[tuple[str, ...]] = field(default_factory=list, init=False)
|
|
43
|
+
|
|
44
|
+
def __post_init__(self) -> None:
|
|
45
|
+
"""Detach headers from the caller's mutable sequence."""
|
|
46
|
+
self.headers = tuple(self.headers)
|
|
47
|
+
|
|
48
|
+
def add_row(self, row: Sequence[object]) -> None:
|
|
49
|
+
"""Append a row after converting its cells to strings."""
|
|
50
|
+
self.rows.append(tuple(map(str, row)))
|
|
51
|
+
|
|
52
|
+
def is_empty(self) -> bool:
|
|
53
|
+
"""Return whether the table has no data rows."""
|
|
54
|
+
return not self.rows
|
|
55
|
+
|
|
56
|
+
def render(self, *, color: bool = False) -> str:
|
|
57
|
+
"""Render aligned columns, padding missing cells and ignoring excess cells."""
|
|
58
|
+
if not self.headers:
|
|
59
|
+
return ""
|
|
60
|
+
count = len(self.headers)
|
|
61
|
+
# Normalize ragged rows to the declared header width before alignment.
|
|
62
|
+
rows = [self.headers, *(tuple((row + ("",) * count)[:count]) for row in self.rows)]
|
|
63
|
+
# @AI: Measure each cell once per render; a mutable Table must not retain stale widths.
|
|
64
|
+
measured = [tuple(map(display_width, row)) for row in rows]
|
|
65
|
+
widths = [max(column) for column in zip(*measured, strict=True)]
|
|
66
|
+
|
|
67
|
+
def line(row: Sequence[str], cell_widths: tuple[int, ...]) -> str:
|
|
68
|
+
return " ".join(
|
|
69
|
+
(cell if color else strip_ansi(cell)) + " " * (width - actual)
|
|
70
|
+
for cell, width, actual in zip(row, widths, cell_widths, strict=True)
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
return "\n".join(
|
|
74
|
+
[
|
|
75
|
+
paint(line(self.headers, measured[0]), Tone.ACCENT, bold=True, color=color),
|
|
76
|
+
" ".join("-" * w for w in widths),
|
|
77
|
+
*(line(row, sizes) for row, sizes in zip(rows[1:], measured[1:], strict=True)),
|
|
78
|
+
]
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def render_section(title: str, detail: Sequence[str] = (), *, color: bool = False) -> str:
|
|
83
|
+
"""Render a section heading, divider and optional detail lines."""
|
|
84
|
+
rule = paint("─" * 64, Tone.MUTED, color=color)
|
|
85
|
+
return "\n".join(
|
|
86
|
+
[
|
|
87
|
+
"",
|
|
88
|
+
rule,
|
|
89
|
+
" " + paint(title, Tone.INFO, bold=True, color=color),
|
|
90
|
+
*(" " + paint(item, Tone.MUTED, color=color) for item in detail),
|
|
91
|
+
rule,
|
|
92
|
+
]
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
_STATUS = {
|
|
97
|
+
**dict.fromkeys(
|
|
98
|
+
[
|
|
99
|
+
"active",
|
|
100
|
+
"enabled",
|
|
101
|
+
"up",
|
|
102
|
+
"running",
|
|
103
|
+
"ready",
|
|
104
|
+
"ok",
|
|
105
|
+
"yes",
|
|
106
|
+
"present",
|
|
107
|
+
"started",
|
|
108
|
+
"restarted",
|
|
109
|
+
"online",
|
|
110
|
+
],
|
|
111
|
+
Tone.GOOD,
|
|
112
|
+
),
|
|
113
|
+
**dict.fromkeys(
|
|
114
|
+
["inactive", "disabled", "down", "failed", "error", "no", "missing", "stopped", "offline"],
|
|
115
|
+
Tone.BAD,
|
|
116
|
+
),
|
|
117
|
+
**dict.fromkeys(["unknown", "degraded", "partial", "warning", "probing", "stale"], Tone.WARN),
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def render_status(
|
|
122
|
+
text: str, mapping: Mapping[str, Tone] | None = None, *, color: bool = False
|
|
123
|
+
) -> str:
|
|
124
|
+
"""Render a status using a caller override or the built-in semantic tone mapping."""
|
|
125
|
+
normalized = text.strip().lower()
|
|
126
|
+
tone = next(
|
|
127
|
+
(v for k, v in (mapping or {}).items() if k.strip().lower() == normalized),
|
|
128
|
+
_STATUS.get(normalized, Tone.INFO),
|
|
129
|
+
)
|
|
130
|
+
return paint(text, tone, bold=True, color=color)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def render_yes_no(value: bool, *, color: bool = False) -> str:
|
|
134
|
+
"""Render a boolean as a semantic yes/no status."""
|
|
135
|
+
return render_status("yes" if value else "no", color=color)
|