Skip to content

Mixins

Feature mixins used internally by pyclifer's group and context classes. Exposed publicly for advanced subclassing.

EventsMixin

Lets a group attach handlers to named lifecycle events with on() and call them with emit(). Handlers run in registration order, a plain string that is not a framework event raises ValueError from both on() and emit(), and an exception raised by a handler propagates. See the Lifecycle events guide.

pyclifer.EventsMixin

Mixin that lets a group attach handlers to named lifecycle events.

Handlers run in registration order. An exception raised by a handler propagates to the caller of emit(); nothing is swallowed.

Source code in src/pyclifer/core/mixins/events.py
class EventsMixin:
    """Mixin that lets a group attach handlers to named lifecycle events.

    Handlers run in registration order. An exception raised by a handler
    propagates to the caller of emit(); nothing is swallowed.
    """

    def __init__(self, *args: Any, **kwargs: Any) -> None:
        """Initialize the handler registry then chain to the next class.

        Args:
            *args: Positional arguments for the parent class.
            **kwargs: Keyword arguments for the parent class.
        """
        self._event_handlers: dict[str, list[EventHandler]] = {}
        super().__init__(*args, **kwargs)

    @staticmethod
    def _check_event(event: str) -> None:
        """Accept an Event object or a framework event name, reject any other string."""
        if not isinstance(event, Event) and event not in EVENTS:
            valid = ", ".join(sorted(EVENTS))
            raise ValueError(
                f"Unknown event '{event}'. Valid events: {valid}. "
                f"To define your own, use Event('{event}')."
            )

    def on(self, event: str, handler: EventHandler | None = None) -> Any:
        """Attach a handler to an event, or return a decorator when handler is omitted.

        Args:
            event: An Event object, or the plain name of a framework event.
            handler: The function to call when the event is emitted.

        Returns:
            The handler when given, otherwise a decorator that registers the
            decorated function and returns it unchanged.

        Raises:
            ValueError: When event is a plain string that is not a framework event.
        """
        self._check_event(event)

        def register(function: EventHandler) -> EventHandler:
            """Add the function to the handlers of the event."""
            self._event_handlers.setdefault(event, []).append(function)
            return function

        if handler is None:
            return register
        return register(handler)

    def emit(self, event: str, ctx: click_extra.Context) -> list[Any]:
        """Call every handler attached to an event, in registration order.

        Args:
            event: An Event object, or the plain name of a framework event.
            ctx: The Click context passed to each handler.

        Returns:
            The values returned by the handlers, in the order they ran.

        Raises:
            ValueError: When event is a plain string that is not a framework event.
        """
        self._check_event(event)
        return [handler(ctx) for handler in self._event_handlers.get(event, [])]

__init__(*args, **kwargs)

Initialize the handler registry then chain to the next class.

Parameters:

Name Type Description Default
*args Any

Positional arguments for the parent class.

()
**kwargs Any

Keyword arguments for the parent class.

{}
Source code in src/pyclifer/core/mixins/events.py
def __init__(self, *args: Any, **kwargs: Any) -> None:
    """Initialize the handler registry then chain to the next class.

    Args:
        *args: Positional arguments for the parent class.
        **kwargs: Keyword arguments for the parent class.
    """
    self._event_handlers: dict[str, list[EventHandler]] = {}
    super().__init__(*args, **kwargs)

on(event, handler=None)

Attach a handler to an event, or return a decorator when handler is omitted.

Parameters:

Name Type Description Default
event str

An Event object, or the plain name of a framework event.

required
handler EventHandler | None

The function to call when the event is emitted.

None

Returns:

Type Description
Any

The handler when given, otherwise a decorator that registers the

Any

decorated function and returns it unchanged.

Raises:

Type Description
ValueError

When event is a plain string that is not a framework event.

Source code in src/pyclifer/core/mixins/events.py
def on(self, event: str, handler: EventHandler | None = None) -> Any:
    """Attach a handler to an event, or return a decorator when handler is omitted.

    Args:
        event: An Event object, or the plain name of a framework event.
        handler: The function to call when the event is emitted.

    Returns:
        The handler when given, otherwise a decorator that registers the
        decorated function and returns it unchanged.

    Raises:
        ValueError: When event is a plain string that is not a framework event.
    """
    self._check_event(event)

    def register(function: EventHandler) -> EventHandler:
        """Add the function to the handlers of the event."""
        self._event_handlers.setdefault(event, []).append(function)
        return function

    if handler is None:
        return register
    return register(handler)

emit(event, ctx)

Call every handler attached to an event, in registration order.

Parameters:

Name Type Description Default
event str

An Event object, or the plain name of a framework event.

required
ctx Context

The Click context passed to each handler.

required

Returns:

Type Description
list[Any]

The values returned by the handlers, in the order they ran.

Raises:

Type Description
ValueError

When event is a plain string that is not a framework event.

Source code in src/pyclifer/core/mixins/events.py
def emit(self, event: str, ctx: click_extra.Context) -> list[Any]:
    """Call every handler attached to an event, in registration order.

    Args:
        event: An Event object, or the plain name of a framework event.
        ctx: The Click context passed to each handler.

    Returns:
        The values returned by the handlers, in the order they ran.

    Raises:
        ValueError: When event is a plain string that is not a framework event.
    """
    self._check_event(event)
    return [handler(ctx) for handler in self._event_handlers.get(event, [])]

Event

A named lifecycle event. It is a string, so it compares equal to its name. The framework defines its own events; plugins and applications create theirs with Event("myplugin.ready"), which needs no registration.

pyclifer.Event

Bases: str

A named lifecycle event.

An Event is a string, so it compares equal to its name and works as a dict key. The framework defines its own events; plugins and applications create theirs with Event("myplugin.ready") and share the object, which needs no prior registration.

Source code in src/pyclifer/core/events.py
class Event(str):
    """A named lifecycle event.

    An Event is a string, so it compares equal to its name and works as a dict key.
    The framework defines its own events; plugins and applications create theirs with
    Event("myplugin.ready") and share the object, which needs no prior registration.
    """

