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,163 @@
1
+ """Commands declared as data: options, an interview, subcommands and a run.
2
+
3
+ A ``Command`` is everything needed to expose one command: its help, the
4
+ plain options that choose what it does (``--check``, ``--dry-run``,
5
+ positional arguments), the ``Interview`` it answers, any subcommands, and the
6
+ function that runs it. ``App`` builds the argument parser from these
7
+ declarations, so no command writes argparse code.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Callable
13
+ from typing import Any, Literal
14
+
15
+ from pydantic import Field, model_validator
16
+
17
+ from cli_interview_kit._model import FrozenModel
18
+ from cli_interview_kit.console import Console
19
+ from cli_interview_kit.interaction import Interaction
20
+ from cli_interview_kit.interview import Interview
21
+
22
+ RESERVED_NAMES = frozenset({"help", "debug", "yes", "questions"})
23
+ """Names no option or question may take.
24
+
25
+ ``--help``, ``--yes`` and ``--questions`` are a command's own flags, and
26
+ ``debug`` is where the app's ``--debug`` lands in the parsed arguments every
27
+ command shares. ``--version`` exists only on the app and stores nothing, so
28
+ ``version`` is free.
29
+ """
30
+
31
+
32
+ class Option(FrozenModel):
33
+ """A plain option or positional argument; not an interview question.
34
+
35
+ Options choose what a command does (``--check``, ``--dry-run``) or name
36
+ what it acts on. Anything the user could be asked belongs in the
37
+ interview instead.
38
+
39
+ Attributes
40
+ ----------
41
+ dest : str
42
+ The name the value is read by, in snake_case; the flag is ``--``
43
+ plus the name with dashes.
44
+ help : str
45
+ Help text.
46
+ kind : Literal["switch", "value", "append", "positional"]
47
+ ``switch`` is an on/off flag; ``value`` takes one value; ``append``
48
+ is repeatable; ``positional`` is an argument.
49
+ metavar : str | None
50
+ Value placeholder in help.
51
+ choices : tuple[str, ...]
52
+ Allowed values.
53
+ nargs : str | None
54
+ A positional's arity, e.g. ``"*"``.
55
+ convert : Callable[[str], Any] | None
56
+ Converts and checks a value; raising ``ValueError`` is a usage error.
57
+ exclusive : str | None
58
+ Options sharing this name are mutually exclusive.
59
+ """
60
+
61
+ dest: str = Field(pattern=r"^[a-z][a-z0-9_]*$")
62
+ help: str = Field(min_length=1)
63
+ kind: Literal["switch", "value", "append", "positional"] = "value"
64
+ metavar: str | None = None
65
+ choices: tuple[str, ...] = ()
66
+ nargs: Literal["?", "*", "+"] | None = None
67
+ convert: Callable[[str], Any] | None = None
68
+ exclusive: str | None = None
69
+
70
+ @model_validator(mode="after")
71
+ def _check_kind(self) -> Option:
72
+ """Reject settings that do not fit the option's kind."""
73
+ if self.nargs is not None and self.kind != "positional":
74
+ raise ValueError(f"{self.flag}: only a positional takes nargs.")
75
+ if self.kind == "switch" and (self.choices or self.convert or self.metavar):
76
+ raise ValueError(f"{self.flag}: a switch takes no value settings.")
77
+ if self.kind == "positional" and self.exclusive is not None:
78
+ raise ValueError(f"{self.flag}: a positional cannot be mutually exclusive.")
79
+ return self
80
+
81
+ @property
82
+ def flag(self) -> str:
83
+ """The option's flag, or its name for a positional."""
84
+ if self.kind == "positional":
85
+ return self.dest
86
+ return "--" + self.dest.replace("_", "-")
87
+
88
+ def describe(self) -> dict[str, Any]:
89
+ """Return the option as ``--questions`` lists it."""
90
+ return {"flag": self.flag, "kind": self.kind, "help": self.help}
91
+
92
+
93
+ class Invocation(FrozenModel):
94
+ """What a command's run function receives.
95
+
96
+ Attributes
97
+ ----------
98
+ console : Console
99
+ Output and prompts.
100
+ interaction : Interaction
101
+ Whether the run may prompt and has consent; pass it to
102
+ ``Consent.ask``.
103
+ answers : dict[str, Any]
104
+ The answers of the questions that applied, by key.
105
+ options : dict[str, Any]
106
+ The options' values, by ``dest``.
107
+ """
108
+
109
+ console: Console
110
+ interaction: Interaction
111
+ answers: dict[str, Any]
112
+ options: dict[str, Any]
113
+
114
+
115
+ class Command(FrozenModel):
116
+ """One command.
117
+
118
+ Attributes
119
+ ----------
120
+ name : str
121
+ The command's name on the command line.
122
+ help : str
123
+ One-line help.
124
+ options : tuple[Option, ...]
125
+ Plain options and positionals.
126
+ interview : Interview
127
+ Questions and consents. A command with any gets ``--yes`` and
128
+ ``--questions``.
129
+ run : Callable[[Invocation], None] | None
130
+ What the command does; ``None`` for a group of subcommands.
131
+ subcommands : tuple[Command, ...]
132
+ Nested commands.
133
+ """
134
+
135
+ name: str = Field(pattern=r"^[a-z][a-z0-9-]*$")
136
+ help: str = Field(min_length=1)
137
+ options: tuple[Option, ...] = ()
138
+ interview: Interview = Interview()
139
+ run: Callable[[Invocation], None] | None = None
140
+ subcommands: tuple[Command, ...] = ()
141
+
142
+ @model_validator(mode="after")
143
+ def _check_names(self) -> Command:
144
+ """Reject a command that runs nothing, and clashing names."""
145
+ if self.run is None and not self.subcommands:
146
+ raise ValueError(f"Command '{self.name}' has neither a run nor subcommands.")
147
+ names = [option.dest for option in self.options]
148
+ names += [question.key for question in self.interview.questions]
149
+ clashes = sorted({n for n in names if names.count(n) > 1} | (set(names) & RESERVED_NAMES))
150
+ if clashes:
151
+ raise ValueError(
152
+ f"Command '{self.name}' uses {', '.join(clashes)} more than once or as a "
153
+ f"reserved name ({', '.join(sorted(RESERVED_NAMES))})."
154
+ )
155
+ commands = [command.name for command in self.subcommands]
156
+ if duplicated := sorted({n for n in commands if commands.count(n) > 1}):
157
+ raise ValueError(f"Command '{self.name}' has duplicate subcommands: {duplicated}.")
158
+ return self
159
+
160
+ @property
161
+ def interactive(self) -> bool:
162
+ """Whether the command has questions or consents."""
163
+ return bool(self.interview.questions or self.interview.consents)
@@ -0,0 +1,280 @@
1
+ """The one channel a command writes to and asks through.
2
+
3
+ Output follows the Unix convention: ``print`` writes the command's result to
4
+ stdout, and the status messages (``info``, ``success``, ``warning``,
5
+ ``error``) and progress bars go to stderr, so a command's output can be piped
6
+ or parsed without the commentary. Status messages are plain text: anything in
7
+ them, including values the user typed, is printed literally and never read
8
+ as rich markup.
9
+
10
+ The prompts are questionary's, plus a free-text prompt that lists
11
+ suggestions under the input. Every prompt raises ``KeyboardInterrupt`` when
12
+ the user cancels it with Ctrl-C, which the app reports as ``Aborted.``.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from collections.abc import Callable, Generator, Sequence
18
+ from contextlib import contextmanager
19
+ from typing import TypeVar
20
+
21
+ import questionary
22
+ from questionary import Choice, Style
23
+ from rich.console import Console as RichConsole
24
+ from rich.progress import BarColumn, MofNCompleteColumn, Progress, TextColumn
25
+ from rich.text import Text
26
+
27
+ from cli_interview_kit._suggest import suggest_text
28
+ from cli_interview_kit.errors import CliError
29
+ from cli_interview_kit.validators import Validator
30
+
31
+ T = TypeVar("T")
32
+
33
+ PROMPT_STYLE = Style(
34
+ [
35
+ ("qmark", "fg:cyan bold"),
36
+ ("question", "bold"),
37
+ ("answer", "fg:green bold"),
38
+ ("pointer", "fg:cyan bold"),
39
+ ("highlighted", "fg:cyan bold"),
40
+ ("selected", "fg:green"),
41
+ ("suggestion", "fg:ansibrightblack"),
42
+ # prompt_toolkit draws a validation message as a maroon bar by default.
43
+ ("validation-toolbar", "noinherit fg:ansired bold"),
44
+ ]
45
+ )
46
+ """The prompts' colours; every prompt uses it."""
47
+
48
+
49
+ class Console:
50
+ """Styled output and interactive prompts for a command.
51
+
52
+ Methods
53
+ -------
54
+ print(renderable)
55
+ Print a result to stdout: text, rich markup or any rich renderable.
56
+ info(message), success(message), warning(message), error(message)
57
+ Print a labelled status line to stderr, as plain text.
58
+ progress(description)
59
+ Show a progress bar on stderr for a series of named steps.
60
+ select(prompt, choices, label)
61
+ Ask for one of ``choices``.
62
+ checkbox(prompt, choices, label, checked)
63
+ Ask for any number of ``choices``.
64
+ confirm(prompt, default)
65
+ Ask a yes/no question.
66
+ text(prompt, default, validate, suggestions)
67
+ Ask for free text, validated, optionally with suggestions.
68
+ """
69
+
70
+ def __init__(self) -> None:
71
+ self._out = RichConsole()
72
+ self._err = RichConsole(stderr=True)
73
+
74
+ def print(self, renderable: object) -> None:
75
+ """Print a result to stdout: text, rich markup or a rich renderable."""
76
+ self._out.print(renderable)
77
+
78
+ def info(self, message: str) -> None:
79
+ """Print an informational status line."""
80
+ self._status("INFO", "bold cyan", message)
81
+
82
+ def success(self, message: str) -> None:
83
+ """Print a success status line."""
84
+ self._status("OK", "bold green", message)
85
+
86
+ def warning(self, message: str) -> None:
87
+ """Print a warning status line."""
88
+ self._status("WARN", "bold yellow", message)
89
+
90
+ def error(self, message: str) -> None:
91
+ """Print an error status line."""
92
+ self._status("ERROR", "bold red", message)
93
+
94
+ def _status(self, label: str, style: str, message: str) -> None:
95
+ # Soft wrap: a long message stays one line when piped, for whatever reads it.
96
+ self._err.print(
97
+ Text.assemble((label, style), " ", message), highlight=False, soft_wrap=True
98
+ )
99
+
100
+ @contextmanager
101
+ def progress(self, description: str) -> Generator[Callable[[int, int, str], None]]:
102
+ """Show a progress bar on stderr for a series of named steps.
103
+
104
+ Parameters
105
+ ----------
106
+ description : str
107
+ What the steps do together, e.g. ``"Checking files"``.
108
+
109
+ Yields
110
+ ------
111
+ Callable[[int, int, str], None]
112
+ ``update(index, total, detail)``: call it before each step, with
113
+ the step's 1-based index and what it is doing.
114
+ """
115
+ with Progress(
116
+ TextColumn("[bold cyan]INFO[/bold cyan]"),
117
+ TextColumn("{task.description}", markup=False),
118
+ BarColumn(),
119
+ MofNCompleteColumn(),
120
+ TextColumn("{task.fields[detail]}", markup=False),
121
+ console=self._err,
122
+ ) as progress:
123
+ task = progress.add_task(description, total=None, detail="")
124
+
125
+ def update(index: int, total: int, detail: str) -> None:
126
+ progress.update(task, completed=index, total=total, detail=detail)
127
+
128
+ yield update
129
+
130
+ def select(self, prompt: str, choices: Sequence[T], label: Callable[[T], str]) -> T:
131
+ """Ask for one of ``choices``.
132
+
133
+ Parameters
134
+ ----------
135
+ prompt : str
136
+ The question.
137
+ choices : Sequence[T]
138
+ What can be chosen.
139
+ label : Callable[[T], str]
140
+ How each choice is shown.
141
+
142
+ Returns
143
+ -------
144
+ T
145
+ The chosen item.
146
+
147
+ Raises
148
+ ------
149
+ CliError
150
+ If there is nothing to choose from.
151
+ KeyboardInterrupt
152
+ If the user cancels.
153
+ """
154
+ if not choices:
155
+ raise CliError(f"{prompt}: nothing to choose from.")
156
+ index: object = questionary.select(
157
+ prompt,
158
+ choices=[Choice(title=label(choice), value=i) for i, choice in enumerate(choices)],
159
+ style=PROMPT_STYLE,
160
+ ).ask()
161
+ if not isinstance(index, int):
162
+ raise KeyboardInterrupt
163
+ return choices[index]
164
+
165
+ def checkbox(
166
+ self,
167
+ prompt: str,
168
+ choices: Sequence[T],
169
+ label: Callable[[T], str],
170
+ checked: Sequence[T] | None = None,
171
+ ) -> list[T]:
172
+ """Ask for any number of ``choices``.
173
+
174
+ Parameters
175
+ ----------
176
+ prompt : str
177
+ The question.
178
+ choices : Sequence[T]
179
+ What can be chosen.
180
+ label : Callable[[T], str]
181
+ How each choice is shown.
182
+ checked : Sequence[T] | None, optional
183
+ The choices ticked when the prompt opens; every choice when
184
+ omitted, so the common answer "all of them" is one keypress.
185
+
186
+ Returns
187
+ -------
188
+ list[T]
189
+ The chosen items, in ``choices`` order.
190
+
191
+ Raises
192
+ ------
193
+ CliError
194
+ If there is nothing to choose from.
195
+ KeyboardInterrupt
196
+ If the user cancels.
197
+ """
198
+ if not choices:
199
+ raise CliError(f"{prompt}: nothing to choose from.")
200
+ ticked = choices if checked is None else checked
201
+ indexes: object = questionary.checkbox(
202
+ prompt,
203
+ choices=[
204
+ Choice(title=label(choice), value=i, checked=choice in ticked)
205
+ for i, choice in enumerate(choices)
206
+ ],
207
+ style=PROMPT_STYLE,
208
+ ).ask()
209
+ if not isinstance(indexes, list):
210
+ raise KeyboardInterrupt
211
+ chosen = sorted(i for i in indexes if isinstance(i, int)) # pyright: ignore[reportUnknownVariableType]
212
+ return [choices[i] for i in chosen]
213
+
214
+ def confirm(self, prompt: str, default: bool) -> bool:
215
+ """Ask a yes/no question.
216
+
217
+ Raises
218
+ ------
219
+ KeyboardInterrupt
220
+ If the user cancels.
221
+ """
222
+ answer: object = questionary.confirm(prompt, default=default, style=PROMPT_STYLE).ask()
223
+ if not isinstance(answer, bool):
224
+ raise KeyboardInterrupt
225
+ return answer
226
+
227
+ def text(
228
+ self,
229
+ prompt: str,
230
+ default: str = "",
231
+ validate: Validator | None = None,
232
+ suggestions: Sequence[str] = (),
233
+ ) -> str:
234
+ """Ask for free text, asking again until it is valid.
235
+
236
+ Parameters
237
+ ----------
238
+ prompt : str
239
+ The question.
240
+ default : str, optional
241
+ Text the input starts with.
242
+ validate : Validator | None, optional
243
+ Raises ``ValueError`` for an invalid answer; its message is shown
244
+ under the input until the answer changes.
245
+ suggestions : Sequence[str], optional
246
+ Values listed under the input while they match what is typed.
247
+ Any other value can still be entered.
248
+
249
+ Returns
250
+ -------
251
+ str
252
+ The answer.
253
+
254
+ Raises
255
+ ------
256
+ KeyboardInterrupt
257
+ If the user cancels.
258
+ """
259
+
260
+ def _verdict(value: str) -> bool | str:
261
+ if validate is None:
262
+ return True
263
+ try:
264
+ _ = validate(value)
265
+ except ValueError as error:
266
+ return str(error)
267
+ return True
268
+
269
+ answer: object
270
+ if suggestions:
271
+ answer = suggest_text(
272
+ prompt, suggestions, default=default, validate=_verdict, style=PROMPT_STYLE
273
+ )
274
+ else:
275
+ answer = questionary.text(
276
+ prompt, default=default, validate=_verdict, style=PROMPT_STYLE
277
+ ).ask()
278
+ if not isinstance(answer, str):
279
+ raise KeyboardInterrupt
280
+ return answer
@@ -0,0 +1,19 @@
1
+ """The two exception types: a user-facing failure and a broken declaration."""
2
+
3
+
4
+ class CliError(Exception):
5
+ """An expected failure, reported as its message without a traceback.
6
+
7
+ Raise it from a command for anything the user can act on: a bad value, a
8
+ missing resource, a check that failed. The app prints the message to
9
+ stderr and exits 1.
10
+ """
11
+
12
+
13
+ class DeclarationError(Exception):
14
+ """A declaration is used in a way it does not allow.
15
+
16
+ A programming error in the app, not the user's: for example asking for a
17
+ consent the command never declared. Declarations that are invalid on their
18
+ own are rejected when they are built, with pydantic's ``ValidationError``.
19
+ """
@@ -0,0 +1,104 @@
1
+ """How a run may interact with its user: answers and consents.
2
+
3
+ Each run resolves one ``Interaction`` from ``--yes`` and whether stdin is a
4
+ terminal, and every question and consent follows it:
5
+
6
+ - **Answers** (what to create, which environment): asked in a terminal.
7
+ When nobody can be asked, each takes its default, and one with no safe
8
+ default fails the run, naming its flag.
9
+ - **Consents** (delete something, deploy to production, overwrite files):
10
+ ``--yes`` gives them. Without it they are asked in a terminal; when nobody
11
+ can be asked, a consent with a safe default takes it and any other fails
12
+ the run, asking for ``--yes``. A piped stdin never consents by itself.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import sys
18
+
19
+ from pydantic import Field
20
+
21
+ from cli_interview_kit._model import FrozenModel
22
+ from cli_interview_kit.console import Console
23
+ from cli_interview_kit.errors import CliError, DeclarationError
24
+
25
+
26
+ class Interaction(FrozenModel):
27
+ """Whether a run may prompt, and whether it has blanket consent.
28
+
29
+ Attributes
30
+ ----------
31
+ can_prompt : bool
32
+ Stdin is a terminal and ``--yes`` was not given.
33
+ consent : bool
34
+ ``--yes`` was given: every declared consent is granted.
35
+ declared : frozenset[str]
36
+ The keys of the consents the running command declares; only these
37
+ can be asked for.
38
+ """
39
+
40
+ can_prompt: bool
41
+ consent: bool
42
+ declared: frozenset[str] = Field(default_factory=frozenset)
43
+
44
+ @classmethod
45
+ def resolve(cls, yes: bool, declared: frozenset[str] = frozenset()) -> Interaction:
46
+ """Return the interaction for a run, from ``--yes`` and the terminal."""
47
+ return cls(can_prompt=sys.stdin.isatty() and not yes, consent=yes, declared=declared)
48
+
49
+
50
+ class Consent(FrozenModel):
51
+ """A confirmation a command may need before it acts.
52
+
53
+ Declared on the command's ``Interview`` so ``--questions`` lists it: an
54
+ assistant describes it to the user first and passes ``--yes`` only once
55
+ they agree.
56
+
57
+ Attributes
58
+ ----------
59
+ key : str
60
+ Stable identifier.
61
+ when : str
62
+ When the command asks for it and what it allows, for ``--questions``.
63
+ safe_default : bool | None
64
+ The answer when nobody can be asked and ``--yes`` was not given, and
65
+ the prompt's default. ``None`` means only ``--yes`` or a person can
66
+ give it.
67
+ """
68
+
69
+ key: str = Field(min_length=1)
70
+ when: str = Field(min_length=1)
71
+ safe_default: bool | None = None
72
+
73
+ def ask(self, console: Console, interaction: Interaction, message: str) -> bool:
74
+ """Return whether the run has this consent.
75
+
76
+ Parameters
77
+ ----------
78
+ console : Console
79
+ Where to ask.
80
+ interaction : Interaction
81
+ The run's interaction.
82
+ message : str
83
+ The question to ask, saying exactly what will happen.
84
+
85
+ Raises
86
+ ------
87
+ DeclarationError
88
+ If the running command does not declare this consent.
89
+ CliError
90
+ If nobody can be asked, ``--yes`` was not given, and the consent
91
+ has no safe default.
92
+ """
93
+ if self.key not in interaction.declared:
94
+ raise DeclarationError(
95
+ f"Consent '{self.key}' is not declared on the running command's "
96
+ "Interview, so --questions cannot list it."
97
+ )
98
+ if interaction.consent:
99
+ return True
100
+ if interaction.can_prompt:
101
+ return console.confirm(message, default=bool(self.safe_default))
102
+ if self.safe_default is not None:
103
+ return self.safe_default
104
+ raise CliError(f"{message} This needs consent: rerun with --yes.")