Skip to content

CommandInfo

🛈 DocStrings

Framework-independent description of a CLI command and its subcommands.

Source code in src/clinspector/models/commandinfo.py
@dataclasses.dataclass
class CommandInfo:
    """Framework-independent description of a CLI command and its subcommands."""

    name: str
    """The name of the command."""
    description: str = ""
    """A description for this command."""
    usage: str = ""
    """A formatted string containing a formatted "usage string" (placeholder example)"""
    subcommands: dict[str, CommandInfo] = dataclasses.field(default_factory=dict)
    """A command-name->CommandInfo mapping containing all subcommands."""
    deprecated: bool = False
    """Whether this command is deprecated."""
    epilog: str | None = None
    """Epilog for this command."""
    hidden: bool = False
    """Whether this command is hidden."""
    callback: Callable[..., Any] | None = dataclasses.field(default=None, repr=False, compare=False)
    """The framework callback for this command (not part of `to_dict` / comparisons)."""
    params: list[Param] = dataclasses.field(default_factory=list)
    """A list of Params for this command."""
    _parent: CommandInfo | None = dataclasses.field(default=None, repr=False, compare=False)
    """Reference to parent command (internal use)."""

    def __post_init__(self) -> None:
        """Set parent references for all subcommands."""
        for subcmd in self.subcommands.values():
            subcmd._parent = self

    def __getitem__(self, name: str) -> CommandInfo:
        """Get a subcommand by name."""
        subcmd = self.subcommands[name]
        subcmd._parent = self  # Ensure parent is set (subcommands may be added later)
        return subcmd

    def walk(self) -> Iterator[CommandInfo]:
        """Iterate over this command and all (nested) subcommands, depth-first."""
        yield self
        for name in self.subcommands:
            yield from self[name].walk()

    def to_dict(self) -> dict[str, Any]:
        """Return a dict representation of this command tree (without callbacks)."""
        return {
            "name": self.name,
            "description": self.description,
            "usage": self.usage,
            "deprecated": self.deprecated,
            "epilog": self.epilog,
            "hidden": self.hidden,
            "params": [p.to_dict() for p in self.params],
            "subcommands": {k: v.to_dict() for k, v in self.subcommands.items()},
        }

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> CommandInfo:
        """Create a command tree from a dict (as returned by `to_dict`)."""
        return cls(
            name=data["name"],
            description=data.get("description", ""),
            usage=data.get("usage", ""),
            deprecated=data.get("deprecated", False),
            epilog=data.get("epilog"),
            hidden=data.get("hidden", False),
            params=[Param.from_dict(p) for p in data.get("params", [])],
            subcommands={k: cls.from_dict(v) for k, v in data.get("subcommands", {}).items()},
        )

    @property
    def full_path(self) -> list[str]:
        """Get the full command path as a list of command parts."""
        path: list[str] = []
        current: CommandInfo | None = self

        # Walk up the parent chain
        while current:
            if current.name:
                path.insert(0, current.name)
            current = current._parent

        return path

    @property
    def full_command(self) -> str:
        """Get the full command string including all parents."""
        return " ".join(self.full_path)

    def execute_callback(self, **kwargs: Any) -> Any:
        """Execute this command's callback with the given arguments.

        Args:
            **kwargs: Arguments to pass to the callback

        Returns:
            Result of the callback function

        Raises:
            ValueError: If the command has no callback
        """
        if not self.callback:
            msg = f"Command '{self.full_command}' has no callback"
            raise ValueError(msg)

        return self.callback(**kwargs)

    def build_cli_command(self, args: dict[str, Any] | None = None) -> list[str]:
        """Build the command line parts for execution.

        List / tuple values are repeated for options (`--opt a --opt b`) and
        expanded for arguments. Integer values for counting flags repeat the flag,
        False for flags with secondary options (`--x/--no-x`) emits the secondary one.

        Args:
            args: Dictionary of parameter name to value mappings

        Returns:
            List of command parts ready for subprocess execution
        """
        args = args or {}
        cmd_parts = self.full_path.copy()
        for p in self.params:
            value = args.get(p.name)
            if value is None:
                continue
            values = list(value) if isinstance(value, list | tuple) else [value]
            if not p.opts:
                cmd_parts.extend(str(v) for v in values)
            elif p.count and not isinstance(value, bool):
                cmd_parts.extend([p.opts[0]] * int(value))
            elif p.is_flag:
                if value:
                    cmd_parts.append(p.opts[0])
                elif p.secondary_opts:
                    cmd_parts.append(p.secondary_opts[0])
            else:
                for v in values:
                    cmd_parts.extend([p.opts[0], str(v)])

        return cmd_parts

    def execute_cli(
        self,
        args: dict[str, Any] | None = None,
        capture_output: bool = False,
        check: bool = True,
        env: dict[str, str] | None = None,
    ) -> subprocess.CompletedProcess[str]:
        """Execute this command as a CLI process.

        Args:
            args: Dictionary of parameter name to value mappings
            capture_output: Whether to capture stdout/stderr
            check: Whether to raise exception if command fails
            env: Environment variables to set for the process

        Returns:
            Completed process with results

        Raises:
            subprocess.CalledProcessError: If check=True and process returns non-zero
        """
        cmd_parts = self.build_cli_command(args)
        return subprocess.run(
            cmd_parts,
            text=True,
            capture_output=capture_output,
            check=check,
            env=env,
        )