GlobalOptionsMixin

Propagates options from a parent group to all child commands and subgroups at registration time.

  • Options marked is_global=True are added as real subcommand parameters — visible in help and forwarded to each callback.
  • The help follows the application. A group that prints plain help (use_rich_help=False) switches the rich-click commands it receives to Click's help, along with everything they hold.
  • A group takes a propagated option only if it wants it. The callback of a subgroup receives a propagated global option when it declares the parameter (or **kwargs); def ops(): works and simply does not see it. An option the group declares itself is always passed, and a leaf command must accept every global option, since it is forwarded to its callback.
  • A global option has one environment variable: the one of the root group. For an application named myapp with --region, every command reads MYAPP_REGION; the variable built from the path of the command (MYAPP_LEAF_REGION) is not read. The help of each command shows the variable that is read, with use_rich_help on or off. An envvar= given to the option is used instead.
  • A global option is parsed where it is written. myapp --region eu leaf gives eu to the group that declares the option, not to leaf, which parses its own copy and keeps its default. Write myapp leaf --region eu for the subcommand to receive it. This holds for a required=True option too: myapp --token T leaf fails with a missing option on leaf, while myapp leaf --token T works.
  • Options marked context=True (non-global) with show_in_subcommand_help=True are injected as display-only copies into subcommand help under a dedicated Context Options panel. These copies have expose_value=False and required=False so they never interfere with subcommand argument parsing or callbacks. They reach commands at any depth, whatever the order in which groups and commands are registered. The panel title is drawn by the Rich help; with use_rich_help=False the option is listed with the other options of the command.

pyclifer.GlobalOptionsMixin

Mixin that propagates global options to subcommands.

Source code in src/pyclifer/core/mixins/cli.py
class GlobalOptionsMixin:
    """Mixin that propagates global options to subcommands."""

    @staticmethod
    def _get_context_option_display_copy(
        opt: click_extra.Parameter, panel_name: str
    ) -> click_extra.Parameter:
        """Create a display-only copy of a context option for subcommand help panels.

        The copy is configured so it appears in a dedicated help panel but is
        never parsed into callback kwargs and never blocks execution when absent.

        Args:
            opt: The original context option to copy.
            panel_name: The panel label to set on the copy.

        Returns:
            A shallow copy with expose_value=False, required=False,
            context=False, and panel set to panel_name. It is marked with
            context_display_copy so that a group holding it can hand it on.
        """
        display = copy.copy(opt)
        display.expose_value = False
        display.required = False
        if hasattr(display, "context"):
            display.context = False
        display.panel = panel_name
        display.context_display_copy = True
        return display

    @staticmethod
    def _rebuild_help_cache(cmd: click_extra.Command) -> None:
        """Make the help of a command list the options added to it after its construction.

        click-extra commands (cloup.OptionGroupMixin) keep the arguments, option groups and
        ungrouped options in lists built once. An option appended to params later is parsed
        but never listed in the help unless those lists are rebuilt. A command without them,
        such as a plain Click command, is left alone.

        Args:
            cmd: The command whose parameters changed.
        """
        if hasattr(cmd, "_group_params") and hasattr(cmd, "ungrouped_options"):
            arguments, option_groups, ungrouped_options = cmd._group_params(cmd.params)
            cmd.arguments = arguments
            cmd.option_groups = option_groups
            cmd.ungrouped_options = ungrouped_options

    @staticmethod
    def _let_group_ignore_propagated(cmd: click_extra.Command, names: list[str]) -> None:
        """Keep a group from being called with a propagated option its callback cannot take.

        The option is parsed by the group like any parameter and Click then calls the callback
        with every parsed value, so a group written as `def ops():` failed with a TypeError as
        soon as the application had a global option. The callback of a group is wrapped, once,
        by a function that drops the propagated options the callback does not accept. An option
        the group declares itself is never dropped, so a real mismatch is still reported.

        Args:
            cmd: The command that was just given the options. Only a group is concerned.
            names: Names of the options that were propagated to it.
        """
        if not hasattr(cmd, "commands") or cmd.callback is None:
            return
        propagated = getattr(cmd, "_propagated_option_names", None)
        if propagated is not None:  # already wrapped: the wrapper reads this set when called
            propagated.update(names)
            return
        original = cmd.callback
        try:
            accepted = inspect.signature(original).parameters
        except (TypeError, ValueError):  # a signature that cannot be read: leave it as it is
            return
        if any(param.kind is inspect.Parameter.VAR_KEYWORD for param in accepted.values()):
            return
        cmd._propagated_option_names = set(names)

        @functools.wraps(original)
        def callback(*args: Any, **kwargs: Any) -> Any:
            """Call the original callback without the propagated options it does not take."""
            for name in cmd._propagated_option_names - accepted.keys():
                kwargs.pop(name, None)
            return original(*args, **kwargs)

        cmd.callback = callback

    def _propagate_global_options(
        self, cmd: click_extra.Command, global_options: list[click_extra.Parameter]
    ) -> None:
        """Recursively propagate global options to a command and its subcommands.

        Args:
            cmd: The command to receive the options.
            global_options: The global options to inject.
        """
        if hasattr(cmd, "params"):
            existing_param_names = {param.name for param in cmd.params}
            added = []
            for opt in global_options:
                if opt.name not in existing_param_names:
                    cmd.params.append(opt)
                    added.append(opt.name)
            if added:
                self._rebuild_help_cache(cmd)
                self._let_group_ignore_propagated(cmd, added)

        # If the command is a group, recursively apply to its currently registered subcommands
        if hasattr(cmd, "commands"):
            for subcommand in cmd.commands.values():
                self._propagate_global_options(subcommand, global_options)

    def _propagate_context_options(
        self,
        cmd: click_extra.Command,
        context_options: list[click_extra.Parameter],
        panel_name: str,
    ) -> None:
        """Recursively inject display-only copies of context options into a command tree.

        Each copy is configured so it renders in the dedicated help panel but
        never interferes with argument parsing or callback signatures.

        Args:
            cmd: Root of the command tree to receive the display copies.
            context_options: Original context options from the root group.
            panel_name: Label for the rich_help_panel on each display copy.
        """
        if hasattr(cmd, "params"):
            existing_names = {p.name for p in cmd.params}
            for opt in context_options:
                if opt.name not in existing_names:
                    cmd.params.append(self._get_context_option_display_copy(opt, panel_name))

            self._rebuild_help_cache(cmd)

        if hasattr(cmd, "commands") and cmd.commands:
            for subcommand in cmd.commands.values():
                self._propagate_context_options(subcommand, context_options, panel_name)

    # noinspection PyUnresolvedReferences
    def add_command(self, cmd: click_extra.Command, name: str | None = None, **kwargs: Any) -> None:
        """Register a subcommand and inject global and context options.

        Args:
            cmd: The command to add.
            name: The name to register the command with.
            **kwargs: Additional arguments passed to the parent method.
        """
        # 0. An application that asked for plain help gets plain help from every command in it,
        # including the rich-click ones that group() and command() build.
        if has_plain_help(self):  # type: ignore[arg-type]
            make_help_plain(cmd)

        # 1. Find global options attached to this group
        global_options = [
            param for param in getattr(self, "params", []) if getattr(param, "is_global", False)
        ]

        # 2. Inject them recursively into the subcommand and all its descendants
        if global_options:
            self._propagate_global_options(cmd, global_options)

        # 3. Find context=True (non-global) options marked for subcommand help
        context_options = [
            param
            for param in getattr(self, "params", [])
            if getattr(param, "context", False)
            and not getattr(param, "is_global", False)
            and getattr(param, "show_in_subcommand_help", True)
        ]
        if context_options:
            panel_name = getattr(self, "_context_options_panel", CONTEXT_OPTIONS_PANEL)
            self._propagate_context_options(cmd, context_options, panel_name)

        # 4. A group attached to its parent before being filled holds display copies, not the
        # real options (those have context=False): hand them on, under the panel they carry,
        # to the commands added to it afterwards.
        for param in getattr(self, "params", []):
            if getattr(param, "context_display_copy", False):
                self._propagate_context_options(cmd, [param], param.panel)

        super().add_command(cmd, name, **kwargs)  # type: ignore

