cli-interview-kit 0.1.0__py3-none-any.whl → 0.1.2__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.
@@ -6,10 +6,8 @@ from pydantic import BaseModel, ConfigDict
6
6
 
7
7
 
8
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
- """
9
+ """An immutable pydantic base for every declaration and value object."""
14
10
 
11
+ # Declarations hold callables (run functions, validators, choice sources), so arbitrary
12
+ # types are allowed.
15
13
  model_config = ConfigDict(frozen=True, arbitrary_types_allowed=True, extra="forbid")
@@ -12,10 +12,21 @@ from cli_interview_kit.validators import Validator, all_of, non_empty
12
12
  def parse_kv(items: Sequence[str] | None, flag: str) -> dict[str, str]:
13
13
  """Parse repeated ``KEY=VALUE`` flag values into a dict.
14
14
 
15
+ Parameters
16
+ ----------
17
+ items
18
+ The values of a repeatable flag, or ``None`` if it was not given.
19
+ flag
20
+ The flag's name, for error messages.
21
+
22
+ Returns
23
+ -------
24
+ The values, by key.
25
+
15
26
  Raises
16
27
  ------
17
28
  CliError
18
- If a value has no ``=`` or an empty key.
29
+ A value has no ``=`` or an empty key.
19
30
  """
20
31
  result: dict[str, str] = {}
21
32
  for item in items or ():
@@ -69,11 +80,8 @@ def prompt_pairs(
69
80
 
70
81
 
71
82
  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
- """
83
+ """Return whether to ask for another item."""
84
+ # A required collection asks for its first item straight away, so it can never end up empty.
77
85
  if collected:
78
86
  return console.confirm("Add another?", default=False)
79
87
  return required or console.confirm(f"Add {_with_article(label)}?", default=False)
@@ -47,6 +47,9 @@ class _State(BaseModel):
47
47
  return found[:MAX_SHOWN]
48
48
 
49
49
 
50
+ # ``validate`` returns ``True`` when valid, else the message to show. ``style`` uses the ``qmark``,
51
+ # ``question``, ``answer``, ``pointer``, ``suggestion`` and ``validation-toolbar`` classes, like
52
+ # the other prompts. The answer is ``None`` when the user cancels with Ctrl-C.
50
53
  def suggest_text(
51
54
  prompt: str,
52
55
  suggestions: Sequence[str],
@@ -55,28 +58,7 @@ def suggest_text(
55
58
  validate: Callable[[str], bool | str] | None = None,
56
59
  style: BaseStyle | None = None,
57
60
  ) -> 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
- """
61
+ """Ask for free text with suggestions listed under the input."""
80
62
  state = _State(suggestions=list(dict.fromkeys(suggestions)))
81
63
  buffer = Buffer(document=Document(default, len(default)), multiline=False)
82
64
  buffer.on_text_changed += lambda _buffer: _reset(state) # pyright: ignore[reportUnknownLambdaType]
cli_interview_kit/app.py CHANGED
@@ -37,21 +37,23 @@ _PATH = "_cik_path"
37
37
 
38
38
 
39
39
  class _ArgumentParser(argparse.ArgumentParser):
40
- """An ``ArgumentParser`` whose help and usage render through rich.
40
+ """An ``ArgumentParser`` whose help and usage render through rich."""
41
41
 
42
- ``add_subparsers()`` gives every subparser its parent's class, so this
43
- one subclass covers every command.
44
- """
42
+ # ``add_subparsers()`` gives every subparser its parent's class, so this one subclass covers
43
+ # every command.
45
44
 
46
45
  def print_help(self, file: object = None) -> None:
46
+ """Print the help through rich, ignoring ``file``."""
47
47
  _ = file
48
48
  print_help(self)
49
49
 
50
50
  def print_usage(self, file: object = None) -> None:
51
+ """Print the usage line through rich, ignoring ``file``."""
51
52
  _ = file
52
53
  print_usage(self)
53
54
 
54
55
  def error(self, message: str) -> NoReturn:
56
+ """Print the usage and the message, then exit with status 2."""
55
57
  print_usage(self)
56
58
  Console().error(message)
57
59
  self.exit(2)
@@ -62,17 +64,24 @@ class App(FrozenModel):
62
64
 
63
65
  Attributes
64
66
  ----------
65
- name : str
67
+ name
66
68
  Program name.
67
- description : str
69
+ description
68
70
  Top-level help.
69
- version : str
71
+ version
70
72
  What ``--version`` prints after the name.
71
- commands : tuple[Command, ...]
73
+ commands
72
74
  The top-level commands.
73
- expected_errors : tuple[type[Exception], ...]
75
+ expected_errors
74
76
  Further exception types whose message is reported like a
75
77
  ``CliError``, for failures the app's own libraries raise.
78
+
79
+ Methods
80
+ -------
81
+ main
82
+ Run the command ``argv`` selects and return the exit code.
83
+ build_parser
84
+ Return the argument parser for every declared command.
76
85
  """
77
86
 
78
87
  name: str = Field(min_length=1)
@@ -94,14 +103,17 @@ class App(FrozenModel):
94
103
 
95
104
  Parameters
96
105
  ----------
97
- argv : Sequence[str] | None, optional
106
+ argv
98
107
  The arguments after the program name; ``sys.argv[1:]`` if omitted.
99
108
 
100
109
  Returns
101
110
  -------
102
- int
103
- 0 on success, 1 on a failure, 130 when interrupted. A usage
104
- error exits 2 through ``SystemExit``, as argparse does.
111
+ The exit code: 0 on success, 1 on a failure, 130 when interrupted.
112
+
113
+ Raises
114
+ ------
115
+ SystemExit
116
+ A usage error (an unknown flag, a bad choice) exits with status 2, as argparse does.
105
117
  """
106
118
  console = Console()
107
119
  args = self.build_parser().parse_args(argv)
@@ -127,7 +139,12 @@ class App(FrozenModel):
127
139
  return 0
128
140
 
129
141
  def build_parser(self) -> argparse.ArgumentParser:
130
- """Return the argument parser for every declared command."""
142
+ """Return the argument parser for every declared command.
143
+
144
+ Returns
145
+ -------
146
+ The parser, with ``--version``, ``--debug`` and one subparser per command.
147
+ """
131
148
  parser = _ArgumentParser(prog=self.name, description=self.description)
132
149
  _ = parser.add_argument(
133
150
  "--version", action="version", version=f"{self.name} {self.version}"
@@ -141,6 +158,7 @@ class App(FrozenModel):
141
158
  return parser
142
159
 
143
160
  def _dispatch(self, console: Console, values: dict[str, Any]) -> None:
161
+ """Print the selected command's ``--questions``, or answer its interview and run it."""
144
162
  command: Command = values[_COMMAND]
145
163
  command_line = " ".join(values[_PATH])
146
164
  options = {option.dest: values.get(option.dest) for option in command.options}
@@ -155,7 +173,7 @@ class App(FrozenModel):
155
173
  )
