Skip to content

topmark.cli.state

topmark / cli / state

Strongly typed Click invocation state for TopMark CLI commands.

TopmarkCliState dataclass

TopmarkCliState(
    *,
    verbosity=0,
    quiet=False,
    output_format=OutputFormat.TEXT,
    color_mode=ColorMode.AUTO,
    color_enabled=False,
    console=(lambda: Console(enable_color=False))(),
    log_level=None,
    prune_pipeline_views=True,
    apply_changes=False,
    write_mode=None,
    resolved_writer_options=None,
    policy=MutablePolicy(),
)

Shared invocation-scoped CLI state stored on Click contexts.

This state object holds the strongly typed human-output/runtime fields that are shared across multiple CLI helpers during a single command invocation.

The extras mapping stores a small number of internal invocation-scoped bridge values shared across CLI helpers.

bootstrap_cli_state

bootstrap_cli_state(ctx)

Create or normalize the typed CLI state stored on ctx.obj.

This is the entrypoint bootstrap helper for the CLI layer. It should be called by the root Click group and by command entrypoints instead of ctx.ensure_object(dict).

Behavior
  • If ctx.obj already contains TopmarkCliState, return it.
  • If ctx.obj is None, create a fresh default state.
  • If ctx.obj is a mapping, lift known typed fields into TopmarkCliState and preserve additional string-keyed values in extras.
  • Otherwise, raise TypeError.

Parameters:

Name Type Description Default
ctx Context

Active Click context.

required

Returns:

Type Description
TopmarkCliState

The bootstrapped typed CLI state.

Raises:

Type Description
TypeError

If ctx.obj is neither None, a mapping, nor TopmarkCliState, or if lifted legacy values have incompatible types.

Source code in src/topmark/cli/state.py
def bootstrap_cli_state(ctx: click.Context) -> TopmarkCliState:
    """Create or normalize the typed CLI state stored on ``ctx.obj``.

    This is the entrypoint bootstrap helper for the CLI layer. It should be
    called by the root Click group and by command entrypoints instead of
    ``ctx.ensure_object(dict)``.

    Behavior:
        - If ``ctx.obj`` already contains ``TopmarkCliState``, return it.
        - If ``ctx.obj`` is ``None``, create a fresh default state.
        - If ``ctx.obj`` is a mapping, lift known typed fields into
          ``TopmarkCliState`` and preserve additional string-keyed values in ``extras``.
        - Otherwise, raise ``TypeError``.

    Args:
        ctx: Active Click context.

    Returns:
        The bootstrapped typed CLI state.

    Raises:
        TypeError: If ``ctx.obj`` is neither ``None``, a mapping, nor
            ``TopmarkCliState``, or if lifted legacy values have incompatible types.
    """
    obj: object = ctx.obj

    if isinstance(obj, TopmarkCliState):
        return obj

    if obj is None:
        state = TopmarkCliState(
            verbosity=0,
            quiet=False,
            output_format=OutputFormat.TEXT,
            color_mode=ColorMode.AUTO,
            color_enabled=False,
            console=Console(enable_color=False),
            log_level=None,
            prune_pipeline_views=True,
            apply_changes=False,
            write_mode=None,
            policy=MutablePolicy(),
            resolved_writer_options=None,
        )
        ctx.obj = state
        return state

    if not is_mapping(obj):
        raise TypeError(f"Unsupported ctx.obj type for TopmarkCliState: {type(obj)!r}")

    extras: dict[str, object] = {}
    for key, value in obj.items():
        if isinstance(key, str):
            extras[key] = value

    output_format_obj: object = extras.pop("output_format", OutputFormat.TEXT)
    color_mode_obj: object = extras.pop("color_mode", ColorMode.AUTO)
    color_enabled_obj: object = extras.pop("color_enabled", False)
    console_obj: object = extras.pop("console", Console(enable_color=False))
    verbosity_obj: object = extras.pop("verbosity", 0)
    quiet_obj: object = extras.pop("quiet", False)
    log_level_obj: object = extras.pop("log_level", None)
    prune_pipeline_views_obj: object = extras.pop("prune_pipeline_views", None)
    apply_changes_obj: object = extras.pop("apply_changes", False)
    write_mode_obj: object = extras.pop("write_mode", None)

    if not isinstance(output_format_obj, OutputFormat):
        raise TypeError("ctx.obj['output_format'] must be an OutputFormat")
    if not isinstance(color_mode_obj, ColorMode):
        raise TypeError("ctx.obj['color_mode'] must be a ColorMode")
    if not isinstance(color_enabled_obj, bool):
        raise TypeError("ctx.obj['color_enabled'] must be a bool")
    if not is_console_protocol(console_obj):
        raise TypeError("ctx.obj['console'] must be a ConsoleProtocol")
    if not isinstance(verbosity_obj, int):
        raise TypeError("ctx.obj['verbosity'] must be an int")
    if not isinstance(quiet_obj, bool):
        raise TypeError("ctx.obj['quiet'] must be a bool")
    if log_level_obj is not None and not isinstance(log_level_obj, int):
        raise TypeError("ctx.obj['log_level'] must be an int | None")
    if prune_pipeline_views_obj is not None and not isinstance(prune_pipeline_views_obj, bool):
        raise TypeError("ctx.obj['prune_pipeline_views'] must be a bool")
    if not isinstance(apply_changes_obj, bool):
        raise TypeError("ctx.obj['apply_changes'] must be a bool")
    if write_mode_obj is not None and not isinstance(write_mode_obj, str):
        raise TypeError("ctx.obj['write_mode'] must be a str | None")

    state = TopmarkCliState(
        verbosity=verbosity_obj,
        quiet=quiet_obj,
        output_format=output_format_obj,
        color_mode=color_mode_obj,
        color_enabled=color_enabled_obj,
        console=console_obj,
        log_level=log_level_obj,
        prune_pipeline_views=True if prune_pipeline_views_obj is None else prune_pipeline_views_obj,
        apply_changes=apply_changes_obj,
        write_mode=write_mode_obj,
        policy=MutablePolicy(),
    )
    ctx.obj = state
    return state

get_cli_state

get_cli_state(ctx)

Return the typed CLI state stored on ctx.obj.

Parameters:

Name Type Description Default
ctx Context

Active Click context.

required

Returns:

Type Description
TopmarkCliState

The typed CLI state.

Raises:

Type Description
TypeError

If ctx.obj is not a TopmarkCliState instance.

Source code in src/topmark/cli/state.py
def get_cli_state(ctx: click.Context) -> TopmarkCliState:
    """Return the typed CLI state stored on ``ctx.obj``.

    Args:
        ctx: Active Click context.

    Returns:
        The typed CLI state.

    Raises:
        TypeError: If ``ctx.obj`` is not a ``TopmarkCliState`` instance.
    """
    obj: object = ctx.obj
    if not isinstance(obj, TopmarkCliState):
        raise TypeError("ctx.obj is not initialized as TopmarkCliState")
    return obj