add_command(cmd, name=None, **kwargs)

Register a subcommand and inject global and context options.

Parameters:

Name Type Description Default
cmd Command

The command to add.

required
name str | None

The name to register the command with.

None
**kwargs Any

Additional arguments passed to the parent method.

{}
Source code in src/pyclifer/core/mixins/cli.py
def add_command(self, cmd: click_extra.Command, name: str | None = None, **kwargs: Any) -> None:
    """Register a subcommand and inject global and context options.

    Args:
        cmd: The command to add.
        name: The name to register the command with.
        **kwargs: Additional arguments passed to the parent method.
    """
    # 0. An application that asked for plain help gets plain help from every command in it,
    # including the rich-click ones that group() and command() build.
    if has_plain_help(self):  # type: ignore[arg-type]
        make_help_plain(cmd)

    # 1. Find global options attached to this group
    global_options = [
        param for param in getattr(self, "params", []) if getattr(param, "is_global", False)
    ]

    # 2. Inject them recursively into the subcommand and all its descendants
    if global_options:
        self._propagate_global_options(cmd, global_options)

    # 3. Find context=True (non-global) options marked for subcommand help
    context_options = [
        param
        for param in getattr(self, "params", [])
        if getattr(param, "context", False)
        and not getattr(param, "is_global", False)
        and getattr(param, "show_in_subcommand_help", True)
    ]
    if context_options:
        panel_name = getattr(self, "_context_options_panel", CONTEXT_OPTIONS_PANEL)
        self._propagate_context_options(cmd, context_options, panel_name)

    # 4. A group attached to its parent before being filled holds display copies, not the
    # real options (those have context=False): hand them on, under the panel they carry,
    # to the commands added to it afterwards.
    for param in getattr(self, "params", []):
        if getattr(param, "context_display_copy", False):
            self._propagate_context_options(cmd, [param], param.panel)

    super().add_command(cmd, name, **kwargs)  # type: ignore

HandleResponseMixin

Auto-wraps commands added via command() or add_command() with returns_response by default (opt out with handle_response=False). handle_response has three values, on a command as well as on a group:

Value Meaning
None (default) Inherit. A command takes its group's setting; a group takes its parent's once attached.
True Enable.
False Opt out. A group set to False protects its whole sub-tree from a parent that handles responses.

Whichever of the sub-group and the application is declared first, a command with no explicit choice is wrapped as soon as its group is attached to an application that handles responses.

pyclifer.HandleResponseMixin

Mixin that adds automatic Response dispatch to Click groups.

When handle_response_by_default is True (set via @app_group(handle_response=True)), every command registered through @group.command() or group.add_command() automatically wraps its return value: if the function returns a Response, it is printed using the output format stored in ctx.meta['pyclifer.output_format'].

The per-command handle_response kwarg always takes precedence over the group-level default.