156
174
  answers = command.interview.run(console, interaction, values, options)
157
175
  # A command without a run has subcommands, and argparse requires one.
158
- assert command.run is not None
176
+ assert command.run is not None # noqa: S101 -- see the comment above
159
177
  command.run(
160
178
  Invocation(console=console, interaction=interaction, answers=answers, options=options)
161
179
  )
@@ -38,24 +38,31 @@ class Option(FrozenModel):
38
38
 
39
39
  Attributes
40
40
  ----------
41
- dest : str
41
+ dest
42
42
  The name the value is read by, in snake_case; the flag is ``--``
43
43
  plus the name with dashes.
44
- help : str
44
+ help
45
45
  Help text.
46
- kind : Literal["switch", "value", "append", "positional"]
46
+ kind
47
47
  ``switch`` is an on/off flag; ``value`` takes one value; ``append``
48
48
  is repeatable; ``positional`` is an argument.
49
- metavar : str | None
49
+ metavar
50
50
  Value placeholder in help.
51
- choices : tuple[str, ...]
51
+ choices
52
52
  Allowed values.
53
- nargs : str | None
53
+ nargs
54
54
  A positional's arity, e.g. ``"*"``.
55
- convert : Callable[[str], Any] | None
55
+ convert
56
56
  Converts and checks a value; raising ``ValueError`` is a usage error.
57
- exclusive : str | None
57
+ exclusive
58
58
  Options sharing this name are mutually exclusive.
59
+ flag
60
+ The option's flag, or its name for a positional.
61
+
62
+ Methods
63
+ -------
64
+ describe
65
+ Describe the option as ``--questions`` lists it.
59
66
  """
60
67
 
61
68
  dest: str = Field(pattern=r"^[a-z][a-z0-9_]*$")
@@ -86,7 +93,12 @@ class Option(FrozenModel):
86
93
  return "--" + self.dest.replace("_", "-")
87
94
 
88
95
  def describe(self) -> dict[str, Any]:
89
- """Return the option as ``--questions`` lists it."""
96
+ """Describe the option as ``--questions`` lists it.
97
+
98
+ Returns
99
+ -------
100
+ The option's flag, kind and help.
101
+ """
90
102
  return {"flag": self.flag, "kind": self.kind, "help": self.help}
91
103
 
92
104
 
@@ -95,14 +107,14 @@ class Invocation(FrozenModel):
95
107
 
96
108
  Attributes
97
109
  ----------
98
- console : Console
110
+ console
99
111
  Output and prompts.
100
- interaction : Interaction
112
+ interaction
101
113
  Whether the run may prompt and has consent; pass it to
102
114
  ``Consent.ask``.
103
- answers : dict[str, Any]
115
+ answers
104
116
  The answers of the questions that applied, by key.
105
- options : dict[str, Any]
117
+ options
106
118
  The options' values, by ``dest``.
107
119
  """
108
120
 
@@ -117,19 +129,21 @@ class Command(FrozenModel):
117
129
 
118
130
  Attributes
119
131
  ----------
120
- name : str
132
+ name
121
133
  The command's name on the command line.
122
- help : str
134
+ help
123
135
  One-line help.
124
- options : tuple[Option, ...]
136
+ options
125
137
  Plain options and positionals.
126
- interview : Interview
138
+ interview
127
139
  Questions and consents. A command with any gets ``--yes`` and
128
140
  ``--questions``.
129
- run : Callable[[Invocation], None] | None
141
+ run
130
142
  What the command does; ``None`` for a group of subcommands.
131
- subcommands : tuple[Command, ...]
143
+ subcommands
132
144
  Nested commands.
145
+ interactive
146
+ Whether the command has questions or consents.
133
147
  """
134
148
 
135
149
  name: str = Field(pattern=r"^[a-z][a-z0-9-]*$")
@@ -51,19 +51,25 @@ class Console:
51
51
 
52
52
  Methods
53
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)
54
+ print
55
+ Print a result to stdout: text, rich markup or a rich renderable.
56
+ info
57
+ Print an informational status line.
58
+ success
59
+ Print a success status line.
60
+ warning
61
+ Print a warning status line.
62
+ error
63
+ Print an error status line.
64
+ progress
59
65
  Show a progress bar on stderr for a series of named steps.
60
- select(prompt, choices, label)
66
+ select
61
67
  Ask for one of ``choices``.
62
- checkbox(prompt, choices, label, checked)
68
+ checkbox
63
69
  Ask for any number of ``choices``.
64
- confirm(prompt, default)
70
+ confirm
65
71
  Ask a yes/no question.
66
- text(prompt, default, validate, suggestions)
72
+ text
67
73
  Ask for free text, validated, optionally with suggestions.
68
74
  """
