Source code for cli_interview_kit.interaction
"""How a run may interact with its user: answers and consents.
``--yes`` and whether stdin is a terminal decide who answers; a pipe never consents by itself.
"""
from __future__ import annotations
import ctypes
import sys
from pydantic import Field
from cli_interview_kit._model import FrozenModel
from cli_interview_kit.console import Console
from cli_interview_kit.errors import CliError, DeclarationError
class Interaction(FrozenModel):
"""Whether a run may prompt, and whether it has blanket consent.
Methods
-------
resolve
Return the interaction for a run, from ``--yes`` and the terminal.
"""
can_prompt: bool = Field(description="Stdin is a terminal and ``--yes`` was not given.")
consent: bool = Field(description="``--yes`` was given: every declared consent is granted.")
declared: frozenset[str] = Field(
description=(
"The keys of the consents the running command declares; only these can be asked for."
)
)
@classmethod
def resolve(cls, yes: bool, declared: frozenset[str]) -> Interaction:
"""Return the interaction for a run, from ``--yes`` and the terminal.
Parameters
----------
yes
Whether ``--yes`` was given.
declared
The keys of the consents the running command declares.
Returns
-------
The interaction every question and consent of the run follows.
"""
return cls(can_prompt=_stdin_is_terminal() and not yes, consent=yes, declared=declared)
def _stdin_is_terminal() -> bool:
"""Whether stdin is a terminal a person types into; Windows calls the ``NUL`` device one too."""
if not sys.stdin.isatty():
return False
if sys.platform != "win32":
return True
import msvcrt
mode = ctypes.c_ulong()
handle = msvcrt.get_osfhandle(sys.stdin.fileno())
return bool(ctypes.windll.kernel32.GetConsoleMode(handle, ctypes.byref(mode)))
[docs]
class Consent(FrozenModel):
"""A confirmation a command may need before it acts.
Declared on the command's ``Interview`` so ``--describe`` lists it: an
assistant describes it to the user first and passes ``--yes`` only once
they agree.
Methods
-------
ask
Return whether the run has this consent.
"""
key: str = Field(min_length=1, description="Stable identifier.")
when: str = Field(
min_length=1,
description="When the command asks for it and what it allows, for ``--describe``.",
)
safe_default: bool | None = Field(
default=None,
description=(
"The answer when nobody can be asked and ``--yes`` was not given, and "
"the prompt's default. ``None`` means only ``--yes`` or a person can "
"give it."
),
)
[docs]
def ask(self, console: Console, interaction: Interaction, message: str) -> bool:
"""Return whether the run has this consent.
Parameters
----------
console
Where to ask.
interaction
The run's interaction.
message
The question to ask, saying exactly what will happen.
Returns
-------
Whether the run has this consent.
Raises
------
DeclarationError
The running command does not declare this consent.
CliError
Nobody can be asked, ``--yes`` was not given, and the consent
has no safe default.
"""
if self.key not in interaction.declared:
raise DeclarationError(
f"Consent '{self.key}' is not declared on the running command's "
"Interview, so --describe cannot list it."
)
if interaction.consent:
return True
if interaction.can_prompt:
return console.confirm(message, default=bool(self.safe_default))
if self.safe_default is not None:
return self.safe_default
raise CliError(f"{message} This needs consent: rerun with --yes.")