Skip to content
v0.1.3

Audit Command API Reference

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

bijux_cli.commands.audit

Audit command for the Bijux CLI.

Audits the current environment and configuration, emitting machine-readable structured output in JSON or YAML. Supports dry-run simulation and writing results to a file. Handles ASCII hygiene and structured error contracts. Output is automation-safe and suitable for scripting or monitoring.

Output Contract
  • Success: {"status": "completed"}
  • Dry-run: {"status": "dry-run"}
  • Written: {"status": "written", "file": "<path>"}
  • Verbose: {"python": str, "platform": str}
  • Error: {"error": str, "code": int}
Exit Codes
  • 0: Success, dry-run, or write success.
  • 1: Unexpected/internal error.
  • 2: CLI argument/flag/format or output-path error.
  • 3: ASCII/encoding error.

audit

audit(
    ctx: Context,
    dry_run: bool = DRY_RUN_OPTION,
    output: Path | None = OUTPUT_OPTION,
    quiet: bool = Option(
        False, "-q", "--quiet", help=HELP_QUIET
    ),
    verbose: bool = Option(
        False, "-v", "--verbose", help=HELP_VERBOSE
    ),
    fmt: str = Option(
        "json", "-f", "--format", help=HELP_FORMAT
    ),
    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 audit command.

This function orchestrates the entire audit process. It validates all CLI flags and arguments, performs environment checks (e.g., for non-ASCII characters), builds the appropriate result payload, and emits it to stdout or a file in the specified format. All errors are handled and emitted in a structured format before exiting with a specific code.

Parameters:

  • ctx (Context) –

    The Typer context, used to manage command state and detect stray arguments.

  • dry_run (bool, default: DRY_RUN_OPTION ) –

    If True, simulates the audit and reports a "dry-run" status without performing actions.

  • output (Path | None, default: OUTPUT_OPTION ) –

    If a path is provided, writes the audit result to the specified file instead of stdout.

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

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

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

    If True, includes Python and platform details in the output payload.

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

    The output format, either "json" or "yaml". Defaults to "json".

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

    If True, pretty-prints the output for human readability. This is overridden by debug.

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

    If True, enables debug diagnostics, which implies verbose and pretty.

Returns:

  • None ( None ) –

Raises:

  • SystemExit

    Exits with a status code and structured error payload upon validation failures (e.g., bad arguments, ASCII errors), I/O issues, or unexpected exceptions. The exit code follows the contract defined in the module docstring.

Source code in src/bijux_cli/commands/audit.py
@audit_app.callback(invoke_without_command=True)
def audit(
    ctx: typer.Context,
    dry_run: bool = DRY_RUN_OPTION,
    output: Path | None = OUTPUT_OPTION,
    quiet: bool = typer.Option(False, "-q", "--quiet", help=HELP_QUIET),
    verbose: bool = typer.Option(False, "-v", "--verbose", help=HELP_VERBOSE),
    fmt: str = typer.Option("json", "-f", "--format", help=HELP_FORMAT),
    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 audit` command.

    This function orchestrates the entire audit process. It validates all CLI
    flags and arguments, performs environment checks (e.g., for non-ASCII
    characters), builds the appropriate result payload, and emits it to
    stdout or a file in the specified format. All errors are handled and
    emitted in a structured format before exiting with a specific code.

    Args:
        ctx (typer.Context): The Typer context, used to manage command state
            and detect stray arguments.
        dry_run (bool): If True, simulates the audit and reports a "dry-run"
            status without performing actions.
        output (Path | None): If a path is provided, writes the audit result
            to the specified file instead of stdout.
        quiet (bool): If True, suppresses all output except for errors. The
            exit code is the primary indicator of the outcome.
        verbose (bool): If True, includes Python and platform details in the
            output payload.
        fmt (str): The output format, either "json" or "yaml". Defaults to "json".
        pretty (bool): If True, pretty-prints the output for human readability.
            This is overridden by `debug`.
        debug (bool): If True, enables debug diagnostics, which implies `verbose`
            and `pretty`.

    Returns:
        None:

    Raises:
        SystemExit: Exits with a status code and structured error payload upon
            validation failures (e.g., bad arguments, ASCII errors), I/O
            issues, or unexpected exceptions. The exit code follows the
            contract defined in the module docstring.
    """
    if ctx.invoked_subcommand:
        return

    command = "audit"

    try:
        stray_args = [a for a in ctx.args if not a.startswith("-")]
        if stray_args:
            raise typer.BadParameter(f"No such argument: {stray_args[0]}")
        fmt_lower = validate_common_flags(fmt, command, quiet)
        include_runtime = verbose or debug
        effective_pretty = debug or pretty
        out_format = OutputFormat.YAML if fmt_lower == "yaml" else OutputFormat.JSON

        if contains_non_ascii_env():
            emit_error_and_exit(
                "Non-ASCII environment variables detected",
                code=3,
                failure="ascii_env",
                command=command,
                fmt=fmt_lower,
                quiet=quiet,
                include_runtime=include_runtime,
            )
        try:
            validate_env_file_if_present(os.environ.get("BIJUXCLI_CONFIG", ""))
        except ValueError as exc:
            emit_error_and_exit(
                str(exc),
                code=3,
                failure="ascii",
                command=command,
                fmt=fmt_lower,
                quiet=quiet,
                include_runtime=include_runtime,
            )

    except typer.BadParameter as exc:
        error_fmt = fmt.lower() if fmt.lower() in ("json", "yaml") else "json"
        emit_error_and_exit(
            exc.message,
            code=2,
            failure="args",
            command=command,
            fmt=error_fmt,
            quiet=quiet,
            include_runtime=verbose or debug,
        )

    try:
        emitter = DIContainer.current().resolve(EmitterProtocol)
        payload = _build_payload(include_runtime, dry_run)

        if output is not None:
            _write_output_file(
                output_path=output,
                payload=payload,
                emitter=emitter,
                fmt=out_format,
                pretty=effective_pretty,
                debug=debug,
                dry_run=dry_run,
            )
            payload = {"status": "written", "file": str(output)}
            if include_runtime:
                payload["python"] = ascii_safe(
                    platform.python_version(), "python_version"
                )
                payload["platform"] = ascii_safe(platform.platform(), "platform")

        new_run_command(
            command_name=command,
            payload_builder=lambda _: payload,
            quiet=quiet,
            verbose=(verbose or debug),
            fmt=fmt_lower,
            pretty=(debug or pretty),
            debug=debug,
        )

    except ValueError as exc:
        emit_error_and_exit(
            str(exc),
            code=3,
            failure="ascii",
            command=command,
            fmt=fmt_lower,
            quiet=quiet,
            include_runtime=include_runtime,
        )
    except OSError as exc:
        emit_error_and_exit(
            str(exc),
            code=2,
            failure="output_file",
            command=command,
            fmt=fmt_lower,
            quiet=quiet,
            include_runtime=include_runtime,
        )
    except Exception as exc:
        emit_error_and_exit(
            f"An unexpected error occurred: {exc}",
            code=1,
            failure="unexpected",
            command=command,
            fmt=fmt_lower,
            quiet=quiet,
            include_runtime=include_runtime,
        )