callback class-attribute instance-attribute

callback: Callable[..., Any] | None = dataclasses.field(default=None, repr=False, compare=False)

The framework callback for this command (not part of to_dict / comparisons).

deprecated class-attribute instance-attribute

deprecated: bool = False

Whether this command is deprecated.

description class-attribute instance-attribute

description: str = ''

A description for this command.

epilog class-attribute instance-attribute

epilog: str | None = None

Epilog for this command.

full_command property

full_command: str

Get the full command string including all parents.

full_path property

full_path: list[str]

Get the full command path as a list of command parts.

hidden class-attribute instance-attribute

hidden: bool = False

Whether this command is hidden.

name instance-attribute

name: str

The name of the command.

params class-attribute instance-attribute

params: list[Param] = dataclasses.field(default_factory=list)

A list of Params for this command.

subcommands class-attribute instance-attribute

subcommands: dict[str, CommandInfo] = dataclasses.field(default_factory=dict)

A command-name->CommandInfo mapping containing all subcommands.

usage class-attribute instance-attribute

usage: str = ''

A formatted string containing a formatted "usage string" (placeholder example)

__getitem__

__getitem__(name: str) -> CommandInfo

Get a subcommand by name.

Source code in src/clinspector/models/commandinfo.py
def __getitem__(self, name: str) -> CommandInfo:
    """Get a subcommand by name."""
    subcmd = self.subcommands[name]
    subcmd._parent = self  # Ensure parent is set (subcommands may be added later)
    return subcmd

__post_init__

__post_init__() -> None

Set parent references for all subcommands.

Source code in src/clinspector/models/commandinfo.py
def __post_init__(self) -> None:
    """Set parent references for all subcommands."""
    for subcmd in self.subcommands.values():
        subcmd._parent = self

build_cli_command

build_cli_command(args: dict[str, Any] | None = None) -> list[str]

Build the command line parts for execution.

List / tuple values are repeated for options (--opt a --opt b) and expanded for arguments. Integer values for counting flags repeat the flag, False for flags with secondary options (--x/--no-x) emits the secondary one.

Parameters:

Name Type Description Default
args dict[str, Any] | None

Dictionary of parameter name to value mappings

None

Returns:

Type Description
list[str]

List of command parts ready for subprocess execution

Source code in src/clinspector/models/commandinfo.py
def build_cli_command(self, args: dict[str, Any] | None = None) -> list[str]:
    """Build the command line parts for execution.

    List / tuple values are repeated for options (`--opt a --opt b`) and
    expanded for arguments. Integer values for counting flags repeat the flag,
    False for flags with secondary options (`--x/--no-x`) emits the secondary one.

    Args:
        args: Dictionary of parameter name to value mappings

    Returns:
        List of command parts ready for subprocess execution
    """
    args = args or {}
    cmd_parts = self.full_path.copy()
    for p in self.params:
        value = args.get(p.name)
        if value is None:
            continue
        values = list(value) if isinstance(value, list | tuple) else [value]
        if not p.opts:
            cmd_parts.extend(str(v) for v in values)
        elif p.count and not isinstance(value, bool):
            cmd_parts.extend([p.opts[0]] * int(value))
        elif p.is_flag:
            if value:
                cmd_parts.append(p.opts[0])
            elif p.secondary_opts:
                cmd_parts.append(p.secondary_opts[0])
        else:
            for v in values:
                cmd_parts.extend([p.opts[0], str(v)])

    return cmd_parts

