Skip to content

topmark.cli.console package index

topmark / cli / console

Console runtime support for the TopMark CLI.

This package contains the concrete console implementations, protocol types, color-resolution helpers, and small runtime utilities used by CLI commands to print user-facing output.

Responsibilities: - Define the framework-agnostic console protocol used by commands. - Provide the Click-backed console implementation and a stdlib fallback. - Resolve terminal color behavior from CLI flags, environment, and output mode. - Expose small runtime helpers such as active-console resolution and terminal width inspection.

This package is intentionally distinct from topmark.presentation, which owns human-facing report preparation and pure TEXT / MARKDOWN rendering.

ClickStyleKwargs

Bases: TypedDict

Documented subset of keyword arguments accepted by click.style().

Console

Console(*, enable_color=True, out=None, err=None)

Bases: ConsoleProtocol

Program-output console, independent from the logger.

Parameters:

Name Type Description Default
enable_color bool

If True, enables ANSI color codes in the output. Otherwise, all output is plain text.

True
out TextIO | None

The text stream to use for standard output. Defaults to sys.stdout.

None
err TextIO | None

The text stream to use for error output. Defaults to sys.stderr.

None

Attributes:

Name Type Description
enable_color bool

Whether to emit ANSI color codes.

out TextIO | None

Stream for standard output (defaults to sys.stdout).

err TextIO | None

Stream for error output (defaults to sys.stderr).

Source code in src/topmark/cli/console/click_console.py
def __init__(
    self,
    *,
    enable_color: bool = True,
    out: TextIO | None = None,
    err: TextIO | None = None,
) -> None:
    self.enable_color = enable_color
    self.out = out or sys.stdout
    self.err = err or sys.stderr

print

print(text='', *, nl=True)

Write a message to stdout.

Parameters:

Name Type Description Default
text str

Message text.

''
nl bool

If True, append a newline.

True
Source code in src/topmark/cli/console/click_console.py
def print(self, text: str = "", *, nl: bool = True) -> None:
    """Write a message to stdout.

    Args:
        text: Message text.
        nl: If True, append a newline.
    """
    click.echo(text, nl=nl, file=self.out, color=self.enable_color)

warn

warn(text, *, nl=True)

Write a warning message to stderr.

Parameters:

Name Type Description Default
text str

Warning text.

required
nl bool

If True, append a newline.

True
Source code in src/topmark/cli/console/click_console.py
def warn(self, text: str, *, nl: bool = True) -> None:
    """Write a warning message to stderr.

    Args:
        text: Warning text.
        nl: If True, append a newline.
    """
    click.secho(text, nl=nl, file=self.err, color=self.enable_color, fg="yellow")

error

error(text, *, nl=True)

Write an error message to stderr.

Parameters:

Name Type Description Default
text str

Error text.

required
nl bool

If True, append a newline.

True
Source code in src/topmark/cli/console/click_console.py
def error(self, text: str, *, nl: bool = True) -> None:
    """Write an error message to stderr.

    Args:
        text: Error text.
        nl: If True, append a newline.
    """
    click.secho(text, nl=nl, file=self.err, color=self.enable_color, fg="bright_red")

ColorMode

Bases: str, Enum

User intent for colorized terminal output.

Attributes:

Name Type Description
AUTO

Enable color only when appropriate (typically when stdout is a TTY).

ALWAYS

Force-enable color regardless of TTY status.

NEVER

Disable color entirely.

Typical usage
  • Parse --color=auto|always|never as ColorMode.
  • Pass the parsed value to resolve_color_mode() along with the current output format (e.g., "json" or "ndjson") to obtain a final bool indicating whether to emit ANSI styles.
Example

resolve_color_mode(color_mode_override=ColorMode.AUTO, output_format=None) True # on an interactive terminal resolve_color_mode(color_mode_override=ColorMode.AUTO, output_format="json") False # machine-readable formats are always colorless

ConsoleProtocol

Bases: Protocol

Minimal behavioral protocol for user-facing CLI console output.

Implementations may be backed by Click, Rich, or plain stdlib streams. The protocol intentionally stays small so commands depend only on core output behavior, not on framework-specific details. Console instances are created during CLI state initialization and passed explicitly to commands and emitters; this protocol does not imply ownership of global stdout/stderr.

print

print(text='', *, nl=True)

Write a message to stdout.

Source code in src/topmark/cli/console/protocols.py
def print(self, text: str = "", *, nl: bool = True) -> None:
    """Write a message to stdout."""
    ...

warn

warn(text, *, nl=True)

Write a warning message to stderr.

Source code in src/topmark/cli/console/protocols.py
def warn(self, text: str, *, nl: bool = True) -> None:
    """Write a warning message to stderr."""
    ...

error

error(text, *, nl=True)

Write an error message to stderr.

Source code in src/topmark/cli/console/protocols.py
def error(self, text: str, *, nl: bool = True) -> None:
    """Write an error message to stderr."""
    ...

StdConsole

StdConsole(*, enable_color=False, out=None, err=None)

Bases: ConsoleProtocol

Simple console implementation backed by stdlib text streams.

Parameters:

Name Type Description Default
enable_color bool

Ignored for this implementation. Present only to keep the constructor shape aligned with the Click-backed console.

False
out TextIO | None

Stream for normal output. Defaults to sys.stdout.

None
err TextIO | None

Stream for warning/error output. Defaults to sys.stderr.

None
Source code in src/topmark/cli/console/standard_console.py
def __init__(
    self, *, enable_color: bool = False, out: TextIO | None = None, err: TextIO | None = None
) -> None:
    self.enable_color: bool = enable_color
    self.out: TextIO = out or sys.stdout
    self.err: TextIO = err or sys.stderr

