cli-interview-kit 0.1.0__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,61 @@
1
+ """Build command-line apps whose prompts are declared once.
2
+
3
+ Declare each command as a ``Command``: its plain options, an ``Interview``
4
+ of questions and consents, and a run function. Hand the commands to an
5
+ ``App``, which derives the flags, the terminal interview, the behaviour
6
+ when nobody can be asked, and the ``--questions`` document an AI assistant
7
+ interviews a user from.
8
+
9
+ Everything public is importable from this package; the modules whose names
10
+ start with an underscore are internal.
11
+ """
12
+
13
+ from importlib.metadata import version as _version
14
+
15
+ from cli_interview_kit._prompts import parse_kv
16
+ from cli_interview_kit.app import App
17
+ from cli_interview_kit.command import Command, Invocation, Option
18
+ from cli_interview_kit.console import Console
19
+ from cli_interview_kit.errors import CliError, DeclarationError
20
+ from cli_interview_kit.interaction import Consent, Interaction
21
+ from cli_interview_kit.interview import (
22
+ ChoiceSource,
23
+ Condition,
24
+ CustomKind,
25
+ DefaultSource,
26
+ Facts,
27
+ Interview,
28
+ Question,
29
+ QuestionKind,
30
+ when,
31
+ )
32
+ from cli_interview_kit.validators import Validator, byte_size, non_empty, whole_number
33
+
34
+ __version__ = _version("cli-interview-kit")
35
+
36
+ __all__ = [
37
+ "App",
38
+ "ChoiceSource",
39
+ "CliError",
40
+ "Command",
41
+ "Condition",
42
+ "Consent",
43
+ "Console",
44
+ "CustomKind",
45
+ "DeclarationError",
46
+ "DefaultSource",
47
+ "Facts",
48
+ "Interaction",
49
+ "Interview",
50
+ "Invocation",
51
+ "Option",
52
+ "Question",
53
+ "QuestionKind",
54
+ "Validator",
55
+ "__version__",
56
+ "byte_size",
57
+ "non_empty",
58
+ "parse_kv",
59
+ "when",
60
+ "whole_number",
61
+ ]
@@ -0,0 +1,102 @@
1
+ """Rich-rendered ``--help`` and usage output for every app.
2
+
3
+ The help is built from the parser's own model (its action groups, each
4
+ action's flags, metavar, choices and help, and a subparsers action's
5
+ commands) and rendered as a definition list: each flag on its own line with
6
+ its help indented beneath it. Flag names vary a lot in length, and a
7
+ two-column table would either wrap the long ones away from their metavar or
8
+ squeeze every other row's help.
9
+
10
+ The usage line itself comes from ``argparse.HelpFormatter``, which already
11
+ wraps brackets and mutually exclusive groups correctly; past
12
+ ``_SUMMARIZE_THRESHOLD`` flags it is shortened to ``[OPTIONS]``.
13
+
14
+ argparse exposes this model only through underscored attributes. They have
15
+ been stable for many Python versions, and CI runs the help tests on the
16
+ oldest and newest supported Python. All text is printed literally, never
17
+ read as rich markup.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+
24
+ from rich.console import Console as RichConsole
25
+ from rich.padding import Padding
26
+ from rich.text import Text
27
+
28
+ _SUMMARIZE_THRESHOLD = 8
29
+ """Above this many flags, the usage line shows ``[OPTIONS]`` instead."""
30
+
31
+
32
+ def usage_line(parser: argparse.ArgumentParser) -> str:
33
+ """Return the parser's ``usage: ...`` line."""
34
+ actions = parser._actions # pyright: ignore[reportPrivateUsage]
35
+ flags = [a for a in actions if a.option_strings and a.option_strings != ["-h", "--help"]]
36
+ if len(flags) <= _SUMMARIZE_THRESHOLD:
37
+ formatter = argparse.HelpFormatter(prog=parser.prog)
38
+ formatter.add_usage(
39
+ parser.usage,
40
+ actions,
41
+ parser._mutually_exclusive_groups, # pyright: ignore[reportPrivateUsage]
42
+ )
43
+ return formatter.format_help().strip()
44
+ positionals = [_metavar(a) for a in actions if not a.option_strings]
45
+ return " ".join([f"usage: {parser.prog}", "[-h]", "[OPTIONS]", *positionals])
46
+
47
+
48
+ def print_usage(parser: argparse.ArgumentParser) -> None:
49
+ """Print the usage line to stderr, as argparse does on a usage error."""
50
+ RichConsole(stderr=True).print(Text(usage_line(parser)))
51
+
52
+
53
+ def print_help(parser: argparse.ArgumentParser) -> None:
54
+ """Print the full help: usage, description, then every group of flags."""
55
+ console = RichConsole()
56
+ console.print(Text(usage_line(parser)))
57
+ if parser.description:
58
+ console.print()
59
+ console.print(Text(parser.description))
60
+ for group in parser._action_groups: # pyright: ignore[reportPrivateUsage]
61
+ _print_group(console, group)
62
+
63
+
64
+ def _print_group(console: RichConsole, group: argparse._ArgumentGroup) -> None: # pyright: ignore[reportPrivateUsage]
65
+ """Print one group's title, then each flag with its help beneath it."""
66
+ title = group.title or ""
67
+ rows: list[tuple[str, str]] = []
68
+ for action in group._group_actions: # pyright: ignore[reportPrivateUsage]
69
+ if action.help == argparse.SUPPRESS:
70
+ continue
71
+ if isinstance(action, argparse._SubParsersAction): # pyright: ignore[reportPrivateUsage]
72
+ title = "commands"
73
+ choices: list[argparse.Action] = action._choices_actions # pyright: ignore[reportPrivateUsage, reportUnknownMemberType]
74
+ rows.extend((choice.dest, choice.help or "") for choice in choices)
75
+ continue
76
+ rows.append((_invocation(action), action.help or ""))
77
+ if not rows:
78
+ return
79
+ console.print()
80
+ console.print(Text(f"{title}:", style="bold cyan"))
81
+ for invocation, help_text in rows:
82
+ console.print(Text(f" {invocation}", style="cyan"))
83
+ if help_text:
84
+ console.print(Padding(Text(help_text), (0, 0, 0, 4), expand=False))
85
+
86
+
87
+ def _invocation(action: argparse.Action) -> str:
88
+ """Return every flag of an action with its metavar, e.g. ``--yes, --no-yes``."""
89
+ if not action.option_strings:
90
+ return _metavar(action)
91
+ if action.nargs == 0:
92
+ return ", ".join(action.option_strings)
93
+ return f"{', '.join(action.option_strings)} {_metavar(action)}"
94
+
95
+
96
+ def _metavar(action: argparse.Action) -> str:
97
+ """Return how an action's value is shown: its metavar, choices or name."""
98
+ if isinstance(action.metavar, str):
99
+ return action.metavar
100
+ if action.choices:
101
+ return "{" + ",".join(str(c) for c in action.choices) + "}"
102
+ return action.dest if not action.option_strings else action.dest.upper()
@@ -0,0 +1,15 @@
1
+ """The immutable pydantic base for the package's value objects."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pydantic import BaseModel, ConfigDict
6
+
7
+
8
+ class FrozenModel(BaseModel):
9
+ """Immutable pydantic base for every declaration and value object.
10
+
11
+ Declarations hold callables (run functions, validators, choice sources),
12
+ so arbitrary types are allowed.
13
+ """
14
+
15
+ model_config = ConfigDict(frozen=True, arbitrary_types_allowed=True, extra="forbid")
@@ -0,0 +1,84 @@
1
+ """Prompt loops for answers made of several items, and ``KEY=VALUE`` parsing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+
7
+ from cli_interview_kit.console import Console
8
+ from cli_interview_kit.errors import CliError
9
+ from cli_interview_kit.validators import Validator, all_of, non_empty
10
+
11
+
12
+ def parse_kv(items: Sequence[str] | None, flag: str) -> dict[str, str]:
13
+ """Parse repeated ``KEY=VALUE`` flag values into a dict.
14
+
15
+ Raises
16
+ ------
17
+ CliError
18
+ If a value has no ``=`` or an empty key.
19
+ """
20
+ result: dict[str, str] = {}
21
+ for item in items or ():
22
+ key, separator, value = item.partition("=")
23
+ if not separator or not key:
24
+ raise CliError(f"{flag} expects KEY=VALUE; got '{item}'.")
25
+ result[key] = value
26
+ return result
27
+
28
+
29
+ def prompt_list(
30
+ console: Console,
31
+ label: str,
32
+ *,
33
+ required: bool,
34
+ validate: Validator | None,
35
+ suggestions: Sequence[str],
36
+ ) -> list[str]:
37
+ """Ask for items one at a time; each must be non-blank and valid."""
38
+ result: list[str] = []
39
+ while _keep_adding(console, label, required, len(result)):
40
+ result.append(
41
+ console.text(
42
+ f"{label}: value",
43
+ validate=all_of(non_empty, validate),
44
+ suggestions=[s for s in suggestions if s not in result],
45
+ )
46
+ )
47
+ return result
48
+
49
+
50
+ def prompt_pairs(
51
+ console: Console,
52
+ label: str,
53
+ *,
54
+ required: bool,
55
+ validate: Validator | None,
56
+ ) -> dict[str, str]:
57
+ """Ask for name/value pairs one at a time; names are non-blank and new."""
58
+ result: dict[str, str] = {}
59
+
60
+ def _new_name(name: str) -> str:
61
+ if name in result:
62
+ raise ValueError(f"'{name}' is already set.")
63
+ return name
64
+
65
+ while _keep_adding(console, label, required, len(result)):
66
+ name = console.text(f"{label}: name", validate=all_of(non_empty, _new_name))
67
+ result[name] = console.text(f"{label}: value", validate=all_of(non_empty, validate))
68
+ return result
69
+
70
+
71
+ def _keep_adding(console: Console, label: str, required: bool, collected: int) -> bool:
72
+ """Return whether to ask for another item.
73
+
74
+ A required collection asks for its first item straight away, so it can
75
+ never end up empty.
76
+ """
77
+ if collected:
78
+ return console.confirm("Add another?", default=False)
79
+ return required or console.confirm(f"Add {_with_article(label)}?", default=False)
80
+
81
+
82
+ def _with_article(label: str) -> str:
83
+ """Return ``label`` with its indefinite article, e.g. ``an upsert key``."""
84
+ return f"{'an' if label[:1].lower() in 'aeiou' else 'a'} {label}"
@@ -0,0 +1,199 @@
1
+ """A free-text prompt with its suggestions listed under the input.
2
+
3
+ prompt_toolkit's completion menu floats at the cursor's column in a framed
4
+ box. This prompt instead lists the matching suggestions as plain lines
5
+ directly under the input, filtered as the user types (a match anywhere in a
6
+ suggestion counts):
7
+
8
+ - Up/Down highlight a suggestion, Tab copies it into the input, Enter
9
+ accepts the highlighted suggestion or else what was typed. Any value can
10
+ be entered; suggestions are never enforced.
11
+ - A failed validation shows as a red line under the input until fixed.
12
+ - When done, the list is erased and the answered line stays, like
13
+ questionary's own prompts.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from collections.abc import Callable, Sequence
19
+
20
+ from prompt_toolkit.application import Application
21
+ from prompt_toolkit.buffer import Buffer
22
+ from prompt_toolkit.document import Document
23
+ from prompt_toolkit.formatted_text import FormattedText, StyleAndTextTuples
24
+ from prompt_toolkit.key_binding import KeyBindings, KeyPressEvent
25
+ from prompt_toolkit.layout import HSplit, Layout, VSplit, Window
26
+ from prompt_toolkit.layout.controls import BufferControl, FormattedTextControl
27
+ from prompt_toolkit.shortcuts import print_formatted_text
28
+ from prompt_toolkit.styles import BaseStyle
29
+ from pydantic import BaseModel
30
+ from questionary.constants import DEFAULT_SELECTED_POINTER
31
+
32
+ MAX_SHOWN = 8
33
+ """How many matching suggestions are listed at once."""
34
+
35
+
36
+ class _State(BaseModel):
37
+ """The prompt's mutable state: its suggestions, the highlight and the error."""
38
+
39
+ suggestions: list[str]
40
+ highlighted: int | None = None
41
+ error: str = ""
42
+
43
+ def matches(self, typed: str) -> list[str]:
44
+ """Return the suggestions containing ``typed``, case-insensitively."""
45
+ needle = typed.strip().lower()
46
+ found = [s for s in self.suggestions if needle in s.lower() and s != typed]
47
+ return found[:MAX_SHOWN]
48
+
49
+
50
+ def suggest_text(
51
+ prompt: str,
52
+ suggestions: Sequence[str],
53
+ *,
54
+ default: str = "",
55
+ validate: Callable[[str], bool | str] | None = None,
56
+ style: BaseStyle | None = None,
57
+ ) -> str | None:
58
+ """Ask for free text with suggestions listed under the input.
59
+
60
+ Parameters
61
+ ----------
62
+ prompt : str
63
+ The question.
64
+ suggestions : Sequence[str]
65
+ Values listed while they match what is typed.
66
+ default : str, optional
67
+ Initial input.
68
+ validate : Callable[[str], bool | str] | None, optional
69
+ ``True`` when valid, else the message to show.
70
+ style : BaseStyle | None, optional
71
+ Uses the ``qmark``, ``question``, ``answer``, ``pointer``,
72
+ ``suggestion`` and ``validation-toolbar`` classes, like the other
73
+ prompts.
74
+
75
+ Returns
76
+ -------
77
+ str | None
78
+ The answer, or ``None`` when cancelled with Ctrl-C.
79
+ """
80
+ state = _State(suggestions=list(dict.fromkeys(suggestions)))
81
+ buffer = Buffer(document=Document(default, len(default)), multiline=False)
82
+ buffer.on_text_changed += lambda _buffer: _reset(state) # pyright: ignore[reportUnknownLambdaType]
83
+
84
+ question: StyleAndTextTuples = [
85
+ ("class:qmark", "? "),
86
+ ("class:question", f"{prompt} "),
87
+ ]
88
+ layout = Layout(
89
+ HSplit(
90
+ [
91
+ VSplit(
92
+ [
93
+ Window(
94
+ FormattedTextControl(question),
95
+ dont_extend_width=True,
96
+ ),
97
+ Window(BufferControl(buffer=buffer), height=1),
98
+ ]
99
+ ),
100
+ Window(
101
+ FormattedTextControl(lambda: _lines(state, buffer.text)),
102
+ dont_extend_height=True,
103
+ ),
104
+ ]
105
+ ),
106
+ focused_element=buffer,
107
+ )
108
+ app: Application[str | None] = Application(
109
+ layout=layout,
110
+ key_bindings=_bindings(state, buffer, validate),
111
+ style=style,
112
+ erase_when_done=True,
113
+ )
114
+ answer = app.run()
115
+ if answer is not None:
116
+ print_formatted_text(
117
+ FormattedText([*question, ("class:answer", answer)]),
118
+ style=style,
119
+ )
120
+ return answer
121
+
122
+
123
+ def _lines(state: _State, typed: str) -> StyleAndTextTuples:
124
+ """Return the matching suggestions, the highlighted one, and any error."""
125
+ lines: StyleAndTextTuples = []
126
+ for index, match in enumerate(state.matches(typed)):
127
+ if index == state.highlighted:
128
+ lines.append(("class:pointer", f" {DEFAULT_SELECTED_POINTER} {match}\n"))
129
+ else:
130
+ lines.append(("class:suggestion", f" {match}\n"))
131
+ if state.error:
132
+ lines.append(("class:validation-toolbar", f" ✗ {state.error}\n"))
133
+ return lines
134
+
135
+
136
+ def _bindings(
137
+ state: _State,
138
+ buffer: Buffer,
139
+ validate: Callable[[str], bool | str] | None,
140
+ ) -> KeyBindings:
141
+ """Return the keys: move the highlight, complete, accept, cancel."""
142
+ bindings = KeyBindings()
143
+
144
+ @bindings.add("down")
145
+ def _down(_event: KeyPressEvent) -> None:
146
+ _move(state, buffer.text, 1)
147
+
148
+ @bindings.add("up")
149
+ def _up(_event: KeyPressEvent) -> None:
150
+ _move(state, buffer.text, -1)
151
+
152
+ @bindings.add("tab")
153
+ def _complete(_event: KeyPressEvent) -> None:
154
+ chosen = _chosen(state, buffer.text, first=True)
155
+ if chosen is not None:
156
+ buffer.document = Document(chosen, len(chosen))
157
+
158
+ @bindings.add("enter")
159
+ def _accept(event: KeyPressEvent) -> None:
160
+ value = _chosen(state, buffer.text, first=False) or buffer.text
161
+ verdict = validate(value) if validate is not None else True
162
+ if verdict is not True:
163
+ state.error = str(verdict)
164
+ return
165
+ event.app.exit(result=value)
166
+
167
+ @bindings.add("c-c")
168
+ def _cancel(event: KeyPressEvent) -> None:
169
+ event.app.exit(result=None)
170
+
171
+ return bindings
172
+
173
+
174
+ def _reset(state: _State) -> None:
175
+ """Forget the highlight and the error once the input changes."""
176
+ state.highlighted = None
177
+ state.error = ""
178
+
179
+
180
+ def _move(state: _State, typed: str, step: int) -> None:
181
+ """Move the highlight through the current matches."""
182
+ matches = state.matches(typed)
183
+ if not matches:
184
+ state.highlighted = None
185
+ return
186
+ if state.highlighted is None:
187
+ state.highlighted = 0 if step > 0 else len(matches) - 1
188
+ else:
189
+ state.highlighted = (state.highlighted + step) % len(matches)
190
+
191
+
192
+ def _chosen(state: _State, typed: str, *, first: bool) -> str | None:
193
+ """Return the highlighted match, or the first one when ``first``."""
194
+ matches = state.matches(typed)
195
+ if state.highlighted is not None and state.highlighted < len(matches):
196
+ return matches[state.highlighted]
197
+ if first and matches:
198
+ return matches[0]
199
+ return None
@@ -0,0 +1,233 @@
1
+ """The app: one parser from the command declarations, one error policy.
2
+
3
+ ``App.main`` builds the argument parser from the declared commands, then for
4
+ the selected command either prints ``--questions`` or resolves the
5
+ ``Interaction``, answers the interview and runs the command. Every failure
6
+ leaves through one policy:
7
+
8
+ - ``CliError`` and the app's ``expected_errors``: the message, exit 1;
9
+ - Ctrl-C: ``Aborted.``, exit 130;
10
+ - anything else: one line naming the exception, exit 1, or the traceback
11
+ with ``--debug``;
12
+ - a usage error (an unknown flag, a bad choice): argparse's message, exit 2.
13
+
14
+ Every app gets ``--version`` and ``--debug``; every command with questions
15
+ or consents gets ``--yes`` and ``--questions``.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import json
22
+ import sys
23
+ from collections.abc import Sequence
24
+ from typing import Any, NoReturn
25
+
26
+ from pydantic import Field, model_validator
27
+
28
+ from cli_interview_kit._help import print_help, print_usage
29
+ from cli_interview_kit._model import FrozenModel
30
+ from cli_interview_kit.command import Command, Invocation, Option
31
+ from cli_interview_kit.console import Console
32
+ from cli_interview_kit.errors import CliError
33
+ from cli_interview_kit.interaction import Interaction
34
+
35
+ _COMMAND = "_cik_command"
36
+ _PATH = "_cik_path"
37
+
38
+
39
+ class _ArgumentParser(argparse.ArgumentParser):
40
+ """An ``ArgumentParser`` whose help and usage render through rich.
41
+
42
+ ``add_subparsers()`` gives every subparser its parent's class, so this
43
+ one subclass covers every command.
44
+ """
45
+
46
+ def print_help(self, file: object = None) -> None:
47
+ _ = file
48
+ print_help(self)
49
+
50
+ def print_usage(self, file: object = None) -> None:
51
+ _ = file
52
+ print_usage(self)
53
+
54
+ def error(self, message: str) -> NoReturn:
55
+ print_usage(self)
56
+ Console().error(message)
57
+ self.exit(2)
58
+
59
+
60
+ class App(FrozenModel):
61
+ """A command-line app built from command declarations.
62
+
63
+ Attributes
64
+ ----------
65
+ name : str
66
+ Program name.
67
+ description : str
68
+ Top-level help.
69
+ version : str
70
+ What ``--version`` prints after the name.
71
+ commands : tuple[Command, ...]
72
+ The top-level commands.
73
+ expected_errors : tuple[type[Exception], ...]
74
+ Further exception types whose message is reported like a
75
+ ``CliError``, for failures the app's own libraries raise.
76
+ """
77
+
78
+ name: str = Field(min_length=1)
79
+ description: str
80
+ version: str = Field(min_length=1)
81
+ commands: tuple[Command, ...] = Field(min_length=1)
82
+ expected_errors: tuple[type[Exception], ...] = ()
83
+
84
+ @model_validator(mode="after")
85
+ def _check_commands(self) -> App:
86
+ """Reject duplicate top-level command names."""
87
+ names = [command.name for command in self.commands]
88
+ if duplicated := sorted({n for n in names if names.count(n) > 1}):
89
+ raise ValueError(f"App '{self.name}' has duplicate commands: {duplicated}.")
90
+ return self
91
+
92
+ def main(self, argv: Sequence[str] | None = None) -> int:
93
+ """Run the command ``argv`` selects and return the exit code.
94
+
95
+ Parameters
96
+ ----------
97
+ argv : Sequence[str] | None, optional
98
+ The arguments after the program name; ``sys.argv[1:]`` if omitted.
99
+
100
+ Returns
101
+ -------
102
+ int
103
+ 0 on success, 1 on a failure, 130 when interrupted. A usage
104
+ error exits 2 through ``SystemExit``, as argparse does.
105
+ """
106
+ console = Console()
107
+ args = self.build_parser().parse_args(argv)
108
+ try:
109
+ self._dispatch(console, vars(args))
110
+ except CliError as error:
111
+ console.error(str(error))
112
+ return 1
113
+ except KeyboardInterrupt:
114
+ console.error("Aborted.")
115
+ return 130
116
+ except Exception as error:
117
+ if args.debug:
118
+ raise
119
+ if isinstance(error, self.expected_errors):
120
+ console.error(str(error))
121
+ return 1
122
+ console.error(
123
+ f"Unexpected {type(error).__name__}: {error}. Rerun with "
124
+ f"`{self.name} --debug ...` for the traceback."
125
+ )
126
+ return 1
127
+ return 0
128
+
129
+ def build_parser(self) -> argparse.ArgumentParser:
130
+ """Return the argument parser for every declared command."""
131
+ parser = _ArgumentParser(prog=self.name, description=self.description)
132
+ _ = parser.add_argument(
133
+ "--version", action="version", version=f"{self.name} {self.version}"
134
+ )
135
+ _ = parser.add_argument(
136
+ "--debug",
137
+ action="store_true",
138
+ help="Show the full traceback when a command fails unexpectedly.",
139
+ )
140
+ _add_commands(parser, self.commands, (self.name,), required=True)
141
+ return parser
142
+
143
+ def _dispatch(self, console: Console, values: dict[str, Any]) -> None:
144
+ command: Command = values[_COMMAND]
145
+ command_line = " ".join(values[_PATH])
146
+ options = {option.dest: values.get(option.dest) for option in command.options}
147
+ if values.get("questions"):
148
+ document = command.interview.document(
149
+ command_line, [option.describe() for option in command.options]
150
+ )
151
+ _ = sys.stdout.write(json.dumps(document, indent=2) + "\n")
152
+ return
153
+ interaction = Interaction.resolve(
154
+ bool(values.get("yes")), declared=command.interview.consent_keys
155
+ )
156
+ answers = command.interview.run(console, interaction, values, options)
157
+ # A command without a run has subcommands, and argparse requires one.
158
+ assert command.run is not None
159
+ command.run(
160
+ Invocation(console=console, interaction=interaction, answers=answers, options=options)
161
+ )
162
+
163
+
164
+ def _add_commands(
165
+ parser: argparse.ArgumentParser,
166
+ commands: Sequence[Command],
167
+ path: tuple[str, ...],
168
+ *,
169
+ required: bool,
170
+ ) -> None:
171
+ """Add a subparser for each command, recursively."""
172
+ subparsers = parser.add_subparsers(dest=f"_cik_{len(path)}", required=required)
173
+ for command in commands:
174
+ sub = subparsers.add_parser(command.name, help=command.help, description=command.help)
175
+ command_path = (*path, command.name)
176
+ sub.set_defaults(**{_COMMAND: command, _PATH: command_path})
177
+ _add_options(sub, command.options)
178
+ if command.interactive:
179
+ command.interview.add_arguments(sub)
180
+ _add_interaction_flags(sub)
181
+ if command.subcommands:
182
+ _add_commands(sub, command.subcommands, command_path, required=command.run is None)
183
+
184
+
185
+ def _add_options(parser: argparse.ArgumentParser, options: Sequence[Option]) -> None:
186
+ """Add a command's plain options and positionals."""
187
+ exclusive: dict[str, argparse._MutuallyExclusiveGroup] = {} # pyright: ignore[reportPrivateUsage]
188
+ for option in options:
189
+ target: argparse._ActionsContainer = parser # pyright: ignore[reportPrivateUsage]
190
+ if option.exclusive is not None:
191
+ if option.exclusive not in exclusive:
192
+ exclusive[option.exclusive] = parser.add_mutually_exclusive_group()
193
+ target = exclusive[option.exclusive]
194
+ kwargs: dict[str, Any] = {"help": option.help}
195
+ if option.metavar:
196
+ kwargs["metavar"] = option.metavar
197
+ if option.choices:
198
+ kwargs["choices"] = list(option.choices)
199
+ if option.convert is not None:
200
+ kwargs["type"] = option.convert
201
+ if option.kind == "positional":
202
+ if option.nargs:
203
+ kwargs["nargs"] = option.nargs
204
+ _ = target.add_argument(option.dest, **kwargs)
205
+ continue
206
+ if option.kind == "switch":
207
+ kwargs["action"] = "store_true"
208
+ elif option.kind == "append":
209
+ kwargs["action"] = "append"
210
+ _ = target.add_argument(option.flag, dest=option.dest, **kwargs)
211
+
212
+
213
+ def _add_interaction_flags(parser: argparse.ArgumentParser) -> None:
214
+ """Add ``--yes`` and ``--questions``."""
215
+ group = parser.add_argument_group("interaction")
216
+ _ = group.add_argument(
217
+ "--yes",
218
+ action="store_true",
219
+ help=(
220
+ "Never prompt: every unanswered question takes its default (one "
221
+ "with no safe default fails, naming its flag) and every consent "
222
+ "the command asks for is given."
223
+ ),
224
+ )
225
+ _ = group.add_argument(
226
+ "--questions",
227
+ action="store_true",
228
+ help=(
229
+ "Print the command's questions, consents and options as JSON and "
230
+ "exit, so an AI assistant can ask them and run the command with "
231
+ "--yes and the flags."
232
+ ),
233
+ )