Skip to content
v0.1.3

Help Command API Reference

This section documents the internals of the help command in Bijux CLI.

bijux_cli.commands.help

Implements the help command for the Bijux CLI.

This module provides a contextual help system that can generate and display help text for any command or subcommand. It supports multiple output formats, including human-readable text for interactive use and structured JSON or YAML for automation and integration purposes. It also includes special logic to suppress known noisy warnings from the plugin system during help generation.

Output Contract
  • Human: Standard CLI help text is printed to stdout.
  • JSON/YAML: {"help": str}
  • Verbose: Adds {"python": str, "platform": str, "runtime_ms": int}.
  • Error: {"error": str, "code": int}
Exit Codes
  • 0: Success.
  • 1: Fatal or internal error.
  • 2: CLI argument, flag, or "command not found" error.
  • 3: ASCII or encoding error.

help_callback

help_callback(
    ctx: Context,
    command_path: list[str] | None = ARGS,
    quiet: bool = Option(
        False, "-q", "--quiet", help=HELP_QUIET
    ),
    verbose: bool = Option(
        False, "-v", "--verbose", help=HELP_VERBOSE
    ),
    fmt: str = Option(
        _HUMAN, "-f", "--format", help=HELP_FORMAT_HELP
    ),
    pretty: bool = Option(
        True, "--pretty/--no-pretty", help=HELP_NO_PRETTY
    ),
    debug: bool = Option(
        False, "-d", "--debug", help=HELP_DEBUG
    ),
) -> None

Defines the entrypoint and logic for the bijux help command.

This function orchestrates the entire help generation process. It parses the target command path, finds the corresponding command object, performs ASCII and format validation, and emits the help text in the specified format.

Parameters:

  • ctx (Context) –

    The Typer context for the CLI.

  • command_path (list[str] | None, default: ARGS ) –

    A list of tokens representing the path to the target command (e.g., ["config", "get"]).

  • quiet (bool, default: Option(False, '-q', '--quiet', help=HELP_QUIET) ) –

    If True, suppresses all output. The exit code is the primary indicator of outcome.

  • verbose (bool, default: Option(False, '-v', '--verbose', help=HELP_VERBOSE) ) –

    If True, includes Python and platform details in structured output formats.

  • fmt (str, default: Option(_HUMAN, '-f', '--format', help=HELP_FORMAT_HELP) ) –

    The output format: "human", "json", or "yaml".

  • pretty (bool, default: Option(True, '--pretty/--no-pretty', help=HELP_NO_PRETTY) ) –

    If True, pretty-prints structured output.

  • debug (bool, default: Option(False, '-d', '--debug', help=HELP_DEBUG) ) –

    If True, enables debug diagnostics, implying verbose and pretty.

Returns:

  • None ( None ) –

Raises:

  • SystemExit

    Always exits with a contract-compliant exit code and payload upon completion or error.

