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:
LazyGroupGroup that falls back to the
wrapsubcommand 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_subcommandsmaps command names to their import paths.Tip
lazy_subcommandsis 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
LazySubcommandinstead 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.
- 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 breakisinstanceandissubclasschecks 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 explicitcls=(like Flask’sFlaskGroup) keeps its own class and a stockclick.Context, and is served by theget_helppatch 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.Nonekeeps the current default.unpatch_click()gives back the default this replaced.color (
bool|None) – Tri-state ANSI control mirroringctx.color:Trueforces colors on,Falsestrips them, andNone(the GNUautodefault) defers to the output stream’s TTY status.
- Return type:
- 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 aset_default_theme()call made while patched is kept.- Return type:
- click_extra.cli_wrapper.resolve_target(script)[source]¶
Resolve a script name to a module path and function name.
Resolution order:
console_scriptsentry points from installed packages.A local project directory: its
console_scriptsentry point is read frompyproject.toml/setup.cfgand its package is added tosys.path..pyfile path.Explicit
module:functionnotation.Bare Python module or package name.
- Return type:
- 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.pathso 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.argvso 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_namefalls back toclick.utils._detect_program_name(), which reads__main__.__package__. That attribute states how click-extra itself was launched: under a documentation build runningpython -m sphinx, a wrapped usage line would readpython -m sphinx.flask, and underpython -m click_extrait would readpython -m click_extra.flask. Emptying it for the call pins the detection on its file-execution branch, which answers the basename ofsys.argv[0]: the script name set above.
- 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). Optionalsubcommandsnavigate into nested groups, mirroring the path a user would type.Shared by the introspection modes of the
wrapcommand (--params,--man,--treeand--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:
- 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
.THline, a Carapace spec’sname, 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:
A path (a separator, or a
.pysuffix): its basename, dropping that suffix.path/to/my_cli.pyis run asmy_cli, not as its own path.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.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 namedcli).
Caution
Case 2 is a best effort. A target reached as
python -m my_package.clihas no single name a user types, so the command’s own is the closest thing to one. Pass an explicitprog_nameto the underlying renderer when that is not what you want in the output.- Return type:
- 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
wraphelp screen.