Skip to content

Module API - Parser

Alt Text

Prefer the top-level package for app code:

from clak import Parser, Argument, Command
# Optional: Arg (positionals), Opt (flags) - Argument still accepts both

Descriptors (Argument, Arg, Opt, SubParser, docstring helpers):

clak.core.descriptors

CLI descriptors: Argument, SubParser, MetaSetting, docstring helpers.

Descriptors are class attributes of a Parser; ParserNode attaches them to argparse at build time. Public names are re-exported from clak.

Arg

Bases: Argument

Optional sugar for a positional argument.

Same *args / **kwargs as :class:Argument, but at least one positional name is required (no leading -). Empty Arg() is rejected; dest-derived flags belong on Opt / Argument. Argument still accepts both positionals and flags.

Source code in clak/core/descriptors.py
class Arg(Argument):
    """Optional sugar for a positional argument.

    Same ``*args`` / ``**kwargs`` as :class:`Argument`, but at least one
    positional name is required (no leading ``-``). Empty ``Arg()`` is
    rejected; dest-derived flags belong on ``Opt`` / ``Argument``.
    ``Argument`` still accepts both positionals and flags.
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        _check_arg_opt_names(self.args, expect_option=False, cls_name="Arg")

ArgParseItem

Bases: _Fn

Base class for argument parser items.

This class represents a generic argument parser item that can be added to an argument parser. It provides common functionality for handling destinations and building parameter dictionaries.

Attributes:

Name Type Description
_destination str

The destination name for the argument value

Source code in clak/core/descriptors.py
class ArgParseItem(_Fn):
    """Base class for argument parser items.

    This class represents a generic argument parser item that can be added to an argument parser.
    It provides common functionality for handling destinations and building parameter dictionaries.

    Attributes:
        _destination (str): The destination name for the argument value
    """

    _destination: str | None = None

    @property
    def destination(self) -> str | None:
        """Get the destination name for this argument.

        Returns:
            str: The destination name, derived from the argument name if not explicitly set
            None: If no destination can be determined
        """
        return self._get_best_dest()

    @destination.setter
    def destination(self, value):
        self._destination = value

    def _get_best_dest(self) -> str | None:
        "Get the best destination name for this argument"
        if self._destination is not None:
            return self._destination

        # If no arguments, return None
        if not self.args:
            return None

        # Get first argument which should be the flag name
        arg = self.args[0]

        # Remove leading dashes and convert remaining dashes to underscores
        if arg.startswith("--"):
            key = arg[2:].replace("-", "_")
        elif arg.startswith("-"):
            # For short flags like -v, use the longer version if available
            if len(self.args) > 1 and self.args[1].startswith("--"):
                key = self.args[1][2:].replace("-", "_")
            else:
                key = arg[1:]
        else:
            key = arg.replace("-", "_")

        return key

    def build_params(self, dest: str) -> tuple[tuple, dict]:
        """Build parameter dictionary for argument parser.

        Args:
            dest (str): Destination name for the argument

        Returns:
            tuple: A tuple containing (args, kwargs) for argument parser

        Raises:
            ValueError: If no arguments are found
        """
        # Copy: descriptors are shared class attributes, never mutate them.
        kwargs = dict(self.kwargs)

        if len(self.args) > 0:
            if len(self.args) > 2:
                raise ValueError(
                    f"Too many arguments found for {self.__class__.__name__}: {self.args}"
                )

            args = self.args

            arg1 = args[0]
            if not arg1.startswith("-"):
                # Remove first position arg to avoid argparse error:
                # ValueError: dest supplied twice for positional argument
                kwargs["metavar"] = args[0]
                args = ()

        elif dest:
            if len(dest) <= 2:
                args = (f"-{dest}",)
            else:
                args = (f"--{dest}",)
        else:
            raise ValueError(
                f"No arguments found for {self.__class__.__name__}: {self.__dict__}"
            )

        # Update dest if forced
        if dest:
            kwargs["dest"] = dest

        return args, kwargs

destination property writable

Get the destination name for this argument.

Returns:

Name Type Description
str str | None

The destination name, derived from the argument name if not explicitly set

None str | None

If no destination can be determined

build_params(dest)

Build parameter dictionary for argument parser.

Parameters:

Name Type Description Default
dest str

Destination name for the argument

required

Returns:

Name Type Description
tuple tuple[tuple, dict]

A tuple containing (args, kwargs) for argument parser

Raises:

Type Description
ValueError

If no arguments are found

Source code in clak/core/descriptors.py
def build_params(self, dest: str) -> tuple[tuple, dict]:
    """Build parameter dictionary for argument parser.

    Args:
        dest (str): Destination name for the argument

    Returns:
        tuple: A tuple containing (args, kwargs) for argument parser

    Raises:
        ValueError: If no arguments are found
    """
    # Copy: descriptors are shared class attributes, never mutate them.
    kwargs = dict(self.kwargs)

    if len(self.args) > 0:
        if len(self.args) > 2:
            raise ValueError(
                f"Too many arguments found for {self.__class__.__name__}: {self.args}"
            )

        args = self.args

        arg1 = args[0]
        if not arg1.startswith("-"):
            # Remove first position arg to avoid argparse error:
            # ValueError: dest supplied twice for positional argument
            kwargs["metavar"] = args[0]
            args = ()

    elif dest:
        if len(dest) <= 2:
            args = (f"-{dest}",)
        else:
            args = (f"--{dest}",)
    else:
        raise ValueError(
            f"No arguments found for {self.__class__.__name__}: {self.__dict__}"
        )

    # Update dest if forced
    if dest:
        kwargs["dest"] = dest

    return args, kwargs

Argument

Bases: ArgParseItem

Represents an argument that can be added to an argument parser.

Handles both positional arguments and optional flags, choosing the appropriate argparse form from the flag names. Optional helpers :class:Arg (positionals) and :class:Opt (flags) reject mixed names.

Most keyword arguments are passed through to :meth:argparse.ArgumentParser.add_argument. Clak-only kwargs (stripped before argparse):

  • argument_group / option_group: Optional title for a help section (parser.add_argument_group). Same title reuses one section; pick the name that matches what you are grouping. Do not set both on one Argument.
  • exclusive_group: Shared key for argparse mutual exclusion (add_mutually_exclusive_group). Same key reuses one XOR set (required=False). May nest under a help section when a help-group kwarg is also set.
  • help_level: "main" (default) or "advanced". Advanced flags are summarized in short --help and listed by --help-all.
  • propagate: Copy this flag onto descendant parsers (default True). Set False to keep it on this parser only.
Source code in clak/core/descriptors.py
class Argument(ArgParseItem):
    """Represents an argument that can be added to an argument parser.

    Handles both positional arguments and optional flags, choosing the
    appropriate argparse form from the flag names. Optional helpers
    :class:`Arg` (positionals) and :class:`Opt` (flags) reject mixed names.

    Most keyword arguments are passed through to
    :meth:`argparse.ArgumentParser.add_argument`. Clak-only kwargs (stripped
    before argparse):

    - ``argument_group`` / ``option_group``: Optional title for a help section
      (``parser.add_argument_group``). Same title reuses one section; pick the
      name that matches what you are grouping. Do not set both on one Argument.
    - ``exclusive_group``: Shared key for argparse mutual exclusion
      (``add_mutually_exclusive_group``). Same key reuses one XOR set
      (``required=False``). May nest under a help section when a help-group
      kwarg is also set.
    - ``help_level``: ``"main"`` (default) or ``"advanced"``. Advanced flags are
      summarized in short ``--help`` and listed by ``--help-all``.
    - ``propagate``: Copy this flag onto descendant parsers (default True).
      Set False to keep it on this parser only.
    """

    def with_kwargs(self, **overrides) -> "Argument":
        """Return a shallow copy with ``overrides`` merged into ``kwargs``.

        Keeps ``args`` and the destination; the original is left untouched.
        """
        clone = copy.copy(self)
        clone.kwargs = {**self.kwargs, **overrides}
        return clone

    def propagates(self) -> bool:
        """True when this flag should be copied onto descendant parsers."""
        return bool(self.kwargs.get("propagate", True))

    def flag_strings(self, dest: str) -> tuple[str, ...]:
        """Option strings for a flag Argument, or empty if it is positional."""
        if dest.startswith("__"):
            return ()
        if self.args:
            if str(self.args[0]).startswith("-"):
                return tuple(str(name) for name in self.args)
            return ()
        if not dest:
            return ()
        if len(dest) <= 2:
            return (f"-{dest}",)
        return (f"--{dest}",)

    def suppress_attach_overrides(self, extra: dict | None = None) -> dict:
        """Attach-time overrides so a copy does not overwrite an outer dest.

        Do not set required unless the source flag is required: some argparse
        actions reject the required= keyword.
        """
        overrides = {"default": argparse.SUPPRESS}
        if self.kwargs.get("required"):
            overrides["required"] = False
        if extra:
            overrides.update(extra)
        return overrides

    def attach_arg_to_parser(
        self,
        key: str,
        config: "ParserNode",
        attach_overrides: dict | None = None,
    ) -> argparse.Action:
        """Create and add an argument to the parser.

        Args:
            key (str): The argument key/name
            config (ParserNode): The parser configuration object
            attach_overrides (dict): Kwargs applied only to this attach
                (not stored on the shared Argument descriptor).

        Returns:
            argparse.Action: The created argument parser action
        """
        parser = config.parser
        args, kwargs = self.build_params(key)
        kwargs = dict(kwargs)
        if attach_overrides:
            kwargs.update(attach_overrides)
        if not isinstance(args, tuple):
            raise TypeError(
                f"Args must be a tuple for {self.__class__.__name__}: {type(args)}"
            )

        help_group_title = _help_group_title_from_kwargs(key, kwargs)
        exclusive_key = kwargs.pop("exclusive_group", None)
        kwargs.pop("propagate", None)
        advanced = kwargs.pop("help_level", "main") == "advanced"

        # Create argument
        logger.debug(
            "Create new argument %s.%s: %s",
            config.get_fname(attr="key"),
            key,
            self.kwargs,
        )

        target = _parser_add_target(parser, help_group_title, exclusive_key)
        action = target.add_argument(*args, **_kwargs_for_add_argument(kwargs, parser))
        help_args = getattr(config, "help_args", None)
        if help_args is not None:
            help_args.append(
                HelpArg.from_action(
                    action,
                    group=help_group_title,
                    advanced=advanced,
                    exclusive=(
                        None
                        if exclusive_key is None
                        else (help_group_title, exclusive_key)
                    ),
                )
            )
        return action

attach_arg_to_parser(key, config, attach_overrides=None)

Create and add an argument to the parser.

Parameters:

Name Type Description Default
key str

The argument key/name

required
config ParserNode

The parser configuration object

required
attach_overrides dict

Kwargs applied only to this attach (not stored on the shared Argument descriptor).

None

Returns:

Type Description
Action

argparse.Action: The created argument parser action

Source code in clak/core/descriptors.py
def attach_arg_to_parser(
    self,
    key: str,
    config: "ParserNode",
    attach_overrides: dict | None = None,
) -> argparse.Action:
    """Create and add an argument to the parser.

    Args:
        key (str): The argument key/name
        config (ParserNode): The parser configuration object
        attach_overrides (dict): Kwargs applied only to this attach
            (not stored on the shared Argument descriptor).

    Returns:
        argparse.Action: The created argument parser action
    """
    parser = config.parser
    args, kwargs = self.build_params(key)
    kwargs = dict(kwargs)
    if attach_overrides:
        kwargs.update(attach_overrides)
    if not isinstance(args, tuple):
        raise TypeError(
            f"Args must be a tuple for {self.__class__.__name__}: {type(args)}"
        )

    help_group_title = _help_group_title_from_kwargs(key, kwargs)
    exclusive_key = kwargs.pop("exclusive_group", None)
    kwargs.pop("propagate", None)
    advanced = kwargs.pop("help_level", "main") == "advanced"

    # Create argument
    logger.debug(
        "Create new argument %s.%s: %s",
        config.get_fname(attr="key"),
        key,
        self.kwargs,
    )

    target = _parser_add_target(parser, help_group_title, exclusive_key)
    action = target.add_argument(*args, **_kwargs_for_add_argument(kwargs, parser))
    help_args = getattr(config, "help_args", None)
    if help_args is not None:
        help_args.append(
            HelpArg.from_action(
                action,
                group=help_group_title,
                advanced=advanced,
                exclusive=(
                    None
                    if exclusive_key is None
                    else (help_group_title, exclusive_key)
                ),
            )
        )
    return action

flag_strings(dest)

Option strings for a flag Argument, or empty if it is positional.

Source code in clak/core/descriptors.py
def flag_strings(self, dest: str) -> tuple[str, ...]:
    """Option strings for a flag Argument, or empty if it is positional."""
    if dest.startswith("__"):
        return ()
    if self.args:
        if str(self.args[0]).startswith("-"):
            return tuple(str(name) for name in self.args)
        return ()
    if not dest:
        return ()
    if len(dest) <= 2:
        return (f"-{dest}",)
    return (f"--{dest}",)

propagates()

True when this flag should be copied onto descendant parsers.

Source code in clak/core/descriptors.py
def propagates(self) -> bool:
    """True when this flag should be copied onto descendant parsers."""
    return bool(self.kwargs.get("propagate", True))

suppress_attach_overrides(extra=None)

Attach-time overrides so a copy does not overwrite an outer dest.

Do not set required unless the source flag is required: some argparse actions reject the required= keyword.

Source code in clak/core/descriptors.py
def suppress_attach_overrides(self, extra: dict | None = None) -> dict:
    """Attach-time overrides so a copy does not overwrite an outer dest.

    Do not set required unless the source flag is required: some argparse
    actions reject the required= keyword.
    """
    overrides = {"default": argparse.SUPPRESS}
    if self.kwargs.get("required"):
        overrides["required"] = False
    if extra:
        overrides.update(extra)
    return overrides

with_kwargs(**overrides)

Return a shallow copy with overrides merged into kwargs.

Keeps args and the destination; the original is left untouched.

Source code in clak/core/descriptors.py
def with_kwargs(self, **overrides) -> "Argument":
    """Return a shallow copy with ``overrides`` merged into ``kwargs``.

    Keeps ``args`` and the destination; the original is left untouched.
    """
    clone = copy.copy(self)
    clone.kwargs = {**self.kwargs, **overrides}
    return clone

MetaSetting

Bases: _Fn

A setting that is used to configure a node

Source code in clak/core/descriptors.py
class MetaSetting(_Fn):
    "A setting that is used to configure a node"

Opt

Bases: Argument

Optional sugar for an option flag.

Same *args / **kwargs as :class:Argument. When names are given, every name must start with - / --. Empty Opt() is allowed: the attribute name becomes a dest-derived flag (--attr or -x). Argument still accepts both positionals and flags.

Source code in clak/core/descriptors.py
class Opt(Argument):
    """Optional sugar for an option flag.

    Same ``*args`` / ``**kwargs`` as :class:`Argument`. When names are
    given, every name must start with ``-`` / ``--``. Empty ``Opt()`` is
    allowed: the attribute name becomes a dest-derived flag (``--attr``
    or ``-x``). ``Argument`` still accepts both positionals and flags.
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        _check_arg_opt_names(self.args, expect_option=True, cls_name="Opt")

