gfw.common.cli#

Lightweight framework around argparse for building CLIs more easily.

Classes#

CLI

Wrapper around argparse for building CLIs more easily.

Command

Abstract base class representing a CLI command or subcommand.

ParametrizedCommand

Command implementation that is fully parameterized via constructor arguments.

Option

Represents a CLI option.

class CLI(name='python /home/docs/checkouts/readthedocs.org/user_builds/gfw-common/envs/latest/lib/python3.12/site-packages/sphinx/__main__.py', description='', options=None, subcommands=None, run=<function CLI.<lambda>>, version='0.1.0', examples=(), formatter=<function default_formatter.<locals>.formatter>, logger_config=None, allow_unknown=False, use_underscore=False, **main_parser_kwargs)[source]#

Wrapper around argparse for building CLIs more easily.

Key Features:
  • Supports a single command or multiple subcommands CLI.

  • Common CLI options can be easily defined once and shared across subcommands.

  • Configuration resolution: CLI arguments > config file > command defaults.

  • Rich logging with optional plain-text fallback.

  • Optionally allows unrecognized CLI arguments for custom handling.

  • Provides builtin options to provide config file, disable rich logging, etc.

Parameters:
  • name (str) – The main command to be run on the command line (e.g., my-cli).

  • description (str) – A brief message describing what the CLI application does.

  • options (List[Option] | None) – A tuple of Option instances representing CLI arguments for the main command. These options are inherited by every subcommand, if any.

  • run (Callable[[...], Any]) – Callable to be run when no subcommands are defined.

  • subcommands (List[Command | Type[Command]] | None) – A list containing either Command instances or types. Each item represents a subcommand to be registered in the CLI. If a type is provided, it will be instantiated automatically. This allows flexibility in defining subcommands either by passing already created instances or by passing the command classes themselves.

  • version (str) – The version of the application.

  • examples (Tuple[str, ...]) – Example command-line usages shown in the help footer.

  • formatter (Callable[[...], HelpFormatter]) – Callable that returns a HelpFormatter for customizing help text.

  • logger_config (LoggerConfig | None) – LoggerConfig instance to control logging behavior.

  • allow_unknown (bool) – If True, unknown CLI arguments are allowed.

  • use_underscore (bool) – If True, converts hyphens in the option name to underscores (e.g., --log_file). If False (default), converts underscores to hyphens (e.g., --log-file). This controls the naming convention of the CLI argument.

  • **main_parser_kwargs (Any) – Extra arguments passed to ArgumentParser constructor of the main command.

classmethod builtin_options()[source]#

Defines built-in CLI options used across commands.

Return type:

list[Option]

property common_parser: ArgumentParser#

Constructs the common parser containing built-in CLI options.

execute(args=['-T', '-b', 'html', '-d', '_build/doctrees', '-D', 'language=en', '.', '/home/docs/checkouts/readthedocs.org/user_builds/gfw-common/checkouts/latest/_readthedocs//html'], **kwargs)[source]#

Parse arguments, load config, and execute the CLI command.

Parameters:
  • args (list[str]) – Command-line arguments (defaults to sys.argv[1:]).

  • **kwargs (Any) – Extra keyword arguments passed to the command’s run() method.

Returns:

  • Result of the executed command.

  • Configuration dictionary used for execution.

Return type:

Tuple

property main_parser: ArgumentParser#

Constructs the main argument parser.

property title: str#

Returns the CLI program title with version.

class Command[source]#

Abstract base class representing a CLI command or subcommand.

This class defines the essential interface that any command implementation must follow to be compatible with the CLI framework.

Subclasses must provide the command’s name, description, options, and implement the run() method which contains the command’s logic.

Properties:
name:

The name of the command (used as the CLI argument, e.g., mycli <name>). For subcommands, this distinguishes them from the main command.

description:

A brief help message describing what the subcommand does.

options:

A list of Option instances representing CLI arguments specific to this subcommand.

run()[source]#

A callable to execute when the subcommand is invoked. It should accept keyword arguments corresponding to the CLI options.

Return type:

Any

copy_with(**kwargs)[source]#

Returns a new command changing some of its properties.

Return type:

ParametrizedCommand

defaults()[source]#

Returns a dictionary of default values for all CLI options.

Returns:

A dictionary mapping option dest (as used in argparse) to their default values.

Return type:

dict[str, Any]

abstract property description: str#

The command’s description.

property header: str#

Returns a descriptive title for the command’s options group.

abstract property name: str#

The name of the command (used as the CLI argument, e.g., mycli <name>).

For subcommands, this distinguishes them from the main command.

abstract property options: List[Option]#

The command’s options.

abstractmethod run(config, **kwargs)[source]#

Executes the command logic.

Return type:

Any

class Option(*flags, type, default=None, required=False, **kwargs)[source]#

Represents a CLI option.

Provides a declarative interface to define command-line options that can be added to an argparse.ArgumentParser instance via its add_argument() method.

Parameters:
  • *flags (str) –

    One or more command-line flag strings for this option. These are passed directly to argparse’s add_argument(). The first long flag (if any) is used to derive the internal name, which is also used as the destination (dest()) when parsing.

    Three examples:
    Option("-c", "--config-file", ...)  # Short and long form
    Option("--verbose", ...)  # Long form only
    Option("-v", ...)  # Short form only
    

  • type (Callable[[...], Any]) – A callable that converts the command-line string to the desired Python type. Typically, a built-in type like str, int, float, or bool.

  • default (Any) – The default value to use if the option is not provided. This should match the specified type, although no enforcement is currently done.

  • required (bool) – We capture the required flag so we can validate it not only against command-line parameters but also against the provided config file.

  • **kwargs (Any) – Additional keyword arguments passed directly to add_argument().

property dest: str#

Returns the internal variable name used by argparse for this option.

Uses the last long flag (e.g., --config-file) if present, or the first flag as a fallback. Dashes are converted to underscores for compatibility with argparse’s variable naming.

class ParametrizedCommand(name, description='', options=None, run=<function ParametrizedCommand.<lambda>>, **y)[source]#

Command implementation that is fully parameterized via constructor arguments.

The command’s name, description, CLI options, and run behavior are provided when instantiating this class, allowing quick creation of commands without subclassing.

Parameters:
  • name (str) – The name of the command (used as a CLI argument).

  • help – A brief help message describing what the command does.

  • options (Optional[List[Option]]) – A list of Option instances representing CLI arguments specific to this command.

  • run (Callable[..., Any]) – Callable executed when the command is invoked. It should accept keyword arguments matching the options.

copy_with(**kwargs)#

Returns a new command changing some of its properties.

Return type:

ParametrizedCommand

defaults()#

Returns a dictionary of default values for all CLI options.

Returns:

A dictionary mapping option dest (as used in argparse) to their default values.

Return type:

dict[str, Any]

property description: str#

The command’s description.

property header: str#

Returns a descriptive title for the command’s options group.

property name: str#

The command’s name.

property options: List[Option]#

The command’s options.

run(config, **kwargs)[source]#

Execute the command logic.

Return type:

Any