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)))