click_extra.cli_wrapper module

        classDiagram
  Command <|-- _WrapCommand
  LazyGroup <|-- WrapperGroup
  _HelpColorsMixin <|-- _WrapCommand
    

The click-extra wrap command and the machinery to wrap a foreign Click CLI.

Monkey-patches Click’s decorator functions before importing (or running) a target module so its @click.command() / @click.group() produce colorized, keyword-highlighted, themed variants. Also resolves and invokes the target, and introspects it for --params, --man, --tree and --help-format without firing its callbacks.

Not to be confused with text wrapping: that is click.wrap_text(), exposed at the package root as click_extra.wrap_text.

class click_extra.cli_wrapper.WrapperGroup(*args, lazy_subcommands=None, **kwargs)[source]

Bases: LazyGroup

Group that falls back to the wrap subcommand for unknown names.

Known subcommands and their aliases are dispatched normally, the lazy ones included. Anything else is treated as a target script and forwarded to wrap.

lazy_subcommands maps command names to their import paths.

Tip

lazy_subcommands is a map of the form:

{"<command-name>": "<module-name>.<command-object-name>"}

For example:

{"mycmd": "my_cli.commands.mycmd"}

A subcommand needing registration settings on top of its import path is declared with a LazySubcommand instead of a bare string:

{"mycmd": LazySubcommand("my_cli.commands.mycmd", section=my_section)}

Every section declared that way is registered on the group here, so the help screen orders its sections as the author declared them. Waiting for each subcommand to be imported would instead order them by import, which is alphabetical and says nothing about intent.

resolve_command(ctx, args)[source]
Return type:

tuple[str | None, Command | None, list[str]]

click_extra.cli_wrapper.patch_click(theme=None, color=True)[source]

Replace Click’s decorator functions with colorized variants.

Must be called before importing the target CLI module so that @click.command() and @click.group() decorators produce colorized commands.

Note

Only the decorator functions are replaced, not the class names (click.Command, click.Group). Replacing class names would break isinstance and issubclass checks in Click internals (_param_memo) and Cloup’s decorator validators.

Note

A decided color (anything but None) is pinned in two places, because the two kinds of target are colorized by different routes. One built with a plain @click.command() picks up the patched decorator and therefore is a _HelpColorsMixin: the context class installed below carries the decision for it. One carrying an explicit cls= (like Flask’s FlaskGroup) keeps its own class and a stock click.Context, and is served by the get_help patch further down instead. Cover a single route and the flag silently works for half the CLIs in the wild.

Parameters:
  • theme (HelpTheme | None) – Color theme to use, as the process-wide default. None keeps the current default. unpatch_click() gives back the default this replaced.

  • color (bool | None) – Tri-state ANSI control mirroring ctx.color: True forces colors on, False strips them, and None (the GNU auto default) defers to the output stream’s TTY status.

Return type:

None

click_extra.cli_wrapper.unpatch_click()[source]

Restore Click’s original decorator functions and methods.

Reverses the changes made by patch_click(). Useful in tests to avoid leaking global state between test cases.

The process-wide default theme goes back to the one in place before the first patch_click() call that set a theme. If no call set one, the default stays as it is, so a set_default_theme() call made while patched is kept.

Return type:

None

click_extra.cli_wrapper.resolve_target(script)[source]

Resolve a script name to a module path and function name.

Resolution order:

  1. console_scripts entry points from installed packages.

  2. A local project directory: its console_scripts entry point is read from pyproject.toml / setup.cfg and its package is added to sys.path.

  3. .py file path.

  4. Explicit module:function notation.

  5. Bare Python module or package name.

Return type:

tuple[str, str]

Returns:

(module_path, function_name) tuple. function_name is empty when the target should be invoked as a module or script file.

Raises:

click.ClickException – If the script cannot be resolved.

Note

Resolving a local project directory has a side effect: the directory holding its top-level package is prepended to sys.path so the subsequent import succeeds. The target’s own dependencies must still be importable in the current environment.

click_extra.cli_wrapper.invoke_target(script, module_path, function_name, args)[source]

Import and call the target CLI.

Reconstructs sys.argv so Click’s argument parsing sees the target’s program name and arguments, and pins __main__.__package__ so the program name Click detects is that same script name.

Note

A target whose Click command is invoked without an explicit prog_name falls back to click.utils._detect_program_name(), which reads __main__.__package__. That attribute states how click-extra itself was launched: under a documentation build running python -m sphinx, a wrapped usage line would read python -m sphinx.flask, and under python -m click_extra it would read python -m click_extra.flask. Emptying it for the call pins the detection on its file-execution branch, which answers the basename of sys.argv[0]: the script name set above.

Parameters:
  • script (str) – Original script name (used as sys.argv[0]).

  • module_path (str) – Dotted module path or .py file path.

  • function_name (str) – Function to call, or empty for module execution.

  • args (tuple[str, ...]) – Arguments to pass to the target CLI.

Return type:

None

click_extra.cli_wrapper.resolve_target_command(script, subcommands=())[source]

Import SCRIPT and return its Click command object and a matching context.

Resolves SCRIPT through resolve_target(), imports the module, then obtains the command object without running the CLI: the entry-point attribute when it is itself a command, otherwise by scanning the module’s namespace for Click command instances (preferring groups). Optional subcommands navigate into nested groups, mirroring the path a user would type.

Shared by the introspection modes of the wrap command (--params, --man, --tree and --help-format) and by the man page hook of the Sphinx extension, so all describe the exact same resolved command.

Raises:

click.ClickException – when no unambiguous Click command can be found, or a requested subcommand does not exist.

Return type:

tuple[Command, Context]

click_extra.cli_wrapper.target_prog_name(script, command)[source]

Return the name a user would type to run SCRIPT.

Every rendering of a target is titled with this: a man page’s .TH line, a Carapace spec’s name, a Markdown heading, the root of a --tree. None of them wants the string that was typed to reach the command, which is a filesystem path or a dotted import path as often as it is a command name.

Three shapes, in the order they are distinguished:

  1. A path (a separator, or a .py suffix): its basename, dropping that suffix. path/to/my_cli.py is run as my_cli, not as its own path.

  2. A dotted or colon-separated import path: the command’s own name, which Click took from the function or an explicit name=. An import path names a module, never a binary.

  3. Anything else is a console-script name, already exactly what a user types, and beats the command’s own name when the two differ (Flask’s entry point is flask, its group object is named cli).

Caution

Case 2 is a best effort. A target reached as python -m my_package.cli has no single name a user types, so the command’s own is the closest thing to one. Pass an explicit prog_name to the underlying renderer when that is not what you want in the output.

Return type:

str

click_extra.cli_wrapper.WRAP_EPILOG = "\x08\nExamples:\n\n\x08\n  Run a CLI with Click Extra's colored help:\n    $ click-extra wrap -- my-cli --help\n\n\x08\n  Read the help of one of its subcommands:\n    $ click-extra wrap -- my-cli pick --help\n\n\x08\n  Report what a subcommand accepts, and where each value comes from:\n    $ click-extra wrap --params -- my-cli pick\n\n\x08\n  Write a shell-completion spec where its consumer looks for it:\n    $ click-extra wrap --help-format carapace --install -- my-cli\n"

Sample invocations closing the wrap help screen.