Source code in src/pyclifer/core/mixins/response.py
class HandleResponseMixin:
    """Mixin that adds automatic Response dispatch to Click groups.

    When handle_response_by_default is True (set via
    @app_group(handle_response=True)), every command registered through
    @group.command() or group.add_command() automatically wraps its return
    value: if the function returns a Response, it is printed using the output
    format stored in ctx.meta['pyclifer.output_format'].

    The per-command handle_response kwarg always takes precedence over the
    group-level default.
    """

    handle_response_by_default: bool = False
    handle_response_opted_out: bool = False
    output_format_default: str = "table"

    def parse_args(self, ctx: click_extra.Context, args: list[str]) -> list[str]:
        """Parse the arguments, answering a Click error in a structured format.

        Args:
            ctx: The context of this group.
            args: The arguments to parse.

        Returns:
            The remaining arguments, as returned by Click.
        """
        try:
            # noinspection PyUnresolvedReferences
            return super().parse_args(ctx, args)
        except click_extra.ClickException as error:
            # On a bare call click-extra swallows an error raised by an event handler,
            # then Click shows the help. Report the handler error rather than lose it.
            pending = ctx.meta.pop(PENDING_ERROR_META, None)
            if pending is None or pending is error:
                self._answer_click_exception(ctx, error)
                raise
            self._answer_click_exception(ctx, pending)
            pending.show()
            raise

    def invoke(self, ctx: click_extra.Context) -> Any:
        """Invoke the group, answering a Click error in a structured format.

        Args:
            ctx: The context of this group.

        Returns:
            The value returned by the invoked command.
        """
        try:
            # noinspection PyUnresolvedReferences
            return super().invoke(ctx)
        except click_extra.ClickException as error:
            self._answer_click_exception(ctx, error)
            raise

    def _answer_click_exception(
        self, ctx: click_extra.Context, error: click_extra.ClickException
    ) -> None:
        """Answer a Click error with a Response and exit, or return to leave it to Click.

        Only acts when response handling is enabled and the output format is
        structured (json or yaml). The usual message stays on stderr for a person
        at a terminal; the Response goes to stdout for a program.

        Args:
            ctx: The context in which the error was raised.
            error: The Click error (usage error or any other ClickException).
        """
        if not self.handle_response_by_default:
            return
        root = ctx.find_root()
        default_format = getattr(root.command, "output_format_default", self.output_format_default)
        output_format = root.meta.get("pyclifer.output_format", default_format)
        if output_format not in _STRUCTURED_FORMATS:
            return

        # Lazy imports to break circular dependencies: these modules import the mixins.
        from pyclifer.core.context import BaseContext
        from pyclifer.core.output import Response

        error_type = "usage_error" if isinstance(error, click_extra.UsageError) else "click_error"
        # A UsageError carries the context of the command that failed, which is more
        # precise than the context of the group that caught it.
        failing_ctx = getattr(error, "ctx", None) or ctx
        response = Response(
            success=False,
            message=error.format_message(),
            error_code=error.exit_code,
            data={"results": [], "error_type": error_type, "command": failing_ctx.command_path},
        )
        error.show()
        output_ctx = ctx.obj if isinstance(ctx.obj, BaseContext) else BaseContext()
        output_ctx.output_format = output_format
        output_ctx.print_result_based_on_format(response)
        ctx.exit(error.exit_code)

    def command(
        self, *args: Any, handle_response: bool | None = None, **kwargs: Any
    ) -> Callable[..., Any]:
        """Override Click.Group.command to automatically handle Response objects."""
        explicit = handle_response is not None or self.handle_response_opted_out
        if handle_response is None:
            handle_response = self.handle_response_by_default
        # noinspection PyUnresolvedReferences
        decorator = super().command(*args, **kwargs)
        if not handle_response and not explicit:
            # No choice was made: leave the command undecided, so that a parent group
            # that handles responses can still wrap it when this group is attached.
            return decorator
        if not handle_response:
            # Mark the raw function as decided *before* calling decorator(f)
            # so that our add_command() override sees the flag when Click
            # calls self.add_command() internally during decorator(f).
            def wrapped_noop(f):
                """Pass-through decorator that marks the command as opted out."""
                setattr(f, _PYCLIFER_RESPONSE_DECIDED, True)
                return decorator(f)

            return wrapped_noop

        def wrapped(f):
            """Wrapper for commands that automatically handles Response objects."""
            # Lazy: decorators imports classes, which imports this module (circular import).
            from pyclifer.core.decorators import returns_response

            wrapped_f = returns_response(f)
            setattr(wrapped_f, _PYCLIFER_RESPONSE_DECIDED, True)
            return decorator(wrapped_f)

        return wrapped

    def add_command(self, cmd: Any, name: str | None = None, **kwargs: Any) -> None:
        """Override Click.Group.add_command to propagate response handling.

        Extra keyword arguments, such as a cloup section, are passed on to the
        next class in the chain.

        When handle_response_by_default is True:
        - Sub-groups: handle_response_by_default is propagated recursively so
          that all already-registered leaf commands are wrapped and future
          registrations on those groups are also covered.
        - Leaf commands: the callback is wrapped with returns_response directly.

        Commands whose callback carries the _PYCLIFER_RESPONSE_DECIDED flag
        (set by the @group.command() factory path before Click registers the
        command) are left untouched so that explicit handle_response=False
        overrides and already-wrapped functions are both respected.
        """
        if self.handle_response_by_default:
            is_group = getattr(cmd, "commands", None) is not None
            if is_group:
                _log.debug(
                    "HandleResponseMixin.add_command: propagating handle_response "
                    "into sub-group '%s'",
                    cmd.name,
                )
                _apply_handle_response_to_group(cmd)
            else:
                already_decided = cmd.callback is not None and getattr(
                    cmd.callback, _PYCLIFER_RESPONSE_DECIDED, False
                )
                if cmd.callback is not None and not already_decided:
                    # Lazy: decorators imports classes, which imports this module (circular import).
                    from pyclifer.core.decorators import returns_response

                    _log.debug(
                        "HandleResponseMixin.add_command: wrapping '%s' with returns_response",
                        cmd.name,
                    )
                    cmd.callback = returns_response(cmd.callback)
                else:
                    _log.debug(
                        "HandleResponseMixin.add_command: skipping leaf '%s' (already_decided=%s)",
                        cmd.name,
                        already_decided,
                    )
        else:
            _log.debug(
                "HandleResponseMixin.add_command: handle_response_by_default=False, skipping '%s'",
                cmd.name,
            )
        # noinspection PyUnresolvedReferences
        super().add_command(cmd, name=name, **kwargs)

parse_args(ctx, args)

Parse the arguments, answering a Click error in a structured format.

Parameters:

Name Type Description Default
ctx Context

The context of this group.

required
args list[str]

The arguments to parse.

required

Returns:

Type Description
list[str]

The remaining arguments, as returned by Click.

