Skip to content

core

core

Composable, transportable command-registry core for interactive CLIs.

CommandError

Bases: Exception

Base error for command dispatch or execution failures.

UsageError

Bases: CommandError

Raise when a command is invoked with missing or invalid arguments.

UnknownCommandError

Bases: CommandError

Raise when a token matches neither a child group nor a local command.

Command dataclass

Command(
    name: str,
    handler: CommandHandler,
    usage: str = "",
    help: str = "",
    completions: Callable[[], list[str]] | None = None,
)

A single named leaf command in a command group.

CommandGroup

CommandGroup(name: str, help: str = '')

A composable namespace of commands and nested child groups.

Initialise an empty command group.

Parameters:

Name Type Description Default
name str

The group's own name.

required
help str

Short description of the group.

''
Source code in src/applied_motion/cli/compose/core.py
def __init__(self, name: str, help: str = "") -> None:
    """Initialise an empty command group.

    Args:
        name: The group's own name.
        help: Short description of the group.
    """
    self.name = name
    self.help = help
    self.commands: dict[str, Command] = {}
    self.children: dict[str, CommandGroup] = {}
    logger.debug("CommandGroup created: name=%s", name)

add_command

add_command(command: Command) -> Command

Register a leaf command on this group.

Parameters:

Name Type Description Default
command Command

The command to register.

required

Returns:

Type Description
Command

The registered command.

Source code in src/applied_motion/cli/compose/core.py
def add_command(self, command: Command) -> Command:
    """Register a leaf command on this group.

    Args:
        command: The command to register.

    Returns:
        The registered command.
    """
    self.commands[command.name.lower()] = command
    return command

add_child

add_child(
    group: CommandGroup, name: str | None = None
) -> CommandGroup

Mount a child group under a name.

Parameters:

Name Type Description Default
group CommandGroup

The child group to mount.

required
name str | None

Mount key. Defaults to the child group's name.

None

Returns:

Type Description
CommandGroup

The mounted child group.

Source code in src/applied_motion/cli/compose/core.py
def add_child(self, group: "CommandGroup", name: str | None = None) -> "CommandGroup":
    """Mount a child group under a name.

    Args:
        group: The child group to mount.
        name: Mount key. Defaults to the child group's name.

    Returns:
        The mounted child group.
    """
    key = (name or group.name).lower()
    self.children[key] = group
    logger.debug("CommandGroup %s mounted child under %r", self.name, key)
    return group

dispatch

dispatch(tokens: Sequence[str]) -> None

Route a token sequence to a child group or a local command.

Parameters:

Name Type Description Default
tokens Sequence[str]

The whitespace-split command line.

required

Raises:

Type Description
UnknownCommandError

If no matching child or command is found.

Source code in src/applied_motion/cli/compose/core.py
def dispatch(self, tokens: Sequence[str]) -> None:
    """Route a token sequence to a child group or a local command.

    Args:
        tokens: The whitespace-split command line.

    Raises:
        UnknownCommandError: If no matching child or command is found.
    """
    if not tokens:
        return
    head = tokens[0].lower()
    rest = tokens[1:]
    if head in self.children:
        self.children[head].dispatch(rest)
        return
    if head in self.commands:
        self.commands[head].handler(rest)
        return
    raise UnknownCommandError(f"Unknown command: {tokens[0]!r}")

iter_paths

iter_paths(
    prefix: Sequence[str] = (),
) -> Iterator[tuple[str, ...]]

Yield the fully-qualified path of every command in the tree.

Parameters:

Name Type Description Default
prefix Sequence[str]

Internal prefix accumulator.

()

Yields:

Type Description
tuple[str, ...]

Tuples of namespace names ending in a command name.

Source code in src/applied_motion/cli/compose/core.py
def iter_paths(self, prefix: Sequence[str] = ()) -> Iterator[tuple[str, ...]]:
    """Yield the fully-qualified path of every command in the tree.

    Args:
        prefix: Internal prefix accumulator.

    Yields:
        Tuples of namespace names ending in a command name.
    """
    for name in self.commands:
        yield (*tuple(prefix), name)
    for child_name, child in self.children.items():
        yield from child.iter_paths((*tuple(prefix), child_name))

format_help

format_help(indent: int = 0) -> list[str]

Build indented help lines for this group and all descendants.

Parameters:

Name Type Description Default
indent int

Current indentation depth.

0

Returns:

Type Description
list[str]

A list of formatted help lines.

Source code in src/applied_motion/cli/compose/core.py
def format_help(self, indent: int = 0) -> list[str]:
    """Build indented help lines for this group and all descendants.

    Args:
        indent: Current indentation depth.

    Returns:
        A list of formatted help lines.
    """
    pad = "  " * indent
    lines: list[str] = []
    for cmd in self.commands.values():
        usage = cmd.usage or cmd.name
        suffix = f"    {cmd.help}" if cmd.help else ""
        lines.append(f"{pad}{usage}{suffix}")
    for child_name, child in self.children.items():
        header = f"{pad}{child_name}"
        if child.help:
            header = f"{header}    {child.help}"
        lines.append(header)
        lines.extend(child.format_help(indent + 1))
    return lines