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/resolver.py ADDED
@@ -0,0 +1,167 @@
1
+ """Resolve command values from explicit configuration and optional interactive input."""
2
+
3
+ import os
4
+ import tomllib
5
+ from collections.abc import Mapping, Sequence
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from .command import MISSING, ArgumentSpec, CommandSpec
11
+ from .env import parse_env_file
12
+ from .prompt import read_prompt_input
13
+ from .session import Session
14
+ from .style import Tone
15
+
16
+
17
+ DEFAULT_SOURCE_ORDER = ("cli", "env", "dotenv", "config", "default")
18
+
19
+
20
+ def validate_source_order(source_order: tuple[str, ...]) -> tuple[str, ...]:
21
+ """Validate an application-level source order; intermediate sources are optional."""
22
+ if not isinstance(source_order, tuple):
23
+ raise TypeError("source_order must be a tuple")
24
+ if len(source_order) < 2 or source_order[0] != "cli" or source_order[-1] != "default":
25
+ raise ValueError("source_order must start with cli and end with default")
26
+ if any(source not in DEFAULT_SOURCE_ORDER for source in source_order):
27
+ raise ValueError("source_order contains an unknown source")
28
+ if len(set(source_order)) != len(source_order):
29
+ raise ValueError("source_order contains duplicate sources")
30
+ return source_order
31
+
32
+
33
+ class ResolutionError(ValueError):
34
+ """Invalid or missing user-facing parameter, not an application failure."""
35
+
36
+
37
+ @dataclass(frozen=True, slots=True)
38
+ class ArgumentSources:
39
+ """Hold the environment, dotenv and configuration mappings for one entry."""
40
+
41
+ environment: Mapping[str, str]
42
+ dotenv: Mapping[str, str]
43
+ config: Mapping[str, Any]
44
+
45
+
46
+ def load_argument_sources(
47
+ env_files: Sequence[str | Path],
48
+ config: Mapping[str, Any] | str | Path | None,
49
+ environ: Mapping[str, str] | None,
50
+ *,
51
+ source_order: tuple[str, ...] = DEFAULT_SOURCE_ORDER,
52
+ ) -> ArgumentSources:
53
+ """Read enabled sources without changing the process environment."""
54
+ dotenv = {}
55
+ # @AI: Excluding a source disables its I/O, not merely its precedence.
56
+ if "dotenv" in source_order:
57
+ for path in env_files:
58
+ # Later explicitly listed files win; filesystem discovery is opt-in elsewhere.
59
+ dotenv.update(parse_env_file(path, strict=True))
60
+ if "config" not in source_order:
61
+ config = None
62
+ elif isinstance(config, (str, Path)):
63
+ with Path(config).open("rb") as file:
64
+ config = tomllib.load(file)
65
+ return ArgumentSources(
66
+ dict(os.environ if environ is None else environ) if "env" in source_order else {},
67
+ dotenv,
68
+ {} if config is None else config,
69
+ )
70
+
71
+
72
+ def _lookup_config(mapping: Mapping[str, Any], path: str) -> Any:
73
+ """Look up a dotted configuration key, preserving the missing-value sentinel."""
74
+ value: Any = mapping
75
+ for part in path.split("."):
76
+ if not isinstance(value, Mapping) or part not in value:
77
+ return MISSING
78
+ value = value[part]
79
+ return value
80
+
81
+
82
+ def _select_source(
83
+ spec: ArgumentSpec,
84
+ supplied: Mapping[str, Any],
85
+ sources: ArgumentSources,
86
+ source_order: tuple[str, ...],
87
+ ) -> tuple[Any, str]:
88
+ """Select the first present value according to the application's precedence."""
89
+ argument = spec.argument
90
+ # Explicit argv and declared defaults are fixed boundaries, not policy choices.
91
+ if spec.name in supplied:
92
+ return supplied[spec.name], "CLI"
93
+ for source in source_order[1:-1]:
94
+ # Membership rather than truthiness preserves explicit empty, false and zero values.
95
+ if source == "env" and argument.env is not None and argument.env in sources.environment:
96
+ return sources.environment[argument.env], "environment"
97
+ if source == "dotenv" and argument.env is not None and argument.env in sources.dotenv:
98
+ return sources.dotenv[argument.env], "env file"
99
+ if source == "config" and argument.config is not None:
100
+ candidate = _lookup_config(sources.config, argument.config)
101
+ if candidate is not MISSING:
102
+ return candidate, "config"
103
+ if argument.default is not MISSING:
104
+ return argument.default, "default"
105
+ return MISSING, "missing"
106
+
107
+
108
+ def _prompt_argument(spec: ArgumentSpec, value: Any, session: Session) -> Any:
109
+ """Read and validate an editable argument, preserving typed defaults on Enter."""
110
+ label = spec.label
111
+ if spec.argument.choices:
112
+ label += " (" + "/".join(map(str, spec.argument.choices)) + ")"
113
+ suffix = "" if value is MISSING else f" [{value}]"
114
+ while True:
115
+ text = read_prompt_input(session.input, session.output, f"{label}{suffix}: ")
116
+ # @AI: Enter preserves the validated typed value; converting its display text
117
+ # again could fail for custom converters or lose information.
118
+ if not text and value is not MISSING:
119
+ return value
120
+ try:
121
+ if not text:
122
+ raise ValueError("a value is required")
123
+ return spec.convert(text)
124
+ except (ValueError, TypeError) as exc:
125
+ session.print_message(
126
+ f"Invalid value: {exc}. Try again, or type q to cancel.", Tone.WARN
127
+ )
128
+
129
+
130
+ def resolve_arguments(
131
+ command: CommandSpec,
132
+ supplied: Mapping[str, Any],
133
+ sources: ArgumentSources,
134
+ session: Session,
135
+ *,
136
+ edit_existing: bool,
137
+ allow_prompt: bool = True,
138
+ source_order: tuple[str, ...] = DEFAULT_SOURCE_ORDER,
139
+ ) -> dict[str, Any]:
140
+ """Resolve and validate all arguments before invoking the handler.
141
+
142
+ Select the first present source, convert and validate once, then prompt
143
+ for missing or editable values when permitted. A failed conversion of
144
+ the winning source raises ResolutionError rather than falling through.
145
+ PromptInterruptError propagates to the navigation owner.
146
+ """
147
+ result = {}
148
+ for spec in command.arguments:
149
+ raw, source = _select_source(spec, supplied, sources, source_order)
150
+ value = MISSING
151
+ if raw is not MISSING:
152
+ try:
153
+ value = spec.convert(raw)
154
+ except (TypeError, ValueError) as exc:
155
+ # @AI: Invalid higher-priority configuration cannot silently fall through.
156
+ raise ResolutionError(f"{spec.cli_name} ({source}): {exc}") from exc
157
+ if (
158
+ allow_prompt
159
+ and spec.argument.prompt
160
+ and session.interactive
161
+ and (value is MISSING or edit_existing)
162
+ ):
163
+ value = _prompt_argument(spec, value, session)
164
+ if value is MISSING:
165
+ raise ResolutionError(f"missing required argument {spec.cli_name}")
166
+ result[spec.name] = value
167
+ return result
cells/cli/session.py ADDED
@@ -0,0 +1,185 @@
1
+ """A session is the sole owner of presentation input/output policy."""
2
+
3
+ import os
4
+ import sys
5
+ from collections.abc import Callable, Iterator, Mapping, Sequence
6
+ from contextlib import contextmanager
7
+ from typing import TextIO
8
+
9
+ from . import menu, prompt, render
10
+ from .banner import Banner, BannerPolicy, BannerStyle, EntryMode
11
+ from .errors import CANCELLED_EXIT_CODE, PromptFlow, PromptInterruptError, PromptUnavailableError
12
+ from .menu import MenuChoice, MenuSpec
13
+ from .style import ColorChoice, Tone, paint
14
+ from .text import strip_ansi
15
+
16
+
17
+ class Session:
18
+ """Own line-mode input, output, banner state and interactive presentation policy."""
19
+
20
+ def __init__(
21
+ self,
22
+ input: TextIO,
23
+ output: TextIO,
24
+ *,
25
+ color: ColorChoice = ColorChoice.AUTO,
26
+ banner: Banner | None = None,
27
+ banner_policy: BannerPolicy = BannerPolicy.AUTO,
28
+ width: int | None = None,
29
+ ):
30
+ """Bind explicit streams and presentation options without writing or reading."""
31
+ if width is not None and width < 1:
32
+ raise ValueError("width must be positive")
33
+ self.input, self.output = input, output
34
+ self.color_choice = color
35
+ self.banner, self.banner_policy = banner, banner_policy
36
+ self.width = width
37
+ self._banner_shown = False
38
+ self._prompts_enabled = True
39
+
40
+ @classmethod
41
+ def stdio(cls, **kwargs) -> "Session":
42
+ """Create a session bound to the process standard input and output."""
43
+ return cls(sys.stdin, sys.stdout, **kwargs)
44
+
45
+ @property
46
+ def interactive(self) -> bool:
47
+ """Return whether prompts are enabled and both streams are terminals."""
48
+ return self._prompts_enabled and self.input.isatty() and self.output.isatty()
49
+
50
+ @contextmanager
51
+ def without_prompts(self) -> Iterator[None]:
52
+ """Temporarily prohibit Session reads; restore the caller's policy on exit."""
53
+ previous = self._prompts_enabled
54
+ self._prompts_enabled = False
55
+ try:
56
+ yield
57
+ finally:
58
+ self._prompts_enabled = previous
59
+
60
+ def _require_prompt(self) -> None:
61
+ """Reject input before reading when the entry prohibits interaction."""
62
+ if not self._prompts_enabled:
63
+ raise PromptUnavailableError("interactive input is disabled for this entry")
64
+
65
+ @property
66
+ def color_enabled(self) -> bool:
67
+ """Resolve the effective color policy against the output stream."""
68
+ return self.color_choice.resolve(self.output)
69
+
70
+ def terminal_width(self) -> int:
71
+ """Return the configured or detected output width, falling back to 80 cells."""
72
+ if self.width is not None:
73
+ return self.width
74
+ try:
75
+ return max(1, os.get_terminal_size(self.output.fileno()).columns)
76
+ except (OSError, ValueError, AttributeError):
77
+ return 80
78
+
79
+ def show_banner(self, *, mode: EntryMode) -> bool:
80
+ """Application entry supplies intent. Machine/version output stays clean."""
81
+ if self.banner is None or self._banner_shown or self.banner_policy is BannerPolicy.NEVER:
82
+ return False
83
+ if mode in (EntryMode.MACHINE, EntryMode.VERSION):
84
+ return False
85
+ if self.banner_policy is BannerPolicy.AUTO and mode not in (
86
+ EntryMode.INTERACTIVE,
87
+ EntryMode.FALLBACK_HELP,
88
+ ):
89
+ return False
90
+ # @AI: Use the injected output; never use a hidden stdout channel.
91
+ # Noninteractive fallback help must remain readable without terminal styling.
92
+ plain = mode is EntryMode.FALLBACK_HELP or not self.output.isatty()
93
+ self.output.write(
94
+ self.banner.render(
95
+ color=self.color_enabled and not plain,
96
+ width=self.terminal_width(),
97
+ style=BannerStyle.PLAIN if plain else None,
98
+ )
99
+ + "\n"
100
+ )
101
+ self.output.flush()
102
+ self._banner_shown = True
103
+ return True
104
+
105
+ def ask_text(self, label: str, default: str | None = None) -> str:
106
+ """Read text through the session, with an optional default."""
107
+ self._require_prompt()
108
+ return prompt.ask_text(self.input, self.output, label, default)
109
+
110
+ def ask_yes_no(self, label: str, default_yes: bool = False) -> bool:
111
+ """Read a confirmation through the session's input and output streams."""
112
+ self._require_prompt()
113
+ return prompt.ask_yes_no(self.input, self.output, label, default_yes)
114
+
115
+ def select_one(self, label: str, items: Sequence[str]) -> str:
116
+ """Read one choice from the supplied items."""
117
+ self._require_prompt()
118
+ return prompt.select_one(self.input, self.output, label, items)
119
+
120
+ def ask_parsed[T](
121
+ self, label: str, parse: Callable[[str], T], *, default: str | None = None
122
+ ) -> T:
123
+ """Read and convert input, retrying user-correctable conversion failures."""
124
+ self._require_prompt()
125
+ return prompt.ask_parsed(self.input, self.output, label, parse, default=default)
126
+
127
+ def print_message(self, text: str, tone: Tone = Tone.INFO) -> None:
128
+ """Write a semantic message followed by a newline."""
129
+ color = self.color_enabled
130
+ self.output.write(paint(text if color else strip_ansi(text), tone, color=color) + "\n")
131
+
132
+ def print_section(self, title: str, detail: Sequence[str] = ()) -> None:
133
+ """Write a rendered section heading and optional detail lines."""
134
+ self.output.write(render.render_section(title, detail, color=self.color_enabled) + "\n")
135
+
136
+ def print_table(self, table: render.Table) -> None:
137
+ """Write a rendered table only when it contains data rows."""
138
+ if not table.is_empty():
139
+ self.output.write(table.render(color=self.color_enabled) + "\n")
140
+
141
+ def print_kv_rows(self, rows: Sequence[render.KvRow]) -> None:
142
+ """Write aligned key/value rows when the sequence is nonempty."""
143
+ if rows:
144
+ self.output.write(render.render_kv_rows(rows, color=self.color_enabled) + "\n")
145
+
146
+ def render_status(self, text: str, mapping: Mapping[str, Tone] | None = None) -> str:
147
+ """Return status text styled according to the session's effective color policy."""
148
+ return render.render_status(text, mapping, color=self.color_enabled)
149
+
150
+ def run_menu(self, spec: MenuSpec) -> MenuChoice:
151
+ """Read one menu choice, without invoking a command handler."""
152
+ self._require_prompt()
153
+ return menu.run_menu(spec, self.input, self.output, color=self.color_enabled)
154
+
155
+ def run_menu_loop(self, spec: MenuSpec, action: Callable[[str, "Session"], None]) -> PromptFlow:
156
+ """Dispatch menu selections until the user navigates out of the menu.
157
+
158
+ BACK from an action returns to this menu; QUIT_ALL unwinds the session.
159
+ Other handler exceptions propagate to the caller.
160
+ """
161
+ while True:
162
+ choice = self.run_menu(spec)
163
+ if choice.flow is not None:
164
+ return choice.flow
165
+ assert choice.key is not None
166
+ item = next(item for item in spec.items if item.key == choice.key)
167
+ self.print_section(
168
+ f"{spec.title} / {item.label}", (item.description,) if item.description else ()
169
+ )
170
+ try:
171
+ action(choice.key, self)
172
+ # BACK returns to the owning menu; QUIT_ALL unwinds the session.
173
+ except PromptInterruptError as interrupt:
174
+ if interrupt.flow is PromptFlow.QUIT_ALL:
175
+ return interrupt.flow
176
+ self.print_message("Action cancelled; returned to this menu.", Tone.MUTED)
177
+
178
+
179
+ def run_action(action: Callable[[], None]) -> int:
180
+ """Return a shell status for a standalone action without hiding handler failures."""
181
+ try:
182
+ action()
183
+ except PromptInterruptError:
184
+ return CANCELLED_EXIT_CODE
185
+ return 0
cells/cli/style.py ADDED
@@ -0,0 +1,46 @@
1
+ """Semantic styling and output-stream-aware color resolution."""
2
+
3
+ import os
4
+ from collections.abc import Mapping
5
+ from enum import StrEnum
6
+ from typing import TextIO
7
+
8
+
9
+ class Tone(StrEnum):
10
+ """Map semantic message categories to terminal ANSI color codes."""
11
+
12
+ INFO = "36"
13
+ GOOD = "32"
14
+ WARN = "33"
15
+ BAD = "31"
16
+ ACCENT = "35"
17
+ MUTED = "90"
18
+
19
+
20
+ class ColorChoice(StrEnum):
21
+ """Select automatic, forced or disabled terminal color."""
22
+
23
+ AUTO = "auto"
24
+ ALWAYS = "always"
25
+ NEVER = "never"
26
+
27
+ def resolve(self, output: TextIO, env: Mapping[str, str] | None = None) -> bool:
28
+ """Determine whether color is enabled for the output stream and environment."""
29
+ if self is ColorChoice.ALWAYS:
30
+ return True
31
+ if self is ColorChoice.NEVER:
32
+ return False
33
+ # Explicit color policy wins; NO_COLOR takes precedence only in AUTO mode.
34
+ env = os.environ if env is None else env
35
+ if "NO_COLOR" in env:
36
+ return False
37
+ if "CLICOLOR_FORCE" in env and env["CLICOLOR_FORCE"] != "0":
38
+ return True
39
+ return output.isatty() and env.get("TERM") != "dumb"
40
+
41
+
42
+ def paint(value: str, tone: Tone, *, bold: bool = False, color: bool = False) -> str:
43
+ """Wrap text in ANSI styling only when color is enabled."""
44
+ if not color:
45
+ return value
46
+ return f"\x1b[{'1;' if bold else ''}{tone.value}m{value}\x1b[0m"
cells/cli/text.py ADDED
@@ -0,0 +1,136 @@
1
+ """Terminal cell geometry. Layout operations return unstyled text."""
2
+
3
+ import re
4
+ import unicodedata
5
+
6
+ import regex
7
+
8
+
9
+ # Strip CSI, OSC (including hyperlinks), DCS/SOS/PM/APC and simple ESC codes.
10
+ _ANSI = re.compile(
11
+ r"\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[P^_X][^\x1b]*\x1b\\|\x1b[ -/]*[@-Z\\-_]"
12
+ )
13
+ _GRAPHEME = regex.compile(r"\X")
14
+ _EMOJI_PRESENTATION = regex.compile(r"\p{Emoji_Presentation}")
15
+ _EMOJI = regex.compile(r"\p{Emoji}")
16
+
17
+
18
+ def strip_ansi(value: str) -> str:
19
+ """Remove supported ANSI escape sequences without altering ordinary text."""
20
+ # Most terminal text has no escape sequences; avoid the regex engine in that case.
21
+ return _ANSI.sub("", value) if "\x1b" in value else value
22
+
23
+
24
+ def graphemes(value: str) -> list[str]:
25
+ """Split text into Unicode extended grapheme clusters."""
26
+ return _GRAPHEME.findall(value)
27
+
28
+
29
+ def _character_width(character: str) -> int:
30
+ """Estimate the cell width of a single Unicode code point."""
31
+ category = unicodedata.category(character)
32
+ if category.startswith("M") or category in ("Cc", "Cf", "Cs", "Zl", "Zp"):
33
+ return 0
34
+ codepoint = ord(character)
35
+ # Hangul medial and trailing Jamo join the leading consonant's cell.
36
+ if 0x1160 <= codepoint <= 0x11FF or 0xD7B0 <= codepoint <= 0xD7FF:
37
+ return 0
38
+ if category == "Cn":
39
+ return 1
40
+ return 2 if unicodedata.east_asian_width(character) in ("W", "F") else 1
41
+
42
+
43
+ def _cell_width(grapheme: str) -> int:
44
+ """Estimate the cell width of an intact grapheme cluster."""
45
+ if grapheme.isascii() and grapheme.isprintable():
46
+ return len(grapheme)
47
+ # @AI: A joined emoji, flag or keycap is typically one two-cell glyph.
48
+ # East Asian Width alone cannot describe these multi-codepoint sequences.
49
+ if "\ufe0e" not in grapheme and (
50
+ _EMOJI_PRESENTATION.search(grapheme)
51
+ or ("\ufe0f" in grapheme and _EMOJI.search(grapheme))
52
+ or (grapheme.endswith("\u20e3") and grapheme[0] in "#*0123456789")
53
+ ):
54
+ return 2
55
+ if len(grapheme) == 1:
56
+ return _character_width(grapheme)
57
+ return sum(map(_character_width, grapheme))
58
+
59
+
60
+ def display_width(value: str) -> int:
61
+ """Estimate terminal cells using Unicode properties and intact grapheme clusters."""
62
+ plain = strip_ansi(value)
63
+ if plain.isascii():
64
+ # Printable ASCII occupies exactly one cell per character, including spaces.
65
+ if plain.isprintable():
66
+ return len(plain)
67
+ return sum(" " <= character <= "~" for character in plain)
68
+ return sum(map(_cell_width, graphemes(plain)))
69
+
70
+
71
+ def pad_to_width(value: str, width: int) -> str:
72
+ """Right-pad text to the requested cell width without truncating it."""
73
+ return value + " " * max(0, width - display_width(value))
74
+
75
+
76
+ def truncate_middle(value: str, max_width: int) -> str:
77
+ """Fit text to a cell budget without splitting graphemes, using a middle ellipsis when possible."""
78
+ if max_width < 0:
79
+ raise ValueError("max_width must be nonnegative")
80
+ value = strip_ansi(value)
81
+ if display_width(value) <= max_width:
82
+ return value
83
+ if max_width == 0:
84
+ return ""
85
+ units = graphemes(value)
86
+
87
+ def prefix(parts: list[str], budget: int) -> list[str]:
88
+ result = []
89
+ for part in parts:
90
+ width = _cell_width(part)
91
+ if width > budget:
92
+ break
93
+ result.append(part)
94
+ budget -= width
95
+ return result
96
+
97
+ if max_width < 4:
98
+ return "".join(prefix(units, max_width))
99
+ left = (max_width - 1) // 2
100
+ start = prefix(units, left)
101
+ end = prefix(list(reversed(units[len(start) :])), max_width - 1 - left)
102
+ return "".join(start) + "…" + "".join(reversed(end))
103
+
104
+
105
+ def wrap_text(text: str, max_width: int) -> list[str]:
106
+ """Prefer word breaks, then grapheme breaks. An oversized glyph stands alone."""
107
+ if max_width < 1:
108
+ raise ValueError("max_width must be positive")
109
+ lines: list[str] = []
110
+ for paragraph in strip_ansi(text).split("\n"):
111
+ units = graphemes(paragraph)
112
+ current: list[str] = []
113
+ width = 0
114
+ for unit in units:
115
+ if unit == " " and not current:
116
+ continue
117
+ size = _cell_width(unit)
118
+ if width + size > max_width and current:
119
+ if unit == " ":
120
+ lines.append("".join(current).rstrip(" "))
121
+ current, width = [], 0
122
+ continue
123
+ boundary = next(
124
+ (i for i in range(len(current) - 1, -1, -1) if current[i] == " "), -1
125
+ )
126
+ if boundary > 0:
127
+ lines.append("".join(current[:boundary]).rstrip(" "))
128
+ current = current[boundary + 1 :]
129
+ width = sum(map(_cell_width, current))
130
+ if current and width + size > max_width:
131
+ lines.append("".join(current).rstrip(" "))
132
+ current, width = [], 0
133
+ current.append(unit)
134
+ width += size
135
+ lines.append("".join(current).rstrip(" "))
136
+ return lines
cells/cli/version.py ADDED
@@ -0,0 +1,3 @@
1
+ """Release version for cells-cli."""
2
+
3
+ __version__ = "0.2.1"