Source code in src/pyclifer/core/mixins/response.py
def parse_args(self, ctx: click_extra.Context, args: list[str]) -> list[str]:
    """Parse the arguments, answering a Click error in a structured format.

    Args:
        ctx: The context of this group.
        args: The arguments to parse.

    Returns:
        The remaining arguments, as returned by Click.
    """
    try:
        # noinspection PyUnresolvedReferences
        return super().parse_args(ctx, args)
    except click_extra.ClickException as error:
        # On a bare call click-extra swallows an error raised by an event handler,
        # then Click shows the help. Report the handler error rather than lose it.
        pending = ctx.meta.pop(PENDING_ERROR_META, None)
        if pending is None or pending is error:
            self._answer_click_exception(ctx, error)
            raise
        self._answer_click_exception(ctx, pending)
        pending.show()
        raise

invoke(ctx)

Invoke the group, answering a Click error in a structured format.

Parameters:

Name Type Description Default
ctx Context

The context of this group.

required

Returns:

Type Description
Any

The value returned by the invoked command.

Source code in src/pyclifer/core/mixins/response.py
def invoke(self, ctx: click_extra.Context) -> Any:
    """Invoke the group, answering a Click error in a structured format.

    Args:
        ctx: The context of this group.

    Returns:
        The value returned by the invoked command.
    """
    try:
        # noinspection PyUnresolvedReferences
        return super().invoke(ctx)
    except click_extra.ClickException as error:
        self._answer_click_exception(ctx, error)
        raise

command(*args, handle_response=None, **kwargs)

Override Click.Group.command to automatically handle Response objects.

Source code in src/pyclifer/core/mixins/response.py
def command(
    self, *args: Any, handle_response: bool | None = None, **kwargs: Any
) -> Callable[..., Any]:
    """Override Click.Group.command to automatically handle Response objects."""
    explicit = handle_response is not None or self.handle_response_opted_out
    if handle_response is None:
        handle_response = self.handle_response_by_default
    # noinspection PyUnresolvedReferences
    decorator = super().command(*args, **kwargs)
    if not handle_response and not explicit:
        # No choice was made: leave the command undecided, so that a parent group
        # that handles responses can still wrap it when this group is attached.
        return decorator
    if not handle_response:
        # Mark the raw function as decided *before* calling decorator(f)
        # so that our add_command() override sees the flag when Click
        # calls self.add_command() internally during decorator(f).
        def wrapped_noop(f):
            """Pass-through decorator that marks the command as opted out."""
            setattr(f, _PYCLIFER_RESPONSE_DECIDED, True)
            return decorator(f)

        return wrapped_noop

    def wrapped(f):
        """Wrapper for commands that automatically handles Response objects."""
        # Lazy: decorators imports classes, which imports this module (circular import).
        from pyclifer.core.decorators import returns_response

        wrapped_f = returns_response(f)
        setattr(wrapped_f, _PYCLIFER_RESPONSE_DECIDED, True)
        return decorator(wrapped_f)

    return wrapped

add_command(cmd, name=None, **kwargs)

Override Click.Group.add_command to propagate response handling.

Extra keyword arguments, such as a cloup section, are passed on to the next class in the chain.

When handle_response_by_default is True: - Sub-groups: handle_response_by_default is propagated recursively so that all already-registered leaf commands are wrapped and future registrations on those groups are also covered. - Leaf commands: the callback is wrapped with returns_response directly.

Commands whose callback carries the _PYCLIFER_RESPONSE_DECIDED flag (set by the @group.command() factory path before Click registers the command) are left untouched so that explicit handle_response=False overrides and already-wrapped functions are both respected.

Source code in src/pyclifer/core/mixins/response.py
def add_command(self, cmd: Any, name: str | None = None, **kwargs: Any) -> None:
    """Override Click.Group.add_command to propagate response handling.

    Extra keyword arguments, such as a cloup section, are passed on to the
    next class in the chain.

    When handle_response_by_default is True:
    - Sub-groups: handle_response_by_default is propagated recursively so
      that all already-registered leaf commands are wrapped and future
      registrations on those groups are also covered.
    - Leaf commands: the callback is wrapped with returns_response directly.

    Commands whose callback carries the _PYCLIFER_RESPONSE_DECIDED flag
    (set by the @group.command() factory path before Click registers the
    command) are left untouched so that explicit handle_response=False
    overrides and already-wrapped functions are both respected.
    """
    if self.handle_response_by_default:
        is_group = getattr(cmd, "commands", None) is not None
        if is_group:
            _log.debug(
                "HandleResponseMixin.add_command: propagating handle_response "
                "into sub-group '%s'",
                cmd.name,
            )
            _apply_handle_response_to_group(cmd)
        else:
            already_decided = cmd.callback is not None and getattr(
                cmd.callback, _PYCLIFER_RESPONSE_DECIDED, False
            )
            if cmd.callback is not None and not already_decided:
                # Lazy: decorators imports classes, which imports this module (circular import).
                from pyclifer.core.decorators import returns_response

                _log.debug(
                    "HandleResponseMixin.add_command: wrapping '%s' with returns_response",
                    cmd.name,
                )
                cmd.callback = returns_response(cmd.callback)
            else:
                _log.debug(
                    "HandleResponseMixin.add_command: skipping leaf '%s' (already_decided=%s)",
                    cmd.name,
                    already_decided,
                )
    else:
        _log.debug(
            "HandleResponseMixin.add_command: handle_response_by_default=False, skipping '%s'",
            cmd.name,
        )
    # noinspection PyUnresolvedReferences
    super().add_command(cmd, name=name, **kwargs)

OutputFormatMixin

Dispatches Response objects to the appropriate formatter (JSON / YAML / Table / Rich / Raw) based on --output-format stored in ctx.meta.

pyclifer.OutputFormatMixin

Provide methods for printing error messages and results based on a specified format.

This mixin expects the inheriting class to have 'console' and 'output_format' attributes. Every result must be a Response with a renderer attached.