SubParser

Bases: ArgParseItem

Represents a subcommand parser that can be added to a parent parser.

This class handles creation of nested command structures, allowing for hierarchical command-line interfaces via argparse add_subparsers.

Most keyword arguments are passed through to :meth:argparse._SubParsersAction.add_parser. Clak-only kwargs (stripped before argparse):

  • command_group: Optional key for a subcommand help section. Pair with Meta.command_groups on the parent Parser. Formatter metadata only; not a second add_subparsers. Commands with no key stay under leftover subcommands:.
Source code in clak/core/descriptors.py
class SubParser(ArgParseItem):
    """Represents a subcommand parser that can be added to a parent parser.

    This class handles creation of nested command structures, allowing for hierarchical
    command-line interfaces via argparse ``add_subparsers``.

    Most keyword arguments are passed through to
    :meth:`argparse._SubParsersAction.add_parser`. Clak-only kwargs (stripped
    before argparse):

    - ``command_group``: Optional key for a subcommand help section. Pair with
      ``Meta.command_groups`` on the parent Parser. Formatter metadata only;
      not a second ``add_subparsers``. Commands with no key stay under
      leftover ``subcommands:``.
    """

    def __init__(self, cls, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.cls = cls

    def attach_sub_to_parser(self, key: str, config: "ParserNode") -> "ParserNode":
        """Create a subcommand parser for this command.

        Creates a new subparser for the command and configures it with the appropriate
        help text and options. Validates that the command name is valid.

        Args:
            key (str): Name of the subcommand
            config (ParserNode): Parent parser configuration object

        Raises:
            ValueError: If command name contains spaces

        Returns:
            ParserNode: The created child parser instance
        """

        if " " in key:
            raise ValueError(
                f"Command name '{key}' contains spaces. Command names must not contain spaces."
            )

        logger.debug(
            "Create new subparser %s.%s",
            config.get_fname(attr="key"),
            key,
        )

        # Fetch help from class
        parser_help = self.kwargs.get(
            "help",
            self.cls.query_cfg_inst(
                self.cls, "help_description", default=self.cls.__doc__
            ),
        )
        parser_help_enabled = self.kwargs.get(
            "help_flags",
            self.cls.query_cfg_inst(self.cls, "help_flags", default=True),
        )

        # Create a new subparser for this command (flat structure)
        parser_help = prepare_docstring(
            first_doc_line(parser_help), variables={"key": key, "self": config}
        )
        parser_kwargs = dict(self.kwargs)
        parser_kwargs.update(
            {
                "add_help": False,  # help flags are installed by the child ParserNode
                "exit_on_error": False,
                "help": parser_help,
            }
        )
        command_group = parser_kwargs.pop("command_group", None)

        # Create parser
        subparser = config.subparsers.add_parser(
            key,
            **parser_kwargs,
        )

        # Create an instance of the command class with the subparser
        child = self.cls(
            parent=config, parser=subparser, key=key, add_help=parser_help_enabled
        )
        child.command_group = command_group
        child.command_help = parser_help

        # Reconfigure subparser
        child_usage, child_desc, child_epilog = child.help_texts(
            {"key": key, "self": child}, first_line=True
        )
        subparser.usage = child_usage
        subparser.description = child_desc
        subparser.epilog = child_epilog

        return child

attach_sub_to_parser(key, config)

Create a subcommand parser for this command.

Creates a new subparser for the command and configures it with the appropriate help text and options. Validates that the command name is valid.

Parameters:

Name Type Description Default
key str

Name of the subcommand

required
config ParserNode

Parent parser configuration object

required

Raises:

Type Description
ValueError

If command name contains spaces

Returns:

Name Type Description
ParserNode ParserNode

The created child parser instance

Source code in clak/core/descriptors.py
def attach_sub_to_parser(self, key: str, config: "ParserNode") -> "ParserNode":
    """Create a subcommand parser for this command.

    Creates a new subparser for the command and configures it with the appropriate
    help text and options. Validates that the command name is valid.

    Args:
        key (str): Name of the subcommand
        config (ParserNode): Parent parser configuration object

    Raises:
        ValueError: If command name contains spaces

    Returns:
        ParserNode: The created child parser instance
    """

    if " " in key:
        raise ValueError(
            f"Command name '{key}' contains spaces. Command names must not contain spaces."
        )

    logger.debug(
        "Create new subparser %s.%s",
        config.get_fname(attr="key"),
        key,
    )

    # Fetch help from class
    parser_help = self.kwargs.get(
        "help",
        self.cls.query_cfg_inst(
            self.cls, "help_description", default=self.cls.__doc__
        ),
    )
    parser_help_enabled = self.kwargs.get(
        "help_flags",
        self.cls.query_cfg_inst(self.cls, "help_flags", default=True),
    )

    # Create a new subparser for this command (flat structure)
    parser_help = prepare_docstring(
        first_doc_line(parser_help), variables={"key": key, "self": config}
    )
    parser_kwargs = dict(self.kwargs)
    parser_kwargs.update(
        {
            "add_help": False,  # help flags are installed by the child ParserNode
            "exit_on_error": False,
            "help": parser_help,
        }
    )
    command_group = parser_kwargs.pop("command_group", None)

    # Create parser
    subparser = config.subparsers.add_parser(
        key,
        **parser_kwargs,
    )

    # Create an instance of the command class with the subparser
    child = self.cls(
        parent=config, parser=subparser, key=key, add_help=parser_help_enabled
    )
    child.command_group = command_group
    child.command_help = parser_help

    # Reconfigure subparser
    child_usage, child_desc, child_epilog = child.help_texts(
        {"key": key, "self": child}, first_line=True
    )
    subparser.usage = child_usage
    subparser.description = child_desc
    subparser.epilog = child_epilog

    return child

first_doc_line(text)

Get the first non-empty line from a text string.

Parameters:

Name Type Description Default
text str | None

The text to extract the first line from (None treated as empty)

required

Returns:

Name Type Description
str str

The first non-empty line, or empty string if no non-empty lines found

Raises:

Type Description
ValueError

If first non-empty line starts with spaces

Source code in clak/core/descriptors.py
def first_doc_line(text: str | None) -> str:
    """Get the first non-empty line from a text string.

    Args:
        text: The text to extract the first line from (None treated as empty)

    Returns:
        str: The first non-empty line, or empty string if no non-empty lines found

    Raises:
        ValueError: If first non-empty line starts with spaces
    """
    if not text:
        return ""
    lines = text.split("\n")
    for line in lines:
        if line.strip():
            if line.startswith(" "):
                raise ValueError(
                    f"First line of docstring should not start with spaces: {line}"
                )
            return line
    return ""

prepare_docstring(text, variables=None, reindent='')

Prepare a docstring by deindenting and formatting with variables.

Parameters:

Name Type Description Default
text str

The docstring text to prepare

required
variables dict

Variables to format into the docstring; self is wrapped so {self.__doc__} is version-stable

None
reindent str

String to use for reindenting

''

Returns:

Name Type Description
str str | None

The prepared docstring, or None/SUPPRESS if input was None/SUPPRESS

Raises:

Type Description
KeyError

If formatting fails due to missing variables

TypeError

If variables arg is not a dict

Source code in clak/core/descriptors.py
def prepare_docstring(
    text: str | None, variables: dict[str, Any] | None = None, reindent: str = ""
) -> str | None:
    """Prepare a docstring by deindenting and formatting with variables.

    Args:
        text (str): The docstring text to prepare
        variables (dict, optional): Variables to format into the docstring;
            ``self`` is wrapped so ``{self.__doc__}`` is version-stable
        reindent (str, optional): String to use for reindenting

    Returns:
        str: The prepared docstring, or None/SUPPRESS if input was None/SUPPRESS

    Raises:
        KeyError: If formatting fails due to missing variables
        TypeError: If variables arg is not a dict
    """

    variables = dict(variables or {})
    if variables.get("self") is not None:
        variables["self"] = CleandocProxy(variables["self"])

    if text is None:
        return None
    if text == SUPPRESS:
        return SUPPRESS

    text = deindent_docstring(text, reindent=reindent)
    try:
        text = text.format(**variables)
    except KeyError as err:
        logger.exception(
            "Error formatting docstring: %s; variables=%s; text=%s",
            err,
            variables,
            text,
        )
        raise

    return text

Build / dispatch / execute:

clak.core.parser

Clak parser: ParserNode build, dispatch, and execute.

Descriptors (Argument, Arg, Opt, SubParser, MetaSetting, docstring helpers) live in clak.core.descriptors.

Canonical public names: Parser, Argument, Command (alias of SubParser). Optional helpers: Arg (positionals), Opt (flags). Instantiate a root Parser to parse and run; it calls dispatch() automatically unless parse=False.

Dispatch and exception handling live in clak.core._dispatch and clak.core._exception; this module keeps the build/inherit facade.

Parser

Bases: ParserNode

A simplified parser class that extends ParserNode.

This class provides a more streamlined interface to ParserNode by: - Automatically parsing arguments on initialization - Maintaining compatibility with legacy argument parser names - Providing simpler command/argument creation methods

Parameters:

Name Type Description Default
*args Any

Positional arguments passed to ParserNode

()
parse bool

Whether to automatically parse arguments on init, only on root nodes

True
**kwargs Any

Keyword arguments passed to ParserNode

{}
Source code in clak/core/parser.py
class Parser(ParserNode):
    """A simplified parser class that extends ParserNode.

    This class provides a more streamlined interface to ParserNode by:
    - Automatically parsing arguments on initialization
    - Maintaining compatibility with legacy argument parser names
    - Providing simpler command/argument creation methods

    Args:
        *args: Positional arguments passed to ParserNode
        parse (bool): Whether to automatically parse arguments on init,
            only on root nodes
        **kwargs: Keyword arguments passed to ParserNode
    """

    def __init__(self, *args: Any, parse: bool = True, **kwargs: Any):
        super().__init__(*args, **kwargs)

        if not self.parent and parse is True:
            logger.debug("Starting automatic arg_parse")
            # Positional args belong to ParserNode.__init__ (add_help, ...),
            # never to argv: dispatch reads sys.argv.
            self.dispatch()

ParserNode

Bases: Node

An extensible argument parser that can be inherited to create custom CLIs.

This class provides a framework for building complex command-line interfaces with: - Hierarchical subcommands - Automatic help generation - Plugin support - Custom argument types - Exception handling

The parser can be extended by: 1. Subclassing and adding Argument instances as class attributes 2. Adding SubParser instances to create command hierarchies 3. Implementing cli_run() for command implementation 4. Implementing cli_group() for command group behavior

Attributes:

Name Type Description
children dict

Dictionary of subcommand name to child parser

meta__name str

ParserNode name

Source code in clak/core/parser.py
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
class ParserNode(Node):
    """An extensible argument parser that can be inherited to create custom CLIs.

    This class provides a framework for building complex command-line interfaces with:
    - Hierarchical subcommands
    - Automatic help generation
    - Plugin support
    - Custom argument types
    - Exception handling

    The parser can be extended by:
    1. Subclassing and adding Argument instances as class attributes
    2. Adding SubParser instances to create command hierarchies
    3. Implementing cli_run() for command implementation
    4. Implementing cli_group() for command group behavior

    Attributes:
        children (dict): Dictionary of subcommand name to child parser
        meta__name (str): ParserNode name
    """

    meta__name: Any = NOT_SET

    meta__subcommands_dict: dict[str, SubParser] = {}
    meta__arguments_dict: dict[str, Argument] = {}

    meta__cli_view = None  # ClakView instance or subclass (see Meta.cli_view)

    # Meta settings
    meta__config__name = MetaSetting(
        help="Name of the parser",
    )
    meta__config__app_name = MetaSetting(
        help="Name of the application",
    )
    meta__config__app_proc_name = MetaSetting(
        help="Name of the application processus",
    )
    meta__config__help_usage = MetaSetting(
        help="Message to display in help usage",
    )
    meta__config__help_description = MetaSetting(
        help="Message to display in help description",
    )
    meta__config__help_epilog = MetaSetting(
        help="Message to display in help epilog",
    )
    meta__config__help_formatter = MetaSetting(
        help=(
            "Legacy: RecursiveHelpFormatter (plain) or RichRecursiveHelpFormatter "
            "(colored). Prefer help_color."
        ),
    )
    meta__config__help_color = MetaSetting(
        help="Color --help (True/False). Default: auto; follows help_formatter.",
    )
    meta__config__help_subcommands = MetaSetting(
        help=(
            "How --help lists subcommands: 'all' (nested children, default) "
            "or 'top' (immediate children only). Inherited; a child may override."
        ),
    )
    meta__config__help_hide_parent = MetaSetting(
        help=(
            "When listing nested subcommands, replace the parent path with "
            "spaces so only the leaf name is shown (default True)."
        ),
    )
    meta__config__command_groups = MetaSetting(
        help=(
            "Ordered (key, title) pairs for subcommand help sections. "
            "Formatter metadata only; not a second add_subparsers."
        ),
    )
    meta__config__parse_intermixed = MetaSetting(
        help=(
            "Mix this command's flags and positionals (default True). "
            "Inherited; set False for argparse leftover errors after a flag. "
            "No-op on parsers with subcommands or nargs=REMAINDER."
        ),
    )
    meta__config__abbrev_commands = MetaSetting(
        help=(
            "Accept a unique prefix of a subcommand name, e.g. 'bu' for "
            "'buzz' (default True). Inherited; ambiguous prefixes error."
        ),
    )
    meta__config__abbrev_options = MetaSetting(
        help=(
            "Accept a unique prefix of a long flag, e.g. '--verb' for "
            "'--verbose' (default True, argparse allow_abbrev). Inherited."
        ),
    )
    meta__config__propagate_options = MetaSetting(
        help=(
            "Copy eligible ancestor flags onto this parser (default True). "
            "Inherited; a child may set False. Per-flag opt-out: propagate=False."
        ),
    )
    meta__config__propagate_options_group = MetaSetting(
        help=(
            "Help section title for propagated ancestor flags "
            "(default 'parent options'). Inherited; a child may override."
        ),
    )
    meta__config__help_collapsed_groups = MetaSetting(
        help=(
            "Option group titles summarized in short --help and listed by "
            "--help-all (default: 'output options' and the propagated group; "
            "[] disables). Inherited."
        ),
    )
    meta__config__help_all_flag = MetaSetting(
        help="Flag printing the full help (default '--help-all'; None disables)",
    )
    meta__config__help_split = MetaSetting(
        help=(
            "-h prints the short help, --help the full one (default False; "
            "disables --help-all and --help-<topic>). Inherited; see LongHelpMixin."
        ),
    )
    meta__config__known_exceptions = MetaSetting(
        help="List of known exceptions to handle",
    )
    meta__config__exception_handlers = MetaSetting(
        help=(
            "Extra (exception_type, handler) pairs or handler callables "
            "for clean_terminate (third-party libs, etc.)"
        ),
    )

    # Views support
    meta__config__cli_view = MetaSetting(
        help="class of the view to use",
    )
    meta__config__runtime_narrow_width = MetaSetting(
        help="Column threshold for ctx.runtime.is_narrow (default 80)",
    )

    def __init__(
        self,
        add_help: bool = True,
        parent: "ParserNode | None" = None,
        name: str | None = None,
        key: str | None = None,
        parser: ClakArgumentParser | None = None,
        proc_name: str | None = None,
    ):
        """Initialize the parser.

        Args:
            add_help (bool): Whether to add help flags
            parent (ParserNode): Parent parser instance
            name (str): ParserNode name
            key (str): ParserNode key
            parser (ArgumentParser): Existing parser to use
            proc_name (str): Process name
        """
        self.logger = logger

        if parent is None:
            apply_debug_logging()

        super().__init__(parent=parent)

        self.dispatcher = Dispatcher(self)
        self.help_args = []
        self.command_group = None
        self.command_help = None

        self.name = self.query_cfg_parents("name", default=self.__class__.__name__)
        self.key = key
        self.fkey = self.get_fname(attr="key")
        self.proc_name = proc_name
        self.add_help = add_help

        # Add children link
        self.children = {}
        self.registry = {}
        if parent:
            parent.children[self.key] = self
            self.registry = parent.registry
        self.registry[self.fkey] = self

        # Create or reuse parent parser
        if parser is None:
            self.parser = self.create_parser()
            self.proc_name = self.parser.prog
        else:
            self.parser = parser
            self.proc_name = self.parent.proc_name
            # add_parser() builds ClakArgumentParser without clak_instance.
            self.parser.clak_instance = self

        self._install_help_flag()

        # Init _subparsers
        self._subparsers = None
        self.local_flag_arguments: dict[str, Argument] = {}

        self.add_arguments()
        self.add_subcommands()
        self._cli_hooks = self._collect_cli_hooks()
        self._install_help()

    def __repr__(self):
        return f"<{self.__class__.__module__}.{self.__class__.__name__}>"

    def help_texts(self, variables: dict, first_line: bool = False) -> tuple:
        """Return prepared ``(usage, description, epilog)`` for this node.

        Reads ``Meta.help_usage`` / ``help_description`` (default: class
        docstring) / ``help_epilog`` and formats them with *variables*.
        *first_line* keeps only the description's first line (subcommands).
        """
        desc = self.query_cfg_inst("help_description", default=self.__doc__)
        if first_line:
            desc = first_doc_line(desc)
        texts = (
            self.query_cfg_inst("help_usage", default=None),
            desc,
            self.query_cfg_inst("help_epilog", default=None),
        )
        return tuple(prepare_docstring(text, variables=variables) for text in texts)

    def create_parser(self):
        "Create a new parser"
        usage, desc, epilog = self.help_texts({"self": self})
        # parse_intermixed / allow_abbrev are set by _install_help.
        parser = ClakArgumentParser(
            prog=self.proc_name,
            usage=usage,
            description=desc,
            epilog=epilog,
            add_help=False,  # help flags are owned by _install_help_flags
            exit_on_error=False,
            clak_instance=self,
        )
        return parser

    def get_help_formatter_class(self):
        """Return the legacy ``help_formatter`` marker class for this node.

        Mixins set ``meta__help_formatter`` (or ``Meta.help_formatter``).
        Unset walks parents, then ``RichRecursiveHelpFormatter``.
        """
        return self.query_cfg_parents(
            "help_formatter",
            default=RichRecursiveHelpFormatter,
        )

    def help_color_enabled(self) -> bool:
        """True when --help is styled: ``help_color``, else ``help_formatter``."""
        color = self.query_cfg_parents("help_color", default=None)
        if color is not None:
            return bool(color)
        fmt = self.get_help_formatter_class()
        return isinstance(fmt, type) and issubclass(fmt, RichRecursiveHelpFormatter)

    def _resolve_collapsed_groups(self) -> tuple:
        groups = self.query_cfg_parents("help_collapsed_groups", default=None)
        if groups is None:
            groups = (
                "output options",
                self.query_cfg_parents(
                    "propagate_options_group", default=PROPAGATE_OPTIONS_GROUP_DEFAULT
                ),
            )
        return tuple(groups)

    def _resolve_help_all_flag(self) -> str | None:
        if self._is_help_split():
            return None
        flag = self.query_cfg_parents("help_all_flag", default="--help-all")
        return flag if flag and self.add_help else None

    def _is_help_split(self) -> bool:
        return bool(self.query_cfg_parents("help_split", default=False))

    def _install_help_topics(self, all_flag: str) -> None:
        """Add ``--help-<topic>`` for each non-empty collapsed group."""
        present = {a.group for a in self.help_args if not a.is_hidden()}
        for title in self.help_layout.collapsed_groups:
            flag = topic_flag(title)
            if title in present and flag != all_flag:
                self.parser.add_argument(
                    flag,
                    action=HelpAllAction,
                    const=title,
                    dest=f"help_{flag[7:].replace('-', '_')}",
                    default=argparse.SUPPRESS,
                    help=argparse.SUPPRESS,
                )

    def _install_help_flag(self) -> None:
        """Register ``-h/--help``; runs first so it leads usage and options."""
        if not self.add_help or not hasattr(self.parser, "add_argument"):
            return
        if self._is_help_split():
            specs = [
                dict(
                    args=("-h",),
                    action="help",
                    dest="help",
                    help=_STRINGS.help_split_short_flag,
                ),
                dict(
                    args=("--help",),
                    action=HelpAllAction,
                    dest="help_all",
                    help=_STRINGS.help_split_full_flag,
                ),
            ]
        else:
            specs = [
                dict(
                    args=("-h", "--help"),
                    action="help",
                    help=_STRINGS.help_short_flag,
                )
            ]
        for spec in specs:
            args = spec.pop("args")
            action = self.parser.add_argument(*args, default=argparse.SUPPRESS, **spec)
            item = HelpArg.from_action(action)
            item.help_flag = True
            self.help_args.append(item)

    def _install_help_flags(self) -> None:
        """Register ``--help-all`` and ``--help-<topic>`` (needs the layout)."""
        if not self.add_help or not hasattr(self.parser, "add_argument"):
            return
        flag = self.help_layout.help_all_flag
        if flag:
            self.parser.add_argument(
                flag,
                action=HelpAllAction,
                dest="help_all",
                default=argparse.SUPPRESS,
                help=argparse.SUPPRESS,
            )
            self._install_help_topics(flag)

    def _install_help(self):
        """Attach HelpRenderer and version-stable parse flags to the wrapper."""
        self.help_layout = HelpLayout(
            subcommands=self.query_cfg_parents(
                "help_subcommands",
                default=HELP_SUBCOMMANDS_ALL,
            ),
            hide_parent=self.query_cfg_parents(
                "help_hide_parent",
                default=True,
            ),
            command_groups=tuple(
                self.query_cfg_inst("command_groups", default=()) or ()
            ),
            collapsed_groups=self._resolve_collapsed_groups(),
            help_all_flag=self._resolve_help_all_flag(),
            help_split=self._is_help_split(),
        )
        renderer = HelpRenderer(self)
        if self.help_color_enabled():
            renderer.colorizer = help_document_colorizer
        self.help_renderer = renderer
        self._install_help_flags()
        self.parser.clak_help_renderer = renderer
        self.parser.parse_intermixed = self.query_cfg_parents(
            "parse_intermixed", default=True
        )
        # Subparsers built by add_parser() get argparse's default; read at
        # parse time, so setting it after build is enough.
        self.parser.allow_abbrev = bool(
            self.query_cfg_parents("abbrev_options", default=True)
        )

    def __getitem__(self, key):
        return self.children[key]

    def get_fname(self, attr="key"):
        "Get full name of the parser, use key instead of name by default"
        return super().get_fname(attr=attr)

    @property
    def subparsers(self):
        """Lazily create and return the subparsers object."""
        if self._subparsers is None:
            level = len(self.get_hierarchy())
            self._subparsers = self.parser.add_subparsers(  # ty: ignore[no-matching-overload]
                dest=f"__cli_cmd__{level}",
                help="Available commands",
                parser_class=ClakArgumentParser,
                action=SubParsersAction,
                allow_abbrev=bool(
                    self.query_cfg_parents("abbrev_commands", default=True)
                ),
            )
        return self._subparsers

    # Argument management
    # ========================

    def _skip_argument_names(self) -> set:
        """Names of class Argument attrs to omit (view mixins override)."""
        return set()

    def _prepare_argument(self, key: str, arg: Argument) -> Argument:
        """Hook to adjust an argument before attach (view mixins override)."""
        return arg

    def add_arguments(self, arguments: dict | None = None):
        """Initialize all argument options defined for this parser.

        This method:
        1. Collects arguments from meta__arguments_dict
        2. Collects arguments defined as class attributes
        3. Adds internal arguments like __cli_self__
        4. Creates all argument parser entries
        5. Copies ancestor flags onto this parser when inherit is on
        """
        if arguments is None:
            arguments = getattr(self, "meta__arguments_dict", None)
        arguments = self._collect_descriptors(
            arguments, Argument, skip=self._skip_argument_names()
        )

        # Add __cli_self__ argument
        arguments["__cli_self__"] = Argument(help=argparse.SUPPRESS, default=self)

        ancestor_dests, ancestor_strings = self._ancestor_flag_index()
        local_flags: dict[str, Argument] = {}

        for key, arg in arguments.items():
            arg = self._prepare_argument(key, arg)
            overrides = None
            flag_strings = arg.flag_strings(key)
            if flag_strings:
                local_flags[key] = arg
                if key in ancestor_dests or (ancestor_strings & set(flag_strings)):
                    overrides = arg.suppress_attach_overrides()
            self.add_argument(key, arg, attach_overrides=overrides)

        self.local_flag_arguments = local_flags

        if self.query_cfg_parents("propagate_options", default=True):
            self._attach_inherited_parent_flags(arguments, local_flags)

    def _collect_descriptors(self, explicit, kind, skip=()) -> dict:
        """``{name: descriptor}``: *explicit* dict, then class attrs of *kind*.

        Walks the MRO so a subclass attribute wins over an inherited one;
        class attributes named in *skip* are ignored.
        """
        if explicit is None:
            explicit = {}
        if not isinstance(explicit, dict):
            raise TypeError(f"Got {type(explicit)} instead of dict")
        found = dict(explicit)
        for cls in type(self).__mro__:
            for name, value in vars(cls).items():
                if isinstance(value, kind) and name not in found and name not in skip:
                    found[name] = value
        return found

    def _iter_ancestor_flags(self):
        """``(dest, Argument)`` flags defined locally on ancestors, closest first."""
        node = self.parent
        while node:
            yield from node.local_flag_arguments.items()
            node = node.parent

    def _ancestor_flag_index(self) -> tuple[set[str], set[str]]:
        """Dests and option strings from ancestors' locally defined flags."""
        dests: set[str] = set()
        strings: set[str] = set()
        for dest, arg in self._iter_ancestor_flags():
            dests.add(dest)
            strings.update(arg.flag_strings(dest))
        return dests, strings

    def _attach_inherited_parent_flags(
        self, arguments: dict, local_flags: dict[str, Argument]
    ) -> None:
        """Copy closest ancestor flags onto this parser (default=SUPPRESS)."""
        seen_dests = set(arguments)
        seen_strings: set[str] = set()
        for dest, arg in local_flags.items():
            seen_strings.update(arg.flag_strings(dest))

        group = self.query_cfg_parents(
            "propagate_options_group",
            default=PROPAGATE_OPTIONS_GROUP_DEFAULT,
        )
        group_extra = {
            "option_group": group,
            "argument_group": None,
        }

        for dest, arg in self._iter_ancestor_flags():
            if dest in seen_dests or not arg.propagates():
                continue
            strings = arg.flag_strings(dest)
            if not strings or (seen_strings & set(strings)):
                continue
            self.add_argument(
                dest,
                arg,
                attach_overrides=arg.suppress_attach_overrides(extra=group_extra),
            )
            seen_dests.add(dest)
            seen_strings.update(strings)

    def add_argument(
        self,
        key: str,
        arg: Argument | None = None,
        attach_overrides: dict | None = None,
        **kwargs: Any,
    ) -> None:
        """Add an argument to this parser.

        Args:
            key (str): The key/name for the argument
            arg (Argument): The argument object to add
            attach_overrides (dict): Kwargs applied only to this attach
            **kwargs (Any): Additional keyword arguments to pass to add_argument()

        This method adds a new argument to the parser. The argument can be either a
        positional argument or an optional flag, determined by the Argument object.
        """

        if arg is None:
            arg = Argument(**kwargs)

        arg.attach_arg_to_parser(key, self, attach_overrides=attach_overrides)

    # Subcommand management
    # ========================

    def add_subcommands(self, subcommands: dict | None = None):
        """Initialize all subcommands defined for this parser.

        This method:
        1. Collects subcommands from children dictionary
        2. Collects Command instances defined as class attributes
        3. Creates parser entries for all subcommands
        """

        if subcommands is None:
            subcommands = getattr(self, "meta__subcommands_dict", None)
        subcommands = self._collect_descriptors(subcommands, Command)

        for key, arg in subcommands.items():
            self.add_subcommand(key, arg)

    def add_subcommand(self, key: str, arg=None, **kwargs) -> None:
        "Add a subcommand to this parser"
        if arg is None:
            arg = Command(**kwargs)

        arg.attach_sub_to_parser(key, self)

    # Help methods
    # ========================

    def show_help(self):
        """Display the help message for this parser."""
        self.parser.print_help()

    def show_usage(self):
        """Display the usage message for this parser."""
        self.parser.print_usage()

    # Execution helpers
    # ========================

    def parse_args(self, *args, **kwargs):
        """Parse argv; see ``Dispatcher.parse_args``."""
        return self.dispatcher.parse_args(*args, **kwargs)

    def dispatch(self, *args, **kwargs):
        """Parse and run; see ``Dispatcher.dispatch``."""
        return self.dispatcher.dispatch(*args, **kwargs)

    def cli_execute(self, *args, **kwargs):
        """Walk hooks and ``cli_run``; see ``Dispatcher.cli_execute``."""
        return self.dispatcher.cli_execute(*args, **kwargs)

    def clean_terminate(self, *args, **kwargs):
        """Handle a dispatch error; see ``clak.core._exception.clean_terminate``."""
        return clean_terminate(self, *args, **kwargs)

    @property
    def ctx(self):
        """Last ``ClakContext`` from dispatch, or None before execute."""
        return self.dispatcher.ctx

    def cli_exit(self, status=0, message=None):
        """Exit the CLI application with given status and message.

        Args:
            status (int): Exit status code
            message (str): Optional message to display
        """
        self.parser.exit(status=status, message=message)

    def cli_exit_error(self, message):
        """Exit the CLI application with an error message.

        Args:
            message (str): Error message to display
        """
        self.parser.error(message)

    def cli_run(self, ctx: Any, **kwargs: Any) -> None:
        """Execute the command implementation.

        This method should be overridden by subclasses to implement command behavior.
        The base implementation shows help for non-leaf nodes.

        Args:
            ctx: Execution context
            **kwargs: Additional keyword arguments from command line

        Raises:
            ClakNotImplementedError: If leaf node has no implementation
        """

        # Check if class is a leaf or not
        if len(ctx.cli_children) > 0:
            self.show_help()
        else:
            raise exception.ClakNotImplementedError(
                f"No 'cli_run' method found for {self}"
            )

    def _collect_cli_hooks(self) -> dict:
        """Bound ``cli_hook__*`` methods on this instance (once at build)."""
        hooks = {}
        for name in dir(self):
            if not name.startswith(CLI_HOOK_PREFIX):
                continue
            fn = getattr(self, name, None)
            if callable(fn):
                hooks[name] = fn
        return hooks

    def cli_group(self, ctx: ClakContext, **_: Any) -> None:
        """Execute group-level command behavior.

        Args:
            ctx: Command context object
            **_: Unused keyword arguments
        """

ctx property

Last ClakContext from dispatch, or None before execute.

subparsers property

Lazily create and return the subparsers object.

__init__(add_help=True, parent=None, name=None, key=None, parser=None, proc_name=None)

Initialize the parser.

Parameters:

Name Type Description Default
add_help bool

Whether to add help flags

True
parent ParserNode

Parent parser instance

None
name str

ParserNode name

None
key str

ParserNode key

None
parser ArgumentParser

Existing parser to use

None
proc_name str

Process name

None
Source code in clak/core/parser.py
def __init__(
    self,
    add_help: bool = True,
    parent: "ParserNode | None" = None,
    name: str | None = None,
    key: str | None = None,
    parser: ClakArgumentParser | None = None,
    proc_name: str | None = None,
):
    """Initialize the parser.

    Args:
        add_help (bool): Whether to add help flags
        parent (ParserNode): Parent parser instance
        name (str): ParserNode name
        key (str): ParserNode key
        parser (ArgumentParser): Existing parser to use
        proc_name (str): Process name
    """
    self.logger = logger

    if parent is None:
        apply_debug_logging()

    super().__init__(parent=parent)

    self.dispatcher = Dispatcher(self)
    self.help_args = []
    self.command_group = None
    self.command_help = None

    self.name = self.query_cfg_parents("name", default=self.__class__.__name__)
    self.key = key
    self.fkey = self.get_fname(attr="key")
    self.proc_name = proc_name
    self.add_help = add_help

    # Add children link
    self.children = {}
    self.registry = {}
    if parent:
        parent.children[self.key] = self
        self.registry = parent.registry
    self.registry[self.fkey] = self

    # Create or reuse parent parser
    if parser is None:
        self.parser = self.create_parser()
        self.proc_name = self.parser.prog
    else:
        self.parser = parser
        self.proc_name = self.parent.proc_name
        # add_parser() builds ClakArgumentParser without clak_instance.
        self.parser.clak_instance = self

    self._install_help_flag()

    # Init _subparsers
    self._subparsers = None
    self.local_flag_arguments: dict[str, Argument] = {}

    self.add_arguments()
    self.add_subcommands()
    self._cli_hooks = self._collect_cli_hooks()
    self._install_help()

add_argument(key, arg=None, attach_overrides=None, **kwargs)

Add an argument to this parser.

Parameters:

Name Type Description Default
key str

The key/name for the argument

required
arg Argument

The argument object to add

None
attach_overrides dict

Kwargs applied only to this attach

None
**kwargs Any

Additional keyword arguments to pass to add_argument()

{}

This method adds a new argument to the parser. The argument can be either a positional argument or an optional flag, determined by the Argument object.

Source code in clak/core/parser.py
def add_argument(
    self,
    key: str,
    arg: Argument | None = None,
    attach_overrides: dict | None = None,
    **kwargs: Any,
) -> None:
    """Add an argument to this parser.

    Args:
        key (str): The key/name for the argument
        arg (Argument): The argument object to add
        attach_overrides (dict): Kwargs applied only to this attach
        **kwargs (Any): Additional keyword arguments to pass to add_argument()

    This method adds a new argument to the parser. The argument can be either a
    positional argument or an optional flag, determined by the Argument object.
    """

    if arg is None:
        arg = Argument(**kwargs)

    arg.attach_arg_to_parser(key, self, attach_overrides=attach_overrides)

add_arguments(arguments=None)

Initialize all argument options defined for this parser.

This method: 1. Collects arguments from meta__arguments_dict 2. Collects arguments defined as class attributes 3. Adds internal arguments like cli_self 4. Creates all argument parser entries 5. Copies ancestor flags onto this parser when inherit is on

Source code in clak/core/parser.py
def add_arguments(self, arguments: dict | None = None):
    """Initialize all argument options defined for this parser.

    This method:
    1. Collects arguments from meta__arguments_dict
    2. Collects arguments defined as class attributes
    3. Adds internal arguments like __cli_self__
    4. Creates all argument parser entries
    5. Copies ancestor flags onto this parser when inherit is on
    """
    if arguments is None:
        arguments = getattr(self, "meta__arguments_dict", None)
    arguments = self._collect_descriptors(
        arguments, Argument, skip=self._skip_argument_names()
    )

    # Add __cli_self__ argument
    arguments["__cli_self__"] = Argument(help=argparse.SUPPRESS, default=self)

    ancestor_dests, ancestor_strings = self._ancestor_flag_index()
    local_flags: dict[str, Argument] = {}

    for key, arg in arguments.items():
        arg = self._prepare_argument(key, arg)
        overrides = None
        flag_strings = arg.flag_strings(key)
        if flag_strings:
            local_flags[key] = arg
            if key in ancestor_dests or (ancestor_strings & set(flag_strings)):
                overrides = arg.suppress_attach_overrides()
        self.add_argument(key, arg, attach_overrides=overrides)

    self.local_flag_arguments = local_flags

    if self.query_cfg_parents("propagate_options", default=True):
        self._attach_inherited_parent_flags(arguments, local_flags)

add_subcommand(key, arg=None, **kwargs)

Add a subcommand to this parser

Source code in clak/core/parser.py
def add_subcommand(self, key: str, arg=None, **kwargs) -> None:
    "Add a subcommand to this parser"
    if arg is None:
        arg = Command(**kwargs)

    arg.attach_sub_to_parser(key, self)

add_subcommands(subcommands=None)

Initialize all subcommands defined for this parser.

This method: 1. Collects subcommands from children dictionary 2. Collects Command instances defined as class attributes 3. Creates parser entries for all subcommands

Source code in clak/core/parser.py
def add_subcommands(self, subcommands: dict | None = None):
    """Initialize all subcommands defined for this parser.

    This method:
    1. Collects subcommands from children dictionary
    2. Collects Command instances defined as class attributes
    3. Creates parser entries for all subcommands
    """

    if subcommands is None:
        subcommands = getattr(self, "meta__subcommands_dict", None)
    subcommands = self._collect_descriptors(subcommands, Command)

    for key, arg in subcommands.items():
        self.add_subcommand(key, arg)

clean_terminate(*args, **kwargs)

Handle a dispatch error; see clak.core._exception.clean_terminate.

Source code in clak/core/parser.py
def clean_terminate(self, *args, **kwargs):
    """Handle a dispatch error; see ``clak.core._exception.clean_terminate``."""
    return clean_terminate(self, *args, **kwargs)

cli_execute(*args, **kwargs)

Walk hooks and cli_run; see Dispatcher.cli_execute.

Source code in clak/core/parser.py
def cli_execute(self, *args, **kwargs):
    """Walk hooks and ``cli_run``; see ``Dispatcher.cli_execute``."""
    return self.dispatcher.cli_execute(*args, **kwargs)

cli_exit(status=0, message=None)

Exit the CLI application with given status and message.

Parameters:

Name Type Description Default
status int

Exit status code

0
message str

Optional message to display

None
Source code in clak/core/parser.py
def cli_exit(self, status=0, message=None):
    """Exit the CLI application with given status and message.

    Args:
        status (int): Exit status code
        message (str): Optional message to display
    """
    self.parser.exit(status=status, message=message)

cli_exit_error(message)

Exit the CLI application with an error message.

Parameters:

Name Type Description Default
message str

Error message to display

required
Source code in clak/core/parser.py
def cli_exit_error(self, message):
    """Exit the CLI application with an error message.

    Args:
        message (str): Error message to display
    """
    self.parser.error(message)

cli_group(ctx, **_)

Execute group-level command behavior.

Parameters:

Name Type Description Default
ctx ClakContext

Command context object

required
**_ Any

Unused keyword arguments

{}
Source code in clak/core/parser.py
def cli_group(self, ctx: ClakContext, **_: Any) -> None:
    """Execute group-level command behavior.

    Args:
        ctx: Command context object
        **_: Unused keyword arguments
    """

cli_run(ctx, **kwargs)

Execute the command implementation.

This method should be overridden by subclasses to implement command behavior. The base implementation shows help for non-leaf nodes.

Parameters:

Name Type Description Default
ctx Any

Execution context

required
**kwargs Any

Additional keyword arguments from command line

{}

Raises:

Type Description
ClakNotImplementedError

If leaf node has no implementation

Source code in clak/core/parser.py
def cli_run(self, ctx: Any, **kwargs: Any) -> None:
    """Execute the command implementation.

    This method should be overridden by subclasses to implement command behavior.
    The base implementation shows help for non-leaf nodes.

    Args:
        ctx: Execution context
        **kwargs: Additional keyword arguments from command line

    Raises:
        ClakNotImplementedError: If leaf node has no implementation
    """

    # Check if class is a leaf or not
    if len(ctx.cli_children) > 0:
        self.show_help()
    else:
        raise exception.ClakNotImplementedError(
            f"No 'cli_run' method found for {self}"
        )

create_parser()

Create a new parser

Source code in clak/core/parser.py
def create_parser(self):
    "Create a new parser"
    usage, desc, epilog = self.help_texts({"self": self})
    # parse_intermixed / allow_abbrev are set by _install_help.
    parser = ClakArgumentParser(
        prog=self.proc_name,
        usage=usage,
        description=desc,
        epilog=epilog,
        add_help=False,  # help flags are owned by _install_help_flags
        exit_on_error=False,
        clak_instance=self,
    )
    return parser

dispatch(*args, **kwargs)

Parse and run; see Dispatcher.dispatch.

Source code in clak/core/parser.py
def dispatch(self, *args, **kwargs):
    """Parse and run; see ``Dispatcher.dispatch``."""
    return self.dispatcher.dispatch(*args, **kwargs)

get_fname(attr='key')

Get full name of the parser, use key instead of name by default

Source code in clak/core/parser.py
def get_fname(self, attr="key"):
    "Get full name of the parser, use key instead of name by default"
    return super().get_fname(attr=attr)

get_help_formatter_class()

Return the legacy help_formatter marker class for this node.

Mixins set meta__help_formatter (or Meta.help_formatter). Unset walks parents, then RichRecursiveHelpFormatter.

Source code in clak/core/parser.py
def get_help_formatter_class(self):
    """Return the legacy ``help_formatter`` marker class for this node.

    Mixins set ``meta__help_formatter`` (or ``Meta.help_formatter``).
    Unset walks parents, then ``RichRecursiveHelpFormatter``.
    """
    return self.query_cfg_parents(
        "help_formatter",
        default=RichRecursiveHelpFormatter,
    )

help_color_enabled()

True when --help is styled: help_color, else help_formatter.

Source code in clak/core/parser.py
def help_color_enabled(self) -> bool:
    """True when --help is styled: ``help_color``, else ``help_formatter``."""
    color = self.query_cfg_parents("help_color", default=None)
    if color is not None:
        return bool(color)
    fmt = self.get_help_formatter_class()
    return isinstance(fmt, type) and issubclass(fmt, RichRecursiveHelpFormatter)

help_texts(variables, first_line=False)

Return prepared (usage, description, epilog) for this node.

Reads Meta.help_usage / help_description (default: class docstring) / help_epilog and formats them with variables. first_line keeps only the description's first line (subcommands).

Source code in clak/core/parser.py
def help_texts(self, variables: dict, first_line: bool = False) -> tuple:
    """Return prepared ``(usage, description, epilog)`` for this node.

    Reads ``Meta.help_usage`` / ``help_description`` (default: class
    docstring) / ``help_epilog`` and formats them with *variables*.
    *first_line* keeps only the description's first line (subcommands).
    """
    desc = self.query_cfg_inst("help_description", default=self.__doc__)
    if first_line:
        desc = first_doc_line(desc)
    texts = (
        self.query_cfg_inst("help_usage", default=None),
        desc,
        self.query_cfg_inst("help_epilog", default=None),
    )
    return tuple(prepare_docstring(text, variables=variables) for text in texts)

parse_args(*args, **kwargs)

Parse argv; see Dispatcher.parse_args.

Source code in clak/core/parser.py
def parse_args(self, *args, **kwargs):
    """Parse argv; see ``Dispatcher.parse_args``."""
    return self.dispatcher.parse_args(*args, **kwargs)

show_help()

Display the help message for this parser.

Source code in clak/core/parser.py
def show_help(self):
    """Display the help message for this parser."""
    self.parser.print_help()

show_usage()

Display the usage message for this parser.

Source code in clak/core/parser.py
def show_usage(self):
    """Display the usage message for this parser."""
    self.parser.print_usage()