Skip to content

toolr._context

This module provides the Context class, which is passed to every command group function as the first argument.

ConsoleVerbosity

Bases: IntEnum

Console verbosity levels.

__repr__

__repr__() -> str

Return a string representation of the console verbosity.

Source code in python/toolr/_context.py
def __repr__(self) -> str:
    """
    Return a string representation of the console verbosity.
    """
    return self.name.lower()

Context

Bases: Struct

Context object passed to every command group function as the first argument.

prompt

prompt(
    prompt: TextType,
    expected_type: type[bool],
    *,
    default: bool | None = None,
    show_default: bool = True,
) -> bool
prompt(
    prompt: TextType,
    expected_type: type[str],
    *,
    password: bool = True,
    default: str | None = None,
    case_sensitive: bool = True,
) -> str
prompt(
    prompt: TextType,
    expected_type: type[int],
    *,
    choices: list[str] | None = None,
    default: int | None = None,
    show_default: bool = True,
    show_choices: bool = True,
) -> int
prompt(
    prompt: TextType,
    expected_type: type[float],
    *,
    choices: list[str] | None = None,
    default: float | None = None,
    show_default: bool = True,
    show_choices: bool = True,
) -> float
prompt(
    prompt: TextType,
    expected_type: None = None,
    *,
    choices: list[str] | None = None,
    default: None = None,
    case_sensitive: bool = True,
    show_default: bool = True,
    show_choices: bool = True,
) -> str
prompt(
    prompt: TextType,
    expected_type: type[str | int | float | bool]
    | None = None,
    *,
    password: bool = False,
    case_sensitive: bool = True,
    choices: list[str] | None = None,
    default: str | int | float | bool | None = None,
    show_default: bool = True,
    show_choices: bool = True,
) -> str | int | float | bool

Prompt the user for input.

This is a wrapper around rich.prompt.Prompt.ask.

See rich.prompt.Prompt.ask for more details.

Source code in python/toolr/_context.py
def prompt(
    self,
    prompt: TextType,
    expected_type: type[str | int | float | bool] | None = None,
    *,
    password: bool = False,
    case_sensitive: bool = True,
    choices: list[str] | None = None,
    default: str | int | float | bool | None = None,
    show_default: bool = True,
    show_choices: bool = True,
) -> str | int | float | bool:
    """
    Prompt the user for input.

    This is a wrapper around [rich.prompt.Prompt.ask][rich.prompt].

    See [rich.prompt.Prompt.ask][rich.prompt] for more details.
    """
    return self._prompt(
        prompt,
        expected_type,
        password=password,
        case_sensitive=case_sensitive,
        choices=choices,
        default=default,
        show_default=show_default,
        show_choices=show_choices,
    )

print

print(
    *args: ConsoleRenderable | RichCast | str, **kwargs: Any
) -> None

Print to stdout.

This is a wrapper around :func:rich.console.Console.print.

See :func:rich.console.Console.print for more details.

Source code in python/toolr/_context.py
def print(self, *args: Any, **kwargs: Any) -> None:
    """
    Print to stdout.

    This is a wrapper around :func:`rich.console.Console.print`.

    See :func:`rich.console.Console.print` for more details.
    """
    self._console_stdout.print(*args, **kwargs)

debug

debug(*args: Any, **kwargs: Any) -> None

Print debug message to stderr.

This is a wrapper around rich.console.Console.log.

See rich.console.Console.log for more details.

Source code in python/toolr/_context.py
def debug(self, *args: Any, **kwargs: Any) -> None:
    """
    Print debug message to stderr.

    This is a wrapper around [rich.console.Console.log][rich.console.Console.log].

    See [rich.console.Console.log][rich.console.Console.log] for more details.
    """
    if self.verbosity >= ConsoleVerbosity.VERBOSE:
        kwargs.update(style="log-debug", _stack_offset=2)
        self._console_stderr.log(*args, **kwargs)

info

info(*args: Any, **kwargs: Any) -> None

Print info message to stderr.

This is a wrapper around rich.console.Console.log.

See rich.console.Console.log for more details.

Source code in python/toolr/_context.py
def info(self, *args: Any, **kwargs: Any) -> None:
    """
    Print info message to stderr.

    This is a wrapper around [rich.console.Console.log][rich.console.Console.log].

    See [rich.console.Console.log][rich.console.Console.log] for more details.
    """
    if self.verbosity >= ConsoleVerbosity.NORMAL:
        kwargs.update(style="log-info", _stack_offset=2)
        self._console_stderr.log(*args, **kwargs)

warn

warn(*args: Any, **kwargs: Any) -> None

Print warning message to stderr.

This is a wrapper around rich.console.Console.log.