Source code in src/bijux_cli/commands/help.py
@help_app.callback(invoke_without_command=True)
def help_callback(
    ctx: typer.Context,
    command_path: list[str] | None = ARGS,
    quiet: bool = typer.Option(False, "-q", "--quiet", help=HELP_QUIET),
    verbose: bool = typer.Option(False, "-v", "--verbose", help=HELP_VERBOSE),
    fmt: str = typer.Option(_HUMAN, "-f", "--format", help=HELP_FORMAT_HELP),
    pretty: bool = typer.Option(True, "--pretty/--no-pretty", help=HELP_NO_PRETTY),
    debug: bool = typer.Option(False, "-d", "--debug", help=HELP_DEBUG),
) -> None:
    """Defines the entrypoint and logic for the `bijux help` command.

    This function orchestrates the entire help generation process. It parses the
    target command path, finds the corresponding command object, performs ASCII
    and format validation, and emits the help text in the specified format.

    Args:
        ctx (typer.Context): The Typer context for the CLI.
        command_path (list[str] | None): A list of tokens representing the path
            to the target command (e.g., `["config", "get"]`).
        quiet (bool): If True, suppresses all output. The exit code is the
            primary indicator of outcome.
        verbose (bool): If True, includes Python and platform details in
            structured output formats.
        fmt (str): The output format: "human", "json", or "yaml".
        pretty (bool): If True, pretty-prints structured output.
        debug (bool): If True, enables debug diagnostics, implying `verbose`
            and `pretty`.

    Returns:
        None:

    Raises:
        SystemExit: Always exits with a contract-compliant exit code and payload
            upon completion or error.
    """
    started_at = time.perf_counter()

    if "-h" in sys.argv or "--help" in sys.argv:
        all_args = sys.argv[2:]
        known_flags_with_args = {"-f", "--format"}
        path_tokens = []
        i = 0
        while i < len(all_args):
            arg = all_args[i]
            if arg in known_flags_with_args:
                i += 2
            elif arg.startswith("-"):
                i += 1
            else:
                path_tokens.append(arg)
                i += 1

        target = _find_target_command(ctx, path_tokens) or _find_target_command(ctx, [])
        if target:
            target_cmd, target_ctx = target
            help_text = _get_formatted_help(target_cmd, target_ctx)
            typer.echo(help_text)
        raise typer.Exit(0)

    tokens = command_path or []
    command = "help"
    effective_include_runtime = (verbose or debug) and not quiet
    effective_pretty = True if (debug and not quiet) else pretty
    fmt_lower = fmt.strip().lower()
    error_fmt = fmt_lower if fmt_lower in ("json", "yaml") else "json"

    if quiet:
        if fmt_lower not in _VALID_FORMATS:
            raise SystemExit(2)

        for token in tokens:
            if "\x00" in token:
                raise SystemExit(3)
            try:
                token.encode("ascii")
            except UnicodeEncodeError as err:
                raise SystemExit(3) from err

        if contains_non_ascii_env():
            raise SystemExit(3)

        if not _find_target_command(ctx, tokens):
            raise SystemExit(2)

        raise SystemExit(0)

    if fmt_lower != "human":
        validate_common_flags(
            fmt,
            command,
            quiet,
            include_runtime=effective_include_runtime,
        )

    if fmt_lower not in _VALID_FORMATS:
        emit_error_and_exit(
            f"Unsupported format: '{fmt}'",
            code=2,
            failure="format",
            command=command,
            fmt=error_fmt,
            quiet=quiet,
            include_runtime=effective_include_runtime,
            debug=debug,
        )

    for token in tokens:
        if "\x00" in token:
            emit_error_and_exit(
                "Embedded null byte in command path",
                code=3,
                failure="null_byte",
                command=command,
                fmt=error_fmt,
                quiet=quiet,
                include_runtime=effective_include_runtime,
                debug=debug,
            )
        try:
            token.encode("ascii")
        except UnicodeEncodeError:
            emit_error_and_exit(
                f"Non-ASCII characters in command path: {token!r}",
                code=3,
                failure="ascii",
                command=command,
                fmt=error_fmt,
                quiet=quiet,
                include_runtime=effective_include_runtime,
                debug=debug,
            )

    if contains_non_ascii_env():
        emit_error_and_exit(
            "Non-ASCII in environment",
            code=3,
            failure="ascii",
            command=command,
            fmt=error_fmt,
            quiet=quiet,
            include_runtime=effective_include_runtime,
            debug=debug,
        )

    target = _find_target_command(ctx, tokens)
    if not target:
        emit_error_and_exit(
            f"No such command: {' '.join(tokens)}",
            code=2,
            failure="not_found",
            command=command,
            fmt=error_fmt,
            quiet=quiet,
            include_runtime=effective_include_runtime,
            debug=debug,
        )

    DIContainer.current().resolve(EmitterProtocol)
    target_cmd, target_ctx = target
    help_text = _get_formatted_help(target_cmd, target_ctx)

    if fmt_lower == _HUMAN:
        typer.echo(help_text)
        raise typer.Exit(0)

    try:
        payload = _build_help_payload(help_text, effective_include_runtime, started_at)
    except ValueError as exc:
        emit_error_and_exit(
            str(exc),
            code=3,
            failure="ascii",
            command=command,
            fmt=fmt_lower,
            quiet=quiet,
            include_runtime=effective_include_runtime,
            debug=debug,
        )

    output_format = OutputFormat.YAML if fmt_lower == "yaml" else OutputFormat.JSON
    emit_and_exit(
        payload=payload,
        fmt=output_format,
        effective_pretty=effective_pretty,
        verbose=verbose,
        debug=debug,
        quiet=quiet,
        command=command,
        exit_code=0,
    )