Skip to content

help_text

Class info

🛈 DocStrings

Parse raw --help output into a CommandInfo.

This is a best-effort, heuristic parser for the common help layouts of argparse, click, typer, rich-click, docopt, cement, cliff, plac and fire. Use the framework introspection (get_cmd_info) instead whenever the CLI object itself is available.

parse_help_text

parse_help_text(text: str) -> CommandInfo

Parse the --help output of a CLI program into a CommandInfo.

Recognized sections are options (Options:, optional arguments:, ...), positional arguments (argparse subcommand lists included) and commands. Subcommands are returned without params (their help pages are separate).

Parameters:

Name Type Description Default
text str

The help text (ANSI color codes are stripped).

required
Source code in src/clinspector/introspect/help_text.py
def parse_help_text(text: str) -> CommandInfo:
    """Parse the `--help` output of a CLI program into a `CommandInfo`.

    Recognized sections are options (`Options:`, `optional arguments:`, ...),
    positional arguments (argparse subcommand lists included) and commands.
    Subcommands are returned without params (their help pages are separate).

    Args:
        text: The help text (ANSI color codes are stripped).
    """
    lines = _ANSI_RE.sub("", text).expandtabs().splitlines()
    usage, usage_start, usage_end = _usage_block(lines)
    prog = _prog_name(usage, lines)

    sections: list[tuple[str | None, list[str]]] = []
    free_lines: list[tuple[int, str]] = []
    first_section = len(lines)
    current: list[str] | None = None
    for i, line in enumerate(lines):
        if usage_start <= i < usage_end:
            current = None
            continue
        if (match := _SECTION_RE.match(line)) and not line[:1].isspace():
            current = []
            sections.append((_section_kind(match["title"]), current))
            first_section = min(first_section, i)
        elif current is not None and (line[:1].isspace() or not line.strip()):
            current.append(line)
        else:
            current = None
            if line.strip():
                free_lines.append((i, line.strip()))

    # description: text between usage and the first section, else text before the usage
    # (docopt / cement put a title line first). Text after the sections is the epilog.
    after_usage = [t for i, t in free_lines if usage_end <= i < first_section]
    before_usage = [t for i, t in free_lines if i < min(usage_start % len(lines), first_section)]
    description = " ".join(after_usage or before_usage)
    epilog = " ".join(t for i, t in free_lines if i > first_section) or None
    params: list[Param] = []
    subcommands: dict[str, CommandInfo] = {}

    def add_command(name: str | None, help_text: str) -> None:
        if name and name not in subcommands:
            subcommands[name] = CommandInfo(name=name, description=help_text)

    for kind, section_lines in sections:
        entries = _parse_entries(section_lines)
        for entry in entries:
            if kind == "options":
                if param := _parse_option(entry):
                    params.append(param)
            elif kind == "commands":
                add_command(_command_name(entry.term, prog), entry.help)
            elif kind == "positional":
                if match := _CHOICES_RE.match(entry.term):  # argparse subparsers
                    for child in entry.children:
                        add_command(_command_name(child.term, prog), child.help)
                    for name in re.split(r"[|,]", match["choices"]):
                        add_command(name.strip(), "")
                else:
                    name = entry.term.strip("<>[]").lower()
                    params.append(
                        Param(
                            name=name,
                            help=entry.help or None,
                            required=True,
                            param_type_name="argument",
                            metavar=entry.term,
                        )
                    )

    return CommandInfo(
        name=prog,
        description=description,
        usage=usage,
        params=params,
        subcommands=subcommands,
        epilog=epilog,
    )