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 ADDED
@@ -0,0 +1,65 @@
1
+ """Public presentation, command declaration and configuration APIs."""
2
+
3
+ from .banner import Banner, BannerPolicy, BannerStyle, EntryMode
4
+ from .command import Argument, ArgumentSpec, CommandSpec
5
+ from .converters import format_human_int, parse_bool, parse_human_int, parse_human_int_or_default
6
+ from .env import (
7
+ find_env_files,
8
+ get_env,
9
+ is_env_true,
10
+ load_env_file,
11
+ load_env_files,
12
+ parse_env_file,
13
+ )
14
+ from .errors import PromptFlow, PromptInterruptError, PromptUnavailableError, ValidationError
15
+ from .menu import MenuChoice, MenuItem, MenuSpec
16
+ from .render import KvRow, Table, kv, render_kv_rows, render_status, render_yes_no
17
+ from .session import Session, run_action
18
+ from .style import ColorChoice, Tone
19
+ from .text import display_width, pad_to_width, strip_ansi, truncate_middle, wrap_text
20
+ from .version import __version__
21
+
22
+
23
+ # @AI: App is intentionally not imported here; presentation must not load argparse.
24
+ __all__ = [
25
+ "Banner",
26
+ "BannerPolicy",
27
+ "BannerStyle",
28
+ "EntryMode",
29
+ "ColorChoice",
30
+ "Tone",
31
+ "PromptFlow",
32
+ "PromptInterruptError",
33
+ "PromptUnavailableError",
34
+ "ValidationError",
35
+ "MenuChoice",
36
+ "MenuItem",
37
+ "MenuSpec",
38
+ "KvRow",
39
+ "Table",
40
+ "kv",
41
+ "render_kv_rows",
42
+ "render_status",
43
+ "render_yes_no",
44
+ "Session",
45
+ "run_action",
46
+ "display_width",
47
+ "pad_to_width",
48
+ "strip_ansi",
49
+ "truncate_middle",
50
+ "wrap_text",
51
+ "Argument",
52
+ "ArgumentSpec",
53
+ "CommandSpec",
54
+ "get_env",
55
+ "is_env_true",
56
+ "parse_human_int_or_default",
57
+ "parse_env_file",
58
+ "load_env_file",
59
+ "find_env_files",
60
+ "load_env_files",
61
+ "parse_bool",
62
+ "parse_human_int",
63
+ "format_human_int",
64
+ "__version__",
65
+ ]
cells/cli/app.py ADDED
@@ -0,0 +1,336 @@
1
+ """Optional command application layer over the standalone presentation API."""
2
+
3
+ import asyncio
4
+ import inspect
5
+ import re
6
+ import sys
7
+ from collections.abc import Callable, Mapping, Sequence
8
+ from contextlib import ExitStack, nullcontext
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+ from typing import Any, TextIO
12
+
13
+ from .banner import Banner, BannerPolicy, EntryMode
14
+ from .command import CommandSpec, build_command
15
+ from .errors import CANCELLED_EXIT_CODE, PromptInterruptError, PromptUnavailableError
16
+ from .menu import MenuItem, MenuSpec
17
+ from .parser import ParserExitError, build_parser
18
+ from .resolver import (
19
+ DEFAULT_SOURCE_ORDER,
20
+ ArgumentSources,
21
+ ResolutionError,
22
+ load_argument_sources,
23
+ resolve_arguments,
24
+ validate_source_order,
25
+ )
26
+ from .session import Session
27
+ from .style import ColorChoice, Tone
28
+
29
+
30
+ @dataclass(slots=True)
31
+ class _Invocation:
32
+ """Carry one parsed entry and its loaded argument sources."""
33
+
34
+ command: CommandSpec | None
35
+ values: dict[str, Any]
36
+ sources: ArgumentSources
37
+ prog: str
38
+
39
+
40
+ async def _await_result(result: Any) -> Any:
41
+ """Adapt an awaitable to the coroutine interface required by Python 3.13 Runner."""
42
+ # Runner.run in Python 3.13 requires a coroutine, not an arbitrary awaitable.
43
+ return await result
44
+
45
+
46
+ def _exit_code(result: Any) -> int:
47
+ """Validate the handler result and normalize None to successful exit."""
48
+ if result is None:
49
+ return 0
50
+ if type(result) is int:
51
+ return result
52
+ raise TypeError("command handler must return None or an integer exit code")
53
+
54
+
55
+ class App:
56
+ """Register commands and coordinate parsing, configuration, presentation and execution."""
57
+
58
+ def __init__(
59
+ self,
60
+ name: str,
61
+ *,
62
+ version: str = "",
63
+ description: str = "",
64
+ banner: Banner | None = None,
65
+ banner_policy: BannerPolicy = BannerPolicy.AUTO,
66
+ env_files: Sequence[str | Path] = (),
67
+ config: Mapping[str, Any] | str | Path | None = None,
68
+ source_order: tuple[str, ...] = DEFAULT_SOURCE_ORDER,
69
+ ):
70
+ """Configure application identity and deployment sources without I/O.
71
+
72
+ Args:
73
+ name: Application name used in help and diagnostics.
74
+ version: Version displayed by the version option.
75
+ description: Application help text.
76
+ banner: Optional application identity to render.
77
+ banner_policy: Controls when the banner is shown.
78
+ env_files: Explicit dotenv paths, in increasing precedence.
79
+ config: Configuration mapping or TOML file path.
80
+ source_order: Source precedence with CLI first and default last.
81
+
82
+ Raises:
83
+ ValueError: The source order is invalid.
84
+ TypeError: The source order is not a tuple.
85
+ """
86
+ self.name, self.version, self.description = name, version, description
87
+ self.banner, self.banner_policy = banner, banner_policy
88
+ self.env_files, self.config = tuple(env_files), config
89
+ # @Human: Deployment precedence belongs to the application, not individual arguments.
90
+ self._source_order = validate_source_order(source_order)
91
+ self._commands: dict[str, CommandSpec] = {}
92
+
93
+ @property
94
+ def source_order(self) -> tuple[str, ...]:
95
+ """Configured source precedence, from highest to lowest."""
96
+ return self._source_order
97
+
98
+ def command(self, name: str | None = None, *, description: str = ""):
99
+ """Register one handler for both argv dispatch and interactive navigation."""
100
+
101
+ def register(handler: Callable[..., Any]):
102
+ key = name or handler.__name__.replace("_", "-")
103
+ if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]*(?: [A-Za-z0-9][A-Za-z0-9_-]*)*", key):
104
+ raise ValueError(f"invalid command name: {key}")
105
+ if any(
106
+ key == existing or key.startswith(existing + " ") or existing.startswith(key + " ")
107
+ for existing in self._commands
108
+ ):
109
+ raise ValueError(f"duplicate or overlapping command: {key}")
110
+ spec = build_command(key, description or (handler.__doc__ or "").strip(), handler)
111
+ # Fail at declaration time if the menu cannot represent the command.
112
+ MenuSpec(
113
+ self.name,
114
+ tuple(MenuItem(str(i), c, c) for i, c in enumerate((*self._commands, key), 1)),
115
+ )
116
+ self._commands[key] = spec
117
+ return handler
118
+
119
+ return register
120
+
121
+ def _call_handler(self, command: CommandSpec, values: dict[str, Any], session: Session) -> Any:
122
+ """Inject the session when declared and invoke the original handler."""
123
+ if command.takes_session:
124
+ values["session"] = session
125
+ # Handler exceptions are not parser failures; preserve application semantics.
126
+ return command.handler(**values)
127
+
128
+ def _prepare(
129
+ self,
130
+ argv: Sequence[str] | None,
131
+ session: Session,
132
+ environ: Mapping[str, str] | None,
133
+ error_output: TextIO,
134
+ *,
135
+ machine: bool,
136
+ ) -> _Invocation | int:
137
+ """Parse argv and load enabled sources only for executable entries."""
138
+ argv = list(sys.argv[1:] if argv is None else argv)
139
+ if machine:
140
+ session.color_choice = ColorChoice.NEVER
141
+ parser = build_parser(
142
+ self.name,
143
+ self.description,
144
+ self.version,
145
+ tuple(self._commands.values()),
146
+ session.output,
147
+ error_output,
148
+ )
149
+ try:
150
+ values = vars(parser.parse_args(argv))
151
+ except ParserExitError as exc:
152
+ return exc.status
153
+ active = values.pop("_active_parser")
154
+ key = values.pop("_command", None)
155
+ if "color" in values:
156
+ choice = ColorChoice(values.pop("color"))
157
+ if not machine:
158
+ session.color_choice = choice
159
+ if key is None and (active is not parser or not session.interactive or not self._commands):
160
+ if active is parser and not machine:
161
+ session.show_banner(mode=EntryMode.FALLBACK_HELP)
162
+ active.print_help()
163
+ return 0
164
+ # Help and version remain usable even with broken configuration files.
165
+ try:
166
+ sources = load_argument_sources(
167
+ self.env_files, self.config, environ, source_order=self.source_order
168
+ )
169
+ except (OSError, ValueError) as exc:
170
+ error_output.write(f"{self.name}: configuration error: {exc}\n")
171
+ return 2
172
+ return _Invocation(self._commands.get(key), values, sources, active.prog)
173
+
174
+ def _resolve_direct(
175
+ self, invocation: _Invocation, session: Session, error_output: TextIO, *, machine: bool
176
+ ) -> dict[str, Any] | int:
177
+ """Resolve direct command values or return a user-facing failure status."""
178
+ assert invocation.command is not None
179
+ try:
180
+ resolved = resolve_arguments(
181
+ invocation.command,
182
+ invocation.values,
183
+ invocation.sources,
184
+ session,
185
+ edit_existing=False,
186
+ source_order=self.source_order,
187
+ )
188
+ except ResolutionError as exc:
189
+ error_output.write(f"{invocation.prog}: error: {exc}\n")
190
+ return 2
191
+ except PromptInterruptError:
192
+ return CANCELLED_EXIT_CODE
193
+ session.show_banner(mode=EntryMode.MACHINE if machine else EntryMode.DIRECT)
194
+ return resolved
195
+
196
+ def run(
197
+ self,
198
+ argv: Sequence[str] | None = None,
199
+ *,
200
+ session: Session | None = None,
201
+ environ: Mapping[str, str] | None = None,
202
+ error_output: TextIO | None = None,
203
+ machine: bool = False,
204
+ ) -> int:
205
+ """Run sync or async commands at a CLI-owned entry point.
206
+
207
+ Args:
208
+ argv: Arguments excluding the executable; None uses process argv.
209
+ session: Optional presentation session with caller-provided streams.
210
+ environ: Environment mapping; None uses the process environment.
211
+ error_output: Diagnostic stream; None uses stderr.
212
+ machine: Disable Session prompts, banners and library color.
213
+
214
+ Returns:
215
+ The handler's exit status, 0 for success, 2 for input errors,
216
+ or 130 for direct command cancellation.
217
+
218
+ Raises:
219
+ RuntimeError: An event loop is already running in this thread.
220
+
221
+ Handler failures and external cancellation propagate.
222
+ """
223
+ try:
224
+ asyncio.get_running_loop()
225
+ except RuntimeError:
226
+ pass
227
+ else:
228
+ raise RuntimeError("App.run() cannot run inside an event loop; await App.run_async()")
229
+ session = (
230
+ session
231
+ if session is not None
232
+ else Session.stdio(banner=self.banner, banner_policy=self.banner_policy)
233
+ )
234
+ error_output = sys.stderr if error_output is None else error_output
235
+ # @AI: One lazy Runner owns the entire CLI visit. Sync handlers remain on the
236
+ # calling thread outside the event loop; async menu actions reuse one loop.
237
+ with ExitStack() as stack, session.without_prompts() if machine else nullcontext():
238
+ runner: asyncio.Runner | None = None
239
+ invocation = self._prepare(argv, session, environ, error_output, machine=machine)
240
+ if isinstance(invocation, int):
241
+ return invocation
242
+
243
+ def invoke(command: CommandSpec, values: dict[str, Any]) -> int:
244
+ nonlocal runner
245
+ result = self._call_handler(command, values, session)
246
+ if inspect.isawaitable(result):
247
+ if runner is None:
248
+ runner = stack.enter_context(asyncio.Runner())
249
+ result = runner.run(_await_result(result))
250
+ return _exit_code(result)
251
+
252
+ if invocation.command is not None:
253
+ resolved = self._resolve_direct(invocation, session, error_output, machine=machine)
254
+ if isinstance(resolved, int):
255
+ return resolved
256
+ try:
257
+ return invoke(invocation.command, resolved)
258
+ except PromptInterruptError:
259
+ return CANCELLED_EXIT_CODE
260
+ except PromptUnavailableError as exc:
261
+ error_output.write(f"{invocation.prog}: error: {exc}\n")
262
+ return 2
263
+
264
+ session.show_banner(mode=EntryMode.INTERACTIVE)
265
+ menu = MenuSpec(
266
+ self.name,
267
+ tuple(
268
+ MenuItem(str(i), c.name, c.name, c.description)
269
+ for i, c in enumerate(self._commands.values(), 1)
270
+ ),
271
+ q_label="exit",
272
+ )
273
+
274
+ def action(key: str, current: Session):
275
+ try:
276
+ resolved = resolve_arguments(
277
+ self._commands[key],
278
+ {},
279
+ invocation.sources,
280
+ current,
281
+ edit_existing=True,
282
+ source_order=self.source_order,
283
+ )
284
+ except ResolutionError as exc:
285
+ current.print_message(str(exc), Tone.BAD)
286
+ return
287
+ code = invoke(self._commands[key], resolved)
288
+ if code:
289
+ current.print_message(f"Command exited with status {code}.", Tone.WARN)
290
+
291
+ session.run_menu_loop(menu, action)
292
+ return 0
293
+
294
+ async def run_async(
295
+ self,
296
+ argv: Sequence[str] | None = None,
297
+ *,
298
+ session: Session | None = None,
299
+ environ: Mapping[str, str] | None = None,
300
+ error_output: TextIO | None = None,
301
+ machine: bool = True,
302
+ ) -> int:
303
+ """Run a noninteractive command in the caller's existing event loop.
304
+
305
+ Accepts the same arguments and returns the same status as run, with
306
+ machine output enabled by default. Never creates or closes the host
307
+ loop. Session prompts are disabled even when machine is False.
308
+ Synchronous handlers and configuration reads remain blocking.
309
+ Handler failures and cancellation propagate.
310
+ """
311
+ session = (
312
+ session
313
+ if session is not None
314
+ else Session.stdio(banner=self.banner, banner_policy=self.banner_policy)
315
+ )
316
+ error_output = sys.stderr if error_output is None else error_output
317
+ # @AI: Never move terminal reads to an uncancellable worker thread or block
318
+ # a host loop on an interactive menu. The caller owns the loop and its tasks.
319
+ with session.without_prompts():
320
+ invocation = self._prepare(argv, session, environ, error_output, machine=machine)
321
+ if isinstance(invocation, int):
322
+ return invocation
323
+ assert invocation.command is not None
324
+ resolved = self._resolve_direct(invocation, session, error_output, machine=machine)
325
+ if isinstance(resolved, int):
326
+ return resolved
327
+ try:
328
+ result = self._call_handler(invocation.command, resolved, session)
329
+ if inspect.isawaitable(result):
330
+ result = await result
331
+ return _exit_code(result)
332
+ except PromptInterruptError:
333
+ return CANCELLED_EXIT_CODE
334
+ except PromptUnavailableError as exc:
335
+ error_output.write(f"{invocation.prog}: error: {exc}\n")
336
+ return 2
cells/cli/banner.py ADDED
@@ -0,0 +1,117 @@
1
+ """Application identity; rendering is pure and policy is separate."""
2
+
3
+ from collections.abc import Mapping
4
+ from dataclasses import dataclass, field
5
+ from enum import StrEnum
6
+ from types import MappingProxyType
7
+
8
+ from .style import Tone, paint
9
+ from .text import display_width, pad_to_width, strip_ansi, wrap_text
10
+
11
+
12
+ class BannerStyle(StrEnum):
13
+ """Select the visual layout of an application banner."""
14
+
15
+ PLAIN = "plain"
16
+ COMPACT = "compact"
17
+ BLOCK = "block"
18
+ CUSTOM = "custom"
19
+
20
+
21
+ class BannerPolicy(StrEnum):
22
+ """Control when a session may display its banner."""
23
+
24
+ AUTO = "auto"
25
+ ALWAYS = "always"
26
+ NEVER = "never"
27
+
28
+
29
+ class EntryMode(StrEnum):
30
+ """Describe the entry intent for presentation policy decisions."""
31
+
32
+ INTERACTIVE = "interactive"
33
+ FALLBACK_HELP = "fallback_help"
34
+ DIRECT = "direct"
35
+ HELP = "help"
36
+ VERSION = "version"
37
+ MACHINE = "machine"
38
+
39
+
40
+ @dataclass(frozen=True, slots=True)
41
+ class Banner:
42
+ """Describe immutable application identity and optional custom artwork."""
43
+
44
+ title: str
45
+ subtitle: str = ""
46
+ version: str = ""
47
+ author: str = ""
48
+ description: str = ""
49
+ style: BannerStyle = BannerStyle.COMPACT
50
+ tone: Tone = Tone.ACCENT
51
+ artwork: str | None = None
52
+ metadata: Mapping[str, str] = field(default_factory=dict)
53
+
54
+ def __post_init__(self) -> None:
55
+ """Validate banner identity and detach metadata from the caller's mapping."""
56
+ if not self.title.strip():
57
+ raise ValueError("Banner title is required")
58
+ # Copy the caller's mapping so a frozen banner cannot change through an alias.
59
+ object.__setattr__(self, "metadata", MappingProxyType(dict(self.metadata)))
60
+ if self.style is BannerStyle.CUSTOM and not self.artwork:
61
+ raise ValueError("Custom banner requires artwork")
62
+
63
+ def render(
64
+ self, *, color: bool = False, width: int = 80, style: BannerStyle | None = None
65
+ ) -> str:
66
+ """Render the banner within the requested cell width without writing to a stream."""
67
+ if width < 1:
68
+ raise ValueError("width must be positive")
69
+ style = self.style if style is None else style
70
+ title = self.title + (f" v{self.version.removeprefix('v')}" if self.version else "")
71
+ # @AI: Apply style only after measuring plain grapheme clusters.
72
+ details = [
73
+ self.subtitle,
74
+ self.description,
75
+ self.author,
76
+ *(f"{key}: {value}" for key, value in self.metadata.items()),
77
+ ]
78
+ raw = [strip_ansi(v) for v in [title, *details] if v]
79
+ if style is BannerStyle.PLAIN or width < 8:
80
+ return "\n".join(part for line in raw for part in wrap_text(line, width))
81
+ if style is BannerStyle.CUSTOM:
82
+ artwork = strip_ansi(self.artwork or "").splitlines()
83
+ if artwork and max(map(display_width, artwork)) <= width:
84
+ return "\n".join(
85
+ [
86
+ *(paint(line, self.tone, color=color) for line in artwork),
87
+ *(part for line in raw for part in wrap_text(line, width)),
88
+ ]
89
+ )
90
+ # Custom artwork is indivisible; fall back rather than distort its layout.
91
+ style = BannerStyle.COMPACT
92
+ if style is BannerStyle.COMPACT:
93
+ lines = [part for line in raw for part in wrap_text(line, width - 2)]
94
+ return "\n".join(
95
+ paint("│", self.tone, color=color)
96
+ + " "
97
+ + (paint(line, self.tone, bold=True, color=color) if i == 0 else line)
98
+ for i, line in enumerate(lines)
99
+ )
100
+ lines = [part for line in raw for part in wrap_text(line, width - 4)]
101
+ inner = max(map(display_width, lines), default=0)
102
+ return "\n".join(
103
+ [
104
+ "┌" + "─" * (inner + 2) + "┐",
105
+ *(
106
+ "│ "
107
+ + (
108
+ paint(pad_to_width(line, inner), self.tone, bold=True, color=color)
109
+ if i == 0
110
+ else pad_to_width(line, inner)
111
+ )
112
+ + " │"
113
+ for i, line in enumerate(lines)
114
+ ),
115
+ "└" + "─" * (inner + 2) + "┘",
116
+ ]
117
+ )
cells/cli/command.py ADDED
@@ -0,0 +1,147 @@
1
+ """The single source of truth for CLI arguments, prompts and help."""
2
+
3
+ import inspect
4
+ from collections.abc import Callable
5
+ from dataclasses import dataclass, replace
6
+ from enum import Enum
7
+ from typing import Annotated, Any, get_args, get_origin, get_type_hints
8
+
9
+ from .converters import parse_bool
10
+ from .session import Session
11
+
12
+
13
+ class _Missing(Enum):
14
+ """Distinguish an absent declaration from explicit values including None."""
15
+
16
+ VALUE = "missing"
17
+
18
+
19
+ MISSING = _Missing.VALUE
20
+
21
+
22
+ @dataclass(frozen=True, slots=True)
23
+ class Argument:
24
+ """Declare an argument's sources, conversion, validation and prompt settings."""
25
+
26
+ default: Any = MISSING
27
+ help: str = ""
28
+ short: str | None = None
29
+ positional: bool = False
30
+ env: str | None = None
31
+ config: str | None = None
32
+ parse: Callable[[Any], Any] | None = None
33
+ validate: Callable[[Any], None] | None = None
34
+ prompt: bool = True
35
+ label: str | None = None
36
+ choices: tuple[Any, ...] = ()
37
+
38
+
39
+ @dataclass(frozen=True, slots=True)
40
+ class ArgumentSpec:
41
+ """Bind a handler parameter to its argument declaration and CLI spelling."""
42
+
43
+ name: str
44
+ annotation: Any
45
+ argument: Argument
46
+
47
+ @property
48
+ def cli_name(self) -> str:
49
+ """Return the positional name or long option spelling used in CLI diagnostics."""
50
+ return self.name if self.argument.positional else "--" + self.name.replace("_", "-")
51
+
52
+ @property
53
+ def label(self) -> str:
54
+ """Return the explicit prompt label or derive one from the parameter name."""
55
+ return self.argument.label or self.name.replace("_", " ").capitalize()
56
+
57
+ def convert(self, raw: Any) -> Any:
58
+ """Apply the same conversion and validation to every parameter source.
59
+
60
+ Explicit converters take priority over built-in scalar conversion.
61
+ Choices and custom validation operate on the converted value.
62
+ Conversion and validation failures propagate to the caller.
63
+ """
64
+ parser = self.argument.parse
65
+ if parser is not None:
66
+ value = parser(raw)
67
+ elif self.annotation is bool:
68
+ value = parse_bool(raw)
69
+ elif self.annotation is int:
70
+ if isinstance(raw, bool) or not isinstance(raw, (str, int)):
71
+ raise ValueError("expected an integer")
72
+ value = int(raw)
73
+ elif self.annotation is float:
74
+ if isinstance(raw, bool) or not isinstance(raw, (str, int, float)):
75
+ raise ValueError("expected a number")
76
+ value = float(raw)
77
+ elif self.annotation is str:
78
+ if not isinstance(raw, str):
79
+ raise ValueError("expected text")
80
+ value = raw
81
+ else:
82
+ value = self.annotation(raw)
83
+ if self.argument.choices and value not in self.argument.choices:
84
+ raise ValueError("expected one of: " + ", ".join(map(str, self.argument.choices)))
85
+ if self.argument.validate is not None:
86
+ self.argument.validate(value)
87
+ return value
88
+
89
+
90
+ @dataclass(frozen=True, slots=True)
91
+ class CommandSpec:
92
+ """Describe a registered handler and its resolved parameter declarations."""
93
+
94
+ name: str
95
+ description: str
96
+ handler: Callable[..., Any]
97
+ arguments: tuple[ArgumentSpec, ...]
98
+ takes_session: bool = False
99
+
100
+
101
+ def build_command(name: str, description: str, handler: Callable[..., Any]) -> CommandSpec:
102
+ """Inspect a handler once to build its command specification and validate declarations."""
103
+ # Resolve annotations once at registration; parser and prompt share this declaration.
104
+ hints = get_type_hints(handler, include_extras=True)
105
+ args = []
106
+ takes_session = False
107
+ for param in inspect.signature(handler).parameters.values():
108
+ if param.kind not in (param.POSITIONAL_OR_KEYWORD, param.KEYWORD_ONLY):
109
+ raise TypeError("command parameters must accept keyword arguments")
110
+ annotation = hints.get(param.name, str)
111
+ if param.name == "session" and annotation is Session:
112
+ takes_session = True
113
+ continue
114
+ if param.name.startswith("_"):
115
+ raise ValueError("command parameter names may not start with underscore")
116
+ default = param.default
117
+ if get_origin(annotation) is Annotated:
118
+ annotation, *metadata = get_args(annotation)
119
+ specs = [item for item in metadata if isinstance(item, Argument)]
120
+ if len(specs) != 1 or isinstance(default, Argument):
121
+ raise TypeError("use exactly one Argument declaration")
122
+ argument = specs[0]
123
+ if default is not inspect.Parameter.empty:
124
+ if argument.default is not MISSING:
125
+ raise TypeError("default declared twice")
126
+ argument = replace(argument, default=default)
127
+ else:
128
+ argument = (
129
+ default
130
+ if isinstance(default, Argument)
131
+ else Argument(default=MISSING if default is inspect.Parameter.empty else default)
132
+ )
133
+ if argument.parse is None and annotation not in (str, int, float, bool):
134
+ raise TypeError(f"{param.name}: supply an explicit converter for this annotation")
135
+ if argument.short is not None and (
136
+ argument.positional
137
+ or len(argument.short) != 2
138
+ or not argument.short.startswith("-")
139
+ or argument.short == "--"
140
+ ):
141
+ raise ValueError(f"{param.name}: invalid short option")
142
+ if argument.positional and annotation is bool:
143
+ raise ValueError("boolean positional arguments are not supported")
144
+ if param.name in ("help", "version", "color"):
145
+ raise ValueError(f"{param.name}: reserved application option")
146
+ args.append(ArgumentSpec(param.name, annotation, argument))
147
+ return CommandSpec(name, description, handler, tuple(args), takes_session)