click_extra package¶

Expose package-wide elements.

Importing this package is the startup cost of every CLI built on it, so the dependencies a code path may never need (wcwidth, PyYAML, wcmatch and extra-platforms) are imported where they are used, and tests/test_commands.py checks that a hello-world --help loads none of them.

Todo

Drop CLOUP_METADATA_PROBE_VERSION from tests/test_commands.py once this package’s cloup floor is above 4.0.0. That release is the last to import importlib.metadata at module scope, which janluke/cloup#242 removes. The startup ballast list then names importlib.metadata and email unconditionally.

Todo

Delete _DEPRECATED_CLICK_EXPORTS, the loop dropping its bindings and its branch in __getattr__ once the Click floor reaches 9.0, which removes the five names it forwards.

Todo

Delete click_extra/blocks.py, the deprecated alias of click_extra.markdown.blocks, and its tests in tests/test_blocks.py in 11.0.0: its warnings announce that release.

Todo

Delete _DEPRECATED_NAMES, _MOVED_NAMES, _REMOVAL_VERSION and __getattr__ from click_extra/capture/recording.py in 11.0.0, which stops serving ERASE_IN_LINE, PARTIAL_CSI_RE, SELECT_GRAPHIC_RENDITION and TerminalScreen, with their test in tests/test_recording.py: its warnings announce that release.

Todo

Delete _tile_runs, _TILE_RUN and _TILE_RE from click_extra/capture/svg.py in 11.0.0, with the __getattr__ serving them as tile_runs, TILE_RUN and _TILING_RE, and their tests in tests/test_screenshots.py: its warnings announce that release.

Todo

Delete click_extra/sphinx/tabs.py, its setup call in click_extra/sphinx/__init__.py, tests/sphinx/test_sphinx_tabs.py, its NON_META_KEYS entry in tests/test_context.py and the vertical tab-sets section of docs/sphinx.md in 11.0.0: its warnings announce that release. Move its entry in docs/upstream.md to the upstreamed section.

exception click_extra.Abort[source]¶

Bases: RuntimeError

An internal signalling exception that signals Click to abort.

class click_extra.AccessibleOption(param_decls=None, *, is_flag=True, default=False, is_eager=True, expose_value=False, help='Accessibility mode: disable colors and render tables in a borderless, screen-reader-friendly format.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured --accessible switch.

Turning it on (either via the flag or the ACCESSIBLE environment variable) is equivalent to passing --no-color --no-progress --table-format plain, and additionally streams echo_via_pager() output without a pager and turns clear() into a no-op: it strips ANSI codes, silences progress spinners and bars, renders tables without box-drawing characters, and avoids interactive screen takeovers.

Note

It is a one-way flag with no --no-accessible counterpart: to opt back out, pass the explicit --color / --table-format you want, which take precedence anyway (see below). A negation flag would also be the widest option label in the help screen, pushing every other option’s description column to the right.

The switch only adjusts the defaults of the --color and --table-format options, through the context’s default_map. An explicit --color / --table-format on the command line (or in a configuration file) therefore keeps precedence over --accessible.

This option is eager so it lands its defaults before --color and --table-format are resolved.

Note

The values are injected with dict.setdefault(), so they never clobber a colorization or table format already requested by the user. Combined with the ChainMap that ConfigOption layers on top of default_map, this yields the precedence: command line > configuration file > --accessible > built-in defaults.

set_accessible(ctx, param, value)[source]¶

Publish the accessibility intent and lower color/progress/table defaults.

Reconciles --accessible with the ACCESSIBLE environment variable, stores the result at ACCESSIBLE for output helpers (clear(), echo_via_pager()) to read, then lowers the --color / --progress / --table-format defaults when active. A CLI that never sees --accessible (nor ACCESSIBLE) keeps every default untouched.

ACCESSIBLE is a machine-wide variable, so the command line and the variable of the option outrank it, as they do for every machine-wide variable (see machine_envvars_apply()). The precedence is: --accessible > <CLI>_ACCESSIBLE > ACCESSIBLE > configuration file > built-in default.

Important

ACCESSIBLE outranks a configuration file, where the other machine-wide variables rank below one. The mode works by lowering the defaults of other options, and parse_args() settles it from the command line and the environment before the configuration file loads, so that --help and --version render in accessible mode too. A file read later could not take those lowered defaults back: it would leave the colors off while the mode reads as off.

Note

The global ACCESSIBLE environment variable is read here rather than wired through the option’s envvar. Click would otherwise list it alongside the auto-generated <CLI>_ACCESSIBLE variable in the --params table, making the combined string the widest cell of the env-var column and pushing every other row’s padding out. This mirrors how ColorOption reads NO_COLOR and friends.

Return type:

None

class click_extra.Argument(param_decls, required=None, help=None, **attrs)[source]¶

Bases: _ParameterMixin, Argument

click.Argument with the overrides of _ParameterMixin.

Inherits from Click directly: cloup.Argument is click.Argument itself.

class click_extra.ArgumentKwargs[source]¶

Bases: _ParamKwargs

Arguments accepted by argument().

Refer to click.Argument for their meaning and defaults.

callback: NotRequired[Callable[[Context, Argument, Any], Any] | None]¶
shell_complete: NotRequired[Callable[[Context, Argument, str], list[CompletionItem] | list[str]] | None]¶
help: NotRequired[str | None]¶
deprecated: NotRequired[bool | str]¶
type: NotRequired[ParamType[Any] | Callable[[str], Any] | tuple[ParamType[Any] | Callable[[str], Any], ...] | None]¶
required: NotRequired[bool | None]¶
default: NotRequired[Any | Callable[[], Any] | None]¶
nargs: NotRequired[int | None]¶
metavar: NotRequired[str | None]¶
expose_value: NotRequired[bool]¶
envvar: NotRequired[str | Sequence[str] | None]¶
exception click_extra.BadArgumentUsage(message, ctx=None)[source]¶

Bases: UsageError

Raised if an argument is generally supplied but the use of the argument was incorrect. This is for instance raised if the number of values for an argument is not correct.

Added in version 6.0.

exception click_extra.BadOptionUsage(option_name, message, ctx=None)[source]¶

Bases: UsageError

Raised if an option is generally supplied but the use of the option was incorrect. This is for instance raised if the number of arguments for an option is not correct.

Added in version 4.0.

Parameters:

option_name (str) – the name of the option being used incorrectly.

option_name: Final[str]¶
exception click_extra.BadParameter(message, ctx=None, param=None, param_hint=None)[source]¶

Bases: UsageError

An exception that formats out a standardized error message for a bad parameter. This is useful when thrown from a callback or type as Click will attach contextual information to it (for instance, which parameter it is).

Added in version 2.0.

Parameters:
  • param (Parameter | None) – the parameter object that caused this error. This can be left out, and Click will attach this info itself if possible.

  • param_hint (Sequence[str] | str | None) – a string that shows up as parameter name. This can be used as alternative to param in cases where custom validation should happen. If it is a string it’s used as such, if it’s a list then each item is quoted and separated.

param: Parameter | None¶
param_hint: Sequence[str] | str | None¶
format_message()[source]¶
Return type:

str

class click_extra.CLITestCase(cli_parameters=tuple(), env=dict(), unset_env=tuple(), skip_platforms=tuple(), only_platforms=tuple(), timeout=None, exit_code=None, strip_ansi=False, output_contains=tuple(), stdout_contains=tuple(), stderr_contains=tuple(), output_regex_matches=tuple(), stdout_regex_matches=tuple(), stderr_regex_matches=tuple(), output_regex_fullmatch=None, stdout_regex_fullmatch=None, stderr_regex_fullmatch=None)[source]¶

Bases: object

A single CLI test case: how to invoke the command and what to expect.

Each case runs the command-under-test once with cli_parameters appended, then checks the captured result against the expectation directives below. A case with no expectation only asserts the command ran (plus exit_code, if set).

cli_parameters: tuple[str, ...] | str¶

Arguments and options appended to the command-under-test.

A plain string is split into arguments the way the platform’s own parser does, quoted runs kept whole: shlex on POSIX, CommandLineToArgvW on Windows. A list or tuple is used as-is.

env: dict[str, str]¶

Environment variables set on the command, over the inherited environment.

The second input surface of a CLI, and the only way to reach a variable-only feature from a suite: an option can be typed as a cli_parameters flag, a variable cannot. Values must be strings, so a number or a boolean is quoted ("1", not 1): an environment holds strings only, and coercing would have to pick between True and true on the author’s behalf.

Applied to that one child process, never to the suite runner’s own environment, so cases stay independent under --jobs. See unset_env to take a variable away instead.

unset_env: tuple[str, ...] | str¶

Environment variables removed from the inherited environment.

The half env cannot express. Assigning the empty string leaves a variable set, and a flag read by bare presence (like ACCESSIBLE or DO_NOT_TRACK) counts that as activation, so hiding one from the command means removing it. This is what keeps a case from answering to whatever the shell running the suite happens to export.

A separate directive rather than a null value in env because TOML has no null literal, and a suite is as likely to be written in TOML as in YAML. Removing a variable that is not set is a no-op.

skip_platforms: Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[_TNestedReferences]]¶

Platforms (or platform-group IDs) on which to skip this case.

Accepts extra_platforms identifiers such as linux, macos, windows, in any case, mixed freely with group IDs.

only_platforms: Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[_TNestedReferences]]¶

Restrict this case to these platforms; skip it everywhere else.

The mirror image of skip_platforms, using the same identifiers.

timeout: float | str | None = None¶

Seconds before the command is killed and the case fails as a timeout.

Falls back to the command’s --timeout default, then to no limit.

exit_code: int | str | None = None¶

Expected process exit code; the case fails on any other code.

strip_ansi: bool = False¶

Strip ANSI escape sequences from the captured output before matching.

output_contains: tuple[str, ...] | str¶

Substrings that must all be present in the combined output.

The combined output interleaves stdout and stderr in the order the command wrote them, matching what a user sees in a terminal. The output_* directives are mutually exclusive with the stdout_* / stderr_* ones: a single subprocess run captures either the merged stream or the separate ones, not both.

stdout_contains: tuple[str, ...] | str¶

Substrings that must all be present in stdout.

stderr_contains: tuple[str, ...] | str¶

Substrings that must all be present in stderr.

output_regex_matches: tuple[Pattern | str, ...] | str¶

Regexes that must each match somewhere in the combined output (searched, re.DOTALL). See output_contains for the merged-stream semantics.

stdout_regex_matches: tuple[Pattern | str, ...] | str¶

Regexes that must each match somewhere in stdout (searched, re.DOTALL).

stderr_regex_matches: tuple[Pattern | str, ...] | str¶

Regexes that must each match somewhere in stderr (searched, re.DOTALL).

output_regex_fullmatch: Pattern | str | None = None¶

Regex that must fully match the combined output, line by line. See output_contains for the merged-stream semantics.

stdout_regex_fullmatch: Pattern | str | None = None¶

Regex that must fully match stdout, line by line.

stderr_regex_fullmatch: Pattern | str | None = None¶

Regex that must fully match stderr, line by line.

execution_trace: str | None = None¶

Rendering of the command execution and its output.

Populated after the case runs, for inspection on failure. Not a directive: a suite cannot set it, and two cases compare the same whether they ran or not.

property has_merged_output_directives: bool¶

Whether any output_* directive (merged stream) is set.

property has_separate_stream_directives: bool¶

Whether any stdout_* or stderr_* directive (separate streams) is set.

run_cli_test(command, additional_skip_platforms, default_timeout, work_directory=None)[source]¶

Run a CLI command and check its output against the test case.

The provided command can be either:

  • a path to a binary or script to execute;

  • a command name to be searched in the PATH,

  • a command line with arguments to be parsed and executed by the shell.

The case’s env and unset_env directives are layered over the inherited environment for this child process only.

work_directory is the directory the command runs in, defaulting to the one the runner itself is in. command is resolved to an absolute path before it takes effect, so moving the target elsewhere never changes which binary is executed, only what a relative path inside the command resolves against.

Return type:

None

class click_extra.Choice[_ValueT_co](choices, case_sensitive=True)[source]¶

Bases: ParamType[_ValueT_co], Generic[_ValueT_co]

The choice type allows a value to be checked against a fixed set of supported values.

You may pass any iterable value which will be converted to a tuple and thus will only be iterated once.

The resulting value will always be one of the originally passed choices. See normalize_choice() for more info on the mapping of strings to choices. See Choice for an example.

Parameters:

case_sensitive (bool) – Set to false to make choices case insensitive. Defaults to true.

Changed in version 8.4.0: Now generic in the choice value type. Parameterize with the type of the choice values (Choice[HashType] for an enum, Choice[str] for plain strings) to enable type-checked consumers.

Changed in version 8.2.0: Non-str choices are now supported. It can additionally be any iterable. Before you were not recommended to pass anything but a list or tuple.

Added in version 8.2.0: Choice normalization can be overridden via normalize_choice().

name: str = 'choice'¶

the descriptive name of this type

choices: tuple[_ValueT_co, ...]¶
case_sensitive: bool¶
to_info_dict()[source]¶

Gather information that could be useful for a tool generating user-facing documentation.

Use click.Context.to_info_dict() to traverse the entire CLI structure.

Added in version 8.0.

Return type:

ChoiceInfoDict[_ValueT_co]

normalize_choice(choice, ctx)[source]¶

Normalize a choice value, used to map a passed string to a choice. Each choice must have a unique normalized value.

By default uses Context.token_normalize_func() and if not case sensitive, convert it to a casefolded value.

Added in version 8.2.0.

Return type:

str

get_metavar(param, ctx)[source]¶

Returns the metavar default for this param if it provides one.

Return type:

str | None

get_missing_message(param, ctx)[source]¶

Message shown when no choice is passed.

Changed in version 8.2.0: Added ctx argument.

Return type:

str

convert(value, param, ctx)[source]¶

For a given value from the parser, normalize it and find its matching normalized value in the list of choices. Then return the matched ā€œoriginalā€ choice.

Return type:

_ValueT_co

get_invalid_choice_message(value, ctx)[source]¶

Get the error message when the given choice is invalid.

Parameters:

value (Any) – The invalid value.

Return type:

str

Added in version 8.2.

shell_complete(ctx, param, incomplete)[source]¶

Complete choices that start with the incomplete value.

Parameters:
  • ctx (Context) – Invocation context for this command.

  • param (Parameter) – The parameter that is requesting completion.

  • incomplete (str) – Value being completed. May be empty.

Return type:

list[CompletionItem]

Added in version 8.0.

class click_extra.ChoiceSource(*values)[source]¶

Bases: Enum

Source of choices for EnumChoice.

KEY = 'key'¶
NAME = 'name'¶
VALUE = 'value'¶
STR = 'str'¶
class click_extra.CliRunner(charset='utf-8', env=None, echo_stdin=False, catch_exceptions=True, capture='sys')[source]¶

Bases: CliRunner

Augment click.testing.CliRunner with extra features and bug fixes.

force_color: bool = False¶

Default of the force_color argument of invoke(), for every run.

A call passing color=False still gets uncolored output.

invoke(cli, *args, input=None, env=None, catch_exceptions=None, color=None, force_color=None, **extra)[source]¶

Same as click.testing.CliRunner.invoke() with extra features.

  • The first positional parameter is the CLI to invoke. The remaining positional parameters of the function are the CLI arguments. All other parameters are required to be named.

  • The CLI arguments can be nested iterables of arbitrary depth. This is useful for argument composition of test cases with @pytest.mark.parametrize.

  • Adds force_color, which keeps colored output while initializing Context.color = True. click.testing.CliRunner.invoke() cannot express it, its color parameter colliding with the Context one (pallets/click#2110). The force_color class attribute sets it for every run.

  • Strips all ANSI codes from results if color was explicitly set to False.

  • Always prints a simulation of the CLI execution as the user would see it in its terminal. Including colors.

  • Pretty-prints a formatted exception traceback if the command fails.

Parameters:
  • cli (Command) – CLI to invoke.

  • args (str | Path | None | Iterable[str | Path | None | Iterable[Iterable[str | Path | None | Iterable[TNestedArgs]]]]) – can be nested iterables composed of str, pathlib.Path objects and None values. The nested structure will be flattened and None values will be filtered out. Then all elements will be cast to str. See args_cleanup() for details.

  • input (str | bytes | IO | None) – same as click.testing.CliRunner.invoke().

  • env (Mapping[str, str | None] | None) – same as click.testing.CliRunner.invoke().

  • catch_exceptions (bool | None) – same as click.testing.CliRunner.invoke(): None (the default) follows the runner’s own catch_exceptions.

  • color (bool | None) – whether the captured streams keep ANSI codes, passed to click.testing.CliRunner.isolation(). False also scrubs the result bytes.

  • force_color (bool | None) – keep the ANSI codes and initialize the invoked CLI’s Context.color to True, so it takes its colored branch. None (the default) follows the force_color class attribute.

  • extra (Any) – same as click.testing.CliRunner.invoke(), but colliding parameters are allowed and properly passed on to the invoked CLI.

Raises:

ValueError – if force_color=True is passed with color=False.

Return type:

Result

isolated_filesystem(temp_dir=None)[source]¶

Same as isolated_filesystem(), minus Click’s deprecation warning.

Overrides click.testing.CliRunner.isolated_filesystem() so a runner keeps the helper once Click 9.0 removes it.

Return type:

Generator[str, None, None]

exception click_extra.ClickException(message)[source]¶

Bases: Exception

An exception that Click can handle and show to the user.

exit_code: ClassVar[int] = 1¶

The exit code for this exception.

show_color: Final[bool | None]¶
message: Final[str]¶
format_message()[source]¶
Return type:

str

show(file=None)[source]¶
Return type:

None

class click_extra.Color[source]¶

Bases: FrozenSpace

Colors accepted by Style and click.style().

black = 'black'¶
red = 'red'¶
green = 'green'¶
yellow = 'yellow'¶
blue = 'blue'¶
magenta = 'magenta'¶
cyan = 'cyan'¶
white = 'white'¶
reset = 'reset'¶
bright_black = 'bright_black'¶
bright_red = 'bright_red'¶
bright_green = 'bright_green'¶
bright_yellow = 'bright_yellow'¶
bright_blue = 'bright_blue'¶
bright_magenta = 'bright_magenta'¶
bright_cyan = 'bright_cyan'¶
bright_white = 'bright_white'¶
class click_extra.ColorOption(param_decls=None, *, is_flag=False, flag_value='always', default='auto', is_eager=True, expose_value=False, help='Colorize the output. A bare --color is the same as --color=always.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured --color[=WHEN] tri-state option.

Mirrors the GNU coreutils convention: WHEN is one of WHEN (auto, always or never), and a bare --color (no value) means always. The negative alias --no-color is carried by the separate NoColorOption, because Click forbids attaching /--no-x secondary flags to a value option.

The resolved tri-state lands on ctx.color, the Click-standard attribute that echo() reads through its resolve_color_default() → should_strip_ansi() chain: True keeps ANSI codes, False strips them, None (auto) defers to the output stream’s TTY status.

This option is eager by default, so other eager options (like --version) are rendered with the resolved color state.

Note

--color is deliberately not wired to an envvar. The color environment variables (NO_COLOR, FORCE_COLOR, …) are read manually through resolve_color_env(). Letting Click manage them would dump the whole COLOR_ENVVARS set into the --params env-var column, and only bind one variable per option anyway.

add_to_parser(parser, ctx)[source]¶

Register the option, then teach the parser GNU optional-argument rules.

Click’s optional-value parser binds --color to the next token whenever it does not look like an option, so mycli --color subcommand would consume subcommand as the color value and fail. GNU instead binds an optional argument only when it is attached with =.

This wraps the parser’s long-option matcher so a bare --color replays as --color=<flag_value> (always) and leaves the following argument untouched, while --color=<when> keeps working. The wrapper stays inert for every option that does not carry _gnu_optional_value, so it is safe to install on the shared parser.

Return type:

None

set_color(ctx, param, value)[source]¶

Resolve --color=<WHEN> against the environment and pin ctx.color.

Precedence, highest first:

  1. An explicit --color on the command line.

  2. The color environment variables, but only when the value comes from the built-in default, as for every machine-wide variable (see machine_envvars_apply()). A configuration file or --accessible (both seen here as a non-DEFAULT source) therefore wins over the environment, matching AccessibleOption.

  3. A color state already pinned by --no-color, a forced test runner, or an explicit Context(color=...): preserved when this option only resolves to auto from its default.

  4. The auto default, leaving ctx.color at None for TTY detection.

Whatever branch settles it, the resolution is mirrored process-wide by publish_invocation_color() so output produced from background threads honors it too.

Stays dormant under resilient parsing, like every other eager callback: an introspection context (make_resilient_context(), behind the man-page, tree and completion-spec exporters) is never closed, so publishing from one would leave the process-wide mirror pinned to that context’s environment resolution. A NO_COLOR build environment would then strip the output of every later CLI carrying no color option of its own.

Return type:

None

class click_extra.ColumnsOption(param_decls=None, *, columns=None, type=None, metavar='COLUMNS', default=(), expose_value=False, is_eager=True, help='Restrict and reorder table columns, SQL SELECT-style. Comma-separated list of column IDs. Default: all columns in canonical order.', **kwargs)[source]¶

Bases: ExtraOption

A --columns option that lets users restrict and reorder table columns.

Accepts a comma-separated list of column IDs, SQL-SELECT-style:

$ my-cli --columns id,spec,value --params

The selection is stored in ctx.meta[click_extra.context.COLUMNS] and consumed by table-rendering callbacks (like click_extra.show_params.ShowParamsOption) to project rows + headers before rendering.

Pass columns= at construction time with the column registry the option should advertise: the help text then lists the accepted IDs and the default selection, and the callback validates the user input against that registry so unknown IDs fail fast with a click.UsageError. Without columns=, the option stays generic: it parses any IDs and leaves validation to the downstream consumer.

Empty / unset means render every column in canonical order: the default behavior, indistinguishable from not passing --columns at all.

columns: tuple[ColumnSpec, ...]¶

Column registry this option advertises and validates against (may be empty).

init_columns(ctx, param, columns)[source]¶

Store the selected column IDs on the context for later projection.

convert() validates the IDs against the registry before this callback runs, so this only threads the parsed selection onto the context.

Return type:

None

class click_extra.Command(*args, report_url=None, version_fields=None, config_schema=None, config_strict=False, schema_strict=False, fallback_sections=(), config_validators=(), included_params=None, excluded_params=None, config_cascade=False, extra_option_at_end=True, option_priorities=None, populate_auto_envvars=True, extra_keywords=None, excluded_keywords=None, examples=(), **kwargs)[source]¶

Bases: _HelpColorsMixin, _WatchedContextMixin, Command

Like cloup.command, with sane defaults and extra help screen colorization.

Like cloup.Command.__init__, with Click Extra’s defaults and parameters.

Parameters:
  • report_url (str | None) – URL of the issue form of the project, like https://github.com/orchard/harvest/issues/new. Set on the root command, an error that the CLI has no rule for then ends the run with a bug report linking to that form, instead of a bare traceback. See invoke().

  • version_fields (dict[str, Any] | None) – dictionary of VersionOption template field overrides forwarded to the version option. Accepts any field from VersionOption.template_fields (like prog_name, version, git_branch). Lets you customize --version output from the command decorator without replacing the default params list.

  • config_strict (bool) – forwarded to the default ConfigOption’s strict setting: configuration keys not matching any CLI parameter raise an error instead of being silently ignored. Like the other config_* and *_params forwards, it spares you from replacing the whole default params list to customize the config option.

  • config_cascade (bool) – forwarded to the default ConfigOption’s cascade setting: auto-discovery layers every configuration file it finds, the most local one winning on key lookup, instead of stopping at the first.

  • excluded_params (Sequence[str] | None) – additional parameter IDs to block from configuration files, merged into the default ConfigOption’s excluded_params blocklist. Additive, unlike the option-level excluded_params which replaces the default blocklist entirely. Items are fully-qualified parameter IDs (like mycli.mail_sources). Mutually exclusive with included_params.

  • extra_keywords (HelpKeywords | None) – a HelpKeywords instance whose entries are merged into the auto-collected keyword set. Use this to inject additional strings for help screen highlighting.

  • excluded_keywords (HelpKeywords | None) – a HelpKeywords instance whose entries are removed from the auto-collected keyword set. Use this to suppress highlighting of specific strings.

  • examples (Sequence[Sequence[str]]) – a sequence of (description, command) string pairs showing the command in use. They are rendered in an Examples: section of the help screen, in the man page, and in every –help-format rendering. A malformed pair raises TypeError here, at command construction, rather than on the first --help a user runs.

  • extra_option_at_end (bool) – reorders all parameters attached to the command, by moving all instances of ExtraOption at the end of the parameter list. The original order of the options is preserved among themselves.

  • option_priorities (Mapping[str, float] | None) – maps an option to its priority in the help screen, relative to DEFAULT_PRIORITY, lowest shown first. Keys are matched against each parameter’s long and short flags first, then its destination name, so the --config / --no-config pair (which shares the config destination) stays addressable one flag at a time. Presentation only: self.params, and with it the order callbacks are evaluated in, is left alone. Positional arguments are never reordered, their sequence being part of the command’s grammar.

  • populate_auto_envvars (bool) – forces all parameters to have their auto-generated environment variables registered. This addresses the shortcoming of click which only evaluates them dynamically. Once registered, the auto-generated environment variables get displayed in the help screen, fixing click#2483 issue. On Windows, environment variable names are case-insensitive, so they are normalized to uppercase.

By default, these Click context settings are applied:

Additionally, these Cloup context settings are set:

Click Extra also adds its own context_settings:

  • show_choices = None (Click Extra feature)

    If set to True or False, will force that value on all options, so we can globally show or hide choices when prompting a user for input. Only makes sense for options whose prompt property is set.

    Defaults to None, which will leave all options untouched, and let them decide of their own show_choices setting.

  • show_envvar = None (Click Extra feature)

    If set to True or False, will force that value on all options, so we can globally enable or disable the display of environment variables in help screen.

    Defaults to None, which will leave all options untouched, and let them decide of their own show_envvar setting. The rationale being that discoverability of environment variables is enabled by the --params option, which is active by default on extra commands. So there is no need to surcharge the help screen.

    This addresses the click#2313 issue.

To override these defaults, you can pass your own settings with the context_settings parameter:

@command(
    context_settings={
        "show_default": False,
        ...
    }
)
context_class¶

alias of Context

report_url: str | None = None¶

URL of the issue form that a bug report links to, or None to report none.

Set from the report_url constructor argument. Declared here so the attribute exists on every command, as invoke() reads it off the root command.

examples: tuple[tuple[str, str], ...] = ()¶

(description, command) pairs showing the command in use.

Normalized from the examples constructor argument by normalize_examples(). Declared here so the attribute exists on every command, whether or not its author passed any: the renderers reading it (help screen, man page, and every HelpFormat backend) then need no guard.

param_priority(param)[source]¶

Priority of param in the help screen.

Defaults to DEFAULT_PRIORITY, and is otherwise resolved against option_priorities by trying each of the parameter’s flags in turn, then its destination name.

Important

This orders the help screen alone. The order of self.params decides when each callback fires: click.core.iter_params_for_processing sorts on (not is_eager, position on the command line), and every eager option the user did not type ties on that second key, leaving declaration order as the tie-break. That is what puts --time ahead of everything it measures and --accessible ahead of the --color default it lowers, so the two orders have to be free to disagree.

Positional arguments always resolve to the default: their sequence is part of the command’s grammar, not a matter of presentation.

Return type:

float

split_option_groups()[source]¶

Explicit option groups, split around the ungrouped section.

Hands back the groups drawn before the ungrouped options, then those drawn after. Cloup draws the ungrouped section last, with no setting to move it, which would bury a CLI’s own options under the ones Click Extra injects. So the rule is kept for the groups a CLI author declares, and every ExtraOptionGroup goes past the ungrouped section, ordered by its priority.

Important

This is the one place the section order is decided. The help screen (format_params()), the man page and every other HelpFormat backend (_build_option_groups()), and the completion specs (iter_params_for_display()) all read it, so a CLI never lists its options in one order on --help and another on --help-format man.

Return type:

tuple[tuple[OptionGroup, ...], tuple[OptionGroup, ...]]

get_argument_help_record(arg, ctx)[source]¶

Pair a positional argument’s metavar with its help text.

Reimplements cloup.OptionGroupMixin.get_argument_help_record, which reads the help attribute as is. Resolution goes through resolve_param_help() instead, the same helper the man page and every other HelpFormat backend reads, so an operand carries one description whatever renders it. An argument without help gets an empty string, not None.

Return type:

tuple[str, str]

format_params(ctx, formatter)[source]¶

Draw the parameter sections of the help screen.

Reimplements cloup.OptionGroupMixin.format_params to honor the order split_option_groups() computes, and to title the ungrouped section against the groups the CLI author declared alone. Cloup picks that title by counting every visible group, click-extra’s included, so a command carrying the default options would otherwise never show a plain Options heading.

Return type:

None

main(args=None, prog_name=None, **kwargs)[source]¶

Pre-invocation step that is instantiating the context, then call invoke() within it.

Caution

During context instantiation, each option’s callbacks are called. These might break the execution flow (like --help or --version).

Sets the default CLI’s prog_name to the command’s name if not provided, instead of relying on Click’s auto-detection via the _detect_program_name() method. This is to avoid the CLI being called python -m <module_name>, which is not very user-friendly.

An abort still prints Click’s Aborted!, which Click prints on purpose (pallets/click#2584), but prints it as soon as the abort leaves the command: before the close callbacks run, where Click prints it after them.

A Ctrl+C then ends the process the way an unhandled Ctrl+C does in Python: by SIGINT, once the running threads finish. Click exits with status 1 instead, which tells a calling shell the program handled the interrupt itself, so a shell loop runs on.

The process-wide state the options of Click Extra take for a run leaves with it, a run that fails while parsing included: the log handler they attach to the root logger, the levels the verbosity options set, and the color the color options publish. See click_extra.context._scoped_run.

A standard stream that cannot encode Unicode is switched to UTF-8 before anything prints, and stays so: see force_unicode_output().

Return type:

Any

invoke(ctx)[source]¶

Like parent’s invoke, but prints the Aborted! of an abort at once.

Click prints it once the root context has closed, so after every close callback. See _abort_notice.

Under a root command with a report_url, an error that is not one of the exceptions Click exits with ends the run with a bug report: see report_unexpected_error(). The innermost command catches it, as its context still holds the options of the run. Click’s main() also ends a run on an end of input, like an abort, and on a broken pipe, without a message: both pass through. So does any error of a run that executes the code of another project, like the CLI that click-extra wrap runs.

Return type:

Any

make_context(info_name, args, parent=None, **extra)[source]¶

Like parent’s make_context, but seeds ctx.meta with the raw arguments.

A copy of the raw, pre-parsed arguments goes under RAW_ARGS, which print_params() re-parses to draw the --params table. A root context also records the name the CLI was invoked under, as INVOCATION_NAME.

See also

See click_extra.context.RAW_ARGS for the full rationale and the upstream-proposal notes (related: click#1279).

Return type:

Any

format_examples(ctx, formatter)[source]¶

Write an Examples: section listing the command’s examples.

Each entry renders its description, then the command line it describes, indented behind a $ prompt. A command declaring none writes nothing at all, so a help screen only grows the section when it has something to put in it.

The command lines go out verbatim rather than through formatter.write_text(): an example exists to be copied, and Click’s text wrapper would fold a long one onto a second line mid-token. This is the same call the \b no-rewrap marker makes for help prose.

Nothing here styles anything. The lines land in the formatter’s buffer, which getvalue() runs through keyword highlighting on its way out, so the option names, subcommands and CLI names inside an example are painted by the same pass that paints them everywhere else.

Return type:

None

format_epilog(ctx, formatter)[source]¶

Insert the examples section ahead of the epilog.

Places it after the options and subcommands, which is where a reader arrives once they know what the command accepts, and keeps the author’s own epilog as the last word on the screen.

Return type:

None

parse_args(ctx, args)[source]¶

Like parent’s parse_args but with better error messages for single-dash multi-character tokens.

Also settles the presentation options before delegating, so --color, --no-color, --accessible and --theme reach the eager help and version screens regardless of their position on the command line. See _resolve_presentation_eagerly.

Return type:

list[str]

class click_extra.CommandCollection(name=None, sources=None, **kwargs)[source]¶

Bases: Group

A Group that looks up subcommands on other groups. If a command is not found on this group, each registered source is checked in order. Parameters on a source are not added to this group, and a source’s callback is not invoked when invoking its commands. In other words, this ā€œflattensā€ commands in many groups into this one group.

Parameters:
  • name (str | None) – The name of the group command.

  • sources (list[Group] | None) – A list of Group objects to look up commands from.

  • kwargs (Any) – Other arguments passed to Group.

Changed in version 8.2: This is a subclass of Group. Commands are looked up first on this group, then each of its sources.

sources: list[Group]¶

The list of registered groups.

add_source(group)[source]¶

Add a group as a source of commands.

Return type:

None

get_command(ctx, cmd_name)[source]¶

Given a context and a command name, this returns a Command object if it exists or returns None.

Return type:

Command | None

list_commands(ctx)[source]¶

Returns a list of subcommand names in the order they should appear.

Return type:

list[str]

class click_extra.CommandDoc(name, short_help='', section='1', synopsis_pieces=(), description='', operands=(), option_groups=(), subcommands=(), environment=(), files=(), exit_status=(('0', 'Success.'), ('1', 'A runtime error, an aborted prompt (Ctrl-D), or a declined confirmation.'), ('2', 'A usage error: unknown option, invalid value, missing operand, or an unparsable configuration file.'), ('130', 'Interrupted with Ctrl-C: the process ends by SIGINT, reported as 130.')), examples=(), version=None, date='', manual=None, authors=None, copyright=None)[source]¶

Bases: object

A whole man page in structured form, ready to render to roff.

One CommandDoc maps to one command (or subcommand). Its fields are the man-pages(7) sections, in the order Man-page documents them. Build it with extract_command_doc() and serialize with to_roff().

name: str¶

Full command path, space-joined (like weather forecast).

short_help: str = ''¶

One-line description for the NAME section.

section: str = '1'¶

Man section number.

synopsis_pieces: tuple[str, ...] = ()¶

Usage metavars after the command name ([OPTIONS], CITY, …).

description: str = ''¶

The command’s full help text / docstring for the DESCRIPTION section.

operands: tuple[tuple[str, str], ...] = ()¶

Positional arguments as (metavar, help) pairs.

option_groups: tuple[DocOptionGroup, ...] = ()¶

The OPTIONS entries, partitioned into one or more groups. A command without explicit option groups carries a single untitled group.

subcommands: tuple[DocSubcommand, ...] = ()¶

For groups: the COMMANDS section entries, in listing order.

environment: tuple[tuple[str, str], ...] = ()¶

ENVIRONMENT entries as (variable_name, help) pairs.

files: tuple[str, ...] = ()¶

FILES entries (configuration search patterns).

exit_status: tuple[tuple[str, str], ...] = (('0', 'Success.'), ('1', 'A runtime error, an aborted prompt (Ctrl-D), or a declined confirmation.'), ('2', 'A usage error: unknown option, invalid value, missing operand, or an unparsable configuration file.'), ('130', 'Interrupted with Ctrl-C: the process ends by SIGINT, reported as 130.'))¶

EXIT STATUS entries as (code, meaning) pairs.

examples: tuple[tuple[str, str], ...] = ()¶

EXAMPLES entries as (description, command_line) pairs.

Collected from the command’s own examples attribute (see click_extra.commands.Command.examples). Empty for a command that declares none, in which case every backend omits the section entirely.

version: str | None = None¶

Version string for the .TH header.

date: str = ''¶

Date for the .TH header (YYYY-MM-DD).

manual: str | None = None¶

Manual name for the .TH header (the centered footer title).

authors: str | None = None¶

AUTHORS section content, or None to omit the section.

copyright: str | None = None¶

COPYRIGHT section content, or None to omit the section.

property title: str¶

The .TH page title: the command path, hyphen-joined and upper-cased.

to_roff()[source]¶

Render the full man page as a roff/troff string.

Return type:

str

to_markdown()[source]¶

Render the whole document as Markdown.

Same sections as to_roff(), in the same order, minus the roff .TH header, whose date, section number and manual name describe a man page rather than the command. The version survives, as a line under the title.

Return type:

str

to_dict()[source]¶

Render the whole document as a JSON-serializable mapping.

Subcommands are listed by name and one-line description only, never recursively: a consumer walking a deep tree asks for the child it cares about instead of paying for the whole tree at once. render_help() exposes the recursive variant separately, for the consumers that do want everything.

Return type:

dict[str, Any]

to_json(indent=2)[source]¶

Serialize to_dict() to a JSON string.

Return type:

str

class click_extra.ConfigOption(param_decls=None, *, metavar='LOCATION', type=UNPROCESSED, help='Location of the configuration file. Supports local path with glob patterns or remote URL.', is_eager=True, expose_value=False, file_format_patterns=None, file_pattern_flags=None, show_file_patterns=None, roaming=True, force_posix=False, search_pattern_flags=None, search_parents=False, stop_at=Sentinel.VCS, cascade=False, excluded_params=None, included_params=None, strict=False, config_schema=None, schema_strict=False, fallback_sections=(), config_validators=(), **kwargs)[source]¶

Bases: ConfigDiscovery, ExtraOption, ParamStructure

A pre-configured option adding --config LOCATION.

Caution

The first ConfigOption a process builds replaces click.Group.parse_args for all of it. The replacement is how the subcommands the configuration names still run in the two cases the option never sees, on a group class click-extra does not own. One is a bare invocation, for which Click prints its no_args_is_help screen before it runs any parameter. The other is a subgroup, which holds no option of its own. Every other call goes to Click unchanged, as does each group of a CLI carrying no ConfigOption.

Takes as input a path to a file or folder, a glob pattern, or an URL.

  • is_eager is active by default so the callback gets the opportunity to set the default_map of the CLI before any other parameter is processed.

  • default is set to the value returned by self.default_pattern(), which is a pattern combining the default configuration folder for the CLI (as returned by click.get_app_dir()) and all supported file formats.

    Attention

    Default search pattern must follow the syntax of wcmatch.glob.

  • excluded_params are parameters which, if present in the configuration file, will be ignored and not applied to the CLI. Items are expected to be the fully-qualified ID of the parameter, as produced in the output of --params. Will default to the value of DEFAULT_EXCLUDED_PARAMS, plus the CLI’s --help option, resolved at runtime.

  • included_params is the inverse of excluded_params: only the listed parameters will be loaded from the configuration file. Cannot be used together with excluded_params.

file_format_patterns: dict[ConfigFormat, tuple[str, ...]]¶

Mapping of ConfigFormat to their associated file patterns.

Can be a string or a sequence of strings. This defines which configuration file formats are supported, and which file patterns are used to search for them.

Note

All formats depending on third-party dependencies that are not installed will be ignored.

Attention

File patterns must follow the syntax of wcmatch.fnmatch.

auto_file_formats¶

Whether the format set was inherited instead of chosen by the developer.

True when no file_format_patterns was provided, so the set is whatever the installed extra dependencies enable. It ranges from 3 patterns on a bare install to 14 with every extra, which is an artifact of the environment rather than a decision the CLI made.

Only collapse_default() reads it, and only when show_file_patterns is left at None.

show_file_patterns¶

Whether the help screen prints the file patterns of the default.

Follows the tri-state convention of Click Extra’s other display settings:

  • None prints them when the developer chose the format set, and hides them when it was inherited from the install.

  • True always prints them, which is how a CLI advertises the formats its own dependencies enable.

  • False always hides them.

See collapse_default() for what each state renders.

force_posix¶

Configuration for default folder search.

roaming and force_posix are fed to click.get_app_dir() to determine the location of the default configuration folder.

search_parents¶

Indicates whether to walk back the tree of parent folders when searching for configuration files.

stop_at¶

Boundary for parent directory walking.

  • None: walk up to filesystem root.

  • VCS: stop at the nearest VCS root, whichever system marks it (see VCS_DIRS) (default).

  • A Path or str: stop at that directory.

cascade¶

Merge every discovered configuration file instead of stopping at the first parseable one.

When True, all files found by auto-discovery (the app-dir search, including the parent walk when search_parents=True, plus the pyproject.toml CWD search when enabled) are loaded and layered into the context’s default_map. The most local file wins each key, in the sections of subcommands too: a pyproject.toml found near the CWD overrides the app-dir config, which overrides files found higher up the parent walk. A list comes whole from the most local file setting it.

An explicit --config value never cascades: it pins a single source, whatever the pattern matches.

Defaults to False: the first successfully parsed file wins.

extra_excluded_params: frozenset[str]¶

Additional exclusions merged into the dynamic excluded_params default.

Populated by Command’s excluded_params forwarding, which is additive: the default blocklist (--config, --version, --help, …) is preserved and the forwarded IDs are unioned into it when the property resolves. Ignored when an explicit excluded_params was frozen on the instance, as the property is then never consulted.

strict¶

Defines the strictness of the configuration loading.

  • If True, raise an error if the configuration file contain parameters not recognized by the CLI.

  • If False, silently ignore unrecognized parameters.

config_schema¶

Optional schema for structured access to configuration values.

When set, the app’s configuration section is extracted from the parsed config file, normalized (hyphens replaced with underscores), flattened (nested dicts joined with _), and passed to this callable to produce a typed configuration object.

Supports:

  • Dataclass types: detected via __dataclass_fields__. Keys are normalized, nested dicts are flattened, and the result is filtered to known fields before instantiation. This allows nested config sections (like [tool.myapp.sub-section]) to map directly to flat dataclass fields (like sub_section_key).

  • Any callable dict → T: called directly with the raw dict. Works with Pydantic’s Model.model_validate, attrs, or custom factory functions. The caller is responsible for key normalization and flattening.

The resulting object is stored in ctx.meta[click_extra.context.TOOL_CONFIG] and can be retrieved via get_tool_config.

schema_strict¶

Strictness for schema validation (separate from strict).

  • If True, raise ValueError when the config section contains keys that do not match any dataclass field (after normalization and flattening). Only applies when config_schema is a dataclass.

  • If False, ignore unrecognized keys. When the section is schema-only (included_params=()), a warning still names them: see warn_unknown in make_schema_callable().

Note

This is distinct from strict, which controls whether config keys not matching CLI parameters are rejected. schema_strict validates against dataclass fields instead.

fallback_sections: Sequence[str]¶

Legacy section names to try when the app’s own section is empty.

Useful when a CLI tool has been renamed: old configuration files that still use [tool.old-name] (TOML), old-name: (YAML), or {"old-name": …} (JSON) are recognized with a deprecation warning. Works with all configuration formats.

schema_warn_unknown: bool¶

Warn on config keys unknown to the schema, in lax mode.

Inferred, not user-supplied: an explicitly empty included_params means no CLI parameter is merged from the app’s config section, so the section is schema-only and any key the schema does not know is a typo worth a warning. Forwarded to make_schema_callable() and the validation pipeline as warn_unknown.

config_validators: tuple[ConfigValidator, ...]¶

Extension validators for sub-trees of the configuration file.

Each ConfigValidator targets a dotted extension_path relative to the app section. Validators run after click-extra’s built-in CLI-parameter strict check (during --validate-config) and after the schema callable produces the typed configuration object (during normal config loading).

The list is seeded with click-extra’s built-in validators (the one for [tool.<cli>.themes.<name>] tables, see click_extra.theme.validate_themes_config()); user-supplied validators are appended after them. App code that registers its own validator on the same extension_path runs alongside the built-in: both validators are called, both sets of errors surface.

apply_command_settings(*, config_schema=None, config_strict=False, schema_strict=False, fallback_sections=(), config_validators=(), included_params=None, excluded_params=None, cascade=False)[source]¶

Take over the configuration settings a command was built with.

Command accepts the settings of its default --config option as keyword arguments of its own, so a CLI tunes that option without replacing the whole default parameter list, and hands them over here once its parameters are known. Each argument defaults to the value meaning ā€œleave the option as it isā€.

excluded_params is additive, where the option’s own argument replaces the default blocklist: the forwarded IDs join it, through extra_excluded_params while the blocklist is still the dynamic default, and straight into the frozen value otherwise. The config_validators join click-extra’s built-in ones the same way, as they do when passed to the option itself.

Raises:

ValueError – when excluded_params is forwarded to an option carrying its own included_params, the two filters being mutually exclusive.

Return type:

None

property file_pattern_flags: int[source]¶

Flags provided to all calls of wcmatch.fnmatch.

Applies to the matching of file names against supported format patterns specified in file_format_patterns. None at construction picks NEGATE | SPLIT.

Important

The SPLIT flag is always forced, as our multi-pattern design relies on it.

Resolved on first use rather than in __init__, so building the option imports nothing from wcmatch.

property search_pattern_flags: int[source]¶

Flags provided to all calls of wcmatch.glob.

Applies to both the default pattern and any user-provided pattern. None at construction picks GLOBSTAR | FOLLOW | DOTGLOB | BRACE | SPLIT | GLOBTILDE | NODIR.

Important

The BRACE flag is always forced, so that multi-format default patterns using {pat1,pat2,...} syntax expand correctly.

The NODIR flag is always forced, to optimize the search for files only.

Resolved on first use rather than in __init__, so building the option imports nothing from wcmatch.

property excluded_params: frozenset[str][source]¶

Generates the default list of fully-qualified IDs to exclude.

Danger

Resolved once, on first read, and only when the user did not provide a list of their own.

The IDs are rooted at the CLI name, which only the running context knows: hence a property, read within that context, rather than a value set by the constructor.

property file_pattern: str[source]¶

Compile all file patterns from the supported formats.

Uses , (comma) notation to combine multiple patterns, suitable for wcmatch brace expansion ({pat1,pat2,...}).

Returns a single pattern string.

default_pattern()[source]¶

Returns the default pattern used to search for the configuration file.

Defaults to the patterns of every format in file_format_patterns, under <app_dir>: <app_dir>/{*.toml,*.json,*.ini,…}. Where <app_dir> is produced by the click.get_app_dir() method. The result depends on OS and is influenced by the roaming and force_posix properties.

Multiple file format patterns are wrapped with {…} brace-expansion syntax so that wcmatch.glob correctly applies the directory prefix to every sub-pattern.

Note

A CLI wanting another folder layout, like the one platformdirs computes, passes its own pattern to default instead. That keeps the layout a choice of the CLI rather than a dependency of this package: see the documentation.

Return type:

str

get_help_extra(ctx)[source]¶

Replaces the default value of the configuration option.

Display a pretty path that is relative to the user’s home directory:

~/folder/my_cli/{*.toml,*.json,*.ini}

Instead of the full absolute path:

/home/user/folder/my_cli/{*.toml,*.json,*.ini}

Caution

This only applies when the GLOBTILDE flag is set in search_pattern_flags.

An inherited format set is then reduced to the folder it searches, as described in collapse_default().

Return type:

OptionHelpExtra

render_default(ctx)[source]¶

The default search pattern, as a portable home-relative path.

Keeps the whole pattern, file patterns included. The help screen collapses an inherited set on top of this with collapse_default(), but a consumer with room for the files (the FILES section of a man page) calls this method instead. A URL is returned as given.

Return type:

str

collapse_default(default)[source]¶

Reduce an inherited default pattern to the folder it searches.

A CLI installed with every extra searches 15 file patterns, so its default renders as a 136-character glob. The help screen has no space for it and no place to break it, so Click splits it mid-word:

[default: ~/.config/hello/{*.
toml,*.yaml,*.yml,*.json,*.json5,*.jwcc,*.jsonc,
*.hjson,*.ini,*.xml,*.plist,*.sqlite,*.sqlite3,*
.conf,pyproject.toml}]

Rendering the folder alone answers the question a reader opens --help for, on one line, and keeps the answer the same on every install:

[default: ~/.config/hello/]

A developer who passed file_format_patterns chose that set, so it is displayed in full: the pattern is short enough to read, and the help screen is where the choice shows up. show_file_patterns overrides that reading in either direction, and True is what a CLI advertising its formats wants: the set is computed from the installed dependencies at each invocation, so the help screen reports what that install can really parse. The complete pattern of any CLI stays available in the output of --params.

The trailing separator marks the value as a folder, since it is a search base and not a location the option accepts back.

Return type:

str

parse_conf(content, formats, location=None)[source]¶

Parse the content with the given formats.

Tries to parse the given raw content string with each of the given formats, in order. Yields the resulting data structure for each successful parse.

location is the path the content was read from. It is only needed by formats that cannot be parsed from a text payload, like SQLITE, which is read straight from its file, and the binary variant of PLIST, which only exists on disk. Such formats are skipped when location is missing or is not a local file.

Attention

Formats whose parsing raises an exception or does not return a dict are considered a failure and are skipped. A format parsing the content to None, as YAML does for a document of comments only, yields an empty dict instead.

This follows the parse, don’t validate principle.

Return type:

Iterable[dict[str, Any] | None]

read_and_parse_all_conf(pattern)[source]¶

Search for every parseable configuration file matching pattern.

Yields (location, parsed_conf) pairs in discovery order, which is the most local first: the original search location, then each parent directory when parent search is enabled. Files already yielded (as matched by their resolved location) are skipped, as are files that parse to an empty configuration.

Raises FileNotFoundError if no file at all matched the pattern.

Return type:

Iterable[tuple[Path | str, dict[str, Any]]]

read_and_parse_conf(pattern)[source]¶

Search for a parseable configuration file.

Returns the location and data structure of the first configuration matching the pattern.

Only return the first match that:

  • exists,

  • is a file, or a character device or a named pipe that pattern names,

  • is not empty,

  • match file format patterns,

  • can be parsed successfully, and

  • produce a non-empty data structure.

Raises FileNotFoundError if no configuration file was found matching the criteria above.

Returns (None, None) if files were found but none could be parsed.

Return type:

tuple[Path | str, dict[str, Any]] | tuple[None, None]

load_ini_config(content)[source]¶

Utility method to parse INI configuration file.

Internal convention is to use a dot (., as set by PARAM_PATH_SEP) in section IDs as a separator between levels. This is a workaround the limitation of INI format which doesn’t allow for sub-sections.

Each value is converted to the type of the parameter its section and key address, like [my-cli.subcommand] for the options of subcommand.

Returns a ready-to-use data structure.

Return type:

dict[str, Any]

load_argfile_config(content)[source]¶

Utility method to parse a plain-text argfile configuration file.

The file holds command-line tokens, one option per line, in the style of mpv’s and yt-dlp’s configuration files:

# Comments start with a hash sign.
--option-name some value
--flag

Tokens are split with shlex.split(), so shell quoting rules apply and a # starts a comment. Each option is matched against the CLI’s root-level parameter declarations, and its value is converted to the parameter’s Python type, like load_ini_config() does. A boolean flag needs no value: its primary declaration sets it to True, its secondary one (--no-*) to False. An option flagged multiple accumulates one list item per occurrence. Unknown options are kept under a normalized key so the strict check can reject them like any other unrecognized configuration key, while positional tokens are skipped; subcommand options cannot be addressed from an argfile.

Returns a ready-to-use data structure, wrapped in the app’s section name like the [my-cli] section of the other formats.

Raises:

ValueError – the content cannot be tokenized, or an option is missing its value.

Return type:

dict[str, Any]

load_sqlite_config(path)[source]¶

Utility method to parse a SQLite configuration database.

The database holds a single SQLITE_CONFIG_TABLE table of key/value rows. Keys are parameter paths, with a dot (., as set by PARAM_PATH_SEP) separating each level, like my-cli.default.int_param. Values are JSON-encoded, which carries every type the other formats do: booleans, numbers, strings, lists and nested objects alike.

Returns a ready-to-use data structure.

Note

sqlite3 is imported here and not at the top of the module, like the optional parsers of parse_content(). A distribution can ship a Python without the SQLite bindings, and an unconditional import would then break every CLI at import time. ConfigFormat.SQLITE.enabled reports whether they are there, and the format is disabled if they are not.

Return type:

dict[str, Any]

load_plist_config(path)[source]¶

Utility method to parse a plist configuration file.

The file is read as raw bytes and handed to the standard library’s plistlib, which transparently decodes both the XML and the binary variants of the format. The XML variant also parses from a text payload through parse_content(), which is how a plist fetched over http:// or https:// is loaded.

Returns a ready-to-use data structure.

Return type:

dict[str, Any]

load_xml_config(content)[source]¶

Utility method to parse an XML configuration document.

parse_xml() collects the elements repeating a tag into a list, so a lone element reads as its text. An element naming a parameter that takes several values reads as a one-item list instead: XML has no other way to spell a list of one. Element names match parameters through canonical_param_name(), so the kebab-case spelling counts too.

Returns a ready-to-use data structure.

Return type:

dict[str, Any]

merge_default_map(ctx, user_conf)[source]¶

Save the user configuration into the context’s default_map.

Merge the user configuration into the pre-computed template structure, which filters out all unrecognized options not supported by the command, then hand the result to _install_default_map().

Opaque sub-trees declared by the schema or by registered ConfigValidator instances are stripped from the conf before dotted-key expansion and the CLI-parameter strict check, so user-controlled keys (like mappings whose keys are data, not flag names) neither split on a dot nor trip strict=True.

Note

load_conf() installs the same merged configuration, as part of the validation it runs: it does not call this method.

Raises:

ValidationError – in strict mode, on an invalid dotted key or a key matching no parameter.

Return type:

None

load_conf(ctx, param, path_pattern)[source]¶

Fetch parameter values from a configuration file and set them as defaults.

User configuration is merged to the context’s default_map, like Click does.

Relying on Click’s default_map keeps the precedence: direct CLI parameters, environment variables or interactive prompts take precedence over any values from the config file.

Hint

Once loading is complete, the resolved file path and its full parsed content are stored in ctx.meta[click_extra.context.CONF_SOURCE] and ctx.meta[click_extra.context.CONF_FULL] respectively. This is the recommended way to identify which configuration file was loaded.

There is no ParameterSource.CONFIG_FILE enum member: ParameterSource is a closed enum in Click, and monkeypatching it would be fragile. Config values end up in default_map, so Click reports them as ParameterSource.DEFAULT_MAP, which is accurate.

Return type:

None

handle_parse_result(ctx, opts, args)[source]¶

Apply the reserved subcommand keys, once the configuration is loaded.

load_conf() runs as this option’s callback, from inside the super() call below, so the parsed document is already in ctx.meta when inject_reserved_subcommands() reads it.

Returning a rewritten args is what makes _default_subcommands and _prepend_subcommands work on any group class: Click threads the residual arguments through each parameter in turn, then hands the final list to Group.parse_args, which splits it into the subcommands to dispatch. The group can be of a class click-extra does not own, so the option carries the feature instead of the group.

Two cases never come here. On a bare invocation, Click raises the no_args_is_help screen before it runs any parameter. A subgroup reached through this option holds no option of its own. The click.Group.parse_args this class installs covers both.

Before loading, it reads the verbosity the command line asks for (see requested_level()), so load_conf() can keep its status lines quiet under -q or a --verbosity above WARNING.

Return type:

tuple[Any, list[str]]

class click_extra.ConstraintMixin(*args, constraints=(), show_constraints=None, **kwargs)[source]¶

Bases: object

Provides support for constraints.

Parameters:
  • constraints (Sequence[BoundConstraintSpec | BoundConstraint]) – sequence of constraints bound to specific groups of parameters. Note that constraints applied to option groups are collected from the option groups themselves, so they don’t need to be included in this argument.

  • show_constraints (bool | None) – whether to include a ā€œConstraintā€ section in the command help. This is also available as a context setting having a lower priority than this attribute.

  • args (Any) – positional arguments forwarded to the next class in the MRO

  • kwargs (Any) – keyword arguments forwarded to the next class in the MRO

optgroup_constraints¶

Constraints applied to OptionGroup instances.

param_constraints: tuple[BoundConstraint, ...]¶

Constraints registered using @constraint (or equivalent method).

all_constraints¶

All constraints applied to parameter/option groups of this command.

parse_args(ctx, args)[source]¶
Return type:

list[str]

get_param_by_name(name)[source]¶
Return type:

Parameter

get_params_by_name(names)[source]¶
Return type:

Sequence[Parameter]

format_constraints(ctx, formatter)[source]¶
Return type:

None

must_show_constraints(ctx)[source]¶
Return type:

bool

class click_extra.Context(*args, meta=None, sort_subcommands=None, **kwargs)[source]¶

Bases: Context

Like cloup.Context, but with the ability to populate the context’s meta property at instantiation.

Also pre-seeds color for root contexts (those without a parent) from the color environment variables, so the eager help and version screens honor FORCE_COLOR, NO_COLOR and their siblings (see resolve_color_env()). With none of them set, color stays at Click’s None default, which auto-detects a TTY. Child contexts inherit the color of their parent, as Click does.

When the POSIXLY_CORRECT environment variable is set, this context forces allow_interspersed_args to False so option parsing stops at the first positional argument, as GNU getopt-based tools do. See POSIXLY_CORRECT_ENVVAR.

Carries the sort_subcommands setting read by click_extra.commands.Group.must_sort_subcommands(), so a whole command tree can settle its subcommand listings in one place.

Todo

Propose addition of meta keyword upstream to Click.

Like parent’s context but with an extra meta keyword-argument.

Also pre-seed color from the color environment variables for a parentless context when the user did not provide it, and force allow_interspersed_args to False when POSIXLY_CORRECT is set in the environment.

Parameters:

sort_subcommands (bool | None) – whether groups list their subcommands alphabetically. Inherited from the parent context when left to None, the way Cloup inherits align_sections, so declaring it once on the root group settles every subgroup below it.

formatter_class¶

alias of HelpFormatter

render_table(table_data, headers=None, table_format=None, sort_key=None, **kwargs)[source]¶

Render a table honoring the invocation’s table options, and return it.

Same contract as click_extra.table.render_table(), with table_format and sort_key defaulting to the values resolved by the --table-format and --sort-by options (read from TABLE_FORMAT and TABLE_SORT_KEY). ctx.meta is shared along the context chain, so this works from any subcommand without reaching for the root context. Without those options in the chain, falls back to the default format and no sort.

Return type:

str

print_table(table_data, headers=None, table_format=None, sort_key=None, **kwargs)[source]¶

Render a table honoring the invocation’s table options, and print it.

The printing counterpart of render_table(): same defaulting of table_format and sort_key from the context’s shared meta, delegating to click_extra.table.print_table() (which also handles ANSI translation and colorization policy).

Return type:

None

class click_extra.DateTime(formats=None)[source]¶

Bases: ParamType[datetime]

The DateTime type converts date strings into datetime objects.

The format strings which are checked are configurable, but default to some common (non-timezone aware) ISO 8601 formats.

When specifying DateTime formats, you should only pass a list or a tuple. Other iterables, like generators, may lead to surprising results.

The format strings are processed using datetime.strptime, and this consequently defines the format strings which are allowed.

Parsing is tried using each format, in order, and the first format which parses successfully is used.

Parameters:

formats (Sequence[str] | None) – A list or tuple of date format strings, in the order in which they should be tried. Defaults to '%Y-%m-%d', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S'.

name: str = 'datetime'¶

the descriptive name of this type

formats: Sequence[str]¶
to_info_dict()[source]¶

Gather information that could be useful for a tool generating user-facing documentation.

Use click.Context.to_info_dict() to traverse the entire CLI structure.

Added in version 8.0.

Return type:

DateTimeInfoDict

get_metavar(param, ctx)[source]¶

Returns the metavar default for this param if it provides one.

Return type:

str

convert(value, param, ctx)[source]¶

Convert the value to the correct type. This is not called if the value is None (the missing value).

This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.

The param and ctx arguments may be None in certain situations, such as when converting prompt input.

If the value cannot be converted, call fail() with a descriptive message.

Parameters:
  • value (Any) – The value to convert.

  • param (Parameter | None) – The parameter that is using this type to convert its value. May be None.

  • ctx (Context | None) – The current context that arrived at this value. May be None.

Return type:

datetime

class click_extra.DebugOption(param_decls=None, *, default_logger='root', is_flag=True, default=False, help='Shorthand for --verbosity DEBUG.', **kwargs)[source]¶

Bases: _VerbosityOption

--debug flag, a shorthand for --verbosity DEBUG.

The one level people reach for by name, so it gets a flag of its own. The quiet end of the scale needs no such thing: -q walks down it, repeatably.

Note

It outranks --verbosity, -v and -q alike rather than joining their arithmetic, because it asks for the loudest level there is and no combination of the other three can ask for more. See _VerbosityOption.resolve_level().

Set up a verbosity-altering option.

Parameters:

default_logger (Logger | str) –

The logger the option sets the level of:

  • A logging.Logger object is used as it is.

  • The name of the root logger, which is the default, selects it.

  • A name found in the global registry selects that logger as it is.

  • Any other name creates the logger with new_logger().

Building the option never touches the root logger, which the whole process shares. Whichever logger is selected, the root one gets Click Extra’s handler for the time of each run of the command: see add_to_parser().

set_level(ctx, param, value)[source]¶

Record that --debug was passed, then reconcile.

The flag is saved in ctx.meta[click_extra.context.DEBUG], so downstream code can tell a level that came from --debug from the same level spelled --verbosity DEBUG.

Return type:

None

class click_extra.Duration[source]¶

Bases: ParamType

Parse a duration or an age into a datetime.timedelta.

Accepts three input shapes:

  • Friendly duration: 7 days, 1 week, 12h, 30m, 45s, or a bare number of days like 7. Case-insensitive.

  • ISO 8601 duration: P7D, PT12H, P1WT6H. Case-insensitive.

  • RFC 3339 absolute timestamp: 2024-05-01T00:00:00Z or with an offset like +02:00. Converted at parse time to its age, now - timestamp.

Some inputs parse to None instead of a timedelta: a zero duration, an empty string, and a timestamp in the future. Cutoff options (cooldowns, timeouts, retention windows, cache TTLs) read None as ā€œno cutoffā€, so a 0 on the command line disables the gate and overrides a value set in a configuration file.

To parse outside a Click parameter (classifying a value read from a file, say), reach for the soft parse_duration() family, which returns None instead of raising on an unrecognized value.

Note

Durations resolve to a fixed number of seconds, assuming a day is 24 hours. The local time zone, DST transitions, and calendar boundaries are ignored. Calendar units (months, years) are rejected for the same reason: 28-31 days and 365-366 days make them unsuitable for a precise cutoff. Use days or weeks instead.

name: str = 'duration'¶

the descriptive name of this type

convert(value, param, ctx)[source]¶

Coerce value to a datetime.timedelta (or None).

Delegates to _parse_duration_strict(), turning its ValueError into a Click parameter error via fail(). A parsed zero duration collapses to None, so 0 disables a cutoff option.

Return type:

timedelta | None

class click_extra.EnumChoice(choices, case_sensitive=False, choice_source=ChoiceSource.STR, show_aliases=False, transform=None)[source]¶

Bases: Choice

Choice type for Enum.

Allows to select which part of the members to use as choice strings, by setting the choice_source parameter to one of:

  • ChoiceSource.KEY or ChoiceSource.NAME to use the key (the name property),

  • ChoiceSource.VALUE to use the value,

  • ChoiceSource.STR to use the str() string representation, or

  • A custom callable that takes an Enum member and returns a string.

Defaults to ChoiceSource.STR, which only requires you to define the __str__() method on your Enum to produce beautiful choice strings.

The transform parameter takes a callable reshaping the string produced by the source. It composes with every source, and is the only way to spell choices in a CLI-friendly case while show_aliases is on: aliases are reachable through ChoiceSource.KEY, ChoiceSource.NAME and ChoiceSource.VALUE alone, which are stuck on raw Python identifiers.

Same as click.Choice, but takes an Enum as choices.

Also defaults to case-insensitive matching.

Raises:
choices: tuple[str, ...]¶

The strings available as choice.

Hint

Contrary to the parent Choice class, we store choices directly as strings, not the Enum members themselves. That way there is no surprises when displaying them to the user.

This trick bypass Enum-specific code path in the Click library. Because, after all, a terminal environment only deals with strings: arguments, parameters, parsing, help messages, environment variables, etc.

get_choice_string(member)[source]¶

Derive the choice string from the given Enum’s member.

The string produced by the choice source is passed through transform.

Return type:

str

normalize_choice(choice, ctx)[source]¶

Expand the parent’s normalize_choice() to accept Enum members as input.

An Enum member is mapped to its choice string first; any other value is passed to the parent untouched.

Return type:

str

convert(value, param, ctx)[source]¶

Convert the input value to the corresponding Enum member.

The parent’s convert() is going to return the choice string, which we then map back to the corresponding Enum member.

Return type:

Enum

class click_extra.ExportConfigOption(param_decls=None, *, type=None, metavar='FORMAT', is_eager=True, expose_value=False, help='Export the configuration in the selected format to <stdout>, then exit.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured option adding --export-config FORMAT.

Resolves the CLI’s current parameter values following Click’s precedence chain (command line, then environment variables, then configuration file, then defaults), renders them as a configuration file in the requested format on <stdout>, and exits.

Hint

Combine the flag with other options or environment variables to capture them in the generated configuration. For example, mycli --verbosity DEBUG --export-config toml emits a configuration whose verbosity is already set to DEBUG.

Like ValidateConfigOption, it relies on a sibling ConfigOption to provide the parameter structure and the excluded_params / included_params filter, so the export contains exactly the parameters that can be loaded back from a configuration file.

Note

The accepted formats are those serialize_content() can write (SERIALIZABLE_FORMATS). INI, SQLITE, ARGFILE and PYPROJECT_TOML have no serializer and cannot be dumped.

build_config(ctx, config_option)[source]¶

Resolve every config-eligible parameter into a dumpable tree.

Walks the sibling ConfigOption’s parameter structure, resolves each parameter’s effective value by replaying RAW_ARGS (falling back to defaults when the command did not capture them), drops the parameters is_excluded() rejects, and layers the coerced values into the {cli-name: {param: value, ...}} shape a configuration file uses. Parameter keys are rendered in their kebab-case spelling, the canonical presentation for configuration files; either spelling loads back to the same parameter.

Parameters without a default are kept as None leaves so the export names every key a configuration file can set: serializers render them as null, except TOML which comments them out (see _serialize_toml_with_unset). Loading null back is harmless: _install_default_map() cleans blank values out of the merged result.

Return type:

dict[str, Any]

export_config(ctx, param, value)[source]¶

Render the resolved configuration to <stdout> and exit.

Return type:

None

class click_extra.ExtraOption(*args, group=None, **attrs)[source]¶

Bases: Option

Base class of the options Click Extra implements itself.

Identifies Click Extra’s own options with certainty.

Note

The one Click Extra class carrying the Extra prefix: every other one takes the name of the Click or Cloup class it shadows. The plain Option name belongs to the user-facing wrapper this class subclasses, and the prefix marks Click Extra’s own built-in options apart from it. Command reads that mark: it sorts parameters with isinstance(param, ExtraOption) to push the built-in options to the end.

Note

Bracket fields (envvar, default, range, required) cannot be pre-styled in get_help_record() because Click’s text wrapper splits lines after the record is returned, which would break ANSI codes that span wrapped boundaries. Styling is instead applied post-wrapping in HelpFormatter._style_bracket_fields(), which uses the structured data from Option.get_help_extra() to identify each field by its label.

Note

Built-in option subclasses share a common shape: their __init__ defaults param_decls to the option’s canonical flags and wires an eager callback via kwargs.setdefault("callback", self.<callback>). Every callback name encodes its role with a verb prefix. The common roles are:

  • set_<key> publishes a resolved value to ctx.meta (set_color, set_no_color, set_theme, set_telemetry, set_progress, set_accessible, set_zero_exit, the verbosity options’ set_level);

  • init_<system> additionally installs a ctx helper or records a snapshot (init_timer, init_formatter, init_columns, init_sort);

  • validate_<thing> coerces and validates the raw input (validate_jobs, validate_config);

  • print_* renders output and exits (print_man, print_params, print_and_exit).

A few options own a richer operation and name it with its own verb rather than forcing one of the above. ConfigOption wires load_conf to read, parse, and merge a configuration file, and NoConfigOption wires check_sibling_config_option to assert that a sibling --config option exists.

add_to_parser(parser, ctx)[source]¶

Register the option, then give the root logger its handler for the run.

Any of these options may log, and reports through its records: the level changes of the verbosity options, the status lines and the validation errors of ConfigOption, the warnings of JobsOption. A command that carries one of them so prints log records in the style of Click Extra while it runs.

Click calls this method on every parameter of a command before it processes any of them, so the handler is in place for the records the first callbacks emit. It is also a step an option goes through on a command of any class, which is what lets one of these options work on a plain click.command.

Nothing is attached while Click only completes or inspects a command line (ctx.resilient_parsing). See click_extra.logging._hold_invocation_handler for the other rules, and for how the handler leaves.

Return type:

None

class click_extra.ExtraOptionGroup(*args, priority=100.0, **kwargs)[source]¶

Bases: OptionGroup

An option group Click Extra draws after the command’s own options.

Cloup lays a help screen out as the explicit option groups first and the ungrouped options last. Click Extra injects a score of its own options into every command, so grouping them under that rule would push the author’s own options below click-extra’s and retitle them Other options. split_option_groups() sends a group carrying this marker past the ungrouped section instead.

Note

The marker mirrors ExtraOption, which Command reads the same way to push click-extra’s own options to the end of params.

Parameters:

priority (float) – rank of the group among the other trailing groups, lowest first. Defaults to DEFAULT_PRIORITY, so a group a CLI author marks this way lands after click-extra’s own.

Contains the information of an option group and identifies it. Note that, as far as the clients of this library are concerned, an OptionGroups acts as a ā€œmarkerā€ for options, not as a container for related options. When you call @optgroup.option(...) you are not adding an option to a container, you are just adding an option marked with this option group.

Added in version 0.8.0: The hidden parameter.

class click_extra.File(mode='r', encoding=None, errors='strict', lazy=None, atomic=False)[source]¶

Bases: ParamType[IO[Any]]

Declares a parameter to be a file for reading or writing. The file is automatically closed once the context tears down (after the command finished working).

Files can be opened for reading or writing. The special value - indicates stdin or stdout depending on the mode.

By default, the file is opened for reading text data, but it can also be opened in binary mode or for writing. The encoding parameter can be used to force a specific encoding.

The lazy flag controls if the file should be opened immediately or upon first IO. The default is to be non-lazy for standard input and output streams as well as files opened for reading, lazy otherwise. When opening a file lazily for reading, it is still opened temporarily for validation, but will not be held open until first IO. lazy is mainly useful when opening for writing to avoid creating the file until it is needed.

Files can also be opened atomically in which case all writes go into a separate file in the same folder and upon completion the file will be moved over to the original location. This is useful if a file regularly read by other users is modified.

See File Arguments for more information.

Changed in version 2.0: Added the atomic parameter.

name: str = 'filename'¶

the descriptive name of this type

envvar_list_splitter: ClassVar[str] = ':'¶

if a list of this type is expected and the value is pulled from a string environment variable, this is what splits it up. None means any whitespace. For all parameters the general rule is that whitespace splits them up. The exception are paths and files which are split by os.path.pathsep by default (ā€œ:ā€ on Unix and ā€œ;ā€ on Windows).

mode: str¶
encoding: str | None¶
errors: str | None¶
lazy: bool | None¶
atomic: bool¶
to_info_dict()[source]¶

Gather information that could be useful for a tool generating user-facing documentation.

Use click.Context.to_info_dict() to traverse the entire CLI structure.

Added in version 8.0.

Return type:

FileInfoDict

resolve_lazy_flag(value)[source]¶
Return type:

bool

convert(value, param, ctx)[source]¶

Convert the value to the correct type. This is not called if the value is None (the missing value).

This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.

The param and ctx arguments may be None in certain situations, such as when converting prompt input.

If the value cannot be converted, call fail() with a descriptive message.

Parameters:
  • value (str | PathLike[str] | IO[Any]) – The value to convert.

  • param (Parameter | None) – The parameter that is using this type to convert its value. May be None.

  • ctx (Context | None) – The current context that arrived at this value. May be None.

Return type:

IO[Any]

shell_complete(ctx, param, incomplete)[source]¶

Return a special completion marker that tells the completion system to use the shell to provide file path completions.

Parameters:
  • ctx (Context) – Invocation context for this command.

  • param (Parameter) – The parameter that is requesting completion.

  • incomplete (str) – Value being completed. May be empty.

Return type:

list[CompletionItem]

Added in version 8.0.

exception click_extra.FileError(filename, hint=None)[source]¶

Bases: ClickException

Raised if a file cannot be opened.

ui_filename: Final[str]¶
filename: Final[str]¶
format_message()[source]¶
Return type:

str

class click_extra.FloatRange(min=None, max=None, min_open=False, max_open=False, clamp=False)[source]¶

Bases: _NumberRangeBase[float, float], FloatParamType

Restrict a click.FLOAT value to a range of accepted values. See Int and Float Ranges.

If min or max are not passed, any value is accepted in that direction. If min_open or max_open are enabled, the corresponding boundary is not included in the range.

If clamp is enabled, a value outside the range is clamped to the boundary instead of failing. This is not supported if either boundary is marked open.

Changed in version 8.0: Added the min_open and max_open parameters.

name: str = 'float range'¶

the descriptive name of this type

class click_extra.Formatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)[source]¶

Bases: Formatter

Click Extra’s default log formatter.

Initialize the formatter with specified format strings.

Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format.

Use a style parameter of ā€˜%’, ā€˜{’ or ā€˜$’ to specify that you want to use one of %-formatting, str.format() ({}) formatting or string.Template formatting in your format string.

Changed in version 3.2: Added the style parameter.

formatMessage(record)[source]¶

Colorize the record’s log level name before calling the standard formatter.

Colors are sourced from a click_extra.theme.HelpTheme, resolved per-invocation via click_extra.theme.get_current_theme().

A record carrying a label attribute (each line run_cli() streams from a subprocess is tagged with its caller-provided label) renders it glued to the level name, styled like an invoked command: debug:mas: Warning: .... The tag stays out of the message text itself, so a foreign formatter is free to render record.label its own way.

A message spanning several lines starts on the line below its prefix. Glued to the prefix, the first line of a block (a command’s captured output, a table) shifts right by the width of that prefix while the lines below stay at the margin, which breaks the block’s columns.

The record’s levelname and message are restored afterwards: a record may be formatted more than once (several handlers, a captured then re-rendered record), and must not accumulate styling, glued labels or line breaks.

Return type:

str

class click_extra.Group(*args, help_command=True, sort_subcommands=None, subcommand_priorities=None, **kwargs)[source]¶

Bases: Command, Group

Like cloup.Group, with sane defaults and extra help screen colorization.

Like Command.__init__, but auto-injects a help subcommand.

Parameters:
  • help_command (bool) – when True (the default), a help subcommand is automatically registered. Set to False to suppress it, or register your own help subcommand to override it.

  • sort_subcommands (bool | None) – how subcommands sharing a priority are broken apart. True lists them alphabetically, False in the order they were registered. None (the default) defers to the sort_subcommands context setting, then to True. See must_sort_subcommands().

  • subcommand_priorities (Mapping[str, float] | None) – maps a subcommand name to its priority relative to DEFAULT_PRIORITY, lowest listed first. Names left out keep the default priority, so numbering a few subcommands moves only those.

command_class¶

alias of Command

group_class¶

alias of type

subcommand_priorities: dict[str, float]¶
must_sort_subcommands(ctx)[source]¶

Resolve whether subcommand listings are alphabetical.

Reads the group’s own sort_subcommands, then the context setting of the same name, then falls back to True. This is the resolution order Cloup uses for align_sections, and it is what lets a single context_settings={"sort_subcommands": False} on the root group reach every subgroup below it instead of being repeated on each.

Return type:

bool

subcommand_priority(name)[source]¶

Priority of the name subcommand.

Defaults to DEFAULT_PRIORITY.

Return type:

float

listed_command(ctx, name)[source]¶

The command the help screen describes under name: the subcommand.

The extension point LazyGroup overrides to describe a lazy subcommand by the help it declares, without importing it. The keyword highlighting of the help screen reads the subcommands through here.

Return type:

Command | None

list_commands(ctx)[source]¶

Subcommand names in presentation order.

Sorted on subcommand_priorities first, then broken apart by must_sort_subcommands(): alphabetically, or by registration order. With no priority declared every subcommand ties, leaving the tie-break as the only ordering, which is Click’s plain alphabetical listing.

In registration order the auto-injected subcommands, like help, are listed last, wherever they happen to have been registered: Group.__init__ appends help before any @cli.command() decorator runs, while a commands=[…] constructor argument lands it after, so its natural position says nothing about the author’s intent. Mirrors what extra_option_at_end does to options.

Return type:

list[str]

list_sections(ctx, include_default_section=True)[source]¶

Like cloup.Group.list_sections, but ordering the default section.

Cloup hard-codes the default section to Section.sorted(…), which is why overriding list_commands() alone leaves the help screen alphabetical: the screen is rendered from sections and never calls it. Rebuild that section from list_commands() instead, and hand it over already ordered.

Note

Sections the author declared themselves are returned untouched. Cloup’s own Section(is_sorted=…) already governs those, and a user holding a Section instance should not have it rewritten underneath them. Priorities and sort_subcommands therefore address the default section and the flat listings (--tree, man pages, completion specs), not the contents of an explicit section.

Return type:

list[Section]

add_command(cmd, name=None, **kwargs)[source]¶

Like cloup.Group.add_command, but a subcommand of the author’s replaces an auto-injected one of the same name, like the help subcommand.

Return type:

None

class click_extra.HelpCommand(name, context_settings=None, callback=None, params=None, help=None, epilog=None, short_help=None, options_metavar='[OPTIONS]', add_help_option=True, no_args_is_help=False, hidden=False, deprecated=False)[source]¶

Bases: _InjectedCommand

Synthetic subcommand that displays help for the parent group or a subcommand.

Auto-injected into every Group. Supports nested resolution: mycli help subgroup subcmd shows the help for subcmd within subgroup.

invoke(ctx)[source]¶

Resolve the command path and display its help.

Return type:

None

class click_extra.HelpFormat(*values)[source]¶

Bases: StrEnum

The formats render_help() renders.

The value is the spelling --help-format takes. Members are ordered alphabetically, which is also the order --help-format advertises them in. Adding a format is a member here, a description in HELP_FORMATS and a branch in render_help(): no new flag, no wider help screen. See Man-page for what each one is good for.

A member prints, compares, hashes and sorts as its value, so a plain string keeps working wherever a format is expected.

CARAPACE = 'carapace'¶
JSON = 'json'¶
JSON_FULL = 'json-full'¶
MAN = 'man'¶
MARKDOWN = 'markdown'¶
MARKDOWN_FULL = 'markdown-full'¶
class click_extra.HelpFormatOption(param_decls=None, *, expose_value=False, is_eager=True, help='Render the command in the given format and exit.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured --help-format option printing the command in one of the HelpFormat formats and exiting.

Eager and value-taking, unlike its --man neighbour. That bare flag typesets the same page and sends it to the pager, where --help-format man prints its roff source. It stays a flag of its own because a runtime manual flag has its own tradition (see ManOption).

Note

One option carrying a format, rather than one flag per format. A CLI’s option list is the most expensive real estate in its help screen, and every reader pays for it whether or not they will ever export anything: a family of --help-json, --help-markdown and --help-carapace flags would widen the label column of every screen, forever, one line per format anyone ever adds. Here a new format costs a HelpFormat member and nothing on screen.

Note

The rendered output is deliberately colorless whatever --color says. Every format here is meant to be piped into something (a file, a parser, a model), and ANSI escapes in a JSON string or a Markdown fence are noise to all of them. --help remains the colorized human view.

print_help_format(ctx, param, value)[source]¶

Render the invoked command in the requested format, then exit.

Return type:

None

class click_extra.HelpFormatter(*args, **kwargs)[source]¶

Bases: HelpFormatter

Extends Cloup’s custom HelpFormatter to highlight options, choices, metavars and default values.

Cloup declined this regex-based highlighting, at janluke/cloup#95 and janluke/cloup#97. The same proposal is open at click-contrib/click-help-colors#17.

Force the theme to a HelpTheme.

The theme defaults to the one active for the current invocation, as click_extra.theme.get_current_theme() resolves it: the per-invocation pick of ThemeOption, or the process-wide default when no context is active. A plain cloup.HelpTheme lends the slots it declares to that active theme, which keeps the slots cloup lacks.

theme: HelpTheme¶
keywords: HelpKeywords¶

Keywords to highlight, collected from the rendered command’s context.

Instance state, initialized per formatter: _HelpColorsMixin.format_help fills it before rendering, and highlight_extra_keywords() mutates it (see the excluded_keywords subtraction), so a shared class-level default would leak keywords across formatters.

excluded_keywords: HelpKeywords | None¶

Keywords subtracted from the cross-reference passes, or None.

highlight_extra_keywords(help_text)[source]¶

Highlight extra keywords in help screens based on the theme.

Uses the highlight() function for all keyword categories. Each category is processed as a batch of regex patterns with a single styling function, which handles overlapping matches and prevents double-styling.

Return type:

str

write_usage(prog, args='', prefix=None)[source]¶

Draw the usage line, naming the command the same way the rest does.

Reimplements cloup.HelpFormatter.write_usage, which paints the whole command path with the invoked_command slot. A subcommand’s path ends on a name the parent screen lists under subcommand, and the same word in two colors across two screens reads as two different things.

Return type:

None

getvalue()[source]¶

Wrap original Click.HelpFormatter.getvalue() to force extra-colorization on rendering.

Return type:

str

class click_extra.HelpKeywords(cli_names=set(), subcommands=set(), command_aliases=set(), arguments=set(), long_options=set(), short_options=set(), choices=set(), choice_metavars=set(), metavars=set(), envvars=set(), defaults=set(), deprecated=set())[source]¶

Bases: object

Structured collection of keywords extracted from a Click context for help screen highlighting.

Each field corresponds to a semantic category with its own styling.

cli_names: set[str]¶
subcommands: set[str]¶
command_aliases: set[str]¶
arguments: set[str]¶
long_options: set[str]¶
short_options: set[str]¶
choices: set[str]¶
choice_metavars: set[str]¶
metavars: set[str]¶
envvars: set[str]¶
defaults: set[str]¶
deprecated: set[str]¶

Markers a CLI paints with the deprecated slot beside Click’s own.

DEPRECATED_RE covers the spellings Click writes, and only those. A project marking a parameter in its own vocabulary ((unmaintained) for a tool whose upstream is gone, where the option itself is not being retired) otherwise gets no color for it, since the word is the whole pattern.

Each entry is matched literally, so a marker is written the way it reads on the screen, punctuation included.

merge(other)[source]¶

Merge another HelpKeywords into this one.

Each set field is updated with the corresponding set from other.

Return type:

None

subtract(other)[source]¶

Remove keywords found in other from this instance.

Each set field is difference-updated with the corresponding set from other. Mirror of merge().

Return type:

None

class click_extra.HelpSection(heading, definitions, help=None, constraint=None)[source]¶

Bases: object

A container for a help section data.

heading: str¶

Help section title.

definitions: Sequence[tuple[str, str | Callable[[int], str]]]¶

Rows with 2 columns each. The 2nd element of each row can also be a function taking an integer (the available width for the 2nd column) and returning a string.

help: str | None = None¶

(Optional) long description of the section.

constraint: str | None = None¶

(Optional) option group constraint description.

class click_extra.HelpTheme(invoked_command=<function identity>, command_help=<function identity>, heading=<function identity>, constraint=<function identity>, section_help=<function identity>, col1=<function identity>, col2=<function identity>, alias=<function identity>, alias_secondary=None, epilog=<function identity>, critical=<function identity>, error=<function identity>, warning=<function identity>, info=<function identity>, debug=<function identity>, option=<function identity>, subcommand=<function identity>, choice=<function identity>, metavar=<function identity>, bracket=<function identity>, envvar=<function identity>, default=<function identity>, range_label=<function identity>, required=<function identity>, argument=<function identity>, deprecated=<function identity>, separator=<function identity>, search=<function identity>, success=<function identity>, cross_ref_highlight=True, subheading=<function identity>)[source]¶

Bases: HelpTheme

Extends cloup.HelpTheme with slots for log levels and the structural elements Click Extra highlights in help screens.

Each slot below documents what it colors. The built-in themes shipped in BUILTIN_THEMES provide the visual styling by setting the relevant slots; user-defined themes can be authored as plain mappings and loaded via from_dict().

critical()¶

Style applied to the CRITICAL level name in log records.

Example: CRITICAL: Database connection lost.

Return type:

T

error()¶

Style applied to the ERROR level name in log records.

Example: ERROR: Configuration file not found.

Return type:

T

warning()¶

Style applied to the WARNING level name in log records.

Example: WARNING: Requested 16 jobs exceeds the 8 logical CPUs: honored, but pays only for I/O-bound work.

Return type:

T

info()¶

Style applied to the INFO level name in log records.

Usually left at identity: INFO is the default verbosity and shouldn’t stand out from regular output.

Return type:

T

debug()¶

Style applied to the DEBUG level name in log records.

Example: DEBUG: Resolved /etc/myapp/config.toml.

Return type:

T

option()¶

Style applied to option names (--config, -v, --color/--no-color) wherever they appear: synopsis column, free-form descriptions, and docstrings (when cross_ref_highlight is enabled).

Return type:

T

subcommand()¶

Style applied to subcommand names: in a group’s command list and wherever they are referenced in prose.

Return type:

T

choice()¶

Style applied to each individual value inside a click.Choice metavar (like json, csv, xml within [json|csv|xml]) and to those values referenced in option descriptions.

Return type:

T

metavar()¶

Style applied to type metavars (INTEGER, TEXT, PATH, FILE, …) that follow an option name in the synopsis column.

Return type:

T

bracket()¶

Style applied to the literal bracket characters and label prefixes of trailing fields: [, ], default:, env var:, and the field separators between them. Also acts as the fallback for the four inner bracket-field slots (envvar, default, required, range_label) whenever any of them is left at identity. A theme that only sets bracket therefore renders the whole bracket field with a single uniform style; richer themes layer specific colors on top by setting the inner slots.

Return type:

T

envvar()¶

Style applied to environment-variable values inside [env var: ...] bracket fields, and to envvar names mentioned in option descriptions. Falls back to bracket when left at identity, so a theme that only styles bracket still gets a consistent rendering inside bracket fields.

Return type:

T

default()¶

Style applied to the default-value content inside [default: ...] bracket fields. Falls back to bracket when left at identity.

Return type:

T

range_label()¶

Style applied to range expressions (0<=x<=9, x>=1024, 0<=x<100) that appear inside bracket fields for IntRange and FloatRange options. Falls back to bracket when left at identity.

Return type:

T

required()¶

Style applied to the required label inside bracket fields on mandatory options. Falls back to bracket when left at identity.

Return type:

T

argument()¶

Style applied to argument metavars (positional parameter names like MY_ARG, SCRIPT, [FILENAMES]...) in the synopsis column and when referenced in prose.

Return type:

T

deprecated()¶

Style applied to (DEPRECATED) / (Deprecated: reason) markers appended to options and commands.

Return type:

T

separator()¶

Style applied to the -- end-of-options separator, wherever a help screen writes it on its own: my-cli wrap -- target-cli --help.

It is punctuation rather than a word, and it reads as one of the target CLI’s own options until something tells the two apart.

Return type:

T

search()¶

Style applied to substring matches in <cli> help --search output, so users can spot where their query matched.

Return type:

T

success()¶

Style applied to success glyphs in pre-rendered UI elements (the āœ“ in OK_GLYPH) and any text passed through this slot by downstream code.

Return type:

T

cross_ref_highlight: bool = True¶

Highlight options, choices, arguments, metavars and CLI names in free-form text (descriptions, docstrings).

When False, only structural elements are styled: bracket fields ([default: ...], [env var: ...], ranges, [required]), deprecated messages, and subcommand names in definition lists.

subheading()¶

Style for sub-section headings inside log output or inline help.

Distinct from heading (which styles the top-level help-screen section titles): subheading is intended for downstream code that wants a second styling level for its own narrative output.

See also

Used by mail-deduplicate to style ā—¼ N mails sharing hash … log lines.

Return type:

T

with_(**kwargs)[source]¶

Derive a new theme from this one, with some slots overridden.

Returns the same instance when every slot keeps its value, where cloup’s version builds a copy whatever it is given. None is a value like any other, not a slot left alone.

Raises:

TypeError – listing every argument that names no slot.

Return type:

Self

classmethod dark()[source]¶

A theme assuming a dark terminal background color.

Carries cloup’s palette, each style widened to Style, and leaves the slots this subclass adds at their default. For a theme coloring those too, reach for BUILTIN_THEMES instead.

Return type:

Self

classmethod light()[source]¶

A theme assuming a light terminal background color.

Carries cloup’s palette, like dark().

Return type:

Self

to_dict()[source]¶

Serialize the theme to a plain dict suitable for TOML/JSON/YAML.

Each Style slot is emitted via Style.to_dict. Slots left at their default (identity or None) are omitted, so the output only carries what the theme actually overrides. Pair with from_dict() to round-trip.

Raises:

TypeError – when a slot holds an opaque IStyle callable that is not a Style (those cannot be serialized).

Return type:

dict[str, Any]

classmethod from_dict(data)[source]¶

Build a theme from the plain dict produced by to_dict().

Each value is interpreted by field type: a mapping becomes a Style via Style.from_dict, while cross_ref_highlight is read as a plain bool. Unknown keys raise TypeError so typos surface immediately.

Return type:

HelpTheme

cascade(base)[source]¶

Layer this theme’s set slots on top of base.

Mirrors Style.cascade at the slot level: this theme’s non-default slots win, base fills the rest. Useful for layering a sparse override (typically parsed from a config file’s [tool.<cli>.themes.<name>] table) on top of a full built-in palette.

Raises:

TypeError – when base is not a HelpTheme.

Return type:

HelpTheme

class click_extra.IntRange(min=None, max=None, min_open=False, max_open=False, clamp=False)[source]¶

Bases: _NumberRangeBase[int, int], IntParamType

Restrict an click.INT value to a range of accepted values. See Int and Float Ranges.

If min or max are not passed, any value is accepted in that direction. If min_open or max_open are enabled, the corresponding boundary is not included in the range.

If clamp is enabled, a value outside the range is clamped to the boundary instead of failing.

Changed in version 8.0: Added the min_open and max_open parameters.

name: str = 'integer range'¶

the descriptive name of this type

class click_extra.JobsOption(param_decls=None, *, default='auto', expose_value=False, show_default=True, type=<click_extra.jobs.JobCount object>, help="Number of parallel jobs. Accepts an integer, auto (the host's logical CPUs, minus one when there are three or more) or max (all logical CPUs). --jobs 0 runs sequentially.", **kwargs)[source]¶

Bases: ExtraOption

A pre-configured --jobs option to control parallel execution.

Accepts an integer or one of two keywords resolved by JobCount: auto (the default: one fewer than the available logical CPU cores, leaving a core free for the main process and system tasks, except on hosts with fewer than three logical CPUs, where reserving one would leave a single worker) and max (every available logical CPU core). A value of 0 disables parallelism and runs sequentially.

The core count is the number of logical CPUs (hardware threads) available to the process, not physical cores: see CPU_COUNT. On a host with a single logical CPU, auto/max resolve to a single job and JobCount logs that execution will be sequential: as a warning when the keyword was requested explicitly, at info level when it came from the option’s own default.

The resolved value is stored as an int in ctx.meta[click_extra.context.JOBS].

Warning

JobsOption only resolves and publishes the job count: it does not drive any concurrency by itself. Pass it to run_jobs() (which reads the resolved ctx.meta[click_extra.context.JOBS] count), or read that value yourself and act on it.

validate_jobs(ctx, param, value)[source]¶

Validate the resolved job count and store it in context metadata.

JobCount has already resolved any auto/max keyword to an integer by the time this runs. A value of 0 disables parallelism: it is rounded up to 1 (sequential execution) with a warning. Negative values are likewise clamped to 1. A count above the available cores is honored: the pool is a ThreadPoolExecutor, and oversubscription is how I/O- and subprocess-bound work overlaps, so the warning only flags the CPU-bound case where extra threads just contend for the GIL. The resolved count is then logged at info level next to the host’s logical CPU count (CPU_COUNT), so a CLI’s parallelism is visible under --verbosity INFO.

Return type:

None

class click_extra.LazyChoice(load, case_sensitive=True)[source]¶

Bases: Choice

A Choice whose values are produced on first use rather than at decoration.

click.Choice freezes its values when the option is declared, which is at import time for a module-level command. Taking a loader instead keeps the module providing the values off the startup path of the CLI: the values are only needed to parse, complete or document the option, never to import it. Every Choice method reads choices, so the help screen, the generated documents and shell completion see the loaded values like any other.

Keep the load callable, which is called on each read of choices.

Parameters:
  • load (Callable[[], Iterable[str]]) – returns the accepted values. Called on each access of choices, so a cheap loader, or a cached one, is expected.

  • case_sensitive (bool) – as for click.Choice.

property choices: tuple[str, ...]¶

The values, read from the loader on each access.

Setter accepts:

Iterable[str]

class click_extra.LazyGroup(*args, lazy_subcommands=None, **kwargs)[source]¶

Bases: Group

A Group that supports lazy loading of subcommands.

Hint

This implementation is based on the snippet from Click’s documentation: Defining the lazy group.

It has been extended to work with Click Extra’s config_option in click_extra#1332 issue.

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.

lazy_subcommands: dict[str, LazySubcommand]¶
get_command(ctx, cmd_name)[source]¶

Get a command by name, loading lazily if necessary.

Return type:

Command | None

listed_command(ctx, name)[source]¶

Like the parent, but describing a lazy subcommand not imported yet by the stand-in its short_help builds.

Return type:

Command | None

class click_extra.LazySubcommand(import_path, section=None, fallback_to_default_section=True, short_help=None)[source]¶

Bases: object

Declaration of a lazily-imported subcommand of a LazyGroup.

Carries the registration settings cloup.Group.add_command() accepts, which a bare import path cannot express. A subcommand needing none of them is declared as a plain string instead.

import_path: str¶

Where to import the command object from, as "<module-name>.<command-name>".

section: Section | None = None¶

Help-screen section the subcommand is filed under, once imported.

A section declared here is registered on the group right away, so the help screen orders its sections as they are declared, not as their subcommands happen to be imported. The same Section instance can be shared with eagerly-registered subcommands.

fallback_to_default_section: bool = True¶

Whether to file the subcommand under the default section when section is None.

Set to False to leave the subcommand out of every section, which hides it from the help screen while keeping it invocable. Cloup calls this an escape hatch for internal code: do not disable it unless you know what you are doing.

short_help: str | None = None¶

The first paragraph of the subcommand’s help, for the help screen to list.

Declared, it lets the group’s help screen list the subcommand without importing it: the listing shortens it the way it shortens the help of an imported subcommand, so the line reads the same before and after the import. Left to None, drawing the help screen imports the subcommand to read its help.

class click_extra.ManOption(param_decls=None, *, is_flag=True, expose_value=False, is_eager=True, help="Read the command's manual page and exit.", **kwargs)[source]¶

Bases: ExtraOption

A pre-configured --man flag that typesets the command’s manual, pages it, and exits.

Eager and value-less, like ShowParamsOption. Part of the default option set injected by default_params(), so every @command and @group exposes it. Use @man_option to add it to a plain Click CLI.

Note

The flag is named --man, not --show-man or --man-page.

In the POSIX, GNU and BSD traditions a program does not emit its own man page through a flag: the page is a separate file read with man <prog>, either hand-written (BSD mdoc) or generated at build time from --help output (GNU help2man). Click Extra already covers that build-time path with write_manpages(), its help2man equivalent.

The one ecosystem that exposes a runtime flag is Perl’s Pod::Usage, whose convention is --help for the brief usage and bare --man for the full manual. --man also lines up with the neighbouring --help and --version informational flags, which use bare nouns with no show- prefix. --show-man and --man-page have no precedent outside Click Extra.

Note

That Perl convention is about reading a manual, so the flag typesets the page and sends it to the pager, the way man itself does. The roff source a build step ships is --help-format man, beside every other artifact this module renders. The two are one question apart: do you want to read the manual, or to ship it?

print_man(ctx, param, value)[source]¶

Typeset the invoked command’s manual, page it, then exit.

Return type:

None

exception click_extra.MissingExtraError(extra, *, subject, package='click-extra')[source]¶

Bases: ClickException, ImportError

A command needs an optional dependency that is not installed.

The one failure every feature gated behind an extra raises once a user asks for it: a table, an export or a completion spec in a format whose writer is missing, a code snippet without Pygments. Click prints the message after Error: and exits with status 1, with no traceback.

It is an ImportError as well, since a failed import is what it reports: code calling such a feature outside a command catches it as one.

The message names the uv pip install command that installs the extra, in the wording every other optional-dependency error of the package uses.

Parameters:
  • extra (str) – the optional dependency group that installs what is missing.

  • subject (str) – what needs the dependency, opening the message.

  • package (str) – the distribution the extra belongs to.

exception click_extra.MissingParameter(message=None, ctx=None, param=None, param_hint=None, param_type=None)[source]¶

Bases: BadParameter

Raised if click required an option or argument but it was not provided when invoking the script.

Added in version 4.0.

Parameters:

param_type (str | None) – a string that indicates the type of the parameter. The default is to inherit the parameter type from the given param. Valid values are 'parameter', 'option' or 'argument'.

param_type: Final[str | None]¶
format_message()[source]¶
Return type:

str

class click_extra.MultiChoice(choices=(), separator=',', case_sensitive=False)[source]¶

Bases: ParamType

Comma-separated multi-pick from a fixed set of values.

The pick-many counterpart to click.Choice. Accepts a single token containing several values joined by a configurable separator (defaults to ,), parses it into a tuple[str, ...] and validates each value against choices when that set is non-empty.

The rendered metavar is [a,b,c] (separator-joined, parallel to Choice’s [a|b|c]): click_extra.highlight._HelpColorsMixin auto-detects the separator and highlights each individual value the same way it does for Choice.

Note

Click ships no single-token equivalent: its idiom is click.Choice with multiple=True, which repeats the flag (--tag a --tag b). pallets/click#2771 asks for a separator-based variant. MultiChoice follows the SQL SELECT a, b, c convention of the tabular use cases Click Extra supports, with click_extra.table_options.ColumnsOption as the headline consumer.

Initialize the type.

Parameters:
  • choices (Sequence[str]) – the accepted values. When non-empty, convert() rejects unknown tokens with fail. When empty, the type behaves as a pure separator-aware parser and leaves validation to the consumer.

  • separator (str) – the token boundary. Use any single character; this also drives the metavar rendering ([a<sep>b<sep>c]).

  • case_sensitive (bool) – when True, a token must match one of choices exactly. By default tokens match case-insensitively, as with EnumChoice and ThemeChoice, and the returned tuple holds the canonical (original-case) values from choices.

name: str = 'multi'¶

the descriptive name of this type

choices: tuple[str, ...]¶
separator: str¶
case_sensitive: bool¶
get_metavar(param, ctx)[source]¶

Render [a<sep>b<sep>c] when choices is set, None otherwise.

None falls back to Click’s default rendering (the uppercased name, like MULTI).

Return type:

str | None

convert(value, param, ctx)[source]¶

Split value on separator and validate each token.

An already-parsed tuple or list keeps its elements verbatim rather than being split again, then goes through the same validation as a raw token: it reaches here from a configuration file as readily as from a default the CLI author declared, and only that check tells a valid selection from a typo. Empty tokens (consecutive separators, trailing separator) are dropped silently.

Return type:

tuple[str, ...]

class click_extra.MulticallGroup(*args, personalities=None, personalities_command=True, **kwargs)[source]¶

Bases: Group

A Group dispatching on its invocation name, BusyBox-style.

When the name the binary was invoked under matches a personality, the group steps aside entirely and runs the matching subcommand as a standalone command: the personality carries the group’s options merged into the subcommand’s, parses them in one flat pass with no positional ordering constraint, and renders its own usage line and help screen. Any other invocation name falls through to regular group behavior.

The invocation name is, in precedence order:

  1. an explicit prog_name passed to main() (what click_extra.testing.CliRunner uses to simulate a symlink),

  2. else the unresolved basename of sys.argv[0].

The basename is used unresolved: resolving through os.path.realpath() would return the symlink’s target and destroy the personality. A trailing WINDOWS_EXE_SUFFIX is stripped for Windows console-script shims. Click’s own _detect_program_name() is deliberately not used: it reads __main__.__package__ and answers python -m … in the module case. See click_extra.cli_wrapper.invoke_target() for the full trap. A name matching no personality is not an error: it falls through, which is also what keeps the feature inert under test runners, where argv[0] is the runner’s own binary.

Like Group.__init__, but with multicall dispatch.

Parameters:
  • personalities (Mapping[str, str | Sequence[str]] | None) – maps an invocation name to the tokens it invokes: a bare subcommand name ("chill") or a token sequence (("chill", "--hours", "1")) whose extra tokens are prepended to the user’s arguments. Left to None, every non-hidden, non-synthetic subcommand is its own personality.

  • personalities_command (bool) – when True (the default), a personalities subcommand is auto-registered on the group, listing every invocation name the binary answers to. Register your own personalities subcommand to override it.

resolve_invocation_name(prog_name=None)[source]¶

The name this binary was invoked under.

An explicit prog_name wins: it is what makes the feature testable without symlinks on disk. Otherwise the unresolved basename of sys.argv[0] is used, with a trailing .exe stripped on Windows.

Return type:

str | None

list_personalities()[source]¶

Every personality name mapped to the tokens it invokes.

The explicit personalities mapping when one was declared, else every subcommand _is_default_personality admits, mapped to itself. The lazy subcommands of a lazy group are imported to be judged, which a listing has to pay for.

Return type:

dict[str, tuple[str, ...]]

match_personality(name)[source]¶

Tokens to invoke when called under name, or None to fall through.

Return type:

tuple[str, ...] | None

main(args=None, prog_name=None, **kwargs)[source]¶

Dispatch on the invocation name before any argument parsing.

A matching personality runs as a standalone command, the group’s own options merged into it, its extra tokens prepended to the arguments. Anything else delegates to the regular group main().

Return type:

Any

build_personality(name, tokens)[source]¶

Synthesize the standalone command the name personality runs as.

The personality is a fresh instance of the subcommand’s own class, re-instantiated over the group’s parameters merged with the subcommand’s, not a copy whose params attribute is patched after the fact. Two reasons make the re-instantiation mandatory:

  • Cloup computes its help layout (arguments, option_groups, ungrouped_options) from params inside __init__, so a patched copy parses every merged option but only renders the subcommand’s own on its help screen.

  • Click Extra’s own Command.__init__ does work that must run over the merged set: extra_option_at_end reordering, option priorities, auto envvar population and help-keyword collection.

Every parameter is deep-copied, because Command.__init__ re-runs populate_auto_envvars over the merged set under the personality’s own auto_envvar_prefix: sharing instances would rewrite the group’s and subcommand’s envvar attributes and leak that back into group mode. This is the same class of leaky state default_params() warns about.

Return type:

Command

class click_extra.NoColorOption(param_decls=None, *, is_flag=True, default=False, is_eager=True, expose_value=False, help='Disable colorization (alias of --color=never).', **kwargs)[source]¶

Bases: ExtraOption

--no-color flag that forces --color=never.

Click rejects /--no-x secondary flags on a value option, so the negative alias of the tri-state ColorOption cannot live on it and is provided here as a standalone boolean flag. When set, it pins ctx.color to False; when absent it is a no-op, leaving the resolution to ColorOption.

Shown on its own line directly below --color (mirroring --no-config below --config), since every other negative in the default option set is visible too. Eager by default, like ColorOption, so the color state is settled before other eager options render.

set_no_color(ctx, param, value)[source]¶

Force ctx.color off when a negative alias is passed; no-op otherwise.

Dormant under resilient parsing, for the same reason as ColorOption.set_color(): a never-closed introspection context must not publish the process-wide color mirror.

Return type:

None

class click_extra.NoConfigOption(param_decls=None, *, help='Ignore all configuration files and only use command line parameters and environment variables.', is_flag=True, flag_value=Sentinel.NO_CONFIG, is_eager=True, expose_value=False, **kwargs)[source]¶

Bases: ExtraOption

A pre-configured option adding --no-config.

This option is supposed to be used alongside the --config option (ConfigOption) to allow users to explicitly disable the use of any configuration file.

This is especially useful to debug side-effects caused by autodetection of configuration files.

flag_value=NO_CONFIG is the Sentinel enum member that signals ā€œskip configuration loadingā€ to ConfigOption. Click picks type=UNPROCESSED for a flag_value of a non-basic type, so the sentinel passes through Option unchanged.

See also

An alternative implementation of this class would be to create a custom click.ParamType instead of a custom Option subclass. Here is for example.

check_sibling_config_option(ctx, param, value)[source]¶

Ensure that this option is used alongside a ConfigOption instance.

Return type:

None

exception click_extra.NoSuchCommand(command_name, message=None, possibilities=None, ctx=None)[source]¶

Bases: UsageError

Raised if Click attempted to handle a command that does not exist.

Added in version 8.4.0.

command_name: Final[str]¶
possibilities: Final[list[str] | None]¶
format_message()[source]¶
Return type:

str

exception click_extra.NoSuchOption(option_name, message=None, possibilities=None, ctx=None)[source]¶

Bases: UsageError

Raised if Click attempted to handle an option that does not exist.

Added in version 4.0.

option_name: Final[str]¶
possibilities: Final[list[str] | None]¶
format_message()[source]¶
Return type:

str

class click_extra.OperationTrail(*, label='', unit='', total=0, jobs=1, spinner=None, progress_bar=False, timer=None, clock='elapsed', visible=True, live='auto', echo_sequential=True, delay=0.0, stream=None)[source]¶

Bases: object

A āœ“/✘ progress trail and finisher for a batch of operations.

Where Spinner narrates one long-running call, OperationTrail reports a batch of them: each completed operation leaves a persistent trail_line() on screen, a running done/total tally keeps the batch’s pulse visible, and finish() closes with a persistent summary line. The natural reporting companion of the concurrency primitives run_jobs() and run_lanes(), rendered one of three ways:

  • sequential (jobs <= 1): echo each outcome as it lands, with no aggregate indicator (each operation is free to keep its own per-call Spinner). finish() appends the elapsed time.

  • concurrent (jobs > 1): drive one aggregate Spinner (per-call spinners would collide on the shared stream), buffering outcomes until it first draws, then streaming the rest live above it. Pick the animation from the SPINNERS catalog with spinner=.

  • progress bar (progress_bar=True): drive one aggregate determinate bar carrying the {done}/{total} tally, with outcomes streaming above it. Serves sequential and concurrent batches alike, and needs a known total.

The aggregate indicators redraw in place, which a pipe or a CI log cannot do, so by default they draw only on an interactive terminal, and live changes where they draw. The āœ“/✘ lines and the finisher only append, so they print on any stream, in plain text where color is off. Where no indicator draws, every rendering echoes each outcome as it lands, as the sequential one does. visible=False silences all of it. The running āœ“ tally is kept as outcomes land (ok_count), so a caller computes no counts of its own.

Thread-safe: mark() may be called from worker threads. Use it as a context manager whenever it may run concurrently, to bound the aggregate spinner’s life; a purely sequential caller may construct it bare.

from click_extra.jobs import run_jobs
from click_extra.trail import OperationTrail

with OperationTrail(label="Fetching", unit="feeds", total=len(feeds),
                    jobs=jobs) as trail:
    def fetch(feed):
        trail.mark(*pull(feed))  # pull() returns (ok, message).

    list(run_jobs(fetch, feeds, jobs=jobs))
    trail.finish(
        trail.ok_count == len(feeds),
        f"Fetched {trail.ok_count}/{len(feeds)} feeds",
    )

Configure (but do not start) the trail.

Parameters:
  • label (str) – present-tense verb for the running aggregate indicator ("Fetching"), composed into its {label} {done}/{total} {unit} tally.

  • unit (str) – the noun counted in the tally ("files", "feeds").

  • total (int) – how many outcomes are expected, for the done/total count.

  • jobs (int) – the batch’s worker count; > 1 selects the concurrent rendering (one aggregate spinner), <= 1 the sequential one (plain echoed lines).

  • spinner (SpinnerPreset | None) – a SpinnerPreset from the SPINNERS catalog (spinner=SPINNERS["moon"]) for the concurrent aggregate spinner. Ignored by the sequential and progress-bar renderings, and mutually exclusive with progress_bar.

  • progress_bar (bool) – render the aggregate indicator as a determinate click.progressbar() instead of a spinner, for a sequential or concurrent batch alike. Requires a positive total (a bar needs a length) and is mutually exclusive with spinner.

  • timer (bool | Callable[[float], str] | None) – append each operation’s and the batch’s elapsed time to the trail lines and the finisher. None (the default) follows the CLI’s --time / --no-time flag; True forces timing on with format_duration()’s compact clock, a callable (seconds: float) -> str forces it on with a custom format, and False forces it off. Per-operation times come from a seconds argument to mark(), filled in automatically by an operation() handle.

  • clock (Literal['elapsed', 'eta']) – whether a running aggregate indicator shows elapsed time ("elapsed", the default: a stopwatch counting up, visible from the start) or remaining time ("eta": an estimate from the batch’s rate, appearing only once an outcome lets it be computed). Both the progress bar and the concurrent spinner honor "eta" (the spinner reuses Click’s progress-bar estimate, since the trail knows its total). Per-operation and finisher times are always elapsed.

  • visible (bool) – whether the trail shows anything. False silences the lines, the finisher and the aggregate indicator, while ok_count keeps counting.

  • live (Literal['auto', 'always', 'never']) – where the aggregate indicator may draw: "auto" (the default) on an interactive terminal only, unless --no-progress turns it off, "always" on any stream, "never" nowhere. Where it does not draw, each outcome line prints as it lands.

  • echo_sequential (bool) – whether the batch echoes its outcome lines and finisher as plain lines at all: in a sequential batch, in a batch whose aggregate indicator cannot draw on the stream, and in one that finishes before its indicator first draws. Turn it off when the batch has another output that is the real product (a result table) and the trail would be noise. An indicator that did draw is unaffected.

  • delay (float) – seconds before the aggregate indicator first draws: a fast batch then completes without ever flashing one, its lines echoed plainly at finish() instead (see echo_sequential).

  • stream (IO[str] | None) – where to render; defaults to sys.stderr so the trail never mixes into stdout data.

Raises:

ValueError – if progress_bar is set without a positive total, or together with spinner, if clock is neither "elapsed" nor "eta", or if live is not one of WHEN.

property ok_count: int¶

How many marked outcomes have succeeded so far.

mark(ok, message, seconds=None)[source]¶

Record one āœ“/✘ outcome: tally it and render its trail line.

Parameters:

seconds (float | None) – the operation’s own elapsed time. When timer is on it is formatted and appended to message as (2.3s). An operation() handle fills this in from when it was created; pass it yourself when you already hold a duration.

Return type:

None

finish(ok, summary)[source]¶

Render the persistent āœ“/✘ {summary} finisher.

With an aggregate indicator that drew, it becomes the indicator’s kept line (a spinner’s ok() / fail() line, or the bar’s replacement line); otherwise, a plain echoed line. The batch’s elapsed time since construction is appended when timer is on.

A batch finishing inside delay never draws its indicator, so none of its buffered lines reached the stream. When the trail is the batch’s output (echo_sequential and visible), they are echoed plainly along with the finisher, the way a sequential batch prints them: how fast a batch ran must not decide whether its record exists.

Return type:

None

operation()[source]¶

Start a timed operation, returning a handle to record its outcome.

The handle captures the current time; call _Operation.mark() when the work finishes to record its āœ“/✘ outcome with the elapsed time appended (when timer is on). This is how a batch reports per-operation timings under concurrency, where the trail itself never sees when an operation began:

def fetch(feed):
    op = trail.operation()
    ok, message = pull(feed)
    op.mark(ok, message)
Return type:

_Operation

class click_extra.Option(*args, group=None, **attrs)[source]¶

Bases: _ParameterMixin, Option

cloup.Option with the overrides of _ParameterMixin.

cloup.Option subclasses click.Option to let an option join a Cloup option group.

Todo

Delete the human_readable_name override and _CLICK_HAS_PARAMETER_SPEC once this package’s Click floor reaches 8.6.0. From that release on, Click names a parameter by Parameter.spec, added by pallets/click#3877: a deprecation notice then names the option by its longest-prefixed flag.

property human_readable_name: str¶

Every spelling of the option, joined the way Click hints at one.

Declared below Click 8.6.0 only: from that release on, Click reads Parameter.spec in its place, and warns about a subclass that overrides this property.

Below it, Click returns self.name here: the Python identifier it derived from the declarations, which is the one spelling that appears nowhere on the command line. Left alone, a deprecated --apt-cyg / --no-apt-cyg announces itself as 'apt_cyg', naming a flag no user can type and none of the two they did. click.Argument already overrides the property for its own reasons, leaving click.Option re-declaring the inherited body verbatim.

" / " is the separator click.Parameter.get_error_hint joins the same spellings with, so a message naming an option reads the same whichever of the two produced it.

class click_extra.OptionGroup(title, help=None, constraint=None, hidden=False)[source]¶

Bases: object

Contains the information of an option group and identifies it. Note that, as far as the clients of this library are concerned, an OptionGroups acts as a ā€œmarkerā€ for options, not as a container for related options. When you call @optgroup.option(...) you are not adding an option to a container, you are just adding an option marked with this option group.

Added in version 0.8.0: The hidden parameter.

property options: Sequence[Option]¶
Setter accepts:

Iterable[Option]

get_help_records(ctx)[source]¶
Return type:

list[tuple[str, str]]

option(*param_decls, **attrs)[source]¶

Refer to cloup.option().

Return type:

Callable[[F], F]

class click_extra.OptionGroupMixin(*args, align_option_groups=None, **kwargs)[source]¶

Bases: object

Implements support for:

  • option groups

  • the ā€œPositional argumentsā€ help section; this section is shown only if at least one of your arguments has non-empty help.

Important

In order to check the constraints defined on the option groups, a command must inherits from cloup.ConstraintMixin too!

Added in version 0.14.0: added the ā€œPositional argumentsā€ help section.

Changed in version 0.8.0: this mixin now relies on cloup.HelpFormatter to align help sections. If a click.HelpFormatter is used with a TypeError is raised.

Changed in version 0.8.0: removed format_option_group. Added get_default_option_group and make_option_group_help_section.

Added in version 0.5.0.

Parameters:
  • align_option_groups (bool | None) – whether to align the columns of all option groups’ help sections. This is also available as a context setting having a lower priority than this attribute. Given that this setting should be consistent across all you commands, you should probably use the context setting only.

  • args (Any) – positional arguments forwarded to the next class in the MRO

  • kwargs (Any) – keyword arguments forwarded to the next class in the MRO

option_groups¶

List of all option groups, except the ā€œdefault option groupā€.

ungrouped_options¶

List of options not explicitly assigned to an user-defined option group. These options will be included in the ā€œdefault option groupā€. Note: this list does not include options added automatically by Click based on context settings, like the --help option; use the get_ungrouped_options() method if you need the real full list (which needs a Context object).

get_ungrouped_options(ctx)[source]¶

Return options not explicitly assigned to an option group (eventually including the --help option), i.e. options that will be part of the ā€œdefault option groupā€.

Return type:

Sequence[Option]

get_argument_help_record(arg, ctx)[source]¶

Like Argument.get_help_record, but it returns a tuple even if help is empty

Return type:

tuple[str, str]

get_arguments_help_section(ctx)[source]¶
Return type:

HelpSection | None

make_option_group_help_section(group, ctx)[source]¶

Return a HelpSection for an OptionGroup, i.e. an object containing the title, the optional description and the options’ definitions for this option group.

Added in version 0.8.0.

Return type:

HelpSection

must_align_option_groups(ctx, default=True)[source]¶

Return True if the help sections of all options groups should have their columns aligned.

Added in version 0.8.0.

Return type:

bool

get_default_option_group(ctx, is_the_only_visible_option_group=False)[source]¶

Return an OptionGroup instance for the options not explicitly assigned to an option group, eventually including the --help option.

Added in version 0.8.0.

Return type:

OptionGroup

format_params(ctx, formatter)[source]¶
Return type:

None

class click_extra.OptionKwargs[source]¶

Bases: _ParamKwargs

Arguments accepted by option().

Refer to click.Option for their meaning and defaults.

callback: NotRequired[Callable[[Context, Option, Any], Any] | None]¶
shell_complete: NotRequired[Callable[[Context, Option, str], list[CompletionItem] | list[str]] | None]¶
is_flag: NotRequired[bool | None]¶
is_eager: NotRequired[bool]¶
show_choices: NotRequired[bool]¶
show_default: NotRequired[bool | str | None]¶
show_envvar: NotRequired[bool]¶
flag_value: NotRequired[Any]¶
count: NotRequired[bool]¶
multiple: NotRequired[bool]¶
prompt: NotRequired[bool | str]¶
confirmation_prompt: NotRequired[bool | str]¶
prompt_required: NotRequired[bool]¶
hide_input: NotRequired[bool]¶
allow_from_autoenv: NotRequired[bool]¶
hidden: NotRequired[bool]¶
help: NotRequired[str | None]¶
deprecated: NotRequired[bool | str]¶
type: NotRequired[ParamType[Any] | Callable[[str], Any] | tuple[ParamType[Any] | Callable[[str], Any], ...] | None]¶
required: NotRequired[bool | None]¶
default: NotRequired[Any | Callable[[], Any] | None]¶
nargs: NotRequired[int | None]¶
metavar: NotRequired[str | None]¶
expose_value: NotRequired[bool]¶
envvar: NotRequired[str | Sequence[str] | None]¶
class click_extra.ParamStructure[source]¶

Bases: object

Utilities to introspect CLI options and commands structure.

Structures are represented by a tree-like dict.

Access to a node is available using a serialized path string composed of the keys to descend to that node, separated by a dot ..

excluded_params: frozenset[str]¶

Fully-qualified IDs of the parameters to block from the structure.

Set by subclasses: ShowParamsOption freezes an empty set, while ConfigOption resolves a dynamic default (or the user-provided list) within the active context. The two filters are mutually exclusive, a constraint each subclass enforces in its own constructor.

With an allowlist, this holds only the IDs that the walk of build_param_trees() reaches and the allowlist leaves out. Ask is_excluded() about a parameter of another subcommand.

included_params: frozenset[str] | None¶

Allowlist of parameter IDs, mutually exclusive with excluded_params.

None disables the allowlist. Otherwise build_param_trees() walks only the subcommands an allowed ID lies under, and resolves the parameters it reaches into excluded_params.

static init_tree_dict(*path, leaf=None)[source]¶

Nest one dict per key of path, the deepest one holding leaf.

An empty path returns leaf itself.

Return type:

Any

static get_tree_value(tree_dict, *path)[source]¶

Get in the tree_dict the value located at the path.

Raises KeyError if no item is found at the provided path.

Return type:

Any

walk_params(*, descend=None)[source]¶

Yield every parameter of the CLI, unfiltered.

Everything is included, from top-level groups to subcommands, and from options to arguments, unless descend skips a subcommand.

Thin adapter over walk_command_params(): it resolves the root CLI from the active context and drops the per-parameter context that the free function also yields.

Parameters:

descend (Callable[[tuple[str, ...]], bool] | None) – passed on to walk_command_params(), to skip the subcommands it declines.

Return type:

Iterator[tuple[tuple[str, ...], Parameter]]

Returns:

(keys, param) pairs: the keys leading to the parameter, then the parameter itself.

TYPE_MAP: ClassVar[dict[type[ParamType], type[str | int | float | bool | list]]] = {<class 'click.types.BoolParamType'>: <class 'bool'>, <class 'click.types.Choice'>: <class 'str'>, <class 'click.types.DateTime'>: <class 'str'>, <class 'click.types.File'>: <class 'str'>, <class 'click.types.FloatParamType'>: <class 'float'>, <class 'click.types.FloatRange'>: <class 'float'>, <class 'click.types.IntParamType'>: <class 'int'>, <class 'click.types.IntRange'>: <class 'int'>, <class 'click.types.Path'>: <class 'str'>, <class 'click.types.StringParamType'>: <class 'str'>, <class 'click.types.Tuple'>: <class 'list'>, <class 'click.types.UUIDParameterType'>: <class 'str'>, <class 'click.types.UnprocessedParamType'>: <class 'str'>}¶

Map Click types to their Python equivalent.

Keys are subclasses of click.types.ParamType. Values are expected to be simple builtins Python types.

This mapping can be seen as a reverse of the click.types.convert_type() method.

static map_click_type(click_type)[source]¶

Map a Click parameter type instance to its Python equivalent.

Returns str for unrecognised custom types, since command-line parameters are strings by default.

See the list of custom types provided by Click.

Return type:

type[str | int | float | bool | list]

static get_param_type(param)[source]¶

Get the Python type of a Click parameter.

Returns str for unrecognised custom types, since command-line parameters are strings by default.

A boolean flag is a bool even when it is repeatable: it collects occurrences of a toggle rather than values, and a configuration file spells it as the boolean it is. That is why the check comes before the multi-value one, which would otherwise read it as a list and have an unset one dump as [], a shape no user writes.

See the list of custom types provided by Click.

Return type:

type[str | int | float | bool | list]

is_excluded(param_id)[source]¶

Whether a configuration file cannot set the parameter param_id.

An allowlist answers alone: the parameter is excluded when included_params does not name it. So the answer holds for a parameter of a subcommand that the walk of build_param_trees() skipped. Without an allowlist, the parameter is excluded when excluded_params lists it.

Parameters:

param_id (str) – the fully-qualified ID of the parameter, its path keys joined with PARAM_PATH_SEP.

Return type:

bool

build_param_trees()[source]¶

Build and return the parameters tree structure.

Each leaf is the list of the parameters its path names: one, or several when options share a name, like the feature switches of one destination.

This removes parameters whose fully-qualified IDs are in the excluded_params blocklist.

With an allowlist, the tree holds only the parameters included_params names. The walk then skips each subcommand that no allowed ID lies under, so it does not import a lazy subcommand of a LazyGroup that the allowlist leaves out. An empty allowlist walks the root command alone. The parameters the walk reaches and the allowlist leaves out become excluded_params.

Return type:

dict[str, Any]

property params_template: dict[str, Any][source]¶

Returns a tree-like dictionary whose keys shadows the CLI options and subcommands and values are None.

Perfect to serve as a template for configuration files.

property params_objects: dict[str, Any][source]¶

Returns a tree-like dictionary whose keys shadows the CLI options and subcommands and values are parameter objects.

Perfect to parse configuration files and user-provided parameters.

class click_extra.ParamType[_ValueT_co, _InputT_contra = Any][source]¶

Bases: Generic[_ValueT_co, _InputT_contra], ABC

Represents the type of a parameter. Validates and converts values from the command line or Python into the correct type.

To implement a custom type, subclass and implement at least the following:

  • The name class attribute must be set.

  • Calling an instance of the type with None must return None. This is already implemented by default.

  • convert() must convert string values to the correct type.

  • convert() must accept values that are already the correct type.

  • It must be able to convert a value if the ctx and param arguments are None. This can occur when converting prompt input.

Changed in version 8.4.0: Now a generic abstract base class. Parameterize with the converted value type (ParamType[int] for an integer-returning type) so that convert() and downstream consumers carry the narrowed return type.

Changed in version 8.5.0: Accepts a second optional type parameter for the input value type that convert() accepts (ParamType[int, str] for a type converting strings to integers), defaulting to Any.

is_composite: ClassVar[bool] = False¶
arity: int = 1¶
name: str¶

the descriptive name of this type

envvar_list_splitter: ClassVar[str | None] = None¶

if a list of this type is expected and the value is pulled from a string environment variable, this is what splits it up. None means any whitespace. For all parameters the general rule is that whitespace splits them up. The exception are paths and files which are split by os.path.pathsep by default (ā€œ:ā€ on Unix and ā€œ;ā€ on Windows).

to_info_dict()[source]¶

Gather information that could be useful for a tool generating user-facing documentation.

Use click.Context.to_info_dict() to traverse the entire CLI structure.

Added in version 8.0.

Return type:

ParamTypeInfoDict

get_metavar(param, ctx)[source]¶

Returns the metavar default for this param if it provides one.

Return type:

str | None

get_missing_message(param, ctx)[source]¶

Optionally might return extra information about a missing parameter.

Added in version 2.0.

Return type:

str | None

convert(value, param, ctx)[source]¶

Convert the value to the correct type. This is not called if the value is None (the missing value).

This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.

The param and ctx arguments may be None in certain situations, such as when converting prompt input.

If the value cannot be converted, call fail() with a descriptive message.

Parameters:
  • value (_InputT_contra) – The value to convert.

  • param (Parameter | None) – The parameter that is using this type to convert its value. May be None.

  • ctx (Context | None) – The current context that arrived at this value. May be None.

Return type:

_ValueT_co

split_envvar_value(rv)[source]¶

Given a value from an environment variable this splits it up into small chunks depending on the defined envvar list splitter.

If the splitter is set to None, which means that whitespace splits, then leading and trailing whitespace is ignored. Otherwise, leading and trailing splitters usually lead to empty items being included.

Return type:

Sequence[str]

fail(message, param=None, ctx=None)[source]¶

Helper method to fail with an invalid value message.

Return type:

NoReturn

shell_complete(ctx, param, incomplete)[source]¶

Return a list of CompletionItem objects for the incomplete value. Most types do not provide completions, but some do, and this allows custom types to provide custom completions as well.

Parameters:
  • ctx (Context) – Invocation context for this command.

  • param (Parameter) – The parameter that is requesting completion.

  • incomplete (str) – Value being completed. May be empty.

Return type:

list[CompletionItem]

Added in version 8.0.

class click_extra.Parameter(param_decls=None, type=None, required=False, default=Sentinel.UNSET, callback=None, nargs=None, multiple=False, metavar=None, expose_value=True, is_eager=False, envvar=None, shell_complete=None, deprecated=False, help=None)[source]¶

Bases: ABC

A parameter to a command comes in two versions: they are either Options or Arguments. Other subclasses are currently not supported by design as some of the internals for parsing are intentionally not finalized.

Some settings are supported by both options and arguments.

Parameters:
  • param_decls (Sequence[str] | None) – the parameter declarations for this option or argument. This is a list of flags or argument names.

  • type (ParamType[Any] | Any | None) – the type that should be used. Either a ParamType or a Python type. The latter is converted into the former automatically if supported.

  • required (bool) – controls if this is optional or not.

  • default (Any | Callable[[], Any] | None) – the default value if omitted. This can also be a callable, in which case it’s invoked when the default is needed without any arguments.

  • callback (Callable[[Context, Parameter, Any], Any] | None) – A function to further process or validate the value after type conversion. It is called as f(ctx, param, value) and must return the value. It is called for all sources, including prompts.

  • nargs (int | None) – the number of arguments to match. If not 1 the return value is a tuple instead of single value. The default for nargs is 1 (except if the type is a tuple, then it’s the arity of the tuple). If nargs=-1, all remaining parameters are collected.

  • metavar (str | None) – how the value is represented in the help page.

  • expose_value (bool) – if this is True then the value is passed onwards to the command callback and stored on the context, otherwise it’s skipped.

  • is_eager (bool) – eager values are processed before non eager ones. This should not be set for arguments or it will inverse the order of processing.

  • envvar (str | Sequence[str] | None) – environment variable(s) that are used to provide a default value for this parameter. This can be a string or a sequence of strings. If a sequence is given, only the first non-empty environment variable is used for the parameter.

  • shell_complete (Callable[[Context, Parameter, str], list[CompletionItem] | list[str]] | None) – A function that returns custom shell completions. Used instead of the param’s type completion if given. Takes ctx, param, incomplete and must return a list of CompletionItem or a list of strings.

  • deprecated (bool | str) – If True or non-empty string, issues a message indicating that the argument is deprecated and highlights its deprecation in –help. The message can be customized by using a string as the value. A deprecated parameter cannot be required, a ValueError will be raised otherwise.

  • help (str | None) – the help string. It is dedented and get a deprecated label if appropriate.

Changed in version 8.5.1: New help parameter to replace the one from Option and Argument.

Changed in version 8.2.0: Introduction of deprecated.

Changed in version 8.2: Adding duplicate parameter names to a Command will result in a UserWarning being shown.

Changed in version 8.2: Adding duplicate parameter names to a Command will result in a UserWarning being shown.

Changed in version 8.0: process_value validates required parameters and bounded nargs, and invokes the parameter callback before returning the value. This allows the callback to validate prompts. full_process_value is removed.

Changed in version 8.0: autocompletion is renamed to shell_complete and has new semantics described above. The old name is deprecated and will be removed in 8.1, until then it will be wrapped to match the new requirements.

Changed in version 8.0: For multiple=True, nargs>1, the default must be a list of tuples.

Changed in version 8.0: Setting a default is no longer required for nargs>1, it will default to None. multiple=True or nargs=-1 will default to ().

Changed in version 7.1: Empty environment variables are ignored rather than taking the empty string value. This makes it possible for scripts to clear variables if they can’t unset them.

Changed in version 2.0: Changed signature for parameter callback to also be passed the parameter. The old callback format will still work, but it will raise a warning to give you a chance to migrate the code easier.

param_type_name = 'parameter'¶
name: str¶
opts: list[str]¶
secondary_opts: list[str]¶
type: ParamType[Any]¶
required: bool¶
callback: Callable[[Context, Parameter, Any], Any] | None¶
nargs: int¶
multiple: bool¶
expose_value: bool¶
default: Any | Callable[[], Any] | None¶
is_eager: bool¶
metavar: str | None¶
envvar: str | Sequence[str] | None¶
deprecated: bool | str¶
help: str | None¶
to_info_dict()[source]¶

Gather information that could be useful for a tool generating user-facing documentation.

Use click.Context.to_info_dict() to traverse the entire CLI structure.

Changed in version 8.3.0: Returns None for the default if it was not set.

Added in version 8.0.

Return type:

dict[str, Any]

property human_readable_name: str¶

Returns the human readable name of this parameter. This is the same as the name for options, but the metavar for arguments.

make_metavar(ctx)[source]¶
Return type:

str

get_default(ctx, call=True)[source]¶

Get the default for the parameter. Tries Context.lookup_default() first, then the local default.

Overloads:
Parameters:
  • ctx (Context) – Current context.

  • call (bool) – If the default is a callable, call it. Disable to return the callable instead.

Changed in version 8.0.2: Type casting is no longer performed when getting a default.

Changed in version 8.0.1: Type casting can fail in resilient parsing mode. Invalid defaults will not prevent showing help text.

Changed in version 8.0: Looks at ctx.default_map first.

Changed in version 8.0: Added the call parameter.

abstractmethod add_to_parser(parser, ctx)[source]¶
Return type:

None

type_cast_value(ctx, value)[source]¶

Convert and validate a value against the parameter’s type, multiple, and nargs.

Return type:

Any

get_help_record(ctx)[source]¶
Return type:

tuple[str, str] | None

get_usage_pieces(ctx)[source]¶
Return type:

list[str]

get_error_hint(ctx)[source]¶

Get a stringified version of the param for use in error messages to indicate which param caused the error.

Changed in version 8.4.0: ctx can be None.

Return type:

str

shell_complete(ctx, incomplete)[source]¶

Return a list of completions for the incomplete value. If a shell_complete function was given during init, it is used. Otherwise, the type shell_complete() function is used.

Parameters:
  • ctx (Context) – Invocation context for this command.

  • incomplete (str) – Value being completed. May be empty.

Return type:

list[CompletionItem]

Added in version 8.0.

class click_extra.ParameterSource(*values)[source]¶

Bases: IntEnum

This is an IntEnum that indicates the source of a parameter’s value.

Use click.Context.get_parameter_source() to get the source for a parameter by name.

Members are ordered from most explicit to least explicit source. This allows comparison to check if a value was explicitly provided:

source = ctx.get_parameter_source("port")
if source < click.ParameterSource.DEFAULT_MAP:
    ...  # value was explicitly set

Changed in version 8.3.3: Use IntEnum and reorder members from most to least explicit. Supports comparison operators.

Changed in version 8.0: Use Enum and drop the validate method.

Changed in version 8.0: Added the PROMPT value.

PROMPT = 1¶

Used a prompt to confirm a default or provide a value.

COMMANDLINE = 2¶

The value was provided by the command line args.

ENVIRONMENT = 3¶

The value was provided with an environment variable.

DEFAULT_MAP = 4¶

Used a default provided by Context.default_map.

DEFAULT = 5¶

Used the default specified by the parameter.

class click_extra.Path[_PathT_co = str | bytes | PathLike[str]](exists=False, file_okay=True, dir_okay=True, writable=False, readable=True, resolve_path=False, allow_dash=False, path_type=None, executable=False)[source]¶

Bases: ParamType[_PathT_co, str | PathLike[str]], Generic[_PathT_co]

The Path type is similar to the File type, but returns the filename instead of an open file. Various checks can be enabled to validate the type of file and permissions.

Parameters:
  • exists (bool) – The file or directory needs to exist for the value to be valid. If this is not set to True, and the file does not exist, then all further checks are silently skipped.

  • file_okay (bool) – Allow a file as a value.

  • dir_okay (bool) – Allow a directory as a value.

  • readable (bool) – if true, a readable check is performed.

  • writable (bool) – if true, a writable check is performed.

  • executable (bool) – if true, an executable check is performed.

  • resolve_path (bool) – Make the value absolute and resolve any symlinks. A ~ is not expanded, as this is supposed to be done by the shell only.

  • allow_dash (bool) – Allow a single dash as a value, which indicates a standard stream (but does not open it). Use open_file() to handle opening this value.

  • path_type (type[_PathT_co] | None) – Convert the incoming path value to this type. If None, keep Python’s default, which is str. Useful to convert to pathlib.Path.

Changed in version 8.5.1: Reveal the actual type of the value as converted from raw input.

Changed in version 8.1: Added the executable parameter.

Changed in version 8.0: Allow passing path_type=pathlib.Path.

Changed in version 6.0: Added the allow_dash parameter.

envvar_list_splitter: ClassVar[str] = ':'¶

if a list of this type is expected and the value is pulled from a string environment variable, this is what splits it up. None means any whitespace. For all parameters the general rule is that whitespace splits them up. The exception are paths and files which are split by os.path.pathsep by default (ā€œ:ā€ on Unix and ā€œ;ā€ on Windows).

exists: bool¶
file_okay: bool¶
dir_okay: bool¶
readable: bool¶
writable: bool¶
executable: bool¶
resolve_path: bool¶
allow_dash: bool¶
type: type[_PathT_co] | None¶
name: str¶

the descriptive name of this type

to_info_dict()[source]¶

Gather information that could be useful for a tool generating user-facing documentation.

Use click.Context.to_info_dict() to traverse the entire CLI structure.

Added in version 8.0.

Return type:

PathInfoDict

coerce_path_result(value)[source]¶
Return type:

_PathT_co

convert(value, param, ctx)[source]¶

Convert the value to the correct type. This is not called if the value is None (the missing value).

This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.

The param and ctx arguments may be None in certain situations, such as when converting prompt input.

If the value cannot be converted, call fail() with a descriptive message.

Parameters:
  • value (str | PathLike[str]) – The value to convert.

  • param (Parameter | None) – The parameter that is using this type to convert its value. May be None.

  • ctx (Context | None) – The current context that arrived at this value. May be None.

Return type:

_PathT_co

shell_complete(ctx, param, incomplete)[source]¶

Return a special completion marker that tells the completion system to use the shell to provide path completions for only directories or any paths.

Parameters:
  • ctx (Context) – Invocation context for this command.

  • param (Parameter) – The parameter that is requesting completion.

  • incomplete (str) – Value being completed. May be empty.

Return type:

list[CompletionItem]

Added in version 8.0.

class click_extra.ProgressOption(param_decls=None, *, is_flag=True, default=True, is_eager=True, expose_value=False, help='Show progress indicators during long operations. Disabled for non-interactive output (pipes, dumb terminals, CI) and by --accessible.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured --progress/--no-progress flag gating spinner display.

Resolves to a single boolean published at ctx.meta[click_extra.context.PROGRESS], which Spinner, OperationTrail and progressbar() read on their own when left at their automatic default. The default is True; --accessible lowers it to False (via default_map) so a screen reader is never handed a spinning glyph.

Note

Spinner display is decoupled from color, even though both emit ANSI. A spinner is an interactivity concern, not a color one: it is built from cursor-control codes (hide-cursor, carriage return, clear-line), which the NO_COLOR standard does not govern. It ā€œonly signals the user’s intention regarding adding ANSI color to text outputā€. So --no-color / NO_COLOR strip the spinner’s colors but never hide it.

The wider ecosystem treats the two axes the same way: cargo, npm, pip, Rich, indicatif and ora all gate progress on the terminal (and a dedicated --progress/--quiet knob), while NO_COLOR only affects color. Rich takes TERM=dumb, not NO_COLOR, as the signal to drop cursor-moving features like progress bars.

Two things silence the spinner, neither of them color:

  • non-interactive output: a pipe, file, CI log, or TERM=dumb terminal that cannot move the cursor (see _can_draw());

  • explicit intent: --no-progress or --accessible.

This option is eager. It never reads ctx.color, so its position relative to ColorOption does not matter.

set_progress(ctx, param, value)[source]¶

Publish whether progress spinners may be shown.

Stores the resolved --progress flag at PROGRESS. Deliberately independent of color: see the ProgressOption note for why a spinner is gated on interactivity (TTY / TERM=dumb) and --accessible, never on --no-color / NO_COLOR.

Return type:

None

class click_extra.QuietOption(param_decls=None, **kwargs)[source]¶

Bases: _CounterOption

--quiet/-q option to lower the log level of _VerbosityOption by one step per repetition.

The symmetric counterpart of VerboseOption: where -v raises the verbosity one LogLevel step at a time, -q lowers it. Starting from VerbosityOption.default (WARNING by default):

  • -q lowers the level to ERROR,

  • -qq lowers the level to CRITICAL,

  • any further repetition is clamped at the quietest level, so -qqqqq for example resolves to CRITICAL.

-q shares a single signed counter with VerboseOption’s -v, so the two cancel out: -v -q leaves the level unchanged. See _VerbosityOption.resolve_level for the full reconciliation rule with --verbosity.

Set up a verbosity-altering option.

Parameters:

default_logger –

The logger the option sets the level of:

  • A logging.Logger object is used as it is.

  • The name of the root logger, which is the default, selects it.

  • A name found in the global registry selects that logger as it is.

  • Any other name creates the logger with new_logger().

Building the option never touches the root logger, which the whole process shares. Whichever logger is selected, the root one gets Click Extra’s handler for the time of each run of the command: see add_to_parser().

class click_extra.Result(runner, stdout_bytes, stderr_bytes, output_bytes, return_value, exit_code, exception, exc_info=None)[source]¶

Bases: Result

A Result subclass with automatic traceback formatting.

Enhances __repr__ so that pytest assertion failures show the full traceback instead of just the exception type.

property formatted_exception: str | None[source]¶

Full formatted traceback, or None if no exception occurred.

class click_extra.SchemaFieldInfo(key, type_hint, default, summary, description)[source]¶

Bases: NamedTuple

Documentation record for one option of a configuration schema.

Produced by schema_field_infos(). Consumed by the click:config Sphinx directive, and by CLIs building their own configuration reference (a show-config table, say) from the same introspection.

Create new instance of SchemaFieldInfo(key, type_hint, default, summary, description)

key: str¶

Dotted configuration path of the option.

Field names are kebab-cased (setup_guide → setup-guide) unless the field pins an explicit path through click_extra.config.schema.CONFIG_PATH_METADATA_KEY. Nested dataclass fields contribute one segment per nesting level (test-suite.timeout).

type_hint: str¶

The field’s type annotation, as written in the schema source.

default: Any¶

The field’s default value, taken from a pristine schema instance.

summary: str¶

First paragraph of the field’s attribute docstring, collapsed onto a single line. Empty when the field has no docstring or the class source is unavailable (see field_docstrings()).

description: str¶

Full attribute docstring of the field, paragraph breaks preserved.

class click_extra.Section(title, commands=(), is_sorted=False)[source]¶

Bases: object

A group of (sub)commands to show in the same help section of a MultiCommand. You can use sections with any Command that inherits from SectionMixin.

Changed in version 0.6.0: removed the deprecated old name GroupSection.

Changed in version 0.5.0: introduced the new name Section and deprecated the old GroupSection.

Parameters:
  • title (str)

  • commands (Sequence[Command] | dict[str, Command]) – sequence of commands or dict of commands keyed by name

  • is_sorted (bool) – if True, list_commands() returns the commands in lexicographic order

commands: OrderedDict[str, Command]¶
classmethod sorted(title, commands=())[source]¶
Return type:

Section

add_command(cmd, name=None)[source]¶
Return type:

None

list_commands()[source]¶
Return type:

list[tuple[str, Command]]

class click_extra.SectionMixin(*args, commands=None, sections=(), align_sections=None, **kwargs)[source]¶

Bases: object

Adds to a click.MultiCommand the possibility of organizing its subcommands into multiple help sections.

Sections can be specified in the following ways:

  1. passing a list of Section objects to the constructor setting the argument sections

  2. using add_section() to add a single section

  3. using add_command() with the argument section set

Commands not assigned to any user-defined section are added to the ā€œdefault sectionā€, whose title is ā€œCommandsā€ or ā€œOther commandsā€ depending on whether it is the only section or not. The default section is the last shown section in the help and its commands are listed in lexicographic order.

Changed in version 0.8.0: this mixin now relies on cloup.HelpFormatter to align help sections. If a click.HelpFormatter is used with a TypeError is raised.

Changed in version 0.8.0: removed format_section. Added make_commands_help_section.

Added in version 0.5.0.

Parameters:
  • align_sections (bool | None) – whether to align the columns of all subcommands’ help sections. This is also available as a context setting having a lower priority than this attribute. Given that this setting should be consistent across all you commands, you should probably use the context setting only.

  • args (Any) – positional arguments forwarded to the next class in the MRO

  • kwargs (Any) – keyword arguments forwarded to the next class in the MRO

add_section(section)[source]¶

Add a Section to this group. You can add the same section object only a single time.

See Also:

section()

Return type:

None

section(title, *commands, **attrs)[source]¶

Create a new Section, adds it to this group and returns it.

Return type:

Section

add_command(cmd, name=None, section=None, fallback_to_default_section=True)[source]¶

Add a subcommand to this Group.

Implementation note: fallback_to_default_section looks not very clean but, even if it’s not immediate to see (it wasn’t for me), I chose it over apparently cleaner options.

Parameters:
  • cmd (Command)

  • name (str | None)

  • section (Section | None) – a Section instance. The command must not be in the section already.

  • fallback_to_default_section (bool) – if section is None and this option is enabled, the command is added to the ā€œdefault sectionā€. If disabled, the command is not added to any section unless section is provided. This is useful for internal code and subclasses. Don’t disable it unless you know what you are doing.

Return type:

None

list_sections(ctx, include_default_section=True)[source]¶

Return the list of all sections in the ā€œcorrect orderā€.

If include_default_section=True and the default section is non-empty, it will be included at the end of the list.

Return type:

list[Section]

format_subcommand_name(ctx, name, cmd)[source]¶

Used to format the name of the subcommands. This method is useful when you combine this extension with other click extensions that override format_commands(). Most of these, like click-default-group, just add something to the name of the subcommands, which is exactly what this method allows you to do without overriding bigger methods.

Return type:

str

make_commands_help_section(ctx, section)[source]¶
Return type:

HelpSection | None

must_align_sections(ctx, default=True)[source]¶
Return type:

bool

format_commands(ctx, formatter)[source]¶
Return type:

None

class click_extra.ShowParamsOption(param_decls=None, *, is_flag=True, expose_value=False, is_eager=True, help='Show all CLI parameters, their provenance, defaults and value, then exit.', **kwargs)[source]¶

Bases: ExtraOption, ParamStructure

A pre-configured option adding a --params option.

Between configuration files, default values and environment variables, it might be hard to guess under which set of parameters the CLI will be executed. This option prints information about the parameters that will be fed to the CLI.

Note

The flag is named --params, not --show-params. It names the view it prints, matching the neighbouring bare-noun informational flags (--help, --version, --man, --tree), none of which carry a show- verb prefix. The class and the @show_params_option decorator are named for what they do (show the parameters), while the flag and the parameter’s ID use the bare noun.

TABLE_HEADERS: ClassVar[tuple[ColumnSpec, ...]] = (ColumnSpec(id='id', label='ID', description='Fully-qualified parameter path (`cli.subcommand.param_name`) derived from the [`click.Command`](https://click.palletsprojects.com/en/stable/api/#click.Command) tree. Doubles as the key used to address the parameter from a configuration file, which also accepts the kebab-case spelling of the last segment.', max_width=None, optional=False, sortable=True), ColumnSpec(id='spec', label='Spec.', description='Option/argument specification string (like `-v, --verbose`) extracted from [`click.Parameter.get_help_record()`](https://click.palletsprojects.com/en/stable/api/#click.Parameter).', max_width=None, optional=False, sortable=True), ColumnSpec(id='help', label='Help', description="The parameter's own help text, as written by the CLI author. Opt-in: it is the only column carrying free-form prose, so it stays out of the default table and is selected by ID (`--columns id,spec,help`). Structured formats are its main audience: it turns a `--params` dump into a self-describing inventory a tool or an agent can read without also parsing the rendered `--help` screen.", max_width=None, optional=True, sortable=True), ColumnSpec(id='class', label='Class', description="Fully-qualified class of the parameter: a subclass of [`click.Option`](https://click.palletsprojects.com/en/stable/api/#click.Option), [`click.Argument`](https://click.palletsprojects.com/en/stable/api/#click.Argument), [`cloup.Option`](https://cloup.readthedocs.io/en/stable/autoapi/cloup/index.html#cloup.Option), or one of Click Extra's own wrappers ([`click_extra.parameters.Option`](#click_extra.parameters.Option), [`click_extra.parameters.Argument`](#click_extra.parameters.Argument), [`click_extra.parameters.ExtraOption`](#click_extra.parameters.ExtraOption)).", max_width=None, optional=False, sortable=True), ColumnSpec(id='param_type', label='Param type', description='Click value converter class: a subclass of [`click.ParamType`](https://click.palletsprojects.com/en/stable/api/#click.ParamType) like [`click.IntRange`](https://click.palletsprojects.com/en/stable/api/#click.IntRange), [`click.Choice`](https://click.palletsprojects.com/en/stable/api/#click.Choice), or a Click Extra type.', max_width=None, optional=False, sortable=True), ColumnSpec(id='python_type', label='Python type', description='Python built-in type the parsed value resolves to: [`str`](https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str), [`int`](https://docs.python.org/3/library/functions.html#int), [`float`](https://docs.python.org/3/library/functions.html#float), [`bool`](https://docs.python.org/3/library/functions.html#bool), or [`list`](https://docs.python.org/3/library/stdtypes.html#list). Computed by [`ParamStructure.get_param_type()`](#click_extra.param_tools.ParamStructure.get_param_type) from the Click `Param type`.', max_width=None, optional=False, sortable=True), ColumnSpec(id='hidden', label='Hidden', description="Reflects [`click.Option`'s `hidden`](https://click.palletsprojects.com/en/stable/api/#click.Option) constructor argument: the option is omitted from `--help` output. Empty for [`click.Argument`](https://click.palletsprojects.com/en/stable/api/#click.Argument), which does not support hiding.", max_width=None, optional=False, sortable=True), ColumnSpec(id='exposed', label='Exposed', description="Reflects [`click.Parameter`'s `expose_value`](https://click.palletsprojects.com/en/stable/api/#click.Parameter) constructor argument: whether the parsed value is forwarded to the command callback. Eager options like `--params` and `--help` typically run a callback and exit, so they are not exposed.", max_width=None, optional=False, sortable=True), ColumnSpec(id='allowed_in_conf', label='Allowed in conf?', description='Click Extra-specific: whether the parameter is reachable from a configuration file. Controlled by [`ParamStructure.excluded_params`](#click_extra.param_tools.ParamStructure.excluded_params) and [`included_params`](#click_extra.param_tools.ParamStructure.included_params). Empty when the CLI has no [`--config` option](config.md).', max_width=None, optional=False, sortable=True), ColumnSpec(id='envvars', label='Env. vars.', description="Environment variables read for this parameter: the explicit [`click.Parameter`'s `envvar`](https://click.palletsprojects.com/en/stable/api/#click.Parameter) plus the auto-resolved IDs documented in [Environment variables](envvar.md).", max_width=None, optional=False, sortable=True), ColumnSpec(id='default', label='Default', description='Default value returned by [`click.Parameter.get_default()`](https://click.palletsprojects.com/en/stable/api/#click.Parameter.get_default), rendered as its Python `repr()`.', max_width=None, optional=False, sortable=True), ColumnSpec(id='is_flag', label='Is flag', description="Reflects [`click.Option`'s `is_flag`](https://click.palletsprojects.com/en/stable/api/#click.Option): whether the option behaves as a flag (no value taken from the command line). Empty for [`click.Argument`](https://click.palletsprojects.com/en/stable/api/#click.Argument).", max_width=None, optional=False, sortable=True), ColumnSpec(id='flag_value', label='Flag value', description="Reflects [`click.Option`'s `flag_value`](https://click.palletsprojects.com/en/stable/api/#click.Option): the Python value substituted for the option when its flag is used. Defaults to `True` for boolean flags, can be any value for flag-value style options (like `@option('--upper', 'transform', flag_value='upper')`).", max_width=None, optional=False, sortable=True), ColumnSpec(id='is_bool_flag', label='Is bool flag', description='Reflects `click.Option.is_bool_flag` (set internally by Click when `flag_value` is `True` or `False`): the option is a *true* boolean flag, as opposed to a flag-value style option.', max_width=None, optional=False, sortable=True), ColumnSpec(id='multiple', label='Multiple', description="Reflects [`click.Parameter`'s `multiple`](https://click.palletsprojects.com/en/stable/api/#click.Parameter): the parameter can be repeated on the command line, collecting values into a tuple.", max_width=None, optional=False, sortable=True), ColumnSpec(id='nargs', label='Nargs', description="Reflects [`click.Parameter`'s `nargs`](https://click.palletsprojects.com/en/stable/api/#click.Parameter): the number of CLI tokens the parameter consumes. `1` is the default; `-1` denotes a variadic argument.", max_width=None, optional=False, sortable=True), ColumnSpec(id='prompt', label='Prompt', description="Reflects [`click.Option`'s `prompt`](https://click.palletsprojects.com/en/stable/api/#click.Option): the text shown to the user when the option is not provided on the command line. Empty when no prompt is configured.", max_width=None, optional=False, sortable=True), ColumnSpec(id='confirmation_prompt', label='Confirmation prompt', description="Reflects [`click.Option`'s `confirmation_prompt`](https://click.palletsprojects.com/en/stable/api/#click.Option): whether the user is asked to enter the value twice for confirmation.", max_width=None, optional=False, sortable=True), ColumnSpec(id='value', label='Value', description='Current value of the parameter at invocation time, computed by [`click.Parameter.consume_value()`](https://click.palletsprojects.com/en/stable/api/#click.Parameter) from the merged sources (CLI, environment, config file, default).', max_width=None, optional=False, sortable=True), ColumnSpec(id='source', label='Source', description='Provenance of the resolved value: a [`click.core.ParameterSource`](https://click.palletsprojects.com/en/stable/api/#click.core.ParameterSource) enum member such as `COMMANDLINE`, `ENVIRONMENT`, `DEFAULT_MAP`, or `DEFAULT`.', max_width=None, optional=False, sortable=True), ColumnSpec(id='config_file', label='Config file', description='The configuration file the effective value was loaded from, when `Source` reports `DEFAULT_MAP`. With [`cascade=True`](config-discovery.md#cascading-configuration-files) several files are layered and this column names the one that won the parameter; with a single loaded file, every config-sourced parameter names that file. Empty for every other source and when no configuration file was loaded. Drawn by default when the `--config` option cascades, and opt-in otherwise, like `help`: paths are wide and stay redundant with `Source` until several files can take part.', max_width=None, optional=True, sortable=True))¶

Rich column registry for the --params table.

Each entry is a click_extra.columns.ColumnSpec carrying the column’s stable id (used by --columns and as structured-format key), its display label, and a MyST/Markdown description consumed by the documentation’s auto-generated Available columns section. Iteration yields columns in canonical display order.

classmethod column_labels()[source]¶

Return just the display labels of TABLE_HEADERS (in order).

Return type:

tuple[str, ...]

classmethod column_ids()[source]¶

Return just the stable IDs of TABLE_HEADERS (in order).

Return type:

tuple[str, ...]

classmethod default_columns()[source]¶

Return the columns rendered when --columns asks for no projection.

Every column but the optional ones, which stay addressable by ID and out of the way until named.

Return type:

tuple[ColumnSpec, ...]

classmethod default_column_ids()[source]¶

Return the stable IDs of default_columns() (in order).

Return type:

tuple[str, ...]

classmethod default_column_labels()[source]¶

Return the display labels of default_columns() (in order).

Return type:

tuple[str, ...]

classmethod find_column(column_id)[source]¶

Return the ColumnSpec matching column_id.

Raises:

KeyError – if no column has this ID. Convert it into a click.UsageError before it reaches a user.

Return type:

ColumnSpec

classmethod render_doc_table()[source]¶

Render TABLE_HEADERS as a Markdown table for documentation.

Used by the show_params_columns_table MyST substitution in docs/conf.py to feed the Available columns section of docs/parameters.md: editing a description here automatically rebuilds the docs table on the next sphinx-build.

Return type:

str

excluded_params: frozenset[str]¶

Deactivates the blocking of any parameter.

included_params: frozenset[str] | None¶

No allowlist filter; show all parameters.

print_params(ctx, param, value)[source]¶

Introspect the current CLI and print its parameter metadata table.

Thin wrapper over render_params_table(), the shared rendering core also driving click-extra wrap --params for foreign CLIs. The live invocation context carries everything the core needs: the captured RAW_ARGS (attached by Command/Group) for value and source resolution, plus any sibling --table-format / --columns options.

Return type:

None

exception click_extra.SkippedTest[source]¶

Bases: Exception

Raised when a test case should be skipped.

class click_extra.SortByOption(*header_defs, param_decls=None, columns=None, default=None, expose_value=False, cell_key=None, help='Sort table by this column. Repeat to set priority.', **kwargs)[source]¶

Bases: ExtraOption

A --sort-by option whose choices are derived from column definitions.

Stores the selected column IDs in ctx.meta[click_extra.context.SORT_BY] and publishes the derived row sort key in ctx.meta[click_extra.context.TABLE_SORT_KEY], which ctx.print_table picks up so that table output is automatically sorted, without changing its (table_data, headers) call contract. The option accepts multiple=True, so users can repeat --sort-by to define a multi-column sort priority.

Column definitions are ColumnSpec instances, passed positionally or via the columns= keyword. A column marked sortable=False keeps its place in the layout without being offered as a choice. Passing a ColumnSpec registry via columns= lets the same tuple drive both ColumnsOption (--columns) and --sort-by, so the two options stay in sync from a single source of truth.

COLUMNS = (
    ColumnSpec("package_id", "Package ID"),
    ColumnSpec("package_name", "Name"),
    ColumnSpec("manager_id", "Manager"),
)


@command
@table_format_option
@columns_option(columns=COLUMNS)
@sort_by_option(columns=COLUMNS)
@pass_context
def my_cmd(ctx):
    ctx.print_table(rows, [col.label for col in COLUMNS])

Definitions may instead be bare column ID strings, declaring a field vocabulary untied to any single table layout. This fits a --sort-by declared once on a group whose subcommands render heterogeneous tables: no sort key is published since no layout is known up front. The selection is resolved per table by print_table(), from the column IDs its headers carry: each table sorts by the selected fields it knows (remaining columns breaking ties left to right) and keeps its original row order when it knows none.

@group
@sort_by_option("package_id", "package_name", "manager_id")
def my_cli():
    pass


@my_cli.command
def installed():
    print_table(
        rows,
        [
            ColumnSpec("package_id", "Package ID"),
            ColumnSpec("manager_id", "Manager"),
        ],
    )


@my_cli.command
def managers():
    print_table(rows, [ColumnSpec("manager_id", "Manager"), "Path"])
field_vocabulary¶

Whether definitions are bare column IDs, untied to any table layout.

In this mode init_sort() only publishes the selection on the context: the sort is resolved per table at print_table() time.

init_sort(ctx, param, sort_columns)[source]¶

Publish the row sort key on the context’s shared meta.

Builds the sort key from this option’s column definitions and the selected sort_columns, then stores it under ctx.meta[click_extra.context.TABLE_SORT_KEY], where ctx.print_table picks it up. The call contract is the same sorted or not: ctx.print_table(table_data, headers).

In field-vocabulary mode no table layout is known at declaration time, so no key is published: only the selection lands on the context (ctx.meta is shared with every subcommand), resolved per table by print_table() from the column IDs its headers carry.

Return type:

None

class click_extra.Spinner(label='', *, frames=None, spinner=None, reverse=False, interval=None, delay=0.0, style=None, label_style=None, timer=None, timer_style=None, stream=None, live='auto', hide_cursor=True, beep=False)[source]¶

Bases: object

A thread-animated, indeterminate progress spinner usable as a context manager.

The animation runs on a background daemon thread, leaving the calling thread free to block on the actual work. Entering the context (or calling start()) begins the animation; leaving it (or calling stop()) halts the thread and erases the spinner line so it never lingers above the next output.

Note

A single Spinner instance drives one animation at a time. A tool running its steps one after another can share one instance and reassign its label between steps. Concurrent work takes one instance per thread.

Configure (but do not start) the spinner.

Parameters:
  • label (str | Callable[..., Any]) – text shown after the spinner glyph. As a special case, a bare @Spinner decorator passes the wrapped function here instead; it is detected and the label defaults to empty.

  • frames (Sequence[str] | None) – the animation frames, cycled in order. Defaults to SPINNER_FRAMES, or the spinner preset’s frames when given.

  • spinner (SpinnerPreset | None) – a SpinnerPreset from the SPINNERS catalog (spinner=SPINNERS["moon"]), supplying both frames and a tuned interval. An explicit frames or interval still overrides it.

  • reverse (bool) – cycle the frames backwards, spinning the animation the other way. Set it when the rotation runs counter to what you expect; it composes with any custom frames.

  • interval (float | None) – seconds between two frames. Defaults to DEFAULT_INTERVAL, or the spinner preset’s interval when given.

  • delay (float) – seconds to wait before drawing the first frame. A non-zero delay keeps the spinner silent for calls that finish quickly, so it only surfaces once an operation is genuinely slow.

  • style (Style | None) – a Style applied to the spinner glyph, label and timer (Style(fg="cyan", bold=True)). Color is decoupled from animation: --no-color / NO_COLOR strip it while the spinner keeps spinning (see ProgressOption). The strip reaches escapes embedded in label itself too, so a label styled by hand is as safe as one styled through these arguments.

  • label_style (Style | None) – a Style for the label alone, in place of style there. It also paints the label of the kept ok() / fail() line, which style leaves plain. It outlives a reassigned label, where styling embedded in the text has to be applied again at every step.

  • timer (bool | Callable[[float], str] | None) – append the elapsed wall-clock time to the spinner, and to any final ok() / fail() line. None (the default) follows the CLI’s --time / --no-time flag, as an OperationTrail does. True forces it on with format_duration()’s compact format (2.3s, 1:05, then 1:02:03), False forces it off, and a callable (seconds: float) -> str formats the duration yourself, like timer=lambda s: f"{s / 60:.0f}m" for whole minutes.

  • timer_style (Style | None) – a Style for the timer, parentheses included, in place of style there (Style(dim=True) to set the clock back from the label). A timer callable formats only the duration, so it cannot reach the parentheses: this can. Also paints the timer of the kept ok() / fail() line.

  • stream (IO[str] | None) – where to draw; defaults to sys.stderr so the spinner never mixes into stdout data.

  • live (Literal['auto', 'always', 'never']) – where the animation may draw: "auto" (the default) on an interactive terminal only, unless --no-progress turns it off, "always" on any stream, "never" nowhere. A spinner that does not draw still writes its ok() / fail() line.

  • hide_cursor (bool) – hide the text cursor while spinning and restore it on stop.

  • beep (bool) – ring the terminal bell once when the spinner stops. It fires only when the spinner was active, so a disabled or redirected spinner stays silent.

Raises:

ValueError – if style, label_style or timer_style carries a color or attribute that cannot be rendered, or if live is not one of WHEN.

label: str¶

Text drawn after the spinner glyph.

Reassign it at any time while the spinner runs to reflect the current step; the animation thread reads it afresh on every frame.

property elapsed_time: float¶

Seconds elapsed since start(), frozen once stop() is called.

Returns 0.0 before the spinner has started.

property shown: bool¶

Whether the spinner has drawn at least one frame to its stream.

True only once an animation frame was actually rendered. It stays False for a disabled spinner (off a TTY, on a TERM=dumb terminal, or with live="never") and for a call that finishes within delay, before the first frame. Reset by start().

Use it to gate output that should mirror the spinner’s visibility. ok() and fail() write their line unconditionally, so an outcome is still recorded in a pipe or log. Guard them with shown when you only want the finisher on screen after a spinner the user actually saw:

with Spinner("Baking bread") as spinner:
    bake()
    if spinner.shown:
        spinner.ok()
frame_lines(*, color=True)[source]¶

Every line this spinner’s animation draws, one per frame.

One turn of the animation, held still. reverse, the label, the style and the timer all land the way start() would draw them, which is what an animated capture stacks into a picture of this spinner.

Note

The timer is read once, here, so every line carries the same elapsed time rather than a counting one: a still cannot show a clock running. A spinner that never started reads zero.

Parameters:

color (bool) – style each line. On by default, because a capture renders ANSI whatever the terminal the spinner would have drawn on accepts.

Return type:

tuple[str, ...]

Returns:

the lines, in the order the animation cycles them.

start()[source]¶

Begin animating on a background thread, unless the spinner is disabled.

A disabled spinner (non-TTY stream, or live="never") returns at once without spawning a thread or emitting anything (but still records the start time, so a later ok() / fail() can report a duration).

Return type:

None

stop()[source]¶

Halt the animation and erase the spinner line.

Idempotent and safe to call when the spinner never started. Restores the cursor and clears the line only if the animation actually drew to the terminal.

Return type:

None

echo(message='')[source]¶

Print message on its own line above the running spinner.

Click’s click.progressbar() and a bare print both fight the animation: a frame drawn between the cursor returns and the text mangles the line. echo() takes the same draw lock as the animation thread, erases the in-progress frame, writes message followed by a newline, and lets the next tick redraw the spinner underneath. It is safe to call from another thread while the spinner runs.

Output goes to the spinner’s own stream (stderr by default), so results written to stdout never need it. When the spinner is not animating (disabled, or a non-TTY stream), it degrades to a plain write of message with no control codes.

Return type:

None

ok(symbol=None, *, style=None)[source]¶

Stop the spinner and leave a persistent success line on screen.

Where stop() erases the spinner, ok() replaces the final frame with symbol followed by the current label (and the elapsed time when timer is set), then keeps that line. symbol defaults to the themed success glyph OK_GLYPH (āœ“), painted with the active theme’s success slot unless style overrides it. Color is stripped under --no-color / NO_COLOR; the glyph stays.

Return type:

None

fail(symbol=None, *, style=None)[source]¶

Stop the spinner and leave a persistent failure line on screen.

The failure counterpart of ok(), defaulting to KO_GLYPH (✘) painted with the active theme’s error slot.

Return type:

None

class click_extra.SpinnerPreset(frames, interval)[source]¶

Bases: NamedTuple

A named spinner animation: its frames and the interval they look best at.

Pick one from the SPINNERS catalog, or build your own, and pass it to Spinner through its spinner argument.

Create new instance of SpinnerPreset(frames, interval)

frames: tuple[str, ...]¶

The animation frames, cycled in order.

interval: float¶

Seconds between two frames, tuned per spinner upstream.

class click_extra.StreamHandler(stream=None)[source]¶

Bases: StreamHandler

A handler to output logs to the console.

Wraps logging.StreamHandler, but uses click.echo() to support color printing.

Only sys.stderr or sys.stdout are allowed as output stream, and sys.stderr is the default.

Initialize the handler.

If stream is not specified, sys.stderr is used.

property stream: IO[Any]¶

The stream to which logs are written.

A proxy of the parent logging.StreamHandler’s stream attribute.

Redefined here to enforce checks on the stream value.

emit(record)[source]¶

Use click.echo() to print to the console.

Cooperates with any live terminal line currently drawing on the same stream (a Spinner, or an OperationTrail progress bar): the record is then printed through its echo, which erases the in-progress render first, so a log line emitted mid-draw lands on its own line instead of garbling the indicator (and vice versa).

The color tri-state is resolved through invocation_color() rather than left to click.echo()’s own context lookup: a record emitted from a background thread (a subprocess stream reader, a fan-out worker) has no reachable Click context, and would otherwise ignore --no-color and keep its ANSI codes on a TTY.

Return type:

None

class click_extra.Style(fg=None, bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None)[source]¶

Bases: Style

cloup.Style with extra ergonomics.

See the module docstring for the full list of additions. The runtime contract (calling the instance to apply the style, equality, hashing) is otherwise identical to cloup.Style.

fg: str | tuple[int, int, int] | int | None = None¶

Foreground color: named ANSI string, #rrggbb hex, RGB tuple, or palette index.

bg: str | tuple[int, int, int] | int | None = None¶

Background color: named ANSI string, #rrggbb hex, RGB tuple, or palette index.

cascade(base)[source]¶

Return a copy with None fields filled in from base.

The instance’s own non-None values always win: cascade only fills gaps. Useful for theme inheritance: derived.cascade(parent) keeps derived’s overrides and inherits the rest from parent.

Return type:

Style

to_dict()[source]¶

Serialize to a plain dict with only the set fields.

RGB tuples are emitted as #rrggbb strings so the result round-trips through TOML/JSON/YAML untouched. Pair with from_dict() to rebuild a Style.

Return type:

dict[str, Any]

classmethod from_dict(data)[source]¶

Build a Style from the plain dict produced by to_dict().

Validates that every key in data names a known Style field and raises TypeError otherwise. Pair with to_dict() to round-trip through TOML/JSON/YAML.

Return type:

Style

to_css()[source]¶

Render the style as a semicolon-separated CSS declaration list.

Style(fg="#f1fa8c", bold=True).to_css() returns "color: #f1fa8c; font-weight: bold". Suitable for inline style="..." attributes on HTML spans.

Return type:

str

classmethod from_ansi(escape)[source]¶

Parse one or more consecutive ANSI SGR escapes into a Style.

Supports the standard 8/16-color codes (30–37, 40–47, 90–97, 100–107), the 38;5;n / 48;5;n 256-color extension, and the 38;2;r;g;b / 48;2;r;g;b 24-bit extension. Reset codes (the full 0 reset, its parameter-less \x1b[m form included, and selective resets like 22, 39 or 49) are ignored, so parsing the full output of a style call (trailing reset included) recovers that style. Multiple back-to-back escapes (as click emits when combining colors with attributes: \x1b[31m\x1b[1m) are merged into a single Style.

To tokenize a string mixing text and escapes, with resets honored, see split_ansi().

Return type:

Style

contrast_ratio(other)[source]¶

Return the WCAG 2.x contrast ratio between this fg and other’s fg.

Result is in [1, 21]: 1 = identical colors (no contrast), 21 = maximum contrast (black on white). WCAG AA requires 4.5+ for normal text, 3.0+ for large text; AAA wants 7.0+ and 4.5+ respectively.

Return type:

float

class click_extra.TableFormat(*values)[source]¶

Bases: Enum

Enumeration of supported table formats.

Hard-coded to be in alphabetical order. Content of this enum is checked in unit tests.

Warning

The youtrack format is missing in action from any official JetBrains documentation. It will be removed in python-tabulate v0.11.

ALIGNED = 'aligned'¶
ASCIIDOC = 'asciidoc'¶
COLON_GRID = 'colon-grid'¶
CSV = 'csv'¶
CSV_EXCEL = 'csv-excel'¶
CSV_EXCEL_TAB = 'csv-excel-tab'¶
CSV_UNIX = 'csv-unix'¶
DOUBLE_GRID = 'double-grid'¶
DOUBLE_OUTLINE = 'double-outline'¶
FANCY_GRID = 'fancy-grid'¶
FANCY_OUTLINE = 'fancy-outline'¶
GITHUB = 'github'¶
GRID = 'grid'¶
HEAVY_GRID = 'heavy-grid'¶
HEAVY_OUTLINE = 'heavy-outline'¶
HJSON = 'hjson'¶
HTML = 'html'¶
JIRA = 'jira'¶
JSON = 'json'¶
JSON5 = 'json5'¶
JSONC = 'jsonc'¶
LATEX = 'latex'¶
LATEX_BOOKTABS = 'latex-booktabs'¶
LATEX_LONGTABLE = 'latex-longtable'¶
LATEX_RAW = 'latex-raw'¶
MEDIAWIKI = 'mediawiki'¶
MIXED_GRID = 'mixed-grid'¶
MIXED_OUTLINE = 'mixed-outline'¶
MOINMOIN = 'moinmoin'¶
ORGTBL = 'orgtbl'¶
OUTLINE = 'outline'¶
PIPE = 'pipe'¶
PLAIN = 'plain'¶
PRESTO = 'presto'¶
PRETTY = 'pretty'¶
PSQL = 'psql'¶
ROUNDED_GRID = 'rounded-grid'¶
ROUNDED_OUTLINE = 'rounded-outline'¶
RST = 'rst'¶
SIMPLE = 'simple'¶
SIMPLE_GRID = 'simple-grid'¶
SIMPLE_OUTLINE = 'simple-outline'¶
TEXTILE = 'textile'¶
TOML = 'toml'¶
TSV = 'tsv'¶
UNSAFEHTML = 'unsafehtml'¶
VERTICAL = 'vertical'¶
XML = 'xml'¶
YAML = 'yaml'¶
YOUTRACK = 'youtrack'¶
property is_markup: bool¶

Whether this format is a markup rendering.

ANSI codes never reach a markup rendering raw: they are either translated to the format’s native styling (see supports_styling) or stripped from cell values. Forcing --color on the command line preserves them as-is in the markup formats without styling support.

property supports_styling: bool¶

Whether ANSI codes are translated to this format’s native styling.

See STYLED_FORMATS for the registry.

property is_wrappable: bool¶

Whether this format renders a cell wrapped onto several lines.

See WRAPPABLE_FORMATS for the registry, and the rationale behind each excluded format.

class click_extra.TableFormatOption(param_decls=None, *, type=EnumChoice('aligned', 'asciidoc', 'colon-grid', 'csv', 'csv-excel', 'csv-excel-tab', 'csv-unix', 'double-grid', 'double-outline', 'fancy-grid', 'fancy-outline', 'github', 'grid', 'heavy-grid', 'heavy-outline', 'hjson', 'html', 'jira', 'json', 'json5', 'jsonc', 'latex', 'latex-booktabs', 'latex-longtable', 'latex-raw', 'mediawiki', 'mixed-grid', 'mixed-outline', 'moinmoin', 'orgtbl', 'outline', 'pipe', 'plain', 'presto', 'pretty', 'psql', 'rounded-grid', 'rounded-outline', 'rst', 'simple', 'simple-grid', 'simple-outline', 'textile', 'toml', 'tsv', 'unsafehtml', 'vertical', 'xml', 'yaml', 'youtrack'), metavar='FORMAT', default=TableFormat.ROUNDED_OUTLINE, expose_value=False, is_eager=True, help='Rendering style of tables.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured option that is adding a --table-format flag to select the rendering style of a table.

The selected table format ID is made available in the context in ctx.meta[click_extra.context.TABLE_FORMAT], where the render_table() and print_table() context methods pick it up as their default format. ctx.meta is shared along the context chain, so declaring this option on a group makes the selected format reach every subcommand:

  • ctx.render_table(table_data, headers, **kwargs): renders and returns the table as a string,

  • ctx.print_table(table_data, headers, **kwargs): renders and prints the table to the console.

Where:

  • table_data is a 2-dimensional iterable of iterables for rows and cells values,

  • headers is a list of string to be used as column headers,

  • **kwargs are any extra keyword arguments supported by the underlying table formatting function.

init_formatter(ctx, param, table_format)[source]¶

Save the resolved table_format in the context’s shared meta.

The render_table() and print_table() context methods read it back at call time.

Return type:

None

class click_extra.TelemetryOption(param_decls=None, *, default=False, expose_value=False, envvar=None, show_envvar=True, help='Collect telemetry and usage data.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured --telemetry/--no-telemetry option flag.

Respects the proposed DO_NOT_TRACK environment variable as a unified standard to opt-out of telemetry for TUI/console apps: a truthy DO_NOT_TRACK forces telemetry off, overriding the user-defined environment variables, the auto-generated values, and configuration files. Only an explicit --telemetry on the command line outranks it.

The resolved value is stored in ctx.meta[click_extra.context.TELEMETRY].

set_telemetry(ctx, param, value)[source]¶

Reconcile the flag with DO_NOT_TRACK and store the result on ctx.meta.

An explicit --telemetry/--no-telemetry on the command line wins. Otherwise a truthy DO_NOT_TRACK (bare presence, or any value not parseable as false, see parse_envvar_flag()) forces telemetry off. Read via click_extra.context.get(ctx, click_extra.context.TELEMETRY).

Important

DO_NOT_TRACK breaks the rule of the other machine-wide variables, which a configuration file and the option’s own variable outrank (see machine_envvars_apply()). It is a consumer-protection opt-out: a user exports it once to refuse tracking from every tool, and a configuration file a project ships, or a <CLI>_TELEMETRY variable a wrapper or a CI job sets, must not opt that user back in. Only the command line, which the user types, outranks it.

Note

DO_NOT_TRACK is read here rather than wired through the option’s envvar: Click’s environment plumbing feeds the raw value straight to the boolean flag, so DO_NOT_TRACK=1 would enable telemetry, inverting the convention. Reading it manually keeps the opt-out meaning, mirroring how ColorOption reads NO_COLOR and friends.

Return type:

None

class click_extra.TerminalBackground(*values)[source]¶

Bases: StrEnum

Shade of the background of a terminal.

What resolve_background() detects of the terminal a CLI runs in, and the chrome of a capture, which pictures a terminal: see click_extra.capture.presets. A capture tells the command it pictures which one it is drawn on through the same variables resolve_background() reads, see CAPTURE_TERMINAL_HINTS, so a command run for a picture picks the palette its picture needs.

A capture freezes the colors of the run it pictures, so its chrome has to answer to the palette that run was colored for. Neither direction survives the other: a screen colored for a dark terminal is unreadable on white, and click-extra’s own light and manpage themes wash out on the dark chrome a renderer defaults to.

A member is the string it names, so it also selects the built-in theme of the same name, and doubles as the --background choice of the capture commands.

DARK = 'dark'¶

What a terminal, and this package’s default theme, usually look like.

LIGHT = 'light'¶

For a CLI rendered with a light-background theme.

class click_extra.ThemeOption(param_decls=None, *, default='dark', is_eager=True, expose_value=False, query_background=False, help='Color theme used for help screens.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured option that adds --theme to select the help-screen palette.

Accepts any name registered in theme_registry or in the per-invocation overrides loaded by ConfigOption from [tool.<cli>.themes.<name>]. Validation goes through ThemeChoice, which reads the live registry at parse time, so config-defined themes appear as valid choices and in the --help metavar without any further wiring.

The resolved HelpTheme lands on the Click context under click_extra.context.THEME and applies for the duration of the current invocation only.

A user who never passes the flag can still pick a palette by exporting THEME_ENVVAR (CLICK_EXTRA_THEME), which is honored by every Click Extra CLI at once. See set_theme() for how it ranks against the flag, the <CLI>_THEME variable and the configuration file.

The reserved value AUTO_THEME (--theme=auto) is also accepted on every CLI: it resolves the palette from the terminal background via resolve_auto_theme() instead of naming a registered theme. Background detection reads environment variables by default; pass query_background=True to additionally allow the live OSC 11 terminal query (query_osc_background()), which is opt-in because it reads stdin.

set_theme(ctx, param, value)[source]¶

Resolve the chosen theme name and store it on the Click context.

ThemeChoice has already validated value against the live registry (or accepted the AUTO_THEME directive) by the time this fires. A plain palette name is looked up unconditionally; auto is resolved from the terminal background via resolve_auto_theme(), leaving ctx.meta untouched when no palette can be resolved so get_current_theme() keeps its default.

Before that, THEME_ENVVAR is consulted when the value still comes from the option’s own default, as for every machine-wide variable (see machine_envvars_apply()). This yields the precedence: --theme > <CLI>_THEME > configuration file > CLICK_EXTRA_THEME > built-in default. The global variable therefore only names the palette of the CLIs nothing else has an opinion about.

Note

The variable is read here rather than wired through the option’s envvar. Click resolves an explicit envvar before the auto-generated <CLI>_THEME, which would let the machine-wide preference outrank the CLI-specific one, and would list both names in the --params table, making the combined string the widest cell of its column. This mirrors how AccessibleOption reads ACCESSIBLE and ColorOption reads NO_COLOR.

An unparsable palette name is a warning, not an error: a typo in a shell profile would otherwise break every Click Extra CLI on the machine at once, including the ones needed to fix it.

Return type:

None

class click_extra.TimerOption(param_decls=None, *, default=False, expose_value=False, is_eager=True, help='Measure and print elapsed execution time.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured option that is adding a --time/--no-time flag to print elapsed time at the end of CLI execution.

The start time is made available in the context in ctx.meta[click_extra.context.START_TIME].

print_timer(start_time)[source]¶

Print the time elapsed since start_time.

Always prints, even when a sibling eager option (--version, --params, --show-config…) short-circuited the command body via ctx.exit(). That makes --time a usable probe for the cost of Click Extra’s own machinery (option parsing, config loading, eager callbacks), not just user command bodies.

Parameters:

start_time (float) – the time.perf_counter() reading the run started at.

Return type:

None

init_timer(ctx, param, value)[source]¶

Set up the execution-timer machinery for the current invocation.

Captures time.perf_counter() as the start time, stores it on ctx.meta under click_extra.context.START_TIME, and queues print_timer() as a context-close callback so the elapsed duration is printed even when a sibling eager option (--version, --params…) short-circuits the command body.

The start time belongs to the run, not to the option: a run started from within another run of the same command times itself, and leaves the outer one its own start.

Return type:

None

class click_extra.TreeOption(param_decls=None, *, is_flag=True, expose_value=False, is_eager=True, help='Show the tree of nested subcommands and exit.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured --tree flag that prints the hierarchy of nested subcommands and exits.

Eager and value-less, like ManOption. Part of the default option set injected by default_params(), so every @command and @group exposes it. Use @tree_option to add it to a plain Click CLI.

Note

The flag is named --tree, not --show-tree or --commands.

Rendering a hierarchy as a tree is conventionally named tree across ecosystems: eza --tree, lsblk --tree, poetry show --tree, cargo tree, pstree(1) and tree(1) itself (ps --forest being the lone dissenter). --commands would suggest the flat listing --help already provides.

The bare noun also lines up with the neighbouring --help, --man, --params and --version informational flags. It is a flag rather than a registered tree subcommand, which could collide with the user’s own command namespace.

print_tree(ctx, param, value)[source]¶

Render and print the invoked command’s subcommand tree, then exit.

Return type:

None

class click_extra.Tuple(types)[source]¶

Bases: CompositeParamType[tuple[Any, ...]]

The default behavior of Click is to apply a type on a value directly. This works well in most cases, except for when nargs is set to a fixed count and different types should be used for different items. In this case the Tuple type can be used. This type can only be used if nargs is set to a fixed number.

For more information see Multi Value Options as Tuples.

This can be selected by using a Python tuple literal as a type.

Parameters:

types (Sequence[type[Any] | ParamType[Any]]) – a list of types that should be used for the tuple items.

types: Sequence[ParamType[Any]]¶
to_info_dict()[source]¶

Gather information that could be useful for a tool generating user-facing documentation.

Use click.Context.to_info_dict() to traverse the entire CLI structure.

Added in version 8.0.

Return type:

TupleInfoDict

property name: str¶
property arity: int¶

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ā€˜+’ or ā€˜-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(ā€˜0b100’, base=0) 4

convert(value, param, ctx)[source]¶

Convert the value to the correct type. This is not called if the value is None (the missing value).

This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.

The param and ctx arguments may be None in certain situations, such as when converting prompt input.

If the value cannot be converted, call fail() with a descriptive message.

Parameters:
  • value (Any) – The value to convert.

  • param (Parameter | None) – The parameter that is using this type to convert its value. May be None.

  • ctx (Context | None) – The current context that arrived at this value. May be None.

Return type:

tuple[Any, ...]

exception click_extra.UsageError(message, ctx=None)[source]¶

Bases: ClickException

An internal exception that signals a usage error. This typically aborts any further handling.

Parameters:
  • message (str) – the error message to display.

  • ctx (Context | None) – optionally the context that caused this error. Click will fill in the context automatically in some situations.

exit_code: ClassVar[int] = 2¶

The exit code for this exception.

ctx: Context | None¶
cmd: Final[Command | None]¶
show(file=None)[source]¶
Return type:

None

class click_extra.ValidateConfigOption(param_decls=None, *, type=UNPROCESSED, metavar='LOCATION', is_eager=True, expose_value=False, help='Validate the configuration file and exit.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured option adding --validate-config LOCATION.

Loads the config file at the given location, validates it against the CLI’s parameter structure in strict mode, reports results, and exits.

Note

The value is left UNPROCESSED so it accepts everything ConfigOption accepts: a file, a folder, a glob pattern, or an http:// or https:// URL. Both options read their value the same way, so a configuration a CLI can load is a configuration it can also validate.

validate_config(ctx, param, value)[source]¶

Load, parse, and validate the configuration file, then exit.

Validation runs three checks in order, every one of them under the same ValidationError shape so the reported path is always rooted at the configuration file:

  1. CLI-parameter strict check on the non-opaque part of the document.

  2. Schema processing, if a config_schema is configured: catches type errors and unknown keys inside the dataclass-described section.

  3. Each registered ConfigValidator runs against its declared opaque sub-tree.

Every detected error is emitted before exiting, so a single --validate-config run surfaces the full list of fixes the user needs to apply.

Return type:

None

exception click_extra.ValidationError(path, message, code=None)[source]¶

Bases: ValueError

Raised when a configuration file fails validation.

A single, structured exception type that uniformly carries the dotted path of the offending key, a human-readable message, and an optional code for programmatic handling. Used by click-extra’s built-in strict-mode check and by every user-registered ConfigValidator, so downstream apps and --validate-config see the same error shape regardless of who detected the problem.

Click-extra raises it with one of these codes, all spelled in snake case:

  • invalid_key: a dotted key conflicts with another key, or has an empty segment, or a key is not a string.

  • invalid_theme: a [tool.<cli>.themes.<name>] table builds no theme, like one naming a slot no theme has.

  • invalid_theme_shape: a [tool.<cli>.themes.<name>] entry is not a table.

  • schema_error: the configuration schema rejects the section.

  • unknown_parameter: a key matches no CLI parameter, or one excluded from configuration files.

Parameters:
  • path (str) – Dotted path to the offending key, relative to the configuration file root (like "my-cli.managers.winget.cli_searchpath"). An empty string means the error applies to the document as a whole.

  • message (str) – Human-readable description of the failure. Should be a single sentence, no trailing punctuation, no path repeated.

  • code (str | None) – Optional machine-readable error code (like "unknown_field") for callers that want to dispatch on error type without parsing the message string.

class click_extra.ValidationReport(schema_instance, opaque_subtrees, errors, merged_conf=None)[source]¶

Bases: object

Outcome of one pass through run_config_validation().

Bundles everything a caller needs after validating a parsed configuration document: the typed schema instance, the extracted opaque sub-trees, the template-filtered config ready for default_map, and every error detected across all validation stages.

Note

The report holds references to the parsed sub-trees, not copies, so building it is cheap regardless of document size.

schema_instance: Any | None¶

Typed object produced by the configured schema callable.

None when no schema is configured, or when the schema stage raised (in which case the failure is recorded in errors).

opaque_subtrees: dict[str, dict[str, Any]]¶

Extracted extension sub-trees, keyed by dotted path relative to the app section. Only paths actually present in the document appear here, so callers can re-route them to per-path validators or stash them on ctx.meta.

errors: tuple[ValidationError, ...]¶

Every ValidationError detected, in stage order (CLI-flag keys first, then schema errors, then validator failures). Empty on success.

With collect_all=False this holds at most one error: the first failure short-circuits the remaining stages.

merged_conf: dict[str, Any] | None = None¶

The CLI-flag-bound configuration merged onto params_template: the payload load_conf() layers into the context’s default_map, as merge_default_map() does.

None when params_template was None (no strict check) or the strict check failed.

property ok: bool¶

True when no error was detected.

class click_extra.VerboseOption(param_decls=None, **kwargs)[source]¶

Bases: _CounterOption

--verbose/-v option to raise the log level of _VerbosityOption by one step per repetition.

Each -v raises the verbosity by one LogLevel step. The option can be repeated, so -vv (or -v -v) raises it by two steps.

The base level the counter starts from is sourced from VerbosityOption.default. So with --verbosity’s default left at WARNING:

  • -v raises the level to INFO,

  • -vv raises the level to DEBUG,

  • any further repetition is clamped at the loudest level, so -vvvvv for example resolves to DEBUG.

-v shares a single signed counter with QuietOption’s -q, so the two cancel out: -v -q leaves the level unchanged. See _VerbosityOption.resolve_level for the full reconciliation rule with --verbosity.

Set up a verbosity-altering option.

Parameters:

default_logger –

The logger the option sets the level of:

  • A logging.Logger object is used as it is.

  • The name of the root logger, which is the default, selects it.

  • A name found in the global registry selects that logger as it is.

  • Any other name creates the logger with new_logger().

Building the option never touches the root logger, which the whole process shares. Whichever logger is selected, the root one gets Click Extra’s handler for the time of each run of the command: see add_to_parser().

class click_extra.VerbosityOption(param_decls=None, *, default_logger='root', default=LogLevel.WARNING, metavar='LEVEL', type=EnumChoice('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'), help='Either CRITICAL, ERROR, WARNING, INFO, DEBUG.', **kwargs)[source]¶

Bases: _VerbosityOption

--verbosity LEVEL option to set the log level of _VerbosityOption.

Set up a verbosity-altering option.

Parameters:

default_logger (Logger | str) –

The logger the option sets the level of:

  • A logging.Logger object is used as it is.

  • The name of the root logger, which is the default, selects it.

  • A name found in the global registry selects that logger as it is.

  • Any other name creates the logger with new_logger().

Building the option never touches the root logger, which the whole process shares. Whichever logger is selected, the root one gets Click Extra’s handler for the time of each run of the command: see add_to_parser().

set_level(ctx, param, value)[source]¶

Record the --verbosity value, then reconcile.

The value passed to --verbosity is saved in ctx.meta[click_extra.context.VERBOSITY].

Return type:

None

class click_extra.VersionOption(param_decls=None, *, message=None, fields=None, styles=None, message_style=None, screen=None, is_flag=True, expose_value=False, is_eager=True, help='Show the version and exit.', **kwargs)[source]¶

Bases: ExtraOption

Gathers CLI metadata and prints a colored version string.

Note

This is not a drop-in replacement for the standard @click.version_option() decorator.

It addresses the following Click issues:

  • click#2324, to allow its use with the declarative params= argument.

  • click#2331, by distinguishing the module from the package.

  • click#1756, by allowing path and Python version.

Preconfigured as a --version option flag.

Parameters:
  • message (str | None) – the message template to print, in format string syntax. Defaults to {prog_name}, version {version}.

  • fields (Mapping[str, Any] | None) – mapping of template field name to a forced value, overriding the value auto-computed for that field. Keys must be members of template_fields (for example {"version": "1.2.3"}).

  • styles (Mapping[str, Callable[[str], str] | None] | None) – mapping of template field name to its Style, merged over default_styles. Pass None as a value to clear a field’s default style. Keys must be members of template_fields.

  • message_style (Callable[[str], str] | None) – fallback style for the message literals and for any field that has no style of its own.

  • screen (VersionScreen | None) – a VersionScreen to draw instead of the one-line message, whenever the terminal can take it. Left unset, --version prints the one-line message.

Raises:

TypeError – when a key of fields or styles names no template field.

template_fields: tuple[str, ...] = ('module', 'module_name', 'module_file', 'module_version', 'package_name', 'package_version', 'author', 'license', 'exec_name', 'version', 'git_repo_path', 'git_branch', 'git_long_hash', 'git_short_hash', 'git_date', 'git_tag', 'git_tag_sha', 'git_distance', 'git_dirty', 'build_time', 'build_os', 'build_target', 'build_target_arch', 'prog_name')¶

List of field IDs recognized by the message template.

default_styles: ClassVar[dict[str, Callable[[str], str]]] = {'build_os': Style(fg='bright_black'), 'build_target': Style(fg='bright_black'), 'build_target_arch': Style(fg='bright_black'), 'build_time': Style(fg='bright_black'), 'exec_name': <function theme_slot.<locals>.apply>, 'git_branch': Style(fg='cyan'), 'git_date': Style(fg='bright_black'), 'git_dirty': Style(fg='red'), 'git_distance': <function theme_slot.<locals>.apply>, 'git_long_hash': Style(fg='yellow'), 'git_repo_path': Style(fg='bright_black'), 'git_short_hash': Style(fg='yellow'), 'git_tag': Style(fg='cyan'), 'git_tag_sha': Style(fg='yellow'), 'module_name': <function theme_slot.<locals>.apply>, 'module_version': <function theme_slot.<locals>.apply>, 'package_name': <function theme_slot.<locals>.apply>, 'package_version': <function theme_slot.<locals>.apply>, 'prog_name': <function theme_slot.<locals>.apply>, 'version': <function theme_slot.<locals>.apply>}¶

Default style for each template field.

Fields absent from this mapping render with no style of their own and fall back to message_style (or no color when that is unset). User-provided styles are merged over these defaults.

The name and version fields read their style off the active palette through theme_slot() rather than naming a color, so the message follows --theme. Under the default dark palette, invoked_command is bright white bold and success is green.

message: str = '{prog_name}, version {version}'¶

Default message template used to render the version string.

pin_field(field_id, value)[source]¶

Pin a template field to a caller-supplied value.

The value shadows the cached_property that would otherwise resolve the field, and is recorded so reset_resolution() can tell the two apart. Every caller that pins a field goes through here: a bare setattr sets the value without the record, and the next reset then discards it.

Parameters:
  • field_id (str) – Name of the template field to pin.

  • value (Any) – Value the field reports from now on.

Raises:

TypeError – when field_id names no template field.

Return type:

None

reset_resolution()[source]¶

Drop every memoized field, so the next read resolves from scratch.

The resolution chain starts on a stack walk, and the option is built once at decoration time, so the first read in a process fixes the answer for every later one. That is what a CLI wants: one invocation, one process, one walk.

A documentation build breaks the assumption. It renders many commands in one process, and a render that carries no CLI frame (writing roff for a command tree, say) resolves the chain from a stack the walk cannot read. The wrong answer then stands for the rest of the build, and a later --version example publishes it. Clearing the memo hands the next reader its own walk, at the cost of repeating one.

A field the caller pinned through fields= is not a resolution and survives: see _field_overrides.

Return type:

None

static cli_frame()[source]¶

Returns the frame in which the CLI is implemented.

Walks the execution stack from the innermost frame outwards, to find the package in which the user’s CLI is implemented. The walk reads the module and the function name of each frame off the frame itself, with no source lookup: --version is eager, so every CLI pays for this walk at startup.

Returns the frame itself. When every frame belongs to the Click ecosystem and none is an entry point, returns the outermost frame, which has no caller: module then defers to the module of the root command’s callback.

Return type:

FrameType

static command_module(ctx)[source]¶

Returns the module implementing the root command’s callback.

The stack walk in cli_frame() can only find the CLI when the CLI’s own module is on the stack. That holds for a normal invocation, and for a CliRunner driven from the test module that declares the command, but not when a runner invokes a command it merely imported: the walk then finds no user frame at all and stops on the runner’s own invoke(), inside the Click ecosystem.

The Sphinx click:run directive is that shape: without this, a documented --version would render the version of the ecosystem package owning the runner in place of the CLI’s own.

A launcher is the other shape. A console script or a compiled binary whose entry point is a command object, like orchard.cli:cli, leaves no frame of that module on the stack: the walk ends on the launcher itself.

A command’s callback names its defining module directly and needs no stack, so it settles the case the walk cannot see. Returns None when the command has no callback (a bare click.Group) or its module is not imported, leaving the walk’s own answer in place.

Return type:

ModuleType | None

property module: ModuleType[source]¶

Returns the module in which the CLI resides.

property module_name: str[source]¶

Returns the full module name or __main__.

property module_file: str | None[source]¶

Returns the module’s file full path.

None for a module with no file, like the __main__ of python -c.

property module_version: str | None[source]¶

Returns the string found in the local __version__ variable.

Hint

__version__ is a convention from early Python packaging. It is not a standard variable and is not defined in the packaging PEPs.

Prefer the package_version property below, which uses the standard library importlib.metadata API.

Click’s own version_option reads the package metadata only (pallets/click#2598). Click Extra reads __version__ too, for the scripts and codebases that set it.

property package_name: str | None[source]¶

Returns the package name.

property package_version: str | None[source]¶

Returns the package version if installed.

Resolved from the distribution name (see _distribution_name) via importlib.metadata.version(). Returns None if the package is not installed or cannot be resolved.

property author: str | None[source]¶

Returns the package author(s) from its core metadata.

See resolve_author() for the fields read, in order. None if no author can be determined.

property license: str | None[source]¶

Returns the package license from its core metadata.

See resolve_license() for the fields read, in order. None if no license can be determined.

property exec_name: str[source]¶

User-friendly name of the executed CLI.

Returns the module name. But if the module is a __main__ entry point, returns the package name: python -m runs it as __main__, while a console script or a compiled binary imports it as package.__main__.

If not packaged, the CLI is assumed to be a simple standalone script, and the returned name is the script’s file name (including its extension). Code with no file, like a CLI run by python -c, keeps the __main__ module name.

property version: str | None[source]¶

Return the version of the CLI.

Returns the module version if a __version__ variable is set alongside the CLI in its module.

Else returns the package version if the CLI is implemented in a package, using importlib.metadata.version().

For development versions (containing .dev), automatically appends the Git short hash as a PEP 440 local version identifier, producing versions like 1.2.3.dev0+abc1234. This helps identify the exact commit a dev build was produced from. When git_short_hash finds no commit, the plain dev version is returned.

Versions that already contain a + (a pre-baked local version identifier, typically set at build time by CI pipelines) are returned as-is to avoid producing invalid double-suffixed versions like 1.2.3.dev0+abc1234+xyz5678.

property git_repo_path: Path | None[source]¶

Find the Git repository root directory.

Walks up from _search_start to the first directory holding a .git entry: see find_git_root().

property git_branch: str | None[source]¶

Returns the current Git branch name.

Checks for a pre-baked __git_branch__ dunder first, then git rev-parse --abbrev-ref HEAD, then .git_archival.json.

property git_long_hash: str | None[source]¶

Returns the full Git commit hash.

Checks for a pre-baked __git_long_hash__ dunder first, then git rev-parse HEAD, then .git_archival.json, then the commit recorded for an install from a Git URL.

property git_short_hash: str | None[source]¶

Returns the short Git commit hash.

Checks for a pre-baked __git_short_hash__ dunder first, then git rev-parse --short HEAD, then .git_archival.json, then the commit recorded for an install from a Git URL. Both fallbacks derive it from the first 7 characters of the full hash.

Hint

The short hash is usually the first 7 characters of the full hash, but this is not guaranteed to be the case.

But it is at least guaranteed to be unique within the repository, and a minimum of 4 characters.

property git_date: str | None[source]¶

Returns the commit date in ISO format: YYYY-MM-DD HH:MM:SS +ZZZZ.

Checks for a pre-baked __git_date__ dunder first, then git show -s --format=%ci HEAD, then .git_archival.json (whose node-date is strict ISO 8601, like 2021-01-01T12:00:00+00:00).

property git_tag: str | None[source]¶

Returns the Git tag pointing at HEAD, if any.

Checks for a pre-baked __git_tag__ dunder first, then git describe --tags --exact-match HEAD, then .git_archival.json.

Returns None if HEAD is not at a tagged commit.

property git_tag_sha: str | None[source]¶

Returns the commit SHA that the current tag points at.

Checks for a pre-baked __git_tag_sha__ dunder first, then git rev-list -1 on the tag returned by git_tag, then .git_archival.json. Returns None if HEAD is not at a tag.

property git_distance: str | None[source]¶

Number of commits since the most recent tag, or None.

Checks for a pre-baked __git_distance__ dunder first, then parses git describe --tags --long, then falls back to .git_archival.json. None when no tag is reachable or Git is unavailable.

property git_dirty: str | None[source]¶

Work-tree state: "dirty", "clean" or None.

Checks for a pre-baked __git_dirty__ dunder first, then runs git status --porcelain. None when not in a Git repository or Git is unavailable. There is no .git_archival.json fallback: an archive has no work tree, so its state is unknowable.

property build_time: str | None[source]¶

When the distribution was built, as an RFC 3339 UTC timestamp.

Reads the pre-baked __build_time__ dunder, the only source of a build fact: see BUILD_RESOLVERS and resolve_build_time().

property build_os: str | None[source]¶

The operating system the build ran on.

Reads the pre-baked __build_os__ dunder. See resolve_build_os().

property build_target: str | None[source]¶

The platform a distribution built here installs on.

Reads the pre-baked __build_target__ dunder. See resolve_build_target().

property build_target_arch: str | None[source]¶

The CPU architecture the build ran on.

Reads the pre-baked __build_target_arch__ dunder. See resolve_build_target_arch().

property prog_name: str | None¶

Return the name of the CLI, from Click’s point of view.

Get the info_name of the root command.

Note

Unlike its siblings, this field is resolved on every access instead of being cached on the instance: it is the one template field whose value legitimately varies between invocations of the same option instance sharing a process. multicall dispatch relies on that, running one CLI under many names in sequence, and a prog_name passed to main() varies it without any multicall at all. A cached value would pin the first name seen forever.

field_style(field_id=None)[source]¶

Style painting the field_id segment of a rendered message.

A field carrying no style of its own falls back to message_style, and one left unset by the caller too renders bare. Call with no field_id for the style of the template’s literal segments, which is message_style alone.

Return type:

Callable[[str], str]

colored_template(template=None)[source]¶

Insert ANSI styles to a message template.

Accepts a custom template as parameter, otherwise uses the default message defined on the Option instance.

The template is linearized so the ANSI codes apply to its string segments: an ANSI directive cannot be nested within another, unlike a markup tag of HTML.

Return type:

str

render_message(template=None)[source]¶

Render the version string from the provided template.

Accepts a custom template as parameter, otherwise uses the default self.colored_template() produced by the instance.

A CLI carrying a VersionScreen gets that drawn instead, whenever three conditions hold. Failing any one of them falls back to the plain template unchanged, which is a deliberate guarantee rather than a default: that form is the one every machine reader parses.

  • Color reaches the output. A flat-shaded mark carries its shape in its colors, and color is the one lever a caller already has. A redirected --version, or one run under --no-color or NO_COLOR, is asking for something parseable.

  • The terminal is wide enough to seat the facts beside the mark without wrapping them.

  • Accessible mode is off. A mark read out character by character is noise to a screen reader, so --accessible keeps the plain message.

Return type:

str

print_debug_message()[source]¶

Render in debug logs all template fields in color.

Return type:

None

print_and_exit(ctx, param, value)[source]¶

Print the version string and exits.

Also stores all version string elements in the Context’s meta dict.

Return type:

None

class click_extra.VersionScreen(logo, tagline='', facts=<function default_facts>, gutter='   ')[source]¶

Bases: object

A logo, and the facts to seat beside it, as --version should draw them.

Owns the layout only. The artwork arrives already rendered, as a string or the lines of one, so a CLI is free to draw its mark however it likes, in ASCII line art, half-blocks or anything else, without this class knowing. Hand one to VersionOption through its screen argument, or to a whole CLI through default_params(screen=…).

The mark, pre-rendered, or a callable producing it. A string splits on newlines.

A callable defers the rendering to the first --version that draws the screen, as facts does for its values: a mark painted by code, from an image say, then costs nothing to the invocations that never ask for it.

tagline: str = ''¶

One line under the program name. Omitted, with its blank line, when empty.

facts()¶

Label-to-value rows under the tagline, or a callable producing them.

A callable defers the work to render time, which matters when a value costs something to compute: a CLI counting plugins should not pay for that on every invocation just to have the number ready in case --version is asked for.

Return type:

dict[str, str]

gutter: str = '   '¶

Blank columns between the mark and the facts, and between label and value.

property lines: tuple[str, ...]¶

The mark’s lines, every one padded out to width.

Padding here rather than asking for it is what lets a caller hand over whatever its renderer produced. Trailing blanks are invisible on a line by itself and ragged the moment anything is placed beside it, and a caller cannot repair that afterwards: pad_to() is what measures a styled line right and closes the style it left open.

property width: int¶

Columns the mark occupies, taken from its widest line.

rows(prog_name, version, styles)[source]¶

The column of facts, as (plain, styled) pairs.

Both forms are built together because the styled one cannot be measured: its escape sequences take columns that never reach the screen, and the plain twin is what render() sizes the layout against.

The program name and version take the same styles the plain message gives them, so the two renderings of --version cannot drift apart on color.

Return type:

tuple[tuple[str, str], ...]

render(prog_name, version, styles)[source]¶

Compose the mark and the facts into the screen, or decline to.

The facts are centred against the mark’s height, and either column may be the taller of the two: a line missing from one side simply renders blank.

Returns None when the terminal is too narrow to seat the two columns side by side, leaving the caller to fall back rather than emit a wrapped mess. The threshold is measured off the facts actually built, since their widest row grows with whatever a CLI chose to report. A non-interactive stream reports shutil’s 80-column default, wide enough that a redirected-but-forced-color run still gets the screen it asked for.

Return type:

str | None

class click_extra.ZeroExitOption(param_decls=None, *, default=False, expose_value=False, is_flag=True, help='Always exit with a status code of 0, even when problems are found.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured -0/--zero-exit option flag.

Follows the convention popularized by linters and static analysers, which exit with a non-zero code whenever they report findings so that automation can gate on it. Setting this flag flips that behavior: the CLI returns 0 as long as it ran to completion, reserving non-zero codes for actual execution failures.

The resolved value is stored in ctx.meta[click_extra.context.ZERO_EXIT].

Warning

This option is a placeholder: it does not alter the CLI’s exit code by itself. Downstream code must read ctx.meta[click_extra.context.ZERO_EXIT] and act on it.

set_zero_exit(ctx, param, value)[source]¶

Store the resolved zero-exit flag on the context’s meta dict.

Read via click_extra.context.get(ctx, click_extra.context.ZERO_EXIT).

Return type:

None

click_extra.accessible_option(param_decls=None, *, is_flag=True, default=False, is_eager=True, expose_value=False, help='Accessibility mode: disable colors and render tables in a borderless, screen-reader-friendly format.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.ansi_to_html(text)[source]¶

Translate ANSI styling in text to inline-styled HTML <span> tags.

\x1b[34mSummer\x1b[0m becomes <span style="color: blue">Summer</span>. The spans are self-contained (no stylesheet needed) and also valid in markups accepting inline HTML, like MediaWiki.

Return type:

str

click_extra.ansi_to_jira(text)[source]¶

Translate ANSI styling in text to Jira wiki markup.

\x1b[34;1mSummer\x1b[0m becomes {color:blue}*Summer*{color}.

Return type:

str

click_extra.ansi_to_latex(text)[source]¶

Translate ANSI styling in text to LaTeX macros.

\x1b[34;1mSummer\x1b[0m becomes \textcolor{blue}{\textbf{Summer}}. The colored macros require \usepackage{xcolor} in the document preamble.

Return type:

str

click_extra.ansi_to_textile(text)[source]¶

Translate ANSI styling in text to Textile spans.

\x1b[34;1mSummer\x1b[0m becomes %{color: blue; font-weight: bold}Summer%.

Return type:

str

click_extra.args_cleanup(*args)[source]¶

Flatten recursive iterables, remove all None, and cast each element to strings.

Serializes pathlib.Path and other objects. Nested iterables and None values are accepted as CLI arguments for convenience: they are flattened and filtered out.

Return type:

tuple[str, ...]

click_extra.argument(param_decls, required=None, help=None, **attrs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.basicConfig(*, filename=None, filemode='a', format='{levelname}: {message}', datefmt=None, style='{', level=None, stream=None, handlers=None, force=False, encoding=None, errors='backslashreplace', stream_handler_class=<class 'click_extra.logging.StreamHandler'>, file_handler_class=<class 'logging.FileHandler'>, formatter_class=<class 'click_extra.logging.Formatter'>)[source]¶

Configure the global root logger.

This function is a wrapper around Python standard library’s logging.basicConfig(), but with additional parameters and tweaked defaults.

It sets up the global root logger, and optionally adds a file or stream handler to it.

Differences in default values:

Argument

basicConfig() default

logging.basicConfig() default

style

{

%

format

{levelname}: {message}

%(levelname)s:%(name)s:%(message)s

This function takes the same parameters as logging.basicConfig(), but require them to be all passed as explicit keywords arguments.

Parameters:
  • filename (str | None) – Specifies that a logging.FileHandler be created, using the specified filename, rather than a StreamHandler.

  • filemode (str) –

    If filename is specified, open the file in this mode.

    Defaults to a.

  • format (str | None) –

    Use the specified format string for the handler.

    Defaults to {levelname}: {message}.

  • datefmt (str | None) – Use the specified date/time format, as accepted by time.strftime().

  • style (Literal['%', '{', '$']) –

    If format is specified, use this style for the format string:

    Defaults to {.

  • level (int | str | None) – Set the root logger level to the specified level.

  • stream (IO[Any] | None) – Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with filename - if both are present, a ValueError is raised.

  • handlers (Iterable[Handler] | None) – If specified, this should be an iterable of already created handlers to add to the root logger. Any handlers which don’t already have a formatter set will be assigned the default formatter created in this function. Note that this argument is incompatible with filename or stream - if both are present, a ValueError is raised.

  • force (bool) – If this argument is specified as True, any existing handlers attached to the root logger are removed and closed, before carrying out the configuration as specified by the other arguments.

  • encoding (str | None) – Name of the encoding used to decode or encode the file. To be specified along with filename, and passed to logging.FileHandler for opening the output file.

  • errors (str | None) – Optional string that specifies how encoding and decoding errors are to be handled by the logging.FileHandler. Defaults to backslashreplace. Note that if None is specified, it will be passed as such to open().

Return type:

None

Important

Always keep the signature of this function, the default values of its parameters and its documentation in sync with the one from Python’s standard library.

These new arguments are available for better configurability:

Parameters:

Note

The camel-cased name mirrors the one of Python’s standard library logging.basicConfig().

click_extra.cases_from_data(data)[source]¶

Build CLITestCase instances from already-parsed suite data.

The in-memory counterpart to parse_test_suite() (which parses a string) and load_test_suite() (which reads a file): feed it a suite that is already a Python object, such as the native cases mappings declared in a [tool.<cli>.test-suite] config section.

A suite is a list of case mappings, each keyed by CLITestCase directive names. Formats with no bare top-level array (TOML) carry that list under a top-level cases key, so a mapping is unwrapped here.

Raises:
  • ValueError – the suite is empty, a mapping suite omits cases, or a case uses unknown directives.

  • TypeError – the suite is not a list, or a case is not a mapping.

Return type:

Generator[CLITestCase, None, None]

click_extra.cell_width(text, term_program=None)[source]¶

Columns text occupies on a terminal’s character grid.

Not its length. A CJK ideograph is drawn two cells wide, a combining mark none, an ANSI escape or an OSC 8 hyperlink none at all while adding several characters, and a tab as many as it takes to reach the next stop eight columns along. wcwidth.width answers for all of them, which is what lets a caller measure text as it arrived rather than stripping it first.

Note

wcwidth.wcswidth, the older call, refuses any string carrying a control character and answers -1 for it, which is every styled string. Reach for it only where a consumer reads that value back, as tabulate does.

Parameters:
  • text (str) – the text to measure.

  • term_program (str | None) – name of the terminal drawing the text, as $TERM_PROGRAM holds it. A few of them advance an emoji-presentation sequence by one column where the Unicode tables say two, and naming the terminal applies wcwidth’s correction for it. None measures what the tables say.

Return type:

int

Returns:

the number of cells it occupies, never negative.

click_extra.clear()[source]¶

Drop-in for click.clear() that becomes a no-op under --accessible.

Clearing the screen wipes the scrollback a screen reader relies on and carries no meaning in a linear stream, so accessibility mode skips it entirely. Outside accessibility mode (or with no active context) it defers to click.clear(), which already no-ops when stdout is not a terminal.

Return type:

None

click_extra.color_option(param_decls=None, *, is_flag=False, flag_value='always', default='auto', is_eager=True, expose_value=False, help='Colorize the output. A bare --color is the same as --color=always.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.column_sort_key(header_defs, sort_columns=None, cell_key=None)[source]¶

Build a row sort key from the sort_columns a table actually carries.

header_defs describes the rendered columns: ColumnSpec instances, with sortable=False for columns that cannot be sorted on. The requested sort_columns the table carries drive the comparison first, de-duplicated and in request order; the remaining columns follow in their natural left-to-right order for tie-breaking.

Returns None when the table carries none of the requested columns, signalling that rows should keep their original order. This is what lets one --sort-by selection apply across subcommands rendering heterogeneous tables: each table sorts by the requested fields it knows, and a table knowing none of them is left untouched.

Return type:

Callable[[Sequence[str | None]], tuple] | None

click_extra.columns_option(param_decls=None, *, columns=None, type=None, metavar='COLUMNS', default=(), expose_value=False, is_eager=True, help='Restrict and reorder table columns, SQL SELECT-style. Comma-separated list of column IDs. Default: all columns in canonical order.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.command(*args, **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.compact_frames(tb)[source]¶

A traceback as module:line in function entries, outermost first.

Module names say as much as file paths about the code, and nothing about where it is installed, so they are what a report shows. A method shows with its class, like Path.open.

Return type:

tuple[str, ...]

click_extra.config_option(param_decls=None, *, metavar='LOCATION', type=UNPROCESSED, help='Location of the configuration file. Supports local path with glob patterns or remote URL.', is_eager=True, expose_value=False, file_format_patterns=None, file_pattern_flags=None, show_file_patterns=None, roaming=True, force_posix=False, search_pattern_flags=None, search_parents=False, stop_at=Sentinel.VCS, cascade=False, excluded_params=None, included_params=None, strict=False, config_schema=None, schema_strict=False, fallback_sections=(), config_validators=(), **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.config_table_to_flags(table)[source]¶

Translate a mapping of configuration keys into long-form CLI flags.

For tools whose command-line options mirror their configuration keys but which cannot read the table themselves (no --config support, no native config file). Follows the conventional mapping:

  • key = True → --key

  • key = "value" (or a number) → --key=value

  • key = ["a", "b"] → --key=a --key=b (one flag per item)

  • key = False is skipped: there is no universal --no-<key> form.

Keys keep their spelling, so hyphenated keys map straight onto long options, and flags follow the mapping’s iteration order.

Parameters:

table (Mapping[str, Any]) – The configuration keys and values, like a parsed [tool.X] section.

Return type:

list[str]

Returns:

The equivalent list of --flag / --flag=value arguments.

click_extra.confirm(text, default=False, abort=False, prompt_suffix=': ', show_default=True, err=False)[source]¶

Prompts for confirmation (yes/no question).

If the user aborts the input by sending a interrupt signal this function will catch it and raise a Abort exception.

Parameters:
  • text (str) – the question to ask.

  • default (bool | None) – The default value to use when no input is given. If None, repeat until input is given.

  • abort (bool) – if this is set to True a negative answer aborts the exception by raising Abort.

  • prompt_suffix (str) – a suffix that should be added to the prompt.

  • show_default (bool) – shows or hides the default value in the prompt.

  • err (bool) – if set to true the file defaults to stderr instead of stdout, the same as with echo.

Return type:

bool

Changed in version 8.3.1: A space is no longer appended to the prompt.

Changed in version 8.0: Repeat until input is given if default is None.

Added in version 4.0: Added the err parameter.

click_extra.confirmation_option(*param_decls, **kwargs)[source]¶

Add a --yes option which shows a prompt before continuing if not passed. If the prompt is declined, the program will exit.

Parameters:
  • param_decls (str) – One or more option names. Defaults to the single value "--yes".

  • kwargs (Any) – Extra arguments are passed to option().

Return type:

Callable[[FC], FC]

click_extra.constrained_params(constr, *param_adders)[source]¶

Return a decorator that adds the given parameters and applies a constraint to them. Equivalent to:

@param_adders[0]
...
@param_adders[-1]
@constraint(constr, <param names>)

This decorator saves you to manually (re)type the parameter names. It can also be used inside @option_group.

Instead of using this decorator, you can also call the constraint itself:

@constr(*param_adders)

but remember that:

  • Python 3.9 is the first that allows arbitrary expressions on the right of @;

  • using a long conditional/composite constraint as decorator may be less readable.

In these cases, you may consider using @constrained_params.

Added in version 0.9.0.

Parameters:
  • constr (Constraint) – an instance of Constraint

  • param_adders (Callable[[Callable[..., Any]], Callable[..., Any]]) – function decorators, each attaching a single parameter to the decorated function.

Return type:

Callable[[F], F]

click_extra.constraint(constr, params)[source]¶

Register a constraint on a list of parameters specified by (destination) name (e.g. the default name of --input-file is input_file).

Return type:

Callable[[F], F]

click_extra.convert_apidoc_rst_to_myst(content)[source]¶

Convert sphinx-apidoc RST to MyST markdown with {eval-rst} blocks.

Parameters:

content (str) – RST content produced by sphinx-apidoc.

Return type:

str

Returns:

Equivalent MyST markdown.

click_extra.convert_directory(directory)[source]¶

Convert all Python files in a directory from reST to MyST docstrings.

Parameters:

directory (Path) – Directory to process recursively.

Return type:

list[Path]

Returns:

List of files that were modified.

click_extra.convert_file(filepath)[source]¶

Apply all conversions to a single Python file.

Parameters:

filepath (Path) – The Python file to convert in place.

Return type:

bool

Returns:

True if the file was modified.

click_extra.convert_rst_files_in_directory(directory)[source]¶

Convert sphinx-apidoc RST files to MyST markdown in the given directory.

For each .rst file containing .. automodule:: directives:

  • If a .md file with the same stem exists, delete the .rst (the existing markdown takes precedence).

  • Otherwise, convert the RST content to MyST and write a .md file, then delete the .rst.

Parameters:

directory (Path) – Directory to scan for .rst files.

Return type:

list[Path]

Returns:

List of newly created .md file paths.

click_extra.convert_source(source)[source]¶

Convert reST markup to MyST in a Python module’s docstrings and comments.

Docstrings get the full pipeline, in an order that matters: inline constructs (cross-references, links, inline code) run before directives so that directive bodies are already converted when they are dedented into fences. Comments get the inline conversions only, except consecutive full-line #: comments, whose directives are also converted through convert_comment_blocks(). Everything outside docstrings and comments passes through byte-for-byte.

Return type:

str

click_extra.corner_header(rows, columns)[source]¶

Name both axes of a two-axis table in its top-left header cell.

rows says what the first column lists, read downward, and columns what the other headers list, read rightward: corner_header("City", "Month") returns City ↓ \ Month →.

Return type:

str

click_extra.culprit_function(tb, package)[source]¶

The name of the innermost function of package in a traceback, or nothing.

It names the code to fix, even for an error that Python or a library raised from a call of the package. A generator expression, a comprehension or a lambda has no name of its own, so the named function nearest to it in the traceback stands for it.

Return type:

str

click_extra.custom_version_option(callback, *param_decls, **kwargs)[source]¶

Add a --version option whose output is produced by callback.

This is the customizable companion to version_option(). Where version_option() is intentionally limited to a fixed message and a small set of values, this option calls callback to build the whole string to print. Use it when you need values that version_option() does not expose, such as a file path, the Python version, or git metadata.

Parameters:
  • callback (Callable[[Context], str]) – Called with the current Context when the option is invoked. Its return value is printed, then the program exits.

  • param_decls (str) – One or more option names. Defaults to the single value --version.

  • kwargs (Any) – Extra arguments are passed to option().

Return type:

Callable[[FC], FC]

Added in version 8.5.0.

click_extra.debug_option(param_decls=None, *, default_logger='root', is_flag=True, default=False, help='Shorthand for --verbosity DEBUG.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.default_facts()[source]¶

The facts every version screen carries, as an ordered label-to-value map.

A mapping rather than a sequence of pairs so a CLI can adjust one row without restating the rest, dict preserving insertion order and replacement keeping a key where it already sat:

default_facts() | {"Platform": my_own_label}   # replaces, in place
default_facts() | {"Docs": DOCS_URL}           # appends, at the end
Return type:

dict[str, str]

click_extra.default_params(screen=None)[source]¶

Default additional options added to @command and @group.

Parameters:

screen (VersionScreen | None) –

a VersionScreen for --version to draw in place of its one-line message. Reach it through the params hook, binding the screen with functools.partial so each decorated command still gets its own fresh option instances:

@group(params=partial(default_params, screen=MY_SCREEN))
def cli():
    pass

Return type:

list[Option]

Caution

The order of options has been carefully crafted to handle subtle edge-cases and avoid leaky states in unit tests.

You can still override this hard-coded order for aesthetic reasons and it should be fine. Your end-users are unlikely to be affected by these sneaky bugs, as the CLI context is going to be naturally reset after each invocation (which is not the case in unit tests).

  1. --time / --no-time

    Hint

    --time is placed at the top of all other eager options so all other options’ processing time can be measured.

  2. --config LOCATION

    Hint

    --config is at the top so it can have a direct influence on the default behavior and value of the other options.

  3. --no-config

  4. --validate-config LOCATION

  5. --export-config FORMAT

  6. --accessible

    Hint

    --accessible is placed before --color and --table-format so it can lower their defaults (via default_map) before they are resolved.

  7. --color / --no-color

  8. --progress / --no-progress

  9. --theme

  10. --params

  11. --table-format FORMAT

  12. --verbosity LEVEL

  13. -v, --verbose

  14. -q, --quiet

  15. --debug

  16. --tree

  17. --man

  18. --help-format FORMAT

  19. --version

  20. -h, --help

    Attention

    This is the option produced by the @click.decorators.help_option decorator.

    It is not explicitly referenced in the implementation of this function.

    That’s because it’s going to be added by Click itself, at the end of the list of options. By letting Click handle this, we ensure that the help option will take into account the help_option_names setting.

Note

The list above is the processing order, and it is the only one these edge-cases care about. The help screen reads a separate presentation order, which the option_priorities argument of @command and @group reshuffles without touching a single callback. See param_priority() and click_extra#544 issue.

Presentation also sorts these options into the sections DEFAULT_OPTION_GROUPS declares, drawn after the command’s own options. The two orders are independent: --time is processed first and rendered last.

click_extra.describe_error(expt)[source]¶

The class and message of an exception, on one line of capped length.

The class shows with its module, unless it is built in. The message keeps its first MAX_MESSAGE_LENGTH characters.

Return type:

str

click_extra.detect_source_package(directory=None)[source]¶

Locate the project’s source package from its script entry point.

Resolves the entry point with resolve_entry_point(), under its ambiguity rule, and derives the top-level package of its target ("pkg.cli:main" gives pkg), so the convert-to-myst command can run bare from a project root. The package is located under the project root or its src/ folder, see locate_package_root(), and assumed under the project root when it is in neither.

Parameters:

directory (Path | None) – The project root, holding its pyproject.toml or setup.cfg. Defaults to the current working directory.

Return type:

Path

Returns:

Path of the detected package directory.

Raises:

ValueError – When the project declares no script entry point, or scripts naming several targets.

click_extra.dir_path(*, path_type=<class 'pathlib.Path'>, exists=False, readable=True, writable=False, executable=False, resolve_path=False, allow_dash=False)[source]¶

Shortcut for click.Path with file_okay=False, path_type=pathlib.Path.

Return type:

Path

click_extra.echo(message=None, file=None, nl=True, err=False, color=None)[source]¶

Print a message and newline to stdout or a file. This should be used instead of print() because it provides better support for different data, files, and environments.

Compared to print(), this does the following:

  • Ensures that the output encoding is not misconfigured on Linux.

  • Supports Unicode in the Windows console.

  • Supports writing to binary outputs, and supports writing bytes to text outputs.

  • Removes ANSI color and style codes if the output does not look like an interactive terminal.

  • Always flushes the output.

Parameters:
  • message (object) – The string or bytes to output. Other objects are converted to strings.

  • file (IO[Any] | None) – The file to write to. Defaults to stdout.

  • err (bool) – Write to stderr instead of stdout.

  • nl (bool) – Print a newline after the message. Enabled by default.

  • color (bool | None) – Force showing or hiding colors and other styles. By default Click will remove color if the output does not look like an interactive terminal.

Return type:

None

Changed in version 8.5.0: Colorama is no longer used for color on Windows.

Changed in version 6.0: Support Unicode output on the Windows console. Click does not modify sys.stdout, so sys.stdout.write() and print() will still not support Unicode.

Changed in version 4.0: Added the color parameter.

Added in version 3.0: Added the err parameter.

Changed in version 2.0: Support colors on Windows if colorama is installed.

click_extra.echo_via_pager(text_or_generator, color=None)[source]¶

Drop-in for click.echo_via_pager() that streams plainly under –accessible.

A pager is a full-screen, cursor-driven TUI: it traps output behind its own keybindings, hostile to a screen reader consuming a linear stream. Under --accessible the text is written straight to stdout via click.echo() instead. Outside accessibility mode (or with no active context) it defers to click.echo_via_pager(), which already falls back to a plain write when stdout is not a terminal.

The argument is normalized exactly as click.echo_via_pager() does (a generator function is called, a string is emitted as-is, anything else is iterated), so the two behave identically on their inputs.

Return type:

None

click_extra.edit(text=None, editor=None, env=None, require_save=True, extension='.txt', filename=None)[source]¶

Edits the given text in the defined editor. If an editor is given (should be the full path to the executable but the regular operating system search path is used for finding the executable) it overrides the detected editor. Optionally, some environment variables can be used. If the editor is closed without changes, None is returned. In case a file is edited directly the return value is always None and require_save and extension are ignored.

Overloads:

If the editor cannot be opened a UsageError is raised.

Note for Windows: to simplify cross-platform usage, the newlines are automatically converted from POSIX to Windows and vice versa. As such, the message here will have \n as newline markers.

Warning

The contract of this utility is that the editor command blocks until the editing session is over: Click waits for it to exit before reading the file back and cleaning it up. Editors whose command launches the real editor in the background and exits immediately break that contract. Click then returns before editing begins and removes the temporary file while the editor still has it open. See The edit utility fails to open Visual Studio Code to make such editors wait.

Parameters:
  • text (str | bytes | bytearray | None) – the text to edit.

  • editor (str | None) – optionally the editor to use. Defaults to automatic detection.

  • env (Mapping[str, str] | None) – environment variables to forward to the editor.

  • require_save (bool) – if this is true, then not saving in the editor will make the return value become None.

  • extension (str) – the extension to tell the editor about. This defaults to .txt but changing this might change syntax highlighting.

  • filename (str | PathLike[str] | Iterable[str | PathLike[str]] | None) – if provided it will edit this file instead of the provided text contents. It will not use a temporary file as an indirection in that case. It accepts a path or any iterable of paths. If the editor supports editing multiple files at once, a sequence of files may be passed as well. Invoke click.file once per file instead if multiple files cannot be managed at once or editing the files serially is desired.

Changed in version 8.2.0: filename now accepts any Iterable[str] in addition to a str if the editor supports editing multiple files at once.

Changed in version 8.5.0: filename accepts os.PathLike values in addition to strings.

click_extra.env_copy(extend=None)[source]¶

Returns a copy of the current environment variables, updated with extend.

Mimics Python’s original implementation by returning None when extend is empty or missing, so a child process inherits the environment unchanged.

A None value removes its variable from the copy instead of setting it, which is the only way to hide an inherited variable from a child process: assigning the empty string leaves it set, and a flag read by bare presence (see parse_envvar_flag()) counts that as activation. Same convention as click.testing.CliRunner.invoke()’s own env argument, and the reason TEnvVars values are typed optional.

Return type:

dict[str, str] | None

click_extra.env_summary()[source]¶

One-line interpreter and platform summary.

Reads Python 3.14.7, macOS ARM64 (AArch64) on an Apple Silicon Mac: the same two facts default_facts() puts on the version screen, joined for a CLI that would rather spend one line of its plain --version on them than draw a screen at all: @version_option(message="{prog_name} {version} (" + env_summary() + ")").

Return type:

str

click_extra.export_config_option(param_decls=None, *, type=None, metavar='FORMAT', is_eager=True, expose_value=False, help='Export the configuration in the selected format to <stdout>, then exit.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.field_docstrings(cls)[source]¶

Extract attribute docstrings from a class body, keyed by field name.

Attribute docstrings are string literals immediately following an annotated assignment in a class body (the PEP 257 convention used by Sphinx’s autodoc). Python discards them at runtime, so they are recovered by parsing the class source with ast. Each docstring is cleaned up with inspect.cleandoc(), preserving paragraph breaks.

Caution

Returns an empty mapping when the class source is unavailable, as for classes defined in an exec-ed code block (an interactive session, or the body of a click:source Sphinx directive). Import the schema from a real module to get its docstrings documented.

Return type:

dict[str, str]

click_extra.file_path(*, path_type=<class 'pathlib.Path'>, exists=False, readable=True, writable=False, executable=False, resolve_path=False, allow_dash=False)[source]¶

Shortcut for click.Path with dir_okay=False, path_type=pathlib.Path.

Return type:

Path

click_extra.flatten_config_keys(conf, sep='_', opaque_keys=frozenset({}), _prefix='')[source]¶

Flatten nested dicts into a single level by joining keys with a separator.

Useful for mapping nested configuration structures (like TOML sub-tables) to flat Python dataclass fields. After normalization with normalize_config_keys, the flattened keys match dataclass field names directly:

>>> from click_extra.config import (
...     flatten_config_keys,
...     normalize_config_keys,
... )
>>> raw = {"dependency-graph": {"all-groups": True, "output": "deps.mmd"}}
>>> flatten_config_keys(normalize_config_keys(raw))
{'dependency_graph_all_groups': True, 'dependency_graph_output': 'deps.mmd'}
Parameters:
  • conf (dict[str, Any]) – Nested dictionary to flatten.

  • sep (str) – Separator used to join parent and child keys. Defaults to "_" which produces valid Python identifiers when combined with normalize_config_keys.

  • opaque_keys (frozenset[str]) – Fully-qualified key names where flattening stops. When the accumulated key matches an entry in this set, the dict value is kept as-is instead of being recursively flattened. This is useful for fields typed as dict[str, X] where the dict keys are data (like GitHub Actions matrix axis names), not config structure.

  • _prefix (str) – Internal parameter for tracking the accumulated key path during recursion. Callers should not set this.

Return type:

dict[str, Any]

click_extra.force_unicode_output()[source]¶

Switch sys.stdout and sys.stderr to UTF-8 when they do not speak it.

Windows gives a redirected stream the encoding of its legacy code page, cp1252 on a Western install, which has no āœ“, no ✘ and none of the box-drawing characters of a table border. A command printing one of them dies on a UnicodeEncodeError the moment its output is piped or redirected, which is how automation runs a CLI. A narrow PYTHONIOENCODING, like ascii, leads a POSIX host to the same crash.

A stream already speaking UTF-8 is left alone. A stream refusing the new encoding is asked for backslashreplace errors instead: an escaped character in the output is ugly, but it loses nothing and does not crash. A stream with no reconfigure(), like an io.StringIO capture, is skipped.

main() calls it as each run starts.

Todo

Remove once the minimum supported Python is 3.15: its UTF-8 mode, on by default (PEP 686), makes the standard streams speak UTF-8 unless the environment asks otherwise.

Return type:

None

click_extra.forced_color()[source]¶

Force ANSI color while Click Extra captures CLI text for documentation.

Click Extra renders CLI help and output into docs from both the MkDocs plugin (click_extra.mkdocs) and the Sphinx directives (click_extra.sphinx.click). During a build that output is a pipe, not a TTY, so the underlying renderers strip their escape codes. Two independent color systems have to be defeated:

  • Click’s, gated by should_strip_ansi / ctx.color (what click.echo and the Click and Click Extra help formatters consult). Sphinx’s runner additionally flips this one with click.testing.CliRunner(color=True).

  • Rich’s, gated by rich.console.Console.is_terminal, which ignores the above and reads FORCE_COLOR (https://force-color.org). This is the system rich-click uses, and color=True never reaches it.

FORCE_COLOR is the only signal common to both systems (Rich reads it directly; Click Extra recognizes it through COLOR_ENVVARS), so this sets it. It also clears the color-disabling variables Click Extra recognizes (NO_COLOR, LLM, …) so an opt-out in the build environment cannot suppress the rendering, and pins COLORTERM=truecolor so the branded 24-bit themes render at full depth instead of being quantized to the 256-color palette (see supports_truecolor()). The previous environment is restored on exit, so the override never leaks beyond a single capture.

Return type:

Generator[None, None, None]

click_extra.format_cli_prompt(cmd_args, extra_env=None, theme=None, prompt=None)[source]¶

Render the shell prompt simulating a CLI invocation, for logs and dry-runs.

Prefixes PROMPT to any extra_env assignments and the command line. Each token family is styled with the theme slot (get_current_theme()) it holds elsewhere in a CLI’s output, so the line reads like the help screens do:

  • the prompt sigil with bracket, the structural-token style;

  • each environment assignment as envvar name, plain =, default value;

  • each variable to unset as an option -u and its envvar name, after a plain env;

  • the program’s binary name with invoked_command, its directory plain (see highlight_bin_name());

  • the -/-- flags with option; other arguments stay plain.

Useful to print a copy-pasteable command trace in debug logs, dry-runs and test output. Each argument and environment value is quoted for the shell, so one carrying a space or a metacharacter reads back as the single token it was: a -c script keeps the quotes that made it one argument, instead of spilling into the line as several. Quote nothing before calling this, or the quotes are themselves quoted. Styling reads the raw argument, since a quoted --name=John Doe no longer opens on a dash.

A variable mapped to None is one env_copy() removes from the child’s environment, and no assignment can say that: the line then opens on env -u NAME, ahead of the assignments, as $ env -u LANGUAGE LC_ALL=C forecast.

Note

The program is left as it stands. Quoting has to wrap the whole token, which would put the closing quote inside the name highlight_bin_name() styles, and a Windows path is quoted whole for its separators alone: C:\Tools\mas.exe needs none of it to paste back.

Parameters:
  • cmd_args (Iterable[str]) – the command line to render.

  • extra_env (Mapping[str, str | None] | None) – environment assignments to prefix it with, a None value unsetting its variable.

  • theme (HelpTheme | None) – palette to style the line with. Defaults to the theme the current invocation runs under, which is what a CLI printing its own trace wants. A caller drawing the line onto a surface of its own choosing (a light capture, say) passes the one that surface can show.

  • prompt (str | None) – sigil to draw before the command, when the shell being pictured is not the one running. A capture mimicking a Windows terminal passes PS C:\>; None keeps PROMPT, which is this platform’s.

Return type:

str

Returns:

the styled prompt line.

click_extra.format_duration(duration)[source]¶

Render an elapsed duration compactly: 2.3s, 1:05, then 1:02:03.

Below a minute the duration reads as one-decimal seconds (2.3s). From a minute up it switches to a clock layout, growing an hours field only once it reaches an hour: 1:05 under an hour, 1:02:03 at or above.

The reverse direction, parsing a human-written duration back into a timedelta, lives in click_extra.types (see Duration).

Parameters:

duration (float | timedelta) – The elapsed time, as a number of seconds or a timedelta.

Return type:

str

Returns:

The compact rendering described above.

click_extra.format_filename(filename, shorten=False)[source]¶

Format a filename as a string for display. Ensures the filename can be displayed by replacing any invalid bytes or surrogate escapes in the name with the replacement character ļæ½.

Invalid bytes or surrogate escapes will raise an error when written to a stream with errors="strict". This will typically happen with stdout when the locale is something like en_GB.UTF-8.

Many scenarios are safe to write surrogates though, due to PEP 538 and PEP 540, including:

  • Writing to stderr, which uses errors="backslashreplace".

  • The system has LANG=C.UTF-8, C, or POSIX. Python opens stdout and stderr with errors="surrogateescape".

  • None of LANG/LC_* are set. Python assumes LANG=C.UTF-8.

  • Python is started in UTF-8 mode with PYTHONUTF8=1 or -X utf8. Python opens stdout and stderr with errors="surrogateescape".

Parameters:
  • filename (str | bytes | PathLike[str] | PathLike[bytes]) – formats a filename for UI display. This will also convert the filename into unicode without failing.

  • shorten (bool) – this optionally shortens the filename to strip of the path that leads up to it.

Return type:

str

click_extra.format_from_mime(mime_type, formats=None)[source]¶

Return the configuration format a media type designates.

The counterpart of format_from_path() for a configuration fetched over HTTP, whose URL often carries no usable file extension: the Content-Type header is then the only thing typing the payload. The media type is matched against each format’s mime_types, so application/toml resolves to TOML and text/yaml to YAML. formats restricts and orders the candidates (the first match wins); it defaults to every ConfigFormat.

Parameters are stripped, so a raw application/yaml; charset=utf-8 header value can be passed as-is, and matching is case-insensitive.

Note

A RFC 6839 structured syntax suffix is honored, so the application/vnd.acme.settings+json a private API answers with resolves to JSON. An exact match wins over a suffix.

Returns None for a media type no format claims, which covers the generic text/plain and application/octet-stream a server falls back to for an extension it does not recognize.

Return type:

ConfigFormat | None

click_extra.format_from_path(path, formats=None)[source]¶

Return the configuration format whose patterns match a file name.

The name is matched against each format’s patterns, so app.toml resolves to TOML and app.yml to YAML. formats restricts and orders the candidates (the first match wins); it defaults to every ConfigFormat.

Return type:

ConfigFormat | None

click_extra.format_manpage(roff, width=None)[source]¶

Typeset roff into readable terminal text, or None if nothing can.

Tries each terminal typesetter of MAN_TYPESETTERS in turn and returns the output of the first that succeeds. Returns None when none of them is installed, which the caller is expected to degrade on rather than fail: a CLI that cannot find a typesetter is a CLI running somewhere that never had man pages to begin with (Windows, a slim container), and that is no reason for --man to error.

Parameters:
  • roff (str) – the man page source, as CommandDoc.to_roff() renders it.

  • width (int | None) – line length in columns. Defaults to the terminal’s own, so the result matches what man would have produced in the same window.

Return type:

str | None

click_extra.format_size(size, *, units='iec', precision=1)[source]¶

Render a byte count as a compact, human-readable string.

Parameters:
  • size (float) – The number of bytes. A negative value keeps a leading -.

  • units (Literal['iec', 'si', 'jedec']) – The unit system to render in: iec (the default) for binary powers with the unambiguous KiB/MiB symbols, si for decimal powers with kB/MB, or jedec for binary powers with the customary but imprecise KB/MB.

  • precision (int) – Number of fractional digits for every unit above bytes. A byte count is always rendered as a whole number.

Return type:

str

Returns:

The size followed by a space and its unit, like 1.5 KiB. The integer part is grouped with thousands separators.

Raises:

ValueError – If units is not a known unit system.

click_extra.get_app_dir(app_name, roaming=True, force_posix=False)[source]¶

Returns the config folder for the application. The default behavior is to return whatever is most appropriate for the operating system.

To give you an idea, for an app called "Foo Bar", something like the following folders could be returned:

Mac OS X:

~/Library/Application Support/Foo Bar

Mac OS X (POSIX):

~/.foo-bar

Unix:

~/.config/foo-bar

Unix (POSIX):

~/.foo-bar

Windows (roaming):

C:\Users\<user>\AppData\Roaming\Foo Bar

Windows (not roaming):

C:\Users\<user>\AppData\Local\Foo Bar

Added in version 2.0.

Parameters:
  • app_name (str) – the application name. This should be properly capitalized and can contain whitespace.

  • roaming (bool) – controls if the folder should be roaming or not on Windows. Has no effect otherwise.

  • force_posix (bool) – if this is set to True then on any POSIX system the folder will be stored in the home folder with a leading dot instead of the XDG config home or darwin’s application support folder.

Return type:

str

click_extra.get_cache_dir(app_name)[source]¶

The user cache directory of app_name, resolved at call time.

The cache counterpart of click.get_app_dir(), which locates the configuration directory:

  • Windows: %LOCALAPPDATA%\<app_name>\Cache.

  • macOS: $XDG_CACHE_HOME/<app_name>, else ~/Library/Caches/<app_name>.

  • Linux and other POSIX systems: $XDG_CACHE_HOME/<app_name>, else ~/.cache/<app_name>.

A user who sets XDG_CACHE_HOME asks every tool to keep its cache there, macOS included. Unlike xdg_dir(), a relative value is ignored, as the XDG specification says: a cache must not move with the working directory.

Return type:

Path

click_extra.get_current_context(silent=False)[source]¶

Equivalent to click.get_current_context() but casts the returned click.Context object to cloup.Context (which is safe when using cloup commands classes and decorators).

Overloads:
click_extra.get_current_theme()[source]¶

Return the theme active for the current CLI invocation.

Resolution order:

  1. The theme stored on the active Click context under click_extra.context.THEME (set by ThemeOption from --theme).

  2. The process-wide fallback returned by get_default_theme() (the dark default, or whatever patch_click() set at process start).

Falling back through the active context (instead of reading a module attribute) keeps --theme scoped to the invocation that received it, so a second invocation in the same process starts from the default again.

Return type:

HelpTheme

click_extra.get_default_theme()[source]¶

Return the process-wide fallback theme.

Read by get_current_theme() when no Click context is active or when the active context has no theme set. The default is the built-in dark palette; patch_click() overrides it via set_default_theme() for the duration of a patched session.

Resolved through a function rather than a module attribute so callers always observe the current value: a module attribute bound once, like a default parameter value, keeps whatever was set at import time.

Return type:

HelpTheme

click_extra.get_pager_file(color=None)[source]¶

Context manager.

Yields a writable file-like object which can be used as an output pager.

Added in version 8.4.0.

Parameters:

color (bool | None) – controls if the pager supports ANSI colors or not. The default is autodetection.

Return type:

ContextManager[TextIO]

click_extra.get_param_spec(param, ctx)[source]¶

Extract the option-spec string (like -v, --verbose) from a parameter.

A hidden option has one too: click.Option.get_help_spec() ignores hidden. An argument has no spec, so it gets None.

Return type:

str | None

click_extra.get_tool_config(ctx=None)[source]¶

Retrieve the typed tool configuration from the context.

Returns the object stored under click_extra.context.TOOL_CONFIG by ConfigOption when a config_schema is set, or None if no schema was configured or no configuration was loaded.

Parameters:

ctx (Context | None) – Click context. Defaults to the current context.

Return type:

Any

click_extra.getchar(echo=False)[source]¶

Fetches a single character from the terminal and returns it. This will always return a unicode character and under certain rare circumstances this might return more than one character. The situations which more than one character is returned is when for whatever reason multiple characters end up in the terminal buffer or standard input was not actually a terminal.

Note that this will always read from the terminal, even if something is piped into the standard input.

Note for Windows: in rare cases when typing non-ASCII characters, this function might wait for a second character and then return both at once. This is because certain Unicode characters look like special-key markers.

Added in version 2.0.

Parameters:

echo (bool) – if set to True, the character read will also show up on the terminal. The default is to not show it.

Return type:

str

click_extra.group(*args, **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.help_format_option(param_decls=None, *, expose_value=False, is_eager=True, help='Render the command in the given format and exit.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.help_option(*args, **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.highlight_bin_name(program, theme=None)[source]¶

Style the binary’s own name inside program, leaving its directory plain.

/opt/homebrew/bin/mas renders with only mas in the active theme’s invoked_command style, so the part of the path the eye scans for stands out from the noise of its location. A bare name (no separator) is styled whole. Both POSIX and Windows separators are recognized, whichever comes last.

Parameters:
  • program (str) – the command, path and all.

  • theme (HelpTheme | None) – palette to style with. Defaults to the theme the current invocation runs under, see format_cli_prompt().

Return type:

str

Returns:

the styled command.

click_extra.install_interrupt_handler(ctx)[source]¶

Make the first Ctrl+C terminate in-flight subprocesses, then abort as usual.

Installs a SIGINT handler for the duration of the CLI run that calls terminate_live_processes() before re-raising KeyboardInterrupt (exactly what Python’s default handler raises). The abort then proceeds normally, and a concurrent fan-out does not hang on surviving children. The previous handler is restored when ctx closes.

Must run in the main thread: signal.signal() refuses to install a handler from any other, so a non-main-thread caller (embedded use, some tests) is a no-op that keeps the default Ctrl+C behavior.

A Click Extra command already asks the children to stop as the run aborts, once its context has closed. This handler does it at the moment of the Ctrl+C, which matters when a close callback waits on one of them, and serves a plain Click command, which has no such abort path.

Return type:

None

click_extra.install_manpages(command, prog_name=None, **overrides)[source]¶

Write the command tree’s man pages where man can find them.

Targets $XDG_DATA_HOME/man/man1 when that variable is set, else ~/.local/share/man/man1, expanded against the HOME in force at the call. Returns the written paths.

The environment is read here rather than at import time, through xdg_dir(), so a caller that sets XDG_DATA_HOME or HOME for one invocation (a test, a packaging script staging into a build root) is honored. This mirrors install_carapace_spec(), whose spec directory resolves the same way.

Return type:

list[Path]

click_extra.invocation_color()[source]¶

The invocation’s resolved color tri-state, reachable from any thread.

Prefers the pinned ctx.color of the calling thread’s own Click context, then the process-wide mirror published by the color callbacks (publish_invocation_color()). None means auto: defer to the output stream’s TTY status, exactly like ctx.color’s own default.

This is what makes --no-color reach output produced outside the main thread, like the subprocess lines click_extra.execution.run_cli() streams through click_extra.logging.StreamHandler.

Return type:

bool | None

click_extra.is_a_tty(stream)[source]¶

Whether stream reports itself as an interactive terminal.

Probes isatty defensively through getattr(): not every stream object exposes the method (a bare buffer, an in-memory capture, a test double), and a plain stream.isatty() would raise there instead of answering ā€œnot a terminalā€.

Return type:

bool

click_extra.is_dumb_terminal()[source]¶

Whether TERM names a terminal in COLOR_DISABLING_TERMS.

Such a terminal renders neither color nor the cursor movements of an animation. Case does not matter, and an unset TERM is no dumb terminal.

Return type:

bool

click_extra.is_stdout(path)[source]¶

Return True when path is the stdout sentinel -.

Guards against accidentally creating a file literally named - in the current directory.

Return type:

bool

click_extra.jobs_option(param_decls=None, *, default='auto', expose_value=False, show_default=True, type=<click_extra.jobs.JobCount object>, help="Number of parallel jobs. Accepts an integer, auto (the host's logical CPUs, minus one when there are three or more) or max (all logical CPUs). --jobs 0 runs sequentially.", **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.last_param(params, klass)[source]¶

Return the last parameter of exactly klass in params, or None.

Unlike search_params(), this matches the exact klass (no subclasses) and tolerates duplicates: when an option is declared more than once (like an explicit @verbosity_option stacked on a Click Extra command that already ships one), Click keeps the last occurrence, so this mirrors that here instead of erroring out on the ambiguity.

Parameters:
  • params (Iterable[Parameter]) – the command’s parameter list to scan.

  • klass (type[P]) – the exact parameter class to look for.

Return type:

P | None

click_extra.launch(url, wait=False, locate=False)[source]¶

This function launches the given URL (or filename) in the default viewer application for this file type. If this is an executable, it might launch the executable in a new session. The return value is the exit code of the launched application. Usually, 0 indicates success.

Examples:

click.launch('https://click.palletsprojects.com/')
click.launch('/my/downloaded/file', locate=True)

Added in version 2.0.

Parameters:
  • url (str) – URL or filename of the thing to launch.

  • wait (bool) – Wait for the program to exit before returning. This only works if the launched program blocks. In particular, xdg-open on Linux does not block.

  • locate (bool) – if this is set to True then instead of launching the application associated with the URL it will attempt to launch a file manager with the file located. This might have weird effects if the URL does not point to the filesystem.

Return type:

int

click_extra.lazy_group(*args, **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.load_test_suite(path)[source]¶

Read a test suite file and parse it by the format of its extension.

The format is resolved from path’s name over the list-capable SUITE_FORMATS (so suite.toml parses as TOML, suite.yaml as YAML). Reading and format detection are delegated to click_extra.config.formats.read_file().

Raises:
  • ValueError – the file extension matches no suite format.

  • ImportError – the matched format’s optional parser is not installed.

Return type:

Generator[CLITestCase, None, None]

click_extra.log_report(level, headline, title, details, ctx=None)[source]¶

Log the report that render_report() builds, and save it with save_report().

The report goes to the root logger, which the CLI prints. The path of the saved file comes last, alone on its line, so it is the last thing a user sees of the run, and easy to copy. It stays out of the file.

ctx defaults to the context of the running command.

Return type:

None

click_extra.machine_envvars_apply(ctx, param)[source]¶

Whether the machine-wide environment variables may set the value of param.

A machine-wide variable speaks for every CLI on the machine, like ACCESSIBLE, CLICK_EXTRA_THEME or NO_COLOR. It fills in only where nothing more specific set the value: the command line, the variable of the option itself and a configuration file each outrank it. So it applies only while param holds its built-in default.

Call it from the callback of param, once Click recorded where the value came from.

Return type:

bool

click_extra.make_pass_decorator(object_type, ensure=False)[source]¶

Given an object type this creates a decorator that will work similar to pass_obj() but instead of passing the object of the current context, it will find the innermost context of type object_type().

This generates a decorator that works roughly like this:

from functools import update_wrapper

def decorator(f):
    @pass_context
    def new_func(ctx, *args, **kwargs):
        obj = ctx.find_object(object_type)
        return ctx.invoke(f, obj, *args, **kwargs)
    return update_wrapper(new_func, f)
return decorator
Parameters:
  • object_type (type[T]) – the type of the object to pass.

  • ensure (bool) – if set to True, a new object will be created and remembered on the context if it’s not there yet.

Return type:

Callable[[Callable[Concatenate[T, P], R]], Callable[P, R]]

click_extra.make_schema_callable(schema, *, strict=False, normalize=True, warn_unknown=False)[source]¶

Wrap a schema type into a callable that accepts a raw config dict.

  • Dataclass types (detected via dataclasses.is_dataclass) are auto-wrapped: keys are normalized (hyphens to underscores), nested dicts are flattened, and the result is filtered to known fields before instantiation. Three schema-aware features refine this process:

    1. Type-aware flattening. Fields typed as dict[str, X] are treated as opaque: flatten_config_keys stops at their boundary so the dict value is kept intact.

    2. Field metadata. Dataclass fields may carry click_extra.config_path (a dotted TOML path like "test-matrix.replace") and click_extra.normalize_keys (False to skip key normalization on the extracted value). Fields with an explicit path are extracted from the raw config before normalization and flattening.

    3. Nested dataclass support. Fields whose resolved type is itself a dataclass are recursively processed with the same logic.

  • Any other callable is returned as-is. The caller is responsible for key normalization if needed.

  • None returns None.

Parameters:
  • strict (bool) – If True, raise ValueError when the config contains keys that do not match any dataclass field (after normalization and flattening).

  • warn_unknown (bool) – If True (and strict is False), log a warning naming those same unknown keys instead of silently dropping them. Meant for configs whose section is schema-only (no CLI parameter is merged from it, i.e. included_params=()), where any unrecognized key can only be a typo. Applies recursively to nested dataclasses.

  • normalize (bool) – If False, skip normalize_config_keys on the remaining config dict. Used internally when recursing into nested dataclasses whose parent opted out of normalization via click_extra.normalize_keys = False.

Return type:

Callable[[dict[str, Any]], Any] | None

click_extra.man_option(param_decls=None, *, is_flag=True, expose_value=False, is_eager=True, help="Read the command's manual page and exit.", **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.multicall_group(*args, **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.new_logger(name='root', *, propagate=False, force=True, **kwargs)[source]¶

Setup a logger in the style of Click Extra.

By default, this helper will:

  • Fetch the logger registered under the name parameter, or creates a new one with that name if it doesn’t exist,

  • Set the logger’s propagate attribute to False,

  • Force removal of any existing handlers and formatters attached to the logger,

  • Attach a new StreamHandler with Formatter,

  • Return the logger object.

This function is a wrapper around basicConfig() and takes the same keywords arguments.

Warning

The removal reaches every handler of the logger, not only the ones Click Extra attached. Left on its default name, this function sets up the root logger, which the whole process shares: the handlers an application or a test runner attached to it are removed and closed.

Call it from the entry point of a program instead of at import time, or name a logger of your own. With force=False the handlers stay, and the function sets nothing up on a logger that already has one.

Note

The options of Click Extra do not call this function for the root logger. They attach their handler beside the others, for the time of a run. See add_to_parser().

Parameters:
  • name (str) – ID of the logger to setup. Defaults to the name of Python’s root logger. If a logger with the provided name is not found in the global registry, a new logger with that name will be created.

  • propagate (bool) – Sets the logger’s propagate attribute. Defaults to False.

  • force (bool) – Same as the force parameter from logging.basicConfig() and basicConfig(). Defaults to True.

  • kwargs – Any other keyword parameters supported by logging.basicConfig() and basicConfig().

Return type:

Logger

click_extra.no_color_option(param_decls=None, *, is_flag=True, default=False, is_eager=True, expose_value=False, help='Disable colorization (alias of --color=never).', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.no_config_option(param_decls=None, *, help='Ignore all configuration files and only use command line parameters and environment variables.', is_flag=True, flag_value=Sentinel.NO_CONFIG, is_eager=True, expose_value=False, **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.normalize_config_keys(conf, opaque_keys=frozenset({}), _prefix='')[source]¶

Normalize configuration keys to valid Python identifiers.

Recursively replaces hyphens with underscores in all dict keys, using the same str.replace("-", "_") transform that Click applies internally when deriving parameter names from option declarations (--foo-bar becomes foo_bar).

Handles the convention mismatch between configuration formats (TOML, YAML, JSON all commonly use kebab-case) and Python identifiers. Works with all configuration formats supported by ConfigOption. A key that is not a string, like the number YAML reads 1: as, is kept as it is.

Parameters:
  • opaque_keys (frozenset[str]) – Fully-qualified key names (using "_" as separator) where recursion stops. The key itself is still normalized, but its dict value is kept as-is. Used in tandem with flatten_config_keys’s opaque_keys to protect data dicts (like GitHub Actions matrix axes) from normalization.

  • _prefix (str) – Internal parameter for tracking the accumulated key path during recursion. Callers should not set this.

Return type:

dict[str, Any]

Note

Click applies the same substitution in Option._parse_decls and Argument._parse_decls, but exposes no public accessor for it, so the one-liner is written out here.

click_extra.open_ansi(text, opened='')[source]¶

Return the ANSI SGR escapes still in effect at the end of text.

Escapes accumulate in the order they were read. A full 0 reset (its parameter-less \x1b[m form included) empties the accumulator, so the result re-opens what text left dangling and nothing else. Escapes come back verbatim rather than folded into a Style, which keeps a code this module does not model.

Use it to splice a styled fragment into styled text: the fragment closes with a reset of its own, which would otherwise strip the surrounding styling from everything after it. See highlight().

Parameters:
  • text (str) – the string to read the escapes from.

  • opened (str) – escapes already in effect before text, as returned by an earlier call. Feeding a string one chunk at a time then costs one pass over it, where re-reading the whole prefix per chunk costs one per chunk. A chunk must not start or end in the middle of an escape: the two halves match nothing, and the escape is lost.

Return type:

str

click_extra.open_file(filename, mode='r', encoding=None, errors='strict', lazy=False, atomic=False)[source]¶

Open a file, with extra behavior to handle '-' to indicate a standard stream, lazy open on write, and atomic write. Similar to the behavior of the File param type.

If '-' is given to open stdout or stdin, the stream is wrapped so that using it in a context manager will not close it. This makes it possible to use the function without accidentally closing a standard stream:

with open_file(filename) as f:
    ...
Parameters:
  • filename (str | PathLike[str]) – The name or Path of the file to open, or '-' for stdin/stdout.

  • mode (str) – The mode in which to open the file.

  • encoding (str | None) – The encoding to decode or encode a file opened in text mode.

  • errors (str | None) – The error handling mode.

  • lazy (bool) – Wait to open the file until it is accessed. For read mode, the file is temporarily opened to raise access errors early, then closed until it is read again.

  • atomic (bool) – Write to a temporary file and replace the given file on close.

Return type:

IO[Any]

Added in version 3.0.

click_extra.option(*args, group=None, **attrs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.option_group(title, *args, **kwargs)[source]¶

Return a decorator that annotates a function with an option group.

Overloads:

The help argument is an optional description and can be provided either as keyword argument or as 2nd positional argument after the name of the group:

# help as keyword argument
@option_group(name, *options, help=None, ...)

# help as 2nd positional argument
@option_group(name, help, *options, ...)

Changed in version 0.9.0: in order to support the decorator cloup.constrained_params(), @option_group now allows each input decorators to add multiple options.

Parameters:
  • title (str) – title of the help section describing the option group.

  • help – an optional description shown below the name; can be provided as keyword argument or 2nd positional argument.

  • options – an arbitrary number of decorators like click.option, which attach one or multiple options to the decorated command function.

  • constraint – an optional instance of Constraint (see Constraints for more info); a description of the constraint will be shown between squared brackets aside the option group title (or below it if too long).

  • hidden – if True, the option group and all its options are hidden from the help page (all contained options will have their hidden attribute set to True).

click_extra.parse_content(fmt, content)[source]¶

Parse content with a single stateless format.

INI is excluded: it needs the CLI parameter structure for type coercion and is handled by load_ini_config(). ARGFILE is excluded for the same reason: it maps command-line tokens to the CLI’s parameters and is handled by load_argfile_config(). SQLITE is excluded too: it is a binary format, read from its file path by load_sqlite_config() instead of a text payload.

PLIST parses here from its XML variant, the only one expressible as a text payload. The binary variant is read from its file path by load_plist_config().

Note

Optional third-party parsers are imported at the point of use. Only enabled formats reach this function (disabled ones are filtered out of ConfigOption.file_format_patterns), so the import always resolves for the formats parsed here.

Return type:

Any

click_extra.parse_duration(value, *, now=None)[source]¶

Parse a friendly, ISO 8601 or RFC 3339 duration into a timedelta.

The soft, library-friendly counterpart of the Duration parameter type: it accepts the same three input shapes but returns None instead of raising when value matches none of them, so it suits classifying values read from files or other machine sources. Unlike Duration, it does not collapse a zero duration to None: parse_duration("0") is timedelta(0), letting callers tell a zero duration from an unparsable value. None is returned only for an empty value, a future timestamp, or a value matching no known form.

Parameters:
  • value (Any) – The duration to parse. An existing timedelta (or None) is returned unchanged.

  • now (datetime | None) – Reference instant for an RFC 3339 timestamp’s age; defaults to the current UTC time.

Return type:

timedelta | None

Returns:

The parsed timedelta (possibly zero), or None.

click_extra.parse_friendly_duration(value)[source]¶

Parse only a friendly duration (7 days, 12h, a bare number of days).

Returns the parsed timedelta (possibly zero, so "0 days" is timedelta(0)), or None for anything that is not a friendly duration: ISO 8601 forms, calendar units (months, years), and empty or unrecognized values. See parse_duration() for the format-detecting umbrella.

Return type:

timedelta | None

click_extra.parse_iso8601_duration(value)[source]¶

Parse only an ISO 8601 duration (P7D, PT12H, P1WT6H).

Returns the parsed timedelta (possibly zero, so "PT0S" is timedelta(0)), or None for anything that is not an ISO 8601 duration: friendly forms, calendar (year or month) components, and empty or unrecognized values. See parse_duration() for the format-detecting umbrella.

Return type:

timedelta | None

click_extra.parse_test_suite(suite_string, fmt=ConfigFormat.YAML)[source]¶

Parse a serialized test suite string into CLITestCase instances.

fmt selects the serialization format, one of SUITE_FORMATS; it defaults to YAML for string sources with no extension to key on, such as an environment variable. load_test_suite() is the file-based counterpart.

Raises:
  • ValueError – the suite is empty, fmt cannot express a suite, a mapping suite omits cases, or a case uses unknown directives.

  • TypeError – the suite is not a list, or a case is not a mapping.

  • ImportError – the format’s optional parser is not installed.

Return type:

Generator[CLITestCase, None, None]

click_extra.pass_context(func)[source]¶

Mark a callback as wanting the active Context as its first argument.

Click’s own click.pass_context() is typed for the base click.Context. A handler annotated with click-extra’s enhanced Context (to reach its extra helpers like ctx.print_table) therefore fails static type checking: function parameters are contravariant, so Callable[[Context], R] is not assignable where a Callable[[click.Context], R] is expected.

This drop-in is typed for the enhanced Context and still accepts handlers typed for the base click.Context (a wider first parameter is allowed), so both type-check. At runtime it forwards the active context unchanged, exactly like click.pass_context().

Return type:

Callable[P, R]

click_extra.pass_obj(f)[source]¶

Similar to pass_context(), but only pass the object on the context onwards (Context.obj). This is useful if that object represents the state of a nested system.

Return type:

Callable[P, R]

click_extra.password_option(*param_decls, **kwargs)[source]¶

Add a --password option which prompts for a password, hiding input and asking to enter the value again for confirmation.

Parameters:
  • param_decls (str) – One or more option names. Defaults to the single value "--password".

  • kwargs (Any) – Extra arguments are passed to option().

Return type:

Callable[[FC], FC]

click_extra.path(*, path_type=<class 'pathlib.Path'>, exists=False, file_okay=True, dir_okay=True, readable=True, writable=False, executable=False, resolve_path=False, allow_dash=False)[source]¶

Shortcut for click.Path with path_type=pathlib.Path.

Return type:

Path

click_extra.pause(info=None, err=False)[source]¶

This command stops execution and waits for the user to press any key to continue. This is similar to the Windows batch ā€œpauseā€ command. If the program is not run through a terminal, this command will instead do nothing.

Added in version 2.0.

Added in version 4.0: Added the err parameter.

Parameters:
  • info (str | None) – The message to print before pausing. Defaults to "Press any key to continue...".

  • err (bool) – if set to message goes to stderr instead of stdout, the same as with echo.

Return type:

None

click_extra.prep_path(path)[source]¶

Open path for writing as UTF-8 text, or return stdout for -.

Yields a UTF-8 stream for a path and for the stdout of the process itself, sidestepping the UnicodeEncodeError a non-ASCII payload triggers on Windows, where the console defaults to cp1252. For a real path, missing parent directories are created first, absorbing the mkdir -p a caller would otherwise need.

Note

A sys.stdout that something replaced is returned as-is: Click’s test runner, the Sphinx {click:run} directive that live-renders CLI output in the docs, a contextlib.redirect_stdout() block. The replacement is where the output must go, in the encoding its owner chose. Its descriptor can point somewhere else: under CliRunner(capture="fd"), Click sends descriptors 1 and 2 to the capture, but sys.stdout.fileno() returns a copy of the original stdout descriptor, so a stream opened on it writes past the capture. A stdout with no file descriptor is returned as-is too.

Parameters:

path (Path) – The destination path, or - for stdout.

Return type:

IO[str]

Returns:

A writable text stream. The caller closes it, unless it is sys.stdout. The stream opened on the stdout descriptor uses closefd=False, so closing it leaves the real stdout open.

click_extra.print_data(data, table_format, *, default=None, root_element='records', package='click-extra', **kwargs)[source]¶

Serialize arbitrary Python data and print it to the console.

Wraps serialize_data() with user-friendly error handling for missing optional dependencies.

Parameters:
  • data (Any) – Arbitrary data to serialize.

  • table_format (TableFormat) – Target serialization format.

  • default (Callable | None) – Fallback serializer for custom types. Defaults to str.

  • root_element (str) – Root element name for XML output.

  • package (str) – Package name for install instructions in error messages.

  • kwargs – Extra keyword arguments forwarded to the underlying serializer.

Raises:

MissingExtraError – the serializer of table_format is not installed.

Return type:

None

click_extra.print_table(table_data, headers=None, table_format=None, sort_key=None, max_column_widths=None, **kwargs)[source]¶

Render a table and print it to the console.

headers entries carrying a column ID (ColumnSpec instances) plug the table into the active --sort-by selection: when no explicit sort_key is given, rows sort by the selected columns this table carries, and keep their original order when it carries none. See column_sort_key() for the exact semantics.

ANSI codes carried by cell values and headers depend on the format:

  • Markup formats with native styling support (see STYLED_FORMATS) get them translated to the format’s own styling markup, unless color output is disabled (--no-color, NO_COLOR, …).

  • Other markup formats get them stripped from cell values before rendering, unless --color is explicitly forced on the command line.

  • Plain-text formats keep them raw, and defer to echo()’s sensitivity to the global colorization settings.

Parameters:
  • sort_key (Callable[[Sequence[str | None]], Any] | None) – Optional callable passed to sorted() as the key argument. When provided, rows are sorted before rendering.

  • max_column_widths (Sequence[int | Literal['auto'] | None] | int | Literal['auto'] | None) – Width limits, as one entry per column or a single value for all of them. Each entry is a character count, "auto" to absorb the width left on the terminal, or None for no limit. Defaults to the max_width declared by ColumnSpec headers. Silently dropped by formats outside WRAPPABLE_FORMATS.

Raises:

MissingExtraError – the renderer of table_format is not installed.

Return type:

None

click_extra.progress_option(param_decls=None, *, is_flag=True, default=True, is_eager=True, expose_value=False, help='Show progress indicators during long operations. Disabled for non-interactive output (pipes, dumb terminals, CI) and by --accessible.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.progressbar(iterable=None, length=None, label=None, hidden=None, show_eta=None, **kwargs)[source]¶

Drop-in for click.progressbar() honoring --progress and --time.

Click’s own progress bar is determinate, the counterpart to the indeterminate Spinner. This thin wrapper gates its visibility on the same PROGRESS flag the spinner uses, so a single --no-progress (or --accessible, which lowers the progress default) silences both, and gates its estimated-time display on --time.

Parameters:
  • hidden (bool | None) – tri-state. Left at its default None, the bar follows the resolved --progress flag: hidden when the user (or --accessible) turned progress off, shown otherwise. An explicit True or False forces the bar regardless, mirroring how an explicit color= argument overrides ctx.color on click.echo(). With no active context (the bar used outside a Click command) it defaults to shown.

  • show_eta (bool | None) – tri-state, like hidden. Left at its default None, the estimated-time-remaining display follows the --time / --no-time flag: shown under --time, hidden otherwise (its default, or outside a command). An explicit True or False forces it, keeping a bare bar’s timing in step with an OperationTrail’s timer. Click’s own default is True.

Return type:

ProgressBar[V]

Unlike click.progressbar(), the bar draws on sys.stderr unless file says otherwise, like Spinner and OperationTrail. That keeps stdout free for the data a command prints, and puts the bar on the stream log records go to. A record logged while the bar draws then prints on a line of its own above the bar, which draws again below it. The bar is also redrawn at most once every DEFAULT_INTERVAL, the cadence of a spinner’s frames, unless update_min_steps says otherwise. Its position still moves on every step.

Note

The --progress flag gates visibility and --time the ETA. Color is already handled upstream: Click renders the bar through click.echo(), whose color=None resolves against ctx.color, so --no-color / NO_COLOR strip the bar’s ANSI without any work from this wrapper.

click_extra.prompt(text, default=None, hide_input=False, confirmation_prompt=False, type=None, value_proc=None, prompt_suffix=': ', show_default=True, err=False, show_choices=True)[source]¶

Prompts a user for input. This is a convenience function that can be used to prompt a user for input later.

Overloads:

If the user aborts the input by sending an interrupt signal, this function will catch it and raise a Abort exception.

Parameters:
  • text (str) – the text to show for the prompt.

  • default (V | str | None) – the default value to use if no input happens. If this is not given it will prompt until it’s aborted.

  • hide_input (bool) – if this is set to true then the input value will be hidden.

  • confirmation_prompt (bool | str) – Prompt a second time to confirm the value. Can be set to a string instead of True to customize the message.

  • type (ParamType[V, str] | type[V] | None) – the type to use to check the value against.

  • value_proc (Callable[[str], V] | None) – if this parameter is provided it’s a function that is invoked instead of the type conversion to convert a value.

  • prompt_suffix (str) – a suffix that should be added to the prompt.

  • show_default (bool | str) – shows or hides the default value in the prompt. If this value is a string, it shows that string in parentheses instead of the actual value.

  • err (bool) – if set to true the file defaults to stderr instead of stdout, the same as with echo.

  • show_choices (bool) – Show or hide choices if the passed type is a Choice. For example if type is a Choice of either day or week, show_choices is true and text is ā€œGroup byā€ then the prompt will be ā€œGroup by (day, week): ā€œ.

Changed in version 8.5.0: Generically typed: the return type is narrowed by type, value_proc, or default instead of being Any. Runtime behavior is unchanged.

Changed in version 8.3.3: show_default can be a string to show a custom value instead of the actual default, matching the help text behavior.

Changed in version 8.3.1: A space is no longer appended to the prompt.

Added in version 8.0: confirmation_prompt can be a custom string.

Added in version 7.0: Added the show_choices parameter.

Added in version 6.0: Added unicode support for cmd.exe on Windows.

Added in version 4.0: Added the err parameter.

click_extra.quiet_option(param_decls=None, **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.read_file(path, formats=None)[source]¶

Read a file and parse it, picking the format from its name.

The format is resolved with format_from_path() over formats (every ConfigFormat by default), then the content is parsed with parse_content().

Raises:
  • ValueError – the file name matches none of the candidate formats.

  • ImportError – the matched format’s parser is not available.

Return type:

Any

click_extra.read_manpage(command, ctx=None)[source]¶

Typeset a command’s manual and send it to the pager.

The reading counterpart of --help-format man, which emits the roff source a packager installs. Falls back to printing that source, with a warning naming what to install, when no typesetter is available: something on screen beats an error, and the source still carries every word of the manual.

Under --accessible the emphasis is stripped and the pager bypassed (echo_via_pager() streams instead). Both matter to the same reader: a pager is a cursor-driven takeover, and overstrike is worse than the ANSI codes accessible mode already removes, since a screen reader voices N\x08NA\x08AM\x08ME\x08E rather than skipping it.

Return type:

None

click_extra.record_command(args, *, columns=80, rows=24, background=TerminalBackground.DARK, duration=None, clock=<built-in function monotonic>)[source]¶

Run a command under a pseudo-terminal and record the screens it draws.

An animation is the one thing a pipe cannot capture. A spinner asks whether its stream is a terminal and stays silent when it is not, so a command run the ordinary way prints its result and none of the frames leading to it. Forcing color through the environment does not help: that answers a different question. Only a pseudo-terminal answers this one.

Caution

Unix only. A pseudo-terminal is termios and pty, neither of which Windows ships, and reaching ConPTY means a dependency. Recording a spinner this process hosts needs none of that: hand a ScreenRecorder to its stream and it animates on any platform.

The terminal this runs from is hidden from the command, see CAPTURE_HIDDEN_TERMINAL_VARS, so one machine’s recording matches another’s.

Both the command’s output and its errors are read, the spinner drawing on the latter. What comes back is timed by the wall clock and therefore differs a little between two runs: quantize the durations before committing them.

Parameters:
Return type:

tuple[Frame, ...]

Returns:

the frames the terminal held, in order.

Raises:
  • NotImplementedError – on a platform with no pseudo-terminal.

  • OSError – when the command cannot start. subprocess.Popen raises a FileNotFoundError for a program it cannot find, and a PermissionError for a file it cannot run.

click_extra.region_markers(name)[source]¶

The (open, close) marker lines of a <!-- name --> region.

The writing-side twin of marker_res(): <!-- name --> opens the region and <!-- name-end --> closes it, and every refresher writes both through here so they cannot drift from what that reader matches.

Return type:

tuple[str, str]

click_extra.register_theme(name, theme)[source]¶

Register a named theme in the module-level theme_registry.

Parameters:
  • name (str) – Lowercase identifier used as the --theme choice value.

  • theme (HelpTheme) – A HelpTheme instance.

Return type:

None

click_extra.render_ansi(text, emitter)[source]¶

Rebuild text, replacing each ANSI-styled run by emitter’s markup.

Unstyled runs pass through verbatim, so any markup surrounding the styled runs (table borders, tags produced by another renderer) is preserved byte for byte. Styled runs are handed to emitter one line at a time: runs are split on newlines so no markup wrapper ever crosses a line boundary, which keeps line-oriented markup (LaTeX rows, wiki tables) well-formed even when a style spans multiple lines.

Return type:

str

click_extra.render_columns_markdown_table(columns)[source]¶

Render an iterable of ColumnSpec as a 2-column Markdown table.

Output shape:

| Column | Description |
| :--- | :--- |
| ``Label`` | description |
...

Suitable for inlining into MyST documents via myst_substitutions so the Available columns reference can be auto-generated from a single source of truth.

Return type:

str

click_extra.render_command_tree(command, prog_name=None, ctx=None, width=None)[source]¶

Render the hierarchy rooted at command as a tree with descriptions.

Reuses ctx when given (like the live invocation context), otherwise builds a throwaway one with resilient_parsing=True. The root line is labeled with prog_name when given, else the context’s command path.

Each node carries the command name, its aliases, its operand metavars (mirroring the usage line) and a column-aligned description from full_short_help(), so deprecated commands carry Click’s own (DEPRECATED) label. Everything is styled with the same theme slots as help screens (invoked_command for the root, subcommand and alias for children, metavar for operands, deprecated for that label), so the tree follows --theme and --color. The rail switches from box-drawing to ASCII when accessibility mode is active on the context (see ACCESSIBLE).

Descriptions wrap at width, resolved like help screens when not given (ctx.make_formatter(), honoring the terminal_width and max_content_width context settings). Wrapped lines keep the tree rail running through the description column. A label wider than the column (typically a long script path as the root, under wrap --tree) keeps its line to itself and hangs its description underneath, at the column.

Note

The tree is a point-in-time snapshot: groups computing their subcommands from external state (plugins, scanned directories) render exactly what click.Group.list_commands() returns at that moment, in listing order. Cloup section groupings are not rendered.

Caution

A non-group command renders as a single root line: valid, just not very interesting. Like a man page, the output stays meaningful for every command type.

Return type:

str

click_extra.render_help(command, help_format, prog_name=None, ctx=None, **overrides)[source]¶

Render command in one of the HelpFormat formats.

Reuses ctx when given (like the live invocation context), otherwise builds a throwaway one with resilient_parsing=True, exactly like render_manpage(). Keyword overrides are passed through to extract_command_doc(), and ignored by the carapace format, which carries no version or authorship of its own.

Raises:

ValueError – on an unknown format, listing the known ones.

Return type:

str

click_extra.render_manpage(command, prog_name=None, ctx=None, **overrides)[source]¶

Render a single command’s man page as a roff string.

Reuses ctx when given (like the live invocation context), otherwise builds a throwaway one with resilient_parsing=True. Keyword overrides (version, date, manual, authors, copyright) are passed through to extract_command_doc().

Return type:

str

click_extra.render_manpages(command, prog_name=None, **overrides)[source]¶

Render the whole command tree, one man page per (sub)command.

Returns an ordered mapping of {filename: roff} where each filename is the command path joined by hyphens plus the section suffix (like weather-forecast.1).

Return type:

dict[str, str]

click_extra.render_table(table_data, headers=None, table_format=None, sort_key=None, max_column_widths=None, **kwargs)[source]¶

Render a table and return it as a string.

headers entries carrying a column ID (ColumnSpec instances) plug the table into the active --sort-by selection: when no explicit sort_key is given, rows sort by the selected columns this table carries, and keep their original order when it carries none. See column_sort_key() for the exact semantics.

Parameters:
  • sort_key (Callable[[Sequence[str | None]], Any] | None) – Optional callable passed to sorted() as the key argument. When provided, rows are sorted before rendering.

  • max_column_widths (Sequence[int | Literal['auto'] | None] | int | Literal['auto'] | None) – Width limits, as one entry per column or a single value for all of them. Each entry is a character count, "auto" to absorb the width left on the terminal, or None for no limit. Defaults to the max_width declared by ColumnSpec headers. Silently dropped by formats outside WRAPPABLE_FORMATS.

Return type:

str

click_extra.replace_region(text, name, content, *, pad=True)[source]¶

Return text with the body of a <!-- name --> region swapped for content.

Finds the <!-- name [args] --> opening and <!-- name-end --> closing markers (the grammar of marker_res()) and replaces everything between them with content. The markers themselves are preserved, so the region round-trips: a second call with the same content is a no-op. A marker quoted inside a code fence, like in a page documenting the grammar, is never taken for a live one.

When either marker is missing the text is returned unchanged, so the call is safe to fan out over every file of an update_blocks() rewrite even when only some carry the region. This is the generic counterpart to the fence-driven refreshers of click_extra.sphinx.matrix and the python:render :mirror: flag: use it when the content is produced outside the document (a registry dump, an external generator) rather than by an inline directive.

Parameters:

pad (bool) – With the default True, content is padded by one blank line on each side, the usual layout for a Markdown block. Set it to False to keep the blank line after the opening marker (Markdown needs it to start a fresh block) but drop the one before the closing marker, so the region ends flush against it. That flush layout is what mdformat-footnote requires: it strips an HTML comment sitting on its own line right after a footnote definition (executablebooks/mdformat-footnote#11), so a region wrapping footnotes must place its closing marker on the line immediately below the last body line. An empty content collapses to a single blank line between the markers whatever the padding.

Return type:

str

click_extra.require_sibling_param(params, requester, klass)[source]¶

Return the sibling klass parameter declared on the same command, or raise.

Some options are inert on their own: they drive machinery owned by a sibling option. --no-config and --validate-config, for instance, both depend on the --config option (ConfigOption). This helper centralizes the lookup so every such option raises the same RuntimeError when its required sibling is missing, naming the offending flag.

Parameters:
  • params (Iterable[Parameter]) – the command’s parameter list to scan.

  • requester (Parameter) – the parameter requiring the sibling, used to build the error message from its flag names and class.

  • klass (type[P]) – the sibling parameter class to look for.

Return type:

P

click_extra.resolve_color_env()[source]¶

Reconcile the recognized color environment variables into a tri-state.

Reads every variable listed in COLOR_ENVVARS by its own convention, and returns:

  • True if at least one variable asks for color. A variable asking for color wins over one refusing it, as in the reference code of FORCE_COLOR.

  • False if variables only refuse color.

  • None if no variable casts a vote, which leaves the caller free to apply its own default (typically auto).

An empty value never votes: both NO_COLOR and FORCE_COLOR treat it as unset. Each family then follows its convention:

  • NO_COLOR refuses color whatever its value, 0 and false included. It never asks for color.

  • FORCE_COLOR asks for color, except for 0, false, no and off, which refuse it, as Node.js tools read them.

  • CLICOLOR refuses color when falsy. Any other value only allows color on a terminal, which is the auto default: it casts no vote.

  • CLICOLOR_FORCE asks for color unless it is falsy, which casts no vote.

  • LLM refuses color unless it is falsy, which casts no vote: it marks an AI agent, not a color preference.

  • COLOR takes the words of --color (see WHEN and COLOR_WHEN_ALIASES) and booleans. Any other value casts no vote.

The plural and unspaced spellings in COLOR_ENVVARS follow the variable they spell.

A dumb or unknown TERM (see COLOR_DISABLING_TERMS) refuses color as well, so a terminal that cannot render ANSI is treated as color-off even when it reports as a TTY. A variable asking for color still wins over it.

Return type:

bool | None

click_extra.resolve_jobs(ctx, count, *, serial_at_debug=False)[source]¶

Resolve how many worker threads to use for a batch of count items.

Returns the number of items to process in parallel; 1 means run sequentially in the calling thread. This is the policy shared by run_jobs() and run_lanes(), exposed on its own for callers that must know the resolved count before they fan out (for example to pick a progress-rendering mode). It collapses to sequential when:

  • there is no active CLI context (programmatic or test use),

  • a single item leaves nothing to parallelize, or

  • the resolved JobsOption count (ctx.meta[click_extra.context.JOBS]) is 1 or less.

Otherwise that count wins, capped at count: there is no point spinning up more workers than there are items.

Parameters:
  • ctx (Context | None) – the active Click context, read for the resolved --jobs count (and, with serial_at_debug, the verbosity). None forces sequential.

  • count (int) – how many items are about to be scheduled.

  • serial_at_debug (bool) – when set, also collapse to sequential at DEBUG verbosity, where coherent per-worker log narration matters more than the speed-up (interleaved threads would scramble it). Off by default.

Return type:

int

click_extra.resolve_wrap_marker(marker)[source]¶

Read a wrap_marker option into the characters written at a fold.

The one reading of the option every entry point shares: the --wrap-marker of the capture commands, and the API those commands call.

Parameters:

marker (str) – the text, AUTO_WRAP_MARKER, or an empty string for no marker at all.

Return type:

str

Returns:

the characters to write at a fold, empty for none.

click_extra.run_cli(args, *, extra_env=None, cwd=None, timeout=None, label=None, merge_stderr=False, errors='replace', windows_creation_flags=0, start_new_session=False, command_level=20, output_level=10, log=None)[source]¶

Run a CLI in a subprocess, disclosing the call and streaming its output live.

A subprocess.run() work-alike for CLI-wrapping tools, with observability built in:

  • the invocation is logged before the spawn, as the copy-pasteable $ ENV=value command args line of format_cli_prompt(), so a user can reproduce by hand what the tool runs on their system;

  • each line of the child’s output is forwarded to the logger as it is produced (ANSI-stripped, tagged with label), instead of being held back until the child exits, so a long-running command narrates its progress live;

  • the child is registered in the live-process registry for the duration of the call, so terminate_live_processes() (wired to Ctrl+C by install_interrupt_handler()) can abort it.

Contract mirrored from subprocess.run():

  • returns a subprocess.CompletedProcess with the full captured stdout and stderr decoded as UTF-8;

  • raises subprocess.TimeoutExpired (with the partial capture attached) when the child, or the draining of its output, outlives timeout. The child is stopped first, and so is every descendant it left behind: on POSIX with SIGTERM, then SIGKILL once a grace period runs out (see _stop_timed_out_process()), sent to the process group and every group its descendants moved to when spawned with start_new_session, to the child plus each descendant PID otherwise. Windows ends the whole process tree at once (see _kill_windows_process_tree());

  • a KeyboardInterrupt mid-run kills the child (with the same tree, group or per-PID scope), then propagates.

The child reads from subprocess.DEVNULL so it can never block on stdin, and never opens a console window on Windows.

Note

The pipes are opened in universal-newlines text mode, so a bare \r (a child redrawing a progress bar in place) terminates a line just like \n: each redraw is streamed as its own log line, and the captured text normalizes both to \n, exactly as subprocess.Popen.communicate() does.

Parameters:
  • args (str | Path | None | Iterable[str | Path | None | Iterable[Iterable[str | Path | None | Iterable[TNestedArgs]]]]) – the command line. Nested iterables are flattened, None values dropped, and every element (Path, versions, …) cast to a string; see args_cleanup().

  • extra_env (Mapping[str, str | None] | None) – environment variables forced over the inherited environment for this call (see env_copy()). They are part of the disclosed prompt line, since reproducing the call requires them.

  • cwd (Path | str | None) – directory to run the child in. None inherits the caller’s, which is subprocess.run()’s own default. A relative args[0] is resolved by the OS against this directory, not the caller’s, so pass an absolute path (or a name on the PATH) when moving the child elsewhere.

  • timeout (float | None) – seconds before the child is asked to stop. None waits forever.

  • label (str | None) – tag identifying this call on each streamed output line, for when several children interleave in one log. Carried as the record’s label attribute, which click_extra.logging.Formatter renders glued to the level name and styled like an invoked command (debug:mas: Warning: ...); a foreign formatter can read record.label itself. Applied to the prompt line and to every output line, so an interleaved log attributes each command as well as what it printed.

  • merge_stderr (bool) – route the child’s stderr into stdout so the OS interleaves both in write order. The result’s stderr is then None, like a subprocess.run() call with stderr=STDOUT.

  • errors (str) – decoding error handler for the child’s output. The default "replace" swaps undecodable bytes for ļæ½; pass "backslashreplace" to keep them inspectable as escapes.

  • windows_creation_flags (int) – extra Windows process-creation flags, OR-ed with the always-on CREATE_NO_WINDOW. No-op off Windows.

  • start_new_session (bool) – make the child lead its own POSIX session and process group (subprocess.Popen’s parameter of the same name). Every kill path then signals the whole group in one call: the timeout overrun, a mid-run KeyboardInterrupt, and terminate_live_processes(). A grandchild spawned by the child (a shim re-executing the real binary, an installer helper) is reaped along with it instead of surviving as an orphan holding the output pipes open. A descendant that left the group with setsid(), like the make test run CPAN.pm forks, is signalled through its own group. Off by default, and to be left off when a descendant must keep the controlling terminal: a new session detaches from it, so an interactive prompt raised from inside the child (sudo reading /dev/tty) would fail, and sudo’s tty-keyed credential cache would no longer match. That costs the atomicity of a single group signal, not the reaping: the timeout and KeyboardInterrupt paths then kill the child and walk the tree it led, signalling each descendant by PID (see _kill_descendants()). terminate_live_processes() signals the direct child alone when it sends SIGTERM, for a clean exit, and walks the same tree when it sends SIGKILL. No-op on Windows, where each of these paths already kills the full tree. Only the reaping half of this flag has that Windows equivalent, and the other half has none: a POSIX session also detaches the child from the controlling terminal, where a Windows child keeps sharing the parent’s console and can still reach back into it: a console control event the child raises, as a package manager’s own teardown can, lands in the parent as a KeyboardInterrupt. The lever there is windows_creation_flags (CREATE_NEW_PROCESS_GROUP), left to the caller because it also changes how a real Ctrl-C reaches the child.

  • command_level (int) – logging level of the invocation-disclosure line. Defaults to logging.INFO; lower it to logging.DEBUG for internal probes not worth narrating.

  • output_level (int) – logging level of the streamed output lines. Defaults to logging.DEBUG.

  • log (Logger | None) – destination logger. Defaults to the root logger, whose level the VerbosityOption family manages.

Return type:

CompletedProcess[str]

click_extra.run_config_validation(user_conf, *, app_name, params_template, config_schema=None, config_validators=(), fallback_sections=(), schema_strict=False, schema_warn_unknown=False, strict=False, blocked_params=(), collect_all=True)[source]¶

Validate a parsed configuration document in one schema-driven pass.

Runs click-extra’s three checks (the CLI-parameter strict check, the dataclass schema, and the app-registered ConfigValidator hooks) behind a single function yielding a single error type. It is not named validate_config: that name belongs to validate_config(), the callback powering the --validate-config flag.

Stages, in order:

  1. Partition. Split opaque sub-trees (schema extension fields plus every registered validator’s extension_path) from the CLI-flag-bound content. Extracted sub-trees land in the report’s opaque_subtrees.

  2. Strict-check the CLI-flag-bound part against params_template, once its dotted keys are expanded, keeping the merged result as the report’s merged_conf (skipped when params_template is None). A key the dataclass schema reads is left to stage 3.

  3. Schema-build the app section through the configured callable, producing the report’s schema_instance.

  4. Validate every opaque sub-tree through its registered validator.

Parameters:
  • user_conf (dict[str, Any]) – The full parsed configuration document.

  • app_name (str) – Name of the app’s section (used to resolve the section and to root opaque paths and error paths at the document level).

  • params_template (dict[str, Any] | None) – The CLI-parameter template the strict check runs against. Pass None to skip the strict check entirely (for example, for a schema-only validation).

  • config_schema (type | Callable[[dict[str, Any]], Any] | None) – Dataclass type or callable describing the typed configuration, or None.

  • config_validators (Sequence[ConfigValidator]) – Extension validators to run against opaque sub-trees.

  • fallback_sections (Sequence[str]) – Legacy section names to try when app_name is absent or empty.

  • schema_strict (bool) – Reject keys the dataclass schema does not recognize.

  • schema_warn_unknown (bool) – In lax mode, log a warning naming keys the dataclass schema does not recognize (see warn_unknown in make_schema_callable()). Ignored when schema_strict rejects them outright.

  • strict (bool) – Reject keys that neither the CLI-parameter template nor the dataclass schema recognize, keys that are not strings, and dotted keys that conflict with another key or have an empty segment.

  • blocked_params (Iterable[str]) – Fully-qualified IDs of parameters excluded from configuration files, used to sharpen strict-mode error messages (a blocked parameter is reported as such, not as unknown).

  • collect_all (bool) – When True (default), run every stage and collect all errors. When False, the first error short-circuits the rest.

Return type:

ValidationReport

Returns:

A ValidationReport. ValidationError is the single error type recorded by every stage; a ValueError or TypeError raised by the schema callable is wrapped into it.

click_extra.run_jobs(func, items, *, jobs=None, serial_at_debug=False)[source]¶

Run func over items, parallelized per the resolved --jobs count.

The worker count is taken from jobs when given, else resolved from the active command’s JobsOption value by resolve_jobs(), else 1. With a single worker (or at most one item) the items run sequentially and lazily, so a caller can stop early on the first result (for example to abort on the first failure); otherwise they run in a thread pool. Either way results are yielded in submission order, like map().

This is the single-task-per-item special case of run_lanes(), which runs every item as a lane of its own. Reach for run_lanes() when some items must run serially relative to one another while others run concurrently.

The pool is thread-based, which suits the I/O- and subprocess-bound work CLI tools usually parallelize (each child releases the GIL). The count is a number of logical CPUs: see CPU_COUNT.

items is never materialized: only a bounded window of tasks is queued at a time, so an unbounded or expensive-to-produce stream stays memory-flat and is read no further than the caller consumes.

Parameters:
  • func (Callable[[T], R]) – Called once per item; its return value is yielded.

  • items (Iterable[T]) – The work items. Read lazily, a window at a time.

  • jobs (int | None) – Override the worker count instead of reading it from the context. 1 or fewer forces sequential execution.

  • serial_at_debug (bool) – forwarded to resolve_jobs() when jobs is not given: collapse to sequential at DEBUG verbosity.

Return type:

Generator[R, None, None]

Returns:

An iterator over func’s results, in the order of items.

click_extra.run_lanes(func, lanes, *, jobs=None, serial_at_debug=False)[source]¶

Run func over grouped items: serial within a lane, concurrent across.

Each lane is an iterable of items. func is mapped over every item, but a lane’s own items run serially and in order on a single worker, while distinct lanes run concurrently up to the resolved --jobs count. This is the right primitive when some work must be serialized relative to itself (a shared lock, a rate limit, one mailbox file, one package-manager backend) yet still overlap with unrelated work.

run_jobs() is the degenerate case where every lane holds a single item. Concurrency is sized by the number of lanes (one worker per lane), since a lane never splits across workers. A single lane runs in the calling thread, whatever the worker count.

Results are yielded in lane-submission order, a lane’s items in order, like map(). The run stays lazy at any worker count: a lane is materialized only when it is about to be scheduled, and only a bounded window of lanes is in flight, so a caller can break early and the lanes behind it are never read. A lane runs entirely on one worker, so a stateful resource bound to the lane (a per-lane cache, a connection) is touched by only that one thread and needs no lock.

Parameters:
  • func (Callable[[T], R]) – Called once per item; its return value is yielded.

  • lanes (Iterable[Iterable[T]]) – The lanes, each an iterable of items. Read lazily, a window of lanes at a time; a lane’s own items are materialized when it is scheduled.

  • jobs (int | None) – Override the worker count instead of reading it from the context. 1 or fewer forces fully sequential execution.

  • serial_at_debug (bool) – forwarded to resolve_jobs() when jobs is not given: collapse to sequential at DEBUG verbosity.

Return type:

Generator[R, None, None]

Returns:

An iterator over func’s results, lane by lane in submission order.

click_extra.run_test_suite(command, cases, *, jobs=1, select_test=None, skip_platform=None, timeout=None, work_directory=None, exit_on_error=False, show_trace_on_error=True, stats=True, show_progress=True)[source]¶

Run a list of test cases against a target command and tally the results.

Cases are parallelized per jobs (see click_extra.jobs.run_jobs()): at one worker they run sequentially and lazily, so exit_on_error can stop before the rest start; otherwise they run in a thread pool and every case runs to completion. Either way outcomes are tallied in submission order. On an interactive terminal a click_extra.spinner.Spinner reports progress unless show_progress is false.

Parameters:
  • command (Path | str) – The target to test: a command name, a command line, or a path to a binary or script.

  • cases (Sequence[CLITestCase]) – The test cases to run.

  • jobs (int) – Number of parallel workers; 1 runs sequentially.

  • select_test (Sequence[int] | None) – 1-based case numbers to run; others are skipped.

  • skip_platform (Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[_TNestedReferences]]]]) – Extra platforms (or group IDs) to skip every case on.

  • timeout (float | None) – Default per-case timeout in seconds when a case sets none.

  • work_directory (Path | str | None) – Directory every case runs its command in, defaulting to the runner’s own. It moves the target, never the runner: the suite file is read before any case starts, and command is resolved to an absolute path first, so neither is looked up relative to it.

  • exit_on_error (bool) – Stop at the first failure (sequential runs only).

  • show_trace_on_error (bool) – Echo the execution trace of each failed case.

  • stats (bool) – Echo a one-line worker summary up front and a result tally.

  • show_progress (bool) – Allow the progress spinner on an interactive terminal.

Return type:

Counter

Returns:

A collections.Counter with total, skipped, and failed keys. A non-zero failed count signals the caller to exit with an error.

click_extra.schema_field_infos(schema)[source]¶

Walk a configuration schema dataclass into per-option records.

Introspects the dataclass fields, their type annotations, defaults, and attribute docstrings. Nested dataclass fields expand recursively into dotted keys (test-suite.timeout), honoring click_extra.config.schema.CONFIG_PATH_METADATA_KEY at every level. Records are sorted by key, segment-wise, so a sub-table’s options stay contiguous even when another table’s name shares their prefix (workflow.sync sorts before workflow-pins.sync).

Defaults are read off a pristine schema() instance, so every field must carry a default: configuration schemas are default-complete by construction, since make_schema_callable() instantiates them from partial user data.

Raises:

TypeError – when schema is not a dataclass type.

Return type:

list[SchemaFieldInfo]

click_extra.search_params(params, klass, include_subclasses=True)[source]¶

Return the one parameter of class klass in params, or None.

The result is typed as klass itself, so a caller needs no isinstance check to use what it found.

Parameters:
  • params (Iterable[Parameter]) – list of parameter instances to search in.

  • klass (type[P]) – the class of the parameter to look for.

  • include_subclasses (bool) – if True (the default), a parameter subclassing klass matches too. If False, only a parameter of exactly klass does.

Raises:

RuntimeError – if more than one parameter matches.

Return type:

P | None

click_extra.secho(message=None, file=None, nl=True, err=False, color=None, **styles)[source]¶

This function combines echo() and style() into one call. As such the following two calls are the same:

click.secho('Hello World!', fg='green')
click.echo(click.style('Hello World!', fg='green'))

All keyword arguments are forwarded to the underlying functions depending on which one they go with.

Non-string types will be converted to str. However, bytes are passed directly to echo() without applying style. If you want to style bytes that represent text, call bytes.decode() first.

Changed in version 8.0: A non-string message is converted to a string. Bytes are passed through without style applied.

Added in version 2.0.

Return type:

None

click_extra.select_columns(columns, selected_ids)[source]¶

Filter and reorder columns according to selected_ids.

Returns columns unchanged when selected_ids is falsy (no projection). Otherwise yields the matching ColumnSpec in the order selected_ids specifies, SQL-SELECT-style. Raises KeyError for an unknown ID. A selection reaching here through --columns is already checked against the registry by MultiChoice, so that guards a caller assembling selected_ids on its own.

Return type:

tuple[ColumnSpec, ...]

click_extra.select_row(row, selected_ids, canonical_ids)[source]¶

Build a positional row by reading cells from row in the selection order.

Falls back to canonical_ids when selected_ids is empty / unset, so the row preserves its canonical column order in the absence of any user selection.

Return type:

tuple

click_extra.serialize_content(fmt, data, **kwargs)[source]¶

Serialize a Python object to a string in the given format.

The dumping counterpart to parse_content(). Per-format defaults can be overridden through kwargs (forwarded to the underlying serializer). JSON5 and JSONC are emitted as plain JSON, a valid subset of both.

Caution

Not every format round-trips: TOML, XML and PLIST have no null type (plistlib even raises on None values), and XML expects a single root mapping, so the caller is responsible for shaping data accordingly. INI, SQLITE, ARGFILE and PYPROJECT_TOML have no serializer.

Note

Optional third-party serializers are imported lazily, at the point of use. Writing TOML uses tomlrt (the [toml] extra), unlike reading which relies on the built-in tomllib.

Raises:

ValueError – the format has no serializer.

Return type:

str

click_extra.serialize_data(data, table_format, *, default=None, root_element='records', **kwargs)[source]¶

Serialize arbitrary Python data to a structured format.

Unlike render_table() which expects tabular rows and headers, this function accepts any JSON-compatible data structure (dicts, lists, nested combinations) and serializes it to the requested format.

Only formats in SERIALIZATION_FORMATS are supported.

Parameters:
  • data (Any) – Arbitrary data to serialize (dicts, lists, scalars).

  • table_format (TableFormat) – Target serialization format.

  • default (Callable | None) – Fallback serializer for types not natively supported. Defaults to str, so Path and similar types are stringified automatically. Set to a custom callable for different behavior.

  • root_element (str) – Root element name for XML output.

  • kwargs – Extra keyword arguments forwarded to the underlying serializer (like sort_keys or indent for JSON).

Raises:

ValueError – If the format is not a serialization format.

Return type:

str

click_extra.set_default_theme(theme)[source]¶

Override the process-wide fallback theme.

ThemeOption writes its picked theme to ctx.meta rather than calling this helper, so per-invocation choices do not leak across invocations sharing the same process. Use this only for genuinely process-wide overrides: patch_click() is the canonical caller.

Return type:

None

click_extra.show_params_option(param_decls=None, *, is_flag=True, expose_value=False, is_eager=True, help='Show all CLI parameters, their provenance, defaults and value, then exit.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.sort_by_option(*header_defs, cls=<class 'click_extra.table_options.SortByOption'>, group=None, **kwargs)[source]¶

Attach a SortByOption to a command.

Forwards the positional header_defs (ColumnSpec instances or bare column IDs) straight to the option constructor and registers it with the same _param_memo primitive Cloup uses, so the --sort-by option composes with @option_group and @constraint like any other option decorator.

Note

Hand-written instead of produced by decorator_factory() because SortByOption accepts its column definitions as positional arguments, which conflicts with the param_decls-first convention the factory relies on. Routing through the factory would force them into a keyword.

click_extra.split_ansi(text)[source]¶

Split text into (style, text) runs at ANSI SGR escape boundaries.

A stateful SGR stream parser: each escape updates the current style state (with full and selective resets honored, unlike Style.from_ansi()), and every maximal run of text sharing the same state is yielded with its Style. Unstyled text is yielded with an empty Style. Consecutive runs with equal styles are merged and empty runs are dropped, so wrapping each yielded run produces minimal markup.

Every other escape carries no style information and is removed from the yielded text by strip_ansi(), so a terminal hyperlink keeps its display text and loses its URI.

Return type:

Iterator[tuple[Style, str]]

click_extra.strip_ansi(text)[source]¶

Remove every ANSI escape sequence from text, leaving its plain text.

Overloads:

Styles, cursor movements, screen clearing and OSC commands all go. A terminal hyperlink keeps its display text and loses its URI, which lived in the markers around it. Bytes come back as bytes.

click_extra.strip_overstrike(text)[source]¶

Remove the character-backspace pairs a roff typesetter emits for emphasis.

A bold N is written N\x08N and an underlined one _\x08N, a convention inherited from line printers that a pager still renders as bold and underline today. Dropping the pair’s first half leaves the plain character.

The terminal-text counterpart of strip_ansi().

Return type:

str

click_extra.style(text, fg=None, bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, reset=True)[source]¶

Styles a text with ANSI styles and returns the new string. By default the styling is self contained which means that at the end of the string a reset code is issued. This can be prevented by passing reset=False.

Examples:

click.echo(click.style('Hello World!', fg='green'))
click.echo(click.style('ATTENTION!', blink=True))
click.echo(click.style('Some things', reverse=True, fg='cyan'))
click.echo(click.style('More colors', fg=(255, 12, 128), bg=117))

Supported color names:

  • black (might be a gray)

  • red

  • green

  • yellow (might be an orange)

  • blue

  • magenta

  • cyan

  • white (might be light gray)

  • bright_black

  • bright_red

  • bright_green

  • bright_yellow

  • bright_blue

  • bright_magenta

  • bright_cyan

  • bright_white

  • reset (reset the color code only)

If the terminal supports it, color may also be specified as:

  • An integer in the interval [0, 255]. The terminal must support 8-bit/256-color mode.

  • An RGB tuple of three integers in [0, 255]. The terminal must support 24-bit/true-color mode.

See https://en.wikipedia.org/wiki/ANSI_color and https://gist.github.com/XVilka/8346728 for more information.

Parameters:
  • text (Any) – the string to style with ansi codes.

  • fg (int | tuple[int, int, int] | str | None) – if provided this will become the foreground color.

  • bg (int | tuple[int, int, int] | str | None) – if provided this will become the background color.

  • bold (bool | None) – if provided this will enable or disable bold mode.

  • dim (bool | None) – if provided this will enable or disable dim mode. This is badly supported.

  • underline (bool | None) – if provided this will enable or disable underline.

  • overline (bool | None) – if provided this will enable or disable overline.

  • italic (bool | None) – if provided this will enable or disable italic.

  • blink (bool | None) – if provided this will enable or disable blinking.

  • reverse (bool | None) – if provided this will enable or disable inverse rendering (foreground becomes background and the other way round).

  • strikethrough (bool | None) – if provided this will enable or disable striking through text.

  • reset (bool) – by default a reset-all code is added at the end of the string which means that styles do not carry over. This can be disabled to compose styles.

Return type:

str

Changed in version 8.5.0: All invalid color values raise ValueError. 256-color index 0 is no longer ignored.

Changed in version 8.0: A non-string message is converted to a string.

Changed in version 8.0: Added support for 256 and RGB color codes.

Changed in version 8.0: Added the strikethrough, italic, and overline parameters.

Changed in version 7.0: Added support for bright colors.

Added in version 2.0.

click_extra.table_format_option(param_decls=None, *, type=EnumChoice('aligned', 'asciidoc', 'colon-grid', 'csv', 'csv-excel', 'csv-excel-tab', 'csv-unix', 'double-grid', 'double-outline', 'fancy-grid', 'fancy-outline', 'github', 'grid', 'heavy-grid', 'heavy-outline', 'hjson', 'html', 'jira', 'json', 'json5', 'jsonc', 'latex', 'latex-booktabs', 'latex-longtable', 'latex-raw', 'mediawiki', 'mixed-grid', 'mixed-outline', 'moinmoin', 'orgtbl', 'outline', 'pipe', 'plain', 'presto', 'pretty', 'psql', 'rounded-grid', 'rounded-outline', 'rst', 'simple', 'simple-grid', 'simple-outline', 'textile', 'toml', 'tsv', 'unsafehtml', 'vertical', 'xml', 'yaml', 'youtrack'), metavar='FORMAT', default=TableFormat.ROUNDED_OUTLINE, expose_value=False, is_eager=True, help='Rendering style of tables.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.telemetry_option(param_decls=None, *, default=False, expose_value=False, envvar=None, show_envvar=True, help='Collect telemetry and usage data.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.terminate_live_processes(signum=Signals.SIGTERM)[source]¶

Send signum to every subprocess currently running through run_cli().

Called from the main thread’s SIGINT handler (see install_interrupt_handler()) so a concurrent fan-out aborts promptly: terminating the children unblocks the worker threads parked in run_cli(), letting the thread pool drain instead of hanging on a child that ignored the terminal’s process-group SIGINT.

A child spawned with start_new_session never receives the terminal’s SIGINT at all (it left the foreground process group), so its whole group is signalled here, with the groups its descendants moved to.

Defaults to SIGTERM rather than SIGKILL so a child still gets to clean up, notably to restore terminal state a sudo password prompt may have altered. An aborting Click Extra command follows up with SIGKILL for a child still running after a grace period.

SIGTERM goes to a child sharing the caller’s process group alone: stopping what it started is part of its own clean-up. SIGKILL cannot be handled, so it also goes to each descendant of that child, one PID at a time (see _kill_descendants()), and to the descendants an earlier call wrote down (see _STRAY_DESCENDANTS), which a child that exited on SIGTERM left running. Windows has a single forced termination, which ends the whole process tree of each child whatever signum asks for.

The registry is snapshotted under the lock, then signalled outside it, because run_cli() may be discarding its own entries from other threads at the same time.

Return type:

None

click_extra.theme_option(param_decls=None, *, default='dark', is_eager=True, expose_value=False, query_background=False, help='Color theme used for help screens.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.timer_option(param_decls=None, *, default=False, expose_value=False, is_eager=True, help='Measure and print elapsed execution time.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.trail_line(ok, message)[source]¶

Format one āœ“/✘ trail line: a glyph followed by message.

The glyph is the one trail_glyph() paints.

Return type:

str

click_extra.tree_option(param_decls=None, *, is_flag=True, expose_value=False, is_eager=True, help='Show the tree of nested subcommands and exit.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.unstyle(text)[source]¶

Removes ANSI styling information from a string. Usually it’s not necessary to use this function as Click’s echo function will automatically remove styling if necessary.

Added in version 2.0.

Parameters:

text (str) – the text to remove style information from.

Return type:

str

click_extra.validate_config_option(param_decls=None, *, type=UNPROCESSED, metavar='LOCATION', is_eager=True, expose_value=False, help='Validate the configuration file and exit.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.verbose_option(param_decls=None, **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.verbosity_option(param_decls=None, *, default_logger='root', default=LogLevel.WARNING, metavar='LEVEL', type=EnumChoice('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'), help='Either CRITICAL, ERROR, WARNING, INFO, DEBUG.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.version_option(version=None, *param_decls, cls=<class 'click_extra.version.VersionOption'>, group=None, **kwargs)[source]¶

Attach a VersionOption to a command.

Drop-in compatible with Click’s @version_option: the first positional argument may be an explicit version string. click-extra otherwise auto-detects the version and treats positional arguments as option flags (like every other option decorator), so the two are disambiguated by their leading character: a value starting with - is a flag declaration, anything else is a Click-style version string forwarded into the version template field.

@command
@version_option("1.2.3")  # Click idiom: pins the displayed version.
def my_cmd(): ...

Note

Hand-written instead of produced by decorator_factory() because Click’s leading version positional conflicts with the param_decls-first convention the factory relies on.

click_extra.wrap_ansi(text, width)[source]¶

Wrap text to width terminal cells, preserving its ANSI styling.

textwrap.wrap() counts every byte of an ANSI escape toward the line length, so a styled string wraps far earlier than its visible width warrants. wcwidth.wrap measures an escape at no cells and every character between escapes at the width a terminal advances by. It reopens on each line the styling still in effect, so no escape sequence crosses a line boundary: each returned line carries the styling it needs, opened and closed within the line.

Note

Breaks land where textwrap.wrap() puts them on plain ASCII, so long-word breaking and whitespace handling match it exactly. The two measures part on a double-width character, which counts for the two cells it takes, and on an OSC 8 hyperlink, which counts for none.

Parameters:
  • text (str) – the text to wrap, ANSI escape sequences included.

  • width (int) – cells each returned line occupies at most.

Return type:

list[str]

Returns:

the wrapped lines, empty text yielding a single empty one.

click_extra.wrap_text(text, width=78, initial_indent='', subsequent_indent='', preserve_paragraphs=False)[source]¶

A helper function that intelligently wraps text. By default, it assumes that it operates on a single paragraph of text but if the preserve_paragraphs parameter is provided it will intelligently handle paragraphs (defined by two empty lines).

If paragraphs are handled, a paragraph can be prefixed with an empty line containing the \b character (\x08) to indicate that no rewrapping should happen in that block.

Parameters:
  • text (str) – the text that should be rewrapped.

  • width (int) – the maximum width for the text.

  • initial_indent (str) – the initial indent that should be placed on the first line as a string.

  • subsequent_indent (str) – the indent string that should be placed on each consecutive line.

  • preserve_paragraphs (bool) – if this flag is set then the wrapping will intelligently handle paragraphs.

Return type:

str

Changed in version 8.4.0: Width is measured in visible characters. ANSI escape sequences in text, initial_indent, or subsequent_indent no longer count toward the width budget, so styled input wraps based on what the user sees instead of raw byte length.

click_extra.write_manpages(command, target_dir, prog_name=None, **overrides)[source]¶

Render the command tree and write each man page into target_dir.

Creates target_dir if missing. Returns the list of written paths.

Return type:

list[Path]

click_extra.xdg_dir(variable, fallback, *parts)[source]¶

A directory under an XDG base directory, resolved at call time.

Reads the base directory from the environment variable variable (XDG_CONFIG_HOME, say) and appends parts to it. An unset or empty variable falls back to fallback, the full default path the XDG spec derives from that variable’s own default base, which already carries the parts. A leading ~ is expanded against the HOME in force at the call, so neither the environment nor the home directory is read at import time: a value set for one invocation, by a test fixture or a packaging script staging into a build root, is the one honored. Pass fallback in its ~ form for that: a path expanded at import carries that HOME for good.

Return type:

Path

click_extra.zero_exit_option(param_decls=None, *, default=False, expose_value=False, is_flag=True, help='Always exit with a status code of 0, even when problems are found.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

Subpackages¶

Submodules¶

click_extra.accessibility module¶

Accessibility helpers switching CLI output to a screen-reader-friendly mode.

A screen reader consumes a terminal as a linear stream of characters. Several of the defaults that make output pleasant for sighted users actively harm that stream:

  • ANSI color codes, which carry no meaning once flattened to text;

  • tables drawn with Unicode box characters (│, ā•­, ─, …), whose separators and whitespace-based column alignment are read out as noise;

  • animated progress spinners and bars, whose cursor-driven frames repeat endlessly to a reader that cannot watch them advance;

  • interactive takeovers like a pager or a screen-clear, which trap or wipe the linear stream the reader is following.

The AccessibleOption collapses these concerns into a single --accessible switch (also driven by the ACCESSIBLE environment variable), which is the same rationale that leads Click Extra to render help screens as minimal-width text rather than inside a terminal-wide table. It lowers the --color, --progress and --table-format defaults and publishes ACCESSIBLE, which clear() and echo_via_pager() read to drop their interactive behavior. See the --accessible section of docs/colorize.md for the full reasoning.

click_extra.accessibility.ACCESSIBLE_ENVVAR: Final[str] = 'ACCESSIBLE'¶

Environment variable that requests accessible mode.

Global and CLI-agnostic, unlike the <CLI>_ACCESSIBLE variable Click derives from the option itself. Its bare presence activates the mode, unless its value reads as false (see parse_envvar_flag()). The flag and the <CLI>_ACCESSIBLE variable outrank it: see set_accessible(), which also says why a configuration file does not, and why it is read directly instead of being wired through the option’s envvar.

class click_extra.accessibility.AccessibleOption(param_decls=None, *, is_flag=True, default=False, is_eager=True, expose_value=False, help='Accessibility mode: disable colors and render tables in a borderless, screen-reader-friendly format.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured --accessible switch.

Turning it on (either via the flag or the ACCESSIBLE environment variable) is equivalent to passing --no-color --no-progress --table-format plain, and additionally streams echo_via_pager() output without a pager and turns clear() into a no-op: it strips ANSI codes, silences progress spinners and bars, renders tables without box-drawing characters, and avoids interactive screen takeovers.

Note

It is a one-way flag with no --no-accessible counterpart: to opt back out, pass the explicit --color / --table-format you want, which take precedence anyway (see below). A negation flag would also be the widest option label in the help screen, pushing every other option’s description column to the right.

The switch only adjusts the defaults of the --color and --table-format options, through the context’s default_map. An explicit --color / --table-format on the command line (or in a configuration file) therefore keeps precedence over --accessible.

This option is eager so it lands its defaults before --color and --table-format are resolved.

Note

The values are injected with dict.setdefault(), so they never clobber a colorization or table format already requested by the user. Combined with the ChainMap that ConfigOption layers on top of default_map, this yields the precedence: command line > configuration file > --accessible > built-in defaults.

set_accessible(ctx, param, value)[source]¶

Publish the accessibility intent and lower color/progress/table defaults.

Reconciles --accessible with the ACCESSIBLE environment variable, stores the result at ACCESSIBLE for output helpers (clear(), echo_via_pager()) to read, then lowers the --color / --progress / --table-format defaults when active. A CLI that never sees --accessible (nor ACCESSIBLE) keeps every default untouched.

ACCESSIBLE is a machine-wide variable, so the command line and the variable of the option outrank it, as they do for every machine-wide variable (see machine_envvars_apply()). The precedence is: --accessible > <CLI>_ACCESSIBLE > ACCESSIBLE > configuration file > built-in default.

Important

ACCESSIBLE outranks a configuration file, where the other machine-wide variables rank below one. The mode works by lowering the defaults of other options, and parse_args() settles it from the command line and the environment before the configuration file loads, so that --help and --version render in accessible mode too. A file read later could not take those lowered defaults back: it would leave the colors off while the mode reads as off.

Note

The global ACCESSIBLE environment variable is read here rather than wired through the option’s envvar. Click would otherwise list it alongside the auto-generated <CLI>_ACCESSIBLE variable in the --params table, making the combined string the widest cell of the env-var column and pushing every other row’s padding out. This mirrors how ColorOption reads NO_COLOR and friends.

Return type:

None

click_extra.accessibility.clear()[source]¶

Drop-in for click.clear() that becomes a no-op under --accessible.

Clearing the screen wipes the scrollback a screen reader relies on and carries no meaning in a linear stream, so accessibility mode skips it entirely. Outside accessibility mode (or with no active context) it defers to click.clear(), which already no-ops when stdout is not a terminal.

Return type:

None

click_extra.accessibility.echo_via_pager(text_or_generator, color=None)[source]¶

Drop-in for click.echo_via_pager() that streams plainly under –accessible.

A pager is a full-screen, cursor-driven TUI: it traps output behind its own keybindings, hostile to a screen reader consuming a linear stream. Under --accessible the text is written straight to stdout via click.echo() instead. Outside accessibility mode (or with no active context) it defers to click.echo_via_pager(), which already falls back to a plain write when stdout is not a terminal.

The argument is normalized exactly as click.echo_via_pager() does (a generator function is called, a string is emitted as-is, anything else is iterated), so the two behave identically on their inputs.

Return type:

None

click_extra.ansi module¶

Read and write ANSI escape sequences, and convert terminal colors.

A terminal styles its text with escape sequences mixed into the text. Every module of this package that reads or writes such text uses the grammar and the color arithmetic of this module:

Style, the stream parser split_ansi() and the markup converters are built on this module, in click_extra.styling.

click_extra.ansi.RESET = '\x1b[0m'¶

Escape closing every style a line left open, written before any padding.

click_extra.ansi.ANSI_16_RGB: tuple[tuple[int, int, int], ...] = ((0, 0, 0), (239, 41, 41), (138, 226, 52), (252, 233, 79), (52, 101, 164), (197, 9, 197), (52, 226, 226), (245, 245, 245), (103, 103, 103), (255, 109, 103), (95, 249, 103), (254, 251, 103), (104, 113, 255), (255, 118, 255), (95, 253, 255), (254, 255, 255))¶

Canonical sRGB values for the 16 ANSI colors.

The single source of truth wherever a named ANSI color, or one of the first 16 slots of the 256-color palette, must materialize as a concrete RGB value: to_css() (bright_* names are not valid CSS keywords), contrast_ratio() (luminance needs RGB), palette_to_rgb() (indices 0-15), and the palettes rendering terminal sessions in the documentation (click_extra.pygments._NAMED_COLORS and _PALETTE_256).

Values are the ones the documentation always rendered: Tango-flavored normal colors and iTerm2’s default brights, picked for legibility on both light and dark backgrounds.

Note

The 8 base named colors keep bypassing this table in markup output: _color_to_css() emits them as plain CSS keywords (and the Jira and LaTeX emitters as macro/xcolor names), delegating the exact shade to the renderer. This table only answers when a concrete value is unavoidable.

click_extra.ansi.ANSI_NAMES: tuple[str, ...] = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white')¶

Names of the 8 base ANSI colors, in palette order.

A bright variant takes the bright_ prefix and the slot 8 places further on.

click_extra.ansi.ANSI_INDEX: dict[str, int] = {'black': 0, 'blue': 4, 'cyan': 6, 'green': 2, 'magenta': 5, 'red': 1, 'white': 7, 'yellow': 3}¶

Palette index of each base ANSI color name, the O(1) mirror of ANSI_NAMES for the name-to-slot lookups color resolution performs.

click_extra.ansi.ANSI_SGR_RE: Pattern[str] = re.compile('\\x1b\\[(?P<sgr_params>[0-9;]*)m')¶

Match a single ANSI SGR escape: \x1b[...m.

The parameter substring may be empty: \x1b[m is a valid, parameter-less full reset. It is captured as sgr_params: the lexer of click_extra.pygments composes this pattern into its own tokenizer and reads the parameters by that name.

click_extra.ansi.SGR_ATTRIBUTES: dict[int, str] = {1: 'bold', 2: 'dim', 3: 'italic', 4: 'underline', 5: 'blink', 7: 'reverse', 9: 'strikethrough', 53: 'overline'}¶

The SGR code switching each boolean style attribute on.

click_extra.ansi.is_rgb(color)[source]¶

Whether color is a 24-bit (r, g, b) triplet.

The one shape of color this module computes on: a named ANSI color, a palette index or a hex string is resolved to it first.

Return type:

TypeGuard[tuple[int, int, int]]

click_extra.ansi.hex_to_rgb(value)[source]¶

Parse a hex color (#rrggbb or shorthand #rgb) to an RGB tuple.

Raises:

ValueError – when value holds anything but 3 or 6 hex digits after its #. int alone would take a sign, an underscore or a non-ASCII digit, and turn #-1-1-1 into negative channels.

Return type:

tuple[int, int, int]

click_extra.ansi.rgb_to_hex(rgb)[source]¶

Format an (r, g, b) tuple as a #rrggbb hex string.

The inverse of hex_to_rgb(). The single source of truth for the RGB-to-hex rendering shared by __repr__, to_css, to_dict, and the documentation palette.

Return type:

str

click_extra.ansi.palette_to_rgb(idx)[source]¶

Convert a 256-color palette index to its sRGB tuple.

Indices 0-15 are the terminal’s system colors: terminals render them with their theme’s palette, so they resolve through the canonical ANSI_16_RGB table. Indices 16-231 (the 6x6x6 color cube) and 232-255 (the grayscale ramp) are fixed by the xterm 256-color layout.

Return type:

tuple[int, int, int]

click_extra.ansi.nearest_256(r, g, b)[source]¶

Map a 24-bit RGB triplet to the nearest index in the 256-color palette.

The inverse of palette_to_rgb(). Compares the Euclidean distance in RGB space against both the 6x6x6 color cube (indices 16-231) and the grayscale ramp (indices 232-255), returning whichever is closer.

Used by Style.__call__ to downsample branded-theme colors when the terminal lacks truecolor (see supports_truecolor()), and by click_extra.pygments and click_extra.cli for the same 24-bit-to-8-bit quantization.

See also

Previous implementation of full-color to 8-bit quantization.

Return type:

int

click_extra.ansi.resolve_rgb(color)[source]¶

Convert a color value to an (r, g, b) tuple.

Accepts RGB tuples, hex strings, named ANSI colors ("red", "bright_blue") and palette indices.

Raises:

ValueError – for any other value.

Return type:

tuple[int, int, int]

click_extra.ansi.CSI_PREFIX_PATTERN = '\\x1b\\[[0-?]*[ -/]*'¶

A CSI sequence short of its final byte, in ECMA-48 syntax.

ESC [, then the parameter bytes and the intermediate bytes. A stream read in chunks can end on one, the rest of the sequence still to arrive.

click_extra.ansi.CSI_PATTERN = '\\x1b\\[[0-?]*[ -/]*[@-~]'¶

One CSI sequence, SGR styles included.

CSI_PREFIX_PATTERN, then a final byte, like the m closing an SGR escape or the ~ closing ESC [ 200 ~.

click_extra.ansi.ANSI_ESCAPE_PATTERN = '(?:\\x1b\\][^\\x07\\x1b]*(?:\\x07|\\x1b\\\\)?|\\x1b\\[[0-?]*[ -/]*[@-~]|\\x1b[ -/]*[0-Z\\\\^-~])'¶

One ANSI escape sequence of any kind, SGR styles included, in ECMA-48 syntax.

click_extra.ansi.strip_ansi(text)[source]¶

Remove every ANSI escape sequence from text, leaving its plain text.

Overloads:

Styles, cursor movements, screen clearing and OSC commands all go. A terminal hyperlink keeps its display text and loses its URI, which lived in the markers around it. Bytes come back as bytes.

click_extra.ansi.sgr_params(params)[source]¶

Decode an SGR parameter substring into a sequence of integer codes.

Per ECMA-48, an empty parameter defaults to 0: \x1b[m is a full reset, and \x1b[;31m carries a reset followed by a red foreground.

Return type:

tuple[int, ...]

click_extra.ansi.apply_sgr_codes(codes, state, *, resets=True)[source]¶

Apply SGR parameter codes to the mutable style state, in place.

The single source of truth for SGR semantics, shared by split_ansi() (with the default resets=True) and from_ansi() (with resets=False).

Style-setting codes add entries to state, keyed by Style field names. When resets is true, the full 0 reset clears the state, and selective resets drop their attribute: 22 (bold and dim), 23 (italic), 24 (underline), 25 (blink), 27 (reverse), 29 (strikethrough), 39 (foreground), 49 (background) and 55 (overline). When resets is false all of them are ignored, letting from_ansi() merge escapes without wiping already-parsed codes.

Unknown codes are silently skipped, like terminals do.

Return type:

None

click_extra.ansi.open_ansi(text, opened='')[source]¶

Return the ANSI SGR escapes still in effect at the end of text.

Escapes accumulate in the order they were read. A full 0 reset (its parameter-less \x1b[m form included) empties the accumulator, so the result re-opens what text left dangling and nothing else. Escapes come back verbatim rather than folded into a Style, which keeps a code this module does not model.

Use it to splice a styled fragment into styled text: the fragment closes with a reset of its own, which would otherwise strip the surrounding styling from everything after it. See highlight().

Parameters:
  • text (str) – the string to read the escapes from.

  • opened (str) – escapes already in effect before text, as returned by an earlier call. Feeding a string one chunk at a time then costs one pass over it, where re-reading the whole prefix per chunk costs one per chunk. A chunk must not start or end in the middle of an escape: the two halves match nothing, and the escape is lost.

Return type:

str

click_extra.bug_report module¶

Bug reports for the errors a command has no rule for.

A command given a report_url ends the run on such an error with a report that its user can paste into an issue. The report gives the version and platform of the run, its options, and the traceback of the error, between two 8< markers. A link opens the issue form of the project with a title filled in. See invoke().

A CLI can also log a report of its own with log_report(), for a failure that does not stop the run.

Caution

Issues are often public, so a report holds no file path. The traceback keeps module names and line numbers, which say as much about the code as file paths, and nothing about where it is installed. The options line masks the values of paths, patterns and positional arguments. The message of the error stays as the code wrote it: the report asks the user to read it before they paste it.

click_extra.bug_report.MAX_FRAMES: Final = 12¶

Innermost frames of a traceback that a report keeps.

The frames past them give way to a line that counts them: the innermost ones hold the code that raised the error.

click_extra.bug_report.MAX_MESSAGE_LENGTH: Final = 200¶

Characters of an error message that a report keeps.

click_extra.bug_report.REPORT_START: Final = '----- 8< ----- bug report ----- 8< -----'¶

First line of the block that a user pastes into an issue.

click_extra.bug_report.REPORT_END: Final = '----- 8< ----- end of bug report ----- 8< -----'¶

Last line of the block that a user pastes into an issue.

click_extra.bug_report.REPORTS_FOLDER: Final = 'reports'¶

Folder of the cache directory of a CLI that holds its saved reports.

click_extra.bug_report.describe_error(expt)[source]¶

The class and message of an exception, on one line of capped length.

The class shows with its module, unless it is built in. The message keeps its first MAX_MESSAGE_LENGTH characters.

Return type:

str

click_extra.bug_report.compact_frames(tb)[source]¶

A traceback as module:line in function entries, outermost first.

Module names say as much as file paths about the code, and nothing about where it is installed, so they are what a report shows. A method shows with its class, like Path.open.

Return type:

tuple[str, ...]

click_extra.bug_report.cli_traceback(tb, callback=None)[source]¶

The traceback from its first frame outside the Click ecosystem.

An error reaches invoke() through the frames that Click and Click Extra run the command with, which are the same in every report. A traceback with no other frame is kept whole.

The code of a CLI built in the Click ecosystem, like the click-extra CLI, is in it too. So the frame of callback, the function of the command, also starts the traceback.

Return type:

TracebackType | None

click_extra.bug_report.culprit_function(tb, package)[source]¶

The name of the innermost function of package in a traceback, or nothing.

It names the code to fix, even for an error that Python or a library raised from a call of the package. A generator expression, a comprehension or a lambda has no name of its own, so the named function nearest to it in the traceback stands for it.

Return type:

str

click_extra.bug_report.masked_value(param, value)[source]¶

One value of a parameter as a report shows it.

A path or a pattern can name the files and the data of the user, so it shows as a placeholder, like the value of a positional argument, which is often the data the command works on. Other values show as typed.

Return type:

str

click_extra.bug_report.option_words(param, value)[source]¶

Render one parameter as typed on the command line, with its values masked.

A flag shows alone, or as its secondary name when it is off, like --no-color. A counting option shows once per count. See masked_value() for the values.

Return type:

list[str]

click_extra.bug_report.options_summary(ctx)[source]¶

The parameters of the run that do not come from their default, masked.

Walks from the root command to the command of ctx, and names each subcommand on the way. A value from a configuration file or an environment variable counts, as it changes the run as much as one typed on the command line.

The options of Click Extra keep no value of their own in the context, and none of them changes what a command does, except --jobs. It shows with the number of jobs it resolved to.

Return type:

str

click_extra.bug_report.cli_version(ctx)[source]¶

The version of the root command, as its --version option prints it.

The report reads it from a new VersionOption, which takes the fields the command pinned on its own. The module of the root command’s callback is pinned too, unless the command pinned one: the walk of the stack that finds it otherwise stops on the caller of the CLI, as the callback has returned when the error reaches the command.

Returns None when the version cannot be found.

Return type:

str | None

click_extra.bug_report.report_form_url(url, title)[source]¶

The URL of the issue form, with title filled in.

The query of url is kept, like the template that picks the form of a GitHub repository.

Return type:

str

click_extra.bug_report.render_report(headline, title, details, ctx)[source]¶

The message inviting the user to file a bug report, with the block to paste.

It links to the issue form of the report_url of the root command, with title filled in. The block opens with the version of the CLI, the platform and the options of the run, then gives the details of the error.

An AI agent running the CLI gets a line of its own: it is to show the report to its user, who decides to file it.

Return type:

str

click_extra.bug_report.save_report(report, ctx)[source]¶

Write a bug report to a new file in the REPORTS_FOLDER of the cache.

The cache is that of the root command, as get_cache_dir() locates it. A user who loses the output of a long run, to a closed terminal or a short scrollback, still finds the report there. The file holds the report as it is printed, so it can be attached to an issue whole.

Each report gets a new file, named after the time it was saved. mkstemp() adds random characters to the name and never reuses one, so two reports of the same second keep a file each.

Returns None if the file cannot be written: the printed report then stands alone.

Return type:

Path | None

click_extra.bug_report.log_report(level, headline, title, details, ctx=None)[source]¶

Log the report that render_report() builds, and save it with save_report().

The report goes to the root logger, which the CLI prints. The path of the saved file comes last, alone on its line, so it is the last thing a user sees of the run, and easy to copy. It stays out of the file.

ctx defaults to the context of the running command.

Return type:

None

click_extra.bug_report.report_unexpected_error(ctx, expt)[source]¶

End the run on an error that its command has no rule for.

An OSError comes from the system, like a missing permission or a full disk, so the user can fix it: it ends the run with a one-line error, and its traceback goes to the debug log. Any other error is a bug. Its traceback is logged with the report inviting the user to file it, and the run exits with code 1. The report shows the frames from cli_traceback() on.

The title of the issue names the class of the error and the innermost function of the package of the root command, which culprit_function() finds. Reports of the same bug then get the same title, so the issue form lists the one already open. Unlike a line number, a function name does not change between releases.

Return type:

NoReturn

click_extra.carapace module¶

Export a Click command tree as a Carapace completion spec.

Carapace is a multi-shell completion engine: a single spec file drives identical completions across Bash, Zsh, Fish, Nushell, PowerShell, Elvish, Xonsh, Oil and more. This module walks a Click/Cloup command tree and serializes it to the YAML carapace-spec format, answering the request for native Carapace support in pallets/click#3188 (closed as out of scope for core Click, redirected here).

Two completion strategies cooperate:

  • Static. Choices, file/directory operands and the command hierarchy are inlined straight into the spec. These complete with no process launch and work in every shell Carapace supports, which is the advantage a spec has over Carapace’s existing bridge to a single shell’s native Click completion.

  • Dynamic. A parameter carrying a custom shell_complete (a callback, or a ParamType that overrides shell_complete()) cannot be frozen into the spec, so its action calls back into the CLI through Carapace’s shell macro. The callback reuses Click’s own completion machinery via CarapaceComplete.

Note

Dynamic completion needs the CarapaceComplete class registered in the target process, which happens on import click_extra. A CLI built with Click Extra gets it for free; a plain Click CLI would have to import click_extra for the dynamic callback to resolve. Static completion has no such requirement.

The dataclasses below mirror the upstream carapace-spec JSON schema; the flag-key grammar and macro contract are taken from that project’s flag.go and core.go.

Todo

Mark a required flag group once carapace-sh/carapace-spec#437 ships a Command key for cobra’s MarkFlagsOneRequired. It closes two gaps at once: a required boolean pair (--foo / --no-foo) reaches the spec unmarked, since ! marks one flag at a time and either spelling satisfies Click; and Cloup’s RequireAtLeast constraint is dropped for want of anywhere to put it.

click_extra.carapace.CARAPACE_DOCS_URL = 'https://kdeldycke.github.io/click-extra/carapace.html'¶

Documentation page stamped into every generated spec’s header comment, so a reader of the raw YAML knows where the feature is documented.

click_extra.carapace.xdg_dir(variable, fallback, *parts)[source]¶

A directory under an XDG base directory, resolved at call time.

Reads the base directory from the environment variable variable (XDG_CONFIG_HOME, say) and appends parts to it. An unset or empty variable falls back to fallback, the full default path the XDG spec derives from that variable’s own default base, which already carries the parts. A leading ~ is expanded against the HOME in force at the call, so neither the environment nor the home directory is read at import time: a value set for one invocation, by a test fixture or a packaging script staging into a build root, is the one honored. Pass fallback in its ~ form for that: a path expanded at import carries that HOME for good.

Return type:

Path

click_extra.carapace.get_cache_dir(app_name)[source]¶

The user cache directory of app_name, resolved at call time.

The cache counterpart of click.get_app_dir(), which locates the configuration directory:

  • Windows: %LOCALAPPDATA%\<app_name>\Cache.

  • macOS: $XDG_CACHE_HOME/<app_name>, else ~/Library/Caches/<app_name>.

  • Linux and other POSIX systems: $XDG_CACHE_HOME/<app_name>, else ~/.cache/<app_name>.

A user who sets XDG_CACHE_HOME asks every tool to keep its cache there, macOS included. Unlike xdg_dir(), a relative value is ignored, as the XDG specification says: a cache must not move with the working directory.

Return type:

Path

class click_extra.carapace.CarapaceCompletion(flag=dict(), positional=list(), positionalany=list())[source]¶

Bases: object

The completion block of a command: per-flag and positional actions.

flag: dict[str, list[str]]¶

Map of flag name (long spelling, no dashes) to its completion action.

positional: list[list[str]]¶

Per-position completion actions for fixed-arity arguments, in order.

positionalany: list[str]¶

Completion action repeated for every trailing variadic argument.

to_dict()[source]¶

Serialize to the carapace-spec completion mapping, dropping empty members and trailing empty positional slots.

Return type:

dict

class click_extra.carapace.CarapaceDocumentation(positional=list(), positionalany='')[source]¶

Bases: object

The documentation block of a command: prose the spec has no other slot for.

Carapace keys a flag’s own description off flags, and leaves an operand with nowhere to carry one: completion.positional holds actions, not text. This block is where the upstream schema puts that prose, indexed the same way, so carapace --style and the spec’s own readers can show what an operand means.

Only the two members Click can fill are modeled. The schema also carries command, flag, dash and dashany: the first two would restate what description and flags already say, and Click has no ---separated argument family to feed the last two.

positional: list[str]¶

Per-position help text for fixed-arity arguments, in order.

positionalany: str = ''¶

Help text for the trailing variadic argument.

to_dict()[source]¶

Serialize to the carapace-spec documentation mapping.

Drops empty members and trailing undocumented slots, keeping the surviving ones index-aligned with completion.positional.

Return type:

dict

class click_extra.carapace.CarapaceCommand(name, description='', aliases=(), hidden=False, flags=dict(), persistentflags=dict(), exclusiveflags=list(), completion=CarapaceCompletion(), documentation=CarapaceDocumentation(), commands=list())[source]¶

Bases: object

One node of a Carapace spec: a command and its flags, completions and subcommands, mirroring the upstream Command schema.

name: str¶

The command’s invocation name (the root carries the program name).

description: str = ''¶

One-line command description (NAME-section short help).

aliases: tuple[str, ...] = ()¶

Alternative names the command also answers to (from Cloup).

hidden: bool = False¶

Whether the command is hidden from listings (still completable).

flags: dict[str, str]¶

Map of flag key (with shape suffixes) to its description.

persistentflags: dict[str, str]¶

Flags inherited by every subcommand.

extract_carapace_command() leaves it empty: Click parses an option only at the level of the command declaring it, so no option is inherited.

exclusiveflags: list[list[str]]¶

Groups of mutually-exclusive flag names (from Cloup constraints).

completion: CarapaceCompletion¶

Static and dynamic completion actions for this command’s parameters.

documentation: CarapaceDocumentation¶

Prose for the operands, which carry theirs nowhere else in the spec.

commands: list[CarapaceCommand]¶

Nested subcommands.

to_dict()[source]¶

Serialize to a carapace-spec command mapping, dropping empties.

Only name is required by the schema, so every other member is omitted when empty to keep the YAML compact.

Return type:

dict

click_extra.carapace.extract_carapace_command(command, ctx, *, command_path)[source]¶

Build a CarapaceCommand from a Click command and its context.

The context must have been created for command (typically via click.Command.make_context() with resilient_parsing=True). Subcommands are discovered dynamically and recursed into.

Every option lands in the flags of the command declaring it. Click parses an option only at the level of its own command: a group option goes before the subcommand, never after it. Carapace persistentflags would offer it after the subcommand too, where Click rejects it.

command_path is the chain of command names from the root down to this command, grown by one name per recursion and baked into dynamic callback macros (see _dynamic_action()).

Return type:

CarapaceCommand

click_extra.carapace.to_carapace_spec(command, prog_name=None, ctx=None)[source]¶

Build the Carapace spec for a command tree as a plain dict.

Reuses ctx when given (the live invocation context), otherwise builds a throwaway one with resilient_parsing=True. The returned mapping conforms to the carapace-spec schema and is ready to hand to yaml.safe_dump.

Return type:

dict

click_extra.carapace.dump_carapace_spec(command, prog_name=None, ctx=None, *, invocation=None)[source]¶

Serialize a command tree to a Carapace spec YAML string.

Requires the optional PyYAML dependency (click-extra[carapace]). The output keeps Click’s declaration order rather than sorting keys, so flags and subcommands line up with the help screen, and is prefixed with a provenance header: the generator, the invocation command line that produced it (when given), and a link to the documentation.

Return type:

str

click_extra.carapace.write_carapace_spec(command, target, prog_name=None, *, invocation=None)[source]¶

Render the spec and write it to target, returning the written path.

Creates parent directories as needed. invocation is recorded in the header comment (see dump_carapace_spec()).

Return type:

Path

click_extra.carapace.install_carapace_spec(command, prog_name=None, *, invocation=None)[source]¶

Write the spec into Carapace’s user spec directory.

Targets $XDG_CONFIG_HOME/carapace/specs/<prog>.yaml when that variable is set, else ~/.config/carapace/specs/<prog>.yaml, both resolved at call time by xdg_dir(): Carapace loads either on startup. Returns the path.

Return type:

Path

class click_extra.carapace.CarapaceComplete(cli, ctx_args, prog_name, complete_var)[source]¶

Bases: ShellComplete

Click completion backend that emits Carapace’s value/description lines.

Registered as the carapace shell, so _FOO_COMPLETE=carapace_complete makes a Click CLI print completions in the value\tdescription text format Carapace’s shell macro parses. This is the callback target of the dynamic actions emitted by _dynamic_action(); it reuses Click’s own get_completions(), so a parameter’s custom shell_complete is honored verbatim.

The current word is left to Carapace to filter, so completion args are the already-typed words with an empty incomplete value.

name: ClassVar[str] = 'carapace'¶

Shell name Click registers this backend under (the carapace_complete completion instruction).

source_template: ClassVar[str] = ''¶

Completion script template formatted by source(). This must be provided by subclasses.

source()[source]¶

No-op source step: Carapace, not a shell, consumes this backend.

Return type:

str

get_completion_args()[source]¶

Read the words Carapace passed via COMP_WORDS (program name first).

Returns the typed arguments with an empty incomplete value: Carapace applies its own prefix filtering to the candidates returned.

Return type:

tuple[list[str], str]

format_completion(item)[source]¶

Render one completion as Carapace’s value or value\tdescription.

Return type:

str

click_extra.cli module¶

The click-extra CLI.

Its commands are the terminal demos, the CLI wrapper, and the documentation and testing utilities.

click_extra.cli.DEMO_EPILOG = "\x08\nExamples:\n\n\x08\n  Run any Click CLI through Click Extra's colored help:\n    $ click-extra wrap -- my-cli --help\n\n\x08\n  Draw that help screen as a picture a README can show:\n    $ click-extra screenshot --output my-cli.svg -- my-cli --help\n\n\x08\n  Report the parameters a CLI accepts, and where each value comes from:\n    $ click-extra wrap --params -- my-cli\n\n\x08\n  Highlight a source file as a themed picture:\n    $ click-extra snippet --output basket.svg basket.py\n\n\x08\n  See how a help screen reads under each built-in theme:\n    $ click-extra themes\n"¶

Sample invocations closing the root help screen. Each \b escape is Click’s marker for a paragraph to keep as written, since the help formatter rewraps an epilog into one block otherwise.

click_extra.cli.LAZY_SUBCOMMANDS: dict[str, LazySubcommand] = {'prebake': LazySubcommand(import_path='click_extra.cli_prebake.prebake', section=None, fallback_to_default_section=True, short_help='Pre-bake build-time metadata into Python source files.'), 'screenshot': LazySubcommand(import_path='click_extra.cli_capture.screenshot_cmd', section=None, fallback_to_default_section=True, short_help="Capture a command's colored output and write it as an image or HTML."), 'snippet': LazySubcommand(import_path='click_extra.cli_capture.snippet_cmd', section=None, fallback_to_default_section=True, short_help='Highlight a source file and write it as an image or HTML.')}¶

The subcommands imported only when a run reaches them.

The capture commands pull the recording and drawing machinery in, and prebake its source rewriting, which no other run of the CLI needs. Each declares the first paragraph of its help, so the root help screen lists it without importing it. A Nuitka build sees no import of these modules, so [tool.nuitka] of pyproject.toml includes each by name.

click_extra.cli.TEST_SUITE_EPILOG = '\x08\nExamples:\n\n\x08\n  Run the built-in default suite against a CLI:\n    $ click-extra test-suite --command my-cli\n\n\x08\n  Run the cases a file declares, one at a time, stopping on the first failure:\n    $ click-extra test-suite --command my-cli --suite-file cases.yaml --jobs 1 --exit-on-error\n\n\x08\n  Run two of them, skipping the cases a platform cannot answer:\n    $ click-extra test-suite --command my-cli --select-test 3 --select-test 7 --skip-platform windows\n'¶

Sample invocations closing the test-suite help screen.

click_extra.cli.REFRESH_DIRECTIVES_EPILOG = '\x08\nExamples:\n\n\x08\n  Refresh every self-updating block of a documentation tree:\n    $ click-extra refresh-directives docs\n\n\x08\n  Refresh one page:\n    $ click-extra refresh-directives docs/recipes.md\n\n\x08\n  Report the stale ones without writing, for a continuous-integration job:\n    $ click-extra refresh-directives --check docs\n'¶

Sample invocations closing the refresh-directives help screen.

click_extra.cli.CONVERT_TO_MYST_EPILOG = '\x08\nExamples:\n\n\x08\n  Convert the docstrings of the package in the current directory:\n    $ click-extra convert-to-myst\n\n\x08\n  Convert the docstrings under another one:\n    $ click-extra convert-to-myst src/basket\n'¶

Sample invocations closing the convert-to-myst help screen.

click_extra.cli_capture module¶

The screenshot and snippet commands of the click-extra CLI.

Both draw a document from terminal text: the first captures what a command prints, the second colors a source file, and they share the window options, the output resolution and the delivery through capture_options(), resolve_capture_format() and deliver_capture(). click_extra.cli registers them on the root group.

click_extra.cli_capture.deliver_capture(document, output)[source]¶

Write a rendered capture where --output points.

A bare - prints it instead, see is_stdout(), through click.echo() rather than a bare write: that is what strips the escape sequences when the terminal turns out to be a pipe, and what lets --color, --no-color, --accessible and NO_COLOR reach a capture, since invocation_color() carries the tri-state all four of them resolve to.

Parameters:
  • document (str) – the rendered capture.

  • output (Path) – where it goes.

Return type:

None

click_extra.cli_capture.resolve_capture_format(output, fragment)[source]¶

Read the capture format off --output, and settle --fragment on it.

Both capture commands carry the pair of options, so both carry the same rejection: --fragment asks for the bare block of a standalone document, and only HTML has one.

Parameters:
  • output (Path) – where the capture goes; its extension names the format.

  • fragment (bool) – whether the caller asked for the bare block.

Return type:

CaptureFormat

Returns:

the format to render.

Raises:

ClickException – on an extension no format claims, or on --fragment against anything but HTML.

click_extra.cli_capture.capture_options(*, columns_help, default_columns=80)[source]¶

Attach every option the two capture commands share.

screenshot pictures what a command printed and snippet pictures what a file says, but both hand their text to the same renderer, so everything from the window’s frame to its credit line is one vocabulary. Declaring it once is what stops the two drifting into near-synonyms, which is the failure a reader hits rather than a maintainer: they learn --backdrop on one command and expect it on the other.

Only the width differs, both in what it defaults to and in what it governs: a command wraps its own output to it, where a file was never wrapped at all.

Note

The options are applied in reverse, so the tuple below reads in the order --help prints. A command’s own options are declared under this decorator and land after the shared ones, which is what keeps the common vocabulary together at the top of every capture command’s help screen.

Parameters:
  • columns_help (str) – what the width means for this command.

  • default_columns (int | Literal['auto']) – the width it takes when nothing states one.

Return type:

Callable[[Callable[..., Any]], Callable[..., Any]]

Returns:

the decorator attaching all of them.

click_extra.cli_capture.SCREENSHOT_EPILOG = '\x08\nExamples:\n\n\x08\n  Draw a help screen as a picture a README can show:\n    $ click-extra screenshot --output my-cli.svg -- my-cli --help\n\n\x08\n  Draw it as selectable text, for a page you own:\n    $ click-extra screenshot --output my-cli.html -- my-cli --help\n\n\x08\n  Capture a CLI that is not built on Click Extra, colored all the same:\n    $ click-extra screenshot --output flask.svg --wrap -- flask run --help\n\n\x08\n  Record the frames a spinner draws, as an animation:\n    $ click-extra screenshot --output ripen.svg --record --columns 80 -- ripen\n'¶

Sample invocations closing the screenshot help screen.

click_extra.cli_capture.SNIPPET_EPILOG = '\x08\nExamples:\n\n\x08\n  Draw a source file as a picture a README can show:\n    $ click-extra snippet --output basket.svg basket.py\n\n\x08\n  Draw it as selectable text, under a named syntax style:\n    $ click-extra snippet --output basket.html --syntax-style dracula basket.py\n\n\x08\n  Number the lines and point at the one that matters:\n    $ click-extra snippet --output basket.svg --line-numbers --emphasize-lines 12 basket.py\n'¶

Sample invocations closing the snippet help screen.

click_extra.cli_prebake module¶

The prebake command group of the click-extra CLI.

Fills the empty __version__ and __<field>__ dunders of a package at build time, from the Git state and the build host, through click_extra.prebake. click_extra.cli registers the group on the root command.

click_extra.cli_wrapper module¶

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.

click_extra.color module¶

Resolve whether terminal output should be colored.

Owns the --color[=WHEN] and --no-color options, the color environment variables (NO_COLOR, FORCE_COLOR, CLICOLOR, and friends), the tri-state WHEN resolution the live displays share, and the detection of what the terminal can render: a dumb TERM, and a dark or light background. The actual styling lives elsewhere: click_extra.styling (the Style primitive), click_extra.theme (palettes), and click_extra.highlight (help-screen rendering).

click_extra.color.TWhen: TypeAlias¶

One of the values of WHEN.

click_extra.color.COLOR_ENVVARS: dict[str, bool] = {'CLICOLOR': True, 'CLICOLORS': True, 'CLICOLORS_FORCE': True, 'CLICOLOR_FORCE': True, 'COLOR': True, 'COLORS': True, 'FORCE_COLOR': True, 'FORCE_COLORS': True, 'LLM': False, 'NOCOLOR': False, 'NOCOLORS': False, 'NO_COLOR': False, 'NO_COLORS': False}¶

Environment variables recognized as flags to switch color rendering on or off.

The key is the name of the variable, and the boolean the direction its convention leans: True for a variable asking for color, False for one refusing it. Each value is read by the convention of its variable, not as a plain boolean: see resolve_color_env().

Source:

click_extra.color.WHEN: tuple[Literal['auto', 'always', 'never'], ...] = ('auto', 'always', 'never')¶

GNU-canonical tri-state saying when a terminal feature is used.

auto decides from the terminal, always uses the feature on any stream, and never leaves it off. The values of --color=<WHEN>, where the feature is ANSI color, and of the live argument of Spinner and OperationTrail, where it is an animation. See GNU coreutils and this discussion.

click_extra.color.COLOR_WHEN_ALIASES: dict[str, str] = {'force': 'always', 'if-tty': 'auto', 'no': 'never', 'none': 'never', 'tty': 'auto', 'yes': 'always'}¶

GNU coreutils synonyms accepted as hidden aliases for each WHEN value.

GNU ls accepts yes/force for always, no/none for never and tty/if-tty for auto, alongside the three canonical spellings (see WHEN). Click Extra mirrors that leniency but keeps the synonyms out of --help output, error messages and shell completion, which only ever advertise WHEN.

click_extra.color.COLOR_DISABLING_TERMS = frozenset({'dumb', 'unknown'})¶

TERM values marking a terminal too limited for ANSI niceties.

A dumb or unknown terminal advertises neither SGR color nor the cursor-control codes (carriage return, clear-line) an animation relies on, so both Click Extra’s color resolution (resolve_color_env()) and the spinner’s animation gating (spinner._can_draw()) treat these two values as a hard opt-out. Both read them through is_dumb_terminal(), which keeps the color and animation axes from drifting apart.

An unset TERM is deliberately excluded: it is common on legitimately color-capable streams (subprocesses, some IDEs) where defaulting to off would be a regression. This matches Rich, which keys its own dumb-terminal detection on the same two values and not on absence.

click_extra.color.is_dumb_terminal()[source]¶

Whether TERM names a terminal in COLOR_DISABLING_TERMS.

Such a terminal renders neither color nor the cursor movements of an animation. Case does not matter, and an unset TERM is no dumb terminal.

Return type:

bool

click_extra.color.is_a_tty(stream)[source]¶

Whether stream reports itself as an interactive terminal.

Probes isatty defensively through getattr(): not every stream object exposes the method (a bare buffer, an in-memory capture, a test double), and a plain stream.isatty() would raise there instead of answering ā€œnot a terminalā€.

Return type:

bool

click_extra.color.resolve_color_env()[source]¶

Reconcile the recognized color environment variables into a tri-state.

Reads every variable listed in COLOR_ENVVARS by its own convention, and returns:

  • True if at least one variable asks for color. A variable asking for color wins over one refusing it, as in the reference code of FORCE_COLOR.

  • False if variables only refuse color.

  • None if no variable casts a vote, which leaves the caller free to apply its own default (typically auto).

An empty value never votes: both NO_COLOR and FORCE_COLOR treat it as unset. Each family then follows its convention:

  • NO_COLOR refuses color whatever its value, 0 and false included. It never asks for color.

  • FORCE_COLOR asks for color, except for 0, false, no and off, which refuse it, as Node.js tools read them.

  • CLICOLOR refuses color when falsy. Any other value only allows color on a terminal, which is the auto default: it casts no vote.

  • CLICOLOR_FORCE asks for color unless it is falsy, which casts no vote.

  • LLM refuses color unless it is falsy, which casts no vote: it marks an AI agent, not a color preference.

  • COLOR takes the words of --color (see WHEN and COLOR_WHEN_ALIASES) and booleans. Any other value casts no vote.

The plural and unspaced spellings in COLOR_ENVVARS follow the variable they spell.

A dumb or unknown TERM (see COLOR_DISABLING_TERMS) refuses color as well, so a terminal that cannot render ANSI is treated as color-off even when it reports as a TTY. A variable asking for color still wins over it.

Return type:

bool | None

click_extra.color.forced_color()[source]¶

Force ANSI color while Click Extra captures CLI text for documentation.

Click Extra renders CLI help and output into docs from both the MkDocs plugin (click_extra.mkdocs) and the Sphinx directives (click_extra.sphinx.click). During a build that output is a pipe, not a TTY, so the underlying renderers strip their escape codes. Two independent color systems have to be defeated:

  • Click’s, gated by should_strip_ansi / ctx.color (what click.echo and the Click and Click Extra help formatters consult). Sphinx’s runner additionally flips this one with click.testing.CliRunner(color=True).

  • Rich’s, gated by rich.console.Console.is_terminal, which ignores the above and reads FORCE_COLOR (https://force-color.org). This is the system rich-click uses, and color=True never reaches it.

FORCE_COLOR is the only signal common to both systems (Rich reads it directly; Click Extra recognizes it through COLOR_ENVVARS), so this sets it. It also clears the color-disabling variables Click Extra recognizes (NO_COLOR, LLM, …) so an opt-out in the build environment cannot suppress the rendering, and pins COLORTERM=truecolor so the branded 24-bit themes render at full depth instead of being quantized to the 256-color palette (see supports_truecolor()). The previous environment is restored on exit, so the override never leaks beyond a single capture.

Return type:

Generator[None, None, None]

class click_extra.color.TerminalBackground(*values)[source]¶

Bases: StrEnum

Shade of the background of a terminal.

What resolve_background() detects of the terminal a CLI runs in, and the chrome of a capture, which pictures a terminal: see click_extra.capture.presets. A capture tells the command it pictures which one it is drawn on through the same variables resolve_background() reads, see CAPTURE_TERMINAL_HINTS, so a command run for a picture picks the palette its picture needs.

A capture freezes the colors of the run it pictures, so its chrome has to answer to the palette that run was colored for. Neither direction survives the other: a screen colored for a dark terminal is unreadable on white, and click-extra’s own light and manpage themes wash out on the dark chrome a renderer defaults to.

A member is the string it names, so it also selects the built-in theme of the same name, and doubles as the --background choice of the capture commands.

DARK = 'dark'¶

What a terminal, and this package’s default theme, usually look like.

LIGHT = 'light'¶

For a CLI rendered with a light-background theme.

click_extra.color.query_osc_background(timeout=0.2)[source]¶

Ask the terminal for its background color with an xterm OSC 11 query.

Writes ESC ] 11 ; ? BEL to the terminal and reads back its rgb:RRRR/GGGG/BBBB reply, returning the color as an 8-bit (r, g, b) tuple. Returns None whenever the query cannot run or the terminal stays silent:

  • on non-POSIX platforms, or when termios / tty are missing;

  • when stdin or stdout is not a terminal (piped, redirected, captured);

  • when no reply arrives within timeout seconds.

Caution

The query reads stdin in cbreak mode. If the user has typed ahead, or another reader competes for stdin, those bytes may be consumed here or interleave with the reply (a leading run is harmless: the reply is located with a re.search()). The terminal mode is always restored through termios.tcsetattr(). Because of this contention, the query is opt-in: it runs only when a caller explicitly allows it (see resolve_background() and ThemeOption’s query_background).

Return type:

tuple[int, int, int] | None

click_extra.color.resolve_background(query_background=False)[source]¶

Detect whether the terminal has a dark or light background.

Consults each signal in turn and returns the first that resolves, or None when none does (callers then keep their own default). Precedence, highest first:

  1. CLITHEME — the cli-theme convention. A dark or light value (optionally suffixed with a :variant) is a deliberate override and wins outright; auto and anything unrecognized fall through.

  2. The live OSC 11 query (query_osc_background()), but only when query_background is true. It is the most accurate and the only real-time signal, yet it reads stdin, so it stays opt-in.

  3. COLORFGBG — set by a handful of terminals (rxvt, Konsole) and cached by shell-term-background at shell startup. Read last because it is frequently stale: it reflects the value at terminal launch and is not refreshed when the user switches themes.

Parameters:

query_background (bool) – permit the stdin-reading OSC 11 query. Off by default, as on ThemeOption.

Return type:

TerminalBackground | None

See also

ā€œIs this terminal dark or light?ā€ has a small ecosystem of prior art, mixing the same two strategies this function does (a cached environment variable versus a live OSC query):

click_extra.color.publish_invocation_color(ctx)[source]¶

Mirror ctx.color into _invocation_color for cross-thread readers.

Called by every color callback after it settled its part of the resolution: whichever fires last leaves the final tri-state in the mirror.

The first call ties the mirror to ctx’s own lifetime, so the value does not leak into a later invocation in the same process. A close callback resets it on the normal path, and click_extra.context._queue_run_cleanup on the abort path: a callback raising during parameter processing leaves the context never entered, and therefore never closed. Click’s UsageError holds that context, and the traceback holds the error, so the pair sits in a reference cycle and the finalizer of that path runs at the next collection rather than immediately. Ordinary allocation churn reaches it within a few hundred objects, but it is not deterministic.

Command does not depend on that timing: its main() runs within the _scoped_run block that calls the cleanup as the run ends, which covers every Click Extra command. The finalizer is what carries a plain click.command that merely borrows the color options.

Return type:

None

click_extra.color.invocation_color()[source]¶

The invocation’s resolved color tri-state, reachable from any thread.

Prefers the pinned ctx.color of the calling thread’s own Click context, then the process-wide mirror published by the color callbacks (publish_invocation_color()). None means auto: defer to the output stream’s TTY status, exactly like ctx.color’s own default.

This is what makes --no-color reach output produced outside the main thread, like the subprocess lines click_extra.execution.run_cli() streams through click_extra.logging.StreamHandler.

Return type:

bool | None

class click_extra.color.ColorWhenChoice(choices, case_sensitive=True)[source]¶

Bases: Choice

click.Choice over WHEN that also accepts the hidden GNU synonyms (COLOR_WHEN_ALIASES) and native configuration booleans, folding them to a canonical value before validation.

Only the three canonical WHEN values reach --help, error messages and shell completion, because the public choices stay canonical. Synonyms and booleans are accepted silently and normalized, so downstream code (ColorOption.set_color(), _WHEN_TO_TRISTATE) only ever sees auto, always or never.

Matching is case-insensitive and whitespace-tolerant, which also makes the canonical values forgiving, such as --color=ALWAYS.

convert(value, param, ctx)[source]¶

Fold synonyms and booleans to canonical, then defer to click.Choice.

A native bool only reaches this method from a structured configuration file: TOML or JSON booleans, or YAML’s coercion of yes/no/on/off/true/false. True maps to always and False to never, consistent with a bare --color and --no-color. The command line always delivers strings, so this never turns --color=true into a valid CLI spelling.

Caution

A configuration boolean therefore diverges from git’s color.ui, where true means auto. Click Extra keeps true equal to always so the yes string synonym and YAML’s coercion of yes to True resolve identically across file formats.

Return type:

Any

class click_extra.color.ColorOption(param_decls=None, *, is_flag=False, flag_value='always', default='auto', is_eager=True, expose_value=False, help='Colorize the output. A bare --color is the same as --color=always.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured --color[=WHEN] tri-state option.

Mirrors the GNU coreutils convention: WHEN is one of WHEN (auto, always or never), and a bare --color (no value) means always. The negative alias --no-color is carried by the separate NoColorOption, because Click forbids attaching /--no-x secondary flags to a value option.

The resolved tri-state lands on ctx.color, the Click-standard attribute that echo() reads through its resolve_color_default() → should_strip_ansi() chain: True keeps ANSI codes, False strips them, None (auto) defers to the output stream’s TTY status.

This option is eager by default, so other eager options (like --version) are rendered with the resolved color state.

Note

--color is deliberately not wired to an envvar. The color environment variables (NO_COLOR, FORCE_COLOR, …) are read manually through resolve_color_env(). Letting Click manage them would dump the whole COLOR_ENVVARS set into the --params env-var column, and only bind one variable per option anyway.

add_to_parser(parser, ctx)[source]¶

Register the option, then teach the parser GNU optional-argument rules.

Click’s optional-value parser binds --color to the next token whenever it does not look like an option, so mycli --color subcommand would consume subcommand as the color value and fail. GNU instead binds an optional argument only when it is attached with =.

This wraps the parser’s long-option matcher so a bare --color replays as --color=<flag_value> (always) and leaves the following argument untouched, while --color=<when> keeps working. The wrapper stays inert for every option that does not carry _gnu_optional_value, so it is safe to install on the shared parser.

Return type:

None

set_color(ctx, param, value)[source]¶

Resolve --color=<WHEN> against the environment and pin ctx.color.

Precedence, highest first:

  1. An explicit --color on the command line.

  2. The color environment variables, but only when the value comes from the built-in default, as for every machine-wide variable (see machine_envvars_apply()). A configuration file or --accessible (both seen here as a non-DEFAULT source) therefore wins over the environment, matching AccessibleOption.

  3. A color state already pinned by --no-color, a forced test runner, or an explicit Context(color=...): preserved when this option only resolves to auto from its default.

  4. The auto default, leaving ctx.color at None for TTY detection.

Whatever branch settles it, the resolution is mirrored process-wide by publish_invocation_color() so output produced from background threads honors it too.

Stays dormant under resilient parsing, like every other eager callback: an introspection context (make_resilient_context(), behind the man-page, tree and completion-spec exporters) is never closed, so publishing from one would leave the process-wide mirror pinned to that context’s environment resolution. A NO_COLOR build environment would then strip the output of every later CLI carrying no color option of its own.

Return type:

None

class click_extra.color.NoColorOption(param_decls=None, *, is_flag=True, default=False, is_eager=True, expose_value=False, help='Disable colorization (alias of --color=never).', **kwargs)[source]¶

Bases: ExtraOption

--no-color flag that forces --color=never.

Click rejects /--no-x secondary flags on a value option, so the negative alias of the tri-state ColorOption cannot live on it and is provided here as a standalone boolean flag. When set, it pins ctx.color to False; when absent it is a no-op, leaving the resolution to ColorOption.

Shown on its own line directly below --color (mirroring --no-config below --config), since every other negative in the default option set is visible too. Eager by default, like ColorOption, so the color state is settled before other eager options render.

set_no_color(ctx, param, value)[source]¶

Force ctx.color off when a negative alias is passed; no-op otherwise.

Dormant under resilient parsing, for the same reason as ColorOption.set_color(): a never-closed introspection context must not publish the process-wide color mirror.

Return type:

None

click_extra.columns module¶

Describe the columns of a table, and select among them.

A ColumnSpec names a column, labels it and documents it, so one declaration feeds the rendered header, the --columns and --sort-by options and the documentation table. click_extra.table renders the columns and click_extra.show_params declares the --params table’s: a home below both is what lets each import the other’s half without a cycle.

class click_extra.columns.ColumnSpec(id, label, description='', max_width=None, optional=False, sortable=True)[source]¶

Bases: object

Rich description of a single column in a rendered table.

Three fields describe the column. description defaults to empty, so a quick prototype does not have to write a sentence for every column:

  • id: stable, snake_case identifier used by --columns to address the column, to key structured-format serializations, and to thread state through click_extra.context.COLUMNS.

  • label: the human-readable header shown at the top of the rendered table.

  • description: a MyST/Markdown blurb describing what the column represents. Used to auto-generate the column reference in the documentation.

The other fields tune presentation and sorting: max_width, optional and sortable.

Note

Frozen: instances are immutable, so a tuple of ColumnSpec can be shared as a module-level constant (like click_extra.show_params.ShowParamsOption.TABLE_HEADERS).

id: str¶

Stable, snake_case identifier addressing this column from CLI flags and code.

label: str¶

Human-readable header label rendered at the top of the table.

description: str = ''¶

MyST/Markdown description of what the column carries.

Used to auto-generate the Available columns section in the docs via the show_params_columns_table MyST substitution. Plain text without inline markup is fine: links and emphasis are optional sugar.

max_width: int | Literal['auto'] | None = None¶

Width limit of this column, as a character count or AUTO_WIDTH.

Cells longer than the limit wrap onto several lines, in the formats able to render that (see WRAPPABLE_FORMATS). None, the default, lets the column take whatever width its widest cell needs.

Declaring the width here rather than passing a positional list to render_table() keeps it attached to its column, so it survives a --columns projection that drops or reorders columns.

optional: bool = False¶

Whether the column is left out of the table until --columns asks for it.

A column carrying long free-form prose costs every other column its width once it joins the default projection, which is a poor trade for a reader who did not ask for it. Marking it optional keeps it out of the unprojected table while leaving it addressable by ID, so a consumer that wants it (a structured-format export feeding a machine, typically) selects it explicitly.

sortable: bool = True¶

Whether --sort-by offers this column and a sort selection matches it.

A column that only annotates its row (free-form notes, a path) still needs a place in the table layout, so a sort key knows where the sortable columns sit, without becoming a sort choice itself.

click_extra.columns.render_columns_markdown_table(columns)[source]¶

Render an iterable of ColumnSpec as a 2-column Markdown table.

Output shape:

| Column | Description |
| :--- | :--- |
| ``Label`` | description |
...

Suitable for inlining into MyST documents via myst_substitutions so the Available columns reference can be auto-generated from a single source of truth.

Return type:

str

click_extra.columns.select_columns(columns, selected_ids)[source]¶

Filter and reorder columns according to selected_ids.

Returns columns unchanged when selected_ids is falsy (no projection). Otherwise yields the matching ColumnSpec in the order selected_ids specifies, SQL-SELECT-style. Raises KeyError for an unknown ID. A selection reaching here through --columns is already checked against the registry by MultiChoice, so that guards a caller assembling selected_ids on its own.

Return type:

tuple[ColumnSpec, ...]

click_extra.columns.select_row(row, selected_ids, canonical_ids)[source]¶

Build a positional row by reading cells from row in the selection order.

Falls back to canonical_ids when selected_ids is empty / unset, so the row preserves its canonical column order in the absence of any user selection.

Return type:

tuple

click_extra.command_doc module¶

Extract a Click command into a structured document and render it.

extract_command_doc() walks a command (and, through iter_command_contexts(), its whole tree) into a CommandDoc: one extraction carrying the man-pages(7) sections documented in Man-page (NAME, SYNOPSIS, DESCRIPTION, OPTIONS, COMMANDS, ENVIRONMENT, FILES and EXIT STATUS). The model then renders to any of the HelpFormat backends: roff (CommandDoc.to_roff()), Markdown (CommandDoc.to_markdown()) and JSON (CommandDoc.to_dict() / CommandDoc.to_json()), with the Carapace completion spec delegated to click_extra.carapace.

The roff backend is Click Extra’s answer to the unmaintained click-man package. It improves on it by:

  • working on a command object via click.Command.make_context(), so it needs no console_scripts entry point;

  • discovering subcommands dynamically through click.Group.list_commands() / click.Group.get_command() with a live context;

  • honoring Click’s \b no-rewrap marker (rendered as roff .nf / .fi);

  • rendering boolean flags (--foo / --no-foo) and skipping hidden commands and options;

  • mirroring Cloup option groups as .SS subsections of OPTIONS (ungrouped options fall under an Other options heading), matching the help screen;

  • emitting ENVIRONMENT (from auto-generated env vars), FILES (from the --config search pattern) and EXIT STATUS sections that click-man never grew.

Font selection follows the man typographic convention encoded by click_extra.theme.LITERAL_STYLES / REPLACEABLE_STYLES: literal tokens (command and option names) render bold (\fB), replaceable tokens (metavars, operands) render italic (\fI).

click_extra.command_doc.MAN_SECTION = '1'¶

Default man page section. Section 1 is for executable programs and shell commands, which is what a Click CLI is.

click_extra.command_doc.DEFAULT_EXIT_STATUS: tuple[tuple[str, str], ...] = (('0', 'Success.'), ('1', 'A runtime error, an aborted prompt (Ctrl-D), or a declined confirmation.'), ('2', 'A usage error: unknown option, invalid value, missing operand, or an unparsable configuration file.'), ('130', 'Interrupted with Ctrl-C: the process ends by SIGINT, reported as 130.'))¶

Conventional exit codes shared by every Click Extra CLI.

Mirrors the EXIT STATUS table in Man-page. Click returns 2 for usage errors (UsageError), 1 for aborts, and 0 on success. A real Ctrl+C ends the process by SIGINT instead, which a shell reports as 130.

click_extra.command_doc.normalize_examples(examples)[source]¶

Validate and freeze a command’s examples into (description, command) pairs.

Accepts any sequence of two-item sequences, so a list of tuples and a list of lists (what a configuration file or a JSON payload would produce) are both fine. None and an empty sequence both yield an empty tuple.

Raises:

TypeError – when an entry is not a pair of strings, naming the offending entry. Raised at command construction, so a malformed example surfaces on import rather than on the first --help a user runs.

Return type:

tuple[tuple[str, str], ...]

class click_extra.command_doc.DocOptionItem(names, metavar, help, required, optional_value=False, choices=())[source]¶

Bases: object

A single OPTIONS entry, extracted from a Click option.

names: tuple[str, ...]¶

All literal spellings: primary opts followed by secondary_opts (so --foo / --no-foo boolean flags render both).

metavar: str | None¶

The rendered metavar, or None when the option takes no value (boolean flags and counters).

help: str | None¶

The option’s help text, possibly carrying a \b no-rewrap marker.

required: bool¶

Whether the option is mandatory.

optional_value: bool = False¶

Whether the option’s value is optional (a bare flag is allowed). Rendered as the attached [=METAVAR] form instead of a space-separated metavar.

choices: tuple[str, ...] = ()¶

Every value the option accepts, for an option whose type enumerates them.

Recorded whatever the metavar shows, so a JSON consumer never has to parse [a|b|c] back out of it. See unlisted_choices for the rendered subset.

property unlisted_choices: tuple[str, ...]¶

The choices the metavar does not already spell out.

A Choice renders as [a|b|c] by default, putting every value on screen already, and repeating them below the help would say the same thing twice. An option overriding that with a short placeholder (--table-format FORMAT) hides them instead, and this is what the man page and the Markdown render add back.

property attached_value: str¶

The [=METAVAR] form of an optional value.

An optional value renders attached and bracketed (--color[=auto|always|never]), the man convention for a flag usable bare. The metavar’s own outer brackets, if any, are stripped so a Choice does not double up.

to_roff()[source]¶

Render this option as a roff tagged paragraph (.TP).

Return type:

list[str]

property spec: str¶

The option’s spelling and value placeholder, as one plain string.

to_markdown()[source]¶

Render this option as a Markdown list item.

A \b no-rewrap region in the help becomes a fenced block indented under the item, rather than being folded into the sentence: the author aligned it on purpose, and a list item can carry a block as well as a paragraph can.

Return type:

list[str]

to_dict()[source]¶

Render this option as a JSON-serializable mapping.

Return type:

dict[str, Any]

class click_extra.command_doc.DocSubcommand(name, short_help, aliases=())[source]¶

Bases: object

One COMMANDS entry: a subcommand as its parent lists it.

name: str¶

The name the subcommand is invoked under.

short_help: str¶

Its one-line description, from full_short_help().

aliases: tuple[str, ...] = ()¶

The other names it answers to, a Cloup feature.

Drawn in parentheses after the name, the way the help screen and --tree draw them: a reader of a generated page learns the short spelling from the same place they learn the command exists.

label(render)[source]¶

The name, then the aliases in parentheses, each passed through render.

Return type:

str

class click_extra.command_doc.DocOptionGroup(options, title=None, help=None)[source]¶

Bases: object

A titled cluster of OPTIONS entries, mirroring a Cloup option group.

A plain Click command, or a Cloup command with no explicit @option_group, yields a single group with title=None: it renders as a flat OPTIONS list with no .SS subsection heading, identical to a man page that never grouped its options.

options: tuple[DocOptionItem, ...]¶

The option entries in this group.

title: str | None = None¶

The subsection heading, rendered as a roff .SS. None for the implicit single group of an ungrouped command (no heading emitted).

help: str | None = None¶

Optional group description, rendered as prose under the heading.

to_roff()[source]¶

Render an optional .SS heading, group help, then the options.

Return type:

list[str]

to_markdown(level=3)[source]¶

Render an optional heading, group help, then the options.

Return type:

list[str]

to_dict()[source]¶

Render this group as a JSON-serializable mapping.

Return type:

dict[str, Any]

class click_extra.command_doc.CommandDoc(name, short_help='', section='1', synopsis_pieces=(), description='', operands=(), option_groups=(), subcommands=(), environment=(), files=(), exit_status=(('0', 'Success.'), ('1', 'A runtime error, an aborted prompt (Ctrl-D), or a declined confirmation.'), ('2', 'A usage error: unknown option, invalid value, missing operand, or an unparsable configuration file.'), ('130', 'Interrupted with Ctrl-C: the process ends by SIGINT, reported as 130.')), examples=(), version=None, date='', manual=None, authors=None, copyright=None)[source]¶

Bases: object

A whole man page in structured form, ready to render to roff.

One CommandDoc maps to one command (or subcommand). Its fields are the man-pages(7) sections, in the order Man-page documents them. Build it with extract_command_doc() and serialize with to_roff().

name: str¶

Full command path, space-joined (like weather forecast).

short_help: str = ''¶

One-line description for the NAME section.

section: str = '1'¶

Man section number.

synopsis_pieces: tuple[str, ...] = ()¶

Usage metavars after the command name ([OPTIONS], CITY, …).

description: str = ''¶

The command’s full help text / docstring for the DESCRIPTION section.

operands: tuple[tuple[str, str], ...] = ()¶

Positional arguments as (metavar, help) pairs.

option_groups: tuple[DocOptionGroup, ...] = ()¶

The OPTIONS entries, partitioned into one or more groups. A command without explicit option groups carries a single untitled group.

subcommands: tuple[DocSubcommand, ...] = ()¶

For groups: the COMMANDS section entries, in listing order.

environment: tuple[tuple[str, str], ...] = ()¶

ENVIRONMENT entries as (variable_name, help) pairs.

files: tuple[str, ...] = ()¶

FILES entries (configuration search patterns).

exit_status: tuple[tuple[str, str], ...] = (('0', 'Success.'), ('1', 'A runtime error, an aborted prompt (Ctrl-D), or a declined confirmation.'), ('2', 'A usage error: unknown option, invalid value, missing operand, or an unparsable configuration file.'), ('130', 'Interrupted with Ctrl-C: the process ends by SIGINT, reported as 130.'))¶

EXIT STATUS entries as (code, meaning) pairs.

examples: tuple[tuple[str, str], ...] = ()¶

EXAMPLES entries as (description, command_line) pairs.

Collected from the command’s own examples attribute (see click_extra.commands.Command.examples). Empty for a command that declares none, in which case every backend omits the section entirely.

version: str | None = None¶

Version string for the .TH header.

date: str = ''¶

Date for the .TH header (YYYY-MM-DD).

manual: str | None = None¶

Manual name for the .TH header (the centered footer title).

authors: str | None = None¶

AUTHORS section content, or None to omit the section.

copyright: str | None = None¶

COPYRIGHT section content, or None to omit the section.

property title: str¶

The .TH page title: the command path, hyphen-joined and upper-cased.

to_roff()[source]¶

Render the full man page as a roff/troff string.

Return type:

str

to_markdown()[source]¶

Render the whole document as Markdown.

Same sections as to_roff(), in the same order, minus the roff .TH header, whose date, section number and manual name describe a man page rather than the command. The version survives, as a line under the title.

Return type:

str

to_dict()[source]¶

Render the whole document as a JSON-serializable mapping.

Subcommands are listed by name and one-line description only, never recursively: a consumer walking a deep tree asks for the child it cares about instead of paying for the whole tree at once. render_help() exposes the recursive variant separately, for the consumers that do want everything.

Return type:

dict[str, Any]

to_json(indent=2)[source]¶

Serialize to_dict() to a JSON string.

Return type:

str

click_extra.command_doc.extract_command_doc(command, ctx, *, version=None, date=None, manual=None, authors=None, copyright=None)[source]¶

Build a CommandDoc from a Click command and its context.

The context must have been created for command (for example via click.Command.make_context() with resilient_parsing=True), so that auto-generated environment-variable prefixes resolve correctly.

A version, date or authors left at None is resolved from the distribution metadata and the build moment, see _fill_overrides.

Return type:

CommandDoc

click_extra.command_doc.iter_command_contexts(command, prog_name=None)[source]¶

Walk a command tree, yielding (path, command, context) for each visible one.

Subcommands are discovered dynamically, through iter_subcommand_contexts(), so dynamically-registered commands are included, each under the name its parent registered it with rather than its own name. Hidden commands are skipped. Each context is built with resilient_parsing=True to avoid triggering required-argument errors, prompts, or eager-option side effects.

Return type:

Iterator[tuple[tuple[str, ...], Command, Context]]

click_extra.command_doc.iter_command_docs(command, prog_name=None, **overrides)[source]¶

Extract every visible command of a tree, yielding (path, doc) pairs.

Walks the tree with iter_command_contexts() and extracts each command into a CommandDoc. The header fields the keyword overrides leave unset (version, date, authors) are resolved once, from the root context, and shared by every page: the pages of one tree name the same program, so they look the same distribution up.

Return type:

Iterator[tuple[tuple[str, ...], CommandDoc]]

click_extra.command_doc.render_manpage(command, prog_name=None, ctx=None, **overrides)[source]¶

Render a single command’s man page as a roff string.

Reuses ctx when given (like the live invocation context), otherwise builds a throwaway one with resilient_parsing=True. Keyword overrides (version, date, manual, authors, copyright) are passed through to extract_command_doc().

Return type:

str

click_extra.command_doc.render_manpages(command, prog_name=None, **overrides)[source]¶

Render the whole command tree, one man page per (sub)command.

Returns an ordered mapping of {filename: roff} where each filename is the command path joined by hyphens plus the section suffix (like weather-forecast.1).

Return type:

dict[str, str]

click_extra.command_doc.write_manpages(command, target_dir, prog_name=None, **overrides)[source]¶

Render the command tree and write each man page into target_dir.

Creates target_dir if missing. Returns the list of written paths.

Return type:

list[Path]

click_extra.command_doc.install_manpages(command, prog_name=None, **overrides)[source]¶

Write the command tree’s man pages where man can find them.

Targets $XDG_DATA_HOME/man/man1 when that variable is set, else ~/.local/share/man/man1, expanded against the HOME in force at the call. Returns the written paths.

The environment is read here rather than at import time, through xdg_dir(), so a caller that sets XDG_DATA_HOME or HOME for one invocation (a test, a packaging script staging into a build root) is honored. This mirrors install_carapace_spec(), whose spec directory resolves the same way.

Return type:

list[Path]

class click_extra.command_doc.HelpFormat(*values)[source]¶

Bases: StrEnum

The formats render_help() renders.

The value is the spelling --help-format takes. Members are ordered alphabetically, which is also the order --help-format advertises them in. Adding a format is a member here, a description in HELP_FORMATS and a branch in render_help(): no new flag, no wider help screen. See Man-page for what each one is good for.

A member prints, compares, hashes and sorts as its value, so a plain string keeps working wherever a format is expected.

CARAPACE = 'carapace'¶
JSON = 'json'¶
JSON_FULL = 'json-full'¶
MAN = 'man'¶
MARKDOWN = 'markdown'¶
MARKDOWN_FULL = 'markdown-full'¶
click_extra.command_doc.HELP_FORMATS: dict[HelpFormat, str] = {HelpFormat.CARAPACE: 'Carapace completion spec (YAML). Doubles as a command-and-flag tree, and is the shape `carapace` itself consumes. Needs the `carapace` extra.', HelpFormat.JSON: 'This command as a JSON object: usage, description, arguments, options grouped as the help screen groups them, environment variables, files, exit codes, and its direct subcommands by name.', HelpFormat.JSON_FULL: 'Every command of the tree as JSON, under a `commands` array, each entry in the `json` shape.', HelpFormat.MAN: 'This command as a man page: the roff source a packager installs, which `--man` typesets for reading.', HelpFormat.MARKDOWN: 'This command as a Markdown document, one section per topic.', HelpFormat.MARKDOWN_FULL: 'Every command of the tree as one Markdown document, in tree order.'}¶

Each HelpFormat, mapped to its one-line description.

Note

The distinction the plain and -full variants draw is progressive disclosure. A plain render describes one command and names its children, so a reader (a tool or an agent, typically) descends one level at a time instead of pulling a whole tree into a context window to answer a question about one leaf. The -full variants exist for the opposite job: generating documentation, or diffing a CLI’s whole surface between two releases.

click_extra.command_doc.INSTALLABLE_FORMATS: frozenset[HelpFormat] = frozenset({HelpFormat.CARAPACE, HelpFormat.MAN})¶

The formats with a canonical place on disk their consumer reads them from.

A man page under a man directory, a Carapace spec under Carapace’s. These are the two renderings that are installed rather than read, which is what lets click-extra wrap offer them a destination (--output-dir, --install) and refuse one to the others. A JSON or Markdown document has no such place: nothing goes looking for it, so stdout and a shell redirection are the whole story.

click_extra.command_doc.render_help(command, help_format, prog_name=None, ctx=None, **overrides)[source]¶

Render command in one of the HelpFormat formats.

Reuses ctx when given (like the live invocation context), otherwise builds a throwaway one with resilient_parsing=True, exactly like render_manpage(). Keyword overrides are passed through to extract_command_doc(), and ignored by the carapace format, which carries no version or authorship of its own.

Raises:

ValueError – on an unknown format, listing the known ones.

Return type:

str

click_extra.command_doc.MAN_TYPESETTERS: dict[str, tuple[tuple[str, ...], ...]] = {'html': (('mandoc', '-Thtml'), ('groff', '-Thtml', '-mandoc')), 'terminal': (('groff', '-man', '-Tutf8', '-rLL={width}n', '-P-c'), ('mandoc', '-Tutf8', '-Owidth={width}'))}¶

The programs typesetting roff, keyed by what they render it to, best first.

Each entry is a command line: the program, then its arguments, where :width: stands for the line length in columns. Both modes run the same two programs. groff is the GNU implementation found nearly everywhere a man page is; mandoc covers the BSDs and Alpine, which ship it instead.

  • terminal: the text format_manpage() sends to the pager for --man, read on stdin.

  • html: the page click_extra.sphinx.manpages publishes beside each man page, read from a file. mandoc comes first there: its HTML gives every section and option a semantic id anchor (#NAME, #SYNOPSIS, #config…), which prose can deep-link to.

Note

-P-c hands -c down to grotty, groff’s terminal driver, pinning the emphasis it produces to the character-backspace pairs strip_overstrike() removes, and read_manpage() with it under --accessible. Left to its own default a grotty recent enough writes SGR escape sequences instead, which that function cannot see: the manual then reaches a screen reader with its emphasis intact, and loses it altogether once the output is not a terminal and the codes are stripped as color. mandoc needs no counterpart: it overstrikes already.

Note

The man binary is deliberately not in this list, even though it is the tool being imitated. Reading roff from stdin is where the implementations diverge: GNU man takes -l -, while the BSD one wants a real file path. Driving the typesetter directly sidesteps a portability problem that buys nothing, since paging is handled here anyway.

click_extra.command_doc.find_typesetters(mode, **fields)[source]¶

Yield the command line of each typesetter installed for mode, best first.

Probes PATH for each program of MAN_TYPESETTERS and skips the absent ones. Each command line starts with the program’s resolved path, and its arguments are filled from fields, like width.

Parameters:

mode (str) – the MAN_TYPESETTERS key naming the output, terminal or html.

Return type:

Iterator[list[str]]

click_extra.command_doc.run_typesetter(argv, roff=None, *, timeout=None)[source]¶

Run a typesetter and return what it wrote to stdout.

The output is read as UTF-8, the encoding groff and mandoc write in whatever the locale of the platform.

Parameters:
  • argv (Sequence[str]) – the command line, as find_typesetters() yields it.

  • roff (str | None) – the man page source, sent on stdin. None sends nothing, for a command line naming the file to read.

  • timeout (float | None) – seconds the typesetter gets before it is stopped.

Raises:
Return type:

str

click_extra.command_doc.format_manpage(roff, width=None)[source]¶

Typeset roff into readable terminal text, or None if nothing can.

Tries each terminal typesetter of MAN_TYPESETTERS in turn and returns the output of the first that succeeds. Returns None when none of them is installed, which the caller is expected to degrade on rather than fail: a CLI that cannot find a typesetter is a CLI running somewhere that never had man pages to begin with (Windows, a slim container), and that is no reason for --man to error.

Parameters:
  • roff (str) – the man page source, as CommandDoc.to_roff() renders it.

  • width (int | None) – line length in columns. Defaults to the terminal’s own, so the result matches what man would have produced in the same window.

Return type:

str | None

click_extra.command_doc.strip_overstrike(text)[source]¶

Remove the character-backspace pairs a roff typesetter emits for emphasis.

A bold N is written N\x08N and an underlined one _\x08N, a convention inherited from line printers that a pager still renders as bold and underline today. Dropping the pair’s first half leaves the plain character.

The terminal-text counterpart of strip_ansi().

Return type:

str

click_extra.command_doc.read_manpage(command, ctx=None)[source]¶

Typeset a command’s manual and send it to the pager.

The reading counterpart of --help-format man, which emits the roff source a packager installs. Falls back to printing that source, with a warning naming what to install, when no typesetter is available: something on screen beats an error, and the source still carries every word of the manual.

Under --accessible the emphasis is stripped and the pager bypassed (echo_via_pager() streams instead). Both matter to the same reader: a pager is a cursor-driven takeover, and overstrike is worse than the ANSI codes accessible mode already removes, since a screen reader voices N\x08NA\x08AM\x08ME\x08E rather than skipping it.

Return type:

None

class click_extra.command_doc.ManOption(param_decls=None, *, is_flag=True, expose_value=False, is_eager=True, help="Read the command's manual page and exit.", **kwargs)[source]¶

Bases: ExtraOption

A pre-configured --man flag that typesets the command’s manual, pages it, and exits.

Eager and value-less, like ShowParamsOption. Part of the default option set injected by default_params(), so every @command and @group exposes it. Use @man_option to add it to a plain Click CLI.

Note

The flag is named --man, not --show-man or --man-page.

In the POSIX, GNU and BSD traditions a program does not emit its own man page through a flag: the page is a separate file read with man <prog>, either hand-written (BSD mdoc) or generated at build time from --help output (GNU help2man). Click Extra already covers that build-time path with write_manpages(), its help2man equivalent.

The one ecosystem that exposes a runtime flag is Perl’s Pod::Usage, whose convention is --help for the brief usage and bare --man for the full manual. --man also lines up with the neighbouring --help and --version informational flags, which use bare nouns with no show- prefix. --show-man and --man-page have no precedent outside Click Extra.

Note

That Perl convention is about reading a manual, so the flag typesets the page and sends it to the pager, the way man itself does. The roff source a build step ships is --help-format man, beside every other artifact this module renders. The two are one question apart: do you want to read the manual, or to ship it?

print_man(ctx, param, value)[source]¶

Typeset the invoked command’s manual, page it, then exit.

Return type:

None

class click_extra.command_doc.HelpFormatOption(param_decls=None, *, expose_value=False, is_eager=True, help='Render the command in the given format and exit.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured --help-format option printing the command in one of the HelpFormat formats and exiting.

Eager and value-taking, unlike its --man neighbour. That bare flag typesets the same page and sends it to the pager, where --help-format man prints its roff source. It stays a flag of its own because a runtime manual flag has its own tradition (see ManOption).

Note

One option carrying a format, rather than one flag per format. A CLI’s option list is the most expensive real estate in its help screen, and every reader pays for it whether or not they will ever export anything: a family of --help-json, --help-markdown and --help-carapace flags would widen the label column of every screen, forever, one line per format anyone ever adds. Here a new format costs a HelpFormat member and nothing on screen.

Note

The rendered output is deliberately colorless whatever --color says. Every format here is meant to be piped into something (a file, a parser, a model), and ANSI escapes in a JSON string or a Markdown fence are noise to all of them. --help remains the colorized human view.

print_help_format(ctx, param, value)[source]¶

Render the invoked command in the requested format, then exit.

Return type:

None

click_extra.commands module¶

Wraps vanilla Click and Cloup commands with extra features.

Click Extra’s commands, groups and contexts subclass their vanilla counterparts, pre-configured with common defaults. The mixins here build custom variants.

click_extra.commands.DEFAULT_HELP_NAMES: tuple[str, ...] = ('--help', '-h')¶

Flags of the help option: every command’s help_option_names, and the flags of help_option().

click_extra.commands.DEFAULT_PRIORITY: Final[float] = 100.0¶

Implicit priority of any subcommand or option left unnumbered.

Priorities order the subcommands of a Group and the options of a Command, lowest first. Anything the author did not number sits on this line, so a lone {"prep": 1} promotes prep without displacing the rest, and a number above 100 demotes.

Note

Priorities are floats, not integers, so a new entry can be wedged between two existing ones without renumbering: 1.5 lands between 1 and 2.

That trick is as old as interactive computing. JOSS, which RAND put online in 1963, required every line number to be a pair of integers separated by a period (1.1, 10.12): a page and a line within it, jointly a step. DEC’s FOCAL carried the scheme to the PDP-8, with steps running from 1.01 to 31.99. BASIC numbered lines with plain integers, and its 10, 20, 30 convention is programmers buying back the same insertion room by hand.

click_extra.commands.EXTRA_OPTION_SETTINGS: tuple[str, ...] = ('show_choices', 'show_envvar')¶

Click Extra context settings forced onto every option when set to non-None.

class click_extra.commands.ExtraOptionGroup(*args, priority=100.0, **kwargs)[source]¶

Bases: OptionGroup

An option group Click Extra draws after the command’s own options.

Cloup lays a help screen out as the explicit option groups first and the ungrouped options last. Click Extra injects a score of its own options into every command, so grouping them under that rule would push the author’s own options below click-extra’s and retitle them Other options. split_option_groups() sends a group carrying this marker past the ungrouped section instead.

Note

The marker mirrors ExtraOption, which Command reads the same way to push click-extra’s own options to the end of params.

Parameters:

priority (float) – rank of the group among the other trailing groups, lowest first. Defaults to DEFAULT_PRIORITY, so a group a CLI author marks this way lands after click-extra’s own.

Contains the information of an option group and identifies it. Note that, as far as the clients of this library are concerned, an OptionGroups acts as a ā€œmarkerā€ for options, not as a container for related options. When you call @optgroup.option(...) you are not adding an option to a container, you are just adding an option marked with this option group.

Added in version 0.8.0: The hidden parameter.

click_extra.commands.DEFAULT_OPTION_GROUPS: Final[tuple[tuple[str, tuple[str, ...]], ...]] = (('Configuration options', ('--config', '--no-config', '--validate-config', '--export-config')), ('Output options', ('--accessible', '--color', '--no-color', '--progress', '--theme', '--table-format')), ('Logging options', ('--verbosity', '--verbose', '--quiet', '--debug')), ('Introspection options', ('--time', '--params', '--tree', '--man', '--help-format', '--version')))¶

Sections default_params() sorts its options into, in rendering order.

Each entry pairs a help-screen heading with the primary flags it collects. The sequence is the order the sections are drawn in, which ExtraOptionGroup carries as a priority so it survives the reshuffling Command does to params.

The last section gathers the options that replace the run instead of configuring it: each one prints and exits. --time is the exception, and sits there because it reports on the run rather than changing what it does.

Caution

Membership is declared, not inferred. Deriving it from the callbacks looks tempting, since each option of the last section ends the run, but --config ends it too when a file fails to load, and would be misfiled.

-h / --help is deliberately absent: Click appends it to every command on its own, so it stays ungrouped and closes the author’s own section, where a reader looks for it first.

click_extra.commands.default_params(screen=None)[source]¶

Default additional options added to @command and @group.

Parameters:

screen (VersionScreen | None) –

a VersionScreen for --version to draw in place of its one-line message. Reach it through the params hook, binding the screen with functools.partial so each decorated command still gets its own fresh option instances:

@group(params=partial(default_params, screen=MY_SCREEN))
def cli():
    pass

Return type:

list[Option]

Caution

The order of options has been carefully crafted to handle subtle edge-cases and avoid leaky states in unit tests.

You can still override this hard-coded order for aesthetic reasons and it should be fine. Your end-users are unlikely to be affected by these sneaky bugs, as the CLI context is going to be naturally reset after each invocation (which is not the case in unit tests).

  1. --time / --no-time

    Hint

    --time is placed at the top of all other eager options so all other options’ processing time can be measured.

  2. --config LOCATION

    Hint

    --config is at the top so it can have a direct influence on the default behavior and value of the other options.

  3. --no-config

  4. --validate-config LOCATION

  5. --export-config FORMAT

  6. --accessible

    Hint

    --accessible is placed before --color and --table-format so it can lower their defaults (via default_map) before they are resolved.

  7. --color / --no-color

  8. --progress / --no-progress

  9. --theme

  10. --params

  11. --table-format FORMAT

  12. --verbosity LEVEL

  13. -v, --verbose

  14. -q, --quiet

  15. --debug

  16. --tree

  17. --man

  18. --help-format FORMAT

  19. --version

  20. -h, --help

    Attention

    This is the option produced by the @click.decorators.help_option decorator.

    It is not explicitly referenced in the implementation of this function.

    That’s because it’s going to be added by Click itself, at the end of the list of options. By letting Click handle this, we ensure that the help option will take into account the help_option_names setting.

Note

The list above is the processing order, and it is the only one these edge-cases care about. The help screen reads a separate presentation order, which the option_priorities argument of @command and @group reshuffles without touching a single callback. See param_priority() and click_extra#544 issue.

Presentation also sorts these options into the sections DEFAULT_OPTION_GROUPS declares, drawn after the command’s own options. The two orders are independent: --time is processed first and rendered last.

click_extra.commands.POSIXLY_CORRECT_ENVVAR: Final[str] = 'POSIXLY_CORRECT'¶

Environment variable that requests strict POSIX argument parsing.

When this variable is present in the environment (regardless of its value, matching GNU getopt semantics), Context forces allow_interspersed_args to False so option parsing stops at the first positional argument.

class click_extra.commands.Context(*args, meta=None, sort_subcommands=None, **kwargs)[source]¶

Bases: Context

Like cloup.Context, but with the ability to populate the context’s meta property at instantiation.

Also pre-seeds color for root contexts (those without a parent) from the color environment variables, so the eager help and version screens honor FORCE_COLOR, NO_COLOR and their siblings (see resolve_color_env()). With none of them set, color stays at Click’s None default, which auto-detects a TTY. Child contexts inherit the color of their parent, as Click does.

When the POSIXLY_CORRECT environment variable is set, this context forces allow_interspersed_args to False so option parsing stops at the first positional argument, as GNU getopt-based tools do. See POSIXLY_CORRECT_ENVVAR.

Carries the sort_subcommands setting read by click_extra.commands.Group.must_sort_subcommands(), so a whole command tree can settle its subcommand listings in one place.

Todo

Propose addition of meta keyword upstream to Click.

Like parent’s context but with an extra meta keyword-argument.

Also pre-seed color from the color environment variables for a parentless context when the user did not provide it, and force allow_interspersed_args to False when POSIXLY_CORRECT is set in the environment.

Parameters:

sort_subcommands (bool | None) – whether groups list their subcommands alphabetically. Inherited from the parent context when left to None, the way Cloup inherits align_sections, so declaring it once on the root group settles every subgroup below it.

formatter_class¶

Use Click Extra’s formatter to colorize the help screen.

alias of HelpFormatter

render_table(table_data, headers=None, table_format=None, sort_key=None, **kwargs)[source]¶

Render a table honoring the invocation’s table options, and return it.

Same contract as click_extra.table.render_table(), with table_format and sort_key defaulting to the values resolved by the --table-format and --sort-by options (read from TABLE_FORMAT and TABLE_SORT_KEY). ctx.meta is shared along the context chain, so this works from any subcommand without reaching for the root context. Without those options in the chain, falls back to the default format and no sort.

Return type:

str

print_table(table_data, headers=None, table_format=None, sort_key=None, **kwargs)[source]¶

Render a table honoring the invocation’s table options, and print it.

The printing counterpart of render_table(): same defaulting of table_format and sort_key from the context’s shared meta, delegating to click_extra.table.print_table() (which also handles ANSI translation and colorization policy).

Return type:

None

class click_extra.commands.Command(*args, report_url=None, version_fields=None, config_schema=None, config_strict=False, schema_strict=False, fallback_sections=(), config_validators=(), included_params=None, excluded_params=None, config_cascade=False, extra_option_at_end=True, option_priorities=None, populate_auto_envvars=True, extra_keywords=None, excluded_keywords=None, examples=(), **kwargs)[source]¶

Bases: _HelpColorsMixin, _WatchedContextMixin, Command

Like cloup.command, with sane defaults and extra help screen colorization.

Like cloup.Command.__init__, with Click Extra’s defaults and parameters.

Parameters:
  • report_url (str | None) – URL of the issue form of the project, like https://github.com/orchard/harvest/issues/new. Set on the root command, an error that the CLI has no rule for then ends the run with a bug report linking to that form, instead of a bare traceback. See invoke().

  • version_fields (dict[str, Any] | None) – dictionary of VersionOption template field overrides forwarded to the version option. Accepts any field from VersionOption.template_fields (like prog_name, version, git_branch). Lets you customize --version output from the command decorator without replacing the default params list.

  • config_strict (bool) – forwarded to the default ConfigOption’s strict setting: configuration keys not matching any CLI parameter raise an error instead of being silently ignored. Like the other config_* and *_params forwards, it spares you from replacing the whole default params list to customize the config option.

  • config_cascade (bool) – forwarded to the default ConfigOption’s cascade setting: auto-discovery layers every configuration file it finds, the most local one winning on key lookup, instead of stopping at the first.

  • excluded_params (Sequence[str] | None) – additional parameter IDs to block from configuration files, merged into the default ConfigOption’s excluded_params blocklist. Additive, unlike the option-level excluded_params which replaces the default blocklist entirely. Items are fully-qualified parameter IDs (like mycli.mail_sources). Mutually exclusive with included_params.

  • extra_keywords (HelpKeywords | None) – a HelpKeywords instance whose entries are merged into the auto-collected keyword set. Use this to inject additional strings for help screen highlighting.

  • excluded_keywords (HelpKeywords | None) – a HelpKeywords instance whose entries are removed from the auto-collected keyword set. Use this to suppress highlighting of specific strings.

  • examples (Sequence[Sequence[str]]) – a sequence of (description, command) string pairs showing the command in use. They are rendered in an Examples: section of the help screen, in the man page, and in every –help-format rendering. A malformed pair raises TypeError here, at command construction, rather than on the first --help a user runs.

  • extra_option_at_end (bool) – reorders all parameters attached to the command, by moving all instances of ExtraOption at the end of the parameter list. The original order of the options is preserved among themselves.

  • option_priorities (Mapping[str, float] | None) – maps an option to its priority in the help screen, relative to DEFAULT_PRIORITY, lowest shown first. Keys are matched against each parameter’s long and short flags first, then its destination name, so the --config / --no-config pair (which shares the config destination) stays addressable one flag at a time. Presentation only: self.params, and with it the order callbacks are evaluated in, is left alone. Positional arguments are never reordered, their sequence being part of the command’s grammar.

  • populate_auto_envvars (bool) – forces all parameters to have their auto-generated environment variables registered. This addresses the shortcoming of click which only evaluates them dynamically. Once registered, the auto-generated environment variables get displayed in the help screen, fixing click#2483 issue. On Windows, environment variable names are case-insensitive, so they are normalized to uppercase.

By default, these Click context settings are applied:

Additionally, these Cloup context settings are set:

Click Extra also adds its own context_settings:

  • show_choices = None (Click Extra feature)

    If set to True or False, will force that value on all options, so we can globally show or hide choices when prompting a user for input. Only makes sense for options whose prompt property is set.

    Defaults to None, which will leave all options untouched, and let them decide of their own show_choices setting.

  • show_envvar = None (Click Extra feature)

    If set to True or False, will force that value on all options, so we can globally enable or disable the display of environment variables in help screen.

    Defaults to None, which will leave all options untouched, and let them decide of their own show_envvar setting. The rationale being that discoverability of environment variables is enabled by the --params option, which is active by default on extra commands. So there is no need to surcharge the help screen.

    This addresses the click#2313 issue.

To override these defaults, you can pass your own settings with the context_settings parameter:

@command(
    context_settings={
        "show_default": False,
        ...
    }
)
context_class¶

alias of Context

report_url: str | None = None¶

URL of the issue form that a bug report links to, or None to report none.

Set from the report_url constructor argument. Declared here so the attribute exists on every command, as invoke() reads it off the root command.

examples: tuple[tuple[str, str], ...] = ()¶

(description, command) pairs showing the command in use.

Normalized from the examples constructor argument by normalize_examples(). Declared here so the attribute exists on every command, whether or not its author passed any: the renderers reading it (help screen, man page, and every HelpFormat backend) then need no guard.

option_priorities: dict[str, float]¶
context_settings: dict[str, Any]¶

an optional dictionary with defaults passed to the context.

param_priority(param)[source]¶

Priority of param in the help screen.

Defaults to DEFAULT_PRIORITY, and is otherwise resolved against option_priorities by trying each of the parameter’s flags in turn, then its destination name.

Important

This orders the help screen alone. The order of self.params decides when each callback fires: click.core.iter_params_for_processing sorts on (not is_eager, position on the command line), and every eager option the user did not type ties on that second key, leaving declaration order as the tie-break. That is what puts --time ahead of everything it measures and --accessible ahead of the --color default it lowers, so the two orders have to be free to disagree.

Positional arguments always resolve to the default: their sequence is part of the command’s grammar, not a matter of presentation.

Return type:

float

split_option_groups()[source]¶

Explicit option groups, split around the ungrouped section.

Hands back the groups drawn before the ungrouped options, then those drawn after. Cloup draws the ungrouped section last, with no setting to move it, which would bury a CLI’s own options under the ones Click Extra injects. So the rule is kept for the groups a CLI author declares, and every ExtraOptionGroup goes past the ungrouped section, ordered by its priority.

Important

This is the one place the section order is decided. The help screen (format_params()), the man page and every other HelpFormat backend (_build_option_groups()), and the completion specs (iter_params_for_display()) all read it, so a CLI never lists its options in one order on --help and another on --help-format man.

Return type:

tuple[tuple[OptionGroup, ...], tuple[OptionGroup, ...]]

get_argument_help_record(arg, ctx)[source]¶

Pair a positional argument’s metavar with its help text.

Reimplements cloup.OptionGroupMixin.get_argument_help_record, which reads the help attribute as is. Resolution goes through resolve_param_help() instead, the same helper the man page and every other HelpFormat backend reads, so an operand carries one description whatever renders it. An argument without help gets an empty string, not None.

Return type:

tuple[str, str]

format_params(ctx, formatter)[source]¶

Draw the parameter sections of the help screen.

Reimplements cloup.OptionGroupMixin.format_params to honor the order split_option_groups() computes, and to title the ungrouped section against the groups the CLI author declared alone. Cloup picks that title by counting every visible group, click-extra’s included, so a command carrying the default options would otherwise never show a plain Options heading.

Return type:

None

main(args=None, prog_name=None, **kwargs)[source]¶

Pre-invocation step that is instantiating the context, then call invoke() within it.

Caution

During context instantiation, each option’s callbacks are called. These might break the execution flow (like --help or --version).

Sets the default CLI’s prog_name to the command’s name if not provided, instead of relying on Click’s auto-detection via the _detect_program_name() method. This is to avoid the CLI being called python -m <module_name>, which is not very user-friendly.

An abort still prints Click’s Aborted!, which Click prints on purpose (pallets/click#2584), but prints it as soon as the abort leaves the command: before the close callbacks run, where Click prints it after them.

A Ctrl+C then ends the process the way an unhandled Ctrl+C does in Python: by SIGINT, once the running threads finish. Click exits with status 1 instead, which tells a calling shell the program handled the interrupt itself, so a shell loop runs on.

The process-wide state the options of Click Extra take for a run leaves with it, a run that fails while parsing included: the log handler they attach to the root logger, the levels the verbosity options set, and the color the color options publish. See click_extra.context._scoped_run.

A standard stream that cannot encode Unicode is switched to UTF-8 before anything prints, and stays so: see force_unicode_output().

Return type:

Any

invoke(ctx)[source]¶

Like parent’s invoke, but prints the Aborted! of an abort at once.

Click prints it once the root context has closed, so after every close callback. See _abort_notice.

Under a root command with a report_url, an error that is not one of the exceptions Click exits with ends the run with a bug report: see report_unexpected_error(). The innermost command catches it, as its context still holds the options of the run. Click’s main() also ends a run on an end of input, like an abort, and on a broken pipe, without a message: both pass through. So does any error of a run that executes the code of another project, like the CLI that click-extra wrap runs.

Return type:

Any

make_context(info_name, args, parent=None, **extra)[source]¶

Like parent’s make_context, but seeds ctx.meta with the raw arguments.

A copy of the raw, pre-parsed arguments goes under RAW_ARGS, which print_params() re-parses to draw the --params table. A root context also records the name the CLI was invoked under, as INVOCATION_NAME.

See also

See click_extra.context.RAW_ARGS for the full rationale and the upstream-proposal notes (related: click#1279).

Return type:

Any

format_examples(ctx, formatter)[source]¶

Write an Examples: section listing the command’s examples.

Each entry renders its description, then the command line it describes, indented behind a $ prompt. A command declaring none writes nothing at all, so a help screen only grows the section when it has something to put in it.

The command lines go out verbatim rather than through formatter.write_text(): an example exists to be copied, and Click’s text wrapper would fold a long one onto a second line mid-token. This is the same call the \b no-rewrap marker makes for help prose.

Nothing here styles anything. The lines land in the formatter’s buffer, which getvalue() runs through keyword highlighting on its way out, so the option names, subcommands and CLI names inside an example are painted by the same pass that paints them everywhere else.

Return type:

None

format_epilog(ctx, formatter)[source]¶

Insert the examples section ahead of the epilog.

Places it after the options and subcommands, which is where a reader arrives once they know what the command accepts, and keeps the author’s own epilog as the last word on the screen.

Return type:

None

parse_args(ctx, args)[source]¶

Like parent’s parse_args but with better error messages for single-dash multi-character tokens.

Also settles the presentation options before delegating, so --color, --no-color, --accessible and --theme reach the eager help and version screens regardless of their position on the command line. See _resolve_presentation_eagerly.

Return type:

list[str]

class click_extra.commands.ColorizedCommand(name, context_settings=None, callback=None, params=None, help=None, epilog=None, short_help=None, options_metavar='[OPTIONS]', add_help_option=True, no_args_is_help=False, hidden=False, deprecated=False)[source]¶

Bases: _HelpColorsMixin, _WatchedContextMixin, Command

Click Command with help colorization but no extra params.

Mixes in _HelpColorsMixin for keyword highlighting and uses Context for the colorized formatter, without inheriting from Command (which would inject default_params).

Watches what its run ends on, like Command: a patched CLI runs under Click’s own main(), inside the wrap command, and the watch is what tells that command a Ctrl+C ended its target.

Use this as a base for lightweight subcommands (like help) or for monkey-patching third-party CLIs (via patch_click()).

context_class¶

alias of Context

class click_extra.commands.ColorizedGroup(name=None, commands=None, invoke_without_command=False, no_args_is_help=None, subcommand_metavar=None, chain=False, result_callback=None, **kwargs)[source]¶

Bases: _HelpColorsMixin, _WatchedContextMixin, Group

Click Group with help colorization but no extra params.

Same as ColorizedCommand but for groups.

context_class¶

alias of Context

class click_extra.commands.HelpCommand(name, context_settings=None, callback=None, params=None, help=None, epilog=None, short_help=None, options_metavar='[OPTIONS]', add_help_option=True, no_args_is_help=False, hidden=False, deprecated=False)[source]¶

Bases: _InjectedCommand

Synthetic subcommand that displays help for the parent group or a subcommand.

Auto-injected into every Group. Supports nested resolution: mycli help subgroup subcmd shows the help for subcmd within subgroup.

invoke(ctx)[source]¶

Resolve the command path and display its help.

Return type:

None

class click_extra.commands.Group(*args, help_command=True, sort_subcommands=None, subcommand_priorities=None, **kwargs)[source]¶

Bases: Command, Group

Like cloup.Group, with sane defaults and extra help screen colorization.

Like Command.__init__, but auto-injects a help subcommand.

Parameters:
  • help_command (bool) – when True (the default), a help subcommand is automatically registered. Set to False to suppress it, or register your own help subcommand to override it.

  • sort_subcommands (bool | None) – how subcommands sharing a priority are broken apart. True lists them alphabetically, False in the order they were registered. None (the default) defers to the sort_subcommands context setting, then to True. See must_sort_subcommands().

  • subcommand_priorities (Mapping[str, float] | None) – maps a subcommand name to its priority relative to DEFAULT_PRIORITY, lowest listed first. Names left out keep the default priority, so numbering a few subcommands moves only those.

command_class¶

Makes commands of a Group be instances of Command.

That way all subcommands created from a Group benefits from the same defaults and extra help screen colorization.

See: https://click.palletsprojects.com/en/stable/api/#click.Group.command_class

alias of Command

group_class¶

Let Group produce sub-groups that are also of Group type.

See: https://click.palletsprojects.com/en/stable/api/#click.Group.group_class

alias of type

subcommand_priorities: dict[str, float]¶
must_sort_subcommands(ctx)[source]¶

Resolve whether subcommand listings are alphabetical.

Reads the group’s own sort_subcommands, then the context setting of the same name, then falls back to True. This is the resolution order Cloup uses for align_sections, and it is what lets a single context_settings={"sort_subcommands": False} on the root group reach every subgroup below it instead of being repeated on each.

Return type:

bool

subcommand_priority(name)[source]¶

Priority of the name subcommand.

Defaults to DEFAULT_PRIORITY.

Return type:

float

listed_command(ctx, name)[source]¶

The command the help screen describes under name: the subcommand.

The extension point LazyGroup overrides to describe a lazy subcommand by the help it declares, without importing it. The keyword highlighting of the help screen reads the subcommands through here.

Return type:

Command | None

list_commands(ctx)[source]¶

Subcommand names in presentation order.

Sorted on subcommand_priorities first, then broken apart by must_sort_subcommands(): alphabetically, or by registration order. With no priority declared every subcommand ties, leaving the tie-break as the only ordering, which is Click’s plain alphabetical listing.

In registration order the auto-injected subcommands, like help, are listed last, wherever they happen to have been registered: Group.__init__ appends help before any @cli.command() decorator runs, while a commands=[…] constructor argument lands it after, so its natural position says nothing about the author’s intent. Mirrors what extra_option_at_end does to options.

Return type:

list[str]

list_sections(ctx, include_default_section=True)[source]¶

Like cloup.Group.list_sections, but ordering the default section.

Cloup hard-codes the default section to Section.sorted(…), which is why overriding list_commands() alone leaves the help screen alphabetical: the screen is rendered from sections and never calls it. Rebuild that section from list_commands() instead, and hand it over already ordered.

Note

Sections the author declared themselves are returned untouched. Cloup’s own Section(is_sorted=…) already governs those, and a user holding a Section instance should not have it rewritten underneath them. Priorities and sort_subcommands therefore address the default section and the flat listings (--tree, man pages, completion specs), not the contents of an explicit section.

Return type:

list[Section]

add_command(cmd, name=None, **kwargs)[source]¶

Like cloup.Group.add_command, but a subcommand of the author’s replaces an auto-injected one of the same name, like the help subcommand.

Return type:

None

class click_extra.commands.LazySubcommand(import_path, section=None, fallback_to_default_section=True, short_help=None)[source]¶

Bases: object

Declaration of a lazily-imported subcommand of a LazyGroup.

Carries the registration settings cloup.Group.add_command() accepts, which a bare import path cannot express. A subcommand needing none of them is declared as a plain string instead.

import_path: str¶

Where to import the command object from, as "<module-name>.<command-name>".

section: Section | None = None¶

Help-screen section the subcommand is filed under, once imported.

A section declared here is registered on the group right away, so the help screen orders its sections as they are declared, not as their subcommands happen to be imported. The same Section instance can be shared with eagerly-registered subcommands.

fallback_to_default_section: bool = True¶

Whether to file the subcommand under the default section when section is None.

Set to False to leave the subcommand out of every section, which hides it from the help screen while keeping it invocable. Cloup calls this an escape hatch for internal code: do not disable it unless you know what you are doing.

short_help: str | None = None¶

The first paragraph of the subcommand’s help, for the help screen to list.

Declared, it lets the group’s help screen list the subcommand without importing it: the listing shortens it the way it shortens the help of an imported subcommand, so the line reads the same before and after the import. Left to None, drawing the help screen imports the subcommand to read its help.

class click_extra.commands.LazyGroup(*args, lazy_subcommands=None, **kwargs)[source]¶

Bases: Group

A Group that supports lazy loading of subcommands.

Hint

This implementation is based on the snippet from Click’s documentation: Defining the lazy group.

It has been extended to work with Click Extra’s config_option in click_extra#1332 issue.

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.

lazy_subcommands: dict[str, LazySubcommand]¶
get_command(ctx, cmd_name)[source]¶

Get a command by name, loading lazily if necessary.

Return type:

Command | None

listed_command(ctx, name)[source]¶

Like the parent, but describing a lazy subcommand not imported yet by the stand-in its short_help builds.

Return type:

Command | None

click_extra.context module¶

Click context plumbing: the central registry of every ctx.meta key Click Extra writes or reads.

The Context subclass lives in click_extra.commands, beside the commands that create it.

Click’s click.Context.meta is a per-invocation dict that Click shares across the parent/child context hierarchy. Click Extra uses it to pass per-invocation state (the picked theme, the resolved table format, the loaded configuration, etc.) between eager callbacks and the rest of the CLI without mutating module-level globals. Per-invocation context storage is what keeps back-to-back invocations of the same CLI (Sphinx builds, test runners, REPLs) from leaking state into each other.

This module is part of Click Extra’s public API. Inside any @command- or @group-decorated function, request the active context with click.pass_context() (or call click.get_current_context()) and read the entries you need:

from click_extra import command, context, echo, pass_context


@command
@pass_context
def cli(ctx):
    echo(f"Theme: {ctx.meta[context.THEME]}")
    echo(f"Jobs:  {ctx.meta[context.JOBS]}")

Each constant below documents who writes the entry, when, and what shape the value takes. The raw string values are stable and downstream code may also read ctx.meta["click_extra.<field>"] directly: the constants exist so internal call sites and downstream code can converge on a single spelling.

click_extra.context.META_NAMESPACE: Final[str] = 'click_extra.'¶

Prefix shared by every ctx.meta key Click Extra writes.

Reserved for entries the framework owns. Downstream consumers picking their own ctx.meta keys are encouraged to use a different prefix to avoid colliding with current or future Click Extra entries.

click_extra.context.RAW_ARGS: Final[str] = 'click_extra.raw_args'¶

The raw, pre-parsed argv slice fed to the current command.

Written by click_extra.commands.Command.make_context so that click_extra.show_params.ShowParamsOption can re-parse the original arguments for the --params table without re-running the callbacks. Consumers normalize the parser’s UNSET sentinel back to None on read, matching what click.Command.parse_args does for ctx.params.

Todo

Open a narrowly-scoped Click issue and PR for a public click.Context accessor returning a parameter’s resolved (value, ParameterSource) after parsing, without re-firing eager callbacks. That is the forward resolution a live CLI needs: landing it retires the replay behind the --params table and the configuration dump. The click-extra wrap --params path keeps this constant and its replay, because Click never parses the foreign CLI it renders.

Reference pallets/click#1279 as related, not as home: it asks for the inverse direction (reconstructing a normalized argv from a Context), was scoped with about a dozen normalization rules, flagged underdefined, and has stalled since 2023. Tracked in docs/upstream.md under ā€œNormalized argumentsā€; the developer note below records why the cheaper alternatives do not work.

click_extra.context.INVOCATION_NAME: Final[str] = 'click_extra.invocation_name'¶

The name the CLI was invoked under, as resolved on the root context.

Written by click_extra.commands.Command.make_context on the root context only (ctx.meta is shared down the whole hierarchy, so a subcommand must not overwrite it). Equals Click’s root info_name: the entry-point script name, the symlink name in multicall personality mode, or an explicit prog_name override passed to main(). Read it with click.pass_context() to implement invocation-name-aware behavior without the full multicall machinery:

if ctx.meta[context.INVOCATION_NAME] == "bunzip2":
    ...
click_extra.context.CONF_SOURCE: Final[str] = 'click_extra.conf_source'¶

Resolved path or URL of the configuration file that was loaded.

Written by click_extra.config.option.ConfigOption.load_conf after a configuration file is found and parsed. None if no file matched.

click_extra.context.CONF_FULL: Final[str] = 'click_extra.conf_full'¶

Full parsed configuration document (the whole file, every section).

Written by click_extra.config.option.ConfigOption.load_conf. Read by click_extra.commands.Group (for subcommand inheritance) and by click_extra.cli_wrapper.invoke_target() (to forward the loaded config to wrapped CLIs).

With cascade=True this holds the deep-merged view of every loaded file, which is the configuration as it was actually applied.

click_extra.context.CONF_SOURCES: Final[str] = 'click_extra.conf_sources'¶

Every configuration file loaded, in precedence order (highest first).

Written by click_extra.config.option.ConfigOption.load_conf as a (possibly empty) tuple of (location, parsed_conf) pairs. Holds a single entry in the default first-file-wins mode, and one entry per loaded file when cascade=True.

click_extra.context.TOOL_CONFIG: Final[str] = 'click_extra.tool_config'¶

The app-specific config section, deserialized through config_schema.

Written by load_conf() when a config_schema is set. Read via click_extra.config.schema.get_tool_config().

click_extra.context.SUBCOMMANDS_APPLIED: Final[str] = 'click_extra.subcommands_applied'¶

Command paths whose reserved subcommand keys were already spliced in.

Written by click_extra.config.subcommands.inject_reserved_subcommands() as a growing set of ctx.command_path strings. This meta dict is shared by the whole context tree, so the set is what tells one group’s injection from another’s, and what keeps a second pass over the same group from prepending its _prepend_subcommands twice.

click_extra.context.VERBOSITY_LEVEL: Final[str] = 'click_extra.verbosity_level'¶

The reconciled LogLevel chosen for the run.

Written by _VerbosityOption.apply_verbosity, which reconciles every verbosity-related option (--verbosity, --verbose/-v and --quiet/-q) into a single level. Read by the same method to detect whether the reconciled level changed since a sibling option last fired.

click_extra.context.VERBOSITY: Final[str] = 'click_extra.verbosity'¶

Raw value of --verbosity LEVEL as the user passed it.

Written by click_extra.logging.VerbosityOption.set_level(). Stored alongside VERBOSITY_LEVEL so downstream code can tell whether the final level came from --verbosity or from -v/-q repetitions.

click_extra.context.DEBUG: Final[str] = 'click_extra.debug'¶

Whether --debug was passed.

Written by the set_level callback of click_extra.logging.DebugOption. Read by _VerbosityOption.resolve_level, which answers it before anything else: --debug names the loudest level there is, so nothing another option asks for can outrank it.

click_extra.context.VERBOSE: Final[str] = 'click_extra.verbose'¶

Raw repetition count of --verbose/-v.

Written by the set_level callback of click_extra.logging.VerboseOption. Combined with QUIET into the signed verbose - quiet counter that _VerbosityOption.resolve_level shifts the base level by.

click_extra.context.QUIET: Final[str] = 'click_extra.quiet'¶

Raw repetition count of --quiet/-q.

Written by the set_level callback of click_extra.logging.QuietOption. The quiet counterpart of VERBOSE: each -q subtracts one step from the verbose - quiet net applied on top of the base verbosity level.

click_extra.context.START_TIME: Final[str] = 'click_extra.start_time'¶

time.perf_counter() snapshot taken when --time is enabled.

Written by click_extra.execution.TimerOption.init_timer.

click_extra.context.JOBS: Final[str] = 'click_extra.jobs'¶

Effective parallel job count after clamping (always >= 1).

Written by click_extra.jobs.JobsOption.validate_jobs. Click Extra itself does not act on this value: it is a contract for downstream commands that drive their own concurrency.

click_extra.context.TABLE_FORMAT: Final[str] = 'click_extra.table_format'¶

The TableFormat chosen via --table-format.

Written by click_extra.table_options.TableFormatOption.init_formatter. Read by render_table() and print_table() as their default format.

click_extra.context.SORT_BY: Final[str] = 'click_extra.sort_by'¶

Tuple of column IDs picked via --sort-by (in priority order).

Written by click_extra.table_options.SortByOption.init_sort.

click_extra.context.TABLE_SORT_KEY: Final[str] = 'click_extra.table_sort_key'¶

Row sort key derived from the --sort-by selection.

Written by click_extra.table_options.SortByOption.init_sort when its column definitions are known at declaration time (labeled mode). Read by render_table() and print_table() as their default sort_key. Absent in field-vocabulary mode, where the sort is resolved per table by click_extra.table.print_table() from the column IDs its headers carry.

click_extra.context.COLUMNS: Final[str] = 'click_extra.columns'¶

Tuple of column IDs selected via --columns (in display order).

Written by click_extra.table_options.ColumnsOption.init_columns. Read by table-rendering consumers (like click_extra.show_params.ShowParamsOption) to project and reorder columns before emitting the table. Empty / unset means no projection: render every column in its canonical order.

click_extra.context.THEME: Final[str] = 'click_extra.theme.active'¶

The HelpTheme active for this invocation.

Written by click_extra.theme.ThemeOption.set_theme. Read via click_extra.theme.get_current_theme(), which falls back to click_extra.theme.default_theme when no key is set.

click_extra.context.THEME_OVERRIDES: Final[str] = 'click_extra.theme.overrides'¶

Per-invocation theme registry overlay loaded from the user’s config file.

Written by click_extra.config.option.ConfigOption when it sees [tool.<cli>.themes.<name>] tables: each table is built into a HelpTheme (cascading on top of an existing theme when name matches one already in theme_registry). Read by click_extra.theme.get_theme_registry() so --theme can pick the new themes without leaking them into sibling invocations sharing the same process.

click_extra.context.TELEMETRY: Final[str] = 'click_extra.telemetry'¶

True if the user opted into telemetry, False otherwise.

Written by click_extra.telemetry.TelemetryOption.set_telemetry after reconciling --telemetry / --no-telemetry with the standard DO_NOT_TRACK environment variable. Downstream code reads this to decide whether to emit usage data.

click_extra.context.PROGRESS: Final[str] = 'click_extra.progress'¶

True when the CLI may display progress spinners, False otherwise.

Written by click_extra.spinner.ProgressOption.set_progress from the --progress / --no-progress flag (which --accessible lowers to False). Spinner, OperationTrail and progressbar() read it on their own when left at their automatic default.

Deliberately independent of color: a spinner is an interactivity concern, so it is gated on the terminal (TTY / TERM=dumb, handled by the spinner) and on explicit intent (--no-progress / --accessible), never on --no-color / NO_COLOR. See ProgressOption for the rationale.

click_extra.context.ACCESSIBLE: Final[str] = 'click_extra.accessible'¶

True when the user requested screen-reader-friendly output.

Written by set_accessible() after reconciling the --accessible flag with the ACCESSIBLE environment variable. Read by output helpers that must degrade a cursor-driven element to a linear stream: clear() becomes a no-op and echo_via_pager() writes its text straight to stdout instead of spawning a pager.

This is the readable counterpart to the --color / --progress / --table-format defaults that --accessible also lowers: those are consumed through their own resolved values (ctx.color, PROGRESS, the table format), while this flag exposes the accessibility intent itself.

click_extra.context.ZERO_EXIT: Final[str] = 'click_extra.zero_exit'¶

True when the user asked the CLI to always return a zero exit code.

Written by click_extra.execution.ZeroExitOption.set_zero_exit. Click Extra itself does not act on this value: it is a contract for downstream commands that suppress their non-zero ā€œproblems foundā€ exit code and return 0 as long as the run itself succeeded.

click_extra.context.pass_context(func)[source]¶

Mark a callback as wanting the active Context as its first argument.

Click’s own click.pass_context() is typed for the base click.Context. A handler annotated with click-extra’s enhanced Context (to reach its extra helpers like ctx.print_table) therefore fails static type checking: function parameters are contravariant, so Callable[[Context], R] is not assignable where a Callable[[click.Context], R] is expected.

This drop-in is typed for the enhanced Context and still accepts handlers typed for the base click.Context (a wider first parameter is allowed), so both type-check. At runtime it forwards the active context unchanged, exactly like click.pass_context().

Return type:

Callable[P, R]

click_extra.context.get(ctx, key, default=None)[source]¶

Read key from the current context’s shared meta dict.

Equivalent to ctx.meta.get(key, default). Click’s meta is shared across the parent/child hierarchy, so reading from the local context is sufficient: there is no need to walk up to the root manually.

Return type:

Any

click_extra.context.set(ctx, key, value)[source]¶

Write value under key in the current context’s shared meta dict.

Equivalent to ctx.meta[key] = value. Provided as the symmetric writer for get() so that callers can route both sides of a meta access through this module.

Return type:

None

click_extra.context.setdefault(ctx, key, factory)[source]¶

Read key from the shared meta dict, first storing factory() if missing.

factory runs for a missing key only, so each invocation gets a mutable value of its own, like the set of command paths a run marks.

Return type:

Any

click_extra.decorators module¶

Decorators for group, commands and options.

click_extra.decorators.allow_missing_parenthesis(dec_factory)[source]¶

Allow to use decorators with or without parenthesis.

As proposed in Cloup issue #127.

click_extra.decorators.decorator_factory(dec, *new_args, **new_defaults)[source]¶

Clone decorator with a set of new defaults.

Overloads:
  • dec (Any), *new_args (Any), cls (type[CommandT_co]), **new_defaults (Any) → CommandDecorator[CommandT_co]

  • dec (Any), *new_args (Any), cls (type[ParamT] | None) = ..., **new_defaults (Any) → ParameterDecorator

Builds Click Extra’s decorators for its own commands and options out of Cloup’s.

The two overloads give static type checkers a precise signature for the decorators this factory produces: command-style decorators (cls is a click.Command subclass) report the resulting command class, while parameter-style decorators (cls is a click.Parameter subclass, or absent) return the decorated callback unchanged. Both overloads model the optional-parenthesis behaviour added by allow_missing_parenthesis, which plain inference cannot recover. See CommandDecorator and ParameterDecorator for the produced shapes.

Attention

The cls argument passed to the factory is used as the reference class from which the produced decorator’s cls argument must inherit.

That way the @command decorator re-implemented by Click Extra always produces a subclass of Command, even when the user overrides the cls argument, so it can rely on the properties and methods Click Extra adds on top of Cloup and Click.

click_extra.decorators.command(*args, **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.group(*args, **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.option(*args, group=None, **attrs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.argument(param_decls, required=None, help=None, **attrs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.help_option(*args, **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.version_option(version=None, *param_decls, cls=<class 'click_extra.version.VersionOption'>, group=None, **kwargs)[source]¶

Attach a VersionOption to a command.

Drop-in compatible with Click’s @version_option: the first positional argument may be an explicit version string. click-extra otherwise auto-detects the version and treats positional arguments as option flags (like every other option decorator), so the two are disambiguated by their leading character: a value starting with - is a flag declaration, anything else is a Click-style version string forwarded into the version template field.

@command
@version_option("1.2.3")  # Click idiom: pins the displayed version.
def my_cmd(): ...

Note

Hand-written instead of produced by decorator_factory() because Click’s leading version positional conflicts with the param_decls-first convention the factory relies on.

click_extra.decorators.lazy_group(*args, **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.multicall_group(*args, **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.accessible_option(param_decls=None, *, is_flag=True, default=False, is_eager=True, expose_value=False, help='Accessibility mode: disable colors and render tables in a borderless, screen-reader-friendly format.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.color_option(param_decls=None, *, is_flag=False, flag_value='always', default='auto', is_eager=True, expose_value=False, help='Colorize the output. A bare --color is the same as --color=always.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.columns_option(param_decls=None, *, columns=None, type=None, metavar='COLUMNS', default=(), expose_value=False, is_eager=True, help='Restrict and reorder table columns, SQL SELECT-style. Comma-separated list of column IDs. Default: all columns in canonical order.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.config_option(param_decls=None, *, metavar='LOCATION', type=UNPROCESSED, help='Location of the configuration file. Supports local path with glob patterns or remote URL.', is_eager=True, expose_value=False, file_format_patterns=None, file_pattern_flags=None, show_file_patterns=None, roaming=True, force_posix=False, search_pattern_flags=None, search_parents=False, stop_at=Sentinel.VCS, cascade=False, excluded_params=None, included_params=None, strict=False, config_schema=None, schema_strict=False, fallback_sections=(), config_validators=(), **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.debug_option(param_decls=None, *, default_logger='root', is_flag=True, default=False, help='Shorthand for --verbosity DEBUG.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.export_config_option(param_decls=None, *, type=None, metavar='FORMAT', is_eager=True, expose_value=False, help='Export the configuration in the selected format to <stdout>, then exit.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.help_format_option(param_decls=None, *, expose_value=False, is_eager=True, help='Render the command in the given format and exit.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.jobs_option(param_decls=None, *, default='auto', expose_value=False, show_default=True, type=<click_extra.jobs.JobCount object>, help="Number of parallel jobs. Accepts an integer, auto (the host's logical CPUs, minus one when there are three or more) or max (all logical CPUs). --jobs 0 runs sequentially.", **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.man_option(param_decls=None, *, is_flag=True, expose_value=False, is_eager=True, help="Read the command's manual page and exit.", **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.no_color_option(param_decls=None, *, is_flag=True, default=False, is_eager=True, expose_value=False, help='Disable colorization (alias of --color=never).', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.no_config_option(param_decls=None, *, help='Ignore all configuration files and only use command line parameters and environment variables.', is_flag=True, flag_value=Sentinel.NO_CONFIG, is_eager=True, expose_value=False, **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.progress_option(param_decls=None, *, is_flag=True, default=True, is_eager=True, expose_value=False, help='Show progress indicators during long operations. Disabled for non-interactive output (pipes, dumb terminals, CI) and by --accessible.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.quiet_option(param_decls=None, **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.show_params_option(param_decls=None, *, is_flag=True, expose_value=False, is_eager=True, help='Show all CLI parameters, their provenance, defaults and value, then exit.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.table_format_option(param_decls=None, *, type=EnumChoice('aligned', 'asciidoc', 'colon-grid', 'csv', 'csv-excel', 'csv-excel-tab', 'csv-unix', 'double-grid', 'double-outline', 'fancy-grid', 'fancy-outline', 'github', 'grid', 'heavy-grid', 'heavy-outline', 'hjson', 'html', 'jira', 'json', 'json5', 'jsonc', 'latex', 'latex-booktabs', 'latex-longtable', 'latex-raw', 'mediawiki', 'mixed-grid', 'mixed-outline', 'moinmoin', 'orgtbl', 'outline', 'pipe', 'plain', 'presto', 'pretty', 'psql', 'rounded-grid', 'rounded-outline', 'rst', 'simple', 'simple-grid', 'simple-outline', 'textile', 'toml', 'tsv', 'unsafehtml', 'vertical', 'xml', 'yaml', 'youtrack'), metavar='FORMAT', default=TableFormat.ROUNDED_OUTLINE, expose_value=False, is_eager=True, help='Rendering style of tables.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.telemetry_option(param_decls=None, *, default=False, expose_value=False, envvar=None, show_envvar=True, help='Collect telemetry and usage data.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.theme_option(param_decls=None, *, default='dark', is_eager=True, expose_value=False, query_background=False, help='Color theme used for help screens.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.timer_option(param_decls=None, *, default=False, expose_value=False, is_eager=True, help='Measure and print elapsed execution time.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.tree_option(param_decls=None, *, is_flag=True, expose_value=False, is_eager=True, help='Show the tree of nested subcommands and exit.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.validate_config_option(param_decls=None, *, type=UNPROCESSED, metavar='LOCATION', is_eager=True, expose_value=False, help='Validate the configuration file and exit.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.verbose_option(param_decls=None, **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.verbosity_option(param_decls=None, *, default_logger='root', default=LogLevel.WARNING, metavar='LEVEL', type=EnumChoice('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'), help='Either CRITICAL, ERROR, WARNING, INFO, DEBUG.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.zero_exit_option(param_decls=None, *, default=False, expose_value=False, is_flag=True, help='Always exit with a status code of 0, even when problems are found.', **kwargs)¶

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.sort_by_option(*header_defs, cls=<class 'click_extra.table_options.SortByOption'>, group=None, **kwargs)[source]¶

Attach a SortByOption to a command.

Forwards the positional header_defs (ColumnSpec instances or bare column IDs) straight to the option constructor and registers it with the same _param_memo primitive Cloup uses, so the --sort-by option composes with @option_group and @constraint like any other option decorator.

Note

Hand-written instead of produced by decorator_factory() because SortByOption accepts its column definitions as positional arguments, which conflicts with the param_decls-first convention the factory relies on. Routing through the factory would force them into a keyword.

click_extra.envvar module¶

Implements environment variable utilities.

click_extra.envvar.parse_envvar_flag(value)[source]¶

Read an environment flag’s value as a boolean, permissively.

The single interpretation shared by the flag-like variables Click Extra reads by hand as booleans (ACCESSIBLE, DO_NOT_TRACK): the value is read as one of the boolean spellings BOOLEAN_STATES lists, in any case and with surrounding whitespace ignored, and anything else counts as activation, the empty string included: the variable’s bare presence is the signal. The color variables are not read this way: each follows its own convention, see resolve_color_env().

Callers handle presence themselves: pass the value only when the variable is set, an unset variable being no vote at all.

Return type:

bool

click_extra.envvar.machine_envvars_apply(ctx, param)[source]¶

Whether the machine-wide environment variables may set the value of param.

A machine-wide variable speaks for every CLI on the machine, like ACCESSIBLE, CLICK_EXTRA_THEME or NO_COLOR. It fills in only where nothing more specific set the value: the command line, the variable of the option itself and a configuration file each outrank it. So it applies only while param holds its built-in default.

Call it from the callback of param, once Click recorded where the value came from.

Return type:

bool

click_extra.envvar.normalize_envvar_id(envvar_id)[source]¶

Spell an environment variable name the way the running platform reads it.

Windows looks variables up case-insensitively, and the standard library upper-cases every name it stores: see merge_envvar_ids(). Every other platform keeps the name as given.

Return type:

str

click_extra.envvar.merge_envvar_ids(*envvar_ids)[source]¶

Merge and deduplicate environment variables.

Multiple parameters are accepted and can be single strings or arbitrary-nested iterables of strings. None values are ignored.

Variable names are deduplicated while preserving their initial order.

Returns a tuple of strings. The result is ready to be used as the envvar parameter for Click’s options or arguments.

Return type:

tuple[str, ...]

click_extra.envvar.clean_envvar_id(envvar_id)[source]¶

Utility to produce a user-friendly environment variable name from a string.

Separates all contiguous alphanumeric string segments, eliminate empty strings, join them with an underscore and uppercase the result.

Return type:

str

click_extra.envvar.param_auto_envvar_id(param, ctx)[source]¶

Compute the auto-generated environment variable of an option or argument.

Returns the auto envvar exactly as computed within Click’s internals, by click.core.Parameter.resolve_envvar_value() and click.core.Option.resolve_envvar_value().

Return type:

str | None

click_extra.envvar.param_envvar_ids(param, ctx)[source]¶

Returns the deduplicated, ordered list of environment variables for an option or argument, including the auto-generated one.

The auto-generated environment variable is added at the end of the list, so that user-defined envvars takes precedence. This respects the current implementation of click.core.Option.resolve_envvar_value().

Names are normalized to uppercase on Windows by merge_envvar_ids().

Return type:

tuple[str, ...]

click_extra.envvar.temporary_env(set_vars=None, unset_vars=())[source]¶

Apply environment variable changes for the block’s duration, then restore.

set_vars are written into os.environ and unset_vars removed. On exit, every touched variable is restored to its pre-block state: recreated with its former value, or removed when it did not exist before.

The process environment is patched directly (not through test-framework fixtures) so the helper serves production code paths and test harnesses alike, with a single restore discipline.

Return type:

Generator[None, None, None]

click_extra.envvar.env_copy(extend=None)[source]¶

Returns a copy of the current environment variables, updated with extend.

Mimics Python’s original implementation by returning None when extend is empty or missing, so a child process inherits the environment unchanged.

A None value removes its variable from the copy instead of setting it, which is the only way to hide an inherited variable from a child process: assigning the empty string leaves it set, and a flag read by bare presence (see parse_envvar_flag()) counts that as activation. Same convention as click.testing.CliRunner.invoke()’s own env argument, and the reason TEnvVars values are typed optional.

Return type:

dict[str, str] | None

click_extra.execution module¶

Options and primitives controlling how CLIs run.

Two altitudes live here. The higher one governs the CLI being authored: the pre-configured ExtraOption subclasses TimerOption and ZeroExitOption publish their resolved value on ctx.meta. The --jobs option, and the fan-out primitives that parallelize work per its count, are in click_extra.jobs.

The lower one runs foreign CLIs in subprocesses, for tools that wrap other programs: run_cli() spawns one command, disclosing its invocation to the logger and streaming its output live, while install_interrupt_handler() and terminate_live_processes() make Ctrl+C abort in-flight children cleanly. args_cleanup() and format_cli_prompt() are the shared serialization and disclosure atoms both altitudes (and click_extra.testing) build upon.

click_extra.execution.is_windows()[source]¶

Whether the running platform is Windows, per extra_platforms.

A thin wrapper around extra_platforms.is_windows() with a deferred import, which keeps extra_platforms off the startup path of every CLI. Kept under the same name so the POSIX-only signal reads below stay under a guard tests/test_execution.py recognizes.

Return type:

bool

class click_extra.execution.TimerOption(param_decls=None, *, default=False, expose_value=False, is_eager=True, help='Measure and print elapsed execution time.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured option that is adding a --time/--no-time flag to print elapsed time at the end of CLI execution.

The start time is made available in the context in ctx.meta[click_extra.context.START_TIME].

print_timer(start_time)[source]¶

Print the time elapsed since start_time.

Always prints, even when a sibling eager option (--version, --params, --show-config…) short-circuited the command body via ctx.exit(). That makes --time a usable probe for the cost of Click Extra’s own machinery (option parsing, config loading, eager callbacks), not just user command bodies.

Parameters:

start_time (float) – the time.perf_counter() reading the run started at.

Return type:

None

init_timer(ctx, param, value)[source]¶

Set up the execution-timer machinery for the current invocation.

Captures time.perf_counter() as the start time, stores it on ctx.meta under click_extra.context.START_TIME, and queues print_timer() as a context-close callback so the elapsed duration is printed even when a sibling eager option (--version, --params…) short-circuits the command body.

The start time belongs to the run, not to the option: a run started from within another run of the same command times itself, and leaves the outer one its own start.

Return type:

None

class click_extra.execution.ZeroExitOption(param_decls=None, *, default=False, expose_value=False, is_flag=True, help='Always exit with a status code of 0, even when problems are found.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured -0/--zero-exit option flag.

Follows the convention popularized by linters and static analysers, which exit with a non-zero code whenever they report findings so that automation can gate on it. Setting this flag flips that behavior: the CLI returns 0 as long as it ran to completion, reserving non-zero codes for actual execution failures.

The resolved value is stored in ctx.meta[click_extra.context.ZERO_EXIT].

Warning

This option is a placeholder: it does not alter the CLI’s exit code by itself. Downstream code must read ctx.meta[click_extra.context.ZERO_EXIT] and act on it.

set_zero_exit(ctx, param, value)[source]¶

Store the resolved zero-exit flag on the context’s meta dict.

Read via click_extra.context.get(ctx, click_extra.context.ZERO_EXIT).

Return type:

None

click_extra.execution.PROMPT = '$ '¶

Prompt used to simulate the CLI execution.

Hint

Use ASCII characters to avoid issues with Windows terminals.

click_extra.execution.INDENT = '  '¶

Blank prefix as wide as PROMPT, to indent what a run prints under the line of its command.

click_extra.execution.args_cleanup(*args)[source]¶

Flatten recursive iterables, remove all None, and cast each element to strings.

Serializes pathlib.Path and other objects. Nested iterables and None values are accepted as CLI arguments for convenience: they are flattened and filtered out.

Return type:

tuple[str, ...]

click_extra.execution.highlight_bin_name(program, theme=None)[source]¶

Style the binary’s own name inside program, leaving its directory plain.

/opt/homebrew/bin/mas renders with only mas in the active theme’s invoked_command style, so the part of the path the eye scans for stands out from the noise of its location. A bare name (no separator) is styled whole. Both POSIX and Windows separators are recognized, whichever comes last.

Parameters:
  • program (str) – the command, path and all.

  • theme (HelpTheme | None) – palette to style with. Defaults to the theme the current invocation runs under, see format_cli_prompt().

Return type:

str

Returns:

the styled command.

click_extra.execution.format_cli_prompt(cmd_args, extra_env=None, theme=None, prompt=None)[source]¶

Render the shell prompt simulating a CLI invocation, for logs and dry-runs.

Prefixes PROMPT to any extra_env assignments and the command line. Each token family is styled with the theme slot (get_current_theme()) it holds elsewhere in a CLI’s output, so the line reads like the help screens do:

  • the prompt sigil with bracket, the structural-token style;

  • each environment assignment as envvar name, plain =, default value;

  • each variable to unset as an option -u and its envvar name, after a plain env;

  • the program’s binary name with invoked_command, its directory plain (see highlight_bin_name());

  • the -/-- flags with option; other arguments stay plain.

Useful to print a copy-pasteable command trace in debug logs, dry-runs and test output. Each argument and environment value is quoted for the shell, so one carrying a space or a metacharacter reads back as the single token it was: a -c script keeps the quotes that made it one argument, instead of spilling into the line as several. Quote nothing before calling this, or the quotes are themselves quoted. Styling reads the raw argument, since a quoted --name=John Doe no longer opens on a dash.

A variable mapped to None is one env_copy() removes from the child’s environment, and no assignment can say that: the line then opens on env -u NAME, ahead of the assignments, as $ env -u LANGUAGE LC_ALL=C forecast.

Note

The program is left as it stands. Quoting has to wrap the whole token, which would put the closing quote inside the name highlight_bin_name() styles, and a Windows path is quoted whole for its separators alone: C:\Tools\mas.exe needs none of it to paste back.

Parameters:
  • cmd_args (Iterable[str]) – the command line to render.

  • extra_env (Mapping[str, str | None] | None) – environment assignments to prefix it with, a None value unsetting its variable.

  • theme (HelpTheme | None) – palette to style the line with. Defaults to the theme the current invocation runs under, which is what a CLI printing its own trace wants. A caller drawing the line onto a surface of its own choosing (a light capture, say) passes the one that surface can show.

  • prompt (str | None) – sigil to draw before the command, when the shell being pictured is not the one running. A capture mimicking a Windows terminal passes PS C:\>; None keeps PROMPT, which is this platform’s.

Return type:

str

Returns:

the styled prompt line.

click_extra.execution.terminate_live_processes(signum=Signals.SIGTERM)[source]¶

Send signum to every subprocess currently running through run_cli().

Called from the main thread’s SIGINT handler (see install_interrupt_handler()) so a concurrent fan-out aborts promptly: terminating the children unblocks the worker threads parked in run_cli(), letting the thread pool drain instead of hanging on a child that ignored the terminal’s process-group SIGINT.

A child spawned with start_new_session never receives the terminal’s SIGINT at all (it left the foreground process group), so its whole group is signalled here, with the groups its descendants moved to.

Defaults to SIGTERM rather than SIGKILL so a child still gets to clean up, notably to restore terminal state a sudo password prompt may have altered. An aborting Click Extra command follows up with SIGKILL for a child still running after a grace period.

SIGTERM goes to a child sharing the caller’s process group alone: stopping what it started is part of its own clean-up. SIGKILL cannot be handled, so it also goes to each descendant of that child, one PID at a time (see _kill_descendants()), and to the descendants an earlier call wrote down (see _STRAY_DESCENDANTS), which a child that exited on SIGTERM left running. Windows has a single forced termination, which ends the whole process tree of each child whatever signum asks for.

The registry is snapshotted under the lock, then signalled outside it, because run_cli() may be discarding its own entries from other threads at the same time.

Return type:

None

click_extra.execution.install_interrupt_handler(ctx)[source]¶

Make the first Ctrl+C terminate in-flight subprocesses, then abort as usual.

Installs a SIGINT handler for the duration of the CLI run that calls terminate_live_processes() before re-raising KeyboardInterrupt (exactly what Python’s default handler raises). The abort then proceeds normally, and a concurrent fan-out does not hang on surviving children. The previous handler is restored when ctx closes.

Must run in the main thread: signal.signal() refuses to install a handler from any other, so a non-main-thread caller (embedded use, some tests) is a no-op that keeps the default Ctrl+C behavior.

A Click Extra command already asks the children to stop as the run aborts, once its context has closed. This handler does it at the moment of the Ctrl+C, which matters when a close callback waits on one of them, and serves a plain Click command, which has no such abort path.

Return type:

None

click_extra.execution.run_cli(args, *, extra_env=None, cwd=None, timeout=None, label=None, merge_stderr=False, errors='replace', windows_creation_flags=0, start_new_session=False, command_level=20, output_level=10, log=None)[source]¶

Run a CLI in a subprocess, disclosing the call and streaming its output live.

A subprocess.run() work-alike for CLI-wrapping tools, with observability built in:

  • the invocation is logged before the spawn, as the copy-pasteable $ ENV=value command args line of format_cli_prompt(), so a user can reproduce by hand what the tool runs on their system;

  • each line of the child’s output is forwarded to the logger as it is produced (ANSI-stripped, tagged with label), instead of being held back until the child exits, so a long-running command narrates its progress live;

  • the child is registered in the live-process registry for the duration of the call, so terminate_live_processes() (wired to Ctrl+C by install_interrupt_handler()) can abort it.

Contract mirrored from subprocess.run():

  • returns a subprocess.CompletedProcess with the full captured stdout and stderr decoded as UTF-8;

  • raises subprocess.TimeoutExpired (with the partial capture attached) when the child, or the draining of its output, outlives timeout. The child is stopped first, and so is every descendant it left behind: on POSIX with SIGTERM, then SIGKILL once a grace period runs out (see _stop_timed_out_process()), sent to the process group and every group its descendants moved to when spawned with start_new_session, to the child plus each descendant PID otherwise. Windows ends the whole process tree at once (see _kill_windows_process_tree());

  • a KeyboardInterrupt mid-run kills the child (with the same tree, group or per-PID scope), then propagates.

The child reads from subprocess.DEVNULL so it can never block on stdin, and never opens a console window on Windows.

Note

The pipes are opened in universal-newlines text mode, so a bare \r (a child redrawing a progress bar in place) terminates a line just like \n: each redraw is streamed as its own log line, and the captured text normalizes both to \n, exactly as subprocess.Popen.communicate() does.

Parameters:
  • args (str | Path | None | Iterable[str | Path | None | Iterable[Iterable[str | Path | None | Iterable[TNestedArgs]]]]) – the command line. Nested iterables are flattened, None values dropped, and every element (Path, versions, …) cast to a string; see args_cleanup().

  • extra_env (Mapping[str, str | None] | None) – environment variables forced over the inherited environment for this call (see env_copy()). They are part of the disclosed prompt line, since reproducing the call requires them.

  • cwd (Path | str | None) – directory to run the child in. None inherits the caller’s, which is subprocess.run()’s own default. A relative args[0] is resolved by the OS against this directory, not the caller’s, so pass an absolute path (or a name on the PATH) when moving the child elsewhere.

  • timeout (float | None) – seconds before the child is asked to stop. None waits forever.

  • label (str | None) – tag identifying this call on each streamed output line, for when several children interleave in one log. Carried as the record’s label attribute, which click_extra.logging.Formatter renders glued to the level name and styled like an invoked command (debug:mas: Warning: ...); a foreign formatter can read record.label itself. Applied to the prompt line and to every output line, so an interleaved log attributes each command as well as what it printed.

  • merge_stderr (bool) – route the child’s stderr into stdout so the OS interleaves both in write order. The result’s stderr is then None, like a subprocess.run() call with stderr=STDOUT.

  • errors (str) – decoding error handler for the child’s output. The default "replace" swaps undecodable bytes for ļæ½; pass "backslashreplace" to keep them inspectable as escapes.

  • windows_creation_flags (int) – extra Windows process-creation flags, OR-ed with the always-on CREATE_NO_WINDOW. No-op off Windows.

  • start_new_session (bool) – make the child lead its own POSIX session and process group (subprocess.Popen’s parameter of the same name). Every kill path then signals the whole group in one call: the timeout overrun, a mid-run KeyboardInterrupt, and terminate_live_processes(). A grandchild spawned by the child (a shim re-executing the real binary, an installer helper) is reaped along with it instead of surviving as an orphan holding the output pipes open. A descendant that left the group with setsid(), like the make test run CPAN.pm forks, is signalled through its own group. Off by default, and to be left off when a descendant must keep the controlling terminal: a new session detaches from it, so an interactive prompt raised from inside the child (sudo reading /dev/tty) would fail, and sudo’s tty-keyed credential cache would no longer match. That costs the atomicity of a single group signal, not the reaping: the timeout and KeyboardInterrupt paths then kill the child and walk the tree it led, signalling each descendant by PID (see _kill_descendants()). terminate_live_processes() signals the direct child alone when it sends SIGTERM, for a clean exit, and walks the same tree when it sends SIGKILL. No-op on Windows, where each of these paths already kills the full tree. Only the reaping half of this flag has that Windows equivalent, and the other half has none: a POSIX session also detaches the child from the controlling terminal, where a Windows child keeps sharing the parent’s console and can still reach back into it: a console control event the child raises, as a package manager’s own teardown can, lands in the parent as a KeyboardInterrupt. The lever there is windows_creation_flags (CREATE_NEW_PROCESS_GROUP), left to the caller because it also changes how a real Ctrl-C reaches the child.

  • command_level (int) – logging level of the invocation-disclosure line. Defaults to logging.INFO; lower it to logging.DEBUG for internal probes not worth narrating.

  • output_level (int) – logging level of the streamed output lines. Defaults to logging.DEBUG.

  • log (Logger | None) – destination logger. Defaults to the root logger, whose level the VerbosityOption family manages.

Return type:

CompletedProcess[str]

click_extra.highlight module¶

Help-screen keyword highlighting and the colorized help formatter.

Hosts the engine that collects highlightable keywords from a Click context (HelpKeywords, _HelpColorsMixin) and renders them with the active theme: HelpFormatter styles --help output and highlight() applies a styling function to arbitrary matches.

Note

The patterns of the help screen stay uncompiled strings at module level. Most runs of a CLI render no help screen, so none of them is worth compiling on import: re compiles each on its first use and caches it from then on. DEPRECATED_RE is the exception: highlight() reads a string as a literal, so the marker pattern other renderers share is handed over compiled.

click_extra.highlight.DEPRECATED_RE = re.compile('\\(deprecated(?::\\s[^)]+)?\\)', re.IGNORECASE)¶

Matches (DEPRECATED) and (DEPRECATED: reason) markers, whatever their case.

The canonical spelling comes from Click’s shared _format_deprecated_label helper; the case-insensitive flag also catches the variants a CLI author writes by hand in a help string.

Read by the help screen and by render_command_tree(), so one marker is painted the same wherever a command’s description is drawn.

class click_extra.highlight.HelpKeywords(cli_names=set(), subcommands=set(), command_aliases=set(), arguments=set(), long_options=set(), short_options=set(), choices=set(), choice_metavars=set(), metavars=set(), envvars=set(), defaults=set(), deprecated=set())[source]¶

Bases: object

Structured collection of keywords extracted from a Click context for help screen highlighting.

Each field corresponds to a semantic category with its own styling.

cli_names: set[str]¶
subcommands: set[str]¶
command_aliases: set[str]¶
arguments: set[str]¶
long_options: set[str]¶
short_options: set[str]¶
choices: set[str]¶
choice_metavars: set[str]¶
metavars: set[str]¶
envvars: set[str]¶
defaults: set[str]¶
deprecated: set[str]¶

Markers a CLI paints with the deprecated slot beside Click’s own.

DEPRECATED_RE covers the spellings Click writes, and only those. A project marking a parameter in its own vocabulary ((unmaintained) for a tool whose upstream is gone, where the option itself is not being retired) otherwise gets no color for it, since the word is the whole pattern.

Each entry is matched literally, so a marker is written the way it reads on the screen, punctuation included.

merge(other)[source]¶

Merge another HelpKeywords into this one.

Each set field is updated with the corresponding set from other.

Return type:

None

subtract(other)[source]¶

Remove keywords found in other from this instance.

Each set field is difference-updated with the corresponding set from other. Mirror of merge().

Return type:

None

class click_extra.highlight.HelpFormatter(*args, **kwargs)[source]¶

Bases: HelpFormatter

Extends Cloup’s custom HelpFormatter to highlight options, choices, metavars and default values.

Cloup declined this regex-based highlighting, at janluke/cloup#95 and janluke/cloup#97. The same proposal is open at click-contrib/click-help-colors#17.

Force the theme to a HelpTheme.

The theme defaults to the one active for the current invocation, as click_extra.theme.get_current_theme() resolves it: the per-invocation pick of ThemeOption, or the process-wide default when no context is active. A plain cloup.HelpTheme lends the slots it declares to that active theme, which keeps the slots cloup lacks.

theme: HelpTheme¶
keywords: HelpKeywords¶

Keywords to highlight, collected from the rendered command’s context.

Instance state, initialized per formatter: _HelpColorsMixin.format_help fills it before rendering, and highlight_extra_keywords() mutates it (see the excluded_keywords subtraction), so a shared class-level default would leak keywords across formatters.

excluded_keywords: HelpKeywords | None¶

Keywords subtracted from the cross-reference passes, or None.

highlight_extra_keywords(help_text)[source]¶

Highlight extra keywords in help screens based on the theme.

Uses the highlight() function for all keyword categories. Each category is processed as a batch of regex patterns with a single styling function, which handles overlapping matches and prevents double-styling.

Return type:

str

write_usage(prog, args='', prefix=None)[source]¶

Draw the usage line, naming the command the same way the rest does.

Reimplements cloup.HelpFormatter.write_usage, which paints the whole command path with the invoked_command slot. A subcommand’s path ends on a name the parent screen lists under subcommand, and the same word in two colors across two screens reads as two different things.

Return type:

None

getvalue()[source]¶

Wrap original Click.HelpFormatter.getvalue() to force extra-colorization on rendering.

Return type:

str

click_extra.highlight.style_choice_metavar(metavar, choices, theme)[source]¶

Style each part of a metavar that enumerates the values it accepts.

Takes a rendered metavar like {json|xml|csv} (a required click.Choice operand), [json|xml|csv] (an optional one) or [id,spec,value] (Click Extra’s multi-pick MultiChoice), and paints every known value with theme.choice. A part that is not one is a type placeholder, like the INTEGER of a hybrid [auto|max|INTEGER], and takes theme.metavar.

Shared by the help screen and by render_command_tree(), so one operand reads the same wherever it is drawn.

Parameters:
  • metavar (str) – the rendered metavar to style.

  • choices (Collection[str]) – the values the parameter accepts.

  • theme (HelpTheme) – the theme whose choice and metavar slots paint the parts.

Return type:

str | None

Returns:

the styled metavar, or None when it enumerates nothing.

click_extra.highlight.highlight(content, patterns, styling_func, ignore_case=False)[source]¶

Highlights parts of the content that matches patterns.

Takes care of overlapping parts within the content, so that the styling function is applied only once to each contiguous range of matching characters.

Todo

Support case-folding, so we can have the Straße string matching the Strasse content.

This could be tricky as it messes with string length and characters index, which our logic relies on.

Danger

Roundtrip through lower-casing/upper-casing is a can of worms, because some characters change length when their case is changed:

Return type:

str

click_extra.humanize module¶

Human-readable rendering of machine values.

Formatters that turn raw numbers into the compact strings shown in terminal output, tables and reports. The reverse direction, parsing a human-written value back into a machine type, lives in click_extra.types (see Duration).

click_extra.humanize.format_size(size, *, units='iec', precision=1)[source]¶

Render a byte count as a compact, human-readable string.

Parameters:
  • size (float) – The number of bytes. A negative value keeps a leading -.

  • units (Literal['iec', 'si', 'jedec']) – The unit system to render in: iec (the default) for binary powers with the unambiguous KiB/MiB symbols, si for decimal powers with kB/MB, or jedec for binary powers with the customary but imprecise KB/MB.

  • precision (int) – Number of fractional digits for every unit above bytes. A byte count is always rendered as a whole number.

Return type:

str

Returns:

The size followed by a space and its unit, like 1.5 KiB. The integer part is grouped with thousands separators.

Raises:

ValueError – If units is not a known unit system.

click_extra.humanize.format_duration(duration)[source]¶

Render an elapsed duration compactly: 2.3s, 1:05, then 1:02:03.

Below a minute the duration reads as one-decimal seconds (2.3s). From a minute up it switches to a clock layout, growing an hours field only once it reaches an hour: 1:05 under an hour, 1:02:03 at or above.

The reverse direction, parsing a human-written duration back into a timedelta, lives in click_extra.types (see Duration).

Parameters:

duration (float | timedelta) – The elapsed time, as a number of seconds or a timedelta.

Return type:

str

Returns:

The compact rendering described above.

click_extra.jobs module¶

The --jobs option, and the fan-out primitives that honor its count.

JobsOption resolves the count, its auto and max keywords included, and publishes it on ctx.meta. run_jobs() and run_lanes() spread work over a thread pool of that size, and resolve_jobs() holds the policy both apply.

Todo

Stop turning a RuntimeError of the wait in _wait_result() back into the KeyboardInterrupt it replaced, once python/cpython#118433 is fixed in every free-threaded Python Click Extra supports.

click_extra.jobs.CPU_COUNT = 4¶

Number of logical CPUs available to this process, or None if undetermined.

A count of logical processors (hardware threads), resolved by _logical_cpu_count(): os.process_cpu_count() on Python 3.13+, falling back to os.cpu_count() on older runtimes. On a CPU with simultaneous multi-threading (Intel Hyper-Threading, AMD SMT) a 4-physical-core chip reports 8. It is therefore not a count of physical cores, and is usually larger than what physical-core tools report, such as psutil.cpu_count(logical=False) or pytest-xdist’s -n auto (which counts physical cores). Parallelism here is keyed on the logical count on purpose: subprocess- and I/O-bound work overlaps well across hardware threads.

click_extra.jobs.DEFAULT_JOBS = 3¶

Default number of parallel jobs: CPU_COUNT minus one reserved core.

Leaves one logical CPU free for the main process and system tasks, but only on hosts with three logical CPUs or more: on smaller hosts the reservation would collapse the pool to a single (sequential) worker, and threads waiting on subprocesses and I/O cost nothing there, so the whole machine is used instead. Falls back to 1 (sequential) when the count cannot be determined.

Caution

On a single-CPU host this still resolves to 1 and the default silently runs sequentially. JobCount.convert() logs whenever a parallel-intent keyword collapses to a single job this way: as a warning for an explicit request, at info level for the option’s own default.

class click_extra.jobs.JobCount[source]¶

Bases: ParamType

Parse a --jobs value: an integer or the auto/max keyword.

Resolves the symbolic keywords against the host’s logical CPU count (CPU_COUNT), counting hardware threads, not physical cores:

  • auto resolves to DEFAULT_JOBS (one fewer than the available logical CPUs, except on hosts with fewer than three, where reserving a core would leave a single worker), the same heuristic used as the option’s default.

  • max resolves to CPU_COUNT (every available logical CPU).

Any other token is parsed as an integer and left to JobsOption.validate_jobs() for clamping and range-checking. Resolving the keywords here keeps the value handed downstream a plain int, so consumers never have to know about the keywords.

name: str = 'jobs'¶

the descriptive name of this type

choices = ('auto', 'max')¶

Symbolic keywords accepted besides an integer count, in render order.

Exposed as choices so the help colorizer highlights them like click.Choice values: the keyword collector duck-types on this attribute (see the getattr(param.type, "choices", ...) branch in _HelpColorsMixin._collect_params). It is also the single source of truth reused by get_metavar() and convert(), so the metavar and the parser never drift apart.

get_metavar(param, ctx)[source]¶

Render [auto|max|INTEGER] (brackets included, as Choice does).

Return type:

str

convert(value, param, ctx)[source]¶

Resolve a keyword to a logical-core count, else parse as an integer.

An already-resolved integer is returned untouched, so option defaults and re-validation can flow back through conversion unharmed. When a parallel-intent keyword (auto/max) resolves to a single job, the collapse is logged: the request reads as ā€œuse several coresā€, but the host has too few logical CPUs, so execution is silently sequential. An explicit request (command line, environment variable, config file) logs a warning; the option’s own default only logs at info level, else every bare invocation on a 1-CPU host would emit a warning the user never asked for, polluting captured runner streams and the CLI output rendered in Sphinx docs.

Return type:

int

shell_complete(ctx, param, incomplete)[source]¶

Suggest the auto/max keywords; an integer count is free-form.

Completion proposes only the symbolic keywords, matched case-insensitively to mirror how convert() lower-cases its input. An integer has no finite set to enumerate, so none is offered, yet convert() still accepts one.

Return type:

list[CompletionItem]

class click_extra.jobs.JobsOption(param_decls=None, *, default='auto', expose_value=False, show_default=True, type=<click_extra.jobs.JobCount object>, help="Number of parallel jobs. Accepts an integer, auto (the host's logical CPUs, minus one when there are three or more) or max (all logical CPUs). --jobs 0 runs sequentially.", **kwargs)[source]¶

Bases: ExtraOption

A pre-configured --jobs option to control parallel execution.

Accepts an integer or one of two keywords resolved by JobCount: auto (the default: one fewer than the available logical CPU cores, leaving a core free for the main process and system tasks, except on hosts with fewer than three logical CPUs, where reserving one would leave a single worker) and max (every available logical CPU core). A value of 0 disables parallelism and runs sequentially.

The core count is the number of logical CPUs (hardware threads) available to the process, not physical cores: see CPU_COUNT. On a host with a single logical CPU, auto/max resolve to a single job and JobCount logs that execution will be sequential: as a warning when the keyword was requested explicitly, at info level when it came from the option’s own default.

The resolved value is stored as an int in ctx.meta[click_extra.context.JOBS].

Warning

JobsOption only resolves and publishes the job count: it does not drive any concurrency by itself. Pass it to run_jobs() (which reads the resolved ctx.meta[click_extra.context.JOBS] count), or read that value yourself and act on it.

validate_jobs(ctx, param, value)[source]¶

Validate the resolved job count and store it in context metadata.

JobCount has already resolved any auto/max keyword to an integer by the time this runs. A value of 0 disables parallelism: it is rounded up to 1 (sequential execution) with a warning. Negative values are likewise clamped to 1. A count above the available cores is honored: the pool is a ThreadPoolExecutor, and oversubscription is how I/O- and subprocess-bound work overlaps, so the warning only flags the CPU-bound case where extra threads just contend for the GIL. The resolved count is then logged at info level next to the host’s logical CPU count (CPU_COUNT), so a CLI’s parallelism is visible under --verbosity INFO.

Return type:

None

click_extra.jobs.resolve_jobs(ctx, count, *, serial_at_debug=False)[source]¶

Resolve how many worker threads to use for a batch of count items.

Returns the number of items to process in parallel; 1 means run sequentially in the calling thread. This is the policy shared by run_jobs() and run_lanes(), exposed on its own for callers that must know the resolved count before they fan out (for example to pick a progress-rendering mode). It collapses to sequential when:

  • there is no active CLI context (programmatic or test use),

  • a single item leaves nothing to parallelize, or

  • the resolved JobsOption count (ctx.meta[click_extra.context.JOBS]) is 1 or less.

Otherwise that count wins, capped at count: there is no point spinning up more workers than there are items.

Parameters:
  • ctx (Context | None) – the active Click context, read for the resolved --jobs count (and, with serial_at_debug, the verbosity). None forces sequential.

  • count (int) – how many items are about to be scheduled.

  • serial_at_debug (bool) – when set, also collapse to sequential at DEBUG verbosity, where coherent per-worker log narration matters more than the speed-up (interleaved threads would scramble it). Off by default.

Return type:

int

click_extra.jobs.run_jobs(func, items, *, jobs=None, serial_at_debug=False)[source]¶

Run func over items, parallelized per the resolved --jobs count.

The worker count is taken from jobs when given, else resolved from the active command’s JobsOption value by resolve_jobs(), else 1. With a single worker (or at most one item) the items run sequentially and lazily, so a caller can stop early on the first result (for example to abort on the first failure); otherwise they run in a thread pool. Either way results are yielded in submission order, like map().

This is the single-task-per-item special case of run_lanes(), which runs every item as a lane of its own. Reach for run_lanes() when some items must run serially relative to one another while others run concurrently.

The pool is thread-based, which suits the I/O- and subprocess-bound work CLI tools usually parallelize (each child releases the GIL). The count is a number of logical CPUs: see CPU_COUNT.

items is never materialized: only a bounded window of tasks is queued at a time, so an unbounded or expensive-to-produce stream stays memory-flat and is read no further than the caller consumes.

Parameters:
  • func (Callable[[T], R]) – Called once per item; its return value is yielded.

  • items (Iterable[T]) – The work items. Read lazily, a window at a time.

  • jobs (int | None) – Override the worker count instead of reading it from the context. 1 or fewer forces sequential execution.

  • serial_at_debug (bool) – forwarded to resolve_jobs() when jobs is not given: collapse to sequential at DEBUG verbosity.

Return type:

Generator[R, None, None]

Returns:

An iterator over func’s results, in the order of items.

click_extra.jobs.run_lanes(func, lanes, *, jobs=None, serial_at_debug=False)[source]¶

Run func over grouped items: serial within a lane, concurrent across.

Each lane is an iterable of items. func is mapped over every item, but a lane’s own items run serially and in order on a single worker, while distinct lanes run concurrently up to the resolved --jobs count. This is the right primitive when some work must be serialized relative to itself (a shared lock, a rate limit, one mailbox file, one package-manager backend) yet still overlap with unrelated work.

run_jobs() is the degenerate case where every lane holds a single item. Concurrency is sized by the number of lanes (one worker per lane), since a lane never splits across workers. A single lane runs in the calling thread, whatever the worker count.

Results are yielded in lane-submission order, a lane’s items in order, like map(). The run stays lazy at any worker count: a lane is materialized only when it is about to be scheduled, and only a bounded window of lanes is in flight, so a caller can break early and the lanes behind it are never read. A lane runs entirely on one worker, so a stateful resource bound to the lane (a per-lane cache, a connection) is touched by only that one thread and needs no lock.

Parameters:
  • func (Callable[[T], R]) – Called once per item; its return value is yielded.

  • lanes (Iterable[Iterable[T]]) – The lanes, each an iterable of items. Read lazily, a window of lanes at a time; a lane’s own items are materialized when it is scheduled.

  • jobs (int | None) – Override the worker count instead of reading it from the context. 1 or fewer forces fully sequential execution.

  • serial_at_debug (bool) – forwarded to resolve_jobs() when jobs is not given: collapse to sequential at DEBUG verbosity.

Return type:

Generator[R, None, None]

Returns:

An iterator over func’s results, lane by lane in submission order.

click_extra.layout module¶

Measure a line of terminal text, and compose one of a stated width.

A terminal is a grid of cells, and everything a CLI draws on it has to agree on how many cells a string occupies. That number is not the string’s length: an ideograph takes two cells and a combining mark none. cell_width() answers it once, and every line this package composes is built on that answer.

The module holds the composition helpers built on it, starting with center_in_rule(). They are terminal-text primitives, not capture machinery: click_extra.capture.screenshot consumes them to lay a picture out on the same grid, and so can any CLI drawing a divider of its own.

click_extra.layout.PADDING = ' \xa0'¶

Characters that separate one column of terminal text from the next.

Both are one cell wide and draw nothing. render_svg() emits every space as a non-breaking one, so the padding survives an XML round-trip and no renderer collapses a run of them.

click_extra.layout.RULE_GLYPH = '─'¶

Character center_in_rule() draws a rule with, absent a better one.

An unbroken line, which is what a divider between two whole things is.

click_extra.layout.RULE_COLOR = 'bright_black'¶

Color center_in_rule() paints a rule and its brackets.

A rule is the one line of a screen nothing printed, so it is drawn to recede: dimmer than the text it separates, in both the gallery of click-extra themes and the marker standing in for what a capture cut. A rule a caller spells out in full is written as given, color included, since a caller naming one has already decided how it should look.

click_extra.layout.cell_width(text, term_program=None)[source]¶

Columns text occupies on a terminal’s character grid.

Not its length. A CJK ideograph is drawn two cells wide, a combining mark none, an ANSI escape or an OSC 8 hyperlink none at all while adding several characters, and a tab as many as it takes to reach the next stop eight columns along. wcwidth.width answers for all of them, which is what lets a caller measure text as it arrived rather than stripping it first.

Note

wcwidth.wcswidth, the older call, refuses any string carrying a control character and answers -1 for it, which is every styled string. Reach for it only where a consumer reads that value back, as tabulate does.

Parameters:
  • text (str) – the text to measure.

  • term_program (str | None) – name of the terminal drawing the text, as $TERM_PROGRAM holds it. A few of them advance an emoji-presentation sequence by one column where the Unicode tables say two, and naming the terminal applies wcwidth’s correction for it. None measures what the tables say.

Return type:

int

Returns:

the number of cells it occupies, never negative.

click_extra.layout.pad_to(text, width)[source]¶

Pad text with blanks until it occupies width cells.

str.ljust() counts characters, so on a styled line it counts the escapes it cannot see and pads too little, or nothing at all. Text already at least width cells wide comes back untouched.

Any style the text left open is closed before the blanks, so a background cannot bleed across the gap into whatever sits beside it.

Parameters:
  • text (str) – the text to pad, styled or not.

  • width (int) – cells the result occupies.

Return type:

str

Returns:

the padded text.

click_extra.layout.center_in_rule(label, width, rule='─', opening='[ ', closing=' ]', color='bright_black')[source]¶

One line of width cells: label centered in a rule drawn with rule.

label may arrive already styled: cell_width() discounts its escapes, so a caller paints the label its own way and hands the whole thing over. color paints the rule and the two brackets, which is the half a caller cannot pre-style without knowing where they fall.

A None or empty label draws no brackets and one contiguous rule: a divider naming nothing should not look like a frame around nothing. A width too narrow for the brackets drops them the same way, and one too narrow for the label leaves the label alone rather than drawing a rule that cannot close.

Measured in cells, not characters: a label carrying a wide glyph shifts a rule built on len by one column per glyph.

Parameters:
  • label (str | None) – the text the rule is drawn around, styled or not, or None for an unbroken rule.

  • width (int) – columns the line occupies.

  • rule (str) – character the rule is drawn with.

  • opening (str) – bracket written between the rule and label.

  • closing (str) – bracket written between label and the rule.

  • color (str | None) – color the rule and brackets are painted, or None to leave them as they are. label is never repainted: a caller styles it itself, or leaves it in the terminal’s own ink.

Return type:

str

Returns:

the whole line.

click_extra.layout.LINE_NUMBER_SEPARATOR = ' │ '¶

Rule drawn between a line’s number and the line itself.

A vertical bar rather than a bare space, so the gutter reads as a column of its own even where the output is itself indented.

click_extra.layout.RTL_BIDI_CLASSES = frozenset({'AL', 'AN', 'R'})¶

Unicode bidirectional classes written right to left.

Right-to-left letters, Arabic letters and Arabic-Indic numbers, as unicodedata.bidirectional() names them. See is_bidirectional().

click_extra.layout.number_lines(text, start=1, digits=0)[source]¶

Prefix each line of text with its number, in a dim gutter.

The numbers are drawn into the terminal text rather than into a column beside it, which is the same trade Pygments makes with its inline line numbers: every renderer places them for free, and every reader copying the text copies them too.

Right-aligned on the widest number, so the gutter is one column whatever the output’s length, and separated by LINE_NUMBER_SEPARATOR.

Parameters:
  • text (str) – the text to number, ANSI escape sequences included.

  • start (int) – number given to the first line.

  • digits (int) – fewest digits the numbers are aligned on, for a text whose gutter has to match the gutter of a longer one, see number_frames(). The widest number of text still fits when it has more.

Return type:

str

Returns:

the numbered text.

click_extra.layout.number_frames(frames, start=1)[source]¶

Number the lines of each frame of an animation, in one gutter for all.

A frame is a screen, so each one counts its own rows from start. The gutter is as wide on every frame as on the tallest: numbered on its own, a frame reaching ten rows takes one digit more than the frame before it, and every one of its rows moves a cell to the right.

Parameters:
  • frames (Sequence[str]) – the frames to number, ANSI escape sequences included.

  • start (int) – number given to the first line of each frame.

Return type:

tuple[str, ...]

Returns:

the numbered frames, in the same order.

click_extra.layout.is_bidirectional(text)[source]¶

Whether text carries a character written right to left.

Arabic, Hebrew and their neighbours are reordered by whoever draws them, and the cursive ones are shaped: a letter’s form depends on what it joins. A terminal grid describes neither, which is why render_svg() stops pinning such a run to an exact width.

Parameters:

text (str) – the text to inspect.

Return type:

bool

Returns:

True when at least one character is right-to-left.

click_extra.layout.fit_columns(text, floor=0)[source]¶

Width, in characters, of the longest line in text.

ANSI escapes style the glyphs around them and occupy no cell of their own, so they are discounted. Measured in terminal cells, so a line of CJK asks for the two columns per glyph it is drawn with.

Parameters:
  • text (str) – the text to measure, ANSI escape sequences included.

  • floor (int) – width to return when every line is narrower than it. A caller laying the text out somewhere with a minimum of its own states that minimum here; the default floors at nothing.

Return type:

int

Returns:

the width laying every line out without folding any.

click_extra.layout.grid(text, columns, *, wrap_marker='')[source]¶

Lay ANSI text out on a terminal’s character grid.

Where a stream of styled text stops being a stream and becomes a picture. Each styled run of split_ansi() is split at newlines into rows, then placed on the column it starts at, measured in cells rather than characters so a wide glyph takes the two it is drawn with.

A line reaching past columns soft-wraps onto the next row, the way it would on a terminal that narrow, rather than being cropped: a command is free to print a line it never wraps itself (a long URL, a wide table, a machine-readable dump), and a layout that silently swallowed the overflow would be lying about what ran. A glyph straddling the edge moves down whole.

Returning the column with each run is what lets a renderer place a run without measuring anything back out of its own output.

Note

wrap_marker closes each row a fold cut short, which is what tells a reader that the row continues below instead of the command having printed a line that stops mid-word. It is the renderer’s own mark, so it is painted with RULE_COLOR rather than left in the terminal’s ink, and it takes a cell of the row it closes: a marked row carries one cell less of text, and a line that would have fit exactly folds once the marker is asked for. A terminal folds silently, so the default draws nothing.

Parameters:
  • text (str) – the text to lay out, ANSI escape sequences included.

  • columns (int) – width of the grid, in cells.

  • wrap_marker (str) – character closing each row a fold cut short, or an empty string to fold silently.

Return type:

list[list[tuple[Style, str, int]]]

Returns:

one list of (style, text, column) runs per row.

click_extra.layout.wrap_ansi(text, width)[source]¶

Wrap text to width terminal cells, preserving its ANSI styling.

textwrap.wrap() counts every byte of an ANSI escape toward the line length, so a styled string wraps far earlier than its visible width warrants. wcwidth.wrap measures an escape at no cells and every character between escapes at the width a terminal advances by. It reopens on each line the styling still in effect, so no escape sequence crosses a line boundary: each returned line carries the styling it needs, opened and closed within the line.

Note

Breaks land where textwrap.wrap() puts them on plain ASCII, so long-word breaking and whitespace handling match it exactly. The two measures part on a double-width character, which counts for the two cells it takes, and on an OSC 8 hyperlink, which counts for none.

Parameters:
  • text (str) – the text to wrap, ANSI escape sequences included.

  • width (int) – cells each returned line occupies at most.

Return type:

list[str]

Returns:

the wrapped lines, empty text yielding a single empty one.

click_extra.logging module¶

Logging utilities.

Todo

Let the -v/-q counter reach beyond the LogLevel range, where it clamps at DEBUG and CRITICAL:

  • a TRACE pseudo-level below LogLevel.DEBUG (numeric value 5, mirroring logging.DEBUG - 5) so repeated -v can surface finer-grained tracing past DEBUG;

  • a SILENT pseudo-level above LogLevel.CRITICAL (any value above logging.CRITICAL) so repeated -q can suppress every record, including LogLevel.CRITICAL.

Both require extending LogLevel, which ripples into the --verbosity EnumChoice, the Formatter level-name color lookup and the level-ordering tests.

class click_extra.logging.LogLevel(*values)[source]¶

Bases: IntEnum

Mapping of canonical log level names to their integer level.

Mirrors logging._nameToLevel, but:

CRITICAL = 50¶
ERROR = 40¶
WARNING = 30¶
INFO = 20¶
DEBUG = 10¶
click_extra.logging.DEFAULT_FORMAT = '{levelname}: {message}'¶

Format of a log record, written in the style of DEFAULT_STYLE.

The default of basicConfig(), and the format of the handler an option of Click Extra attaches to the root logger for the time of a run.

click_extra.logging.DEFAULT_LEVEL: LogLevel = LogLevel.WARNING¶

The level a logger starts its life at: WARNING.

It is the level Python sets its global root logger up at.

This value is also the default level of VerbosityOption.

click_extra.logging.DEFAULT_STYLE: Literal['%', '{', '$'] = '{'¶

Style of the format strings: { is the one of str.format().

The default of basicConfig(), where logging.basicConfig() defaults to %.

class click_extra.logging.StreamHandler(stream=None)[source]¶

Bases: StreamHandler

A handler to output logs to the console.

Wraps logging.StreamHandler, but uses click.echo() to support color printing.

Only sys.stderr or sys.stdout are allowed as output stream, and sys.stderr is the default.

Initialize the handler.

If stream is not specified, sys.stderr is used.

property stream: IO[Any]¶

The stream to which logs are written.

A proxy of the parent logging.StreamHandler’s stream attribute.

Redefined here to enforce checks on the stream value.

emit(record)[source]¶

Use click.echo() to print to the console.

Cooperates with any live terminal line currently drawing on the same stream (a Spinner, or an OperationTrail progress bar): the record is then printed through its echo, which erases the in-progress render first, so a log line emitted mid-draw lands on its own line instead of garbling the indicator (and vice versa).

The color tri-state is resolved through invocation_color() rather than left to click.echo()’s own context lookup: a record emitted from a background thread (a subprocess stream reader, a fan-out worker) has no reachable Click context, and would otherwise ignore --no-color and keep its ANSI codes on a TTY.

Return type:

None

class click_extra.logging.Formatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)[source]¶

Bases: Formatter

Click Extra’s default log formatter.

Initialize the formatter with specified format strings.

Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format.

Use a style parameter of ā€˜%’, ā€˜{’ or ā€˜$’ to specify that you want to use one of %-formatting, str.format() ({}) formatting or string.Template formatting in your format string.

Changed in version 3.2: Added the style parameter.

formatMessage(record)[source]¶

Colorize the record’s log level name before calling the standard formatter.

Colors are sourced from a click_extra.theme.HelpTheme, resolved per-invocation via click_extra.theme.get_current_theme().

A record carrying a label attribute (each line run_cli() streams from a subprocess is tagged with its caller-provided label) renders it glued to the level name, styled like an invoked command: debug:mas: Warning: .... The tag stays out of the message text itself, so a foreign formatter is free to render record.label its own way.

A message spanning several lines starts on the line below its prefix. Glued to the prefix, the first line of a block (a command’s captured output, a table) shifts right by the width of that prefix while the lines below stay at the margin, which breaks the block’s columns.

The record’s levelname and message are restored afterwards: a record may be formatted more than once (several handlers, a captured then re-rendered record), and must not accumulate styling, glued labels or line breaks.

Return type:

str

click_extra.logging.basicConfig(*, filename=None, filemode='a', format='{levelname}: {message}', datefmt=None, style='{', level=None, stream=None, handlers=None, force=False, encoding=None, errors='backslashreplace', stream_handler_class=<class 'click_extra.logging.StreamHandler'>, file_handler_class=<class 'logging.FileHandler'>, formatter_class=<class 'click_extra.logging.Formatter'>)[source]¶

Configure the global root logger.

This function is a wrapper around Python standard library’s logging.basicConfig(), but with additional parameters and tweaked defaults.

It sets up the global root logger, and optionally adds a file or stream handler to it.

Differences in default values:

Argument

basicConfig() default

logging.basicConfig() default

style

{

%

format

{levelname}: {message}

%(levelname)s:%(name)s:%(message)s

This function takes the same parameters as logging.basicConfig(), but require them to be all passed as explicit keywords arguments.

Parameters:
  • filename (str | None) – Specifies that a logging.FileHandler be created, using the specified filename, rather than a StreamHandler.

  • filemode (str) –

    If filename is specified, open the file in this mode.

    Defaults to a.

  • format (str | None) –

    Use the specified format string for the handler.

    Defaults to {levelname}: {message}.

  • datefmt (str | None) – Use the specified date/time format, as accepted by time.strftime().

  • style (Literal['%', '{', '$']) –

    If format is specified, use this style for the format string:

    Defaults to {.

  • level (int | str | None) – Set the root logger level to the specified level.

  • stream (IO[Any] | None) – Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with filename - if both are present, a ValueError is raised.

  • handlers (Iterable[Handler] | None) – If specified, this should be an iterable of already created handlers to add to the root logger. Any handlers which don’t already have a formatter set will be assigned the default formatter created in this function. Note that this argument is incompatible with filename or stream - if both are present, a ValueError is raised.

  • force (bool) – If this argument is specified as True, any existing handlers attached to the root logger are removed and closed, before carrying out the configuration as specified by the other arguments.

  • encoding (str | None) – Name of the encoding used to decode or encode the file. To be specified along with filename, and passed to logging.FileHandler for opening the output file.

  • errors (str | None) – Optional string that specifies how encoding and decoding errors are to be handled by the logging.FileHandler. Defaults to backslashreplace. Note that if None is specified, it will be passed as such to open().

Return type:

None

Important

Always keep the signature of this function, the default values of its parameters and its documentation in sync with the one from Python’s standard library.

These new arguments are available for better configurability:

Parameters:

Note

The camel-cased name mirrors the one of Python’s standard library logging.basicConfig().

click_extra.logging.new_logger(name='root', *, propagate=False, force=True, **kwargs)[source]¶

Setup a logger in the style of Click Extra.

By default, this helper will:

  • Fetch the logger registered under the name parameter, or creates a new one with that name if it doesn’t exist,

  • Set the logger’s propagate attribute to False,

  • Force removal of any existing handlers and formatters attached to the logger,

  • Attach a new StreamHandler with Formatter,

  • Return the logger object.

This function is a wrapper around basicConfig() and takes the same keywords arguments.

Warning

The removal reaches every handler of the logger, not only the ones Click Extra attached. Left on its default name, this function sets up the root logger, which the whole process shares: the handlers an application or a test runner attached to it are removed and closed.

Call it from the entry point of a program instead of at import time, or name a logger of your own. With force=False the handlers stay, and the function sets nothing up on a logger that already has one.

Note

The options of Click Extra do not call this function for the root logger. They attach their handler beside the others, for the time of a run. See add_to_parser().

Parameters:
  • name (str) – ID of the logger to setup. Defaults to the name of Python’s root logger. If a logger with the provided name is not found in the global registry, a new logger with that name will be created.

  • propagate (bool) – Sets the logger’s propagate attribute. Defaults to False.

  • force (bool) – Same as the force parameter from logging.basicConfig() and basicConfig(). Defaults to True.

  • kwargs – Any other keyword parameters supported by logging.basicConfig() and basicConfig().

Return type:

Logger

class click_extra.logging.VerbosityOption(param_decls=None, *, default_logger='root', default=LogLevel.WARNING, metavar='LEVEL', type=EnumChoice('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'), help='Either CRITICAL, ERROR, WARNING, INFO, DEBUG.', **kwargs)[source]¶

Bases: _VerbosityOption

--verbosity LEVEL option to set the log level of _VerbosityOption.

Set up a verbosity-altering option.

Parameters:

default_logger (Logger | str) –

The logger the option sets the level of:

  • A logging.Logger object is used as it is.

  • The name of the root logger, which is the default, selects it.

  • A name found in the global registry selects that logger as it is.

  • Any other name creates the logger with new_logger().

Building the option never touches the root logger, which the whole process shares. Whichever logger is selected, the root one gets Click Extra’s handler for the time of each run of the command: see add_to_parser().

set_level(ctx, param, value)[source]¶

Record the --verbosity value, then reconcile.

The value passed to --verbosity is saved in ctx.meta[click_extra.context.VERBOSITY].

Return type:

None

class click_extra.logging.DebugOption(param_decls=None, *, default_logger='root', is_flag=True, default=False, help='Shorthand for --verbosity DEBUG.', **kwargs)[source]¶

Bases: _VerbosityOption

--debug flag, a shorthand for --verbosity DEBUG.

The one level people reach for by name, so it gets a flag of its own. The quiet end of the scale needs no such thing: -q walks down it, repeatably.

Note

It outranks --verbosity, -v and -q alike rather than joining their arithmetic, because it asks for the loudest level there is and no combination of the other three can ask for more. See _VerbosityOption.resolve_level().

Set up a verbosity-altering option.

Parameters:

default_logger (Logger | str) –

The logger the option sets the level of:

  • A logging.Logger object is used as it is.

  • The name of the root logger, which is the default, selects it.

  • A name found in the global registry selects that logger as it is.

  • Any other name creates the logger with new_logger().

Building the option never touches the root logger, which the whole process shares. Whichever logger is selected, the root one gets Click Extra’s handler for the time of each run of the command: see add_to_parser().

set_level(ctx, param, value)[source]¶

Record that --debug was passed, then reconcile.

The flag is saved in ctx.meta[click_extra.context.DEBUG], so downstream code can tell a level that came from --debug from the same level spelled --verbosity DEBUG.

Return type:

None

class click_extra.logging.VerboseOption(param_decls=None, **kwargs)[source]¶

Bases: _CounterOption

--verbose/-v option to raise the log level of _VerbosityOption by one step per repetition.

Each -v raises the verbosity by one LogLevel step. The option can be repeated, so -vv (or -v -v) raises it by two steps.

The base level the counter starts from is sourced from VerbosityOption.default. So with --verbosity’s default left at WARNING:

  • -v raises the level to INFO,

  • -vv raises the level to DEBUG,

  • any further repetition is clamped at the loudest level, so -vvvvv for example resolves to DEBUG.

-v shares a single signed counter with QuietOption’s -q, so the two cancel out: -v -q leaves the level unchanged. See _VerbosityOption.resolve_level for the full reconciliation rule with --verbosity.

Set up a verbosity-altering option.

Parameters:

default_logger –

The logger the option sets the level of:

  • A logging.Logger object is used as it is.

  • The name of the root logger, which is the default, selects it.

  • A name found in the global registry selects that logger as it is.

  • Any other name creates the logger with new_logger().

Building the option never touches the root logger, which the whole process shares. Whichever logger is selected, the root one gets Click Extra’s handler for the time of each run of the command: see add_to_parser().

class click_extra.logging.QuietOption(param_decls=None, **kwargs)[source]¶

Bases: _CounterOption

--quiet/-q option to lower the log level of _VerbosityOption by one step per repetition.

The symmetric counterpart of VerboseOption: where -v raises the verbosity one LogLevel step at a time, -q lowers it. Starting from VerbosityOption.default (WARNING by default):

  • -q lowers the level to ERROR,

  • -qq lowers the level to CRITICAL,

  • any further repetition is clamped at the quietest level, so -qqqqq for example resolves to CRITICAL.

-q shares a single signed counter with VerboseOption’s -v, so the two cancel out: -v -q leaves the level unchanged. See _VerbosityOption.resolve_level for the full reconciliation rule with --verbosity.

Set up a verbosity-altering option.

Parameters:

default_logger –

The logger the option sets the level of:

  • A logging.Logger object is used as it is.

  • The name of the root logger, which is the default, selects it.

  • A name found in the global registry selects that logger as it is.

  • Any other name creates the logger with new_logger().

Building the option never touches the root logger, which the whole process shares. Whichever logger is selected, the root one gets Click Extra’s handler for the time of each run of the command: see add_to_parser().

click_extra.logging.requested_level(ctx, opts)[source]¶

The level the verbosity options of ctx.command will settle on.

Read from the parsed opts, the environment and the defaults, without running any of the options’ callbacks, so an eager option processed before them can honor it. ConfigOption relies on it: it loads the configuration before any verbosity option applies a level, yet -q and a quieter --verbosity still silence its status lines.

Returns None when the command carries no verbosity option, or when a value does not convert: the regular parse reports that error in its turn.

Return type:

LogLevel | None

click_extra.mkdocs module¶

MkDocs plugin for ANSI color rendering in code blocks.

Patches the formatter classes of pymdownx.highlight so that Token.Ansi.* tokens produced by Click Extra’s Pygments lexers are decomposed into individual CSS classes and styled with the correct colors.

Decomposing tokens into classes only strips the raw escape codes: the classes carry no color until a matching stylesheet is present. Unlike Sphinx’s PygmentsBridge, which regenerates pygments.css from the active formatter on every build, MkDocs never emits one for these classes. The plugin therefore writes the ANSI rules to a dedicated stylesheet, ANSI_STYLESHEET, and registers it in extra_css so every page links it.

When mkdocs-click is installed, the plugin also patches its code-block generators to use the ansi-output lexer instead of plain text, so that CLI help text with ANSI escape codes renders with colors.

Note

This is the MkDocs counterpart of the Sphinx integration in click_extra.sphinx, which achieves the same result by replacing sphinx.highlighting.PygmentsBridge.html_formatter.

click_extra.mkdocs.ANSI_OUTPUT_FENCE = '```ansi-output'¶

Fenced code-block opening that triggers the ANSI-aware Pygments lexer.

click_extra.mkdocs.TEXT_FENCE = '```text'¶

Fenced code-block opening used by mkdocs-click for CLI help output.

click_extra.mkdocs.ANSI_STYLESHEET = 'assets/click-extra/ansi.css'¶

Site-relative path of the generated ANSI color stylesheet.

Registered in the MkDocs config’s extra_css by AnsiColorPlugin.on_config() so every page links it, and written into the build output by AnsiColorPlugin.on_post_build().

class click_extra.mkdocs.AnsiColorPlugin[SomeConfig: Config][source]¶

Bases: BasePlugin

MkDocs plugin that adds ANSI color support to Pygments code blocks.

Monkey-patches pymdownx.highlight’s block and inline formatter classes to inherit from AnsiHtmlFormatter. This gives every code block in the MkDocs site full ANSI color rendering: compound tokens like Token.Ansi.Bold.Cyan are decomposed into individual CSS classes, and a generated stylesheet (written by on_post_build() and registered in extra_css by on_config()) supplies the color rules for the 256-color indexed palette and all SGR text attributes.

When mkdocs-click is installed, its code-block generators are also patched to use the ansi-output lexer so that CLI help text renders with colors.

on_config(config)[source]¶

Patch pymdownx.highlight formatters and register the ANSI stylesheet.

Runs before page processing begins. Appending ANSI_STYLESHEET to extra_css makes MkDocs link it from every page (resolving the relative path per page, including under use_directory_urls). The file itself is written later, in on_post_build().

Return type:

MkDocsConfig

on_post_build(config)[source]¶

Write the ANSI color stylesheet into the built site.

Without it, the -Ansi-* classes the formatters patched in on_config() emit carry no color. Runs after the theme copied its own assets, so the file survives the site-directory cleanup.

Return type:

None

click_extra.multicall module¶

Multicall / argv[0] dispatch: one binary answering to many names.

A multicall binary is a single executable whose behavior is selected by the name it is invoked with: bzip2, bunzip2 and bzcat are the same file, vim and view differ by default options, and BusyBox multiplexes hundreds of applets behind symlinks pointing at one binary. MulticallGroup brings the pattern to Click Extra: a group that, when invoked under the name of one of its subcommands, skips the group and behaves exactly like that subcommand as a standalone binary.

Declare one with multicall_group():

from click_extra import argument, echo, multicall_group, option


@multicall_group()
def kitchen():
    '''A multicall kitchen appliance.'''


@kitchen.command()
@option("--temperature", default="180")
@argument("dishes", nargs=-1)
def bake(temperature, dishes):
    '''Bake dishes in the oven.'''


@kitchen.command()
@option("--hours", default="2")
@argument("bottles", nargs=-1)
def chill(hours, bottles):
    '''Chill bottles in the fridge.'''

Invoked as kitchen, the CLI is a regular group. Invoked through a symlink named bake (or any other subcommand name), it is the bake command: one flat argument parse, its own usage line and help screen, and the full set of Click Extra options merged in:

$ kitchen bake --temperature 200 pie       # regular group dispatch
$ ln -s $(which kitchen) bake
$ bake --temperature 200 pie               # same thing, no subcommand

A personality maps to a sequence of tokens, not just a subcommand, so a name can also pre-fill options (bzcat is bzip2 --decompress --stdout):

@multicall_group(personalities={"chill-fast": ("chill", "--hours", "1")})
def kitchen():
    ...

Note

Behavioral notes for personality mode:

  • The group’s own callback does not run: the personality is a standalone command with no parent context.

  • Configuration and environment variable namespaces follow the personality name: bake reads its configuration from the bake app dir and the BAKE_* environment variables, the way a standalone binary would, and not from the group’s kitchen namespace.

  • The invocation name a command was started under is also exposed on its own, for custom dispatch logic: see click_extra.context.INVOCATION_NAME.

click_extra.multicall.WINDOWS_EXE_SUFFIX = '.exe'¶

Suffix of Windows console-script wrappers, stripped from argv[0].

On Windows, entry points are materialized as .exe shims, so a symlink named bake lands in argv[0] as bake.exe.

click_extra.multicall.normalize_personality(tokens)[source]¶

Normalize a personality mapping value into a tuple of CLI tokens.

Accepts a bare subcommand name ("chill") or a token sequence (("chill", "--hours", "1")). The first token names the subcommand the personality dispatches to; the rest is prepended to the user’s arguments.

Raises:
  • TypeError – when the value is neither a string nor a sequence.

  • ValueError – on an empty sequence or a non-string token.

Return type:

tuple[str, ...]

class click_extra.multicall.PersonalitiesCommand(name, context_settings=None, callback=None, params=None, help=None, epilog=None, short_help=None, options_metavar='[OPTIONS]', add_help_option=True, no_args_is_help=False, hidden=False, deprecated=False)[source]¶

Bases: _InjectedCommand

Synthetic subcommand listing every name a MulticallGroup answers to.

Auto-injected into every MulticallGroup, the way HelpCommand is injected into every Group: the group mode needs a place to enumerate the symlink names, and a subcommand costs no new top-level option on the group’s help screen.

invoke(ctx)[source]¶

List each personality next to the command line it invokes.

Return type:

None

class click_extra.multicall.MulticallGroup(*args, personalities=None, personalities_command=True, **kwargs)[source]¶

Bases: Group

A Group dispatching on its invocation name, BusyBox-style.

When the name the binary was invoked under matches a personality, the group steps aside entirely and runs the matching subcommand as a standalone command: the personality carries the group’s options merged into the subcommand’s, parses them in one flat pass with no positional ordering constraint, and renders its own usage line and help screen. Any other invocation name falls through to regular group behavior.

The invocation name is, in precedence order:

  1. an explicit prog_name passed to main() (what click_extra.testing.CliRunner uses to simulate a symlink),

  2. else the unresolved basename of sys.argv[0].

The basename is used unresolved: resolving through os.path.realpath() would return the symlink’s target and destroy the personality. A trailing WINDOWS_EXE_SUFFIX is stripped for Windows console-script shims. Click’s own _detect_program_name() is deliberately not used: it reads __main__.__package__ and answers python -m … in the module case. See click_extra.cli_wrapper.invoke_target() for the full trap. A name matching no personality is not an error: it falls through, which is also what keeps the feature inert under test runners, where argv[0] is the runner’s own binary.

Like Group.__init__, but with multicall dispatch.

Parameters:
  • personalities (Mapping[str, str | Sequence[str]] | None) – maps an invocation name to the tokens it invokes: a bare subcommand name ("chill") or a token sequence (("chill", "--hours", "1")) whose extra tokens are prepended to the user’s arguments. Left to None, every non-hidden, non-synthetic subcommand is its own personality.

  • personalities_command (bool) – when True (the default), a personalities subcommand is auto-registered on the group, listing every invocation name the binary answers to. Register your own personalities subcommand to override it.

personalities: dict[str, tuple[str, ...]]¶
resolve_invocation_name(prog_name=None)[source]¶

The name this binary was invoked under.

An explicit prog_name wins: it is what makes the feature testable without symlinks on disk. Otherwise the unresolved basename of sys.argv[0] is used, with a trailing .exe stripped on Windows.

Return type:

str | None

list_personalities()[source]¶

Every personality name mapped to the tokens it invokes.

The explicit personalities mapping when one was declared, else every subcommand _is_default_personality admits, mapped to itself. The lazy subcommands of a lazy group are imported to be judged, which a listing has to pay for.

Return type:

dict[str, tuple[str, ...]]

match_personality(name)[source]¶

Tokens to invoke when called under name, or None to fall through.

Return type:

tuple[str, ...] | None

main(args=None, prog_name=None, **kwargs)[source]¶

Dispatch on the invocation name before any argument parsing.

A matching personality runs as a standalone command, the group’s own options merged into it, its extra tokens prepended to the arguments. Anything else delegates to the regular group main().

Return type:

Any

build_personality(name, tokens)[source]¶

Synthesize the standalone command the name personality runs as.

The personality is a fresh instance of the subcommand’s own class, re-instantiated over the group’s parameters merged with the subcommand’s, not a copy whose params attribute is patched after the fact. Two reasons make the re-instantiation mandatory:

  • Cloup computes its help layout (arguments, option_groups, ungrouped_options) from params inside __init__, so a patched copy parses every merged option but only renders the subcommand’s own on its help screen.

  • Click Extra’s own Command.__init__ does work that must run over the merged set: extra_option_at_end reordering, option priorities, auto envvar population and help-keyword collection.

Every parameter is deep-copied, because Command.__init__ re-runs populate_auto_envvars over the merged set under the personality’s own auto_envvar_prefix: sharing instances would rewrite the group’s and subcommand’s envvar attributes and leak that back into group mode. This is the same class of leaky state default_params() warns about.

Return type:

Command

click_extra.output module¶

Send command output to a file path or to stdout.

Helpers for the common --output option pattern, where a - value means ā€œwrite to stdoutā€ instead of creating a file literally named -, for standard streams that cannot encode what a command prints, and for the error a command reports when its output needs an optional dependency that is not installed.

click_extra.output.STDOUT_SENTINEL = '-'¶

Conventional --output value asking for stdout instead of a file on disk.

exception click_extra.output.MissingExtraError(extra, *, subject, package='click-extra')[source]¶

Bases: ClickException, ImportError

A command needs an optional dependency that is not installed.

The one failure every feature gated behind an extra raises once a user asks for it: a table, an export or a completion spec in a format whose writer is missing, a code snippet without Pygments. Click prints the message after Error: and exits with status 1, with no traceback.

It is an ImportError as well, since a failed import is what it reports: code calling such a feature outside a command catches it as one.

The message names the uv pip install command that installs the extra, in the wording every other optional-dependency error of the package uses.

Parameters:
  • extra (str) – the optional dependency group that installs what is missing.

  • subject (str) – what needs the dependency, opening the message.

  • package (str) – the distribution the extra belongs to.

click_extra.output.is_stdout(path)[source]¶

Return True when path is the stdout sentinel -.

Guards against accidentally creating a file literally named - in the current directory.

Return type:

bool

click_extra.output.prep_path(path)[source]¶

Open path for writing as UTF-8 text, or return stdout for -.

Yields a UTF-8 stream for a path and for the stdout of the process itself, sidestepping the UnicodeEncodeError a non-ASCII payload triggers on Windows, where the console defaults to cp1252. For a real path, missing parent directories are created first, absorbing the mkdir -p a caller would otherwise need.

Note

A sys.stdout that something replaced is returned as-is: Click’s test runner, the Sphinx {click:run} directive that live-renders CLI output in the docs, a contextlib.redirect_stdout() block. The replacement is where the output must go, in the encoding its owner chose. Its descriptor can point somewhere else: under CliRunner(capture="fd"), Click sends descriptors 1 and 2 to the capture, but sys.stdout.fileno() returns a copy of the original stdout descriptor, so a stream opened on it writes past the capture. A stdout with no file descriptor is returned as-is too.

Parameters:

path (Path) – The destination path, or - for stdout.

Return type:

IO[str]

Returns:

A writable text stream. The caller closes it, unless it is sys.stdout. The stream opened on the stdout descriptor uses closefd=False, so closing it leaves the real stdout open.

click_extra.output.force_unicode_output()[source]¶

Switch sys.stdout and sys.stderr to UTF-8 when they do not speak it.

Windows gives a redirected stream the encoding of its legacy code page, cp1252 on a Western install, which has no āœ“, no ✘ and none of the box-drawing characters of a table border. A command printing one of them dies on a UnicodeEncodeError the moment its output is piped or redirected, which is how automation runs a CLI. A narrow PYTHONIOENCODING, like ascii, leads a POSIX host to the same crash.

A stream already speaking UTF-8 is left alone. A stream refusing the new encoding is asked for backslashreplace errors instead: an escaped character in the output is ugly, but it loses nothing and does not crash. A stream with no reconfigure(), like an io.StringIO capture, is skipped.

main() calls it as each run starts.

Todo

Remove once the minimum supported Python is 3.15: its UTF-8 mode, on by default (PEP 686), makes the standard streams speak UTF-8 unless the environment asks otherwise.

Return type:

None

click_extra.param_tools module¶

Helpers to introspect a CLI: its parameters and its command tree.

Every renderer of a CLI reads it through these helpers: the man pages, the Markdown and JSON documents, the Carapace completion spec, the --tree view and the --params table. One helper per question keeps their answers from drifting apart: which parameters a command lists and in which order, what each one is called, what it accepts, and how its help text reads once Click’s markers are taken out.

class click_extra.param_tools.P¶

Type variable bound to click.Parameter, letting search_params(), last_param() and require_sibling_param() return the exact subclass they were asked to find.

alias of TypeVar(ā€˜P’, bound=Parameter)

click_extra.param_tools.PARAM_PATH_SEP = '.'¶

Separator joining the keys of a parameter’s fully-qualified path (cli.subcommand.param).

click_extra.param_tools.INLINE_LITERAL_RE = re.compile('``([^`]+?)``')¶

Match a reST inline literal, text between two pairs of backticks, in a docstring.

Click stores docstrings verbatim, so any reST markup the author used to render code-like tokens in HTML docs leaks into Command.help / Command.short_help. The roff and HTML man-page paths translate these matches into the bold/literal markers their renderers understand; the Sphinx index directive translates them into nodes.literal.

click_extra.param_tools.iter_inline_literals(text)[source]¶

Walk text and yield (segment, is_literal) pairs.

Split on INLINE_LITERAL_RE so the consumer can apply different rendering to the literal segments (bold for roff, a literal node for docutils) without re-parsing the regex.

Return type:

Iterator[tuple[str, bool]]

click_extra.param_tools.clean_help(text)[source]¶

Normalize Click help prose for the backends that carry newlines natively.

Runs inspect.cleandoc() and drops Click’s \b (\x08) no-rewrap marker, keeping every line break the marker protected. Markdown, JSON and a completion spec all represent those breaks on their own, so none needs an equivalent of the roff .nf / .fi pair: only the control character has to go, or it lands in the output as a stray byte.

Return type:

str

click_extra.param_tools.choice_values(param_type)[source]¶

The values a click.Choice-like type accepts, spelled as Click completes them.

An Enum member is named by its name, as click.Choice.normalize_choice() does before it folds case, and anything else by str(). A type carrying no choices attribute, or an empty one, answers an empty tuple. The one spelling every document of a CLI lists a choice under: the help screen, the man page, the completion spec.

Return type:

tuple[str, ...]

click_extra.param_tools.search_params(params, klass, include_subclasses=True)[source]¶

Return the one parameter of class klass in params, or None.

The result is typed as klass itself, so a caller needs no isinstance check to use what it found.

Parameters:
  • params (Iterable[Parameter]) – list of parameter instances to search in.

  • klass (type[P]) – the class of the parameter to look for.

  • include_subclasses (bool) – if True (the default), a parameter subclassing klass matches too. If False, only a parameter of exactly klass does.

Raises:

RuntimeError – if more than one parameter matches.

Return type:

P | None

click_extra.param_tools.last_param(params, klass)[source]¶

Return the last parameter of exactly klass in params, or None.

Unlike search_params(), this matches the exact klass (no subclasses) and tolerates duplicates: when an option is declared more than once (like an explicit @verbosity_option stacked on a Click Extra command that already ships one), Click keeps the last occurrence, so this mirrors that here instead of erroring out on the ambiguity.

Parameters:
  • params (Iterable[Parameter]) – the command’s parameter list to scan.

  • klass (type[P]) – the exact parameter class to look for.

Return type:

P | None

click_extra.param_tools.require_sibling_param(params, requester, klass)[source]¶

Return the sibling klass parameter declared on the same command, or raise.

Some options are inert on their own: they drive machinery owned by a sibling option. --no-config and --validate-config, for instance, both depend on the --config option (ConfigOption). This helper centralizes the lookup so every such option raises the same RuntimeError when its required sibling is missing, naming the offending flag.

Parameters:
  • params (Iterable[Parameter]) – the command’s parameter list to scan.

  • requester (Parameter) – the parameter requiring the sibling, used to build the error message from its flag names and class.

  • klass (type[P]) – the sibling parameter class to look for.

Return type:

P

click_extra.param_tools.full_short_help(command)[source]¶

Return the command’s canonical one-line short help, untruncated.

Click’s click.Command.get_short_help_str() truncates to 45 characters by default with a trailing "..." so subcommand listings fit a terminal column. That bound is wrong for generated documentation and completion specs, where the NAME / COMMANDS sections carry the full description and the renderer wraps text on its own.

The lookup mirrors Click’s order: an explicit short_help wins, otherwise the first paragraph of command.help is joined into one line. A truthy deprecated flag appends Click’s own label, so a listing reads the same marker Click’s get_short_help_str() produces, reason string included.

Return type:

str

click_extra.param_tools.resolve_param_help(param, ctx)[source]¶

Return a parameter’s help text, including the dynamically-generated ones.

Reading param.help covers the options that carry a static string, and misses the ones that compute their help from the context: Click Extra’s own -v / -q derive theirs from the resolved base verbosity, and leave the attribute at None (see VerboseOption.get_help_record()). Falling back to the help record picks those up.

The record also carries Click’s bracket fields ([default: …], [required], [env var: …]), appended to the prose behind two spaces. They are stripped here: they are not the author’s documentation, and every backend of this module renders them (or deliberately does not) from structured fields of its own.

Return type:

str | None

click_extra.param_tools.canonical_param_name(name)[source]¶

Fold a spelling to the parameter name Click would derive from it.

Applies Click’s own derivation, minus the option prefix its callers strip first: hyphens become underscores and the result is case-folded, so Foo-Bar answers foo_bar. Use it to resolve an outside spelling (a configuration key, an argfile declaration) against the names a CLI already has.

Caution

The fold is many-to-one, so it identifies a name and never reconstructs a spelling. --foo-bar, --Foo-Bar and --FOO-BAR answer the same name, as do --foo--bar and --foo__bar, and --K (the Kelvin sign, U+212A) lands on the same k as --k. Case folding reaches every script and is not length-preserving: --įŗž answers ß, whose upper case is the two letters SS, and a composed cafĆ© answers a different name than a decomposed one that renders identically.

Caution

A folded spelling is a candidate, never an answer on its own. Click takes an identifier declaration verbatim, so @option("--x", "Foo_Bar") names its parameter Foo_Bar, which this function would never produce. Match the fold against the names a CLI declares and keep the CLI’s own spelling, rather than storing what this returns.

Todo

Upstream pallets/click#3827 asks whether Option should keep the case of an identifier declaration, as it does today, or fold it the way Argument already does. Should Click fold both, no parameter can be named Foo_Bar any more: drop the caution above, and with it the ambiguity branch of _merge_into_template in click_extra.config.schema, which exists only to tell two such names apart.

Return type:

str

click_extra.param_tools.param_spellings(param)[source]¶

All literal spellings of a parameter: primary opts then secondary_opts.

A boolean flag pair yields both forms (--foo, --no-foo); a plain option yields just its declared names.

Return type:

tuple[str, ...]

click_extra.param_tools.short_long_opts(opts)[source]¶

Split option spellings into the first short (-x) and long (--xy) form.

Either element is the empty string when that form is absent.

Return type:

tuple[str, str]

click_extra.param_tools.option_value_kind(param)[source]¶

Classify how an option consumes a value, the basis for rendering its metavar.

  • "flag": takes no value. A boolean switch (--foo, --foo/--no-foo), a flag with a custom flag_value (--no-config), or a counter (-v).

  • "optional": the value may be omitted. Click models this as is_flag=False with a flag_value set, so a bare --color stands for the flag value while --color=never passes an explicit one.

  • "required": consumes a value (--config LOCATION).

Note

The discriminator is Click’s is_flag (plus count), not is_bool_flag: a flag carrying a custom flag_value such as NoConfigOption reports is_bool_flag=False yet still takes no value.

Return type:

Literal['flag', 'optional', 'required']

click_extra.param_tools.resolve_flag_value(param)[source]¶

The value param’s primary declaration stands for.

None for a plain option, a counter or an argument, True for a boolean flag, and the declared value otherwise (--color standing for always).

Read from Click’s Option.flag_activation_value, not from flag_value: Click keeps the UNSET sentinel there when no value was declared, and the sentinel stored anywhere it is read back as a value turns the flag off.

Return type:

Any

click_extra.param_tools.is_repeatable(param)[source]¶

Whether the parameter may be supplied several times (multiple or count).

Return type:

bool

class click_extra.param_tools.ParamStructure[source]¶

Bases: object

Utilities to introspect CLI options and commands structure.

Structures are represented by a tree-like dict.

Access to a node is available using a serialized path string composed of the keys to descend to that node, separated by a dot ..

excluded_params: frozenset[str]¶

Fully-qualified IDs of the parameters to block from the structure.

Set by subclasses: ShowParamsOption freezes an empty set, while ConfigOption resolves a dynamic default (or the user-provided list) within the active context. The two filters are mutually exclusive, a constraint each subclass enforces in its own constructor.

With an allowlist, this holds only the IDs that the walk of build_param_trees() reaches and the allowlist leaves out. Ask is_excluded() about a parameter of another subcommand.

included_params: frozenset[str] | None¶

Allowlist of parameter IDs, mutually exclusive with excluded_params.

None disables the allowlist. Otherwise build_param_trees() walks only the subcommands an allowed ID lies under, and resolves the parameters it reaches into excluded_params.

static init_tree_dict(*path, leaf=None)[source]¶

Nest one dict per key of path, the deepest one holding leaf.

An empty path returns leaf itself.

Return type:

Any

static get_tree_value(tree_dict, *path)[source]¶

Get in the tree_dict the value located at the path.

Raises KeyError if no item is found at the provided path.

Return type:

Any

walk_params(*, descend=None)[source]¶

Yield every parameter of the CLI, unfiltered.

Everything is included, from top-level groups to subcommands, and from options to arguments, unless descend skips a subcommand.

Thin adapter over walk_command_params(): it resolves the root CLI from the active context and drops the per-parameter context that the free function also yields.

Parameters:

descend (Callable[[tuple[str, ...]], bool] | None) – passed on to walk_command_params(), to skip the subcommands it declines.

Return type:

Iterator[tuple[tuple[str, ...], Parameter]]

Returns:

(keys, param) pairs: the keys leading to the parameter, then the parameter itself.

TYPE_MAP: ClassVar[dict[type[ParamType], type[str | int | float | bool | list]]] = {<class 'click.types.BoolParamType'>: <class 'bool'>, <class 'click.types.Choice'>: <class 'str'>, <class 'click.types.DateTime'>: <class 'str'>, <class 'click.types.File'>: <class 'str'>, <class 'click.types.FloatParamType'>: <class 'float'>, <class 'click.types.FloatRange'>: <class 'float'>, <class 'click.types.IntParamType'>: <class 'int'>, <class 'click.types.IntRange'>: <class 'int'>, <class 'click.types.Path'>: <class 'str'>, <class 'click.types.StringParamType'>: <class 'str'>, <class 'click.types.Tuple'>: <class 'list'>, <class 'click.types.UUIDParameterType'>: <class 'str'>, <class 'click.types.UnprocessedParamType'>: <class 'str'>}¶

Map Click types to their Python equivalent.

Keys are subclasses of click.types.ParamType. Values are expected to be simple builtins Python types.

This mapping can be seen as a reverse of the click.types.convert_type() method.

static map_click_type(click_type)[source]¶

Map a Click parameter type instance to its Python equivalent.

Returns str for unrecognised custom types, since command-line parameters are strings by default.

See the list of custom types provided by Click.

Return type:

type[str | int | float | bool | list]

static get_param_type(param)[source]¶

Get the Python type of a Click parameter.

Returns str for unrecognised custom types, since command-line parameters are strings by default.

A boolean flag is a bool even when it is repeatable: it collects occurrences of a toggle rather than values, and a configuration file spells it as the boolean it is. That is why the check comes before the multi-value one, which would otherwise read it as a list and have an unset one dump as [], a shape no user writes.

See the list of custom types provided by Click.

Return type:

type[str | int | float | bool | list]

is_excluded(param_id)[source]¶

Whether a configuration file cannot set the parameter param_id.

An allowlist answers alone: the parameter is excluded when included_params does not name it. So the answer holds for a parameter of a subcommand that the walk of build_param_trees() skipped. Without an allowlist, the parameter is excluded when excluded_params lists it.

Parameters:

param_id (str) – the fully-qualified ID of the parameter, its path keys joined with PARAM_PATH_SEP.

Return type:

bool

build_param_trees()[source]¶

Build and return the parameters tree structure.

Each leaf is the list of the parameters its path names: one, or several when options share a name, like the feature switches of one destination.

This removes parameters whose fully-qualified IDs are in the excluded_params blocklist.

With an allowlist, the tree holds only the parameters included_params names. The walk then skips each subcommand that no allowed ID lies under, so it does not import a lazy subcommand of a LazyGroup that the allowlist leaves out. An empty allowlist walks the root command alone. The parameters the walk reaches and the allowlist leaves out become excluded_params.

Return type:

dict[str, Any]

property params_template: dict[str, Any][source]¶

Returns a tree-like dictionary whose keys shadows the CLI options and subcommands and values are None.

Perfect to serve as a template for configuration files.

property params_objects: dict[str, Any][source]¶

Returns a tree-like dictionary whose keys shadows the CLI options and subcommands and values are parameter objects.

Perfect to parse configuration files and user-provided parameters.

click_extra.param_tools.get_param_spec(param, ctx)[source]¶

Extract the option-spec string (like -v, --verbose) from a parameter.

A hidden option has one too: click.Option.get_help_spec() ignores hidden. An argument has no spec, so it gets None.

Return type:

str | None

click_extra.param_tools.make_resilient_context(command, info_name=None, parent=None)[source]¶

Build an introspection context for a command.

Parses no arguments and sets resilient_parsing=True so required-argument errors, prompts and eager-option side effects stay dormant: the canonical way to materialize a click.Context purely to read a command’s structure (its parameters, env-var prefix and subcommands), shared by the man-page and Carapace exporters.

Parameters:
  • command (Command) – the command to build the context of.

  • info_name (str | None) – the name the command goes by in that context. Defaults to the command’s own name.

  • parent (Context | None) – the context of the command’s parent, if any.

Return type:

Context

click_extra.param_tools.child_context(command, parent, info_name)[source]¶

Build the context of a subcommand under parent, without parsing anything.

Built the way click.Command.make_context() builds one, from the command’s own context_class and context_settings, so the context reads like the one a real invocation gets: a subcommand setting its own auto_envvar_prefix names its environment variables after it, where a bare click.Context would derive them from the parent’s prefix. Unlike make_resilient_context(), no parameter is processed, so a walk over a live invocation never re-runs a callback.

Return type:

Context

click_extra.param_tools.iter_subcommands(command, ctx, *, skip_hidden=True, listing=False)[source]¶

Yield a group’s direct subcommands as (name, command) pairs.

Subcommands are discovered dynamically through click.Group.list_commands() / get_command(), in listing order, so lazily-registered commands are included. A non-group yields nothing, a name resolving to None is skipped, and hidden subcommands are skipped unless skip_hidden is False (completion specs keep them, flagged hidden; documentation drops them).

Parameters:

listing (bool) – resolve each name to the command the group’s help screen describes, through its listed_command method when it has one. A LazyGroup answers there with a stand-in for a lazy subcommand declaring its help, so the walk imports nothing.

Return type:

Iterator[tuple[str, Command]]

click_extra.param_tools.iter_subcommand_contexts(command, ctx, *, skip_hidden=True)[source]¶

Yield a group’s direct subcommands, each with an introspection context.

Pairs iter_subcommands() with make_resilient_context(): every renderer walking a command tree (the man pages, the Markdown and JSON documents, the Carapace spec, the --tree view) descends through here, so a lazy subcommand, the order click.Group.list_commands() sets and a name resolving to None are handled the same way in all of them.

Each context is built under ctx and named after the subcommand’s registration name, so its command_path and its environment variable prefix are the ones a run reaches.

Parameters:

skip_hidden (bool) – passed on to iter_subcommands().

Return type:

Iterator[tuple[str, Command, Context]]

Returns:

(name, subcommand, subcontext) triples, in listing order.

click_extra.param_tools.split_option_groups(command)[source]¶

A command’s explicit option groups, split around its ungrouped section.

Hands back the groups drawn before the ungrouped options, then those drawn after. A Click Extra command decides that split itself, through click_extra.commands.Command.split_option_groups(), so its own sections land past the ungrouped ones. A plain Cloup command has no such method and keeps every group ahead of the ungrouped section, which is Cloup’s own rule.

Every renderer reading a command’s sections goes through this, so the split is resolved in one place whatever the command class.

Parameters:

command (OptionGroupMixin) – the command whose groups are read.

Return type:

tuple[tuple[OptionGroup, ...], tuple[OptionGroup, ...]]

Returns:

the groups drawn before the ungrouped section, then those after it.

click_extra.param_tools.iter_params_for_display(command, ctx)[source]¶

Yield a command’s parameters in the order its help screen lists them.

A Click Extra command keeps two orders apart: command.params is the processing order, which decides when each callback fires, while the help screen reads the presentation order Cloup caches in arguments, option_groups and ungrouped_options, sectioned by click_extra.commands.Command.split_option_groups() and sorted within a section by param_priority(). Reading get_params() therefore renders a man page, a Markdown document or a completion spec whose flags no longer match the --help its reader just saw. This is the accessor every such renderer should go through.

Falls back to get_params() for a command that carries no Cloup option groups, where the two orders are the same list. Any parameter attached after construction, and so absent from the cached groups, is yielded last rather than dropped.

Return type:

Iterator[Parameter]

click_extra.param_tools.walk_command_params(cmd, ctx, parent_keys=(), *, descend=None)[source]¶

Walk the parameter tree of a Click command and all its subcommands.

Yields (path_keys, param, owning_ctx) for every parameter found on cmd and, recursively, on each subcommand. Each subcommand is walked under its own freshly-built child context (see child_context()), so context-sensitive metadata (notably the auto-generated environment variable, which derives from Context.auto_envvar_prefix) is computed at the correct nesting level, with the subcommand’s own context settings applied, rather than inherited from the root.

A subcommand whose name collides with a sibling parameter at the same level is skipped: a single fully-qualified path cannot address both an option and a subcommand at once.

Parameters:

descend (Callable[[tuple[str, ...]], bool] | None) – called with the path keys of each subcommand, before the group resolves it. The walk skips a subcommand for which it returns False, so a lazy subcommand it declines is not imported. None walks every subcommand.

Return type:

Iterator[tuple[tuple[str, ...], Parameter, Context]]

click_extra.param_tools.replay_raw_args(subject_ctx)[source]¶

Re-parse the captured raw arguments to recover per-parameter values.

Click discards the pre-parsed arguments once processing is done, so the value and provenance of each parameter cannot be read back directly. When RAW_ARGS was captured on the context (by Command/Group), replaying it through a fresh parser rebuilds the opts mapping that Parameter.consume_value consults, without re-firing eager callbacks: handle_parse_result is never called here, only the parser.

Returns an empty mapping when no raw arguments were captured, so callers can fall back to parameter defaults.

Return type:

dict[str, Any]

click_extra.parameters module¶

Our own flavor of Option, Argument and parameters.

The helpers that introspect a CLI’s parameters live in click_extra.param_tools, and the --params option in click_extra.show_params.

class click_extra.parameters.Argument(param_decls, required=None, help=None, **attrs)[source]¶

Bases: _ParameterMixin, Argument

click.Argument with the overrides of _ParameterMixin.

Inherits from Click directly: cloup.Argument is click.Argument itself.

class click_extra.parameters.Option(*args, group=None, **attrs)[source]¶

Bases: _ParameterMixin, Option

cloup.Option with the overrides of _ParameterMixin.

cloup.Option subclasses click.Option to let an option join a Cloup option group.

Todo

Delete the human_readable_name override and _CLICK_HAS_PARAMETER_SPEC once this package’s Click floor reaches 8.6.0. From that release on, Click names a parameter by Parameter.spec, added by pallets/click#3877: a deprecation notice then names the option by its longest-prefixed flag.

property human_readable_name: str¶

Every spelling of the option, joined the way Click hints at one.

Declared below Click 8.6.0 only: from that release on, Click reads Parameter.spec in its place, and warns about a subclass that overrides this property.

Below it, Click returns self.name here: the Python identifier it derived from the declarations, which is the one spelling that appears nowhere on the command line. Left alone, a deprecated --apt-cyg / --no-apt-cyg announces itself as 'apt_cyg', naming a flag no user can type and none of the two they did. click.Argument already overrides the property for its own reasons, leaving click.Option re-declaring the inherited body verbatim.

" / " is the separator click.Parameter.get_error_hint joins the same spellings with, so a message naming an option reads the same whichever of the two produced it.

class click_extra.parameters.ExtraOption(*args, group=None, **attrs)[source]¶

Bases: Option

Base class of the options Click Extra implements itself.

Identifies Click Extra’s own options with certainty.

Note

The one Click Extra class carrying the Extra prefix: every other one takes the name of the Click or Cloup class it shadows. The plain Option name belongs to the user-facing wrapper this class subclasses, and the prefix marks Click Extra’s own built-in options apart from it. Command reads that mark: it sorts parameters with isinstance(param, ExtraOption) to push the built-in options to the end.

Note

Bracket fields (envvar, default, range, required) cannot be pre-styled in get_help_record() because Click’s text wrapper splits lines after the record is returned, which would break ANSI codes that span wrapped boundaries. Styling is instead applied post-wrapping in HelpFormatter._style_bracket_fields(), which uses the structured data from Option.get_help_extra() to identify each field by its label.

Note

Built-in option subclasses share a common shape: their __init__ defaults param_decls to the option’s canonical flags and wires an eager callback via kwargs.setdefault("callback", self.<callback>). Every callback name encodes its role with a verb prefix. The common roles are:

  • set_<key> publishes a resolved value to ctx.meta (set_color, set_no_color, set_theme, set_telemetry, set_progress, set_accessible, set_zero_exit, the verbosity options’ set_level);

  • init_<system> additionally installs a ctx helper or records a snapshot (init_timer, init_formatter, init_columns, init_sort);

  • validate_<thing> coerces and validates the raw input (validate_jobs, validate_config);

  • print_* renders output and exits (print_man, print_params, print_and_exit).

A few options own a richer operation and name it with its own verb rather than forcing one of the above. ConfigOption wires load_conf to read, parse, and merge a configuration file, and NoConfigOption wires check_sibling_config_option to assert that a sibling --config option exists.

add_to_parser(parser, ctx)[source]¶

Register the option, then give the root logger its handler for the run.

Any of these options may log, and reports through its records: the level changes of the verbosity options, the status lines and the validation errors of ConfigOption, the warnings of JobsOption. A command that carries one of them so prints log records in the style of Click Extra while it runs.

Click calls this method on every parameter of a command before it processes any of them, so the handler is in place for the records the first callbacks emit. It is also a step an option goes through on a command of any class, which is what lets one of these options work on a plain click.command.

Nothing is attached while Click only completes or inspects a command line (ctx.resilient_parsing). See click_extra.logging._hold_invocation_handler for the other rules, and for how the handler leaves.

Return type:

None

click_extra.prebake module¶

Bake build-time metadata into Python source files before compilation.

Compiled binaries (Nuitka, PyInstaller) and git-less runtimes (Docker images, archive checkouts) cannot resolve version or Git metadata at runtime the way click_extra.version.VersionOption does. The values must instead be written into the source before the build, by rewriting the relevant dunder assignments (__version__, __git_short_hash__, …) in place with ast.

This mirrors shadow-rs, which injects build-time constants (BRANCH, SHORT_COMMIT, COMMIT_HASH, COMMIT_DATE, TAG, …) into Rust binaries at compile time. Its BUILD_TIME, BUILD_OS and BUILD_TARGET constants have counterparts here too, in click_extra.version_facts.BUILD_RESOLVERS: those describe the host that produced the binary, which neither the git fields nor the running interpreter can answer once it is running somewhere else.

click_extra.project.discover_package_init_files() finds the files to bake from a project’s packaging metadata.

click_extra.prebake.prebake_version(file_path, local_version)[source]¶

Append a PEP 440 local version identifier to __version__.

The compile-time complement to the runtime click_extra.version.VersionOption.version property: a Nuitka or PyInstaller binary cannot run git at runtime, so the hash must be baked into __version__ in the source file before compilation.

Only a .dev version is touched, and only when it carries no + suffix yet: a release version and an already pre-baked one are left alone, which makes a second run safe.

Parameters:
  • file_path (Path) – the Python source file declaring __version__.

  • local_version (str) – the identifier to append, like a Git short hash.

Return type:

str | None

Returns:

the new version, or None when nothing changed: a release version, an already pre-baked one, or no __version__ at all.

click_extra.prebake.prebake_dunders(file_path, fields)[source]¶

Fill the empty dunder placeholders of a Python source file in one pass.

Reads and parses file_path once, then writes it once, with every placeholder of fields that was found empty filled in. A field whose value is a callable is resolved only when its placeholder is present and still empty, so a resolver that shells out (to git, say) runs for the placeholders that need it, never for a file carrying none. A callable answering None or an empty string leaves its placeholder alone, as does a placeholder already holding a value: running the pass twice is safe.

Placeholders must use empty strings (__field__ = "", not None). The AST matcher only recognizes string literals, and the empty string acts as a falsy sentinel that stays type-consistent with baked values (always str).

A name with no placeholder in the file is skipped: a build bakes every field it knows into every file of a package, and most files declare a few of them. prebake_dunder() is the single-field form, which does warn.

Parameters:
  • file_path (Path) – the Python source file to rewrite.

  • fields (Mapping[str, str | Callable[[], str | None]]) – dunder names (__git_branch__) mapped to the value to bake, or to a callable resolving it on demand.

Return type:

dict[str, str]

Returns:

the names written, each mapped to the value it received. Empty when the file was left untouched.

click_extra.prebake.prebake_dunder(file_path, name, value)[source]¶

Replace an empty dunder variable’s value in a Python source file.

The single-field form of prebake_dunders(), which carries the placeholder rules, with one addition: a file holding no name assignment at all is reported with a warning, since a lone field is asked for on purpose and a typo in its name would otherwise pass unnoticed.

Where prebake_version() appends a PEP 440 local identifier to __version__, this replaces the whole value of any dunder variable that starts empty. Typical use case: injecting a release commit SHA into __git_tag_sha__ = "" at build time.

Parameters:
  • file_path (Path) – the Python source file to rewrite.

  • name (str) – the dunder variable to fill, like __git_tag_sha__.

  • value (str) – the value to bake.

Return type:

str | None

Returns:

the value written, or None when nothing changed: no such variable, or one already holding a value.

click_extra.progress module¶

A determinate progress bar that honors --progress and --time.

progressbar() is a drop-in for click.progressbar(), the determinate counterpart of the indeterminate Spinner. Its bar joins the spinner’s registry of live lines while it draws, so a log record prints on a line of its own above it.

click_extra.progress.progressbar(iterable=None, length=None, label=None, hidden=None, show_eta=None, **kwargs)[source]¶

Drop-in for click.progressbar() honoring --progress and --time.

Click’s own progress bar is determinate, the counterpart to the indeterminate Spinner. This thin wrapper gates its visibility on the same PROGRESS flag the spinner uses, so a single --no-progress (or --accessible, which lowers the progress default) silences both, and gates its estimated-time display on --time.

Parameters:
  • hidden (bool | None) – tri-state. Left at its default None, the bar follows the resolved --progress flag: hidden when the user (or --accessible) turned progress off, shown otherwise. An explicit True or False forces the bar regardless, mirroring how an explicit color= argument overrides ctx.color on click.echo(). With no active context (the bar used outside a Click command) it defaults to shown.

  • show_eta (bool | None) – tri-state, like hidden. Left at its default None, the estimated-time-remaining display follows the --time / --no-time flag: shown under --time, hidden otherwise (its default, or outside a command). An explicit True or False forces it, keeping a bare bar’s timing in step with an OperationTrail’s timer. Click’s own default is True.

Return type:

ProgressBar[V]

Unlike click.progressbar(), the bar draws on sys.stderr unless file says otherwise, like Spinner and OperationTrail. That keeps stdout free for the data a command prints, and puts the bar on the stream log records go to. A record logged while the bar draws then prints on a line of its own above the bar, which draws again below it. The bar is also redrawn at most once every DEFAULT_INTERVAL, the cadence of a spinner’s frames, unless update_min_steps says otherwise. Its position still moves on every step.

Note

The --progress flag gates visibility and --time the ETA. Color is already handled upstream: Click renders the bar through click.echo(), whose color=None resolves against ctx.color, so --no-color / NO_COLOR strip the bar’s ANSI without any work from this wrapper.

click_extra.project module¶

Find a local project’s entry point and packages from its packaging metadata.

read_project_scripts() lists the console scripts a project declares, entry_point_package() names the top-level package of an entry point, and locate_package_root() finds the directory a package imports from, whether the project uses the flat or the src layout.

resolve_entry_point() combines them into the one entry point of a project, under one ambiguity rule. The wrap command runs a project directory through it, and detect_source_package() finds the package the convert-to-myst command converts. discover_package_init_files() finds the __init__.py of every package the scripts enter, for the prebake commands to bake.

click_extra.project.read_project_scripts(directory)[source]¶

Read the console-script entry points declared by a local project.

Inspects PEP 621 [project.scripts] in pyproject.toml first, then console_scripts under [options.entry_points] in setup.cfg. The dynamic setup.py form cannot be parsed statically and is ignored.

Parameters:

directory (Path) – the project root, holding the packaging metadata.

Return type:

dict[str, str]

Returns:

a mapping of each console-script name to its module:function target. Empty when the project declares none.

click_extra.project.entry_point_package(target)[source]¶

The top-level package an entry point target lives in.

orchard.cli:main and orchard:main both answer orchard: the module path before the colon, cut at its first dot.

Parameters:

target (str) – the entry point, as module:function.

Return type:

str

Returns:

the top-level package name.

click_extra.project.locate_package_root(directory, top_package)[source]¶

Find which directory must be on sys.path to import top_package.

Handles the two common project layouts: the flat layout (the package sits directly under the project root) and the src layout (under a src/ subdirectory). A package directory, with or without an __init__.py, and a single-module {top_package}.py all count.

Parameters:
  • directory (Path) – the project root.

  • top_package (str) – the top-level package name, as entry_point_package() reads it off an entry point.

Return type:

Path | None

Returns:

the directory to prepend to sys.path, or None when the package cannot be located on disk.

class click_extra.project.ProjectEntryPoint(target, root)[source]¶

Bases: NamedTuple

The console-script entry point a project directory resolves to.

Create new instance of ProjectEntryPoint(target, root)

target: str¶

The module:function target the console scripts name.

root: Path | None¶

The directory to put on sys.path to import the target, or None when its package is not on disk.

property module: str¶

The module path of the target, before its colon.

property function: str¶

The function name of the target, after its colon.

property package: str¶

The top-level package of the target, see entry_point_package().

click_extra.project.resolve_entry_point(directory)[source]¶

Resolve the one console-script entry point of the project in directory.

Reads the console scripts with read_project_scripts(), and locates the package of their target with locate_package_root().

The ambiguity rule: the console scripts must name a single module:function target. Several script names for one target, like a long name and its short alias, count as one. Two targets are ambiguous even when they live in one package: nothing tells which function the project means.

Parameters:

directory (Path) – the project root, holding its pyproject.toml or setup.cfg.

Return type:

ProjectEntryPoint

Returns:

the entry point, whose root is None when its package is not on disk.

Raises:

ValueError – When the project declares no console script, or scripts naming several targets.

click_extra.project.detect_source_package(directory=None)[source]¶

Locate the project’s source package from its script entry point.

Resolves the entry point with resolve_entry_point(), under its ambiguity rule, and derives the top-level package of its target ("pkg.cli:main" gives pkg), so the convert-to-myst command can run bare from a project root. The package is located under the project root or its src/ folder, see locate_package_root(), and assumed under the project root when it is in neither.

Parameters:

directory (Path | None) – The project root, holding its pyproject.toml or setup.cfg. Defaults to the current working directory.

Return type:

Path

Returns:

Path of the detected package directory.

Raises:

ValueError – When the project declares no script entry point, or scripts naming several targets.

click_extra.project.discover_package_init_files(directory=None)[source]¶

Discover the __init__.py of each package a project’s console scripts enter.

Reads the console scripts of the project in directory with read_project_scripts(), takes the top-level package of each entry point and locates it on disk with locate_package_root(), so a src-layout project resolves like a flat one.

Parameters:

directory (Path | None) – the project root. None reads the current directory.

Return type:

list[Path]

Returns:

each __init__.py found, once, in entry point order. Empty when the project declares no console script, or none of their packages is found.

click_extra.pygments module¶

Pygments lexers, filters, and formatters for ANSI escape sequences.

Parses ANSI SGR escape sequences (ECMA-48 / ISO 6429) from terminal output and renders them as colored HTML with CSS classes. Supports the standard 8/16 named colors, the 256-color indexed palette, and 24-bit RGB.

SGR text attributes: bold, faint, italic, underline, blink, reverse video, strikethrough, and overline.

OSC 8 hyperlinks are rendered as HTML <a> tags. Other OSC sequences are silently stripped.

Note

24-bit RGB colors (SGR 38;2;r;g;b and 48;2;r;g;b) are preserved by default and rendered by AnsiHtmlFormatter as inline style="color: #rrggbb" / style="background-color: #rrggbb" spans (CSS classes cannot enumerate 16.7M colors). Other token components (bold, named colors, palette indices) keep their CSS-class rendering. Pass true_color=False to AnsiColorLexer, AnsiFilter, or any session lexer (via get_lexer_by_name(..., true_color=False)) to opt into quantization to the nearest entry in the 256-color palette instead.

click_extra.pygments.Ansi = ('Ansi',)¶

Unified token namespace for ANSI styling.

Compound tokens from the lexer (like Token.Ansi.Bold.Red) and individual style components (like Token.Ansi.Red) share this single namespace. The formatter decomposes compound tokens into individual CSS classes at render time.

click_extra.pygments.DEFAULT_TOKEN_TYPE = ('Generic', 'Output')¶

Default Pygments token type to render with ANSI support.

Defaults to Generic.Output tokens, as this is the token type used by all REPL-like and terminal session lexers.

click_extra.pygments.DEFAULT_TRUE_COLOR = True¶

Whether 24-bit RGB colors are kept as such, rather than quantized.

The default of the true_color option every ANSI lexer and filter of this module takes: AnsiColorLexer, AnsiFilter, and the session lexers of LEXER_MAP, which hand the option down to the lexers they wrap.

class click_extra.pygments.AnsiColorLexer(**options)[source]¶

Bases: Lexer

Lexer for text containing ANSI escape sequences.

Parses Select Graphic Rendition (SGR) codes and emits compound Token.Ansi.* tokens representing the active styling state. OSC 8 hyperlinks emit Token.AnsiLinkStart / Token.AnsiLinkEnd structural tokens. All other escape sequences are silently stripped.

Supported SGR codes:

  • Text attributes: bold (1), faint (2), italic (3), underline (4), blink (5), reverse video (7), strikethrough (9), overline (53), and their resets.

  • Named colors: standard (30-37, 40-47) and bright (90-97, 100-107).

  • 256-color indexed palette (38;5;n, 48;5;n).

  • 24-bit RGB (38;2;r;g;b, 48;2;r;g;b), kept as is, or quantized to the nearest 256-color entry with true_color=False.

Supported OSC sequences:

  • OSC 8 hyperlinks: rendered as <a> tags by AnsiHtmlFormatter. Only URLs with safe schemes (http, https, mailto, ftp, ftps) are emitted; others are stripped.

Initialize the lexer.

Parameters:

true_color – Default DEFAULT_TRUE_COLOR. 24-bit RGB sequences are preserved as Token.Ansi.FG_{rrggbb} / Token.Ansi.BG_{rrggbb} tokens, which AnsiHtmlFormatter renders as inline style="color: #rrggbb" / style="background-color: #rrggbb" attributes (CSS classes cannot enumerate 16.7M colors). Pass False to quantize 24-bit RGB to the nearest entry in the 256-color palette and emit Token.Ansi.C{n} / Token.Ansi.BGC{n} tokens that map to CSS classes via the style dict.

name = 'ANSI Color'¶

Full name of the lexer, in human-readable form

aliases = ('ansi-color', 'ansi', 'ansi-terminal')¶

A list of short, unique identifiers that can be used to look up the lexer from a list, e.g., using get_lexer_by_name().

get_tokens_unprocessed(text)[source]¶

Parse ANSI escape sequences from text and yield styled tokens.

SGR sequences update the styling state, through the decoder of click_extra.ansi: an escape reads the same here as in split_ansi(), so an empty parameter is a 0 reset and \x1b[;31m is a reset followed by a red foreground. OSC 8 hyperlinks emit structural Token.AnsiLinkStart / Token.AnsiLinkEnd tokens. All other escape sequences are consumed and stripped.

Return type:

Iterator[tuple[int, _TokenType, str]]

class click_extra.pygments.AnsiFilter(**options)[source]¶

Bases: Filter

Custom filter transforming a particular kind of token (Generic.Output by default) into ANSI tokens.

Initialize an AnsiColorLexer and configure the token_type to be colorized.

Parameters:

true_color – Forwarded to the inner AnsiColorLexer to control whether 24-bit RGB sequences are preserved as FG_/BG_ hex tokens for inline-style rendering (default DEFAULT_TRUE_COLOR) or quantized to the 256-color palette. See AnsiColorLexer for details.

Note

Only one token_type is supported. All Pygments session lexers (ShellSessionBaseLexer and the manually-maintained list in collect_session_lexers) emit terminal output exclusively as Generic.Output. No upstream issue or PR proposes splitting output into additional token types (like Generic.Error for stderr). If that changes, this filter would need to accept a set of token types instead of a single one. See pygments#1148 and pygments#2499 for the closest related discussions.

filter(lexer, stream)[source]¶

Transform each token of token_type type into a stream of ANSI tokens.

The token value is lexed as is: the lexer emitting it already normalized the text, and a second pass would strip the blank lines opening or closing each output block.

Return type:

Iterator[tuple[_TokenType, str]]

click_extra.pygments.collect_session_lexers()[source]¶

Retrieve all lexers producing shell-like sessions in Pygments.

The list is maintained by hand, and imports only the lexer modules it names: discovering it at import time would load every lexer Pygments ships.

Hint

tests/test_pygments.py fails when Pygments adds a shell session lexer, or a REPL or terminal lexer emitting Generic.Output, missing from this list.

Return type:

Iterator[type[Lexer]]

click_extra.pygments.LEXER_MAP: dict[type[Lexer], type[Lexer]] = {<class 'pygments.lexers.algebra.GAPConsoleLexer'>: <class 'click_extra.pygments.AnsiGAPConsoleLexer'>, <class 'pygments.lexers.dylan.DylanConsoleLexer'>: <class 'click_extra.pygments.AnsiDylanConsoleLexer'>, <class 'pygments.lexers.erlang.ElixirConsoleLexer'>: <class 'click_extra.pygments.AnsiElixirConsoleLexer'>, <class 'pygments.lexers.erlang.ErlangShellLexer'>: <class 'click_extra.pygments.AnsiErlangShellLexer'>, <class 'pygments.lexers.julia.JuliaConsoleLexer'>: <class 'click_extra.pygments.AnsiJuliaConsoleLexer'>, <class 'pygments.lexers.matlab.MatlabSessionLexer'>: <class 'click_extra.pygments.AnsiMatlabSessionLexer'>, <class 'pygments.lexers.php.PsyshConsoleLexer'>: <class 'click_extra.pygments.AnsiPsyshConsoleLexer'>, <class 'pygments.lexers.python.PythonConsoleLexer'>: <class 'click_extra.pygments.AnsiPythonConsoleLexer'>, <class 'pygments.lexers.r.RConsoleLexer'>: <class 'click_extra.pygments.AnsiRConsoleLexer'>, <class 'pygments.lexers.ruby.RubyConsoleLexer'>: <class 'click_extra.pygments.AnsiRubyConsoleLexer'>, <class 'pygments.lexers.shell.BashSessionLexer'>: <class 'click_extra.pygments.AnsiBashSessionLexer'>, <class 'pygments.lexers.shell.MSDOSSessionLexer'>: <class 'click_extra.pygments.AnsiMSDOSSessionLexer'>, <class 'pygments.lexers.shell.PowerShellSessionLexer'>: <class 'click_extra.pygments.AnsiPowerShellSessionLexer'>, <class 'pygments.lexers.shell.TcshSessionLexer'>: <class 'click_extra.pygments.AnsiTcshSessionLexer'>, <class 'pygments.lexers.special.OutputLexer'>: <class 'click_extra.pygments.AnsiOutputLexer'>, <class 'pygments.lexers.sql.PostgresConsoleLexer'>: <class 'click_extra.pygments.AnsiPostgresConsoleLexer'>, <class 'pygments.lexers.sql.SqliteConsoleLexer'>: <class 'click_extra.pygments.AnsiSqliteConsoleLexer'>}¶

Map original session lexers to their ANSI-capable variants.

click_extra.pygments.EXTRA_ANSI_CSS: dict[str, str] = {'Blink': 'animation: ansi-blink 1s step-end infinite', 'Bold': 'font-weight: bold', 'Faint': 'opacity: 0.6', 'Italic': 'font-style: italic', 'Overline': 'text-decoration: overline', 'Reverse': 'filter: invert(1)', 'Strikethrough': 'text-decoration: line-through', 'Underline': 'text-decoration: underline'}¶

All SGR text attribute CSS declarations.

Maps Token.Ansi component names to CSS declarations, taken from click_extra.styling._ATTR_CSS so an attribute renders the same in a documentation code block as in the HTML to_css() writes. Blink alone takes _BLINK_CSS. The rules are kept out of the Pygments style dict (_ANSI_STYLES) to prevent Furo’s dark-mode CSS generator from injecting color: #D0D0D0 fallbacks that conflict with foreground color tokens.

Used by AnsiHtmlFormatter.get_token_style_defs to inject CSS rules that both standalone pygmentize and Furo’s dark-mode CSS generator pick up.

class click_extra.pygments.AnsiBashSessionLexer(**options)¶

Bases: _AnsiFilterMixin, BashSessionLexer

ANSI-capable variant of BashSessionLexer.

Add TokenMergeFilter and AnsiFilter to the filter chain.

Session lexers parse code blocks line by line to differentiate inputs and outputs. Each output line ends up encapsulated into a Generic.Output token. The TokenMergeFilter consolidates contiguous output lines into a single token, then AnsiFilter transforms the merged output into ANSI-styled tokens.

Parameters:

true_color – Forwarded to AnsiFilter, and to the inner lexer a shell session builds from its options. Default DEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. Pass False to quantize to the 256-color palette.

aliases = ('ansi-console', 'ansi-shell-session')¶

A list of short, unique identifiers that can be used to look up the lexer from a list, e.g., using get_lexer_by_name().

name = 'ANSI Bash Session'¶

Full name of the lexer, in human-readable form

class click_extra.pygments.AnsiDylanConsoleLexer(**options)¶

Bases: _AnsiFilterMixin, DylanConsoleLexer

ANSI-capable variant of DylanConsoleLexer.

Add TokenMergeFilter and AnsiFilter to the filter chain.

Session lexers parse code blocks line by line to differentiate inputs and outputs. Each output line ends up encapsulated into a Generic.Output token. The TokenMergeFilter consolidates contiguous output lines into a single token, then AnsiFilter transforms the merged output into ANSI-styled tokens.

Parameters:

true_color – Forwarded to AnsiFilter, and to the inner lexer a shell session builds from its options. Default DEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. Pass False to quantize to the 256-color palette.

aliases = ('ansi-dylan-console', 'ansi-dylan-repl')¶

A list of short, unique identifiers that can be used to look up the lexer from a list, e.g., using get_lexer_by_name().

name = 'ANSI Dylan session'¶

Full name of the lexer, in human-readable form

class click_extra.pygments.AnsiElixirConsoleLexer(**options)¶

Bases: _AnsiFilterMixin, ElixirConsoleLexer

ANSI-capable variant of ElixirConsoleLexer.

Add TokenMergeFilter and AnsiFilter to the filter chain.

Session lexers parse code blocks line by line to differentiate inputs and outputs. Each output line ends up encapsulated into a Generic.Output token. The TokenMergeFilter consolidates contiguous output lines into a single token, then AnsiFilter transforms the merged output into ANSI-styled tokens.

Parameters:

true_color – Forwarded to AnsiFilter, and to the inner lexer a shell session builds from its options. Default DEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. Pass False to quantize to the 256-color palette.

aliases = ('ansi-iex',)¶

A list of short, unique identifiers that can be used to look up the lexer from a list, e.g., using get_lexer_by_name().

name = 'ANSI Elixir iex session'¶

Full name of the lexer, in human-readable form

class click_extra.pygments.AnsiErlangShellLexer(**options)¶

Bases: _AnsiFilterMixin, ErlangShellLexer

ANSI-capable variant of ErlangShellLexer.

Add TokenMergeFilter and AnsiFilter to the filter chain.

Session lexers parse code blocks line by line to differentiate inputs and outputs. Each output line ends up encapsulated into a Generic.Output token. The TokenMergeFilter consolidates contiguous output lines into a single token, then AnsiFilter transforms the merged output into ANSI-styled tokens.

Parameters:

true_color – Forwarded to AnsiFilter, and to the inner lexer a shell session builds from its options. Default DEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. Pass False to quantize to the 256-color palette.

aliases = ('ansi-erl',)¶

A list of short, unique identifiers that can be used to look up the lexer from a list, e.g., using get_lexer_by_name().

name = 'ANSI Erlang erl session'¶

Full name of the lexer, in human-readable form

class click_extra.pygments.AnsiGAPConsoleLexer(**options)¶

Bases: _AnsiFilterMixin, GAPConsoleLexer

ANSI-capable variant of GAPConsoleLexer.

Add TokenMergeFilter and AnsiFilter to the filter chain.

Session lexers parse code blocks line by line to differentiate inputs and outputs. Each output line ends up encapsulated into a Generic.Output token. The TokenMergeFilter consolidates contiguous output lines into a single token, then AnsiFilter transforms the merged output into ANSI-styled tokens.

Parameters:

true_color – Forwarded to AnsiFilter, and to the inner lexer a shell session builds from its options. Default DEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. Pass False to quantize to the 256-color palette.

aliases = ('ansi-gap-console', 'ansi-gap-repl')¶

A list of short, unique identifiers that can be used to look up the lexer from a list, e.g., using get_lexer_by_name().

name = 'ANSI GAP session'¶

Full name of the lexer, in human-readable form

class click_extra.pygments.AnsiJuliaConsoleLexer(**options)¶

Bases: _AnsiFilterMixin, JuliaConsoleLexer

ANSI-capable variant of JuliaConsoleLexer.

Add TokenMergeFilter and AnsiFilter to the filter chain.

Session lexers parse code blocks line by line to differentiate inputs and outputs. Each output line ends up encapsulated into a Generic.Output token. The TokenMergeFilter consolidates contiguous output lines into a single token, then AnsiFilter transforms the merged output into ANSI-styled tokens.

Parameters:

true_color – Forwarded to AnsiFilter, and to the inner lexer a shell session builds from its options. Default DEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. Pass False to quantize to the 256-color palette.

aliases = ('ansi-jlcon', 'ansi-julia-repl')¶

A list of short, unique identifiers that can be used to look up the lexer from a list, e.g., using get_lexer_by_name().

name = 'ANSI Julia console'¶

Full name of the lexer, in human-readable form

class click_extra.pygments.AnsiMSDOSSessionLexer(**options)¶

Bases: _AnsiFilterMixin, MSDOSSessionLexer

ANSI-capable variant of MSDOSSessionLexer.

Add TokenMergeFilter and AnsiFilter to the filter chain.

Session lexers parse code blocks line by line to differentiate inputs and outputs. Each output line ends up encapsulated into a Generic.Output token. The TokenMergeFilter consolidates contiguous output lines into a single token, then AnsiFilter transforms the merged output into ANSI-styled tokens.

Parameters:

true_color – Forwarded to AnsiFilter, and to the inner lexer a shell session builds from its options. Default DEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. Pass False to quantize to the 256-color palette.

aliases = ('ansi-doscon',)¶

A list of short, unique identifiers that can be used to look up the lexer from a list, e.g., using get_lexer_by_name().

name = 'ANSI MSDOS Session'¶

Full name of the lexer, in human-readable form

class click_extra.pygments.AnsiMatlabSessionLexer(**options)¶

Bases: _AnsiFilterMixin, MatlabSessionLexer

ANSI-capable variant of MatlabSessionLexer.

Add TokenMergeFilter and AnsiFilter to the filter chain.

Session lexers parse code blocks line by line to differentiate inputs and outputs. Each output line ends up encapsulated into a Generic.Output token. The TokenMergeFilter consolidates contiguous output lines into a single token, then AnsiFilter transforms the merged output into ANSI-styled tokens.

Parameters:

true_color – Forwarded to AnsiFilter, and to the inner lexer a shell session builds from its options. Default DEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. Pass False to quantize to the 256-color palette.

aliases = ('ansi-matlabsession',)¶

A list of short, unique identifiers that can be used to look up the lexer from a list, e.g., using get_lexer_by_name().

name = 'ANSI Matlab session'¶

Full name of the lexer, in human-readable form

class click_extra.pygments.AnsiOutputLexer(**options)¶

Bases: _AnsiFilterMixin, OutputLexer

ANSI-capable variant of OutputLexer.

Add TokenMergeFilter and AnsiFilter to the filter chain.

Session lexers parse code blocks line by line to differentiate inputs and outputs. Each output line ends up encapsulated into a Generic.Output token. The TokenMergeFilter consolidates contiguous output lines into a single token, then AnsiFilter transforms the merged output into ANSI-styled tokens.

Parameters:

true_color – Forwarded to AnsiFilter, and to the inner lexer a shell session builds from its options. Default DEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. Pass False to quantize to the 256-color palette.

aliases = ('ansi-output',)¶

A list of short, unique identifiers that can be used to look up the lexer from a list, e.g., using get_lexer_by_name().

name = 'ANSI Text output'¶

Full name of the lexer, in human-readable form

class click_extra.pygments.AnsiPostgresConsoleLexer(**options)¶

Bases: _AnsiFilterMixin, PostgresConsoleLexer

ANSI-capable variant of PostgresConsoleLexer.

Add TokenMergeFilter and AnsiFilter to the filter chain.

Session lexers parse code blocks line by line to differentiate inputs and outputs. Each output line ends up encapsulated into a Generic.Output token. The TokenMergeFilter consolidates contiguous output lines into a single token, then AnsiFilter transforms the merged output into ANSI-styled tokens.

Parameters:

true_color – Forwarded to AnsiFilter, and to the inner lexer a shell session builds from its options. Default DEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. Pass False to quantize to the 256-color palette.

aliases = ('ansi-psql', 'ansi-postgresql-console', 'ansi-postgres-console')¶

A list of short, unique identifiers that can be used to look up the lexer from a list, e.g., using get_lexer_by_name().

name = 'ANSI PostgreSQL console (psql)'¶

Full name of the lexer, in human-readable form

class click_extra.pygments.AnsiPowerShellSessionLexer(**options)¶

Bases: _AnsiFilterMixin, PowerShellSessionLexer

ANSI-capable variant of PowerShellSessionLexer.

Add TokenMergeFilter and AnsiFilter to the filter chain.

Session lexers parse code blocks line by line to differentiate inputs and outputs. Each output line ends up encapsulated into a Generic.Output token. The TokenMergeFilter consolidates contiguous output lines into a single token, then AnsiFilter transforms the merged output into ANSI-styled tokens.

Parameters:

true_color – Forwarded to AnsiFilter, and to the inner lexer a shell session builds from its options. Default DEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. Pass False to quantize to the 256-color palette.

aliases = ('ansi-pwsh-session', 'ansi-ps1con')¶

A list of short, unique identifiers that can be used to look up the lexer from a list, e.g., using get_lexer_by_name().

name = 'ANSI PowerShell Session'¶

Full name of the lexer, in human-readable form

class click_extra.pygments.AnsiPsyshConsoleLexer(**options)¶

Bases: _AnsiFilterMixin, PsyshConsoleLexer

ANSI-capable variant of PsyshConsoleLexer.

Add TokenMergeFilter and AnsiFilter to the filter chain.

Session lexers parse code blocks line by line to differentiate inputs and outputs. Each output line ends up encapsulated into a Generic.Output token. The TokenMergeFilter consolidates contiguous output lines into a single token, then AnsiFilter transforms the merged output into ANSI-styled tokens.

Parameters:

true_color – Forwarded to AnsiFilter, and to the inner lexer a shell session builds from its options. Default DEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. Pass False to quantize to the 256-color palette.

aliases = ('ansi-psysh',)¶

A list of short, unique identifiers that can be used to look up the lexer from a list, e.g., using get_lexer_by_name().

name = 'ANSI PsySH console session for PHP'¶

Full name of the lexer, in human-readable form

class click_extra.pygments.AnsiPythonConsoleLexer(**options)¶

Bases: _AnsiFilterMixin, PythonConsoleLexer

ANSI-capable variant of PythonConsoleLexer.

Add TokenMergeFilter and AnsiFilter to the filter chain.

Session lexers parse code blocks line by line to differentiate inputs and outputs. Each output line ends up encapsulated into a Generic.Output token. The TokenMergeFilter consolidates contiguous output lines into a single token, then AnsiFilter transforms the merged output into ANSI-styled tokens.

Parameters:

true_color – Forwarded to AnsiFilter, and to the inner lexer a shell session builds from its options. Default DEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. Pass False to quantize to the 256-color palette.

aliases = ('ansi-pycon', 'ansi-python-console')¶

A list of short, unique identifiers that can be used to look up the lexer from a list, e.g., using get_lexer_by_name().

name = 'ANSI Python console session'¶

Full name of the lexer, in human-readable form

class click_extra.pygments.AnsiRConsoleLexer(**options)¶

Bases: _AnsiFilterMixin, RConsoleLexer

ANSI-capable variant of RConsoleLexer.

Add TokenMergeFilter and AnsiFilter to the filter chain.

Session lexers parse code blocks line by line to differentiate inputs and outputs. Each output line ends up encapsulated into a Generic.Output token. The TokenMergeFilter consolidates contiguous output lines into a single token, then AnsiFilter transforms the merged output into ANSI-styled tokens.

Parameters:

true_color – Forwarded to AnsiFilter, and to the inner lexer a shell session builds from its options. Default DEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. Pass False to quantize to the 256-color palette.

aliases = ('ansi-rconsole', 'ansi-rout')¶

A list of short, unique identifiers that can be used to look up the lexer from a list, e.g., using get_lexer_by_name().

name = 'ANSI RConsole'¶

Full name of the lexer, in human-readable form

class click_extra.pygments.AnsiRubyConsoleLexer(**options)¶

Bases: _AnsiFilterMixin, RubyConsoleLexer

ANSI-capable variant of RubyConsoleLexer.

Add TokenMergeFilter and AnsiFilter to the filter chain.

Session lexers parse code blocks line by line to differentiate inputs and outputs. Each output line ends up encapsulated into a Generic.Output token. The TokenMergeFilter consolidates contiguous output lines into a single token, then AnsiFilter transforms the merged output into ANSI-styled tokens.

Parameters:

true_color – Forwarded to AnsiFilter, and to the inner lexer a shell session builds from its options. Default DEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. Pass False to quantize to the 256-color palette.

aliases = ('ansi-rbcon', 'ansi-irb')¶

A list of short, unique identifiers that can be used to look up the lexer from a list, e.g., using get_lexer_by_name().

name = 'ANSI Ruby irb session'¶

Full name of the lexer, in human-readable form

class click_extra.pygments.AnsiSqliteConsoleLexer(**options)¶

Bases: _AnsiFilterMixin, SqliteConsoleLexer

ANSI-capable variant of SqliteConsoleLexer.

Add TokenMergeFilter and AnsiFilter to the filter chain.

Session lexers parse code blocks line by line to differentiate inputs and outputs. Each output line ends up encapsulated into a Generic.Output token. The TokenMergeFilter consolidates contiguous output lines into a single token, then AnsiFilter transforms the merged output into ANSI-styled tokens.

Parameters:

true_color – Forwarded to AnsiFilter, and to the inner lexer a shell session builds from its options. Default DEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. Pass False to quantize to the 256-color palette.

aliases = ('ansi-sqlite3',)¶

A list of short, unique identifiers that can be used to look up the lexer from a list, e.g., using get_lexer_by_name().

name = 'ANSI sqlite3con'¶

Full name of the lexer, in human-readable form

class click_extra.pygments.AnsiTcshSessionLexer(**options)¶

Bases: _AnsiFilterMixin, TcshSessionLexer

ANSI-capable variant of TcshSessionLexer.

Add TokenMergeFilter and AnsiFilter to the filter chain.

Session lexers parse code blocks line by line to differentiate inputs and outputs. Each output line ends up encapsulated into a Generic.Output token. The TokenMergeFilter consolidates contiguous output lines into a single token, then AnsiFilter transforms the merged output into ANSI-styled tokens.

Parameters:

true_color – Forwarded to AnsiFilter, and to the inner lexer a shell session builds from its options. Default DEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. Pass False to quantize to the 256-color palette.

aliases = ('ansi-tcshcon',)¶

A list of short, unique identifiers that can be used to look up the lexer from a list, e.g., using get_lexer_by_name().

name = 'ANSI Tcsh Session'¶

Full name of the lexer, in human-readable form

class click_extra.pygments.AnsiHtmlFormatter(**kwargs)[source]¶

Bases: HtmlFormatter

HTML formatter with ANSI color and hyperlink support.

Extends Pygments’ HtmlFormatter to handle compound Token.Ansi.* tokens by decomposing them into individual CSS classes, augments the base style with ANSI color definitions for the 256-color indexed palette, and renders OSC 8 hyperlinks as HTML <a> tags.

Intercept the style argument to augment it with ANSI color support.

The formatter runs on a subclass of the style provided by the user, whose styles attribute is extended with the ANSI token definitions of _ANSI_STYLES, see _ansi_style.

name = 'ANSI HTML'¶

Full name for the formatter, in human-readable form.

aliases: ClassVar[list[str]] = ['ansi-html']¶

A list of short, unique identifiers that can be used to lookup the formatter from a list, e.g. using get_formatter_by_name().

format_unencoded(tokensource, outfile)[source]¶

Render tokens to HTML, converting OSC 8 link and 24-bit RGB markers to tags.

Replaces Token.AnsiLinkStart / Token.AnsiLinkEnd with Unicode Private Use Area markers, strips FG_/BG_ 24-bit RGB components from compound tokens and replaces them with PUA markers carrying the hex value, delegates to Pygments’ HTML rendering, then post-processes the output to swap markers for <a> and inline-styled <span> tags.

Return type:

None

get_token_style_defs(arg=None)[source]¶

Extend Pygments’ token CSS with rules for SGR attributes it cannot express.

Overriding get_token_style_defs (rather than get_style_defs) ensures that Furo’s dark-mode CSS generator, which calls this method directly, also picks up the extra rules built by _extra_ansi_css_lines.

get_ansi_style_defs(arg=None)[source]¶

Return only this formatter’s ANSI CSS, dropping Pygments’ base syntax-token rules.

The MkDocs plugin layers these over a theme’s own syntax highlighting, so it must not pull in the standard token rules (those would override the theme). Keeps the -Ansi-* token rules plus everything _extra_ansi_css_lines adds. Owning this selection here, next to the rules it returns, keeps the MkDocs plugin from hard-coding this formatter’s class names and CSS internals.

Return type:

str

click_extra.pytest module¶

Pytest fixtures and marks to help testing Click CLIs.

click_extra.pytest.runner()[source]¶

Runner fixture for click_extra.testing.CliRunner.

Pins HOME (and its platform-specific equivalents) to a subdirectory of the runner’s isolated filesystem so configuration-file discovery is deterministic and independent of the ambient environment. Without this, the handful of tests asserting on the config-search debug output depend on the caller’s HOME: hermetic builders set HOME=/homeless-shelter, which would otherwise leak into those assertions. XDG_CACHE_HOME is pinned too, so get_cache_dir() never sends a CLI under test to the cache of the user running the tests.

It also unsets every variable in COLOR_ENVVARS. The color option reads them, so a FORCE_COLOR or CLICOLOR_FORCE in the caller’s shell would otherwise leave ANSI codes in the output a test matches as plain text. A test that wants them passes env= or force_color=True to invoke().

The environment is patched directly (via temporary_env()) rather than through the monkeypatch fixture on purpose: depending on monkeypatch here would tear it down after isolated_filesystem removed the working directory it tries to restore, breaking unrelated tests that chdir within the runner. For the same reason, an autouse fixture that patches the environment must use its own pytest.MonkeyPatch.context(), not the monkeypatch fixture, which would outlive this one.

Warning

The pinning is scoped to each test requesting this fixture, but a cache filled from inside one is not: a module-global populated lazily during a test records what a home-less environment answered, and keeps serving that for the rest of the worker’s session. A binary resolved through a $HOME-dependent shim is the usual victim, answering an error rather than a version, after which every later test on that worker sees the tool as missing. Seed such a cache from a session-scoped fixture, which runs before the first test and outside this isolation.

click_extra.pytest.invoke(runner)[source]¶

Invoke fixture shorthand for click_extra.testing.CliRunner.invoke().

click_extra.pytest.isolated_app_dir(monkeypatch, tmp_path)[source]¶

Repoint configuration-file discovery at a fresh, empty directory.

The default --config search pattern derives from click.get_app_dir(), which resolves to the host configuration folder (~/Library/Application Support/<app> on macOS, ~/.config/<app> on Unix, %APPDATA%\<app> on Windows). Any configuration file living there bleeds into every in-process CLI invocation, making a test suite pass or fail depending on the developer’s personal configuration.

This fixture repoints get_app_dir (both click’s and the reference bound into click-extra’s config machinery) at a per-test temporary directory, whatever application name is requested. It returns that directory, so a test can also plant a configuration file in it to exercise the default discovery against a controlled file.

An explicit --config <path> bypasses the default search pattern and is left unaffected.

Note

The runner() fixture pins HOME and its platform equivalents inside an isolated filesystem, which also redirects the discovery paths built from the home directory, but only for tests requesting that fixture. This one intercepts get_app_dir directly, covering any in-process invocation, without touching HOME (a suite may need the real one elsewhere) and without leaking into subprocesses.

To make a whole suite hermetic, alias it to an autouse fixture in your conftest.py:

import pytest


@pytest.fixture(autouse=True)
def isolate_user_config(isolated_app_dir):
    return isolated_app_dir
click_extra.pytest.command_decorators(no_commands=False, no_groups=False, no_click=False, no_cloup=False, no_extra=False, with_parenthesis=True, with_types=False)[source]¶

Return the Pytest parameters testing every command-like decorator.

Return type:

tuple[ParameterSet, ...]

Returns:

Pytest parameters covering each command-like decorator variant:

  • click.command

  • click.command()

  • cloup.command

  • cloup.command()

  • click_extra.command

  • click_extra.command()

  • click.group

  • click.group()

  • cloup.group

  • cloup.group()

  • click_extra.group

  • click_extra.group()

click_extra.pytest.option_decorators(no_options=False, no_arguments=False, no_click=False, no_cloup=False, no_extra=False, with_parenthesis=True, with_types=False)[source]¶

Return the Pytest parameters testing every parameter-like decorator.

Return type:

tuple[ParameterSet, ...]

Returns:

Pytest parameters covering each parameter-like decorator variant:

  • click.option

  • click.option()

  • cloup.option

  • cloup.option()

  • click_extra.option

  • click_extra.option()

  • click.argument

  • click.argument()

  • cloup.argument

  • cloup.argument()

  • click_extra.argument

  • click_extra.argument()

click_extra.pytest.create_config(tmp_path)[source]¶

A generic fixture to produce a temporary configuration file.

click_extra.pytest.assert_output_regex()[source]¶

An assert-like utility for Pytest to compare CLI output against the regex.

Designed for the regexes defined above.

click_extra.show_params module¶

The --params option, which prints a table of every parameter of a CLI.

The table shows each parameter’s value and where that value comes from: the command line, an environment variable, a configuration file or a default.

click_extra.show_params.param_config_source(root_ctx, keys)[source]¶

Return the configuration file supplying a parameter’s default_map value.

keys is the parameter’s fully-qualified path, root command name first and parameter name last, as yielded by walk_command_params(). A local file is returned as a Path, a remote one as its URL, a str. Returns None when no configuration file was loaded, when the parameter is absent from every loaded layer, or when the context carries no layered default_map at all.

The walk mirrors how Click resolves default_map, so the attribution matches the value Click actually picks. The root context’s default_map is a ~collections.ChainMap whose first layers are the loaded files, in the order of CONF_SOURCES. A key resolves to the first layer holding it, in a subcommand section as at the root: the first layer holding the whole path of the parameter names the file.

Note

Lazy subcommands receive their section from the merged configuration document, injected into the front layer by _apply_config_to_parent_context(): those values are attributed to the highest-precedence file even when several files contributed to the merge.

Return type:

Path | str | None

click_extra.show_params.render_params_table(subject_ctx, *, default_columns=None)[source]¶

Introspect subject_ctx.command and print its parameter metadata table.

Walks the command and any nested subcommands, emitting one row per parameter. The table format and column selection are read from subject_ctx.meta (see TABLE_FORMAT and COLUMNS); when neither is set, a sibling --table-format / --columns option on the command is consulted, then the default_columns fallback, then the canonical order.

When subject_ctx.meta carries pre-parsed RAW_ARGS, the value and source columns are resolved by replaying those arguments against the command parser; otherwise they fall back to the parameter defaults.

This is the shared rendering core behind both print_params() (introspecting the live CLI) and the click-extra wrap --params path (introspecting a foreign target). The caller is responsible for exiting the context afterwards.

Important

Click does not keep the raw, pre-parsed arguments around, so values and their provenance cannot be read back directly. The workaround replays RAW_ARGS (captured on the context by Command/Group) through the command parser, calling consume_value() rather than handle_parse_result() so eager callbacks are not re-triggered.

Return type:

None

class click_extra.show_params.ShowParamsOption(param_decls=None, *, is_flag=True, expose_value=False, is_eager=True, help='Show all CLI parameters, their provenance, defaults and value, then exit.', **kwargs)[source]¶

Bases: ExtraOption, ParamStructure

A pre-configured option adding a --params option.

Between configuration files, default values and environment variables, it might be hard to guess under which set of parameters the CLI will be executed. This option prints information about the parameters that will be fed to the CLI.

Note

The flag is named --params, not --show-params. It names the view it prints, matching the neighbouring bare-noun informational flags (--help, --version, --man, --tree), none of which carry a show- verb prefix. The class and the @show_params_option decorator are named for what they do (show the parameters), while the flag and the parameter’s ID use the bare noun.

TABLE_HEADERS: ClassVar[tuple[ColumnSpec, ...]] = (ColumnSpec(id='id', label='ID', description='Fully-qualified parameter path (`cli.subcommand.param_name`) derived from the [`click.Command`](https://click.palletsprojects.com/en/stable/api/#click.Command) tree. Doubles as the key used to address the parameter from a configuration file, which also accepts the kebab-case spelling of the last segment.', max_width=None, optional=False, sortable=True), ColumnSpec(id='spec', label='Spec.', description='Option/argument specification string (like `-v, --verbose`) extracted from [`click.Parameter.get_help_record()`](https://click.palletsprojects.com/en/stable/api/#click.Parameter).', max_width=None, optional=False, sortable=True), ColumnSpec(id='help', label='Help', description="The parameter's own help text, as written by the CLI author. Opt-in: it is the only column carrying free-form prose, so it stays out of the default table and is selected by ID (`--columns id,spec,help`). Structured formats are its main audience: it turns a `--params` dump into a self-describing inventory a tool or an agent can read without also parsing the rendered `--help` screen.", max_width=None, optional=True, sortable=True), ColumnSpec(id='class', label='Class', description="Fully-qualified class of the parameter: a subclass of [`click.Option`](https://click.palletsprojects.com/en/stable/api/#click.Option), [`click.Argument`](https://click.palletsprojects.com/en/stable/api/#click.Argument), [`cloup.Option`](https://cloup.readthedocs.io/en/stable/autoapi/cloup/index.html#cloup.Option), or one of Click Extra's own wrappers ([`click_extra.parameters.Option`](#click_extra.parameters.Option), [`click_extra.parameters.Argument`](#click_extra.parameters.Argument), [`click_extra.parameters.ExtraOption`](#click_extra.parameters.ExtraOption)).", max_width=None, optional=False, sortable=True), ColumnSpec(id='param_type', label='Param type', description='Click value converter class: a subclass of [`click.ParamType`](https://click.palletsprojects.com/en/stable/api/#click.ParamType) like [`click.IntRange`](https://click.palletsprojects.com/en/stable/api/#click.IntRange), [`click.Choice`](https://click.palletsprojects.com/en/stable/api/#click.Choice), or a Click Extra type.', max_width=None, optional=False, sortable=True), ColumnSpec(id='python_type', label='Python type', description='Python built-in type the parsed value resolves to: [`str`](https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str), [`int`](https://docs.python.org/3/library/functions.html#int), [`float`](https://docs.python.org/3/library/functions.html#float), [`bool`](https://docs.python.org/3/library/functions.html#bool), or [`list`](https://docs.python.org/3/library/stdtypes.html#list). Computed by [`ParamStructure.get_param_type()`](#click_extra.param_tools.ParamStructure.get_param_type) from the Click `Param type`.', max_width=None, optional=False, sortable=True), ColumnSpec(id='hidden', label='Hidden', description="Reflects [`click.Option`'s `hidden`](https://click.palletsprojects.com/en/stable/api/#click.Option) constructor argument: the option is omitted from `--help` output. Empty for [`click.Argument`](https://click.palletsprojects.com/en/stable/api/#click.Argument), which does not support hiding.", max_width=None, optional=False, sortable=True), ColumnSpec(id='exposed', label='Exposed', description="Reflects [`click.Parameter`'s `expose_value`](https://click.palletsprojects.com/en/stable/api/#click.Parameter) constructor argument: whether the parsed value is forwarded to the command callback. Eager options like `--params` and `--help` typically run a callback and exit, so they are not exposed.", max_width=None, optional=False, sortable=True), ColumnSpec(id='allowed_in_conf', label='Allowed in conf?', description='Click Extra-specific: whether the parameter is reachable from a configuration file. Controlled by [`ParamStructure.excluded_params`](#click_extra.param_tools.ParamStructure.excluded_params) and [`included_params`](#click_extra.param_tools.ParamStructure.included_params). Empty when the CLI has no [`--config` option](config.md).', max_width=None, optional=False, sortable=True), ColumnSpec(id='envvars', label='Env. vars.', description="Environment variables read for this parameter: the explicit [`click.Parameter`'s `envvar`](https://click.palletsprojects.com/en/stable/api/#click.Parameter) plus the auto-resolved IDs documented in [Environment variables](envvar.md).", max_width=None, optional=False, sortable=True), ColumnSpec(id='default', label='Default', description='Default value returned by [`click.Parameter.get_default()`](https://click.palletsprojects.com/en/stable/api/#click.Parameter.get_default), rendered as its Python `repr()`.', max_width=None, optional=False, sortable=True), ColumnSpec(id='is_flag', label='Is flag', description="Reflects [`click.Option`'s `is_flag`](https://click.palletsprojects.com/en/stable/api/#click.Option): whether the option behaves as a flag (no value taken from the command line). Empty for [`click.Argument`](https://click.palletsprojects.com/en/stable/api/#click.Argument).", max_width=None, optional=False, sortable=True), ColumnSpec(id='flag_value', label='Flag value', description="Reflects [`click.Option`'s `flag_value`](https://click.palletsprojects.com/en/stable/api/#click.Option): the Python value substituted for the option when its flag is used. Defaults to `True` for boolean flags, can be any value for flag-value style options (like `@option('--upper', 'transform', flag_value='upper')`).", max_width=None, optional=False, sortable=True), ColumnSpec(id='is_bool_flag', label='Is bool flag', description='Reflects `click.Option.is_bool_flag` (set internally by Click when `flag_value` is `True` or `False`): the option is a *true* boolean flag, as opposed to a flag-value style option.', max_width=None, optional=False, sortable=True), ColumnSpec(id='multiple', label='Multiple', description="Reflects [`click.Parameter`'s `multiple`](https://click.palletsprojects.com/en/stable/api/#click.Parameter): the parameter can be repeated on the command line, collecting values into a tuple.", max_width=None, optional=False, sortable=True), ColumnSpec(id='nargs', label='Nargs', description="Reflects [`click.Parameter`'s `nargs`](https://click.palletsprojects.com/en/stable/api/#click.Parameter): the number of CLI tokens the parameter consumes. `1` is the default; `-1` denotes a variadic argument.", max_width=None, optional=False, sortable=True), ColumnSpec(id='prompt', label='Prompt', description="Reflects [`click.Option`'s `prompt`](https://click.palletsprojects.com/en/stable/api/#click.Option): the text shown to the user when the option is not provided on the command line. Empty when no prompt is configured.", max_width=None, optional=False, sortable=True), ColumnSpec(id='confirmation_prompt', label='Confirmation prompt', description="Reflects [`click.Option`'s `confirmation_prompt`](https://click.palletsprojects.com/en/stable/api/#click.Option): whether the user is asked to enter the value twice for confirmation.", max_width=None, optional=False, sortable=True), ColumnSpec(id='value', label='Value', description='Current value of the parameter at invocation time, computed by [`click.Parameter.consume_value()`](https://click.palletsprojects.com/en/stable/api/#click.Parameter) from the merged sources (CLI, environment, config file, default).', max_width=None, optional=False, sortable=True), ColumnSpec(id='source', label='Source', description='Provenance of the resolved value: a [`click.core.ParameterSource`](https://click.palletsprojects.com/en/stable/api/#click.core.ParameterSource) enum member such as `COMMANDLINE`, `ENVIRONMENT`, `DEFAULT_MAP`, or `DEFAULT`.', max_width=None, optional=False, sortable=True), ColumnSpec(id='config_file', label='Config file', description='The configuration file the effective value was loaded from, when `Source` reports `DEFAULT_MAP`. With [`cascade=True`](config-discovery.md#cascading-configuration-files) several files are layered and this column names the one that won the parameter; with a single loaded file, every config-sourced parameter names that file. Empty for every other source and when no configuration file was loaded. Drawn by default when the `--config` option cascades, and opt-in otherwise, like `help`: paths are wide and stay redundant with `Source` until several files can take part.', max_width=None, optional=True, sortable=True))¶

Rich column registry for the --params table.

Each entry is a click_extra.columns.ColumnSpec carrying the column’s stable id (used by --columns and as structured-format key), its display label, and a MyST/Markdown description consumed by the documentation’s auto-generated Available columns section. Iteration yields columns in canonical display order.

classmethod column_labels()[source]¶

Return just the display labels of TABLE_HEADERS (in order).

Return type:

tuple[str, ...]

classmethod column_ids()[source]¶

Return just the stable IDs of TABLE_HEADERS (in order).

Return type:

tuple[str, ...]

classmethod default_columns()[source]¶

Return the columns rendered when --columns asks for no projection.

Every column but the optional ones, which stay addressable by ID and out of the way until named.

Return type:

tuple[ColumnSpec, ...]

classmethod default_column_ids()[source]¶

Return the stable IDs of default_columns() (in order).

Return type:

tuple[str, ...]

classmethod default_column_labels()[source]¶

Return the display labels of default_columns() (in order).

Return type:

tuple[str, ...]

classmethod find_column(column_id)[source]¶

Return the ColumnSpec matching column_id.

Raises:

KeyError – if no column has this ID. Convert it into a click.UsageError before it reaches a user.

Return type:

ColumnSpec

classmethod render_doc_table()[source]¶

Render TABLE_HEADERS as a Markdown table for documentation.

Used by the show_params_columns_table MyST substitution in docs/conf.py to feed the Available columns section of docs/parameters.md: editing a description here automatically rebuilds the docs table on the next sphinx-build.

Return type:

str

excluded_params: frozenset[str]¶

Deactivates the blocking of any parameter.

included_params: frozenset[str] | None¶

No allowlist filter; show all parameters.

print_params(ctx, param, value)[source]¶

Introspect the current CLI and print its parameter metadata table.

Thin wrapper over render_params_table(), the shared rendering core also driving click-extra wrap --params for foreign CLIs. The live invocation context carries everything the core needs: the captured RAW_ARGS (attached by Command/Group) for value and source resolution, plus any sibling --table-format / --columns options.

Return type:

None

click_extra.spinner module¶

An indeterminate terminal spinner for long-running, blocking work.

Click ships click.progressbar(), but it is determinate: it needs a known length or an iterable to advance through. Some work has no measurable progress: a blocking subprocess, a network round-trip, a query whose duration is unknown. For those, the only honest feedback is ā€œsomething is happeningā€.

Spinner fills that gap. It animates a small frame sequence on a daemon thread, so the caller can stay blocked in a single call (communicate(), urlopen(), …) while the spinner keeps turning:

from time import sleep

from click_extra import Spinner

with Spinner("Brewing tea"):
    sleep(5)  # A blocking call with no measurable progress.

This module also keeps the registry of the live lines drawing on the terminal, which OperationTrail and progressbar() join while they draw.

Caution

The spinner draws with carriage returns and ANSI control codes, so it is a no-op whenever its output stream is not a TTY (a pipe, a file, a captured test buffer, a CI log), unless live="always" forces it. This keeps redirected output and machine-readable formats clean.

Note

On Windows, Spinner.start() enables the console’s virtual-terminal processing so the ANSI control codes animate in place rather than print literally (⠋␛[0m … ␛[K). Modern terminals (Windows Terminal, recent conhost) already have it on; this just covers older consoles.

click_extra.spinner.CLEAR_LINE: Final = '\x1b[K'¶

Erase the line from the cursor to its end.

Written after a carriage return, it clears the row a live line is about to redraw, so a shrinking label leaves no stale characters behind.

click_extra.spinner.HIDE_CURSOR: Final = '\x1b[?25l'¶

Hide the terminal’s cursor, which would otherwise flicker beside a live line.

click_extra.spinner.SHOW_CURSOR: Final = '\x1b[?25h'¶

Show the cursor again, once a live line stops drawing.

click_extra.spinner.DEFAULT_INTERVAL: Final = 0.1¶

Seconds between two frames of a Spinner given no other cadence.

Also how often a progress bar carrying a running clock redraws, so the two live lines tick at the same rate.

click_extra.spinner.active_spinner(stream=None)[source]¶

Return the innermost Spinner currently animating, or None.

A spinner-typed view of _active_line(), skipping any progress-bar indicator that may own the line instead. With stream given, only a spinner drawing on that very stream matches.

Return type:

Spinner | None

click_extra.spinner.trail_glyph(ok, symbol=None, style=None, *, color=True)[source]¶

Return the āœ“ or ✘ glyph marking an outcome, painted for it.

The success glyph OK_GLYPH painted with the active theme’s success slot, or the failure glyph KO_GLYPH painted with its error slot.

Parameters:
  • ok (bool) – whether the outcome is a success.

  • symbol (str | None) – a glyph to draw in place of the themed one.

  • style (Style | None) – a style to paint the glyph with, in place of the theme’s slot.

  • color (bool) – whether to paint the glyph at all. With color off, the glyph goes bare and the theme is never consulted.

Return type:

str

Returns:

the glyph, painted or bare.

class click_extra.spinner.Spinner(label='', *, frames=None, spinner=None, reverse=False, interval=None, delay=0.0, style=None, label_style=None, timer=None, timer_style=None, stream=None, live='auto', hide_cursor=True, beep=False)[source]¶

Bases: object

A thread-animated, indeterminate progress spinner usable as a context manager.

The animation runs on a background daemon thread, leaving the calling thread free to block on the actual work. Entering the context (or calling start()) begins the animation; leaving it (or calling stop()) halts the thread and erases the spinner line so it never lingers above the next output.

Note

A single Spinner instance drives one animation at a time. A tool running its steps one after another can share one instance and reassign its label between steps. Concurrent work takes one instance per thread.

Configure (but do not start) the spinner.

Parameters:
  • label (str | Callable[..., Any]) – text shown after the spinner glyph. As a special case, a bare @Spinner decorator passes the wrapped function here instead; it is detected and the label defaults to empty.

  • frames (Sequence[str] | None) – the animation frames, cycled in order. Defaults to SPINNER_FRAMES, or the spinner preset’s frames when given.

  • spinner (SpinnerPreset | None) – a SpinnerPreset from the SPINNERS catalog (spinner=SPINNERS["moon"]), supplying both frames and a tuned interval. An explicit frames or interval still overrides it.

  • reverse (bool) – cycle the frames backwards, spinning the animation the other way. Set it when the rotation runs counter to what you expect; it composes with any custom frames.

  • interval (float | None) – seconds between two frames. Defaults to DEFAULT_INTERVAL, or the spinner preset’s interval when given.

  • delay (float) – seconds to wait before drawing the first frame. A non-zero delay keeps the spinner silent for calls that finish quickly, so it only surfaces once an operation is genuinely slow.

  • style (Style | None) – a Style applied to the spinner glyph, label and timer (Style(fg="cyan", bold=True)). Color is decoupled from animation: --no-color / NO_COLOR strip it while the spinner keeps spinning (see ProgressOption). The strip reaches escapes embedded in label itself too, so a label styled by hand is as safe as one styled through these arguments.

  • label_style (Style | None) – a Style for the label alone, in place of style there. It also paints the label of the kept ok() / fail() line, which style leaves plain. It outlives a reassigned label, where styling embedded in the text has to be applied again at every step.

  • timer (bool | Callable[[float], str] | None) – append the elapsed wall-clock time to the spinner, and to any final ok() / fail() line. None (the default) follows the CLI’s --time / --no-time flag, as an OperationTrail does. True forces it on with format_duration()’s compact format (2.3s, 1:05, then 1:02:03), False forces it off, and a callable (seconds: float) -> str formats the duration yourself, like timer=lambda s: f"{s / 60:.0f}m" for whole minutes.

  • timer_style (Style | None) – a Style for the timer, parentheses included, in place of style there (Style(dim=True) to set the clock back from the label). A timer callable formats only the duration, so it cannot reach the parentheses: this can. Also paints the timer of the kept ok() / fail() line.

  • stream (IO[str] | None) – where to draw; defaults to sys.stderr so the spinner never mixes into stdout data.

  • live (Literal['auto', 'always', 'never']) – where the animation may draw: "auto" (the default) on an interactive terminal only, unless --no-progress turns it off, "always" on any stream, "never" nowhere. A spinner that does not draw still writes its ok() / fail() line.

  • hide_cursor (bool) – hide the text cursor while spinning and restore it on stop.

  • beep (bool) – ring the terminal bell once when the spinner stops. It fires only when the spinner was active, so a disabled or redirected spinner stays silent.

Raises:

ValueError – if style, label_style or timer_style carries a color or attribute that cannot be rendered, or if live is not one of WHEN.

label: str¶

Text drawn after the spinner glyph.

Reassign it at any time while the spinner runs to reflect the current step; the animation thread reads it afresh on every frame.

property elapsed_time: float¶

Seconds elapsed since start(), frozen once stop() is called.

Returns 0.0 before the spinner has started.

property shown: bool¶

Whether the spinner has drawn at least one frame to its stream.

True only once an animation frame was actually rendered. It stays False for a disabled spinner (off a TTY, on a TERM=dumb terminal, or with live="never") and for a call that finishes within delay, before the first frame. Reset by start().

Use it to gate output that should mirror the spinner’s visibility. ok() and fail() write their line unconditionally, so an outcome is still recorded in a pipe or log. Guard them with shown when you only want the finisher on screen after a spinner the user actually saw:

with Spinner("Baking bread") as spinner:
    bake()
    if spinner.shown:
        spinner.ok()
frame_lines(*, color=True)[source]¶

Every line this spinner’s animation draws, one per frame.

One turn of the animation, held still. reverse, the label, the style and the timer all land the way start() would draw them, which is what an animated capture stacks into a picture of this spinner.

Note

The timer is read once, here, so every line carries the same elapsed time rather than a counting one: a still cannot show a clock running. A spinner that never started reads zero.

Parameters:

color (bool) – style each line. On by default, because a capture renders ANSI whatever the terminal the spinner would have drawn on accepts.

Return type:

tuple[str, ...]

Returns:

the lines, in the order the animation cycles them.

start()[source]¶

Begin animating on a background thread, unless the spinner is disabled.

A disabled spinner (non-TTY stream, or live="never") returns at once without spawning a thread or emitting anything (but still records the start time, so a later ok() / fail() can report a duration).

Return type:

None

stop()[source]¶

Halt the animation and erase the spinner line.

Idempotent and safe to call when the spinner never started. Restores the cursor and clears the line only if the animation actually drew to the terminal.

Return type:

None

echo(message='')[source]¶

Print message on its own line above the running spinner.

Click’s click.progressbar() and a bare print both fight the animation: a frame drawn between the cursor returns and the text mangles the line. echo() takes the same draw lock as the animation thread, erases the in-progress frame, writes message followed by a newline, and lets the next tick redraw the spinner underneath. It is safe to call from another thread while the spinner runs.

Output goes to the spinner’s own stream (stderr by default), so results written to stdout never need it. When the spinner is not animating (disabled, or a non-TTY stream), it degrades to a plain write of message with no control codes.

Return type:

None

ok(symbol=None, *, style=None)[source]¶

Stop the spinner and leave a persistent success line on screen.

Where stop() erases the spinner, ok() replaces the final frame with symbol followed by the current label (and the elapsed time when timer is set), then keeps that line. symbol defaults to the themed success glyph OK_GLYPH (āœ“), painted with the active theme’s success slot unless style overrides it. Color is stripped under --no-color / NO_COLOR; the glyph stays.

Return type:

None

fail(symbol=None, *, style=None)[source]¶

Stop the spinner and leave a persistent failure line on screen.

The failure counterpart of ok(), defaulting to KO_GLYPH (✘) painted with the active theme’s error slot.

Return type:

None

class click_extra.spinner.ProgressOption(param_decls=None, *, is_flag=True, default=True, is_eager=True, expose_value=False, help='Show progress indicators during long operations. Disabled for non-interactive output (pipes, dumb terminals, CI) and by --accessible.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured --progress/--no-progress flag gating spinner display.

Resolves to a single boolean published at ctx.meta[click_extra.context.PROGRESS], which Spinner, OperationTrail and progressbar() read on their own when left at their automatic default. The default is True; --accessible lowers it to False (via default_map) so a screen reader is never handed a spinning glyph.

Note

Spinner display is decoupled from color, even though both emit ANSI. A spinner is an interactivity concern, not a color one: it is built from cursor-control codes (hide-cursor, carriage return, clear-line), which the NO_COLOR standard does not govern. It ā€œonly signals the user’s intention regarding adding ANSI color to text outputā€. So --no-color / NO_COLOR strip the spinner’s colors but never hide it.

The wider ecosystem treats the two axes the same way: cargo, npm, pip, Rich, indicatif and ora all gate progress on the terminal (and a dedicated --progress/--quiet knob), while NO_COLOR only affects color. Rich takes TERM=dumb, not NO_COLOR, as the signal to drop cursor-moving features like progress bars.

Two things silence the spinner, neither of them color:

  • non-interactive output: a pipe, file, CI log, or TERM=dumb terminal that cannot move the cursor (see _can_draw());

  • explicit intent: --no-progress or --accessible.

This option is eager. It never reads ctx.color, so its position relative to ColorOption does not matter.

set_progress(ctx, param, value)[source]¶

Publish whether progress spinners may be shown.

Stores the resolved --progress flag at PROGRESS. Deliberately independent of color: see the ProgressOption note for why a spinner is gated on interactivity (TTY / TERM=dumb) and --accessible, never on --no-color / NO_COLOR.

Return type:

None

click_extra.spinner_presets module¶

The bundled catalog of terminal spinner presets.

Ported from cli-spinners, with frame intervals converted from milliseconds to seconds.

Note

One upstream entry is deliberately absent. timeTravel is clock running backwards, which upstream has to ship as a second preset because its renderers only play frames forwards. Spinner takes a reverse argument, so the same animation is SPINNERS["clock"] with reverse=True and a duplicate would only be a second name for it.

Note

The emoji frames are one cell narrower than upstream writes them. Upstream pads each with a trailing space, so a terminal drawing the emoji one cell wide still leaves a gap before whatever follows. Here that space is one cell too many: Spinner already writes one before its label, and the pair reads as a double gap. A capture laid out on the frames alone also reserves a column nothing is ever drawn in, which leaves the glyph off center.

Every frame of a preset is the same width, so a label never moves as the animation turns. weather is the one upstream entry that was ragged, mixing two- and three-cell frames.

click_extra.spinner_presets.ASCII_SPINNER_FRAMES: Final = ('-', '\\', '|', '/')¶

Plain ASCII animation frames, for terminals or fonts lacking Unicode glyphs.

click_extra.spinner_presets.SPINNER_FRAMES: Final = ('ā ‹', 'ā ™', 'ā ¹', 'ā ø', 'ā ¼', 'ā “', 'ā ¦', 'ā §', 'ā ‡', 'ā ')¶

Default animation frames: the ubiquitous Braille-dots spinner.

Ten frames give a smooth rotation in any UTF-8 terminal. Fall back to ASCII_SPINNER_FRAMES where Braille glyphs are unavailable.

class click_extra.spinner_presets.SpinnerPreset(frames, interval)[source]¶

Bases: NamedTuple

A named spinner animation: its frames and the interval they look best at.

Pick one from the SPINNERS catalog, or build your own, and pass it to Spinner through its spinner argument.

Create new instance of SpinnerPreset(frames, interval)

frames: tuple[str, ...]¶

The animation frames, cycled in order.

interval: float¶

Seconds between two frames, tuned per spinner upstream.

click_extra.spinner_presets.SPINNERS: Final = {'aesthetic': (('▰▱▱▱▱▱▱', '▰▰▱▱▱▱▱', '▰▰▰▱▱▱▱', '▰▰▰▰▱▱▱', '▰▰▰▰▰▱▱', 'ā–°ā–°ā–°ā–°ā–°ā–°ā–±', 'ā–°ā–°ā–°ā–°ā–°ā–°ā–°', '▰▱▱▱▱▱▱'), 0.08), 'arc': (('ā—œ', 'ā— ', 'ā—', 'ā—ž', 'ā—”', 'ā—Ÿ'), 0.1), 'arrow': (('←', '↖', '↑', '↗', '→', 'ā†˜', '↓', '↙'), 0.1), 'arrow2': (('ā¬†ļø', 'ā†—ļø', 'āž”ļø', 'ā†˜ļø', 'ā¬‡ļø', 'ā†™ļø', 'ā¬…ļø', 'ā†–ļø'), 0.08), 'arrow3': (('▹▹▹▹▹', '▸▹▹▹▹', '▹▸▹▹▹', '▹▹▸▹▹', '▹▹▹▸▹', '▹▹▹▹▸'), 0.12), 'balloon': ((' ', '.', 'o', 'O', '@', '*', ' '), 0.14), 'balloon2': (('.', 'o', 'O', '°', 'O', 'o', '.'), 0.12), 'beta-wave': (('ρββββββ', 'βρβββββ', 'ββρββββ', 'βββρβββ', 'ββββρββ', 'βββββρβ', 'ββββββρ'), 0.08), 'binary': (('010010', '001100', '100101', '111010', '111101', '010111', '101011', '111000', '110011', '110101'), 0.08), 'blue-pulse': (('šŸ”¹', 'šŸ”·', 'šŸ”µ', 'šŸ”µ', 'šŸ”·'), 0.1), 'bounce': (('⠁', 'ā ‚', 'ā „', 'ā ‚'), 0.12), 'bouncing-ball': (('( ā—    )', '(  ā—   )', '(   ā—  )', '(    ā— )', '(     ā—)', '(    ā— )', '(   ā—  )', '(  ā—   )', '( ā—    )', '(ā—     )'), 0.08), 'bouncing-bar': (('[    ]', '[=   ]', '[==  ]', '[=== ]', '[====]', '[ ===]', '[  ==]', '[   =]', '[    ]', '[   =]', '[  ==]', '[ ===]', '[====]', '[=== ]', '[==  ]', '[=   ]'), 0.08), 'box-bounce': (('ā––', 'ā–˜', 'ā–', 'ā–—'), 0.12), 'box-bounce2': (('ā–Œ', 'ā–€', '▐', 'ā–„'), 0.1), 'christmas': (('🌲', 'šŸŽ„'), 0.4), 'circle': (('ā—”', 'āŠ™', 'ā— '), 0.12), 'circle-halves': (('◐', 'ā—“', 'ā—‘', 'ā—’'), 0.05), 'circle-quarters': (('ā—“', 'ā—·', 'ā—¶', 'ā—µ'), 0.12), 'clock': (('šŸ•›', 'šŸ•', 'šŸ•‘', 'šŸ•’', 'šŸ•“', 'šŸ•”', 'šŸ••', 'šŸ•–', 'šŸ•—', 'šŸ•˜', 'šŸ•™', 'šŸ•š'), 0.1), 'dots': (('ā ‹', 'ā ™', 'ā ¹', 'ā ø', 'ā ¼', 'ā “', 'ā ¦', 'ā §', 'ā ‡', 'ā '), 0.08), 'dots-8bit': (('ā €', '⠁', 'ā ‚', '⠃', 'ā „', 'ā …', 'ā †', 'ā ‡', '─', '━', '│', '┃', '┄', 'ā”…', '┆', '┇', '⠈', 'ā ‰', '⠊', 'ā ‹', '⠌', 'ā ', 'ā Ž', 'ā ', '┈', '┉', '┊', '┋', '┌', 'ā”', 'ā”Ž', 'ā”', '⠐', 'ā ‘', 'ā ’', 'ā “', 'ā ”', 'ā •', 'ā –', 'ā —', '┐', '┑', 'ā”’', '┓', 'ā””', '┕', 'ā”–', 'ā”—', '⠘', 'ā ™', '⠚', 'ā ›', '⠜', 'ā ', 'ā ž', '⠟', '┘', 'ā”™', '┚', 'ā”›', '├', 'ā”', 'ā”ž', '┟', 'ā  ', 'ā ”', 'ā ¢', 'ā £', 'ā ¤', 'ā „', 'ā ¦', 'ā §', 'ā” ', 'ā””', '┢', '┣', '┤', '┄', '┦', 'ā”§', 'ā Ø', 'ā ©', 'ā Ŗ', 'ā «', 'ā ¬', 'ā ­', 'ā ®', 'ā Æ', '┨', '┩', '┪', '┫', '┬', 'ā”­', 'ā”®', '┯', 'ā °', 'ā ±', 'ā ²', 'ā ³', 'ā “', 'ā µ', 'ā ¶', 'ā ·', 'ā”°', 'ā”±', '┲', '┳', '┓', '┵', 'ā”¶', 'ā”·', 'ā ø', 'ā ¹', 'ā ŗ', 'ā »', 'ā ¼', 'ā ½', 'ā ¾', 'ā æ', '┸', '┹', '┺', 'ā”»', '┼', '┽', '┾', '┿', '⢀', '⢁', '⢂', '⢃', '⢄', '⢅', '⢆', '⢇', '⣀', '⣁', '⣂', '⣃', '⣄', '⣅', '⣆', '⣇', '⢈', '⢉', '⢊', '⢋', '⢌', 'ā¢', 'ā¢Ž', 'ā¢', '⣈', '⣉', '⣊', '⣋', '⣌', 'ā£', 'ā£Ž', 'ā£', '⢐', '⢑', '⢒', '⢓', '⢔', '⢕', '⢖', '⢗', '⣐', '⣑', '⣒', '⣓', '⣔', '⣕', '⣖', '⣗', '⢘', '⢙', '⢚', '⢛', '⢜', 'ā¢', 'ā¢ž', '⢟', '⣘', '⣙', '⣚', '⣛', '⣜', 'ā£', 'ā£ž', '⣟', '⢠', '⢔', '⢢', '⢣', '⢤', '⢄', '⢦', '⢧', '⣠', '⣔', '⣢', '⣣', '⣤', '⣄', '⣦', '⣧', '⢨', '⢩', '⢪', '⢫', '⢬', '⢭', '⢮', '⢯', '⣨', '⣩', '⣪', '⣫', '⣬', '⣭', '⣮', '⣯', '⢰', '⢱', '⢲', '⢳', '⢓', '⢵', '⢶', '⢷', '⣰', '⣱', '⣲', '⣳', '⣓', '⣵', '⣶', '⣷', '⢸', '⢹', '⢺', '⢻', '⢼', '⢽', '⢾', '⢿', '⣸', '⣹', '⣺', '⣻', '⣼', '⣽', '⣾', '⣿'), 0.08), 'dots-circle': (('ā¢Ž ', 'ā Žā ', 'ā Šā ‘', '⠈⠱', ' ā”±', '⢀┰', '⢄┠', '⢆─'), 0.08), 'dots10': (('⢄', '⢂', '⢁', '━', '┈', '┐', 'ā” '), 0.08), 'dots11': (('⠁', 'ā ‚', 'ā „', '─', '⢀', 'ā  ', '⠐', '⠈'), 0.1), 'dots12': (('⢀⠀', '─⠀', 'ā „ā €', '⢂⠀', '│⠀', 'ā …ā €', 'ā¢ƒā €', 'ā”ƒā €', 'ā ā €', '⢋⠀', '┋⠀', 'ā ā ', '⢋⠁', '┋⠁', 'ā ā ‰', 'ā ‹ā ‰', 'ā ‹ā ‰', '⠉⠙', '⠉⠙', '⠉⠩', 'ā ˆā¢™', 'ā ˆā”™', '⢈⠩', '─⢙', 'ā „ā”™', '⢂⠩', 'ā”‚ā¢˜', 'ā …ā”˜', '⢃⠨', '┃⢐', 'ā ā”', '⢋⠠', '┋⢀', 'ā ā”', '⢋⠁', '┋⠁', 'ā ā ‰', 'ā ‹ā ‰', 'ā ‹ā ‰', '⠉⠙', '⠉⠙', '⠉⠩', 'ā ˆā¢™', 'ā ˆā”™', '⠈⠩', '⠀⢙', '⠀┙', '⠀⠩', 'ā €ā¢˜', 'ā €ā”˜', '⠀⠨', '⠀⢐', '⠀┐', '⠀⠠', '⠀⢀', '⠀─'), 0.08), 'dots13': (('⣼', '⣹', '⢻', 'ā æ', '┟', 'ā£', '⣧', '⣶'), 0.08), 'dots14': (('⠉⠉', 'ā ˆā ™', '⠀⠹', '⠀⢸', '⠀⣰', '⢀⣠', '⣀⣀', '⣄─', '⣆⠀', '┇⠀', 'ā ā €', '⠋⠁'), 0.08), 'dots2': (('⣾', '⣽', '⣻', '⢿', '┿', '⣟', '⣯', '⣷'), 0.08), 'dots3': (('ā ‹', 'ā ™', '⠚', 'ā ž', 'ā –', 'ā ¦', 'ā “', 'ā ²', 'ā ³', 'ā “'), 0.08), 'dots4': (('ā „', 'ā †', 'ā ‡', 'ā ‹', 'ā ™', 'ā ø', 'ā °', 'ā  ', 'ā °', 'ā ø', 'ā ™', 'ā ‹', 'ā ‡', 'ā †'), 0.08), 'dots5': (('ā ‹', 'ā ™', '⠚', 'ā ’', 'ā ‚', 'ā ‚', 'ā ’', 'ā ²', 'ā “', 'ā ¦', 'ā –', 'ā ’', '⠐', '⠐', 'ā ’', 'ā “', 'ā ‹'), 0.08), 'dots6': (('⠁', 'ā ‰', 'ā ™', '⠚', 'ā ’', 'ā ‚', 'ā ‚', 'ā ’', 'ā ²', 'ā “', 'ā ¤', 'ā „', 'ā „', 'ā ¤', 'ā “', 'ā ²', 'ā ’', 'ā ‚', 'ā ‚', 'ā ’', '⠚', 'ā ™', 'ā ‰', '⠁'), 0.08), 'dots7': (('⠈', 'ā ‰', 'ā ‹', 'ā “', 'ā ’', '⠐', '⠐', 'ā ’', 'ā –', 'ā ¦', 'ā ¤', 'ā  ', 'ā  ', 'ā ¤', 'ā ¦', 'ā –', 'ā ’', '⠐', '⠐', 'ā ’', 'ā “', 'ā ‹', 'ā ‰', '⠈'), 0.08), 'dots8': (('⠁', '⠁', 'ā ‰', 'ā ™', '⠚', 'ā ’', 'ā ‚', 'ā ‚', 'ā ’', 'ā ²', 'ā “', 'ā ¤', 'ā „', 'ā „', 'ā ¤', 'ā  ', 'ā  ', 'ā ¤', 'ā ¦', 'ā –', 'ā ’', '⠐', '⠐', 'ā ’', 'ā “', 'ā ‹', 'ā ‰', '⠈', '⠈'), 0.08), 'dots9': (('⢹', '⢺', '⢼', '⣸', '⣇', 'ā”§', 'ā”—', 'ā”'), 0.08), 'dqpb': (('d', 'q', 'p', 'b'), 0.1), 'dwarf-fortress': ((' ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', 'ā˜ŗā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', 'ā˜ŗā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', 'ā˜ŗā–“ā–ˆā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', 'ā˜ŗā–“ā–ˆā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', 'ā˜ŗā–’ā–ˆā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', 'ā˜ŗā–’ā–ˆā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', 'ā˜ŗā–‘ā–ˆā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', 'ā˜ŗā–‘ā–ˆā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', '☺ ā–ˆā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', ' ā˜ŗā–ˆā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', ' ā˜ŗā–ˆā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', ' ā˜ŗā–“ā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', ' ā˜ŗā–“ā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', ' ā˜ŗā–’ā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', ' ā˜ŗā–’ā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', ' ā˜ŗā–‘ā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', ' ā˜ŗā–‘ā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', ' ☺ ā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', '  ā˜ŗā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', '  ā˜ŗā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', '  ā˜ŗā–“ā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', '  ā˜ŗā–“ā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', '  ā˜ŗā–’ā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', '  ā˜ŗā–’ā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', '  ā˜ŗā–‘ā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', '  ā˜ŗā–‘ā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', '  ☺ ā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', '   ā˜ŗā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', '   ā˜ŗā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', '   ā˜ŗā–“ā–ˆā–ˆĀ£Ā£Ā£  ', '   ā˜ŗā–“ā–ˆā–ˆĀ£Ā£Ā£  ', '   ā˜ŗā–’ā–ˆā–ˆĀ£Ā£Ā£  ', '   ā˜ŗā–’ā–ˆā–ˆĀ£Ā£Ā£  ', '   ā˜ŗā–‘ā–ˆā–ˆĀ£Ā£Ā£  ', '   ā˜ŗā–‘ā–ˆā–ˆĀ£Ā£Ā£  ', '   ☺ ā–ˆā–ˆĀ£Ā£Ā£  ', '    ā˜ŗā–ˆā–ˆĀ£Ā£Ā£  ', '    ā˜ŗā–ˆā–ˆĀ£Ā£Ā£  ', '    ā˜ŗā–“ā–ˆĀ£Ā£Ā£  ', '    ā˜ŗā–“ā–ˆĀ£Ā£Ā£  ', '    ā˜ŗā–’ā–ˆĀ£Ā£Ā£  ', '    ā˜ŗā–’ā–ˆĀ£Ā£Ā£  ', '    ā˜ŗā–‘ā–ˆĀ£Ā£Ā£  ', '    ā˜ŗā–‘ā–ˆĀ£Ā£Ā£  ', '    ☺ ā–ˆĀ£Ā£Ā£  ', '     ā˜ŗā–ˆĀ£Ā£Ā£  ', '     ā˜ŗā–ˆĀ£Ā£Ā£  ', '     ā˜ŗā–“Ā£Ā£Ā£  ', '     ā˜ŗā–“Ā£Ā£Ā£  ', '     ā˜ŗā–’Ā£Ā£Ā£  ', '     ā˜ŗā–’Ā£Ā£Ā£  ', '     ā˜ŗā–‘Ā£Ā£Ā£  ', '     ā˜ŗā–‘Ā£Ā£Ā£  ', '     ☺ £££  ', '      ☺£££  ', '      ☺£££  ', '      ā˜ŗā–“Ā£Ā£  ', '      ā˜ŗā–“Ā£Ā£  ', '      ā˜ŗā–’Ā£Ā£  ', '      ā˜ŗā–’Ā£Ā£  ', '      ā˜ŗā–‘Ā£Ā£  ', '      ā˜ŗā–‘Ā£Ā£  ', '      ☺ ££  ', '       ☺££  ', '       ☺££  ', '       ā˜ŗā–“Ā£  ', '       ā˜ŗā–“Ā£  ', '       ā˜ŗā–’Ā£  ', '       ā˜ŗā–’Ā£  ', '       ā˜ŗā–‘Ā£  ', '       ā˜ŗā–‘Ā£  ', '       ☺ Ā£  ', '        ☺£  ', '        ☺£  ', '        ā˜ŗā–“  ', '        ā˜ŗā–“  ', '        ā˜ŗā–’  ', '        ā˜ŗā–’  ', '        ā˜ŗā–‘  ', '        ā˜ŗā–‘  ', '        ☺   ', '        ☺  &', '        ☺ ☼&', '       ☺ ☼ &', '       ☺☼  &', '      ☺☼  & ', '      ‼   & ', '     ☺   &  ', '    ‼    &  ', '   ☺    &   ', '  ‼     &   ', ' ☺     &    ', '‼      &    ', '      &     ', '      &     ', '     &   ā–‘  ', '     &   ā–’  ', '    &    ā–“  ', '    &    Ā£  ', '   &    ā–‘Ā£  ', '   &    ā–’Ā£  ', '  &     ā–“Ā£  ', '  &     ££  ', ' &     ░££  ', ' &     ▒££  ', '&      ▓££  ', '&      £££  ', '      ░£££  ', '      ▒£££  ', '      ▓£££  ', '      ā–ˆĀ£Ā£Ā£  ', '     ā–‘ā–ˆĀ£Ā£Ā£  ', '     ā–’ā–ˆĀ£Ā£Ā£  ', '     ā–“ā–ˆĀ£Ā£Ā£  ', '     ā–ˆā–ˆĀ£Ā£Ā£  ', '    ā–‘ā–ˆā–ˆĀ£Ā£Ā£  ', '    ā–’ā–ˆā–ˆĀ£Ā£Ā£  ', '    ā–“ā–ˆā–ˆĀ£Ā£Ā£  ', '    ā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', '   ā–‘ā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', '   ā–’ā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', '   ā–“ā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', '   ā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', '  ā–‘ā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', '  ā–’ā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', '  ā–“ā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', '  ā–ˆā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', ' ā–‘ā–ˆā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', ' ā–’ā–ˆā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', ' ā–“ā–ˆā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', ' ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  ', ' ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆĀ£Ā£Ā£  '), 0.08), 'earth': (('šŸŒ', 'šŸŒŽ', 'šŸŒ'), 0.18), 'finger-dance': (('🤘', '🤟', 'šŸ––', 'āœ‹', '🤚', 'šŸ‘†'), 0.16), 'fish': (('~~~~~~~~~~~~~~~~~~~~', '> ~~~~~~~~~~~~~~~~~~', 'Āŗ> ~~~~~~~~~~~~~~~~~', '(Āŗ> ~~~~~~~~~~~~~~~~', '((Āŗ> ~~~~~~~~~~~~~~~', '<((Āŗ> ~~~~~~~~~~~~~~', '><((Āŗ> ~~~~~~~~~~~~~', ' ><((Āŗ> ~~~~~~~~~~~~', '~ ><((Āŗ> ~~~~~~~~~~~', '~~ <>((Āŗ> ~~~~~~~~~~', '~~~ ><((Āŗ> ~~~~~~~~~', '~~~~ <>((Āŗ> ~~~~~~~~', '~~~~~ ><((Āŗ> ~~~~~~~', '~~~~~~ <>((Āŗ> ~~~~~~', '~~~~~~~ ><((Āŗ> ~~~~~', '~~~~~~~~ <>((Āŗ> ~~~~', '~~~~~~~~~ ><((Āŗ> ~~~', '~~~~~~~~~~ <>((Āŗ> ~~', '~~~~~~~~~~~ ><((Āŗ> ~', '~~~~~~~~~~~~ <>((Āŗ> ', '~~~~~~~~~~~~~ ><((Āŗ>', '~~~~~~~~~~~~~~ <>((Āŗ', '~~~~~~~~~~~~~~~ ><((', '~~~~~~~~~~~~~~~~ <>(', '~~~~~~~~~~~~~~~~~ ><', '~~~~~~~~~~~~~~~~~~ <', '~~~~~~~~~~~~~~~~~~~~'), 0.08), 'fist-bump': (('🤜\u3000\u3000\u3000\u3000šŸ¤›', '🤜\u3000\u3000\u3000\u3000šŸ¤›', '🤜\u3000\u3000\u3000\u3000šŸ¤›', '\u3000🤜\u3000\u3000šŸ¤›\u3000', '\u3000\u3000šŸ¤œšŸ¤›\u3000\u3000', '\u3000šŸ¤œāœØšŸ¤›\u3000\u3000', '🤜\u3000✨\u3000šŸ¤›\u3000'), 0.08), 'flip': (('_', '_', '_', '-', '`', '`', "'", 'Ā“', '-', '_', '_', '_'), 0.07), 'grenade': (('،  ', '′  ', ' Ā“ ', ' ‾ ', '  ⸌', '  ⸊', '  |', '  āŽ', '  ⁕', ' ą·“ ', '  ⁓', '   ', '   ', '   '), 0.08), 'grow-horizontal': (('ā–', 'ā–Ž', 'ā–', 'ā–Œ', 'ā–‹', 'ā–Š', 'ā–‰', 'ā–Š', 'ā–‹', 'ā–Œ', 'ā–', 'ā–Ž'), 0.12), 'grow-vertical': (('▁', 'ā–ƒ', 'ā–„', 'ā–…', 'ā–†', 'ā–‡', 'ā–†', 'ā–…', 'ā–„', 'ā–ƒ'), 0.12), 'hamburger': (('☱', '☲', '☓'), 0.1), 'hearts': (('šŸ’›', 'šŸ’™', 'šŸ’œ', 'šŸ’š', 'šŸ’—'), 0.1), 'layer': (('-', '=', '≔'), 0.15), 'line': (('-', '\\', '|', '/'), 0.13), 'line2': (('ā ‚', '-', '–', '—', '–', '-'), 0.1), 'material': (('ā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–', 'ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–', 'ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–', 'ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–', 'ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–', 'ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–', 'ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–', 'ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–', 'ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–', 'ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–', 'ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–', 'ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–', 'ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆ', 'ā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆ', 'ā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆ', 'ā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆ', 'ā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆ', 'ā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆ', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆ', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆ', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆ', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–', 'ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–ā–', 'ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–', 'ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–ā–', 'ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–ā–', 'ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–', 'ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–', 'ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–ā–', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ā–', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆ', 'ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ā–ˆ', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁'), 0.017), 'mindblown': (('😐', '😐', '😮', '😮', '😦', '😦', '😧', '😧', '🤯', 'šŸ’„', '✨', '\u3000', '\u3000', '\u3000'), 0.16), 'monkey': (('šŸ™ˆ', 'šŸ™ˆ', 'šŸ™‰', 'šŸ™Š'), 0.3), 'moon': (('šŸŒ‘', 'šŸŒ’', 'šŸŒ“', 'šŸŒ”', 'šŸŒ•', 'šŸŒ–', 'šŸŒ—', '🌘'), 0.08), 'noise': (('ā–“', 'ā–’', 'ā–‘'), 0.1), 'orange-blue-pulse': (('šŸ”ø', 'šŸ”¶', '🟠', '🟠', 'šŸ”¶', 'šŸ”¹', 'šŸ”·', 'šŸ”µ', 'šŸ”µ', 'šŸ”·'), 0.1), 'orange-pulse': (('šŸ”ø', 'šŸ”¶', '🟠', '🟠', 'šŸ”¶'), 0.1), 'pipe': (('┤', 'ā”˜', '┓', 'ā””', 'ā”œ', 'ā”Œ', '┬', '┐'), 0.1), 'point': (('āˆ™āˆ™āˆ™', 'ā—āˆ™āˆ™', 'āˆ™ā—āˆ™', 'āˆ™āˆ™ā—', 'āˆ™āˆ™āˆ™'), 0.125), 'pong': (('▐⠂       ā–Œ', 'ā–ā ˆ       ā–Œ', '▐ ā ‚      ā–Œ', '▐ ā        ā–Œ', '▐  ─     ā–Œ', '▐  ā       ā–Œ', '▐   ā ‚    ā–Œ', '▐   ⠈    ā–Œ', '▐    ā ‚   ā–Œ', '▐    ā     ā–Œ', '▐     ─  ā–Œ', '▐     ā    ā–Œ', '▐      ā ‚ ā–Œ', '▐      ⠈ ā–Œ', '▐       ā ‚ā–Œ', '▐       ā  ā–Œ', '▐       ā”€ā–Œ', '▐      ā   ā–Œ', '▐      ā ‚ ā–Œ', '▐     ⠈  ā–Œ', '▐     ā ‚  ā–Œ', '▐    ā     ā–Œ', '▐    ─   ā–Œ', '▐   ā      ā–Œ', '▐   ā ‚    ā–Œ', '▐  ⠈     ā–Œ', '▐  ā ‚     ā–Œ', '▐ ā        ā–Œ', '▐ ─      ā–Œ', '▐⠠       ā–Œ'), 0.08), 'rolling-line': (('/  ', ' - ', ' \\ ', '  |', '  |', ' \\ ', ' - ', '/  '), 0.08), 'runner': (('🚶', 'šŸƒ'), 0.14), 'sand': (('⠁', 'ā ‚', 'ā „', '─', '┈', '┐', 'ā” ', '⣀', '⣁', '⣂', '⣄', '⣌', '⣔', '⣤', '⣄', '⣦', '⣮', '⣶', '⣷', '⣿', '┿', 'ā æ', '⢟', '⠟', 'ā”›', 'ā ›', 'ā «', '⢋', 'ā ‹', 'ā ', '┉', 'ā ‰', 'ā ‘', 'ā ”', '⢁'), 0.08), 'shark': (('▐|\\____________ā–Œ', '▐_|\\___________ā–Œ', '▐__|\\__________ā–Œ', '▐___|\\_________ā–Œ', '▐____|\\________ā–Œ', '▐_____|\\_______ā–Œ', '▐______|\\______ā–Œ', '▐_______|\\_____ā–Œ', '▐________|\\____ā–Œ', '▐_________|\\___ā–Œ', '▐__________|\\__ā–Œ', '▐___________|\\_ā–Œ', '▐____________|\\ā–Œ', '▐____________/|ā–Œ', '▐___________/|_ā–Œ', '▐__________/|__ā–Œ', '▐_________/|___ā–Œ', '▐________/|____ā–Œ', '▐_______/|_____ā–Œ', '▐______/|______ā–Œ', '▐_____/|_______ā–Œ', '▐____/|________ā–Œ', '▐___/|_________ā–Œ', '▐__/|__________ā–Œ', '▐_/|___________ā–Œ', '▐/|____________ā–Œ'), 0.12), 'simple-dots': (('.  ', '.. ', '...', '   '), 0.4), 'simple-dots-scrolling': (('.  ', '.. ', '...', ' ..', '  .', '   '), 0.2), 'smiley': (('šŸ˜„', 'šŸ˜'), 0.2), 'soccer-header': ((' šŸ§‘āš½ļø       šŸ§‘', 'šŸ§‘  āš½ļø      šŸ§‘', 'šŸ§‘   āš½ļø     šŸ§‘', 'šŸ§‘    āš½ļø    šŸ§‘', 'šŸ§‘     āš½ļø   šŸ§‘', 'šŸ§‘      āš½ļø  šŸ§‘', 'šŸ§‘       āš½ļøšŸ§‘ ', 'šŸ§‘      āš½ļø  šŸ§‘', 'šŸ§‘     āš½ļø   šŸ§‘', 'šŸ§‘    āš½ļø    šŸ§‘', 'šŸ§‘   āš½ļø     šŸ§‘', 'šŸ§‘  āš½ļø      šŸ§‘'), 0.08), 'speaker': (('šŸ”ˆ', 'šŸ”‰', 'šŸ”Š', 'šŸ”‰'), 0.16), 'square-corners': (('ā—°', 'ā—³', 'ā—²', 'ā—±'), 0.18), 'squish': (('ā•«', '╪'), 0.1), 'star': (('✶', '✸', '✹', '✺', '✹', '✷'), 0.07), 'star2': (('+', 'x', '*'), 0.08), 'toggle': (('⊶', '⊷'), 0.25), 'toggle10': (('抂', '技', '㊁'), 0.1), 'toggle11': (('⧇', '⧆'), 0.05), 'toggle12': (('ā˜—', 'ā˜–'), 0.12), 'toggle13': (('=', '*', '-'), 0.08), 'toggle2': (('ā–«', 'ā–Ŗ'), 0.08), 'toggle3': (('ā–”', 'ā– '), 0.12), 'toggle4': (('ā– ', 'ā–”', 'ā–Ŗ', 'ā–«'), 0.1), 'toggle5': (('ā–®', 'ā–Æ'), 0.1), 'toggle6': (('į€', '၀'), 0.3), 'toggle7': (('⦾', '⦿'), 0.08), 'toggle8': (('ā—', 'ā—Œ'), 0.1), 'toggle9': (('ā—‰', 'ā—Ž'), 0.1), 'triangle': (('ā—¢', 'ā—£', 'ā—¤', 'ā—„'), 0.05), 'weather': (('ā˜€ļø', 'ā˜€ļø', 'ā˜€ļø', '🌤 ', 'ā›…ļø', '🌄 ', 'ā˜ļø', '🌧 ', '🌨 ', '🌧 ', '🌨 ', '🌧 ', '🌨 ', 'ā›ˆ ', '🌨 ', '🌧 ', '🌨 ', 'ā˜ļø', '🌄 ', 'ā›…ļø', '🌤 ', 'ā˜€ļø', 'ā˜€ļø'), 0.1)}¶

Named spinner animations ported from cli-spinners, keyed by name.

Each value is a SpinnerPreset bundling frames and a tuned interval. Select one with Spinner’s spinner argument:

from click_extra import SPINNERS, Spinner

with Spinner("Brewing tea", spinner=SPINNERS["moon"]):
    ...

Unlike the upstream \b-based renderers, Spinner redraws the whole line, so the multi-character animations (bouncing-bar, pong, shark, …) render correctly here.

click_extra.styling module¶

Drop-in replacement for cloup.Style with extra features.

The module name mirrors cloup.styling, the upstream module that hosts the original Style class. Click Extra’s Style is a subclass that keeps cloup’s runtime contract (calling the instance to apply the style, equality, hashing) intact and adds:

  • An equality and a hash shared with cloup.Style, so a Style equals the cloup.Style carrying the same fields.

  • A compact, single-line __repr__ that hides None and falsy attributes and renders RGB tuples as #rrggbb hex.

  • Hex-string color shorthand: Style(fg="#f1fa8c") works alongside Style(fg=(241, 250, 140)).

  • A __str__ that returns the styled word "sample" so REPL prints and debuggers visualize what the style does, not just its fields.

  • A composition operator a | b that merges two styles, with the right operand winning on conflicts.

  • A Style.cascade() method that fills the style’s None fields from a base style without overriding any value already set.

  • Style.to_dict() / Style.from_dict() for round-tripping styles through TOML/JSON/YAML.

  • Style.to_css() for emitting CSS-equivalent declarations: useful for HTML renderings of help screens.

  • Style.from_ansi() for parsing an ANSI SGR escape sequence back into a Style instance.

  • Style.contrast_ratio() returning the WCAG contrast ratio between two foreground colors. Useful for theme designers checking accessibility.

  • split_ansi() and render_ansi() for tokenizing a string mixing text and ANSI escapes into styled runs, then re-rendering those runs through a markup emitter. Wrapping them to a width lives in wrap_ansi(), with the rest of the terminal-grid measures.

  • The ansi_to_html(), ansi_to_jira(), ansi_to_latex() and ansi_to_textile() converters, translating ANSI styling to markup languages with native styling support.

The escape grammar, the SGR decoder and the color conversions all of this reads through live in click_extra.ansi, with strip_ansi() and open_ansi().

click_extra.styling.fields_to_dict(instance, *, encode=<function <lambda>>, keep=<function <lambda>>)[source]¶

Serialize a dataclass instance to a dict of its non-default fields.

Skips every field still holding its declared default, then applies keep to decide which of the remaining fields are written, and passes their values through encode.

Parameters:
  • instance (Any) – the dataclass to serialize.

  • encode (Callable[[Any, Any], Any]) – callable (field, value) -> encoded_value applied to every kept value. Use to convert RGB tuples to #rrggbb strings, nested dataclasses to dicts, etc. Defaults to the identity.

  • keep (Callable[[Any, Any], bool]) – callable (field, value) -> bool deciding whether a non-default field is emitted. Defaults to keeping all of them.

Return type:

dict[str, Any]

click_extra.styling.dict_to_fields(cls, data, *, decode=<function <lambda>>)[source]¶

Validate data’s keys against cls’s dataclass fields and decode them.

Returns a kwargs dict ready to splat into cls(**kwargs).

Parameters:
  • cls (type) – the dataclass type whose fields define the legal keys.

  • data (dict[str, Any]) – mapping from field name to a serialized value.

  • decode (Callable[[Any, Any], Any]) – callable (field, raw) -> decoded_value invoked for every recognized key. Default returns the raw value unchanged.

Raises:

TypeError – listing every key that names no field of cls, so callers can build a constructor call without validating first.

Return type:

dict[str, Any]

click_extra.styling.supports_truecolor()[source]¶

Whether the terminal is assumed to render 24-bit (truecolor) ANSI.

Drives Style.__call__’s choice between emitting a 24-bit 38;2;r;g;b sequence and quantizing it to the nearest 38;5;n 256-color index, so a branded theme’s RGB colors degrade gracefully on a terminal that cannot display them.

The policy is optimistic: assume truecolor unless the environment positively says otherwise. Precedence, highest first:

  1. COLORTERM of truecolor / 24bit (see _TRUECOLOR_COLORTERMS) keeps 24-bit.

  2. Any other non-empty COLORTERM quantizes: an explicit lower advertisement.

  3. A TERM ending in -16color quantizes: an unambiguous sub-256 terminal. *-256color is deliberately not treated as a downgrade, since truecolor terminals routinely report it while advertising their 24-bit support through COLORTERM instead. Honoring it would strip truecolor from the very terminals this optimistic default protects.

  4. Otherwise keeps 24-bit.

A dumb / unknown TERM never reaches this decision for CLI output: it has already disabled color upstream through resolve_color_env().

Return type:

bool

class click_extra.styling.Style(fg=None, bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None)[source]¶

Bases: Style

cloup.Style with extra ergonomics.

See the module docstring for the full list of additions. The runtime contract (calling the instance to apply the style, equality, hashing) is otherwise identical to cloup.Style.

fg: str | tuple[int, int, int] | int | None = None¶

Foreground color: named ANSI string, #rrggbb hex, RGB tuple, or palette index.

bg: str | tuple[int, int, int] | int | None = None¶

Background color: named ANSI string, #rrggbb hex, RGB tuple, or palette index.

cascade(base)[source]¶

Return a copy with None fields filled in from base.

The instance’s own non-None values always win: cascade only fills gaps. Useful for theme inheritance: derived.cascade(parent) keeps derived’s overrides and inherits the rest from parent.

Return type:

Style

to_dict()[source]¶

Serialize to a plain dict with only the set fields.

RGB tuples are emitted as #rrggbb strings so the result round-trips through TOML/JSON/YAML untouched. Pair with from_dict() to rebuild a Style.

Return type:

dict[str, Any]

classmethod from_dict(data)[source]¶

Build a Style from the plain dict produced by to_dict().

Validates that every key in data names a known Style field and raises TypeError otherwise. Pair with to_dict() to round-trip through TOML/JSON/YAML.

Return type:

Style

to_css()[source]¶

Render the style as a semicolon-separated CSS declaration list.

Style(fg="#f1fa8c", bold=True).to_css() returns "color: #f1fa8c; font-weight: bold". Suitable for inline style="..." attributes on HTML spans.

Return type:

str

classmethod from_ansi(escape)[source]¶

Parse one or more consecutive ANSI SGR escapes into a Style.

Supports the standard 8/16-color codes (30–37, 40–47, 90–97, 100–107), the 38;5;n / 48;5;n 256-color extension, and the 38;2;r;g;b / 48;2;r;g;b 24-bit extension. Reset codes (the full 0 reset, its parameter-less \x1b[m form included, and selective resets like 22, 39 or 49) are ignored, so parsing the full output of a style call (trailing reset included) recovers that style. Multiple back-to-back escapes (as click emits when combining colors with attributes: \x1b[31m\x1b[1m) are merged into a single Style.

To tokenize a string mixing text and escapes, with resets honored, see split_ansi().

Return type:

Style

contrast_ratio(other)[source]¶

Return the WCAG 2.x contrast ratio between this fg and other’s fg.

Result is in [1, 21]: 1 = identical colors (no contrast), 21 = maximum contrast (black on white). WCAG AA requires 4.5+ for normal text, 3.0+ for large text; AAA wants 7.0+ and 4.5+ respectively.

Return type:

float

click_extra.styling.split_ansi(text)[source]¶

Split text into (style, text) runs at ANSI SGR escape boundaries.

A stateful SGR stream parser: each escape updates the current style state (with full and selective resets honored, unlike Style.from_ansi()), and every maximal run of text sharing the same state is yielded with its Style. Unstyled text is yielded with an empty Style. Consecutive runs with equal styles are merged and empty runs are dropped, so wrapping each yielded run produces minimal markup.

Every other escape carries no style information and is removed from the yielded text by strip_ansi(), so a terminal hyperlink keeps its display text and loses its URI.

Return type:

Iterator[tuple[Style, str]]

click_extra.styling.render_ansi(text, emitter)[source]¶

Rebuild text, replacing each ANSI-styled run by emitter’s markup.

Unstyled runs pass through verbatim, so any markup surrounding the styled runs (table borders, tags produced by another renderer) is preserved byte for byte. Styled runs are handed to emitter one line at a time: runs are split on newlines so no markup wrapper ever crosses a line boundary, which keeps line-oriented markup (LaTeX rows, wiki tables) well-formed even when a style spans multiple lines.

Return type:

str

click_extra.styling.ansi_to_html(text)[source]¶

Translate ANSI styling in text to inline-styled HTML <span> tags.

\x1b[34mSummer\x1b[0m becomes <span style="color: blue">Summer</span>. The spans are self-contained (no stylesheet needed) and also valid in markups accepting inline HTML, like MediaWiki.

Return type:

str

click_extra.styling.ansi_to_jira(text)[source]¶

Translate ANSI styling in text to Jira wiki markup.

\x1b[34;1mSummer\x1b[0m becomes {color:blue}*Summer*{color}.

Return type:

str

click_extra.styling.ansi_to_latex(text)[source]¶

Translate ANSI styling in text to LaTeX macros.

\x1b[34;1mSummer\x1b[0m becomes \textcolor{blue}{\textbf{Summer}}. The colored macros require \usepackage{xcolor} in the document preamble.

Return type:

str

click_extra.styling.ansi_to_textile(text)[source]¶

Translate ANSI styling in text to Textile spans.

\x1b[34;1mSummer\x1b[0m becomes %{color: blue; font-weight: bold}Summer%.

Return type:

str

click_extra.table module¶

Render tables for a terminal, a markup document or a serialization format.

Todo

Drop the github patch of _setup_tabulate once a python-tabulate release ships astanin/python-tabulate#410: github then marks column alignment in its separator row, as pipe does.

Todo

Delete _pad_gfm_separator once a python-tabulate release ships astanin/python-tabulate#426: the separator rows of pipe and github then carry the padding mdformat writes.

click_extra.table.THeader: TypeAlias¶

One entry of a table’s headers: a plain label, or a ColumnSpec.

click_extra.table.TColumnDef: TypeAlias¶

One column definition of SortByOption or column_sort_key().

A ColumnSpec, or a bare column ID.

class click_extra.table.TableFormat(*values)[source]¶

Bases: Enum

Enumeration of supported table formats.

Hard-coded to be in alphabetical order. Content of this enum is checked in unit tests.

Warning

The youtrack format is missing in action from any official JetBrains documentation. It will be removed in python-tabulate v0.11.

ALIGNED = 'aligned'¶
ASCIIDOC = 'asciidoc'¶
COLON_GRID = 'colon-grid'¶
CSV = 'csv'¶
CSV_EXCEL = 'csv-excel'¶
CSV_EXCEL_TAB = 'csv-excel-tab'¶
CSV_UNIX = 'csv-unix'¶
DOUBLE_GRID = 'double-grid'¶
DOUBLE_OUTLINE = 'double-outline'¶
FANCY_GRID = 'fancy-grid'¶
FANCY_OUTLINE = 'fancy-outline'¶
GITHUB = 'github'¶
GRID = 'grid'¶
HEAVY_GRID = 'heavy-grid'¶
HEAVY_OUTLINE = 'heavy-outline'¶
HJSON = 'hjson'¶
HTML = 'html'¶
JIRA = 'jira'¶
JSON = 'json'¶
JSON5 = 'json5'¶
JSONC = 'jsonc'¶
LATEX = 'latex'¶
LATEX_BOOKTABS = 'latex-booktabs'¶
LATEX_LONGTABLE = 'latex-longtable'¶
LATEX_RAW = 'latex-raw'¶
MEDIAWIKI = 'mediawiki'¶
MIXED_GRID = 'mixed-grid'¶
MIXED_OUTLINE = 'mixed-outline'¶
MOINMOIN = 'moinmoin'¶
ORGTBL = 'orgtbl'¶
OUTLINE = 'outline'¶
PIPE = 'pipe'¶
PLAIN = 'plain'¶
PRESTO = 'presto'¶
PRETTY = 'pretty'¶
PSQL = 'psql'¶
ROUNDED_GRID = 'rounded-grid'¶
ROUNDED_OUTLINE = 'rounded-outline'¶
RST = 'rst'¶
SIMPLE = 'simple'¶
SIMPLE_GRID = 'simple-grid'¶
SIMPLE_OUTLINE = 'simple-outline'¶
TEXTILE = 'textile'¶
TOML = 'toml'¶
TSV = 'tsv'¶
UNSAFEHTML = 'unsafehtml'¶
VERTICAL = 'vertical'¶
XML = 'xml'¶
YAML = 'yaml'¶
YOUTRACK = 'youtrack'¶
property is_markup: bool¶

Whether this format is a markup rendering.

ANSI codes never reach a markup rendering raw: they are either translated to the format’s native styling (see supports_styling) or stripped from cell values. Forcing --color on the command line preserves them as-is in the markup formats without styling support.

property supports_styling: bool¶

Whether ANSI codes are translated to this format’s native styling.

See STYLED_FORMATS for the registry.

property is_wrappable: bool¶

Whether this format renders a cell wrapped onto several lines.

See WRAPPABLE_FORMATS for the registry, and the rationale behind each excluded format.

click_extra.table.MARKUP_FORMATS = frozenset({TableFormat.ASCIIDOC, TableFormat.CSV, TableFormat.CSV_EXCEL, TableFormat.CSV_EXCEL_TAB, TableFormat.CSV_UNIX, TableFormat.GITHUB, TableFormat.HJSON, TableFormat.HTML, TableFormat.JIRA, TableFormat.JSON, TableFormat.JSON5, TableFormat.JSONC, TableFormat.LATEX, TableFormat.LATEX_BOOKTABS, TableFormat.LATEX_LONGTABLE, TableFormat.LATEX_RAW, TableFormat.MEDIAWIKI, TableFormat.MOINMOIN, TableFormat.ORGTBL, TableFormat.PIPE, TableFormat.RST, TableFormat.TEXTILE, TableFormat.TOML, TableFormat.TSV, TableFormat.UNSAFEHTML, TableFormat.XML, TableFormat.YAML, TableFormat.YOUTRACK})¶

Subset of table formats that are considered as markup rendering.

click_extra.table.STYLED_FORMATS: dict[TableFormat, Callable[[str], str]] = {TableFormat.HTML: <function ansi_to_html>, TableFormat.JIRA: <function ansi_to_jira>, TableFormat.LATEX: <function ansi_to_latex>, TableFormat.LATEX_BOOKTABS: <function ansi_to_latex>, TableFormat.LATEX_LONGTABLE: <function ansi_to_latex>, TableFormat.LATEX_RAW: <function ansi_to_latex>, TableFormat.MEDIAWIKI: <function ansi_to_html>, TableFormat.TEXTILE: <function ansi_to_textile>, TableFormat.UNSAFEHTML: <function ansi_to_html>}¶

Markup formats able to express styles natively, mapped to their ANSI translator.

print_table() runs the rendered output of these formats through their translator, converting the ANSI codes carried by cells and headers into the format’s own styling markup: inline-CSS HTML <span>s for the HTML pair and MediaWiki (which accepts embedded HTML), Textile %{...} spans, Jira {color:...} macros, and xcolor-based LaTeX macros.

Note

Translation happens on the rendered output, not on cell values, on purpose. tabulate escapes cell content for some formats (html escapes HTML entities, non-raw latex variants escape TeX specials) while ANSI sequences pass through unscathed, so pre-render translation would get its markup mangled by those escaping rules. Post-render injection also keeps column-width computation on the ANSI text, which tabulate measures correctly.

Every markup format absent from this registry strips ANSI codes from its cells before rendering. The Colors and styles section of Table gives the reason, format by format.

click_extra.table.DEFAULT_FORMAT = TableFormat.ROUNDED_OUTLINE¶

Default table format, if none is specified.

click_extra.table.RECORD_KEY = 'record'¶

Key used for each record in structured formats that require named containers (TOML [[record]], XML <record>).

click_extra.table.XML_ROOT_KEY = 'records'¶

Root element name for XML table output.

click_extra.table.CSV_FORMATS = frozenset({TableFormat.CSV, TableFormat.CSV_EXCEL, TableFormat.CSV_EXCEL_TAB, TableFormat.CSV_UNIX})¶

Formats rendered by Python’s csv module, each named after its dialect.

click_extra.table.SERIALIZATION_FORMATS = frozenset({TableFormat.HJSON, TableFormat.JSON, TableFormat.JSON5, TableFormat.JSONC, TableFormat.TOML, TableFormat.XML, TableFormat.YAML})¶

Structured serialization formats whose renderers escape raw ESC bytes, making post-render strip_ansi() ineffective.

click_extra.table.AUTO_WIDTH: Final = 'auto'¶

Sentinel asking for a column width derived from the space left on the terminal.

Annotated Final so it narrows to Literal["auto"] instead of str, which is what lets it stand in for the raw string anywhere a ColumnWidth is expected.

click_extra.table.MIN_COLUMN_WIDTH = 8¶

Floor applied to an AUTO_WIDTH column, so a crowded table still renders a usable column instead of collapsing it to nothing.

click_extra.table.WRAPPABLE_FORMATS = frozenset({TableFormat.COLON_GRID, TableFormat.DOUBLE_GRID, TableFormat.DOUBLE_OUTLINE, TableFormat.FANCY_GRID, TableFormat.FANCY_OUTLINE, TableFormat.GRID, TableFormat.HEAVY_GRID, TableFormat.HEAVY_OUTLINE, TableFormat.MIXED_GRID, TableFormat.MIXED_OUTLINE, TableFormat.OUTLINE, TableFormat.PLAIN, TableFormat.PRESTO, TableFormat.PRETTY, TableFormat.PSQL, TableFormat.ROUNDED_GRID, TableFormat.ROUNDED_OUTLINE, TableFormat.RST, TableFormat.SIMPLE, TableFormat.SIMPLE_GRID, TableFormat.SIMPLE_OUTLINE, TableFormat.VERTICAL})¶

Formats laying a wrapped cell over several lines while keeping it one cell.

Column widths are a presentation hint: they are honored by the formats listed here and silently dropped by every other one, the same way styling degrades per format in STYLED_FORMATS. Dropping is the point, as a width forced onto a format below would corrupt its output.

Important

Every format absent from this registry renders max_column_widths unusable, for one of four reasons:

  • aligned: this module’s own zero-padding format. tabulate does not indent its continuation lines, so a wrapped cell escapes its column.

  • github, jira, orgtbl, pipe: continuation lines are emitted as additional table rows. They look right in a terminal, but a Markdown, Jira or Org renderer reads them as extra records.

  • asciidoc, html, latex, latex-booktabs, latex-longtable, latex-raw, mediawiki, moinmoin, textile, unsafehtml, youtrack: the line break lands raw inside the cell markup, where the target renderer either collapses it back to a space or breaks the row. These formats delegate wrapping to whatever displays them.

  • CSV_FORMATS, tsv, and the SERIALIZATION_FORMATS: data interchange, where a line break inside a field changes the record rather than its presentation.

click_extra.table.EMOJI_PRESENTATION_SELECTOR = 'ļø'¶

Unicode VARIATION SELECTOR-16, asking for the emoji form of what precedes it.

click_extra.table.EMOJI_PRESENTATION_RE = re.compile('.ļø')¶

Matches one emoji-presentation sequence: a character and the selector.

click_extra.table.CORNER_GLYPH = '↓'¶

The arrow corner_header() places after the row axis.

The Sphinx extension looks for it to find a table with a corner label: see click_extra.sphinx.tables.

click_extra.table.corner_header(rows, columns)[source]¶

Name both axes of a two-axis table in its top-left header cell.

rows says what the first column lists, read downward, and columns what the other headers list, read rightward: corner_header("City", "Month") returns City ↓ \ Month →.

Return type:

str

click_extra.table.render_table(table_data, headers=None, table_format=None, sort_key=None, max_column_widths=None, **kwargs)[source]¶

Render a table and return it as a string.

headers entries carrying a column ID (ColumnSpec instances) plug the table into the active --sort-by selection: when no explicit sort_key is given, rows sort by the selected columns this table carries, and keep their original order when it carries none. See column_sort_key() for the exact semantics.

Parameters:
  • sort_key (Callable[[Sequence[str | None]], Any] | None) – Optional callable passed to sorted() as the key argument. When provided, rows are sorted before rendering.

  • max_column_widths (Sequence[int | Literal['auto'] | None] | int | Literal['auto'] | None) – Width limits, as one entry per column or a single value for all of them. Each entry is a character count, "auto" to absorb the width left on the terminal, or None for no limit. Defaults to the max_width declared by ColumnSpec headers. Silently dropped by formats outside WRAPPABLE_FORMATS.

Return type:

str

click_extra.table.print_table(table_data, headers=None, table_format=None, sort_key=None, max_column_widths=None, **kwargs)[source]¶

Render a table and print it to the console.

headers entries carrying a column ID (ColumnSpec instances) plug the table into the active --sort-by selection: when no explicit sort_key is given, rows sort by the selected columns this table carries, and keep their original order when it carries none. See column_sort_key() for the exact semantics.

ANSI codes carried by cell values and headers depend on the format:

  • Markup formats with native styling support (see STYLED_FORMATS) get them translated to the format’s own styling markup, unless color output is disabled (--no-color, NO_COLOR, …).

  • Other markup formats get them stripped from cell values before rendering, unless --color is explicitly forced on the command line.

  • Plain-text formats keep them raw, and defer to echo()’s sensitivity to the global colorization settings.

Parameters:
  • sort_key (Callable[[Sequence[str | None]], Any] | None) – Optional callable passed to sorted() as the key argument. When provided, rows are sorted before rendering.

  • max_column_widths (Sequence[int | Literal['auto'] | None] | int | Literal['auto'] | None) – Width limits, as one entry per column or a single value for all of them. Each entry is a character count, "auto" to absorb the width left on the terminal, or None for no limit. Defaults to the max_width declared by ColumnSpec headers. Silently dropped by formats outside WRAPPABLE_FORMATS.

Raises:

MissingExtraError – the renderer of table_format is not installed.

Return type:

None

click_extra.table.serialize_data(data, table_format, *, default=None, root_element='records', **kwargs)[source]¶

Serialize arbitrary Python data to a structured format.

Unlike render_table() which expects tabular rows and headers, this function accepts any JSON-compatible data structure (dicts, lists, nested combinations) and serializes it to the requested format.

Only formats in SERIALIZATION_FORMATS are supported.

Parameters:
  • data (Any) – Arbitrary data to serialize (dicts, lists, scalars).

  • table_format (TableFormat) – Target serialization format.

  • default (Callable | None) – Fallback serializer for types not natively supported. Defaults to str, so Path and similar types are stringified automatically. Set to a custom callable for different behavior.

  • root_element (str) – Root element name for XML output.

  • kwargs – Extra keyword arguments forwarded to the underlying serializer (like sort_keys or indent for JSON).

Raises:

ValueError – If the format is not a serialization format.

Return type:

str

click_extra.table.print_data(data, table_format, *, default=None, root_element='records', package='click-extra', **kwargs)[source]¶

Serialize arbitrary Python data and print it to the console.

Wraps serialize_data() with user-friendly error handling for missing optional dependencies.

Parameters:
  • data (Any) – Arbitrary data to serialize.

  • table_format (TableFormat) – Target serialization format.

  • default (Callable | None) – Fallback serializer for custom types. Defaults to str.

  • root_element (str) – Root element name for XML output.

  • package (str) – Package name for install instructions in error messages.

  • kwargs – Extra keyword arguments forwarded to the underlying serializer.

Raises:

MissingExtraError – the serializer of table_format is not installed.

Return type:

None

click_extra.table_options module¶

Options to pick a table’s format, sort its rows and select its columns.

--table-format, --sort-by and --columns publish their choice on the context, where the renderers of click_extra.table read it.

class click_extra.table_options.TableFormatOption(param_decls=None, *, type=EnumChoice('aligned', 'asciidoc', 'colon-grid', 'csv', 'csv-excel', 'csv-excel-tab', 'csv-unix', 'double-grid', 'double-outline', 'fancy-grid', 'fancy-outline', 'github', 'grid', 'heavy-grid', 'heavy-outline', 'hjson', 'html', 'jira', 'json', 'json5', 'jsonc', 'latex', 'latex-booktabs', 'latex-longtable', 'latex-raw', 'mediawiki', 'mixed-grid', 'mixed-outline', 'moinmoin', 'orgtbl', 'outline', 'pipe', 'plain', 'presto', 'pretty', 'psql', 'rounded-grid', 'rounded-outline', 'rst', 'simple', 'simple-grid', 'simple-outline', 'textile', 'toml', 'tsv', 'unsafehtml', 'vertical', 'xml', 'yaml', 'youtrack'), metavar='FORMAT', default=TableFormat.ROUNDED_OUTLINE, expose_value=False, is_eager=True, help='Rendering style of tables.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured option that is adding a --table-format flag to select the rendering style of a table.

The selected table format ID is made available in the context in ctx.meta[click_extra.context.TABLE_FORMAT], where the render_table() and print_table() context methods pick it up as their default format. ctx.meta is shared along the context chain, so declaring this option on a group makes the selected format reach every subcommand:

  • ctx.render_table(table_data, headers, **kwargs): renders and returns the table as a string,

  • ctx.print_table(table_data, headers, **kwargs): renders and prints the table to the console.

Where:

  • table_data is a 2-dimensional iterable of iterables for rows and cells values,

  • headers is a list of string to be used as column headers,

  • **kwargs are any extra keyword arguments supported by the underlying table formatting function.

init_formatter(ctx, param, table_format)[source]¶

Save the resolved table_format in the context’s shared meta.

The render_table() and print_table() context methods read it back at call time.

Return type:

None

click_extra.table_options.column_sort_key(header_defs, sort_columns=None, cell_key=None)[source]¶

Build a row sort key from the sort_columns a table actually carries.

header_defs describes the rendered columns: ColumnSpec instances, with sortable=False for columns that cannot be sorted on. The requested sort_columns the table carries drive the comparison first, de-duplicated and in request order; the remaining columns follow in their natural left-to-right order for tie-breaking.

Returns None when the table carries none of the requested columns, signalling that rows should keep their original order. This is what lets one --sort-by selection apply across subcommands rendering heterogeneous tables: each table sorts by the requested fields it knows, and a table knowing none of them is left untouched.

Return type:

Callable[[Sequence[str | None]], tuple] | None

class click_extra.table_options.ColumnsType(choices=())[source]¶

Bases: MultiChoice

MultiChoice over the IDs of table columns.

Pins the comma separator and case-sensitive matching (column IDs are snake_case identifiers, not free-form strings), and renames the metavar fallback to COLUMNS instead of the generic MULTI.

Initialize the type.

Parameters:
  • choices (Sequence[str]) – the accepted values. When non-empty, convert() rejects unknown tokens with fail. When empty, the type behaves as a pure separator-aware parser and leaves validation to the consumer.

  • separator – the token boundary. Use any single character; this also drives the metavar rendering ([a<sep>b<sep>c]).

  • case_sensitive – when True, a token must match one of choices exactly. By default tokens match case-insensitively, as with EnumChoice and ThemeChoice, and the returned tuple holds the canonical (original-case) values from choices.

name: str = 'columns'¶

the descriptive name of this type

class click_extra.table_options.ColumnsOption(param_decls=None, *, columns=None, type=None, metavar='COLUMNS', default=(), expose_value=False, is_eager=True, help='Restrict and reorder table columns, SQL SELECT-style. Comma-separated list of column IDs. Default: all columns in canonical order.', **kwargs)[source]¶

Bases: ExtraOption

A --columns option that lets users restrict and reorder table columns.

Accepts a comma-separated list of column IDs, SQL-SELECT-style:

$ my-cli --columns id,spec,value --params

The selection is stored in ctx.meta[click_extra.context.COLUMNS] and consumed by table-rendering callbacks (like click_extra.show_params.ShowParamsOption) to project rows + headers before rendering.

Pass columns= at construction time with the column registry the option should advertise: the help text then lists the accepted IDs and the default selection, and the callback validates the user input against that registry so unknown IDs fail fast with a click.UsageError. Without columns=, the option stays generic: it parses any IDs and leaves validation to the downstream consumer.

Empty / unset means render every column in canonical order: the default behavior, indistinguishable from not passing --columns at all.

columns: tuple[ColumnSpec, ...]¶

Column registry this option advertises and validates against (may be empty).

init_columns(ctx, param, columns)[source]¶

Store the selected column IDs on the context for later projection.

convert() validates the IDs against the registry before this callback runs, so this only threads the parsed selection onto the context.

Return type:

None

class click_extra.table_options.SortByOption(*header_defs, param_decls=None, columns=None, default=None, expose_value=False, cell_key=None, help='Sort table by this column. Repeat to set priority.', **kwargs)[source]¶

Bases: ExtraOption

A --sort-by option whose choices are derived from column definitions.

Stores the selected column IDs in ctx.meta[click_extra.context.SORT_BY] and publishes the derived row sort key in ctx.meta[click_extra.context.TABLE_SORT_KEY], which ctx.print_table picks up so that table output is automatically sorted, without changing its (table_data, headers) call contract. The option accepts multiple=True, so users can repeat --sort-by to define a multi-column sort priority.

Column definitions are ColumnSpec instances, passed positionally or via the columns= keyword. A column marked sortable=False keeps its place in the layout without being offered as a choice. Passing a ColumnSpec registry via columns= lets the same tuple drive both ColumnsOption (--columns) and --sort-by, so the two options stay in sync from a single source of truth.

COLUMNS = (
    ColumnSpec("package_id", "Package ID"),
    ColumnSpec("package_name", "Name"),
    ColumnSpec("manager_id", "Manager"),
)


@command
@table_format_option
@columns_option(columns=COLUMNS)
@sort_by_option(columns=COLUMNS)
@pass_context
def my_cmd(ctx):
    ctx.print_table(rows, [col.label for col in COLUMNS])

Definitions may instead be bare column ID strings, declaring a field vocabulary untied to any single table layout. This fits a --sort-by declared once on a group whose subcommands render heterogeneous tables: no sort key is published since no layout is known up front. The selection is resolved per table by print_table(), from the column IDs its headers carry: each table sorts by the selected fields it knows (remaining columns breaking ties left to right) and keeps its original row order when it knows none.

@group
@sort_by_option("package_id", "package_name", "manager_id")
def my_cli():
    pass


@my_cli.command
def installed():
    print_table(
        rows,
        [
            ColumnSpec("package_id", "Package ID"),
            ColumnSpec("manager_id", "Manager"),
        ],
    )


@my_cli.command
def managers():
    print_table(rows, [ColumnSpec("manager_id", "Manager"), "Path"])
field_vocabulary¶

Whether definitions are bare column IDs, untied to any table layout.

In this mode init_sort() only publishes the selection on the context: the sort is resolved per table at print_table() time.

init_sort(ctx, param, sort_columns)[source]¶

Publish the row sort key on the context’s shared meta.

Builds the sort key from this option’s column definitions and the selected sort_columns, then stores it under ctx.meta[click_extra.context.TABLE_SORT_KEY], where ctx.print_table picks it up. The call contract is the same sorted or not: ctx.print_table(table_data, headers).

In field-vocabulary mode no table layout is known at declaration time, so no key is published: only the selection lands on the context (ctx.meta is shared with every subcommand), resolved per table by print_table() from the column IDs its headers carry.

Return type:

None

click_extra.telemetry module¶

Telemetry utilities.

class click_extra.telemetry.TelemetryOption(param_decls=None, *, default=False, expose_value=False, envvar=None, show_envvar=True, help='Collect telemetry and usage data.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured --telemetry/--no-telemetry option flag.

Respects the proposed DO_NOT_TRACK environment variable as a unified standard to opt-out of telemetry for TUI/console apps: a truthy DO_NOT_TRACK forces telemetry off, overriding the user-defined environment variables, the auto-generated values, and configuration files. Only an explicit --telemetry on the command line outranks it.

The resolved value is stored in ctx.meta[click_extra.context.TELEMETRY].

set_telemetry(ctx, param, value)[source]¶

Reconcile the flag with DO_NOT_TRACK and store the result on ctx.meta.

An explicit --telemetry/--no-telemetry on the command line wins. Otherwise a truthy DO_NOT_TRACK (bare presence, or any value not parseable as false, see parse_envvar_flag()) forces telemetry off. Read via click_extra.context.get(ctx, click_extra.context.TELEMETRY).

Important

DO_NOT_TRACK breaks the rule of the other machine-wide variables, which a configuration file and the option’s own variable outrank (see machine_envvars_apply()). It is a consumer-protection opt-out: a user exports it once to refuse tracking from every tool, and a configuration file a project ships, or a <CLI>_TELEMETRY variable a wrapper or a CI job sets, must not opt that user back in. Only the command line, which the user types, outranks it.

Note

DO_NOT_TRACK is read here rather than wired through the option’s envvar: Click’s environment plumbing feeds the raw value straight to the boolean flag, so DO_NOT_TRACK=1 would enable telemetry, inverting the convention. Reading it manually keeps the opt-out meaning, mirroring how ColorOption reads NO_COLOR and friends.

Return type:

None

click_extra.test_suite module¶

Declarative, black-box CLI test suites.

A test suite is a list of CLITestCase invocations: each runs a target command (a name, a command line, or a path to a binary) once with extra parameters, then checks its exit code and stdout/stderr against literal, substring, or regex expectations. Cases carry their own platform skip/only rules, so one suite runs across operating systems unchanged.

Suites are written in any list-capable configuration format and loaded with load_test_suite() (which picks the format from the file extension) or parse_test_suite() (which parses a serialized string). TOML, JSON and JSONC are built in; YAML and the other SUITE_FORMATS need their matching click-extra[…] extra. run_test_suite() drives a list of cases against a target, parallelized per the resolved --jobs count (see click_extra.jobs.run_jobs()) and reporting live progress through a click_extra.spinner.Spinner.

This is the black-box, subprocess-level complement to click_extra.testing.CliRunner, which drives a CLI in-process.

Todo

Import NestedReferences from the root of extra_platforms, in place of the private extra_platforms._types._TNestedReferences, once extra-platforms 15.0.0 ships on PyPI and the floor of that dependency moves to >=15. extra-platforms 16.0.0 removes the private alias.

click_extra.test_suite.SUITE_FORMATS: tuple[ConfigFormat, ...] = (ConfigFormat.TOML, ConfigFormat.JSON, ConfigFormat.JSONC, ConfigFormat.YAML, ConfigFormat.JSON5, ConfigFormat.HJSON)¶

Configuration formats a test suite can be serialized in, built-in ones first.

These are the formats able to represent a top-level list of case mappings, matched against a file’s extension by load_test_suite(). TOML, JSON and JSONC parse with no extra dependency; the others each need their matching click-extra[…] extra. TOML has no bare top-level array, so a TOML suite lists its cases under a [[cases]] array of tables (see parse_test_suite()); the others use a bare list. INI (no nesting) and XML (no natural list representation) are excluded.

Per-format availability is resolved by ConfigFormat, so a format whose parser is not installed raises an ImportError pointing at its extra at parse time.

exception click_extra.test_suite.SkippedTest[source]¶

Bases: Exception

Raised when a test case should be skipped.

class click_extra.test_suite.CLITestCase(cli_parameters=tuple(), env=dict(), unset_env=tuple(), skip_platforms=tuple(), only_platforms=tuple(), timeout=None, exit_code=None, strip_ansi=False, output_contains=tuple(), stdout_contains=tuple(), stderr_contains=tuple(), output_regex_matches=tuple(), stdout_regex_matches=tuple(), stderr_regex_matches=tuple(), output_regex_fullmatch=None, stdout_regex_fullmatch=None, stderr_regex_fullmatch=None)[source]¶

Bases: object

A single CLI test case: how to invoke the command and what to expect.

Each case runs the command-under-test once with cli_parameters appended, then checks the captured result against the expectation directives below. A case with no expectation only asserts the command ran (plus exit_code, if set).

cli_parameters: tuple[str, ...] | str¶

Arguments and options appended to the command-under-test.

A plain string is split into arguments the way the platform’s own parser does, quoted runs kept whole: shlex on POSIX, CommandLineToArgvW on Windows. A list or tuple is used as-is.

env: dict[str, str]¶

Environment variables set on the command, over the inherited environment.

The second input surface of a CLI, and the only way to reach a variable-only feature from a suite: an option can be typed as a cli_parameters flag, a variable cannot. Values must be strings, so a number or a boolean is quoted ("1", not 1): an environment holds strings only, and coercing would have to pick between True and true on the author’s behalf.

Applied to that one child process, never to the suite runner’s own environment, so cases stay independent under --jobs. See unset_env to take a variable away instead.

unset_env: tuple[str, ...] | str¶

Environment variables removed from the inherited environment.

The half env cannot express. Assigning the empty string leaves a variable set, and a flag read by bare presence (like ACCESSIBLE or DO_NOT_TRACK) counts that as activation, so hiding one from the command means removing it. This is what keeps a case from answering to whatever the shell running the suite happens to export.

A separate directive rather than a null value in env because TOML has no null literal, and a suite is as likely to be written in TOML as in YAML. Removing a variable that is not set is a no-op.

skip_platforms: Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[_TNestedReferences]]¶

Platforms (or platform-group IDs) on which to skip this case.

Accepts extra_platforms identifiers such as linux, macos, windows, in any case, mixed freely with group IDs.

only_platforms: Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[_TNestedReferences]]¶

Restrict this case to these platforms; skip it everywhere else.

The mirror image of skip_platforms, using the same identifiers.

timeout: float | str | None = None¶

Seconds before the command is killed and the case fails as a timeout.

Falls back to the command’s --timeout default, then to no limit.

exit_code: int | str | None = None¶

Expected process exit code; the case fails on any other code.

strip_ansi: bool = False¶

Strip ANSI escape sequences from the captured output before matching.

output_contains: tuple[str, ...] | str¶

Substrings that must all be present in the combined output.

The combined output interleaves stdout and stderr in the order the command wrote them, matching what a user sees in a terminal. The output_* directives are mutually exclusive with the stdout_* / stderr_* ones: a single subprocess run captures either the merged stream or the separate ones, not both.

stdout_contains: tuple[str, ...] | str¶

Substrings that must all be present in stdout.

stderr_contains: tuple[str, ...] | str¶

Substrings that must all be present in stderr.

output_regex_matches: tuple[Pattern | str, ...] | str¶

Regexes that must each match somewhere in the combined output (searched, re.DOTALL). See output_contains for the merged-stream semantics.

stdout_regex_matches: tuple[Pattern | str, ...] | str¶

Regexes that must each match somewhere in stdout (searched, re.DOTALL).

stderr_regex_matches: tuple[Pattern | str, ...] | str¶

Regexes that must each match somewhere in stderr (searched, re.DOTALL).

output_regex_fullmatch: Pattern | str | None = None¶

Regex that must fully match the combined output, line by line. See output_contains for the merged-stream semantics.

stdout_regex_fullmatch: Pattern | str | None = None¶

Regex that must fully match stdout, line by line.

stderr_regex_fullmatch: Pattern | str | None = None¶

Regex that must fully match stderr, line by line.

execution_trace: str | None = None¶

Rendering of the command execution and its output.

Populated after the case runs, for inspection on failure. Not a directive: a suite cannot set it, and two cases compare the same whether they ran or not.

property has_merged_output_directives: bool¶

Whether any output_* directive (merged stream) is set.

property has_separate_stream_directives: bool¶

Whether any stdout_* or stderr_* directive (separate streams) is set.

run_cli_test(command, additional_skip_platforms, default_timeout, work_directory=None)[source]¶

Run a CLI command and check its output against the test case.

The provided command can be either:

  • a path to a binary or script to execute;

  • a command name to be searched in the PATH,

  • a command line with arguments to be parsed and executed by the shell.

The case’s env and unset_env directives are layered over the inherited environment for this child process only.

work_directory is the directory the command runs in, defaulting to the one the runner itself is in. command is resolved to an absolute path before it takes effect, so moving the target elsewhere never changes which binary is executed, only what a relative path inside the command resolves against.

Return type:

None

click_extra.test_suite.cases_from_data(data)[source]¶

Build CLITestCase instances from already-parsed suite data.

The in-memory counterpart to parse_test_suite() (which parses a string) and load_test_suite() (which reads a file): feed it a suite that is already a Python object, such as the native cases mappings declared in a [tool.<cli>.test-suite] config section.

A suite is a list of case mappings, each keyed by CLITestCase directive names. Formats with no bare top-level array (TOML) carry that list under a top-level cases key, so a mapping is unwrapped here.

Raises:
  • ValueError – the suite is empty, a mapping suite omits cases, or a case uses unknown directives.

  • TypeError – the suite is not a list, or a case is not a mapping.

Return type:

Generator[CLITestCase, None, None]

click_extra.test_suite.parse_test_suite(suite_string, fmt=ConfigFormat.YAML)[source]¶

Parse a serialized test suite string into CLITestCase instances.

fmt selects the serialization format, one of SUITE_FORMATS; it defaults to YAML for string sources with no extension to key on, such as an environment variable. load_test_suite() is the file-based counterpart.

Raises:
  • ValueError – the suite is empty, fmt cannot express a suite, a mapping suite omits cases, or a case uses unknown directives.

  • TypeError – the suite is not a list, or a case is not a mapping.

  • ImportError – the format’s optional parser is not installed.

Return type:

Generator[CLITestCase, None, None]

click_extra.test_suite.load_test_suite(path)[source]¶

Read a test suite file and parse it by the format of its extension.

The format is resolved from path’s name over the list-capable SUITE_FORMATS (so suite.toml parses as TOML, suite.yaml as YAML). Reading and format detection are delegated to click_extra.config.formats.read_file().

Raises:
  • ValueError – the file extension matches no suite format.

  • ImportError – the matched format’s optional parser is not installed.

Return type:

Generator[CLITestCase, None, None]

click_extra.test_suite.run_test_suite(command, cases, *, jobs=1, select_test=None, skip_platform=None, timeout=None, work_directory=None, exit_on_error=False, show_trace_on_error=True, stats=True, show_progress=True)[source]¶

Run a list of test cases against a target command and tally the results.

Cases are parallelized per jobs (see click_extra.jobs.run_jobs()): at one worker they run sequentially and lazily, so exit_on_error can stop before the rest start; otherwise they run in a thread pool and every case runs to completion. Either way outcomes are tallied in submission order. On an interactive terminal a click_extra.spinner.Spinner reports progress unless show_progress is false.

Parameters:
  • command (Path | str) – The target to test: a command name, a command line, or a path to a binary or script.

  • cases (Sequence[CLITestCase]) – The test cases to run.

  • jobs (int) – Number of parallel workers; 1 runs sequentially.

  • select_test (Sequence[int] | None) – 1-based case numbers to run; others are skipped.

  • skip_platform (Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[_TNestedReferences]]]]) – Extra platforms (or group IDs) to skip every case on.

  • timeout (float | None) – Default per-case timeout in seconds when a case sets none.

  • work_directory (Path | str | None) – Directory every case runs its command in, defaulting to the runner’s own. It moves the target, never the runner: the suite file is read before any case starts, and command is resolved to an absolute path first, so neither is looked up relative to it.

  • exit_on_error (bool) – Stop at the first failure (sequential runs only).

  • show_trace_on_error (bool) – Echo the execution trace of each failed case.

  • stats (bool) – Echo a one-line worker summary up front and a result tally.

  • show_progress (bool) – Allow the progress spinner on an interactive terminal.

Return type:

Counter

Returns:

A collections.Counter with total, skipped, and failed keys. A non-zero failed count signals the caller to exit with an error.

click_extra.testing module¶

CLI testing and simulation of their execution.

click_extra.testing.OUTPUT_LABEL = '<output>'¶

Label for the merged stream, where stdout and stderr are interleaved.

click_extra.testing.STDOUT_LABEL = '<stdout>'¶

Label for the standard output stream.

click_extra.testing.STDERR_LABEL = '<stderr>'¶

Label for the standard error stream.

click_extra.testing.EXIT_CODE_LABEL = '<exit_code>'¶

Label for the process exit code.

click_extra.testing.REGEX_NEWLINE = '\\n'¶

Newline token used to split a multi-line regex pattern for line-by-line matching.

click_extra.testing.INVOKE_ARGS = {'args', 'catch_exceptions', 'cli', 'color', 'env', 'input', 'self'}¶

Parameter names of click.testing.CliRunner.invoke().

An extra keyword of CliRunner.invoke() named like one of them collides with Click’s own parameter, and reaches Context through a patched Command.main() call instead (pallets/click#2110).

Todo

pallets/click#3896 adds a context_settings parameter to click.testing.CliRunner.invoke(). It sets the context color without the Command.main() patch in invoke().

On a Click release that carries it, this constant also catches context_settings, and the patch sends it to Context, which rejects it. On such a release, keep context_settings out of the collision set and pass force_color through it. Drop this constant and the patch once the Click floor of this package reaches that release.

click_extra.testing.STREAM_FIELDS = {'output_': ('<output>', 'output'), 'stderr_': ('<stderr>', 'stderr'), 'stdout_': ('<stdout>', 'stdout')}¶

Maps a test-case field prefix to its stream label and StreamView attribute.

output_* directives target the merged stream; stdout_* and stderr_* target the separate streams. Both render_cli_run() and click_extra.test_suite.CLITestCase.run_cli_test() read this single table so the rendered trace and the assertion loop agree on labels and stream selection.

class click_extra.testing.StreamView(stdout='', stderr='', output='', exit_code=None)[source]¶

Bases: object

Normalized view of a CLI run’s captured streams and exit code.

Both runners produce one of these so the renderer and the assertion loop read a single shape, regardless of whether the run was driven in-process (Click’s click.testing.Result) or as a black-box subprocess (subprocess.CompletedProcess).

A run captures either the merged stream (output) or the separate stdout and stderr streams, never both: the unused fields stay empty.

stdout: str = ''¶

Captured standard output, or empty when the merged stream was captured.

stderr: str = ''¶

Captured standard error, or empty when the merged stream was captured.

output: str = ''¶

Captured merged stream (stdout and stderr interleaved), or empty when the separate streams were captured.

exit_code: int | None = None¶

Process exit code, or None when unavailable.

classmethod from_result(result)[source]¶

Build a view from an in-process click.testing.Result.

Click always exposes stdout, stderr and the interleaved output together, so all three are carried over verbatim.

Return type:

StreamView

classmethod from_completed_process(result)[source]¶

Build a view from a black-box subprocess.CompletedProcess.

A subprocess run with stderr merged into stdout (stderr=STDOUT) reports result.stderr as None: that case is rendered as the interleaved output stream. Otherwise the two streams are kept separate.

Return type:

StreamView

click_extra.testing.render_cli_run(args, result, env=None)[source]¶

Render the full simulation of a CLI execution, output included.

CliRunner.invoke() prints it after every run, so a failing test shows the session that produced it.

Return type:

str

class click_extra.testing.Result(runner, stdout_bytes, stderr_bytes, output_bytes, return_value, exit_code, exception, exc_info=None)[source]¶

Bases: Result

A Result subclass with automatic traceback formatting.

Enhances __repr__ so that pytest assertion failures show the full traceback instead of just the exception type.

property formatted_exception: str | None[source]¶

Full formatted traceback, or None if no exception occurred.

click_extra.testing.isolated_filesystem(temp_dir=None)[source]¶

Create a temporary directory and change the working directory to it.

Replaces click.testing.CliRunner.isolated_filesystem(), which Click deprecates and removes in 9.0. Click points at tempfile.TemporaryDirectory and pytest’s tmp_path fixture, and neither replaces it: what isolates a CLI here is the working directory, which a command reads through relative paths and configuration-file globs. The runner pytest fixture and the click:run Sphinx directive both call this on every test and every documented example, where Click’s version would raise a deprecation warning each time.

Warning

The isolation is process-global, because it calls os.chdir(). Parallelize with processes, never with threads.

Parameters:

temp_dir (str | PathLike[str] | None) – create the temporary directory inside this one. When given, the directory is left in place on exit.

Return type:

Generator[str, None, None]

Returns:

path of the directory the working directory was changed to.

class click_extra.testing.CliRunner(charset='utf-8', env=None, echo_stdin=False, catch_exceptions=True, capture='sys')[source]¶

Bases: CliRunner

Augment click.testing.CliRunner with extra features and bug fixes.

force_color: bool = False¶

Default of the force_color argument of invoke(), for every run.

A call passing color=False still gets uncolored output.

invoke(cli, *args, input=None, env=None, catch_exceptions=None, color=None, force_color=None, **extra)[source]¶

Same as click.testing.CliRunner.invoke() with extra features.

  • The first positional parameter is the CLI to invoke. The remaining positional parameters of the function are the CLI arguments. All other parameters are required to be named.

  • The CLI arguments can be nested iterables of arbitrary depth. This is useful for argument composition of test cases with @pytest.mark.parametrize.

  • Adds force_color, which keeps colored output while initializing Context.color = True. click.testing.CliRunner.invoke() cannot express it, its color parameter colliding with the Context one (pallets/click#2110). The force_color class attribute sets it for every run.

  • Strips all ANSI codes from results if color was explicitly set to False.

  • Always prints a simulation of the CLI execution as the user would see it in its terminal. Including colors.

  • Pretty-prints a formatted exception traceback if the command fails.

Parameters:
  • cli (Command) – CLI to invoke.

  • args (str | Path | None | Iterable[str | Path | None | Iterable[Iterable[str | Path | None | Iterable[TNestedArgs]]]]) – can be nested iterables composed of str, pathlib.Path objects and None values. The nested structure will be flattened and None values will be filtered out. Then all elements will be cast to str. See args_cleanup() for details.

  • input (str | bytes | IO | None) – same as click.testing.CliRunner.invoke().

  • env (Mapping[str, str | None] | None) – same as click.testing.CliRunner.invoke().

  • catch_exceptions (bool | None) – same as click.testing.CliRunner.invoke(): None (the default) follows the runner’s own catch_exceptions.

  • color (bool | None) – whether the captured streams keep ANSI codes, passed to click.testing.CliRunner.isolation(). False also scrubs the result bytes.

  • force_color (bool | None) – keep the ANSI codes and initialize the invoked CLI’s Context.color to True, so it takes its colored branch. None (the default) follows the force_color class attribute.

  • extra (Any) – same as click.testing.CliRunner.invoke(), but colliding parameters are allowed and properly passed on to the invoked CLI.

Raises:

ValueError – if force_color=True is passed with color=False.

Return type:

Result

isolated_filesystem(temp_dir=None)[source]¶

Same as isolated_filesystem(), minus Click’s deprecation warning.

Overrides click.testing.CliRunner.isolated_filesystem() so a runner keeps the helper once Click 9.0 removes it.

Return type:

Generator[str, None, None]

click_extra.testing.unescape_regex(text)[source]¶

De-obfuscate a regex for better readability.

This is like the reverse of re.escape().

Return type:

str

exception click_extra.testing.RegexLineMismatch(regex_line, content_line, line_number)[source]¶

Bases: AssertionError

Raised when a regex line does not match the corresponding content line.

click_extra.testing.regex_fullmatch_line_by_line(regex, content)[source]¶

Check that the content matches the given regex.

If the regex does not fully match the content, raise an AssertionError, with a message showing the first mismatching line.

This is useful when comparing large walls of text, such as CLI output.

Return type:

None

click_extra.theme module¶

Help-screen color themes for Click Extra.

Holds the HelpTheme dataclass, the NOCOLOR_THEME constant, the process-wide fallback accessed via get_default_theme() / set_default_theme(), the named-theme theme_registry plus register_theme() helper, and the ThemeOption that exposes --theme on every Click Extra command.

The built-in themes (dark, dracula, light, manpage, monokai, nord, solarized-dark) are plain mappings declared in this module, each built through HelpTheme.from_dict() on its first lookup: importing the package builds none of them, and a help screen builds only the one it renders with. manpage is a colorless theme that shadows man-pages(7) typography (bold literals, italic replaceable); the others apply that same bold/italic split on top of their color palettes. Those mappings follow the schema of user-defined themes loaded from configuration: see Themes for the user guide.

Note

The active theme for a CLI invocation is stored on the Click context’s meta dict under click_extra.context.THEME by ThemeOption. Use get_current_theme() to retrieve it: that helper consults the active Click context first and falls back to get_default_theme() when no context is in flight (like at import time, in wrap patching, or in bare REPL usage). Per-invocation context storage means concurrent invocations of the same CLI in one process (Sphinx builds, test runners, REPLs) do not leak --theme choices into each other.

click_extra.theme.THEME_ENVVAR: Final[str] = 'CLICK_EXTRA_THEME'¶

Environment variable naming the help-screen palette of every Click Extra CLI.

Global and CLI-agnostic, unlike the <CLI>_THEME variable Click derives from the option itself: exporting it once from a shell profile themes every Click Extra command installed on the machine, including the ones a user wraps with click-extra wrap. It accepts the same values as --theme, the AUTO_THEME directive included.

Read by set_theme() as a last resort, so a --theme flag, a <CLI>_THEME variable and a configuration file each outrank it. See that method for why it is read directly instead of being wired through the option’s envvar.

class click_extra.theme.HelpTheme(invoked_command=<function identity>, command_help=<function identity>, heading=<function identity>, constraint=<function identity>, section_help=<function identity>, col1=<function identity>, col2=<function identity>, alias=<function identity>, alias_secondary=None, epilog=<function identity>, critical=<function identity>, error=<function identity>, warning=<function identity>, info=<function identity>, debug=<function identity>, option=<function identity>, subcommand=<function identity>, choice=<function identity>, metavar=<function identity>, bracket=<function identity>, envvar=<function identity>, default=<function identity>, range_label=<function identity>, required=<function identity>, argument=<function identity>, deprecated=<function identity>, separator=<function identity>, search=<function identity>, success=<function identity>, cross_ref_highlight=True, subheading=<function identity>)[source]¶

Bases: HelpTheme

Extends cloup.HelpTheme with slots for log levels and the structural elements Click Extra highlights in help screens.

Each slot below documents what it colors. The built-in themes shipped in BUILTIN_THEMES provide the visual styling by setting the relevant slots; user-defined themes can be authored as plain mappings and loaded via from_dict().

critical()¶

Style applied to the CRITICAL level name in log records.

Example: CRITICAL: Database connection lost.

Rendered with the default dark theme:

CRITICAL: Database connection lost.
Return type:

T

error()¶

Style applied to the ERROR level name in log records.

Example: ERROR: Configuration file not found.

Rendered with the default dark theme:

ERROR: Configuration file not found.
Return type:

T

warning()¶

Style applied to the WARNING level name in log records.

Example: WARNING: Requested 16 jobs exceeds the 8 logical CPUs: honored, but pays only for I/O-bound work.

Rendered with the default dark theme:

WARNING: Requested 16 jobs exceeds the 8 logical CPUs: honored, but pays only for I/O-bound work.
Return type:

T

info()¶

Style applied to the INFO level name in log records.

Usually left at identity: INFO is the default verbosity and shouldn’t stand out from regular output.

Rendered with the default dark theme:

INFO: Loaded 23 records.
Return type:

T

debug()¶

Style applied to the DEBUG level name in log records.

Example: DEBUG: Resolved /etc/myapp/config.toml.

Rendered with the default dark theme:

DEBUG: Resolved /etc/myapp/config.toml.
Return type:

T

option()¶

Style applied to option names (--config, -v, --color/--no-color) wherever they appear: synopsis column, free-form descriptions, and docstrings (when cross_ref_highlight is enabled).

Rendered with the default dark theme:

--config LOCATION    Location of the configuration file.
-v, --verbose        Increase verbosity.
Return type:

T

subcommand()¶

Style applied to subcommand names: in a group’s command list and wherever they are referenced in prose.

Rendered with the default dark theme:

Commands:
  backup        Snapshot the data store.
  restore       Restore from a snapshot.
Return type:

T

choice()¶

Style applied to each individual value inside a click.Choice metavar (like json, csv, xml within [json|csv|xml]) and to those values referenced in option descriptions.

Rendered with the default dark theme:

--format [json|csv|xml]   Output format. Defaults to json.
Return type:

T

metavar()¶

Style applied to type metavars (INTEGER, TEXT, PATH, FILE, …) that follow an option name in the synopsis column.

Rendered with the default dark theme:

--output TEXT       Destination file.
--workers INTEGER   Worker count.
Return type:

T

bracket()¶

Style applied to the literal bracket characters and label prefixes of trailing fields: [, ], default:, env var:, and the field separators between them. Also acts as the fallback for the four inner bracket-field slots (envvar, default, required, range_label) whenever any of them is left at identity. A theme that only sets bracket therefore renders the whole bracket field with a single uniform style; richer themes layer specific colors on top by setting the inner slots.

Rendered with the default dark theme:

--port INTEGER    [env var: PORT; default: 8080; required]
Return type:

T

envvar()¶

Style applied to environment-variable values inside [env var: ...] bracket fields, and to envvar names mentioned in option descriptions. Falls back to bracket when left at identity, so a theme that only styles bracket still gets a consistent rendering inside bracket fields.

Rendered with the default dark theme:

--threshold INTEGER   Acceptable error rate.
                      [env var: THRESHOLD, TEST_THRESHOLD]
Return type:

T

default()¶

Style applied to the default-value content inside [default: ...] bracket fields. Falls back to bracket when left at identity.

Rendered with the default dark theme:

--output FILENAME    Destination file.  [default: out.csv]
--retries INTEGER    Retry budget.  [default: 5]
Return type:

T

range_label()¶

Style applied to range expressions (0<=x<=9, x>=1024, 0<=x<100) that appear inside bracket fields for IntRange and FloatRange options. Falls back to bracket when left at identity.

Rendered with the default dark theme:

--level INTEGER RANGE    Verbosity level.  [0<=x<=9]
--port INTEGER RANGE     Bind port.        [x>=1024]
Return type:

T

required()¶

Style applied to the required label inside bracket fields on mandatory options. Falls back to bracket when left at identity.

Rendered with the default dark theme:

--token TEXT    Authentication token.  [required]
Return type:

T

argument()¶

Style applied to argument metavars (positional parameter names like MY_ARG, SCRIPT, [FILENAMES]...) in the synopsis column and when referenced in prose.

Rendered with the default dark theme:

Usage: cp [OPTIONS] SRC DST
Usage: pack [OPTIONS] [FILES]... [OUTPUT]
Return type:

T

deprecated()¶

Style applied to (DEPRECATED) / (Deprecated: reason) markers appended to options and commands.

Rendered with the default dark theme:

--old-api    Legacy endpoint. (DEPRECATED: use --new-api instead)
--legacy     Kept for compatibility. (deprecated: removed in v9)
Return type:

T

separator()¶

Style applied to the -- end-of-options separator, wherever a help screen writes it on its own: my-cli wrap -- target-cli --help.

It is punctuation rather than a word, and it reads as one of the target CLI’s own options until something tells the two apart.

Return type:

T

search()¶

Style applied to substring matches in <cli> help --search output, so users can spot where their query matched.

Rendered with the default dark theme:

--retry-budget INTEGER    The retry budget.
Return type:

T

success()¶

Style applied to success glyphs in pre-rendered UI elements (the āœ“ in OK_GLYPH) and any text passed through this slot by downstream code.

Rendered with the default dark theme:

āœ“ database migration completed
āœ“ 1,245 records imported
Return type:

T

cross_ref_highlight: bool = True¶

Highlight options, choices, arguments, metavars and CLI names in free-form text (descriptions, docstrings).

When False, only structural elements are styled: bracket fields ([default: ...], [env var: ...], ranges, [required]), deprecated messages, and subcommand names in definition lists.

subheading()¶

Style for sub-section headings inside log output or inline help.

Distinct from heading (which styles the top-level help-screen section titles): subheading is intended for downstream code that wants a second styling level for its own narrative output.

See also

Used by mail-deduplicate to style ā—¼ N mails sharing hash … log lines.

Rendered with the default dark theme:

ā—¼ 3 mails sharing hash a1b2c3d4
ā—¼ 7 mails sharing hash e5f6a7b8
Return type:

T

with_(**kwargs)[source]¶

Derive a new theme from this one, with some slots overridden.

Returns the same instance when every slot keeps its value, where cloup’s version builds a copy whatever it is given. None is a value like any other, not a slot left alone.

Raises:

TypeError – listing every argument that names no slot.

Return type:

Self

classmethod dark()[source]¶

A theme assuming a dark terminal background color.

Carries cloup’s palette, each style widened to Style, and leaves the slots this subclass adds at their default. For a theme coloring those too, reach for BUILTIN_THEMES instead.

Return type:

Self

classmethod light()[source]¶

A theme assuming a light terminal background color.

Carries cloup’s palette, like dark().

Return type:

Self

to_dict()[source]¶

Serialize the theme to a plain dict suitable for TOML/JSON/YAML.

Each Style slot is emitted via Style.to_dict. Slots left at their default (identity or None) are omitted, so the output only carries what the theme actually overrides. Pair with from_dict() to round-trip.

Raises:

TypeError – when a slot holds an opaque IStyle callable that is not a Style (those cannot be serialized).

Return type:

dict[str, Any]

classmethod from_dict(data)[source]¶

Build a theme from the plain dict produced by to_dict().

Each value is interpreted by field type: a mapping becomes a Style via Style.from_dict, while cross_ref_highlight is read as a plain bool. Unknown keys raise TypeError so typos surface immediately.

Return type:

HelpTheme

cascade(base)[source]¶

Layer this theme’s set slots on top of base.

Mirrors Style.cascade at the slot level: this theme’s non-default slots win, base fills the rest. Useful for layering a sparse override (typically parsed from a config file’s [tool.<cli>.themes.<name>] table) on top of a full built-in palette.

Raises:

TypeError – when base is not a HelpTheme.

Return type:

HelpTheme

click_extra.theme.LITERAL_STYLES: frozenset[str] = frozenset({'alias', 'alias_secondary', 'choice', 'invoked_command', 'option', 'separator', 'subcommand'})¶

Names of the HelpTheme slots that color literal tokens: text the user types verbatim on the command line.

Covers the command and subcommand names, their aliases, option flags (--config, -v), the concrete values of a click.Choice (json in [json|csv|xml]), and the -- separator.

These map to the bold font of the man-pages(7) typographic convention, which sets text ā€œtyped literallyā€ in bold (\fB in roff) ā€œeven in the SYNOPSIS sectionā€. Paired with REPLACEABLE_STYLES: the two are disjoint, and every remaining slot is an annotation, prose, or chrome style that the literal/replaceable dichotomy does not classify (log levels, [default: ...] / [env var: ...] fields, headings, …).

Note

Every built-in theme applies this classification: literal slots render bold and REPLACEABLE_STYLES italic, mirroring a man page even in the color palettes. tests/test_theme.py enforces the invariant, and the manpage built-in theme is its pure-monochrome embodiment (bold/italic, no color). The man-page generator of click_extra.command_doc follows the same split, setting each token in \fB or \fI.

click_extra.theme.REPLACEABLE_STYLES: frozenset[str] = frozenset({'argument', 'metavar'})¶

Names of the HelpTheme slots that color replaceable tokens: placeholders the user substitutes with a real value.

Covers type metavars on options (INTEGER, PATH) and positional argument metavars (SOURCE, [FILENAMES]...).

These map to the italic font of the man-pages(7) convention, which sets replaceable arguments in italic (\fI in roff). See LITERAL_STYLES for the bold counterpart and the full rationale.

click_extra.theme.NOCOLOR_THEME: HelpTheme = HelpTheme(invoked_command=<function identity>, command_help=<function identity>, heading=<function identity>, constraint=<function identity>, section_help=<function identity>, col1=<function identity>, col2=<function identity>, alias=<function identity>, alias_secondary=None, epilog=<function identity>, critical=<function identity>, error=<function identity>, warning=<function identity>, info=<function identity>, debug=<function identity>, option=<function identity>, subcommand=<function identity>, choice=<function identity>, metavar=<function identity>, bracket=<function identity>, envvar=<function identity>, default=<function identity>, range_label=<function identity>, required=<function identity>, argument=<function identity>, deprecated=<function identity>, separator=<function identity>, search=<function identity>, success=<function identity>, cross_ref_highlight=True, subheading=<function identity>)¶

Color theme for Click Extra to force no colors.

All style slots default to identity, so styling calls return the raw text unchanged.

click_extra.theme.BUILTIN_THEMES: Mapping[str, HelpTheme] = _LazyThemes(['dark', 'dracula', 'light', 'manpage', 'monokai', 'nord', 'solarized-dark'])¶

Mapping of built-in theme names to their HelpTheme instances.

Each theme is built from its definition in this module on its first lookup, and the same instance is returned from then on. theme_registry starts with the same entries.

Index by name to access any palette, like BUILTIN_THEMES["dark"] or BUILTIN_THEMES["solarized-dark"].

click_extra.theme.get_default_theme()[source]¶

Return the process-wide fallback theme.

Read by get_current_theme() when no Click context is active or when the active context has no theme set. The default is the built-in dark palette; patch_click() overrides it via set_default_theme() for the duration of a patched session.

Resolved through a function rather than a module attribute so callers always observe the current value: a module attribute bound once, like a default parameter value, keeps whatever was set at import time.

Return type:

HelpTheme

click_extra.theme.set_default_theme(theme)[source]¶

Override the process-wide fallback theme.

ThemeOption writes its picked theme to ctx.meta rather than calling this helper, so per-invocation choices do not leak across invocations sharing the same process. Use this only for genuinely process-wide overrides: patch_click() is the canonical caller.

Return type:

None

click_extra.theme.get_current_theme()[source]¶

Return the theme active for the current CLI invocation.

Resolution order:

  1. The theme stored on the active Click context under click_extra.context.THEME (set by ThemeOption from --theme).

  2. The process-wide fallback returned by get_default_theme() (the dark default, or whatever patch_click() set at process start).

Falling back through the active context (instead of reading a module attribute) keeps --theme scoped to the invocation that received it, so a second invocation in the same process starts from the default again.

Return type:

HelpTheme

click_extra.theme.theme_registry: MutableMapping[str, HelpTheme] = _LazyThemes(['dark', 'dracula', 'light', 'manpage', 'monokai', 'nord', 'solarized-dark'])¶

Process-wide registry of named themes used by ThemeOption.

Each entry maps a theme name to its HelpTheme instance. It starts with the entries of BUILTIN_THEMES, each built on its first lookup.

Use register_theme() to add your own at import time, or declare them in your CLI’s config file under [tool.<cli>.themes.<name>]: the latter goes through ConfigOption, lands on ctx.meta (see click_extra.context.THEME_OVERRIDES), and never mutates this module-level dict, so per-invocation choices don’t leak between sibling invocations sharing the same process.

click_extra.theme.register_theme(name, theme)[source]¶

Register a named theme in the module-level theme_registry.

Parameters:
  • name (str) – Lowercase identifier used as the --theme choice value.

  • theme (HelpTheme) – A HelpTheme instance.

Return type:

None

click_extra.theme.get_theme_registry(ctx=None)[source]¶

Return the theme registry visible to ctx.

Merges the module-level theme_registry with any per-invocation overrides stored on ctx.meta under click_extra.context.THEME_OVERRIDES. Per-invocation entries win on key collisions, which is what lets a config file’s [tool.<cli>.themes.dark] table override the built-in dark palette for one invocation without touching the global registry.

When ctx is None or has no overrides, returns a copy of the module-level registry. Either way, a built-in theme is built only when its value is read.

Return type:

MutableMapping[str, HelpTheme]

click_extra.theme.AUTO_THEME: str = 'auto'¶

Reserved --theme value resolving the palette from the terminal background.

Unlike the named built-in palettes, auto is not a registry entry: it is a directive handled by ThemeOption, which calls resolve_auto_theme() to pick dark or light from the detected background, mirroring --color=auto.

It is advertised all the same, in the --help metavar and in shell completion (ThemeChoice.choices), because it works on every Click Extra CLI whether or not that CLI knows about it: a value accepted everywhere and named nowhere is one nobody finds. --color lists its own auto beside always and never for the same reason.

click_extra.theme.resolve_auto_theme(ctx=None, query_background=False)[source]¶

Pick a built-in palette from the detected terminal background.

Resolves the background mode via resolve_background() and maps "dark" / "light" to the same-named theme in the registry visible to ctx (built-ins plus any [tool.<cli>.themes.<name>] config overlays). An undetected background falls back to "dark", preserving Click Extra’s default.

Parameters:
  • ctx (Context | None) – context whose theme registry is consulted.

  • query_background (bool) – when true, allow the live OSC 11 terminal query (query_osc_background()) on top of the environment-variable signals. Off by default because the query reads stdin.

Return type:

HelpTheme | None

Returns:

the chosen HelpTheme, or None when neither the detected palette nor the dark fallback is registered (both were removed from the registry). A None leaves ctx.meta untouched so get_current_theme() keeps the default theme.

click_extra.theme.themes_from_config(table)[source]¶

Build a {name: HelpTheme} mapping from a [tool.<cli>.themes] sub-tree.

For each entry, build a HelpTheme via HelpTheme.from_dict(). If name matches an existing key in theme_registry, the new theme is layered on top via HelpTheme.cascade() so partial overrides (like just one slot) inherit the rest from the built-in palette. Stand-alone names produce theme instances with the unset slots left at their defaults.

Return type:

dict[str, HelpTheme]

click_extra.theme.validate_themes_config(themes_subtree)[source]¶

Validate a [tool.<cli>.themes] sub-tree.

Registered as a built-in ConfigValidator by ConfigOption so malformed theme tables surface as ValidationError with a rooted path (my-cli.themes.<name>) rather than a deep TypeError from HelpTheme.from_dict().

Return type:

None

class click_extra.theme.ThemeChoice(case_sensitive=False)[source]¶

Bases: ParamType

A click.ParamType whose choices track the live theme registry.

Implements the click.Choice-shaped duck interface (choices, case_sensitive, normalize_choice) so click_extra.highlight can collect theme names for per-token highlighting through the same code path it uses for Click’s own Choice. The choices attribute is a property that queries get_theme_registry() at every lookup, so themes registered late (typically by ConfigOption parsing [tool.<cli>.themes.<name>] tables before --theme is processed) are valid choices and appear in the --help metavar.

A plain click.ParamType rather than a click.Choice subclass: click.Choice.__init__ assigns self.choices, which a read-only property cannot take.

name: str = 'choice'¶

the descriptive name of this type

property choices: tuple[str, ...]¶

Values --theme takes, alphabetically sorted.

The theme names visible in the current context, plus AUTO_THEME, which says why a directive is listed among them.

normalize_choice(choice, ctx)[source]¶

Mirrors click.Choice.normalize_choice() for highlight compatibility.

Return type:

str

get_metavar(param, ctx)[source]¶

Returns the metavar default for this param if it provides one.

Return type:

str | None

convert(value, param, ctx)[source]¶

Resolve value to a canonical theme name from the live registry.

Normalizes value and looks it up against the names visible in ctx. Returns the canonical name, None when no themes are registered at all (an inert --theme), and calls fail when value is not a string or does not match any registered theme.

Return type:

str | None

shell_complete(ctx, param, incomplete)[source]¶

Return a list of CompletionItem objects for the incomplete value. Most types do not provide completions, but some do, and this allows custom types to provide custom completions as well.

Parameters:
  • ctx (Context) – Invocation context for this command.

  • param (Parameter) – The parameter that is requesting completion.

  • incomplete (str) – Value being completed. May be empty.

Return type:

list[CompletionItem]

Added in version 8.0.

class click_extra.theme.ThemeOption(param_decls=None, *, default='dark', is_eager=True, expose_value=False, query_background=False, help='Color theme used for help screens.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured option that adds --theme to select the help-screen palette.

Accepts any name registered in theme_registry or in the per-invocation overrides loaded by ConfigOption from [tool.<cli>.themes.<name>]. Validation goes through ThemeChoice, which reads the live registry at parse time, so config-defined themes appear as valid choices and in the --help metavar without any further wiring.

The resolved HelpTheme lands on the Click context under click_extra.context.THEME and applies for the duration of the current invocation only.

A user who never passes the flag can still pick a palette by exporting THEME_ENVVAR (CLICK_EXTRA_THEME), which is honored by every Click Extra CLI at once. See set_theme() for how it ranks against the flag, the <CLI>_THEME variable and the configuration file.

The reserved value AUTO_THEME (--theme=auto) is also accepted on every CLI: it resolves the palette from the terminal background via resolve_auto_theme() instead of naming a registered theme. Background detection reads environment variables by default; pass query_background=True to additionally allow the live OSC 11 terminal query (query_osc_background()), which is opt-in because it reads stdin.

set_theme(ctx, param, value)[source]¶

Resolve the chosen theme name and store it on the Click context.

ThemeChoice has already validated value against the live registry (or accepted the AUTO_THEME directive) by the time this fires. A plain palette name is looked up unconditionally; auto is resolved from the terminal background via resolve_auto_theme(), leaving ctx.meta untouched when no palette can be resolved so get_current_theme() keeps its default.

Before that, THEME_ENVVAR is consulted when the value still comes from the option’s own default, as for every machine-wide variable (see machine_envvars_apply()). This yields the precedence: --theme > <CLI>_THEME > configuration file > CLICK_EXTRA_THEME > built-in default. The global variable therefore only names the palette of the CLIs nothing else has an opinion about.

Note

The variable is read here rather than wired through the option’s envvar. Click resolves an explicit envvar before the auto-generated <CLI>_THEME, which would let the machine-wide preference outrank the CLI-specific one, and would list both names in the --params table, making the combined string the widest cell of its column. This mirrors how AccessibleOption reads ACCESSIBLE and ColorOption reads NO_COLOR.

An unparsable palette name is a warning, not an error: a typo in a shell profile would otherwise break every Click Extra CLI on the machine at once, including the ones needed to fix it.

Return type:

None

click_extra.theme.OK_GLYPH: str = 'āœ“'¶

Plain check-mark glyph for success indicators.

Style at the call site with the active theme’s success slot: get_current_theme().success(OK_GLYPH). Stored as a raw string so downstream code can render it under whichever theme is active rather than the (frozen) theme that happened to be loaded at import time.

click_extra.theme.KO_GLYPH: str = '✘'¶

Plain heavy-ballot-X glyph for failure indicators.

Style at the call site with the active theme’s error slot: get_current_theme().error(KO_GLYPH). See OK_GLYPH for why the glyph is exposed unstyled.

click_extra.trail module¶

A āœ“/✘ progress trail that reports a batch of operations.

OperationTrail leaves a persistent trail_line() for each completed operation, keeps a running done/total tally on an aggregate indicator while the batch runs, and closes the batch with a kept summary line. The indicator is a Spinner or a determinate click.progressbar().

click_extra.trail.trail_line(ok, message)[source]¶

Format one āœ“/✘ trail line: a glyph followed by message.

The glyph is the one trail_glyph() paints.

Return type:

str

class click_extra.trail.OperationTrail(*, label='', unit='', total=0, jobs=1, spinner=None, progress_bar=False, timer=None, clock='elapsed', visible=True, live='auto', echo_sequential=True, delay=0.0, stream=None)[source]¶

Bases: object

A āœ“/✘ progress trail and finisher for a batch of operations.

Where Spinner narrates one long-running call, OperationTrail reports a batch of them: each completed operation leaves a persistent trail_line() on screen, a running done/total tally keeps the batch’s pulse visible, and finish() closes with a persistent summary line. The natural reporting companion of the concurrency primitives run_jobs() and run_lanes(), rendered one of three ways:

  • sequential (jobs <= 1): echo each outcome as it lands, with no aggregate indicator (each operation is free to keep its own per-call Spinner). finish() appends the elapsed time.

  • concurrent (jobs > 1): drive one aggregate Spinner (per-call spinners would collide on the shared stream), buffering outcomes until it first draws, then streaming the rest live above it. Pick the animation from the SPINNERS catalog with spinner=.

  • progress bar (progress_bar=True): drive one aggregate determinate bar carrying the {done}/{total} tally, with outcomes streaming above it. Serves sequential and concurrent batches alike, and needs a known total.

The aggregate indicators redraw in place, which a pipe or a CI log cannot do, so by default they draw only on an interactive terminal, and live changes where they draw. The āœ“/✘ lines and the finisher only append, so they print on any stream, in plain text where color is off. Where no indicator draws, every rendering echoes each outcome as it lands, as the sequential one does. visible=False silences all of it. The running āœ“ tally is kept as outcomes land (ok_count), so a caller computes no counts of its own.

Thread-safe: mark() may be called from worker threads. Use it as a context manager whenever it may run concurrently, to bound the aggregate spinner’s life; a purely sequential caller may construct it bare.

from click_extra.jobs import run_jobs
from click_extra.trail import OperationTrail

with OperationTrail(label="Fetching", unit="feeds", total=len(feeds),
                    jobs=jobs) as trail:
    def fetch(feed):
        trail.mark(*pull(feed))  # pull() returns (ok, message).

    list(run_jobs(fetch, feeds, jobs=jobs))
    trail.finish(
        trail.ok_count == len(feeds),
        f"Fetched {trail.ok_count}/{len(feeds)} feeds",
    )

Configure (but do not start) the trail.

Parameters:
  • label (str) – present-tense verb for the running aggregate indicator ("Fetching"), composed into its {label} {done}/{total} {unit} tally.

  • unit (str) – the noun counted in the tally ("files", "feeds").

  • total (int) – how many outcomes are expected, for the done/total count.

  • jobs (int) – the batch’s worker count; > 1 selects the concurrent rendering (one aggregate spinner), <= 1 the sequential one (plain echoed lines).

  • spinner (SpinnerPreset | None) – a SpinnerPreset from the SPINNERS catalog (spinner=SPINNERS["moon"]) for the concurrent aggregate spinner. Ignored by the sequential and progress-bar renderings, and mutually exclusive with progress_bar.

  • progress_bar (bool) – render the aggregate indicator as a determinate click.progressbar() instead of a spinner, for a sequential or concurrent batch alike. Requires a positive total (a bar needs a length) and is mutually exclusive with spinner.

  • timer (bool | Callable[[float], str] | None) – append each operation’s and the batch’s elapsed time to the trail lines and the finisher. None (the default) follows the CLI’s --time / --no-time flag; True forces timing on with format_duration()’s compact clock, a callable (seconds: float) -> str forces it on with a custom format, and False forces it off. Per-operation times come from a seconds argument to mark(), filled in automatically by an operation() handle.

  • clock (Literal['elapsed', 'eta']) – whether a running aggregate indicator shows elapsed time ("elapsed", the default: a stopwatch counting up, visible from the start) or remaining time ("eta": an estimate from the batch’s rate, appearing only once an outcome lets it be computed). Both the progress bar and the concurrent spinner honor "eta" (the spinner reuses Click’s progress-bar estimate, since the trail knows its total). Per-operation and finisher times are always elapsed.

  • visible (bool) – whether the trail shows anything. False silences the lines, the finisher and the aggregate indicator, while ok_count keeps counting.

  • live (Literal['auto', 'always', 'never']) – where the aggregate indicator may draw: "auto" (the default) on an interactive terminal only, unless --no-progress turns it off, "always" on any stream, "never" nowhere. Where it does not draw, each outcome line prints as it lands.

  • echo_sequential (bool) – whether the batch echoes its outcome lines and finisher as plain lines at all: in a sequential batch, in a batch whose aggregate indicator cannot draw on the stream, and in one that finishes before its indicator first draws. Turn it off when the batch has another output that is the real product (a result table) and the trail would be noise. An indicator that did draw is unaffected.

  • delay (float) – seconds before the aggregate indicator first draws: a fast batch then completes without ever flashing one, its lines echoed plainly at finish() instead (see echo_sequential).

  • stream (IO[str] | None) – where to render; defaults to sys.stderr so the trail never mixes into stdout data.

Raises:

ValueError – if progress_bar is set without a positive total, or together with spinner, if clock is neither "elapsed" nor "eta", or if live is not one of WHEN.

property ok_count: int¶

How many marked outcomes have succeeded so far.

mark(ok, message, seconds=None)[source]¶

Record one āœ“/✘ outcome: tally it and render its trail line.

Parameters:

seconds (float | None) – the operation’s own elapsed time. When timer is on it is formatted and appended to message as (2.3s). An operation() handle fills this in from when it was created; pass it yourself when you already hold a duration.

Return type:

None

finish(ok, summary)[source]¶

Render the persistent āœ“/✘ {summary} finisher.

With an aggregate indicator that drew, it becomes the indicator’s kept line (a spinner’s ok() / fail() line, or the bar’s replacement line); otherwise, a plain echoed line. The batch’s elapsed time since construction is appended when timer is on.

A batch finishing inside delay never draws its indicator, so none of its buffered lines reached the stream. When the trail is the batch’s output (echo_sequential and visible), they are echoed plainly along with the finisher, the way a sequential batch prints them: how fast a batch ran must not decide whether its record exists.

Return type:

None

operation()[source]¶

Start a timed operation, returning a handle to record its outcome.

The handle captures the current time; call _Operation.mark() when the work finishes to record its āœ“/✘ outcome with the elapsed time appended (when timer is on). This is how a batch reports per-operation timings under concurrency, where the trail itself never sees when an operation began:

def fetch(feed):
    op = trail.operation()
    ok, message = pull(feed)
    op.mark(ok, message)
Return type:

_Operation

click_extra.tree module¶

Render Click command hierarchies as trees.

Provides the --tree flag: a constant-cost overview of a CLI’s nested subcommands, where the only alternative is walking --help screens one level at a time or generating a full man page or completion spec dump.

This is the command-level, hierarchical companion of --params: where the parameter table flattens the hierarchy into dotted id paths (cli.subcommand.param), the tree renders the skeleton those paths hang off. Both share the same dynamic discovery (click.Group.list_commands() / click.Group.get_command() via iter_subcommands()) and the same one-line descriptions (full_short_help()).

The tree is a human rendering only: machine-readable hierarchies are already served by --params --table-format json (parameters with dotted paths) and the Carapace exporter (click_extra.carapace, a YAML command-and-flag tree).

Subcommands are discovered through a live-context walk, so lazily-registered commands are included, and the view hides behind a dedicated eager flag, so the plain help screen stays untouched. See Upstream for how this compares to the tree views of neighboring packages.

class click_extra.tree.TreeGlyphs(branch, last, pipe, space)[source]¶

Bases: object

The four drawing strings composing a tree’s left-hand rail.

branch: str¶

Connector of a subcommand with siblings below it.

last: str¶

Connector of the last subcommand of its level.

pipe: str¶

Rail continuation under a branch connector.

space: str¶

Rail continuation under a last connector.

click_extra.tree.BOX_GLYPHS = TreeGlyphs(branch='ā”œā”€ā”€ ', last='└── ', pipe='│   ', space='    ')¶

Unicode box-drawing rail, the same set drawn by tree(1).

The default table format (rounded-outline) already emits box-drawing characters, so the tree matches the rest of Click Extra’s terminal output.

click_extra.tree.ASCII_GLYPHS = TreeGlyphs(branch='|-- ', last='`-- ', pipe='|   ', space='    ')¶

Pure-ASCII rail, the same set drawn by tree(1) under --charset=ascii.

Selected when accessibility mode is active (ACCESSIBLE): box-drawing characters are hostile to screen readers, which either skip them or spell out their Unicode names.

click_extra.tree.COLUMN_GAP = 2¶

Blank cells between the tree rail column and the description column.

click_extra.tree.MIN_DESCRIPTION_WIDTH = 20¶

Floor for the description column’s wrap width.

A deep tree with long labels can push the description column close to (or past) the terminal’s right edge. Below this floor, wrapping would shred sentences into confetti, so the column keeps this width and overflows the terminal instead.

click_extra.tree.render_command_tree(command, prog_name=None, ctx=None, width=None)[source]¶

Render the hierarchy rooted at command as a tree with descriptions.

Reuses ctx when given (like the live invocation context), otherwise builds a throwaway one with resilient_parsing=True. The root line is labeled with prog_name when given, else the context’s command path.

Each node carries the command name, its aliases, its operand metavars (mirroring the usage line) and a column-aligned description from full_short_help(), so deprecated commands carry Click’s own (DEPRECATED) label. Everything is styled with the same theme slots as help screens (invoked_command for the root, subcommand and alias for children, metavar for operands, deprecated for that label), so the tree follows --theme and --color. The rail switches from box-drawing to ASCII when accessibility mode is active on the context (see ACCESSIBLE).

Descriptions wrap at width, resolved like help screens when not given (ctx.make_formatter(), honoring the terminal_width and max_content_width context settings). Wrapped lines keep the tree rail running through the description column. A label wider than the column (typically a long script path as the root, under wrap --tree) keeps its line to itself and hangs its description underneath, at the column.

Note

The tree is a point-in-time snapshot: groups computing their subcommands from external state (plugins, scanned directories) render exactly what click.Group.list_commands() returns at that moment, in listing order. Cloup section groupings are not rendered.

Caution

A non-group command renders as a single root line: valid, just not very interesting. Like a man page, the output stays meaningful for every command type.

Return type:

str

class click_extra.tree.TreeOption(param_decls=None, *, is_flag=True, expose_value=False, is_eager=True, help='Show the tree of nested subcommands and exit.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured --tree flag that prints the hierarchy of nested subcommands and exits.

Eager and value-less, like ManOption. Part of the default option set injected by default_params(), so every @command and @group exposes it. Use @tree_option to add it to a plain Click CLI.

Note

The flag is named --tree, not --show-tree or --commands.

Rendering a hierarchy as a tree is conventionally named tree across ecosystems: eza --tree, lsblk --tree, poetry show --tree, cargo tree, pstree(1) and tree(1) itself (ps --forest being the lone dissenter). --commands would suggest the flat listing --help already provides.

The bare noun also lines up with the neighbouring --help, --man, --params and --version informational flags. It is a flag rather than a registered tree subcommand, which could collide with the user’s own command namespace.

print_tree(ctx, param, value)[source]¶

Render and print the invoked command’s subcommand tree, then exit.

Return type:

None

click_extra.types module¶

Custom click.ParamType subclasses for multi-pick, Enum choices and durations, plus the standalone duration parsers that back Duration.

class click_extra.types.MultiChoice(choices=(), separator=',', case_sensitive=False)[source]¶

Bases: ParamType

Comma-separated multi-pick from a fixed set of values.

The pick-many counterpart to click.Choice. Accepts a single token containing several values joined by a configurable separator (defaults to ,), parses it into a tuple[str, ...] and validates each value against choices when that set is non-empty.

The rendered metavar is [a,b,c] (separator-joined, parallel to Choice’s [a|b|c]): click_extra.highlight._HelpColorsMixin auto-detects the separator and highlights each individual value the same way it does for Choice.

Note

Click ships no single-token equivalent: its idiom is click.Choice with multiple=True, which repeats the flag (--tag a --tag b). pallets/click#2771 asks for a separator-based variant. MultiChoice follows the SQL SELECT a, b, c convention of the tabular use cases Click Extra supports, with click_extra.table_options.ColumnsOption as the headline consumer.

Initialize the type.

Parameters:
  • choices (Sequence[str]) – the accepted values. When non-empty, convert() rejects unknown tokens with fail. When empty, the type behaves as a pure separator-aware parser and leaves validation to the consumer.

  • separator (str) – the token boundary. Use any single character; this also drives the metavar rendering ([a<sep>b<sep>c]).

  • case_sensitive (bool) – when True, a token must match one of choices exactly. By default tokens match case-insensitively, as with EnumChoice and ThemeChoice, and the returned tuple holds the canonical (original-case) values from choices.

name: str = 'multi'¶

the descriptive name of this type

choices: tuple[str, ...]¶
separator: str¶
case_sensitive: bool¶
get_metavar(param, ctx)[source]¶

Render [a<sep>b<sep>c] when choices is set, None otherwise.

None falls back to Click’s default rendering (the uppercased name, like MULTI).

Return type:

str | None

convert(value, param, ctx)[source]¶

Split value on separator and validate each token.

An already-parsed tuple or list keeps its elements verbatim rather than being split again, then goes through the same validation as a raw token: it reaches here from a configuration file as readily as from a default the CLI author declared, and only that check tells a valid selection from a typo. Empty tokens (consecutive separators, trailing separator) are dropped silently.

Return type:

tuple[str, ...]

class click_extra.types.LazyChoice(load, case_sensitive=True)[source]¶

Bases: Choice

A Choice whose values are produced on first use rather than at decoration.

click.Choice freezes its values when the option is declared, which is at import time for a module-level command. Taking a loader instead keeps the module providing the values off the startup path of the CLI: the values are only needed to parse, complete or document the option, never to import it. Every Choice method reads choices, so the help screen, the generated documents and shell completion see the loaded values like any other.

Keep the load callable, which is called on each read of choices.

Parameters:
  • load (Callable[[], Iterable[str]]) – returns the accepted values. Called on each access of choices, so a cheap loader, or a cached one, is expected.

  • case_sensitive (bool) – as for click.Choice.

property choices: tuple[str, ...]¶

The values, read from the loader on each access.

Setter accepts:

Iterable[str]

class click_extra.types.ChoiceSource(*values)[source]¶

Bases: Enum

Source of choices for EnumChoice.

KEY = 'key'¶
NAME = 'name'¶
VALUE = 'value'¶
STR = 'str'¶
class click_extra.types.EnumChoice(choices, case_sensitive=False, choice_source=ChoiceSource.STR, show_aliases=False, transform=None)[source]¶

Bases: Choice

Choice type for Enum.

Allows to select which part of the members to use as choice strings, by setting the choice_source parameter to one of:

  • ChoiceSource.KEY or ChoiceSource.NAME to use the key (the name property),

  • ChoiceSource.VALUE to use the value,

  • ChoiceSource.STR to use the str() string representation, or

  • A custom callable that takes an Enum member and returns a string.

Defaults to ChoiceSource.STR, which only requires you to define the __str__() method on your Enum to produce beautiful choice strings.

The transform parameter takes a callable reshaping the string produced by the source. It composes with every source, and is the only way to spell choices in a CLI-friendly case while show_aliases is on: aliases are reachable through ChoiceSource.KEY, ChoiceSource.NAME and ChoiceSource.VALUE alone, which are stuck on raw Python identifiers.

Same as click.Choice, but takes an Enum as choices.

Also defaults to case-insensitive matching.

Raises:
choices: tuple[str, ...]¶

The strings available as choice.

Hint

Contrary to the parent Choice class, we store choices directly as strings, not the Enum members themselves. That way there is no surprises when displaying them to the user.

This trick bypass Enum-specific code path in the Click library. Because, after all, a terminal environment only deals with strings: arguments, parameters, parsing, help messages, environment variables, etc.

get_choice_string(member)[source]¶

Derive the choice string from the given Enum’s member.

The string produced by the choice source is passed through transform.

Return type:

str

normalize_choice(choice, ctx)[source]¶

Expand the parent’s normalize_choice() to accept Enum members as input.

An Enum member is mapped to its choice string first; any other value is passed to the parent untouched.

Return type:

str

convert(value, param, ctx)[source]¶

Convert the input value to the corresponding Enum member.

The parent’s convert() is going to return the choice string, which we then map back to the corresponding Enum member.

Return type:

Enum

click_extra.types.parse_duration(value, *, now=None)[source]¶

Parse a friendly, ISO 8601 or RFC 3339 duration into a timedelta.

The soft, library-friendly counterpart of the Duration parameter type: it accepts the same three input shapes but returns None instead of raising when value matches none of them, so it suits classifying values read from files or other machine sources. Unlike Duration, it does not collapse a zero duration to None: parse_duration("0") is timedelta(0), letting callers tell a zero duration from an unparsable value. None is returned only for an empty value, a future timestamp, or a value matching no known form.

Parameters:
  • value (Any) – The duration to parse. An existing timedelta (or None) is returned unchanged.

  • now (datetime | None) – Reference instant for an RFC 3339 timestamp’s age; defaults to the current UTC time.

Return type:

timedelta | None

Returns:

The parsed timedelta (possibly zero), or None.

click_extra.types.parse_friendly_duration(value)[source]¶

Parse only a friendly duration (7 days, 12h, a bare number of days).

Returns the parsed timedelta (possibly zero, so "0 days" is timedelta(0)), or None for anything that is not a friendly duration: ISO 8601 forms, calendar units (months, years), and empty or unrecognized values. See parse_duration() for the format-detecting umbrella.

Return type:

timedelta | None

click_extra.types.parse_iso8601_duration(value)[source]¶

Parse only an ISO 8601 duration (P7D, PT12H, P1WT6H).

Returns the parsed timedelta (possibly zero, so "PT0S" is timedelta(0)), or None for anything that is not an ISO 8601 duration: friendly forms, calendar (year or month) components, and empty or unrecognized values. See parse_duration() for the format-detecting umbrella.

Return type:

timedelta | None

class click_extra.types.Duration[source]¶

Bases: ParamType

Parse a duration or an age into a datetime.timedelta.

Accepts three input shapes:

  • Friendly duration: 7 days, 1 week, 12h, 30m, 45s, or a bare number of days like 7. Case-insensitive.

  • ISO 8601 duration: P7D, PT12H, P1WT6H. Case-insensitive.

  • RFC 3339 absolute timestamp: 2024-05-01T00:00:00Z or with an offset like +02:00. Converted at parse time to its age, now - timestamp.

Some inputs parse to None instead of a timedelta: a zero duration, an empty string, and a timestamp in the future. Cutoff options (cooldowns, timeouts, retention windows, cache TTLs) read None as ā€œno cutoffā€, so a 0 on the command line disables the gate and overrides a value set in a configuration file.

To parse outside a Click parameter (classifying a value read from a file, say), reach for the soft parse_duration() family, which returns None instead of raising on an unrecognized value.

Note

Durations resolve to a fixed number of seconds, assuming a day is 24 hours. The local time zone, DST transitions, and calendar boundaries are ignored. Calendar units (months, years) are rejected for the same reason: 28-31 days and 365-366 days make them unsuitable for a precise cutoff. Use days or weeks instead.

name: str = 'duration'¶

the descriptive name of this type

convert(value, param, ctx)[source]¶

Coerce value to a datetime.timedelta (or None).

Delegates to _parse_duration_strict(), turning its ValueError into a Click parameter error via fail(). A parsed zero duration collapses to None, so 0 disables a cutoff option.

Return type:

timedelta | None

click_extra.version module¶

Introspect CLI metadata at runtime and print a colored --version string.

VersionOption gathers the executed CLI’s metadata (module and package names, distribution version, author and license, environment profile, and the live Git state) and renders them through a customizable, colorized message template.

Git fields (git_branch, git_short_hash, …) are resolved at runtime by shelling out to git, with three fallbacks for git-less environments: a pre-baked __<field>__ dunder in the CLI module or its package (injected before build by click_extra.prebake), then a committed .git_archival.json populated by git archive, then the commit an installer records for a distribution installed from a Git URL. The resolvers behind each field live in click_extra.version_facts.

click_extra.version.Facts: TypeAlias¶

Label-to-value rows of a version screen, in the order they are drawn.

click_extra.version.MUTED = Style(fg='bright_black')¶

The recessive style of what a version message says beside its name and version.

The tagline and the fact labels of a VersionScreen take it, and so do the template fields that locate a build rather than identify it: the repository path, the commit date, the build facts and the environment profile.

click_extra.version.is_main_module(module_name)[source]¶

Is module_name a __main__ entry point, of a package or of a script?

An entry point is where the interpreter started: python -m package, a console script, or a compiled binary. It is never plumbing a stack walk lands on after running out of user frames, so it is exempt from CLI_ECOSYSTEM_PACKAGES even when it sits under one of those packages, as click_extra.__main__ does in Click Extra’s own binary.

Return type:

bool

click_extra.version.theme_slot(slot)[source]¶

A style reading its palette slot off the active theme, on every call.

The lookup happens at call time, so the message follows --theme, CLICK_EXTRA_THEME and the background-sniffing auto alike, and drops its color under the monochrome manpage palette. A style captured at import would paint every theme with one palette: the bright white program name of dark is white on white on a light terminal.

get_current_theme() answers with the colorless theme outside an invocation, and with a full palette inside one, so no slot can come back missing.

Return type:

Callable[[str], str]

click_extra.version.unstyled(text)[source]¶

Identity style, for a segment left with no color of its own.

Return type:

str

class click_extra.version.VersionScreen(logo, tagline='', facts=<function default_facts>, gutter='   ')[source]¶

Bases: object

A logo, and the facts to seat beside it, as --version should draw them.

Owns the layout only. The artwork arrives already rendered, as a string or the lines of one, so a CLI is free to draw its mark however it likes, in ASCII line art, half-blocks or anything else, without this class knowing. Hand one to VersionOption through its screen argument, or to a whole CLI through default_params(screen=…).

The mark, pre-rendered, or a callable producing it. A string splits on newlines.

A callable defers the rendering to the first --version that draws the screen, as facts does for its values: a mark painted by code, from an image say, then costs nothing to the invocations that never ask for it.

tagline: str = ''¶

One line under the program name. Omitted, with its blank line, when empty.

facts()¶

Label-to-value rows under the tagline, or a callable producing them.

A callable defers the work to render time, which matters when a value costs something to compute: a CLI counting plugins should not pay for that on every invocation just to have the number ready in case --version is asked for.

Return type:

dict[str, str]

gutter: str = '   '¶

Blank columns between the mark and the facts, and between label and value.

property lines: tuple[str, ...]¶

The mark’s lines, every one padded out to width.

Padding here rather than asking for it is what lets a caller hand over whatever its renderer produced. Trailing blanks are invisible on a line by itself and ragged the moment anything is placed beside it, and a caller cannot repair that afterwards: pad_to() is what measures a styled line right and closes the style it left open.

property width: int¶

Columns the mark occupies, taken from its widest line.

rows(prog_name, version, styles)[source]¶

The column of facts, as (plain, styled) pairs.

Both forms are built together because the styled one cannot be measured: its escape sequences take columns that never reach the screen, and the plain twin is what render() sizes the layout against.

The program name and version take the same styles the plain message gives them, so the two renderings of --version cannot drift apart on color.

Return type:

tuple[tuple[str, str], ...]

render(prog_name, version, styles)[source]¶

Compose the mark and the facts into the screen, or decline to.

The facts are centred against the mark’s height, and either column may be the taller of the two: a line missing from one side simply renders blank.

Returns None when the terminal is too narrow to seat the two columns side by side, leaving the caller to fall back rather than emit a wrapped mess. The threshold is measured off the facts actually built, since their widest row grows with whatever a CLI chose to report. A non-interactive stream reports shutil’s 80-column default, wide enough that a redirected-but-forced-color run still gets the screen it asked for.

Return type:

str | None

click_extra.version.colors_reach_output()[source]¶

Will ANSI codes survive all the way to the user’s terminal?

Resolves Click Extra’s color tri-state, deferring to the output stream’s TTY status on its auto default, exactly as click.echo does when it decides whether to strip the codes itself.

Note

The stream probed is sys.stdout, not Click’s own resolution of it. click.echo reaches stdout through a private cached wrapper, which fixes the output encoding and delegates isatty() to the stream beneath it, so both answer alike. Click deprecates the public accessor of that wrapper, click.get_text_stream().

Return type:

bool

click_extra.version.template_segments(template)[source]¶

Split a version message template into its literal and field segments.

Yields one (literal, field_id, field) triple per field of template, in order: the literal text before the field, the identifier the field resolves on the option (module for {module.__name__}, the part before any index or attribute), and the field as written, braces and format spec included. A doubled brace of a literal comes back single. Literal text left after the last field comes in a final triple carrying no field.

Return type:

Iterator[tuple[str, str | None, str | None]]

class click_extra.version.VersionOption(param_decls=None, *, message=None, fields=None, styles=None, message_style=None, screen=None, is_flag=True, expose_value=False, is_eager=True, help='Show the version and exit.', **kwargs)[source]¶

Bases: ExtraOption

Gathers CLI metadata and prints a colored version string.

Note

This is not a drop-in replacement for the standard @click.version_option() decorator.

It addresses the following Click issues:

  • click#2324, to allow its use with the declarative params= argument.

  • click#2331, by distinguishing the module from the package.

  • click#1756, by allowing path and Python version.

Preconfigured as a --version option flag.

Parameters:
  • message (str | None) – the message template to print, in format string syntax. Defaults to {prog_name}, version {version}.

  • fields (Mapping[str, Any] | None) – mapping of template field name to a forced value, overriding the value auto-computed for that field. Keys must be members of template_fields (for example {"version": "1.2.3"}).

  • styles (Mapping[str, Callable[[str], str] | None] | None) – mapping of template field name to its Style, merged over default_styles. Pass None as a value to clear a field’s default style. Keys must be members of template_fields.

  • message_style (Callable[[str], str] | None) – fallback style for the message literals and for any field that has no style of its own.

  • screen (VersionScreen | None) – a VersionScreen to draw instead of the one-line message, whenever the terminal can take it. Left unset, --version prints the one-line message.

Raises:

TypeError – when a key of fields or styles names no template field.

template_fields: tuple[str, ...] = ('module', 'module_name', 'module_file', 'module_version', 'package_name', 'package_version', 'author', 'license', 'exec_name', 'version', 'git_repo_path', 'git_branch', 'git_long_hash', 'git_short_hash', 'git_date', 'git_tag', 'git_tag_sha', 'git_distance', 'git_dirty', 'build_time', 'build_os', 'build_target', 'build_target_arch', 'prog_name')¶

List of field IDs recognized by the message template.

default_styles: ClassVar[dict[str, Callable[[str], str]]] = {'build_os': Style(fg='bright_black'), 'build_target': Style(fg='bright_black'), 'build_target_arch': Style(fg='bright_black'), 'build_time': Style(fg='bright_black'), 'exec_name': <function theme_slot.<locals>.apply>, 'git_branch': Style(fg='cyan'), 'git_date': Style(fg='bright_black'), 'git_dirty': Style(fg='red'), 'git_distance': <function theme_slot.<locals>.apply>, 'git_long_hash': Style(fg='yellow'), 'git_repo_path': Style(fg='bright_black'), 'git_short_hash': Style(fg='yellow'), 'git_tag': Style(fg='cyan'), 'git_tag_sha': Style(fg='yellow'), 'module_name': <function theme_slot.<locals>.apply>, 'module_version': <function theme_slot.<locals>.apply>, 'package_name': <function theme_slot.<locals>.apply>, 'package_version': <function theme_slot.<locals>.apply>, 'prog_name': <function theme_slot.<locals>.apply>, 'version': <function theme_slot.<locals>.apply>}¶

Default style for each template field.

Fields absent from this mapping render with no style of their own and fall back to message_style (or no color when that is unset). User-provided styles are merged over these defaults.

The name and version fields read their style off the active palette through theme_slot() rather than naming a color, so the message follows --theme. Under the default dark palette, invoked_command is bright white bold and success is green.

message: str = '{prog_name}, version {version}'¶

Default message template used to render the version string.

styles: dict[str, Callable[[str], str] | None]¶
pin_field(field_id, value)[source]¶

Pin a template field to a caller-supplied value.

The value shadows the cached_property that would otherwise resolve the field, and is recorded so reset_resolution() can tell the two apart. Every caller that pins a field goes through here: a bare setattr sets the value without the record, and the next reset then discards it.

Parameters:
  • field_id (str) – Name of the template field to pin.

  • value (Any) – Value the field reports from now on.

Raises:

TypeError – when field_id names no template field.

Return type:

None

reset_resolution()[source]¶

Drop every memoized field, so the next read resolves from scratch.

The resolution chain starts on a stack walk, and the option is built once at decoration time, so the first read in a process fixes the answer for every later one. That is what a CLI wants: one invocation, one process, one walk.

A documentation build breaks the assumption. It renders many commands in one process, and a render that carries no CLI frame (writing roff for a command tree, say) resolves the chain from a stack the walk cannot read. The wrong answer then stands for the rest of the build, and a later --version example publishes it. Clearing the memo hands the next reader its own walk, at the cost of repeating one.

A field the caller pinned through fields= is not a resolution and survives: see _field_overrides.

Return type:

None

static cli_frame()[source]¶

Returns the frame in which the CLI is implemented.

Walks the execution stack from the innermost frame outwards, to find the package in which the user’s CLI is implemented. The walk reads the module and the function name of each frame off the frame itself, with no source lookup: --version is eager, so every CLI pays for this walk at startup.

Returns the frame itself. When every frame belongs to the Click ecosystem and none is an entry point, returns the outermost frame, which has no caller: module then defers to the module of the root command’s callback.

Return type:

FrameType

static command_module(ctx)[source]¶

Returns the module implementing the root command’s callback.

The stack walk in cli_frame() can only find the CLI when the CLI’s own module is on the stack. That holds for a normal invocation, and for a CliRunner driven from the test module that declares the command, but not when a runner invokes a command it merely imported: the walk then finds no user frame at all and stops on the runner’s own invoke(), inside the Click ecosystem.

The Sphinx click:run directive is that shape: without this, a documented --version would render the version of the ecosystem package owning the runner in place of the CLI’s own.

A launcher is the other shape. A console script or a compiled binary whose entry point is a command object, like orchard.cli:cli, leaves no frame of that module on the stack: the walk ends on the launcher itself.

A command’s callback names its defining module directly and needs no stack, so it settles the case the walk cannot see. Returns None when the command has no callback (a bare click.Group) or its module is not imported, leaving the walk’s own answer in place.

Return type:

ModuleType | None

property module: ModuleType[source]¶

Returns the module in which the CLI resides.

property module_name: str[source]¶

Returns the full module name or __main__.

property module_file: str | None[source]¶

Returns the module’s file full path.

None for a module with no file, like the __main__ of python -c.

property module_version: str | None[source]¶

Returns the string found in the local __version__ variable.

Hint

__version__ is a convention from early Python packaging. It is not a standard variable and is not defined in the packaging PEPs.

Prefer the package_version property below, which uses the standard library importlib.metadata API.

Click’s own version_option reads the package metadata only (pallets/click#2598). Click Extra reads __version__ too, for the scripts and codebases that set it.

property package_name: str | None[source]¶

Returns the package name.

property package_version: str | None[source]¶

Returns the package version if installed.

Resolved from the distribution name (see _distribution_name) via importlib.metadata.version(). Returns None if the package is not installed or cannot be resolved.

property author: str | None[source]¶

Returns the package author(s) from its core metadata.

See resolve_author() for the fields read, in order. None if no author can be determined.

property license: str | None[source]¶

Returns the package license from its core metadata.

See resolve_license() for the fields read, in order. None if no license can be determined.

property exec_name: str[source]¶

User-friendly name of the executed CLI.

Returns the module name. But if the module is a __main__ entry point, returns the package name: python -m runs it as __main__, while a console script or a compiled binary imports it as package.__main__.

If not packaged, the CLI is assumed to be a simple standalone script, and the returned name is the script’s file name (including its extension). Code with no file, like a CLI run by python -c, keeps the __main__ module name.

property version: str | None[source]¶

Return the version of the CLI.

Returns the module version if a __version__ variable is set alongside the CLI in its module.

Else returns the package version if the CLI is implemented in a package, using importlib.metadata.version().

For development versions (containing .dev), automatically appends the Git short hash as a PEP 440 local version identifier, producing versions like 1.2.3.dev0+abc1234. This helps identify the exact commit a dev build was produced from. When git_short_hash finds no commit, the plain dev version is returned.

Versions that already contain a + (a pre-baked local version identifier, typically set at build time by CI pipelines) are returned as-is to avoid producing invalid double-suffixed versions like 1.2.3.dev0+abc1234+xyz5678.

property git_repo_path: Path | None[source]¶

Find the Git repository root directory.

Walks up from _search_start to the first directory holding a .git entry: see find_git_root().

property git_branch: str | None[source]¶

Returns the current Git branch name.

Checks for a pre-baked __git_branch__ dunder first, then git rev-parse --abbrev-ref HEAD, then .git_archival.json.

property git_long_hash: str | None[source]¶

Returns the full Git commit hash.

Checks for a pre-baked __git_long_hash__ dunder first, then git rev-parse HEAD, then .git_archival.json, then the commit recorded for an install from a Git URL.

property git_short_hash: str | None[source]¶

Returns the short Git commit hash.

Checks for a pre-baked __git_short_hash__ dunder first, then git rev-parse --short HEAD, then .git_archival.json, then the commit recorded for an install from a Git URL. Both fallbacks derive it from the first 7 characters of the full hash.

Hint

The short hash is usually the first 7 characters of the full hash, but this is not guaranteed to be the case.

But it is at least guaranteed to be unique within the repository, and a minimum of 4 characters.

property git_date: str | None[source]¶

Returns the commit date in ISO format: YYYY-MM-DD HH:MM:SS +ZZZZ.

Checks for a pre-baked __git_date__ dunder first, then git show -s --format=%ci HEAD, then .git_archival.json (whose node-date is strict ISO 8601, like 2021-01-01T12:00:00+00:00).

property git_tag: str | None[source]¶

Returns the Git tag pointing at HEAD, if any.

Checks for a pre-baked __git_tag__ dunder first, then git describe --tags --exact-match HEAD, then .git_archival.json.

Returns None if HEAD is not at a tagged commit.

property git_tag_sha: str | None[source]¶

Returns the commit SHA that the current tag points at.

Checks for a pre-baked __git_tag_sha__ dunder first, then git rev-list -1 on the tag returned by git_tag, then .git_archival.json. Returns None if HEAD is not at a tag.

property git_distance: str | None[source]¶

Number of commits since the most recent tag, or None.

Checks for a pre-baked __git_distance__ dunder first, then parses git describe --tags --long, then falls back to .git_archival.json. None when no tag is reachable or Git is unavailable.

property git_dirty: str | None[source]¶

Work-tree state: "dirty", "clean" or None.

Checks for a pre-baked __git_dirty__ dunder first, then runs git status --porcelain. None when not in a Git repository or Git is unavailable. There is no .git_archival.json fallback: an archive has no work tree, so its state is unknowable.

property build_time: str | None[source]¶

When the distribution was built, as an RFC 3339 UTC timestamp.

Reads the pre-baked __build_time__ dunder, the only source of a build fact: see BUILD_RESOLVERS and resolve_build_time().

property build_os: str | None[source]¶

The operating system the build ran on.

Reads the pre-baked __build_os__ dunder. See resolve_build_os().

property build_target: str | None[source]¶

The platform a distribution built here installs on.

Reads the pre-baked __build_target__ dunder. See resolve_build_target().

property build_target_arch: str | None[source]¶

The CPU architecture the build ran on.

Reads the pre-baked __build_target_arch__ dunder. See resolve_build_target_arch().

property prog_name: str | None¶

Return the name of the CLI, from Click’s point of view.

Get the info_name of the root command.

Note

Unlike its siblings, this field is resolved on every access instead of being cached on the instance: it is the one template field whose value legitimately varies between invocations of the same option instance sharing a process. multicall dispatch relies on that, running one CLI under many names in sequence, and a prog_name passed to main() varies it without any multicall at all. A cached value would pin the first name seen forever.

field_style(field_id=None)[source]¶

Style painting the field_id segment of a rendered message.

A field carrying no style of its own falls back to message_style, and one left unset by the caller too renders bare. Call with no field_id for the style of the template’s literal segments, which is message_style alone.

Return type:

Callable[[str], str]

colored_template(template=None)[source]¶

Insert ANSI styles to a message template.

Accepts a custom template as parameter, otherwise uses the default message defined on the Option instance.

The template is linearized so the ANSI codes apply to its string segments: an ANSI directive cannot be nested within another, unlike a markup tag of HTML.

Return type:

str

render_message(template=None)[source]¶

Render the version string from the provided template.

Accepts a custom template as parameter, otherwise uses the default self.colored_template() produced by the instance.

A CLI carrying a VersionScreen gets that drawn instead, whenever three conditions hold. Failing any one of them falls back to the plain template unchanged, which is a deliberate guarantee rather than a default: that form is the one every machine reader parses.

  • Color reaches the output. A flat-shaded mark carries its shape in its colors, and color is the one lever a caller already has. A redirected --version, or one run under --no-color or NO_COLOR, is asking for something parseable.

  • The terminal is wide enough to seat the facts beside the mark without wrapping them.

  • Accessible mode is off. A mark read out character by character is noise to a screen reader, so --accessible keeps the plain message.

Return type:

str

print_debug_message()[source]¶

Render in debug logs all template fields in color.

Return type:

None

print_and_exit(ctx, param, value)[source]¶

Print the version string and exits.

Also stores all version string elements in the Context’s meta dict.

Return type:

None

click_extra.version.reset_version_resolution(command)[source]¶

Reset every VersionOption in a command tree.

Walks the tree once, cycle-safe, and calls VersionOption.reset_resolution() on each option it finds.

Written for a documentation build, which renders many commands in one process where a CLI renders one. See that method for what a stale resolution costs a published page.

Note

The walk reads the subcommands each group has registered, rather than going through iter_subcommand_contexts() like the renderers do. A lazy subcommand not imported yet holds no resolution to reset, and the context that function builds for each subcommand runs its --version callback, which resolves the very chain this function clears.

Return type:

None

click_extra.version_facts module¶

Resolvers for the facts a --version message reports.

Each function answers one fact on its own, with no option or command around it: the live Git state (GIT_RESOLVERS, run_git()), the build host (BUILD_RESOLVERS), the .git_archival.json and direct_url.json fallbacks, the core metadata of a distribution (resolve_author(), resolve_license()), and the interpreter and platform (default_facts(), env_summary()). VersionOption chains them into its template fields, and click-extra prebake all calls them to bake the values into a build.

click_extra.version_facts.distribution_of(package_name)[source]¶

Resolve an import package name to the installed distribution providing it.

An import (top-level module) name may differ from the distribution name (PIL vs Pillow, jwt vs PyJWT). A name already matching an installed distribution is returned as-is; otherwise it is resolved through importlib.metadata.packages_distributions(). Ambiguous mappings (one import name to several distributions) return None: pass package_name explicitly to disambiguate.

Returns None when nothing installed provides the name, which is what makes it usable as a test of whether a module belongs to a real distribution.

Return type:

str | None

click_extra.version_facts.GIT_FIELDS: dict[str, tuple[str, ...]] = {'git_branch': ('rev-parse', '--abbrev-ref', 'HEAD'), 'git_date': ('show', '-s', '--format=%ci', 'HEAD'), 'git_long_hash': ('rev-parse', 'HEAD'), 'git_short_hash': ('rev-parse', '--short', 'HEAD'), 'git_tag': ('describe', '--tags', '--exact-match', 'HEAD')}¶

Git fields whose live value is the stripped output of one static git subcommand, mapped to that subcommand’s args.

git_tag_sha, git_distance and git_dirty are excluded: their resolution is not a single static git invocation whose stripped output is the value. git_tag_sha dereferences the tag (git rev-list -1 <tag>), git_distance parses git describe and git_dirty maps the porcelain status to a label. See resolve_git_tag_sha(), resolve_git_distance() and resolve_git_dirty().

For the resolver of every pre-bakeable git field (these five plus the three computed ones), keyed uniformly by field ID, see GIT_RESOLVERS.

click_extra.version_facts.GIT_TIMEOUT: float = 5¶

Seconds run_git() lets a git command run before it gives up on it.

A local read answers in milliseconds. The bound is for a repository that blocks, like one on a network share that stopped answering.

click_extra.version_facts.run_git(*args, cwd=None, allow_empty=False, check=False, timeout=5)[source]¶

Run a git command and return its output, without the final newline.

A command that fails returns None: no git on the PATH, a non-zero exit status, like the one of a cwd outside a repository, or a command still running after timeout seconds. Set check to raise instead: an OSError when git does not start, a subprocess.CalledProcessError on a non-zero exit status, and a subprocess.TimeoutExpired when the time runs out.

By default an empty output returns None too, like a failure. Set allow_empty to keep the empty string, which some commands use meaningfully: git status --porcelain prints nothing for a clean work tree, and that is distinct from the command failing.

The output decodes as UTF-8, and a byte that is no UTF-8 becomes a replacement character: Git prints a ref name as the bytes it stores, which a repository can hold in any encoding.

Parameters:

cwd (Path | None) – the folder to run in. The current working directory when None.

Return type:

str | None

click_extra.version_facts.resolve_git_dirty(cwd=None)[source]¶

Report the work-tree state as "dirty", "clean" or None.

Returns "dirty" when git status --porcelain reports uncommitted changes, "clean" when it reports none, and None when the state cannot be determined (not a Git repository, or git is unavailable).

The empty output of a clean work tree is meaningful here, so the command is run with allow_empty to tell it apart from a failure.

Return type:

str | None

click_extra.version_facts.resolve_git_distance(cwd=None)[source]¶

Count commits since the most recent tag, as a string, or None.

Parses git describe --tags --long, whose output has the form <tag>-<distance>-g<short_hash>. Returns None when no tag is reachable, the directory is not a Git repository, or git is unavailable.

Return type:

str | None

click_extra.version_facts.resolve_git_tag_sha(cwd=None)[source]¶

Resolve the commit SHA the tag at HEAD points at, or None.

Runs git describe --tags --exact-match HEAD to find the tag, then git rev-list -1 <tag> to dereference it to a commit SHA. Returns None when HEAD is not at a tagged commit, the directory is not a Git repository, or git is unavailable.

Return type:

str | None

click_extra.version_facts.GIT_RESOLVERS: dict[str, Callable[[Path | None], str | None]] = {'git_branch': <function _direct_git_resolver.<locals>.resolver>, 'git_date': <function _direct_git_resolver.<locals>.resolver>, 'git_dirty': <function resolve_git_dirty>, 'git_distance': <function resolve_git_distance>, 'git_long_hash': <function _direct_git_resolver.<locals>.resolver>, 'git_short_hash': <function _direct_git_resolver.<locals>.resolver>, 'git_tag': <function _direct_git_resolver.<locals>.resolver>, 'git_tag_sha': <function resolve_git_tag_sha>}¶

Canonical live resolver for every pre-bakeable git_* field.

Maps each field ID to a callable that takes an optional working directory and returns the field’s value by shelling out to git (or None when it cannot be resolved). This is the single source of truth for how each git field is computed live, shared by two consumers:

  • VersionOption’s runtime accessors, which wrap each resolver with the pre-baked-dunder and .git_archival.json fallbacks.

  • the click-extra prebake all command, which calls every resolver to bake values into source files at build time.

Keeping it here means adding a new git field is a one-line edit in this module, with no matching change needed in the CLI.

click_extra.version_facts.SOURCE_DATE_EPOCH = 'SOURCE_DATE_EPOCH'¶

Environment variable a reproducible build sets to pin every timestamp it writes.

See the reproducible-builds.org specification.

click_extra.version_facts.build_moment()[source]¶

The instant a build happens, in UTC.

Reads SOURCE_DATE_EPOCH when the build sets it, so two runs of a reproducible build stamp the same instant. Falls back to the current time.

Return type:

datetime

click_extra.version_facts.resolve_build_time()[source]¶

The moment the distribution is built, as an RFC 3339 UTC timestamp.

See build_moment() for where the instant comes from.

Return type:

str

click_extra.version_facts.resolve_build_os()[source]¶

The operating system the build runs on.

Return type:

str

click_extra.version_facts.resolve_build_target()[source]¶

The platform a distribution built here installs on.

This is the wheel platform tag (macosx-15.0-arm64, linux-x86_64, win-amd64), which is Python’s answer to the target triple shadow-rs bakes into a Rust binary. It states an ABI floor the two fields beside it cannot: macosx-15.0-arm64 says the binary needs macOS 15, where resolve_build_os() only says it was built on macOS.

Return type:

str

click_extra.version_facts.resolve_build_target_arch()[source]¶

The CPU architecture the build runs on.

Return type:

str

click_extra.version_facts.BUILD_RESOLVERS: dict[str, Callable[[], str]] = {'build_os': <function resolve_build_os>, 'build_target': <function resolve_build_target>, 'build_target_arch': <function resolve_build_target_arch>, 'build_time': <function resolve_build_time>}¶

Canonical resolver for every pre-bakeable build_* field.

These describe the machine and moment a distribution was built, which GIT_RESOLVERS and env_summary() both leave unanswered: git states what source went in, env_summary() states where the binary is running now, and neither one identifies the host that produced it. That gap is what a cross-built binary turns into a support question, and what shadow-rs answers for Rust with its BUILD_TIME, BUILD_OS and BUILD_TARGET constants.

A build fact has no live fallback, unlike a git one: nothing at runtime can recover the host a binary was compiled on, so click-extra prebake all is the only thing that ever writes these. A field left unbaked stays empty, and its VersionOption accessor answers None.

Adding a field here is a one-line edit, with no matching change in the CLI.

click_extra.version_facts.dunder_name(field_id)[source]¶

The module-level name a pre-baked template field is stored under.

git_branch is baked as __git_branch__: the one spelling VersionOption reads back, and click-extra prebake writes. Keeping the contract in one place is what lets the two sides stay agreed.

Return type:

str

click_extra.version_facts.find_git_root(start)[source]¶

Walk up from start to the first folder holding a .git entry.

The entry is a folder in a plain clone, and a file in a worktree or a submodule. Returns that folder, start included, or None.

Return type:

Path | None

click_extra.version_facts.find_archival_file(start)[source]¶

Walk up from start to find a .git_archival.json file.

Returns the first match in start or any of its parents, or None.

Return type:

Path | None

click_extra.version_facts.read_archival(path)[source]¶

Parse a .git_archival.json file into a string mapping.

Returns an empty mapping when the file is missing, unreadable, or not a valid JSON object.

Return type:

dict[str, str]

click_extra.version_facts.archival_field(data, field_id)[source]¶

Resolve a git_* field from parsed .git_archival.json data.

data follows the setuptools-scm archival schema: node (full hash), node-date, describe-name and ref-names. The same file is read by setuptools-scm and Dunamai, so a single committed .git_archival.json serves all three.

Returns None when the field is absent, empty, or still holds an unsubstituted $Format:…$ placeholder. That last case is what a plain checkout contains: git archive performs the substitution, so values are real only inside an exported archive (including GitHub’s source tarballs).

There is no entry for git_dirty: an archive has no work tree, so its state is unknowable.

Return type:

str | None

click_extra.version_facts.read_direct_url(distribution)[source]¶

Parse the direct_url.json record of an installed distribution.

PEP 610 has installers write this record beside the metadata of a distribution installed from a URL, like uvx --from git+https://... or pip install git+https://....

Returns an empty mapping when the distribution is not installed, carries no record, or holds a record that is not a JSON object.

Return type:

dict[str, Any]

click_extra.version_facts.direct_url_field(data, field_id)[source]¶

Resolve a git_* field from a parsed direct_url.json record.

Only an install from a Git URL records a commit: the full hash of the checkout the installer built, in vcs_info.commit_id. It answers git_long_hash, and its first 7 characters git_short_hash.

Every other field answers None. The vcs_info.requested_revision the record may also hold names a branch, a tag or a commit, with nothing to tell which.

Return type:

str | None

click_extra.version_facts.resolve_distribution(names)[source]¶

Return the first installed distribution among names, or None.

Probes each candidate name in order with importlib.metadata.distribution() and returns the first that resolves to an installed distribution. Used to pick a distribution from a set of plausible spellings (like the program name with - / _ variants) before reading its metadata.

Return type:

str | None

click_extra.version_facts.meta_value(meta, *keys)[source]¶

Return the first non-empty value among core-metadata keys.

Each key is tested with in before [] reads it: [] on a missing key returns None with a DeprecationWarning, and is to raise KeyError.

Return type:

str | None

click_extra.version_facts.resolve_author(meta)[source]¶

Return the author(s) from meta’s core metadata, or None.

Prefers the Author field, then the Maintainer field, then the display name parsed out of the Author-email / Maintainer-email fields (Name <email>). Returns None when meta is None or no author can be determined.

Return type:

str | None

click_extra.version_facts.resolve_license(meta)[source]¶

Return the license from meta’s core metadata, or None.

Prefers the SPDX License-Expression field (core metadata 2.4+). Falls back to the human-readable name of the first License :: trove classifier, then to the free-form License field (which may hold the full license text). Returns None when meta is None or no license can be determined.

Return type:

str | None

click_extra.version_facts.platform_label()[source]¶

Current platform and CPU architecture, as displayed to the user.

Return type:

str

click_extra.version_facts.env_summary()[source]¶

One-line interpreter and platform summary.

Reads Python 3.14.7, macOS ARM64 (AArch64) on an Apple Silicon Mac: the same two facts default_facts() puts on the version screen, joined for a CLI that would rather spend one line of its plain --version on them than draw a screen at all: @version_option(message="{prog_name} {version} (" + env_summary() + ")").

Return type:

str

click_extra.version_facts.dependency_versions()[source]¶

The Click and Cloup releases this install is sitting on.

Worth a row on a screen whose main job is to be pasted into a bug report: Click Extra subclasses both, so which of the three is at fault is the first question any such report raises. Not a default fact, since a CLI built on Click Extra may reasonably consider that its own business rather than its user’s.

Read from the installed distributions: Click deprecates its own __version__ attribute.

Return type:

str

click_extra.version_facts.default_facts()[source]¶

The facts every version screen carries, as an ordered label-to-value map.

A mapping rather than a sequence of pairs so a CLI can adjust one row without restating the rest, dict preserving insertion order and replacement keeping a key where it already sat:

default_facts() | {"Platform": my_own_label}   # replaces, in place
default_facts() | {"Docs": DOCS_URL}           # appends, at the end
Return type:

dict[str, str]