Source code in src/pyclifer/core/mixins/output.py
class OutputFormatMixin:
    """Provide methods for printing error messages and results based on a specified format.

    This mixin expects the inheriting class to have 'console' and 'output_format' attributes.
    Every result must be a Response with a renderer attached.
    """

    def print_error_based_on_format(self, exception: Exception) -> None:
        """Format and print an unhandled exception as a structured Response.

        Creates a single-result Response from the exception and dispatches
        it through the normal renderer path using _ExceptionRenderer.

        Args:
            exception: The exception to display.
        """
        result = OperationResult(
            success=False,
            item=type(exception).__name__,
            message=str(exception),
            error_code=ExitCode.ERROR,
            data={"traceback": traceback.format_exc()},
        )
        response = Response.from_results(
            [result], message=str(exception), renderer=_ExceptionRenderer()
        )
        self.print_result_based_on_format(response)

    @staticmethod
    def _materialise_stream(response: Response) -> None:
        """Consume a streaming Response generator and re-evaluate its fields.

        Replaces data["stream"] with data["results"], then re-computes
        success, error_code, and message from the materialized list using
        the renderer's message methods.

        Args:
            response: A Response carrying a generator in data["stream"].
        """
        assert response.renderer is not None, "_materialise_stream requires a renderer"
        items = list(response.data.pop("stream"))
        failed = [r for r in items if not r.success]
        response.success = not bool(failed)
        response.error_code = failed[0].error_code if failed else 0
        response.message = (
            response.renderer.get_success_message(items)
            if not failed
            else response.renderer.get_failure_message(items)
        )
        response.data["results"] = items

    def print_result_based_on_format(self, result: Response, options: dict | None = None) -> None:
        """Print a Response using its renderer.

        Streaming responses (data["stream"] present) are handled via the Live
        context for rich output, or materialized first for all other formats.

        Args:
            result: The Response to print. Must have a renderer attached.
            options: Optional dict with the filter_value key for --output-filter support.

        Raises:
            RuntimeError: When result.renderer is None — a programming error.
        """
        renderer: BaseRenderer = result.renderer or BaseRenderer()
        result.renderer = renderer

        opts: dict = options or {}
        output_format: str | None = getattr(self, "output_format", None)

        if "stream" in result.data:
            if output_format == "rich":
                renderable = renderer.rich_setup()
                items: list = []
                with Live(renderable, console=self.console):  # type: ignore[attr-defined]
                    for item in result.data.pop("stream"):
                        items.append(item)
                        renderer.rich_on_item(item, items)
                result.data["results"] = items
                renderer.rich_summary(result, self.console)  # type: ignore[attr-defined]
                return
            self._materialise_stream(result)
        filter_key: str | None = opts.get("filter_value")

        def _json() -> None:
            serialized = renderer.serialize(result)
            if filter_key:
                self._print_json(self._apply_output_filter(serialized, filter_key))
            else:
                self._print_json(serialized)

        def _yaml() -> None:
            serialized = renderer.serialize(result)
            if filter_key:
                self._print_yaml(self._apply_output_filter(serialized, filter_key))
            else:
                self._print_yaml(serialized)

        dispatch: dict[str, Any] = {
            "json": _json,
            "yaml": _yaml,
            "table": lambda: self.console.print(renderer.table(result)),  # type: ignore[attr-defined]
            "rich": lambda: renderer.rich(result, self.console),  # type: ignore[attr-defined]
            "raw": lambda: self._print_raw_dict(renderer.raw(result), filter_key),
            "text": lambda: self.console.print(renderer.text(result)),  # type: ignore[attr-defined]
        }
        dispatch.get(output_format or "table", dispatch["table"])()

    @staticmethod
    def _resolve_filter_path(data: dict, path: str) -> tuple[Any, bool]:
        """Traverse a dotted path in a nested dict or list.

        Args:
            data: The dict to traverse.
            path: Dotted path — numeric segments are treated as list indices,
                  negative indices are supported (e.g. 'results.-1.id').

        Returns:
            A tuple of (resolved value, found). If the path does not exist,
            found is False and value is None.
        """
        segments = path.split(".")
        node: Any = data
        for segment in segments:
            if isinstance(node, list):
                if not segment.lstrip("-").isdigit():
                    return None, False
                idx = int(segment)
                if idx >= len(node) or idx < -len(node):
                    return None, False
                node = node[idx]
            elif isinstance(node, dict):
                if segment not in node:
                    return None, False
                node = node[segment]
            else:
                return None, False
        return node, True

    def _apply_output_filter(self, serialized: dict, filter_path: str) -> Any:
        """Resolve a dotted filter path in a serialized response, or exit with an error.

        Traverses data["data"] first (the structured payload), then falls back
        to the top-level dict. On failure, prints an error Response and raises
        SystemExit(2).

        Args:
            serialized: Serialized response dict.
            filter_path: Dotted path to resolve (e.g. "results.0.id").

        Returns:
            The resolved value.

        Raises:
            SystemExit: With code 2 when the path cannot be resolved.
        """
        sub = serialized.get("data")
        if isinstance(sub, dict):
            value, found = self._resolve_filter_path(sub, filter_path)
            if found:
                return value

        value, found = self._resolve_filter_path(serialized, filter_path)
        if found:
            return value

        available_keys = sorted(sub.keys() if isinstance(sub, dict) else serialized.keys())
        message = f"filter path '{filter_path}' not found in response."
        err_result = OperationResult(
            success=False,
            item="output-filter",
            message=message,
            error_code=ExitCode.INVALID_INPUT,
            data={"available_keys": available_keys},
        )
        error_response = Response.from_results(
            [err_result], message=message, renderer=_ExceptionRenderer()
        )
        self.print_result_based_on_format(error_response)
        raise SystemExit(2)

    def _print_raw_dict(self, data: dict, filter_key: str | None) -> None:
        """Print a serialized dict as compact JSON, or extract and print a raw value.

        When filter_key is set, the extracted value is printed as-is with no
        re-serialization — suitable for shell scripting and piping.
        When filter_key is None, prints the full dict as compact JSON without
        syntax highlighting.

        Args:
            data: Serialized response dict from renderer.raw().
            filter_key: Key to extract, or None to print the full dict.
        """
        if filter_key:
            self.console.print(self._apply_output_filter(data, filter_key), soft_wrap=True)  # type: ignore[attr-defined]
        else:
            self.console.print(json.dumps(data, cls=_FallbackEncoder), soft_wrap=True)  # type: ignore[attr-defined]

    def _print_json(self, data: Any) -> None:
        """Print a value as syntax-highlighted JSON.

        Accepts any JSON-serializable value — dict, list, str, int, etc.
        Used for both full-response output and filtered single-value output.

        Args:
            data: Value to serialize and display as JSON.
        """
        self.console.print_json(json.dumps(data, cls=_FallbackEncoder))  # type: ignore[attr-defined]

    def _print_yaml(self, data: Any) -> None:
        """Print a value as syntax-highlighted YAML.

        Accepts any YAML-serializable value — dict, list, str, int, etc.
        Used for both full-response output and filtered single-value output.

        Args:
            data: Value to serialize and display as YAML.
        """
        yaml_content = yaml.dump(
            data, Dumper=_FallbackDumper, allow_unicode=True, indent=2, sort_keys=False
        )
        self.console.print(  # type: ignore[attr-defined]
            Syntax(yaml_content, "yaml", theme="ansi_dark"), soft_wrap=True
        )