See rich.console.Console.log for more details.

Source code in python/toolr/_context.py
def warn(self, *args: Any, **kwargs: Any) -> None:
    """
    Print warning message to stderr.

    This is a wrapper around [rich.console.Console.log][rich.console.Console.log].

    See [rich.console.Console.log][rich.console.Console.log] for more details.
    """
    kwargs.update(style="log-warning", _stack_offset=2)
    self._console_stderr.log(*args, **kwargs)

error

error(*args: Any, **kwargs: Any) -> None

Print error message to stderr.

This is a wrapper around rich.console.Console.log.

See rich.console.Console.log for more details.

Source code in python/toolr/_context.py
def error(self, *args: Any, **kwargs: Any) -> None:
    """
    Print error message to stderr.

    This is a wrapper around [rich.console.Console.log][rich.console.Console.log].

    See [rich.console.Console.log][rich.console.Console.log] for more details.
    """
    kwargs.update(style="log-error", _stack_offset=2)
    self._console_stderr.log(*args, **kwargs)

exit

exit(
    status: int = 0, message: str | None = None
) -> NoReturn

Exit the command execution.

Source code in python/toolr/_context.py
def exit(self, status: int = 0, message: str | None = None) -> NoReturn:
    """
    Exit the command execution.
    """
    if message is not None:
        if status == 0:
            style = "exit-ok"
        else:
            style = "exit-failure"
        self._console_stderr.print(message, style=style)
    self.parser.exit(status)

run

run(
    *cmdline: str,
    stream_output: bool = True,
    capture_output: bool = False,
    timeout_secs: float | None = None,
    no_output_timeout_secs: float | None = None,
    **kwargs: Any,
) -> CommandResult[str] | CommandResult[bytes]

Run a command with the given arguments.

This is a wrapper around toolr.utils.command.run that provides a simpler interface for command functions.

Parameters:

Name Type Description Default
cmdline str

Command line to run

()
stream_output bool

Whether to stream output to stdout/stderr

True
capture_output bool

Whether to capture output to return

False
timeout_secs float | None

Maximum time to wait for command completion

None
no_output_timeout_secs float | None

Maximum time to wait without output

None
kwargs Any

Additional keyword arguments to pass to toolr.utils.command.run

{}

Returns:

Type Description
CommandResult[str] | CommandResult[bytes]

CommandResult instance.

Source code in python/toolr/_context.py
def run(
    self,
    *cmdline: str,
    stream_output: bool = True,
    capture_output: bool = False,
    timeout_secs: float | None = None,
    no_output_timeout_secs: float | None = None,
    **kwargs: Any,
) -> CommandResult[str] | CommandResult[bytes]:
    """Run a command with the given arguments.

    This is a wrapper around [toolr.utils.command.run][] that provides
    a simpler interface for command functions.

    Args:
        cmdline: Command line to run
        stream_output: Whether to stream output to stdout/stderr
        capture_output: Whether to capture output to return
        timeout_secs: Maximum time to wait for command completion
        no_output_timeout_secs: Maximum time to wait without output
        kwargs: Additional keyword arguments to pass to [toolr.utils.command.run][]

    Returns:
        CommandResult instance.
    """
    self.debug(f"""Running '{" ".join(cmdline)}'""")
    return command.run(
        cmdline,
        stream_output=stream_output,
        capture_output=capture_output,
        timeout_secs=timeout_secs,
        no_output_timeout_secs=no_output_timeout_secs,
        **kwargs,
    )

chdir

chdir(path: str | Path) -> Iterator[Path]

Change the working directory for this context.

Parameters:

Name Type Description Default
path str | Path

The new working directory path

required

Returns:

Type Description
Iterator[Path]

Iterator yielding the new working directory as a Path object

This is a context manager, so it should be used with 'with':

.. code-block:: python

with ctx.chdir("/some/path") as p:
    # Do something in /some/path
    # p is the Path object for /some/path
Source code in python/toolr/_context.py
@contextmanager
def chdir(self, path: str | pathlib.Path) -> Iterator[pathlib.Path]:
    """Change the working directory for this context.

    Args:
        path: The new working directory path

    Returns:
        Iterator yielding the new working directory as a Path object

    This is a context manager, so it should be used with 'with':

    .. code-block:: python

        with ctx.chdir("/some/path") as p:
            # Do something in /some/path
            # p is the Path object for /some/path
    """
    cwd = pathlib.Path.cwd()
    if isinstance(path, str):
        path = pathlib.Path(path)
    try:
        os.chdir(path)
        yield path
    finally:
        if not cwd.exists():
            self.error(f"Unable to change back to path {cwd}")
        else:
            os.chdir(cwd)