execute_callback

execute_callback(**kwargs: Any) -> Any

Execute this command's callback with the given arguments.

Parameters:

Name Type Description Default
**kwargs Any

Arguments to pass to the callback

{}

Returns:

Type Description
Any

Result of the callback function

Raises:

Type Description
ValueError

If the command has no callback

Source code in src/clinspector/models/commandinfo.py
def execute_callback(self, **kwargs: Any) -> Any:
    """Execute this command's callback with the given arguments.

    Args:
        **kwargs: Arguments to pass to the callback

    Returns:
        Result of the callback function

    Raises:
        ValueError: If the command has no callback
    """
    if not self.callback:
        msg = f"Command '{self.full_command}' has no callback"
        raise ValueError(msg)

    return self.callback(**kwargs)

execute_cli

execute_cli(
    args: dict[str, Any] | None = None,
    capture_output: bool = False,
    check: bool = True,
    env: dict[str, str] | None = None,
) -> CompletedProcess[str]

Execute this command as a CLI process.

Parameters:

Name Type Description Default
args dict[str, Any] | None

Dictionary of parameter name to value mappings

None
capture_output bool

Whether to capture stdout/stderr

False
check bool

Whether to raise exception if command fails

True
env dict[str, str] | None

Environment variables to set for the process

None

Returns:

Type Description
CompletedProcess[str]

Completed process with results

Raises:

Type Description
CalledProcessError

If check=True and process returns non-zero

Source code in src/clinspector/models/commandinfo.py
def execute_cli(
    self,
    args: dict[str, Any] | None = None,
    capture_output: bool = False,
    check: bool = True,
    env: dict[str, str] | None = None,
) -> subprocess.CompletedProcess[str]:
    """Execute this command as a CLI process.

    Args:
        args: Dictionary of parameter name to value mappings
        capture_output: Whether to capture stdout/stderr
        check: Whether to raise exception if command fails
        env: Environment variables to set for the process

    Returns:
        Completed process with results

    Raises:
        subprocess.CalledProcessError: If check=True and process returns non-zero
    """
    cmd_parts = self.build_cli_command(args)
    return subprocess.run(
        cmd_parts,
        text=True,
        capture_output=capture_output,
        check=check,
        env=env,
    )

from_dict classmethod

from_dict(data: dict[str, Any]) -> CommandInfo

Create a command tree from a dict (as returned by to_dict).

Source code in src/clinspector/models/commandinfo.py
@classmethod
def from_dict(cls, data: dict[str, Any]) -> CommandInfo:
    """Create a command tree from a dict (as returned by `to_dict`)."""
    return cls(
        name=data["name"],
        description=data.get("description", ""),
        usage=data.get("usage", ""),
        deprecated=data.get("deprecated", False),
        epilog=data.get("epilog"),
        hidden=data.get("hidden", False),
        params=[Param.from_dict(p) for p in data.get("params", [])],
        subcommands={k: cls.from_dict(v) for k, v in data.get("subcommands", {}).items()},
    )

to_dict

to_dict() -> dict[str, Any]

Return a dict representation of this command tree (without callbacks).

Source code in src/clinspector/models/commandinfo.py
def to_dict(self) -> dict[str, Any]:
    """Return a dict representation of this command tree (without callbacks)."""
    return {
        "name": self.name,
        "description": self.description,
        "usage": self.usage,
        "deprecated": self.deprecated,
        "epilog": self.epilog,
        "hidden": self.hidden,
        "params": [p.to_dict() for p in self.params],
        "subcommands": {k: v.to_dict() for k, v in self.subcommands.items()},
    }

walk

walk() -> Iterator[CommandInfo]

Iterate over this command and all (nested) subcommands, depth-first.

Source code in src/clinspector/models/commandinfo.py
def walk(self) -> Iterator[CommandInfo]:
    """Iterate over this command and all (nested) subcommands, depth-first."""
    yield self
    for name in self.subcommands:
        yield from self[name].walk()

:fa-brands-github: Show source on GitHub