print_error_based_on_format(exception)

Format and print an unhandled exception as a structured Response.

Creates a single-result Response from the exception and dispatches it through the normal renderer path using _ExceptionRenderer.

Parameters:

Name Type Description Default
exception Exception

The exception to display.

required
Source code in src/pyclifer/core/mixins/output.py
def print_error_based_on_format(self, exception: Exception) -> None:
    """Format and print an unhandled exception as a structured Response.

    Creates a single-result Response from the exception and dispatches
    it through the normal renderer path using _ExceptionRenderer.

    Args:
        exception: The exception to display.
    """
    result = OperationResult(
        success=False,
        item=type(exception).__name__,
        message=str(exception),
        error_code=ExitCode.ERROR,
        data={"traceback": traceback.format_exc()},
    )
    response = Response.from_results(
        [result], message=str(exception), renderer=_ExceptionRenderer()
    )
    self.print_result_based_on_format(response)

print_result_based_on_format(result, options=None)

Print a Response using its renderer.

Streaming responses (data["stream"] present) are handled via the Live context for rich output, or materialized first for all other formats.

Parameters:

Name Type Description Default
result Response

The Response to print. Must have a renderer attached.

required
options dict | None

Optional dict with the filter_value key for --output-filter support.

None

Raises:

Type Description
RuntimeError

When result.renderer is None — a programming error.

Source code in src/pyclifer/core/mixins/output.py
def print_result_based_on_format(self, result: Response, options: dict | None = None) -> None:
    """Print a Response using its renderer.

    Streaming responses (data["stream"] present) are handled via the Live
    context for rich output, or materialized first for all other formats.

    Args:
        result: The Response to print. Must have a renderer attached.
        options: Optional dict with the filter_value key for --output-filter support.

    Raises:
        RuntimeError: When result.renderer is None — a programming error.
    """
    renderer: BaseRenderer = result.renderer or BaseRenderer()
    result.renderer = renderer

    opts: dict = options or {}
    output_format: str | None = getattr(self, "output_format", None)

    if "stream" in result.data:
        if output_format == "rich":
            renderable = renderer.rich_setup()
            items: list = []
            with Live(renderable, console=self.console):  # type: ignore[attr-defined]
                for item in result.data.pop("stream"):
                    items.append(item)
                    renderer.rich_on_item(item, items)
            result.data["results"] = items
            renderer.rich_summary(result, self.console)  # type: ignore[attr-defined]
            return
        self._materialise_stream(result)
    filter_key: str | None = opts.get("filter_value")

    def _json() -> None:
        serialized = renderer.serialize(result)
        if filter_key:
            self._print_json(self._apply_output_filter(serialized, filter_key))
        else:
            self._print_json(serialized)

    def _yaml() -> None:
        serialized = renderer.serialize(result)
        if filter_key:
            self._print_yaml(self._apply_output_filter(serialized, filter_key))
        else:
            self._print_yaml(serialized)

    dispatch: dict[str, Any] = {
        "json": _json,
        "yaml": _yaml,
        "table": lambda: self.console.print(renderer.table(result)),  # type: ignore[attr-defined]
        "rich": lambda: renderer.rich(result, self.console),  # type: ignore[attr-defined]
        "raw": lambda: self._print_raw_dict(renderer.raw(result), filter_key),
        "text": lambda: self.console.print(renderer.text(result)),  # type: ignore[attr-defined]
    }
    dispatch.get(output_format or "table", dispatch["table"])()

RichHelpersMixin

Rich console helpers available on the context: panels, rules, status spinners, prompts.

pyclifer.RichHelpersMixin

Provide rich console helper methods for CLI contexts.

This mixin expects the inheriting class to have a 'console' attribute instantiated with a rich.console.Console object.