print

print(text='', *, nl=True)

Write a message to stdout.

Source code in src/topmark/cli/console/standard_console.py
def print(self, text: str = "", *, nl: bool = True) -> None:
    """Write a message to stdout."""
    self.out.write(text + ("\n" if nl else ""))

warn

warn(text, *, nl=True)

Write a warning message to stderr.

Source code in src/topmark/cli/console/standard_console.py
def warn(self, text: str, *, nl: bool = True) -> None:
    """Write a warning message to stderr."""
    self.err.write(text + ("\n" if nl else ""))

error

error(text, *, nl=True)

Write an error message to stderr.

Source code in src/topmark/cli/console/standard_console.py
def error(self, text: str, *, nl: bool = True) -> None:
    """Write an error message to stderr."""
    self.err.write(text + ("\n" if nl else ""))

resolve_color_mode

resolve_color_mode(
    *,
    color_mode_override,
    output_format,
    stdout_isatty=None,
)

Determine whether color output should be enabled.

Decision precedence
  1. Machine-readable formats: If output_format is "json" or "ndjson", return False.
  2. CLI override: If color_mode_override is ALWAYS → True; if NEVER → False.
  3. Environment:
    • FORCE_COLOR (set and not equal to "0") → True
    • NO_COLOR (set to any value) → False
  4. Auto: If none of the above decide, return stdout.isatty().

Parameters:

Name Type Description Default
color_mode_override ColorMode | None

Parsed ColorMode value from --color; None means "not provided".

required
output_format str | None

Structured output mode; "json" or "ndjson" suppress color.

required
stdout_isatty bool | None

Optional override for TTY detection. When None, the function calls sys.stdout.isatty() and falls back to False on error.

None

Returns:

Type Description
bool

True if ANSI color should be enabled; False otherwise.

Examples:

>>> resolve_color_mode(color_mode_override=ColorMode.NEVER, output_format=None)
False
>>> resolve_color_mode(color_mode_override=None, output_format="ndjson")
False
>>> resolve_color_mode(color_mode_override=None, output_format=None, stdout_isatty=True)
True
Source code in src/topmark/cli/console/color.py
def resolve_color_mode(
    *,
    color_mode_override: ColorMode | None,
    output_format: str | None,
    stdout_isatty: bool | None = None,
) -> bool:
    """Determine whether color output should be enabled.

    Decision precedence:
        1. **Machine-readable formats**: If `output_format` is `"json"` or `"ndjson"`, return False.
        2. **CLI override**: If `color_mode_override` is `ALWAYS` → True; if `NEVER` → False.
        3. **Environment**:
            - `FORCE_COLOR` (set and not equal to `"0"`) → True
            - `NO_COLOR` (set to any value) → False
        4. **Auto**: If none of the above decide, return `stdout.isatty()`.

    Args:
        color_mode_override: Parsed `ColorMode` value from `--color`;
            `None` means "not provided".
        output_format: Structured output mode; `"json"` or `"ndjson"` suppress color.
        stdout_isatty: Optional override for TTY detection. When `None`, the function
            calls `sys.stdout.isatty()` and falls back to `False` on error.

    Returns:
        True if ANSI color should be enabled; False otherwise.

    Examples:
        >>> resolve_color_mode(color_mode_override=ColorMode.NEVER, output_format=None)
        False
        >>> resolve_color_mode(color_mode_override=None, output_format="ndjson")
        False
        >>> resolve_color_mode(color_mode_override=None, output_format=None, stdout_isatty=True)
        True
    """
    # 1) Machine-readable formats and Markdown never use color
    if output_format and output_format.lower() in {"json", "ndjson", "markdown"}:
        return False

    # 2) CLI overrides
    if color_mode_override == ColorMode.ALWAYS:
        return True
    if color_mode_override == ColorMode.NEVER:
        return False

    # 3) Env overrides
    force_color: str | None = os.getenv("FORCE_COLOR")
    if force_color and force_color != "0":
        return True
    if os.getenv("NO_COLOR") is not None:
        return False

    # 4) Auto: TTY?
    if stdout_isatty is None:
        try:
            stdout_isatty = sys.stdout.isatty()
        except OSError:
            stdout_isatty = False
    return bool(stdout_isatty)

get_console_line_width

get_console_line_width(*, default=80, max_width=100)

Return a safe line width for human-facing console rendering.

Parameters:

Name Type Description Default
default int

Fallback terminal width when no terminal size is available.

80
max_width int

Upper bound applied to wide terminals to keep output readable.

100

Returns:

Type Description
int

The smaller of the detected terminal width and max_width. If terminal

int

size detection fails, default is used.

Source code in src/topmark/cli/console/utils.py
def get_console_line_width(
    *,
    default: int = 80,
    max_width: int = 100,
) -> int:
    """Return a safe line width for human-facing console rendering.

    Args:
        default: Fallback terminal width when no terminal size is available.
        max_width: Upper bound applied to wide terminals to keep output readable.

    Returns:
        The smaller of the detected terminal width and `max_width`. If terminal
        size detection fails, `default` is used.
    """
    try:
        columns, _ = shutil.get_terminal_size(fallback=(default, 24))
    except OSError:
        columns: int = default
    return min(columns, max_width)

Immediate children in this package

topmark.cli.console.click_console
Click-backed console implementation for TopMark CLI output.
topmark.cli.console.color
Color-resolution helpers for TopMark CLI console output.
topmark.cli.console.protocols
Framework-agnostic console protocol for user-facing CLI output.
topmark.cli.console.standard_console
Stdlib-based console implementation used outside Click contexts.
topmark.cli.console.utils
Small terminal-layout helpers for CLI console output.