Source code for cli_interview_kit.command

"""Commands declared as data: options, an interview, subcommands and a run."""

from __future__ import annotations

import shlex
from collections.abc import Callable
from typing import Any, Literal

from pydantic import Field, model_validator

from cli_interview_kit._model import FrozenModel
from cli_interview_kit.console import Console
from cli_interview_kit.interaction import Interaction
from cli_interview_kit.interview import (
    DOCUMENT_VERSION,
    HOW_TO_ANSWER,
    PROCEDURE,
    RULES,
    Interview,
)

RESERVED_NAMES = frozenset({"help", "debug", "yes", "describe"})
"""Names no option or question may take.

``--help``, ``--yes`` and ``--describe`` are a command's own flags, and
``debug`` is where the app's ``--debug`` lands in the parsed arguments every
command shares. ``--version`` exists only on the app and stores nothing, so
``version`` is free.
"""


[docs] class Option(FrozenModel): """A plain option or positional argument; not an interview question. Options choose what a command does (``--check``, ``--dry-run``) or name what it acts on. Anything the user could be asked belongs in the interview instead. Attributes ---------- flag The option's flag, or its name for a positional. Methods ------- describe Describe the option as ``--describe`` lists it. """ dest: str = Field( pattern=r"^[a-z][a-z0-9_]*$", description=( "The name the value is read by, in snake_case; the flag is ``--`` plus " "the name with dashes." ), ) help: str = Field(min_length=1, description="Help text.") kind: Literal["switch", "value", "append", "positional"] = Field( default="value", description=( "``switch`` is an on/off flag; ``value`` takes one value; ``append`` is " "repeatable; ``positional`` is an argument." ), ) metavar: str | None = Field(default=None, description="Value placeholder in help.") choices: tuple[str, ...] = Field(default=(), description="Allowed values.") nargs: Literal["?", "*", "+"] | None = Field( default=None, description='A positional\'s arity, e.g. ``"*"``.' ) convert: Callable[[str], Any] | None = Field( default=None, description=( "Converts and checks a value; a ``ValueError`` is a usage error that shows its " "message, as a validator's does." ), ) exclusive: str | None = Field( default=None, description="Options sharing this name are mutually exclusive." ) @model_validator(mode="after") def _check_kind(self) -> Option: """Reject settings that do not fit the option's kind.""" if self.nargs is not None and self.kind != "positional": raise ValueError(f"{self.flag}: only a positional takes nargs.") if self.kind == "switch" and (self.choices or self.convert or self.metavar): raise ValueError(f"{self.flag}: a switch takes no value settings.") if self.kind == "positional" and self.exclusive is not None: raise ValueError(f"{self.flag}: a positional cannot be mutually exclusive.") return self @property def flag(self) -> str: """The option's flag, or its name for a positional.""" if self.kind == "positional": return self.dest return "--" + self.dest.replace("_", "-")
[docs] def describe(self) -> dict[str, Any]: """Describe the option as ``--describe`` lists it. Returns ------- The option's flag, kind and help. """ return {"flag": self.flag, "kind": self.kind, "help": self.help}
[docs] class Example(FrozenModel): """A command line that runs a command, shown in ``--help`` and ``--describe``. The app checks every example against the command's parser when it is built, so an example that no longer parses fails at once instead of misleading its reader. Methods ------- shell Return the example as a shell command line. """ argv: tuple[str, ...] = Field( description=( "The arguments after the program and command names, one string each, " 'e.g. ``("--name", "billing")``.' ) ) says: str = Field( min_length=1, max_length=80, description="What the example does, in one sentence." )
[docs] def shell(self, command_line: str) -> str: """Return the example as a shell command line. Parameters ---------- command_line How the command is invoked, e.g. ``mytool deploy``. Returns ------- The command line with the example's arguments quoted for a POSIX shell. """ return " ".join(filter(None, (command_line, shlex.join(self.argv))))
[docs] class Invocation(FrozenModel): """What a command's run function receives.""" console: Console = Field(description="Output and prompts.") interaction: Interaction = Field( description=("Whether the run may prompt and has consent; pass it to ``Consent.ask``.") ) answers: dict[str, Any] = Field( description="The answers of the questions that applied, by key." ) options: dict[str, Any] = Field(description="The options' values, by ``dest``.")
[docs] class Command(FrozenModel): """One command. Attributes ---------- interactive Whether the command has questions or consents. Methods ------- document Return what ``--describe`` prints: everything needed to run the command. """ name: str = Field( pattern=r"^[a-z][a-z0-9-]*$", description="The command's name on the command line." ) help: str = Field(min_length=1, description="One-line help.") options: tuple[Option, ...] = Field(default=(), description="Plain options and positionals.") interview: Interview = Field( default=Interview(), description=("Questions and consents. A command with any gets ``--yes``."), ) run: Callable[[Invocation], None] | None = Field( default=None, description="What the command does; ``None`` for a group of subcommands." ) subcommands: tuple[Command, ...] = Field(default=(), description="Nested commands.") examples: tuple[Example, ...] = Field( default=(), description="Command lines that run the command, checked when the app is built." ) annotations: dict[str, str] = Field( default_factory=dict, description=( "Free-form metadata for the app built on the kit, such as whether an " "assistant may run the command. The kit stores it and includes it in " "``--describe``, but never interprets it; namespace keys by the app, " 'e.g. ``{"myapp.agent": "hand-off"}``.' ), ) @model_validator(mode="after") def _check_names(self) -> Command: """Reject a command that runs nothing, and clashing names.""" if self.run is None and not self.subcommands: raise ValueError(f"Command '{self.name}' has neither a run nor subcommands.") names = [option.dest for option in self.options] names += [question.key for question in self.interview.questions] clashes = sorted({n for n in names if names.count(n) > 1} | (set(names) & RESERVED_NAMES)) if clashes: raise ValueError( f"Command '{self.name}' uses {', '.join(clashes)} more than once or as a " f"reserved name ({', '.join(sorted(RESERVED_NAMES))})." ) commands = [command.name for command in self.subcommands] if duplicated := sorted({n for n in commands if commands.count(n) > 1}): raise ValueError(f"Command '{self.name}' has duplicate subcommands: {duplicated}.") return self @property def interactive(self) -> bool: """Whether the command has questions or consents.""" return bool(self.interview.questions or self.interview.consents)
[docs] def document(self, command_line: str) -> dict[str, Any]: """Return what ``--describe`` prints: everything needed to run the command. Parameters ---------- command_line How the command is invoked, e.g. ``mytool deploy``. Returns ------- The document: the command's help, examples, options and annotations; for a command that asks, also its questions and consents with the procedure an assistant follows. """ # Only a command that asks needs the interview's parts; a plain one stays a few lines. interview: dict[str, Any] = ( { "how_to_answer": HOW_TO_ANSWER, "procedure": list(PROCEDURE), "rules": list(RULES), **self.interview.describe(), } if self.interactive else {} ) return { "version": DOCUMENT_VERSION, "command": f"{command_line} --yes" if self.interactive else command_line, "help": self.help, "examples": [ {"command": example.shell(command_line), "says": example.says} for example in self.examples ], **interview, "options": [option.describe() for option in self.options], "annotations": dict(self.annotations), }