69
75
 
@@ -72,26 +78,57 @@ class Console:
72
78
  self._err = RichConsole(stderr=True)
73
79
 
74
80
  def print(self, renderable: object) -> None:
75
- """Print a result to stdout: text, rich markup or a rich renderable."""
81
+ """Print a result to stdout: text, rich markup or a rich renderable.
82
+
83
+ Parameters
84
+ ----------
85
+ renderable
86
+ Text, rich markup or any rich renderable.
87
+ """
76
88
  self._out.print(renderable)
77
89
 
78
90
  def info(self, message: str) -> None:
79
- """Print an informational status line."""
91
+ """Print an informational status line.
92
+
93
+ Parameters
94
+ ----------
95
+ message
96
+ The text to show, printed literally.
97
+ """
80
98
  self._status("INFO", "bold cyan", message)
81
99
 
82
100
  def success(self, message: str) -> None:
83
- """Print a success status line."""
101
+ """Print a success status line.
102
+
103
+ Parameters
104
+ ----------
105
+ message
106
+ The text to show, printed literally.
107
+ """
84
108
  self._status("OK", "bold green", message)
85
109
 
86
110
  def warning(self, message: str) -> None:
87
- """Print a warning status line."""
111
+ """Print a warning status line.
112
+
113
+ Parameters
114
+ ----------
115
+ message
116
+ The text to show, printed literally.
117
+ """
88
118
  self._status("WARN", "bold yellow", message)
89
119
 
90
120
  def error(self, message: str) -> None:
91
- """Print an error status line."""
121
+ """Print an error status line.
122
+
123
+ Parameters
124
+ ----------
125
+ message
126
+ The text to show, printed literally.
127
+ """
92
128
  self._status("ERROR", "bold red", message)
93
129
 
94
130
  def _status(self, label: str, style: str, message: str) -> None:
131
+ """Print a labelled status line to stderr."""
95
132
  # Soft wrap: a long message stays one line when piped, for whatever reads it.