Source code in src/pyclifer/core/mixins/rich.py
class RichHelpersMixin:
    """Provide rich console helper methods for CLI contexts.

    This mixin expects the inheriting class to have a 'console' attribute
    instantiated with a rich.console.Console object.
    """

    console: Console

    def rich_panel(
        self,
        text: Any,
        title: str | None = None,
        border_style: str | None = None,
        padding: tuple = (0, 1),
        console_print: bool = False,
        fit: bool = False,
    ) -> Panel:
        """Create a rich panel with the given formatting options.

        Args:
            text: The text content or renderable of the panel.
            title: The title of the panel.
            border_style: The border style of the panel.
            padding: The padding of the panel (top/bottom, left/right).
            console_print: If True, prints the panel directly to the console.
            fit: If True, the panel fits its contents.

        Returns:
            The rendered rich panel object.
        """
        panel_class = Panel.fit if fit else Panel
        panel_kwargs: dict[str, Any] = {"renderable": text, "title": title, "padding": padding}
        if border_style is not None:
            panel_kwargs["border_style"] = border_style
        renderer = panel_class(**panel_kwargs)
        if console_print:
            self.console.print(renderer)  # type: ignore
        return renderer

    def display_rule(self, title: str = "", style: str = "blue") -> None:
        """Display a horizontal rule with an optional title.

        Args:
            title: The text to display in the middle of the rule.
            style: The color and style of the rule.
        """
        self.console.print(Rule(title=title, style=style))  # type: ignore

    def show_status(self, message: str = "Processing...", spinner: str = "dots") -> Status:
        """Return a rich status context manager for long-running tasks.

        Args:
            message: The message to display next to the spinner.
            spinner: The type of spinner animation to use.

        Returns:
            Status: A context manager for the status.
        """
        return self.console.status(message, spinner=spinner)  # type: ignore

    def ask_user(
        self,
        question: str,
        default: str | None = None,
        choices: list[str] | None = None,
        password: bool = False,
    ) -> Any:
        """Prompt the user for input.

        Args:
            question: The prompt text to display.
            default: The default value if the user presses enter.
            choices: A list of valid choices to restrict input.
            password: If True, hides the user's input.

        Returns:
            The user's input.
        """
        return Prompt.ask(
            question, default=default, choices=choices, password=password, console=self.console
        )  # type: ignore

    def ask_confirmation(self, question: str, default: bool = False) -> bool:
        """Ask the user a yes or no confirmation question.

        Args:
            question: The prompt text to display.
            default: The default answer if the user presses enter.

        Returns:
            bool: True if the user confirmed, False otherwise.
        """
        return Confirm.ask(question, default=default, console=self.console)  # type: ignore

rich_panel(text, title=None, border_style=None, padding=(0, 1), console_print=False, fit=False)

Create a rich panel with the given formatting options.

Parameters:

Name Type Description Default
text Any

The text content or renderable of the panel.

required
title str | None

The title of the panel.

None
border_style str | None

The border style of the panel.

None
padding tuple

The padding of the panel (top/bottom, left/right).

(0, 1)
console_print bool

If True, prints the panel directly to the console.

False
fit bool

If True, the panel fits its contents.

False

Returns:

Type Description
Panel

The rendered rich panel object.

Source code in src/pyclifer/core/mixins/rich.py
def rich_panel(
    self,
    text: Any,
    title: str | None = None,
    border_style: str | None = None,
    padding: tuple = (0, 1),
    console_print: bool = False,
    fit: bool = False,
) -> Panel:
    """Create a rich panel with the given formatting options.

    Args:
        text: The text content or renderable of the panel.
        title: The title of the panel.
        border_style: The border style of the panel.
        padding: The padding of the panel (top/bottom, left/right).
        console_print: If True, prints the panel directly to the console.
        fit: If True, the panel fits its contents.

    Returns:
        The rendered rich panel object.
    """
    panel_class = Panel.fit if fit else Panel
    panel_kwargs: dict[str, Any] = {"renderable": text, "title": title, "padding": padding}
    if border_style is not None:
        panel_kwargs["border_style"] = border_style
    renderer = panel_class(**panel_kwargs)
    if console_print:
        self.console.print(renderer)  # type: ignore
    return renderer

display_rule(title='', style='blue')

Display a horizontal rule with an optional title.

Parameters:

Name Type Description Default
title str

The text to display in the middle of the rule.

''
style str

The color and style of the rule.

'blue'
Source code in src/pyclifer/core/mixins/rich.py
def display_rule(self, title: str = "", style: str = "blue") -> None:
    """Display a horizontal rule with an optional title.

    Args:
        title: The text to display in the middle of the rule.
        style: The color and style of the rule.
    """
    self.console.print(Rule(title=title, style=style))  # type: ignore

show_status(message='Processing...', spinner='dots')

Return a rich status context manager for long-running tasks.

Parameters:

Name Type Description Default
message str

The message to display next to the spinner.

'Processing...'
spinner str

The type of spinner animation to use.

'dots'

Returns:

Name Type Description
Status Status

A context manager for the status.

Source code in src/pyclifer/core/mixins/rich.py
def show_status(self, message: str = "Processing...", spinner: str = "dots") -> Status:
    """Return a rich status context manager for long-running tasks.

    Args:
        message: The message to display next to the spinner.
        spinner: The type of spinner animation to use.

    Returns:
        Status: A context manager for the status.
    """
    return self.console.status(message, spinner=spinner)  # type: ignore

ask_user(question, default=None, choices=None, password=False)

Prompt the user for input.

Parameters:

Name Type Description Default
question str

The prompt text to display.

required
default str | None

The default value if the user presses enter.

None
choices list[str] | None

A list of valid choices to restrict input.

None
password bool

If True, hides the user's input.

False

Returns:

Type Description
Any

The user's input.

Source code in src/pyclifer/core/mixins/rich.py
def ask_user(
    self,
    question: str,
    default: str | None = None,
    choices: list[str] | None = None,
    password: bool = False,
) -> Any:
    """Prompt the user for input.

    Args:
        question: The prompt text to display.
        default: The default value if the user presses enter.
        choices: A list of valid choices to restrict input.
        password: If True, hides the user's input.

    Returns:
        The user's input.
    """
    return Prompt.ask(
        question, default=default, choices=choices, password=password, console=self.console
    )  # type: ignore

ask_confirmation(question, default=False)

Ask the user a yes or no confirmation question.

Parameters:

Name Type Description Default
question str

The prompt text to display.

required
default bool

The default answer if the user presses enter.

False

Returns:

Name Type Description
bool bool

True if the user confirmed, False otherwise.

Source code in src/pyclifer/core/mixins/rich.py
def ask_confirmation(self, question: str, default: bool = False) -> bool:
    """Ask the user a yes or no confirmation question.

    Args:
        question: The prompt text to display.
        default: The default answer if the user presses enter.

    Returns:
        bool: True if the user confirmed, False otherwise.
    """
    return Confirm.ask(question, default=default, console=self.console)  # type: ignore