96
133
  self._err.print(
97
134
  Text.assemble((label, style), " ", message), highlight=False, soft_wrap=True
@@ -103,14 +140,13 @@ class Console:
103
140
 
104
141
  Parameters
105
142
  ----------
106
- description : str
143
+ description
107
144
  What the steps do together, e.g. ``"Checking files"``.
108
145
 
109
146
  Yields
110
147
  ------
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.
148
+ ``update(index, total, detail)``: call it before each step, with the step's
149
+ 1-based index and what it is doing.
114
150
  """
115
151
  with Progress(
116
152
  TextColumn("[bold cyan]INFO[/bold cyan]"),
@@ -132,24 +168,23 @@ class Console:
132
168
 
133
169
  Parameters
134
170
  ----------
135
- prompt : str
171
+ prompt
136
172
  The question.
137
- choices : Sequence[T]
173
+ choices
138
174
  What can be chosen.
139
- label : Callable[[T], str]
175
+ label
140
176
  How each choice is shown.
141
177
 
142
178
  Returns
143
179
  -------
144
- T
145
- The chosen item.
180
+ The chosen item.
146
181
 
147
182
  Raises
148
183
  ------
149
184
  CliError
150
- If there is nothing to choose from.
185
+ There is nothing to choose from.
151
186
  KeyboardInterrupt
152
- If the user cancels.
187
+ The user cancels.
153
188
  """
154
189
  if not choices:
155
190
  raise CliError(f"{prompt}: nothing to choose from.")
@@ -173,27 +208,26 @@ class Console:
173
208
 
174
209
  Parameters
175
210
  ----------
176
- prompt : str
211
+ prompt
177
212
  The question.
178
- choices : Sequence[T]
213
+ choices
179
214
  What can be chosen.
180
- label : Callable[[T], str]
215
+ label
181
216
  How each choice is shown.
182
- checked : Sequence[T] | None, optional
217
+ checked
183
218
  The choices ticked when the prompt opens; every choice when
184
219
  omitted, so the common answer "all of them" is one keypress.
185
220
 
186
221
  Returns
187
222
  -------
188
- list[T]
189
- The chosen items, in ``choices`` order.
223
+ The chosen items, in ``choices`` order.
190
224
 
191
225
  Raises
192
226
  ------
193
227
  CliError
194
- If there is nothing to choose from.
228
+ There is nothing to choose from.
195
229
  KeyboardInterrupt
196
- If the user cancels.
230
+ The user cancels.
197
231
  """
198
232
  if not choices:
199
233
  raise CliError(f"{prompt}: nothing to choose from.")
@@ -214,10 +248,21 @@ class Console:
214
248
  def confirm(self, prompt: str, default: bool) -> bool:
215
249
  """Ask a yes/no question.
216
250
 
251
+ Parameters
252
+ ----------
253
+ prompt
254
+ The question.
255
+ default
256
+ The answer an empty reply gives.
257
+
258
+ Returns
259
+ -------
260
+ The answer.
261
+
217
262
  Raises
218
263
  ------
219
264
  KeyboardInterrupt
220
- If the user cancels.
265
+ The user cancels.
221
266
  """
222
267
  answer: object = questionary.confirm(prompt, default=default, style=PROMPT_STYLE).ask()
223
268
  if not isinstance(answer, bool):
@@ -235,26 +280,25 @@ class Console:
235
280
 
236
281
  Parameters
237
282
  ----------
238
- prompt : str
283
+ prompt
239
284
  The question.
240
- default : str, optional
285
+ default
241
286
  Text the input starts with.
242
- validate : Validator | None, optional
287
+ validate
243
288
  Raises ``ValueError`` for an invalid answer; its message is shown
244
289
  under the input until the answer changes.
245
- suggestions : Sequence[str], optional
290
+ suggestions
246
291
  Values listed under the input while they match what is typed.
247
292
  Any other value can still be entered.
248
293
 
249
294
  Returns
250
295
  -------
251
- str
252
- The answer.
296
+ The answer.
253
297
 
254
298
  Raises
255
299
  ------
256
300
  KeyboardInterrupt
257
- If the user cancels.
301
+ The user cancels.
258
302
  """
259
303
 
260
304
  def _verdict(value: str) -> bool | str:
@@ -28,13 +28,18 @@ class Interaction(FrozenModel):
28
28
 
29
29
  Attributes
30
30
  ----------
31
- can_prompt : bool
31
+ can_prompt
32
32
  Stdin is a terminal and ``--yes`` was not given.
33
- consent : bool
33
+ consent
34
34
  ``--yes`` was given: every declared consent is granted.
35
- declared : frozenset[str]
35
+ declared
36
36
  The keys of the consents the running command declares; only these
37
37
  can be asked for.
38
+
39
+ Methods
40
+ -------
41
+ resolve
42
+ Return the interaction for a run, from ``--yes`` and the terminal.
38
43
  """
39
44
 
40
45
  can_prompt: bool
@@ -43,7 +48,19 @@ class Interaction(FrozenModel):
43
48
 
44
49
  @classmethod
45
50
  def resolve(cls, yes: bool, declared: frozenset[str] = frozenset()) -> Interaction:
46
- """Return the interaction for a run, from ``--yes`` and the terminal."""
51
+ """Return the interaction for a run, from ``--yes`` and the terminal.
52
+
53
+ Parameters
54
+ ----------
55
+ yes
56
+ Whether ``--yes`` was given.
57
+ declared
58
+ The keys of the consents the running command declares.
59
+
60
+ Returns
61
+ -------
62
+ The interaction every question and consent of the run follows.
63
+ """
47
64
  return cls(can_prompt=sys.stdin.isatty() and not yes, consent=yes, declared=declared)
48
65
 
49
66
 
@@ -56,14 +73,19 @@ class Consent(FrozenModel):
56
73
 
57
74
  Attributes
58
75
  ----------
59
- key : str
76
+ key
60
77
  Stable identifier.
61
- when : str
78
+ when
62
79
  When the command asks for it and what it allows, for ``--questions``.
63
- safe_default : bool | None
80
+ safe_default
64
81
  The answer when nobody can be asked and ``--yes`` was not given, and
65
82
  the prompt's default. ``None`` means only ``--yes`` or a person can
66
83
  give it.
84
+
85
+ Methods
86
+ -------
87
+ ask
88
+ Return whether the run has this consent.
67
89
  """
68
90
 
69
91
  key: str = Field(min_length=1)
@@ -75,19 +97,23 @@ class Consent(FrozenModel):
75
97
 
76
98
  Parameters
77
99
  ----------
78
- console : Console
100
+ console
79
101
  Where to ask.
80
- interaction : Interaction
102
+ interaction
81
103
  The run's interaction.
82
- message : str
104
+ message
83
105
  The question to ask, saying exactly what will happen.
84
106
 
107
+ Returns
108
+ -------
109
+ Whether the run has this consent.
110
+
85
111
  Raises
86
112
  ------
87
113
  DeclarationError
88
- If the running command does not declare this consent.
114
+ The running command does not declare this consent.
89
115
  CliError
90
- If nobody can be asked, ``--yes`` was not given, and the consent
116
+ Nobody can be asked, ``--yes`` was not given, and the consent
91
117
  has no safe default.
92
118
  """
93
119
  if self.key not in interaction.declared:
@@ -128,27 +128,61 @@ class Condition(FrozenModel):
128
128
 
129
129
  Attributes
130
130
  ----------
131
- key : str
131
+ key
132
132
  An earlier question's key, an option's ``dest``, or a fact.
133
- is_in : tuple[str | bool, ...]
133
+ is_in
134
134
  The values that satisfy the condition.
135
+
136
+ Methods
137
+ -------
138
+ holds
139
+ Return whether the context's value is one of ``is_in``.
140
+ describe
141
+ Return the condition as text.
135
142
  """
136
143
 
137
144
  key: str
138
145
  is_in: tuple[str | bool, ...] = Field(min_length=1)
139
146
 
140
147
  def holds(self, context: Mapping[str, Any]) -> bool:
141
- """Return whether the context's value is one of ``is_in``."""
148
+ """Return whether the context's value is one of ``is_in``.
149
+
150
+ Parameters
151
+ ----------
152
+ context
153
+ The values conditions see: options, answers and facts, by key.
154
+
155
+ Returns
156
+ -------
157
+ Whether the condition holds.
158
+ """
142
159
  return self.key in context and context[self.key] in self.is_in
143
160
 
144
161
  def describe(self) -> str:
145
- """Return the condition as text, e.g. ``source_type is files``."""
162
+ """Return the condition as text, e.g. ``source_type is files``.
163
+
164
+ Returns
165
+ -------
166
+ The condition as text.
167
+ """
146
168
  values = " or ".join(str(value).lower() for value in self.is_in)
147
169
  return f"{self.key} is {values}"
148
170
 
149
171
 
150
172
  def when(key: str, *values: str | bool) -> Condition:
151
- """Return a condition: ``key`` is one of ``values``."""
173
+ """Return a condition: ``key`` is one of ``values``.
174
+
175
+ Parameters
176
+ ----------
177
+ key
178
+ An earlier question's key, an option's ``dest``, or a fact.
179
+ values
180
+ The values that satisfy the condition.
181
+
182
+ Returns
183
+ -------
184
+ The condition.
185
+ """
152
186
  return Condition(key=key, is_in=values)
153
187
 
154
188
 
@@ -157,57 +191,68 @@ class Question(FrozenModel):
157
191
 
158
192
  Attributes
159
193
  ----------
160
- key : str
194
+ key
161
195
  Answer key, in snake_case; the flag is ``--`` plus the key with dashes.
162
- section : str
196
+ section
163
197
  Interview section and help group.
164
- kind : QuestionKind
198
+ kind
165
199
  How the question is answered.
166
- prompt : str
200
+ prompt
167
201
  Terminal prompt. For ``list`` and ``pairs`` it names one item; for
168
202
  ``per_item`` it may use ``{item}``.
169
- help : str
203
+ help
170
204
  What the answer means; the flag's help.
171
- choices : tuple[str, ...]
205
+ choices
172
206
  Fixed choices of a ``select``, ``multiselect`` or ``per_item`` question.
173
- choices_from : str | None
207
+ choices_from
174
208
  Dynamic choices from the interview's ``choices`` source of that name,
175
209
  after any fixed ones (per item for ``per_item``).
176
- flag_choices_from : str | None
210
+ flag_choices_from
177
211
  Further values the flag accepts that the prompt does not offer.
178
- items_from : str | None
212
+ items_from
179
213
  The ``choices`` source listing a ``per_item`` question's items.
180
- labels : dict[str, str]
214
+ labels
181
215
  How choices are shown.
182
- default : str | bool | int | None
216
+ default
183
217
  The answer when nobody is asked, and the prompt's starting value. A
184
218
  string may reference earlier text or select answers (``{name}``) and,
185
219
  for ``per_item``, ``{item}``.
186
- default_from : str | None
220
+ default_from
187
221
  A dynamic default from the interview's ``defaults`` source instead.
188
- required : bool
222
+ required
189
223
  The answer has no safe default: a run that cannot prompt fails
190
224
  without the flag.
191
- validator : Validator | None
225
+ validator
192
226
  Checks every answer, at the prompt and from the flag.
193
- metavar : str | None
227
+ metavar
194
228
  The flag's value placeholder in help.
195
- prompted : bool
229
+ prompted
196
230
  Whether the terminal interview asks it; ``False`` for settings only
197
231
  set by flag.
198
- custom : str | None
232
+ custom
199
233
  The custom kind of a ``custom`` question.
200
- suggestions_from : str | None
234
+ suggestions_from
201
235
  A ``choices`` source of suggested values for a free-text answer:
202
236
  listed under the input in a terminal and by ``--questions``, never
203
237
  enforced.
204
- group : str | None
238
+ group
205
239
  A group from ``Interview.groups`` an assistant may ask as one
206
240
  bundled question ("keep these defaults?").
207
- when_all : tuple[Condition, ...]
241
+ when_all
208
242
  Asked only when every condition holds.
209
- when_any : tuple[Condition, ...]
243
+ when_any
210
244
  Asked only when at least one condition holds, if any are declared.
245
+ flag
246
+ The flag answering this question.
247
+
248
+ Methods
249
+ -------
250
+ applies
251
+ Return whether the question is asked, given the context so far.
252
+ describe_conditions
253
+ Return when the question applies, as text.
254
+ placeholders
255
+ Return the ``{name}`` placeholders of a string default.
211
256
  """
212
257
 
213
258
  key: str = Field(pattern=r"^[a-z][a-z0-9_]*$")
@@ -239,6 +284,7 @@ class Question(FrozenModel):
239
284
 
240
285
  @field_serializer("validator")
241
286
  def _validator_name(self, validator: Validator | None) -> str | None:
287
+ """Serialize a validator as its function name."""
242
288
  return None if validator is None else getattr(validator, "__name__", "validator")
243
289
 
244
290
  @model_validator(mode="after")
@@ -304,20 +350,40 @@ class Question(FrozenModel):
304
350
  return self
305
351
 
306
352
  def applies(self, context: Mapping[str, Any]) -> bool:
307
- """Return whether the question is asked, given the context so far."""
353
+ """Return whether the question is asked, given the context so far.
354
+
355
+ Parameters
356
+ ----------
357
+ context
358
+ The values conditions see: options, answers and facts, by key.
359
+
360
+ Returns
361
+ -------
362
+ Whether the question is asked.
363
+ """
308
364
  return all(c.holds(context) for c in self.when_all) and (
309
365
  not self.when_any or any(c.holds(context) for c in self.when_any)
310
366
  )
311
367
 
312
368
  def describe_conditions(self) -> str:
313
- """Return when the question applies, as text."""
369
+ """Return when the question applies, as text.
370
+
371
+ Returns
372
+ -------
373
+ The conditions, joined with "and" and "or".
374
+ """
314
375
  parts = [c.describe() for c in self.when_all]
315
376
  if self.when_any:
316
377
  parts.append(" or ".join(c.describe() for c in self.when_any))
317
378
  return " and ".join(parts)
318
379
 
319
380
  def placeholders(self) -> list[str]:
320
- """Return the ``{name}`` placeholders of a string default."""
381
+ """Return the ``{name}`` placeholders of a string default.
382
+
383
+ Returns
384
+ -------
385
+ The placeholder names; empty if the default is not a string.
386
+ """
321
387
  return _fields(self.default) if isinstance(self.default, str) else []
322
388
 
323
389
 
@@ -347,11 +413,11 @@ class CustomKind(FrozenModel):
347
413
 
348
414
  Attributes
349
415
  ----------
350
- flag_form : str
416
+ flag_form
351
417
  How one flag value is written, for help and ``--questions``.
352
- parse : Callable[[list[str]], Any]
418
+ parse
353
419
  Turns the flag's values into the answer; raises ``CliError``.
354
- prompt : Callable[[Console], Any]
420
+ prompt
355
421
  Asks for the answer in a terminal, validating as it goes.
356
422
  """
357
423
 
@@ -365,24 +431,35 @@ class Interview(FrozenModel):
365
431
 
366
432
  Attributes
367
433
  ----------
368
- questions : tuple[Question, ...]
434
+ questions
369
435
  The questions, in the order they are asked.
370
- consents : tuple[Consent, ...]
436
+ consents
371
437
  The confirmations the command may ask for while it runs.
372
- choices : dict[str, ChoiceSource]
438
+ choices
373
439
  Dynamic choice, item and suggestion sources, by name.
374
- defaults : dict[str, DefaultSource]
440
+ defaults
375
441
  Dynamic default sources, by name.
376
- offline : frozenset[str]
442
+ offline
377
443
  The choice sources that are local and cheap: ``--questions`` lists
378
444
  their values and only names the others.
379
- facts : Facts | None
445
+ facts
380
446
  Facts derived from the answers and options, for conditions.
381
- custom_kinds : dict[str, CustomKind]
447
+ custom_kinds
382
448
  The custom kinds the questions use, by name.
383
- groups : dict[str, str]
449
+ groups
384
450
  Bundled question groups, by name, each with what it covers in one
385
451
  line.
452
+ consent_keys
453
+ The keys of the declared consents.
454
+
455
+ Methods
456
+ -------
457
+ add_arguments
458
+ Add one flag per question to a parser, grouped by section.
459
+ run
460
+ Answer every applicable question from its flag, a prompt, or its default.
461
+ document
462
+ Return the interview as the document ``--questions`` prints.
386
463
  """
387
464
 
388
465
  questions: tuple[Question, ...] = ()
@@ -459,7 +536,13 @@ class Interview(FrozenModel):
459
536
  return frozenset(consent.key for consent in self.consents)
460
537
 
461
538
  def add_arguments(self, parser: argparse.ArgumentParser) -> None:
462
- """Add one flag per question to ``parser``, grouped by section."""
539
+ """Add one flag per question to ``parser``, grouped by section.
540
+
541
+ Parameters
542
+ ----------
543
+ parser
544
+ The command's argument parser.
545
+ """
463
546
  sections: dict[str, argparse._ArgumentGroup] = {} # pyright: ignore[reportPrivateUsage]
464
547
  for question in self.questions:
465
548
  if question.section not in sections:
@@ -494,24 +577,23 @@ class Interview(FrozenModel):
494
577
 
495
578
  Parameters
496
579
  ----------
497
- console : Console
580
+ console
498
581
  Where to ask.
499
- interaction : Interaction
582
+ interaction
500
583
  Whether the run may prompt.
501
- flag_values : Mapping[str, Any]
584
+ flag_values
502
585
  The parsed flags, by question key; ``None`` or ``[]`` if not given.
503
- options : Mapping[str, Any]
586
+ options
504
587
  The command's option values, which conditions may test.
505
588
 
506
589
  Returns
507
590
  -------
508
- dict[str, Any]
509
- The answers of the questions that apply, by key.
591
+ The answers of the questions that apply, by key.
510
592
 
511
593
  Raises
512
594
  ------
513
595
  CliError
514
- If a flag answers a question that does not apply, a value fails
596
+ A flag answers a question that does not apply, a value fails
515
597
  validation, or a run that cannot prompt misses a required answer.
516
598
  """
517
599
  asker = _Asker(self, console, interaction.can_prompt)
@@ -543,10 +625,14 @@ class Interview(FrozenModel):
543
625
 
544
626
  Parameters
545
627
  ----------
546
- command_line : str
628
+ command_line
547
629
  How the command is invoked, e.g. ``mytool deploy``.
548
- options : Sequence[Mapping[str, Any]]
630
+ options
549
631
  The command's plain options, described.
632
+
633
+ Returns
634
+ -------
635
+ The document: the questions, consents and options, with how an assistant asks them.
550
636
  """
551
637
  return {
552
638
  "version": QUESTIONS_FORMAT_VERSION,
@@ -629,10 +715,8 @@ class _Asker:
629
715
  return self._custom(question, flag_value)
630
716
 
631
717
  def unprompted(self, question: Question, answers: Mapping[str, Any]) -> Any:
632
- """Answer a question the interview never asks and no flag answered.
633
-
634
- It takes its default, resolved like any other; a collection is empty.
635
- """
718
+ """Answer a question the interview never asks and no flag answered."""
719
+ # It takes its default, resolved like any other; a collection is empty.
636
720
  if question.kind in ("list", "multiselect"):
637
721
  return []
638
722
  if question.kind in ("pairs", "per_item"):
@@ -690,9 +774,11 @@ class _Asker:
690
774
  ]
691
775
 
692
776
  def _label(self, question: Question) -> Callable[[str], str]:
777
+ """Return how a choice is shown: its label, or itself."""
693
778
  return lambda choice: question.labels.get(choice, choice)
694
779
 
695
780
  def _text(self, question: Question, flag_value: str | None, answers: Mapping[str, Any]) -> str:
781
+ """Answer a ``text`` question from its flag, a prompt, or its default."""
696
782
  if flag_value is not None:
697
783
  return self._checked(question, flag_value)
698
784
  default = self._default(question, answers) or ""
@@ -710,6 +796,7 @@ class _Asker:
710
796
  def _select(
711
797
  self, question: Question, flag_value: str | None, answers: Mapping[str, Any]
712
798
  ) -> str:
799
+ """Answer a ``select`` question from its flag, a prompt, or its default."""
713
800
  if flag_value is not None:
714
801
  allowed = self._flag_choices(question, answers)
715
802
  if flag_value not in allowed:
@@ -738,6 +825,7 @@ class _Asker:
738
825
  def _multiselect(
739
826
  self, question: Question, flag_value: list[str] | None, answers: Mapping[str, Any]
740
827
  ) -> list[str]:
828
+ """Answer a ``multiselect`` question from its flag, a prompt, or every choice."""
741
829
  if flag_value:
742
830
  allowed = self._flag_choices(question, answers)
743
831
  if unknown := sorted(set(flag_value) - set(allowed)):
@@ -756,6 +844,7 @@ class _Asker:
756
844
  return selected
757
845
 
758
846
  def _confirm(self, question: Question, flag_value: bool | None) -> bool:
847
+ """Answer a ``confirm`` question from its flag, a prompt, or its default."""
759
848
  if flag_value is not None:
760
849
  return flag_value
761
850
  default = bool(question.default)
@@ -764,6 +853,7 @@ class _Asker:
764
853
  return default
765
854
 
766
855
  def _int(self, question: Question, flag_value: int | None) -> int | None:
856
+ """Answer an ``int`` question from its flag, a prompt, or its default."""
767
857
  if flag_value is not None:
768
858
  return flag_value
769
859
  default = question.default if isinstance(question.default, int) else None
@@ -781,6 +871,7 @@ class _Asker:
781
871
  def _list(
782
872
  self, question: Question, flag_value: list[str] | None, answers: Mapping[str, Any]
783
873
  ) -> list[str]:
874
+ """Answer a ``list`` question from its flag, a prompt, or an empty list."""
784
875
  if flag_value:
785
876
  return [self._checked(question, value) for value in flag_value]
786
877
  if self._can_prompt:
@@ -796,6 +887,7 @@ class _Asker:
796
887
  return []
797
888
 
798
889
  def _pairs(self, question: Question, flag_value: list[str] | None) -> dict[str, str]:
890
+ """Answer a ``pairs`` question from its flag, a prompt, or an empty dict."""
799
891
  if flag_value:
800
892
  pairs = parse_kv(flag_value, question.flag)
801
893
  return {
@@ -816,6 +908,7 @@ class _Asker:
816
908
  def _per_item(
817
909
  self, question: Question, flag_value: list[str] | None, answers: Mapping[str, Any]
818
910
  ) -> dict[str, str]:
911
+ """Answer a ``per_item`` question: one value for each item of its source."""
819
912
  items = self._source(question.items_from, answers, None)
820
913
  supplied = parse_kv(flag_value, question.flag)
821
914
  if unknown := sorted(set(supplied) - set(items)):
@@ -830,6 +923,7 @@ class _Asker:
830
923
  def _per_item_answer(
831
924
  self, question: Question, item: str, flag_value: str | None, answers: Mapping[str, Any]
832
925
  ) -> str:
926
+ """Answer a ``per_item`` question for one item."""
833
927
  label = f"{question.flag} {item}=..."
834
928
  if flag_value is not None:
835
929
  return self._checked(question, flag_value, label)
@@ -852,6 +946,7 @@ class _Asker:
852
946
  return default
853
947
 
854
948
  def _custom(self, question: Question, flag_value: list[str] | None) -> Any:
949
+ """Answer a ``custom`` question with its kind's parser or prompt."""
855
950
  kind = self._interview.custom_kinds[str(question.custom)]
856
951
  if flag_value:
857
952
  return kind.parse(flag_value)
@@ -19,14 +19,44 @@ _BYTE_SIZE = re.compile(r"\d+[kmgt]?b?")
19
19
 
20
20
 
21
21
  def non_empty(value: str) -> str:
22
- """Reject a blank answer."""
22
+ """Reject a blank answer.
23
+
24
+ Parameters
25
+ ----------
26
+ value
27
+ The answer as typed.
28
+
29
+ Returns
30
+ -------
31
+ The answer, unchanged.
32
+
33
+ Raises
34
+ ------
35
+ ValueError
36
+ The answer is blank.
37
+ """
23
38
  if not value.strip():
24
39
  raise ValueError("A value is required.")
25
40
  return value
26
41
 
27
42
 
28
43
  def whole_number(value: str) -> str:
29
- """Accept a whole number, or a blank answer."""
44
+ """Accept a whole number, or a blank answer.
45
+
46
+ Parameters
47
+ ----------
48
+ value
49
+ The answer as typed.
50
+
51
+ Returns
52
+ -------
53
+ The answer, unchanged.
54
+
55
+ Raises
56
+ ------
57
+ ValueError
58
+ The answer is neither blank nor a whole number.
59
+ """
30
60
  stripped = value.strip()
31
61
  if stripped and not stripped.removeprefix("-").isdigit():
32
62
  raise ValueError("Enter a whole number, or leave it blank.")
@@ -34,7 +64,22 @@ def whole_number(value: str) -> str:
34
64
 
35
65
 
36
66
  def byte_size(value: str) -> str:
37
- """Accept a size such as ``512m`` or ``1g``, or a blank answer."""
67
+ """Accept a size such as ``512m`` or ``1g``, or a blank answer.
68
+
69
+ Parameters
70
+ ----------
71
+ value
72
+ The answer as typed.
73
+
74
+ Returns
75
+ -------
76
+ The answer, unchanged.
77
+
78
+ Raises
79
+ ------
80
+ ValueError
81
+ The answer is neither blank nor a size.
82
+ """
38
83
  stripped = value.strip()
39
84
  if stripped and not _BYTE_SIZE.fullmatch(stripped.lower()):
40
85
  raise ValueError("Enter a size such as 512m or 1g, or leave it blank.")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: cli-interview-kit
3
- Version: 0.1.0
3
+ Version: 0.1.2
4
4
  Summary: Python CLIs whose prompts are declared once and answered at the terminal, by flags, or by an AI assistant.
5
5
  Project-URL: Homepage, https://github.com/Northbridge-Capital/cli-interview-kit
6
6
  Project-URL: Source, https://github.com/Northbridge-Capital/cli-interview-kit
@@ -33,8 +33,8 @@ Description-Content-Type: text/markdown
33
33
  # cli-interview-kit
34
34
 
35
35
  [![CI](https://github.com/Northbridge-Capital/cli-interview-kit/actions/workflows/ci.yml/badge.svg)](https://github.com/Northbridge-Capital/cli-interview-kit/actions/workflows/ci.yml)
36
- [![PyPI](https://img.shields.io/pypi/v/cli-interview-kit)](https://pypi.org/project/cli-interview-kit/)
37
- [![Python](https://img.shields.io/pypi/pyversions/cli-interview-kit)](https://pypi.org/project/cli-interview-kit/)
36
+ [![PyPI](https://img.shields.io/pypi/v/cli-interview-kit?style=flat)](https://pypi.org/project/cli-interview-kit/)
37
+ [![Python](https://img.shields.io/pypi/pyversions/cli-interview-kit?style=flat)](https://pypi.org/project/cli-interview-kit/)
38
38
  [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](https://github.com/Northbridge-Capital/cli-interview-kit/blob/main/LICENSE)
39
39
 
40
40
  Build Python command-line tools whose prompts are declared once and answered in three ways:
@@ -0,0 +1,17 @@
1
+ cli_interview_kit/__init__.py,sha256=HeH9HsAOKBR6rZrkuCDmF7mRbvsBuzxdwLZkSCzOH9k,1609
2
+ cli_interview_kit/_help.py,sha256=982dNrc-5VxvFlnChPiNbGUQgT_5LHr21neH8Zv_bC8,4388
3
+ cli_interview_kit/_model.py,sha256=TlDkN5v5DY9OqGShc1HEAWFEG4c2zIuMEgGdkiSFVpY,463
4
+ cli_interview_kit/_prompts.py,sha256=Gno16q0fAtUqI15A0Du_MG2oGZ9RVVBhYBp9TNFAUNQ,2853
5
+ cli_interview_kit/_suggest.py,sha256=CT5D2iQGPS_RtTv38TCCzk1Zl11Tz2JNQYvtSQsGo8k,6445
6
+ cli_interview_kit/app.py,sha256=N9uaksD5XbTBdZO_EYgfhYPu7JtUez4X-DsOTanQjLM,9314
7
+ cli_interview_kit/command.py,sha256=5uJ_2nm9Z87waFpuvWtH7mBXMQukEGSXbkzik-CEnjo,6117
8
+ cli_interview_kit/console.py,sha256=zEmfK2F9k8Ac6IocGIOwaSunBaDaHPjHAc-SkJKAGmc,9683
9
+ cli_interview_kit/errors.py,sha256=jNys-p3K0bVUxtLIhbIBvMHCy-vdeaUlqlk_O-_PiHM,702
10
+ cli_interview_kit/interaction.py,sha256=PO9-0t548lh14HfMRQltR05hQhxQJsTtZhottyh_uUg,4153
11
+ cli_interview_kit/interview.py,sha256=CgEDtpkJ2zJumXDftZmxFFzuFQG5ndPlX8LCLQLaA_E,39306
12
+ cli_interview_kit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
+ cli_interview_kit/validators.py,sha256=uapleOXQ5QbcXzPfPi99hjEFDkjeTselNeHq3u9brYw,2345
14
+ cli_interview_kit-0.1.2.dist-info/METADATA,sha256=tFguhf28_IoIPWgWJUwzLMRe9e6CPiMn-bB71ggz8xU,10480
15
+ cli_interview_kit-0.1.2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
16
+ cli_interview_kit-0.1.2.dist-info/licenses/LICENSE,sha256=omg-klCAZJHC5HKL1tynLFBkmFb6gsysszTxvhElGXs,1076
17
+ cli_interview_kit-0.1.2.dist-info/RECORD,,
@@ -1,17 +0,0 @@
1
- cli_interview_kit/__init__.py,sha256=HeH9HsAOKBR6rZrkuCDmF7mRbvsBuzxdwLZkSCzOH9k,1609
2
- cli_interview_kit/_help.py,sha256=982dNrc-5VxvFlnChPiNbGUQgT_5LHr21neH8Zv_bC8,4388
3
- cli_interview_kit/_model.py,sha256=Glk_sFtYanK6sG7EsbxBEx4xmzX5-ewA_rNhPO_oyDI,462
4
- cli_interview_kit/_prompts.py,sha256=E9GrWWcTqQzwZDaG3BWwtLtfRXGu6m3EeQqcrsOQASU,2646
5
- cli_interview_kit/_suggest.py,sha256=B_PBl5l0S6lUH6BepGtSyI3KLuQ51X4OsSxKafm46BA,6793
6
- cli_interview_kit/app.py,sha256=2sxXeXqO5jcmIQTFrpPHieXYpP-LNdm2WYTsD88Vb0M,8705
7
- cli_interview_kit/command.py,sha256=7sPHcWV0l5ZmyycGeBGcbuABOptaSyJny36aluNch-A,6114
8
- cli_interview_kit/console.py,sha256=3XD1yRl0rKj1IPPewwC3u-PDg6H63t60ZqAyUW_7ISg,9251
9
- cli_interview_kit/errors.py,sha256=jNys-p3K0bVUxtLIhbIBvMHCy-vdeaUlqlk_O-_PiHM,702
10
- cli_interview_kit/interaction.py,sha256=5SqpFm69xUSAa0VsxSpVHsSZpfvYpQH6aebd1Y5n_vw,3688
11
- cli_interview_kit/interview.py,sha256=eZsjLYPA3rWGAPLtSh7_YTJXf-kaRgdtpQc_LMFkXFc,37105
12
- cli_interview_kit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
- cli_interview_kit/validators.py,sha256=2M8HM_0ix5JsJZuCoKpVkvZyf2pQKN4flSipHE9d3UA,1717
14
- cli_interview_kit-0.1.0.dist-info/METADATA,sha256=lVPIW8k3vJf84cJnY26pLhEMDGEDJiVajK8ZJcFxLmo,10458
15
- cli_interview_kit-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
16
- cli_interview_kit-0.1.0.dist-info/licenses/LICENSE,sha256=omg-klCAZJHC5HKL1tynLFBkmFb6gsysszTxvhElGXs,1076
17
- cli_interview_kit-0.1.0.dist-info/RECORD,,