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:
RuntimeErrorAn 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:
ExtraOptionA pre-configured
--accessibleswitch.Turning it on (either via the flag or the
ACCESSIBLEenvironment variable) is equivalent to passing--no-color --no-progress --table-format plain, and additionally streamsecho_via_pager()output without a pager and turnsclear()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-accessiblecounterpart: to opt back out, pass the explicit--color/--table-formatyou 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
--colorand--table-formatoptions, through the contextāsdefault_map. An explicit--color/--table-formaton the command line (or in a configuration file) therefore keeps precedence over--accessible.This option is eager so it lands its defaults before
--colorand--table-formatare 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 theChainMapthatConfigOptionlayers on top ofdefault_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
--accessiblewith theACCESSIBLEenvironment variable, stores the result atACCESSIBLEfor output helpers (clear(),echo_via_pager()) to read, then lowers the--color/--progress/--table-formatdefaults when active. A CLI that never sees--accessible(norACCESSIBLE) keeps every default untouched.ACCESSIBLEis a machine-wide variable, so the command line and the variable of the option outrank it, as they do for every machine-wide variable (seemachine_envvars_apply()). The precedence is:--accessible><CLI>_ACCESSIBLE>ACCESSIBLE> configuration file > built-in default.Important
ACCESSIBLEoutranks a configuration file, where the other machine-wide variables rank below one. The mode works by lowering the defaults of other options, andparse_args()settles it from the command line and the environment before the configuration file loads, so that--helpand--versionrender 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
ACCESSIBLEenvironment variable is read here rather than wired through the optionāsenvvar. Click would otherwise list it alongside the auto-generated<CLI>_ACCESSIBLEvariable in the--paramstable, making the combined string the widest cell of the env-var column and pushing every other rowās padding out. This mirrors howColorOptionreadsNO_COLORand friends.- Return type:
- class click_extra.Argument(param_decls, required=None, help=None, **attrs)[source]¶
Bases:
_ParameterMixin,Argumentclick.Argumentwith the overrides of_ParameterMixin.Inherits from Click directly:
cloup.Argumentisclick.Argumentitself.
- class click_extra.ArgumentKwargs[source]¶
Bases:
_ParamKwargsArguments accepted by
argument().Refer to
click.Argumentfor their meaning and defaults.- 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]¶
- nargs: NotRequired[int | None]¶
- metavar: NotRequired[str | None]¶
- expose_value: NotRequired[bool]¶
- exception click_extra.BadArgumentUsage(message, ctx=None)[source]¶
Bases:
UsageErrorRaised 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:
UsageErrorRaised 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.
- exception click_extra.BadParameter(message, ctx=None, param=None, param_hint=None)[source]¶
Bases:
UsageErrorAn 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 toparamin 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.
- 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:
objectA single CLI test case: how to invoke the command and what to expect.
Each case runs the command-under-test once with
cli_parametersappended, then checks the captured result against the expectation directives below. A case with no expectation only asserts the command ran (plusexit_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:
shlexon POSIX,CommandLineToArgvWon 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_parametersflag, a variable cannot. Values must be strings, so a number or a boolean is quoted ("1", not1): an environment holds strings only, and coercing would have to pick betweenTrueandtrueon the authorās behalf.Applied to that one child process, never to the suite runnerās own environment, so cases stay independent under
--jobs. Seeunset_envto take a variable away instead.
- unset_env: tuple[str, ...] | str¶
Environment variables removed from the inherited environment.
The half
envcannot express. Assigning the empty string leaves a variable set, and a flag read by bare presence (likeACCESSIBLEorDO_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
nullvalue inenvbecause 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_platformsidentifiers such aslinux,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
--timeoutdefault, then to no limit.
- 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 thestdout_*/stderr_*ones: a single subprocess run captures either the merged stream or the separate ones, not both.
- output_regex_matches: tuple[Pattern | str, ...] | str¶
Regexes that must each match somewhere in the combined output (searched,
re.DOTALL). Seeoutput_containsfor 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_containsfor 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_*orstderr_*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
commandcan 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
envandunset_envdirectives are layered over the inherited environment for this child process only.work_directoryis the directory the command runs in, defaulting to the one the runner itself is in.commandis 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:
- 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-
strchoicesare 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().- 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:
- get_missing_message(param, ctx)[source]¶
Message shown when no choice is passed.
Changed in version 8.2.0: Added
ctxargument.- Return type:
- 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.
Added in version 8.2.
- class click_extra.ChoiceSource(*values)[source]¶
Bases:
EnumSource 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:
CliRunnerAugment
click.testing.CliRunnerwith extra features and bug fixes.- force_color: bool = False¶
Default of the
force_colorargument ofinvoke(), for every run.A call passing
color=Falsestill 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 initializingContext.color = True.click.testing.CliRunner.invoke()cannot express it, itscolorparameter colliding with theContextone (pallets/click#2110). Theforce_colorclass attribute sets it for every run.Strips all ANSI codes from results if
colorwas explicitly set toFalse.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 ofstr,pathlib.Pathobjects andNonevalues. The nested structure will be flattened andNonevalues will be filtered out. Then all elements will be cast tostr. Seeargs_cleanup()for details.input (
str|bytes|IO|None) ā same asclick.testing.CliRunner.invoke().env (
Mapping[str,str|None] |None) ā same asclick.testing.CliRunner.invoke().catch_exceptions (
bool|None) ā same asclick.testing.CliRunner.invoke():None(the default) follows the runnerās owncatch_exceptions.color (
bool|None) ā whether the captured streams keep ANSI codes, passed toclick.testing.CliRunner.isolation().Falsealso scrubs the result bytes.force_color (
bool|None) ā keep the ANSI codes and initialize the invoked CLIāsContext.colortoTrue, so it takes its colored branch.None(the default) follows theforce_colorclass attribute.extra (
Any) ā same asclick.testing.CliRunner.invoke(), but colliding parameters are allowed and properly passed on to the invoked CLI.
- Raises:
ValueError ā if
force_color=Trueis passed withcolor=False.- Return type:
- 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 Click9.0removes it.
- exception click_extra.ClickException(message)[source]¶
Bases:
ExceptionAn exception that Click can handle and show to the user.
- class click_extra.Color[source]¶
Bases:
FrozenSpaceColors accepted by
Styleandclick.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:
ExtraOptionA pre-configured
--color[=WHEN]tri-state option.Mirrors the GNU coreutils convention:
WHENis one ofWHEN(auto,alwaysornever), and a bare--color(no value) meansalways. The negative alias--no-coloris carried by the separateNoColorOption, because Click forbids attaching/--no-xsecondary flags to a value option.The resolved tri-state lands on
ctx.color, the Click-standard attribute thatecho()reads through itsresolve_color_default()āshould_strip_ansi()chain:Truekeeps ANSI codes,Falsestrips 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
--coloris deliberately not wired to anenvvar. The color environment variables (NO_COLOR,FORCE_COLOR, ā¦) are read manually throughresolve_color_env(). Letting Click manage them would dump the wholeCOLOR_ENVVARSset into the--paramsenv-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
--colorto the next token whenever it does not look like an option, somycli --color subcommandwould consumesubcommandas 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
--colorreplays 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:
- set_color(ctx, param, value)[source]¶
Resolve
--color=<WHEN>against the environment and pinctx.color.Precedence, highest first:
An explicit
--coloron the command line.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-DEFAULTsource) therefore wins over the environment, matchingAccessibleOption.A color state already pinned by
--no-color, a forced test runner, or an explicitContext(color=...): preserved when this option only resolves toautofrom its default.The
autodefault, leavingctx.coloratNonefor 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. ANO_COLORbuild environment would then strip the output of every later CLI carrying no color option of its own.- Return type:
- 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:
ExtraOptionA
--columnsoption 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 (likeclick_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 aclick.UsageError. Withoutcolumns=, 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
--columnsat all.- columns: tuple[ColumnSpec, ...]¶
Column registry this option advertises and validates against (may be empty).
- 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,CommandLike
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, likehttps://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. Seeinvoke().version_fields (
dict[str,Any] |None) ā dictionary ofVersionOptiontemplate field overrides forwarded to the version option. Accepts any field fromVersionOption.template_fields(likeprog_name,version,git_branch). Lets you customize--versionoutput from the command decorator without replacing the defaultparamslist.config_strict (
bool) ā forwarded to the defaultConfigOptionāsstrictsetting: configuration keys not matching any CLI parameter raise an error instead of being silently ignored. Like the otherconfig_*and*_paramsforwards, it spares you from replacing the whole defaultparamslist to customize the config option.config_cascade (
bool) ā forwarded to the defaultConfigOptionāscascadesetting: 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 defaultConfigOptionāsexcluded_paramsblocklist. Additive, unlike the option-levelexcluded_paramswhich replaces the default blocklist entirely. Items are fully-qualified parameter IDs (likemycli.mail_sources). Mutually exclusive withincluded_params.extra_keywords (
HelpKeywords|None) ā aHelpKeywordsinstance whose entries are merged into the auto-collected keyword set. Use this to inject additional strings for help screen highlighting.excluded_keywords (
HelpKeywords|None) ā aHelpKeywordsinstance 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 anExamples:section of the help screen, in the man page, and in every āhelp-format rendering. A malformed pair raisesTypeErrorhere, at command construction, rather than on the first--helpa user runs.extra_option_at_end (
bool) ā reorders all parameters attached to the command, by moving all instances ofExtraOptionat 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 toDEFAULT_PRIORITY, lowest shown first. Keys are matched against each parameterās long and short flags first, then its destination name, so the--config/--no-configpair (which shares theconfigdestination) 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 ofclickwhich 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:
auto_envvar_prefix = self.name(Click feature)Auto-generate environment variables for all options, using the command ID as prefix. The prefix is normalized to be uppercased and all non-alphanumerics replaced by underscores.
help_option_names = ("--help", "-h")(Click feature)Allow help screen to be invoked with either āhelp or -h options.
show_default = True(Click feature)Show all default values in help screen.
Additionally, these Cloup context settings are set:
align_option_groups = True(Cloup feature)Aligns option groups in help screen.
Every command carries the sections of
DEFAULT_OPTION_GROUPS, so leaving each to compute its own column width would step the help text left and right from one section to the next. Aligned, a commandās own options keep the column click-extraās widest option sets, which is what thedefault_options_*_helpfixtures ofclick_extra.pytestmatch against.show_constraints = True(Cloup feature)show_subcommand_aliases = True(Cloup feature)
Click Extra also adds its own
context_settings:show_choices = None(Click Extra feature)If set to
TrueorFalse, 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 whosepromptproperty is set.Defaults to
None, which will leave all options untouched, and let them decide of their ownshow_choicessetting.show_envvar = None(Click Extra feature)If set to
TrueorFalse, 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 ownshow_envvarsetting. The rationale being that discoverability of environment variables is enabled by the--paramsoption, 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_settingsparameter:@command( context_settings={ "show_default": False, ... } )
- report_url: str | None = None¶
URL of the issue form that a bug report links to, or
Noneto report none.Set from the
report_urlconstructor argument. Declared here so the attribute exists on every command, asinvoke()reads it off the root command.
- examples: tuple[tuple[str, str], ...] = ()¶
(description, command)pairs showing the command in use.Normalized from the
examplesconstructor argument bynormalize_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 everyHelpFormatbackend) then need no guard.
- param_priority(param)[source]¶
Priority of param in the help screen.
Defaults to
DEFAULT_PRIORITY, and is otherwise resolved againstoption_prioritiesby trying each of the parameterās flags in turn, then its destination name.Important
This orders the help screen alone. The order of
self.paramsdecides when each callback fires:click.core.iter_params_for_processingsorts 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--timeahead of everything it measures and--accessibleahead of the--colordefault 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:
- 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
ExtraOptionGroupgoes past the ungrouped section, ordered by itspriority.Important
This is the one place the section order is decided. The help screen (
format_params()), the man page and every otherHelpFormatbackend (_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--helpand 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 thehelpattribute as is. Resolution goes throughresolve_param_help()instead, the same helper the man page and every otherHelpFormatbackend reads, so an operand carries one description whatever renders it. An argument without help gets an empty string, notNone.
- format_params(ctx, formatter)[source]¶
Draw the parameter sections of the help screen.
Reimplements
cloup.OptionGroupMixin.format_paramsto honor the ordersplit_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 plainOptionsheading.- Return type:
- 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
--helpor--version).Sets the default CLIās
prog_nameto 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 calledpython -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
rootlogger, the levels the verbosity options set, and the color the color options publish. Seeclick_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:
- invoke(ctx)[source]¶
Like parentās
invoke, but prints theAborted!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: seereport_unexpected_error(). The innermost command catches it, as its context still holds the options of the run. Clickāsmain()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 thatclick-extra wrapruns.- Return type:
- make_context(info_name, args, parent=None, **extra)[source]¶
Like parentās
make_context, but seedsctx.metawith the raw arguments.A copy of the raw, pre-parsed arguments goes under
RAW_ARGS, whichprint_params()re-parses to draw the--paramstable. A root context also records the name the CLI was invoked under, asINVOCATION_NAME.See also
See
click_extra.context.RAW_ARGSfor the full rationale and the upstream-proposal notes (related: click#1279).- Return type:
- format_examples(ctx, formatter)[source]¶
Write an
Examples:section listing the commandāsexamples.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\bno-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:
- 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:
- parse_args(ctx, args)[source]¶
Like parentās
parse_argsbut with better error messages for single-dash multi-character tokens.Also settles the presentation options before delegating, so
--color,--no-color,--accessibleand--themereach the eager help and version screens regardless of their position on the command line. See_resolve_presentation_eagerly.
- class click_extra.CommandCollection(name=None, sources=None, **kwargs)[source]¶
Bases:
GroupA
Groupthat 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:
Changed in version 8.2: This is a subclass of
Group. Commands are looked up first on this group, then each of its sources.
- 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:
objectA whole man page in structured form, ready to render to roff.
One
CommandDocmaps to one command (or subcommand). Its fields are the man-pages(7) sections, in the order Man-page documents them. Build it withextract_command_doc()and serialize withto_roff().- synopsis_pieces: tuple[str, ...] = ()¶
Usage metavars after the command name (
[OPTIONS],CITY, ā¦).
- 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.
- 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
examplesattribute (seeclick_extra.commands.Command.examples). Empty for a command that declares none, in which case every backend omits the section entirely.
- to_markdown()[source]¶
Render the whole document as Markdown.
Same sections as
to_roff(), in the same order, minus the roff.THheader, 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:
- 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.
- 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,ParamStructureA pre-configured option adding
--config LOCATION.Caution
The first
ConfigOptiona process builds replacesclick.Group.parse_argsfor 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 itsno_args_is_helpscreen 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 noConfigOption.Takes as input a path to a file or folder, a glob pattern, or an URL.
is_eageris active by default so thecallbackgets the opportunity to set thedefault_mapof the CLI before any other parameter is processed.defaultis set to the value returned byself.default_pattern(), which is a pattern combining the default configuration folder for the CLI (as returned byclick.get_app_dir()) and all supported file formats.Attention
Default search pattern must follow the syntax of wcmatch.glob.
excluded_paramsare 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 ofDEFAULT_EXCLUDED_PARAMS, plus the CLIās--helpoption, resolved at runtime.included_paramsis the inverse ofexcluded_params: only the listed parameters will be loaded from the configuration file. Cannot be used together withexcluded_params.
- file_format_patterns: dict[ConfigFormat, tuple[str, ...]]¶
Mapping of
ConfigFormatto 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.
Truewhen nofile_format_patternswas 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 whenshow_file_patternsis left atNone.
- 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:
Noneprints them when the developer chose the format set, and hides them when it was inherited from the install.Truealways prints them, which is how a CLI advertises the formats its own dependencies enable.Falsealways hides them.
See
collapse_default()for what each state renders.
- force_posix¶
Configuration for default folder search.
roamingandforce_posixare 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 (seeVCS_DIRS) (default).A
Pathorstr: 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 whensearch_parents=True, plus thepyproject.tomlCWD search when enabled) are loaded and layered into the contextāsdefault_map. The most local file wins each key, in the sections of subcommands too: apyproject.tomlfound 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
--configvalue 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_paramsdefault.Populated by
Commandāsexcluded_paramsforwarding, 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 explicitexcluded_paramswas 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 (likesub_section_key).Any callable
dict ā T: called directly with the raw dict. Works with PydanticāsModel.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 viaget_tool_config.
- schema_strict¶
Strictness for schema validation (separate from
strict).If
True, raiseValueErrorwhen the config section contains keys that do not match any dataclass field (after normalization and flattening). Only applies whenconfig_schemais a dataclass.If
False, ignore unrecognized keys. When the section is schema-only (included_params=()), a warning still names them: seewarn_unknowninmake_schema_callable().
Note
This is distinct from
strict, which controls whether config keys not matching CLI parameters are rejected.schema_strictvalidates 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_paramsmeans 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 tomake_schema_callable()and the validation pipeline aswarn_unknown.
- config_validators: tuple[ConfigValidator, ...]¶
Extension validators for sub-trees of the configuration file.
Each
ConfigValidatortargets a dottedextension_pathrelative 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, seeclick_extra.theme.validate_themes_config()); user-supplied validators are appended after them. App code that registers its own validator on the sameextension_pathruns 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.
Commandaccepts the settings of its default--configoption 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_paramsis additive, where the optionās own argument replaces the default blocklist: the forwarded IDs join it, throughextra_excluded_paramswhile the blocklist is still the dynamic default, and straight into the frozen value otherwise. Theconfig_validatorsjoin click-extraās built-in ones the same way, as they do when passed to the option itself.- Raises:
ValueError ā when
excluded_paramsis forwarded to an option carrying its ownincluded_params, the two filters being mutually exclusive.- Return type:
- 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.Noneat construction picksNEGATE | SPLIT.Important
The
SPLITflag 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.
Noneat construction picks GLOBSTAR | FOLLOW | DOTGLOB | BRACE | SPLIT | GLOBTILDE | NODIR.Important
The
BRACEflag is always forced, so that multi-format default patterns using{pat1,pat2,...}syntax expand correctly.The
NODIRflag 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 forwcmatchbrace 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 theroamingandforce_posixproperties.Multiple file format patterns are wrapped with
{ā¦}brace-expansion syntax so thatwcmatch.globcorrectly 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
defaultinstead. That keeps the layout a choice of the CLI rather than a dependency of this package: see the documentation.- Return type:
- 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
GLOBTILDEflag is set insearch_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 (theFILESsection of a man page) calls this method instead. A URL is returned as given.- Return type:
- 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
--helpfor, on one line, and keeps the answer the same on every install:[default: ~/.config/hello/]
A developer who passed
file_format_patternschose 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_patternsoverrides that reading in either direction, andTrueis 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:
- parse_conf(content, formats, location=None)[source]¶
Parse the
contentwith the givenformats.Tries to parse the given raw
contentstring with each of the givenformats, in order. Yields the resulting data structure for each successful parse.locationis the path thecontentwas read from. It is only needed by formats that cannot be parsed from a text payload, likeSQLITE, which is read straight from its file, and the binary variant ofPLIST, which only exists on disk. Such formats are skipped whenlocationis missing or is not a local file.Attention
Formats whose parsing raises an exception or does not return a
dictare considered a failure and are skipped. A format parsing the content toNone, as YAML does for a document of comments only, yields an emptydictinstead.This follows the parse, donāt validate principle.
- 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
FileNotFoundErrorif no file at all matched the pattern.
- 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
patternnames,is not empty,
match file format patterns,
can be parsed successfully, and
produce a non-empty data structure.
Raises
FileNotFoundErrorif no configuration file was found matching the criteria above.Returns
(None, None)if files were found but none could be parsed.
- load_ini_config(content)[source]¶
Utility method to parse INI configuration file.
Internal convention is to use a dot (
., as set byPARAM_PATH_SEP) in section IDs as a separator between levels. This is a workaround the limitation ofINIformat 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 ofsubcommand.Returns a ready-to-use data structure.
- 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 andyt-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, likeload_ini_config()does. A boolean flag needs no value: its primary declaration sets it toTrue, its secondary one (--no-*) toFalse. An option flaggedmultipleaccumulates 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:
- load_sqlite_config(path)[source]¶
Utility method to parse a SQLite configuration database.
The database holds a single
SQLITE_CONFIG_TABLEtable ofkey/valuerows. Keys are parameter paths, with a dot (., as set byPARAM_PATH_SEP) separating each level, likemy-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
sqlite3is imported here and not at the top of the module, like the optional parsers ofparse_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.enabledreports whether they are there, and the format is disabled if they are not.
- load_plist_config(path)[source]¶
Utility method to parse a
plistconfiguration 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 throughparse_content(), which is how aplistfetched overhttp://orhttps://is loaded.Returns a ready-to-use data structure.
- load_xml_config(content)[source]¶
Utility method to parse an
XMLconfiguration 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 throughcanonical_param_name(), so the kebab-case spelling counts too.Returns a ready-to-use data structure.
- 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
ConfigValidatorinstances 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 tripstrict=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:
- 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_mapkeeps 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]andctx.meta[click_extra.context.CONF_FULL]respectively. This is the recommended way to identify which configuration file was loaded.There is no
ParameterSource.CONFIG_FILEenum member:ParameterSourceis a closed enum in Click, and monkeypatching it would be fragile. Config values end up indefault_map, so Click reports them asParameterSource.DEFAULT_MAP, which is accurate.- Return type:
- 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 thesuper()call below, so the parsed document is already inctx.metawheninject_reserved_subcommands()reads it.Returning a rewritten
argsis what makes_default_subcommandsand_prepend_subcommandswork on any group class: Click threads the residual arguments through each parameter in turn, then hands the final list toGroup.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_helpscreen before it runs any parameter. A subgroup reached through this option holds no option of its own. Theclick.Group.parse_argsthis class installs covers both.Before loading, it reads the verbosity the command line asks for (see
requested_level()), soload_conf()can keep its status lines quiet under-qor a--verbosityaboveWARNING.
- class click_extra.ConstraintMixin(*args, constraints=(), show_constraints=None, **kwargs)[source]¶
Bases:
objectProvides 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 MROkwargs (
Any) ā keyword arguments forwarded to the next class in the MRO
- optgroup_constraints¶
Constraints applied to
OptionGroupinstances.
- param_constraints: tuple[BoundConstraint, ...]¶
Constraints registered using
@constraint(or equivalent method).
- all_constraints¶
All constraints applied to parameter/option groups of this command.
- class click_extra.Context(*args, meta=None, sort_subcommands=None, **kwargs)[source]¶
Bases:
ContextLike
cloup.Context, but with the ability to populate the contextāsmetaproperty at instantiation.Also pre-seeds
colorfor root contexts (those without a parent) from the color environment variables, so the eager help and version screens honorFORCE_COLOR,NO_COLORand their siblings (seeresolve_color_env()). With none of them set,colorstays at ClickāsNonedefault, which auto-detects a TTY. Child contexts inherit the color of their parent, as Click does.When the
POSIXLY_CORRECTenvironment variable is set, this context forcesallow_interspersed_argstoFalseso option parsing stops at the first positional argument, as GNU getopt-based tools do. SeePOSIXLY_CORRECT_ENVVAR.Carries the
sort_subcommandssetting read byclick_extra.commands.Group.must_sort_subcommands(), so a whole command tree can settle its subcommand listings in one place.Todo
Propose addition of
metakeyword upstream to Click.Like parentās context but with an extra
metakeyword-argument.Also pre-seed
colorfrom the color environment variables for a parentless context when the user did not provide it, and forceallow_interspersed_argstoFalsewhenPOSIXLY_CORRECTis set in the environment.- Parameters:
sort_subcommands (
bool|None) ā whether groups list their subcommands alphabetically. Inherited from the parent context when left toNone, the way Cloup inheritsalign_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(), withtable_formatandsort_keydefaulting to the values resolved by the--table-formatand--sort-byoptions (read fromTABLE_FORMATandTABLE_SORT_KEY).ctx.metais 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:
- 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 oftable_formatandsort_keyfrom the contextās sharedmeta, delegating toclick_extra.table.print_table()(which also handles ANSI translation and colorization policy).- Return type:
- class click_extra.DateTime(formats=None)[source]¶
-
The DateTime type converts date strings into
datetimeobjects.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'.
- 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:
- 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
paramandctxarguments may beNonein certain situations, such as when converting prompt input.If the value cannot be converted, call
fail()with a descriptive message.
- class click_extra.DebugOption(param_decls=None, *, default_logger='root', is_flag=True, default=False, help='Shorthand for --verbosity DEBUG.', **kwargs)[source]¶
Bases:
_VerbosityOption--debugflag, 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:
-qwalks down it, repeatably.Note
It outranks
--verbosity,-vand-qalike 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.Loggerobject is used as it is.The name of the
rootlogger, 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
rootlogger, which the whole process shares. Whichever logger is selected, therootone gets Click Extraās handler for the time of each run of the command: seeadd_to_parser().
- class click_extra.Duration[source]¶
Bases:
ParamTypeParse 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 like7. Case-insensitive.ISO 8601 duration:
P7D,PT12H,P1WT6H. Case-insensitive.RFC 3339 absolute timestamp:
2024-05-01T00:00:00Zor with an offset like+02:00. Converted at parse time to its age,now - timestamp.
Some inputs parse to
Noneinstead of atimedelta: a zero duration, an empty string, and a timestamp in the future. Cutoff options (cooldowns, timeouts, retention windows, cache TTLs) readNoneas āno cutoffā, so a0on 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 returnsNoneinstead 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
daysorweeksinstead.
- class click_extra.EnumChoice(choices, case_sensitive=False, choice_source=ChoiceSource.STR, show_aliases=False, transform=None)[source]¶
Bases:
ChoiceChoice type for
Enum.Allows to select which part of the members to use as choice strings, by setting the
choice_sourceparameter to one of:ChoiceSource.KEYorChoiceSource.NAMEto use the key (thenameproperty),ChoiceSource.VALUEto use thevalue,ChoiceSource.STRto use thestr()string representation, orA custom callable that takes an
Enummember and returns a string.
Defaults to
ChoiceSource.STR, which only requires you to define the__str__()method on yourEnumto produce beautiful choice strings.The
transformparameter 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 whileshow_aliasesis on: aliases are reachable throughChoiceSource.KEY,ChoiceSource.NAMEandChoiceSource.VALUEalone, which are stuck on raw Python identifiers.Same as
click.Choice, but takes anEnumaschoices.Also defaults to case-insensitive matching.
- Raises:
TypeError ā if
choicesis not anEnumsubclass.ValueError ā if
choice_sourceis a string naming noChoiceSourcemember.
- choices: tuple[str, ...]¶
The strings available as choice.
Hint
Contrary to the parent
Choiceclass, we store choices directly as strings, not theEnummembers 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āsmember.The string produced by the choice source is passed through
transform.- Return type:
- 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:
ExtraOptionA 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 tomlemits a configuration whoseverbosityis already set toDEBUG.Like
ValidateConfigOption, it relies on a siblingConfigOptionto provide the parameter structure and theexcluded_params/included_paramsfilter, 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,ARGFILEandPYPROJECT_TOMLhave 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 replayingRAW_ARGS(falling back to defaults when the command did not capture them), drops the parametersis_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
Noneleaves so the export names every key a configuration file can set: serializers render them asnull, except TOML which comments them out (see_serialize_toml_with_unset). Loadingnullback is harmless:_install_default_map()cleans blank values out of the merged result.
- class click_extra.ExtraOption(*args, group=None, **attrs)[source]¶
Bases:
OptionBase class of the options Click Extra implements itself.
Identifies Click Extraās own options with certainty.
Note
The one Click Extra class carrying the
Extraprefix: every other one takes the name of the Click or Cloup class it shadows. The plainOptionname belongs to the user-facing wrapper this class subclasses, and the prefix marks Click Extraās own built-in options apart from it.Commandreads that mark: it sorts parameters withisinstance(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 inHelpFormatter._style_bracket_fields(), which uses the structured data fromOption.get_help_extra()to identify each field by its label.Note
Built-in option subclasses share a common shape: their
__init__defaultsparam_declsto the optionās canonical flags and wires an eager callback viakwargs.setdefault("callback", self.<callback>). Every callback name encodes its role with a verb prefix. The common roles are:set_<key>publishes a resolved value toctx.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 actxhelper 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.
ConfigOptionwiresload_confto read, parse, and merge a configuration file, andNoConfigOptionwirescheck_sibling_config_optionto assert that a sibling--configoption exists.- add_to_parser(parser, ctx)[source]¶
Register the option, then give the
rootlogger 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 ofJobsOption. 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). Seeclick_extra.logging._hold_invocation_handlerfor the other rules, and for how the handler leaves.- Return type:
- class click_extra.ExtraOptionGroup(*args, priority=100.0, **kwargs)[source]¶
Bases:
OptionGroupAn 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, whichCommandreads the same way to push click-extraās own options to the end ofparams.- Parameters:
priority (
float) ā rank of the group among the other trailing groups, lowest first. Defaults toDEFAULT_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
OptionGroupsacts 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
hiddenparameter.
- class click_extra.File(mode='r', encoding=None, errors='strict', lazy=None, atomic=False)[source]¶
-
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
lazyflag 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,lazyotherwise. 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
atomicparameter.- 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.
Nonemeans any whitespace. For all parameters the general rule is that whitespace splits them up. The exception are paths and files which are split byos.path.pathsepby 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:
FileInfoDict
- 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
paramandctxarguments may beNonein certain situations, such as when converting prompt input.If the value cannot be converted, call
fail()with a descriptive message.
- exception click_extra.FileError(filename, hint=None)[source]¶
Bases:
ClickExceptionRaised if a file cannot be opened.
- class click_extra.FloatRange(min=None, max=None, min_open=False, max_open=False, clamp=False)[source]¶
Bases:
_NumberRangeBase[float,float],FloatParamTypeRestrict a
click.FLOATvalue to a range of accepted values. See Int and Float Ranges.If
minormaxare not passed, any value is accepted in that direction. Ifmin_openormax_openare enabled, the corresponding boundary is not included in the range.If
clampis enabled, a value outside the range is clamped to the boundary instead of failing. This is not supported if either boundary is markedopen.Changed in version 8.0: Added the
min_openandmax_openparameters.
- class click_extra.Formatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)[source]¶
Bases:
FormatterClick 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 orstring.Templateformatting in your format string.Changed in version 3.2: Added the
styleparameter.- 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 viaclick_extra.theme.get_current_theme().A record carrying a
labelattribute (each linerun_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 renderrecord.labelits 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
levelnameandmessageare 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:
- class click_extra.Group(*args, help_command=True, sort_subcommands=None, subcommand_priorities=None, **kwargs)[source]¶
Bases:
Command,GroupLike
cloup.Group, with sane defaults and extra help screen colorization.Like
Command.__init__, but auto-injects ahelpsubcommand.- Parameters:
help_command (
bool) ā whenTrue(the default), ahelpsubcommand is automatically registered. Set toFalseto suppress it, or register your ownhelpsubcommand to override it.sort_subcommands (
bool|None) ā how subcommands sharing a priority are broken apart.Truelists them alphabetically,Falsein the order they were registered.None(the default) defers to thesort_subcommandscontext setting, then toTrue. Seemust_sort_subcommands().subcommand_priorities (
Mapping[str,float] |None) ā maps a subcommand name to its priority relative toDEFAULT_PRIORITY, lowest listed first. Names left out keep the default priority, so numbering a few subcommands moves only those.
- 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 toTrue. This is the resolution order Cloup uses foralign_sections, and it is what lets a singlecontext_settings={"sort_subcommands": False}on the root group reach every subgroup below it instead of being repeated on each.- Return type:
- subcommand_priority(name)[source]¶
Priority of the name subcommand.
Defaults to
DEFAULT_PRIORITY.- Return type:
- listed_command(ctx, name)[source]¶
The command the help screen describes under name: the subcommand.
The extension point
LazyGroupoverrides 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.
- list_commands(ctx)[source]¶
Subcommand names in presentation order.
Sorted on
subcommand_prioritiesfirst, then broken apart bymust_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__appendshelpbefore any@cli.command()decorator runs, while acommands=[ā¦]constructor argument lands it after, so its natural position says nothing about the authorās intent. Mirrors whatextra_option_at_enddoes to options.
- 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 overridinglist_commands()alone leaves the help screen alphabetical: the screen is rendered from sections and never calls it. Rebuild that section fromlist_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 aSectioninstance should not have it rewritten underneath them. Priorities andsort_subcommandstherefore address the default section and the flat listings (--tree, man pages, completion specs), not the contents of an explicit section.
- 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:
_InjectedCommandSynthetic subcommand that displays help for the parent group or a subcommand.
Auto-injected into every
Group. Supports nested resolution:mycli help subgroup subcmdshows the help forsubcmdwithinsubgroup.
- class click_extra.HelpFormat(*values)[source]¶
Bases:
StrEnumThe formats
render_help()renders.The value is the spelling
--help-formattakes. Members are ordered alphabetically, which is also the order--help-formatadvertises them in. Adding a format is a member here, a description inHELP_FORMATSand a branch inrender_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:
ExtraOptionA pre-configured
--help-formatoption printing the command in one of theHelpFormatformats and exiting.Eager and value-taking, unlike its
--manneighbour. That bare flag typesets the same page and sends it to the pager, where--help-format manprints its roff source. It stays a flag of its own because a runtime manual flag has its own tradition (seeManOption).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-markdownand--help-carapaceflags would widen the label column of every screen, forever, one line per format anyone ever adds. Here a new format costs aHelpFormatmember and nothing on screen.Note
The rendered output is deliberately colorless whatever
--colorsays. 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.--helpremains the colorized human view.
- class click_extra.HelpFormatter(*args, **kwargs)[source]¶
Bases:
HelpFormatterExtends 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 ofThemeOption, or the process-wide default when no context is active. A plaincloup.HelpThemelends the slots it declares to that active theme, which keeps the slots cloup lacks.- keywords: HelpKeywords¶
Keywords to highlight, collected from the rendered commandās context.
Instance state, initialized per formatter:
_HelpColorsMixin.format_helpfills it before rendering, andhighlight_extra_keywords()mutates it (see theexcluded_keywordssubtraction), 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:
- 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 theinvoked_commandslot. A subcommandās path ends on a name the parent screen lists undersubcommand, and the same word in two colors across two screens reads as two different things.- Return type:
- 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:
objectStructured collection of keywords extracted from a Click context for help screen highlighting.
Each field corresponds to a semantic category with its own styling.
- deprecated: set[str]¶
Markers a CLI paints with the
deprecatedslot beside Clickās own.DEPRECATED_REcovers 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.
- class click_extra.HelpSection(heading, definitions, help=None, constraint=None)[source]¶
Bases:
objectA container for a help section data.
- 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:
HelpThemeExtends
cloup.HelpThemewith 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_THEMESprovide the visual styling by setting the relevant slots; user-defined themes can be authored as plain mappings and loaded viafrom_dict().- critical()¶
Style applied to the
CRITICALlevel name in log records.Example:
CRITICAL: Database connection lost.- Return type:
T
- error()¶
Style applied to the
ERRORlevel name in log records.Example:
ERROR: Configuration file not found.- Return type:
T
- warning()¶
Style applied to the
WARNINGlevel 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
INFOlevel name in log records.Usually left at
identity:INFOis the default verbosity and shouldnāt stand out from regular output.- Return type:
T
- debug()¶
Style applied to the
DEBUGlevel 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 (whencross_ref_highlightis 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.Choicemetavar (likejson,csv,xmlwithin[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 atidentity. A theme that only setsbrackettherefore 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 tobracketwhen left atidentity, so a theme that only stylesbracketstill gets a consistent rendering inside bracket fields.- Return type:
T
- default()¶
Style applied to the default-value content inside
[default: ...]bracket fields. Falls back tobracketwhen left atidentity.- Return type:
T
- range_label()¶
Style applied to range expressions (
0<=x<=9,x>=1024,0<=x<100) that appear inside bracket fields forIntRangeandFloatRangeoptions. Falls back tobracketwhen left atidentity.- Return type:
T
- required()¶
Style applied to the
requiredlabel inside bracket fields on mandatory options. Falls back tobracketwhen left atidentity.- 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
āinOK_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):subheadingis 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.
Noneis a value like any other, not a slot left alone.
- 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 forBUILTIN_THEMESinstead.- Return type:
- classmethod light()[source]¶
A theme assuming a light terminal background color.
Carries cloupās palette, like
dark().- Return type:
- to_dict()[source]¶
Serialize the theme to a plain dict suitable for TOML/JSON/YAML.
Each
Styleslot is emitted viaStyle.to_dict. Slots left at their default (identityorNone) are omitted, so the output only carries what the theme actually overrides. Pair withfrom_dict()to round-trip.
- 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
StyleviaStyle.from_dict, whilecross_ref_highlightis read as a plainbool. Unknown keys raiseTypeErrorso typos surface immediately.- Return type:
- cascade(base)[source]¶
Layer this themeās set slots on top of base.
Mirrors
Style.cascadeat 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.
- class click_extra.IntRange(min=None, max=None, min_open=False, max_open=False, clamp=False)[source]¶
Bases:
_NumberRangeBase[int,int],IntParamTypeRestrict an
click.INTvalue to a range of accepted values. See Int and Float Ranges.If
minormaxare not passed, any value is accepted in that direction. Ifmin_openormax_openare enabled, the corresponding boundary is not included in the range.If
clampis enabled, a value outside the range is clamped to the boundary instead of failing.Changed in version 8.0: Added the
min_openandmax_openparameters.
- 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:
ExtraOptionA pre-configured
--jobsoption 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) andmax(every available logical CPU core). A value of0disables 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/maxresolve to a single job andJobCountlogs 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
intinctx.meta[click_extra.context.JOBS].Warning
JobsOptiononly resolves and publishes the job count: it does not drive any concurrency by itself. Pass it torun_jobs()(which reads the resolvedctx.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.
JobCounthas already resolved anyauto/maxkeyword to an integer by the time this runs. A value of0disables parallelism: it is rounded up to1(sequential execution) with a warning. Negative values are likewise clamped to1. A count above the available cores is honored: the pool is aThreadPoolExecutor, 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:
- class click_extra.LazyChoice(load, case_sensitive=True)[source]¶
Bases:
ChoiceA
Choicewhose values are produced on first use rather than at decoration.click.Choicefreezes 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. EveryChoicemethod readschoices, so the help screen, the generated documents and shell completion see the loaded values like any other.Keep the
loadcallable, which is called on each read ofchoices.- Parameters:
load (
Callable[[],Iterable[str]]) ā returns the accepted values. Called on each access ofchoices, so a cheap loader, or a cached one, is expected.case_sensitive (
bool) ā as forclick.Choice.
- class click_extra.LazyGroup(*args, lazy_subcommands=None, **kwargs)[source]¶
Bases:
GroupA
Groupthat 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_optionin click_extra#1332 issue.lazy_subcommandsmaps command names to their import paths.Tip
lazy_subcommandsis a map of the form:{"<command-name>": "<module-name>.<command-object-name>"}
For example:
{"mycmd": "my_cli.commands.mycmd"}
A subcommand needing registration settings on top of its import path is declared with a
LazySubcommandinstead of a bare string:{"mycmd": LazySubcommand("my_cli.commands.mycmd", section=my_section)}
Every section declared that way is registered on the group here, so the help screen orders its sections as the author declared them. Waiting for each subcommand to be imported would instead order them by import, which is alphabetical and says nothing about intent.
- lazy_subcommands: dict[str, LazySubcommand]¶
- listed_command(ctx, name)[source]¶
Like the parent, but describing a lazy subcommand not imported yet by the stand-in its
short_helpbuilds.
- class click_extra.LazySubcommand(import_path, section=None, fallback_to_default_section=True, short_help=None)[source]¶
Bases:
objectDeclaration 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.- 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
Sectioninstance can be shared with eagerly-registered subcommands.
- fallback_to_default_section: bool = True¶
Whether to file the subcommand under the default section when
sectionisNone.Set to
Falseto 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:
ExtraOptionA pre-configured
--manflag that typesets the commandās manual, pages it, and exits.Eager and value-less, like
ShowParamsOption. Part of the default option set injected bydefault_params(), so every@commandand@groupexposes it. Use@man_optionto add it to a plain Click CLI.Note
The flag is named
--man, not--show-manor--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 (BSDmdoc) or generated at build time from--helpoutput (GNUhelp2man). Click Extra already covers that build-time path withwrite_manpages(), itshelp2manequivalent.The one ecosystem that exposes a runtime flag is Perlās
Pod::Usage, whose convention is--helpfor the brief usage and bare--manfor the full manual.--manalso lines up with the neighbouring--helpand--versioninformational flags, which use bare nouns with noshow-prefix.--show-manand--man-pagehave 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
manitself 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?
- exception click_extra.MissingExtraError(extra, *, subject, package='click-extra')[source]¶
Bases:
ClickException,ImportErrorA 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 status1, with no traceback.It is an
ImportErroras 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 installcommand that installs the extra, in the wording every other optional-dependency error of the package uses.
- exception click_extra.MissingParameter(message=None, ctx=None, param=None, param_hint=None, param_type=None)[source]¶
Bases:
BadParameterRaised if click required an option or argument but it was not provided when invoking the script.
Added in version 4.0.
- class click_extra.MultiChoice(choices=(), separator=',', case_sensitive=False)[source]¶
Bases:
ParamTypeComma-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 configurableseparator(defaults to,), parses it into atuple[str, ...]and validates each value againstchoiceswhen that set is non-empty.The rendered metavar is
[a,b,c](separator-joined, parallel toChoiceās[a|b|c]):click_extra.highlight._HelpColorsMixinauto-detects the separator and highlights each individual value the same way it does forChoice.Note
Click ships no single-token equivalent: its idiom is
click.Choicewithmultiple=True, which repeats the flag (--tag a --tag b). pallets/click#2771 asks for a separator-based variant.MultiChoicefollows the SQLSELECT a, b, cconvention of the tabular use cases Click Extra supports, withclick_extra.table_options.ColumnsOptionas the headline consumer.Initialize the type.
- Parameters:
choices (
Sequence[str]) ā the accepted values. When non-empty,convert()rejects unknown tokens withfail. 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) ā whenTrue, a token must match one ofchoicesexactly. By default tokens match case-insensitively, as withEnumChoiceandThemeChoice, and the returned tuple holds the canonical (original-case) values fromchoices.
- get_metavar(param, ctx)[source]¶
Render
[a<sep>b<sep>c]whenchoicesis set,Noneotherwise.Nonefalls back to Clickās default rendering (the uppercasedname, likeMULTI).
- convert(value, param, ctx)[source]¶
Split
valueonseparatorand 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.
- class click_extra.MulticallGroup(*args, personalities=None, personalities_command=True, **kwargs)[source]¶
Bases:
GroupA
Groupdispatching 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:
an explicit
prog_namepassed tomain()(whatclick_extra.testing.CliRunneruses to simulate a symlink),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 trailingWINDOWS_EXE_SUFFIXis stripped for Windows console-script shims. Clickās own_detect_program_name()is deliberately not used: it reads__main__.__package__and answerspython -m ā¦in the module case. Seeclick_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, whereargv[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 toNone, every non-hidden, non-synthetic subcommand is its own personality.personalities_command (
bool) ā whenTrue(the default), apersonalitiessubcommand is auto-registered on the group, listing every invocation name the binary answers to. Register your ownpersonalitiessubcommand 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.exestripped on Windows.
- list_personalities()[source]¶
Every personality name mapped to the tokens it invokes.
The explicit
personalitiesmapping when one was declared, else every subcommand_is_default_personalityadmits, mapped to itself. The lazy subcommands of a lazy group are imported to be judged, which a listing has to pay for.
- 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:
- 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
paramsattribute is patched after the fact. Two reasons make the re-instantiation mandatory:Cloup computes its help layout (
arguments,option_groups,ungrouped_options) fromparamsinside__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_endreordering, option priorities, auto envvar population and help-keyword collection.
Every parameter is deep-copied, because
Command.__init__re-runspopulate_auto_envvarsover the merged set under the personalityās ownauto_envvar_prefix: sharing instances would rewrite the groupās and subcommandāsenvvarattributes and leak that back into group mode. This is the same class of leaky statedefault_params()warns about.- Return type:
- 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-colorflag that forces--color=never.Click rejects
/--no-xsecondary flags on a value option, so the negative alias of the tri-stateColorOptioncannot live on it and is provided here as a standalone boolean flag. When set, it pinsctx.colortoFalse; when absent it is a no-op, leaving the resolution toColorOption.Shown on its own line directly below
--color(mirroring--no-configbelow--config), since every other negative in the default option set is visible too. Eager by default, likeColorOption, so the color state is settled before other eager options render.- set_no_color(ctx, param, value)[source]¶
Force
ctx.coloroff 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:
- 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:
ExtraOptionA pre-configured option adding
--no-config.This option is supposed to be used alongside the
--configoption (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_CONFIGis theSentinelenum member that signals āskip configuration loadingā toConfigOption. Click pickstype=UNPROCESSEDfor aflag_valueof a non-basic type, so the sentinel passes throughOptionunchanged.See also
An alternative implementation of this class would be to create a custom click.ParamType instead of a custom
Optionsubclass. Here is for example.
- exception click_extra.NoSuchCommand(command_name, message=None, possibilities=None, ctx=None)[source]¶
Bases:
UsageErrorRaised if Click attempted to handle a command that does not exist.
Added in version 8.4.0.
- exception click_extra.NoSuchOption(option_name, message=None, possibilities=None, ctx=None)[source]¶
Bases:
UsageErrorRaised if Click attempted to handle an option that does not exist.
Added in version 4.0.
- 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:
objectA
ā/āprogress trail and finisher for a batch of operations.Where
Spinnernarrates one long-running call,OperationTrailreports a batch of them: each completed operation leaves a persistenttrail_line()on screen, a runningdone/totaltally keeps the batchās pulse visible, andfinish()closes with a persistent summary line. The natural reporting companion of the concurrency primitivesrun_jobs()andrun_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-callSpinner).finish()appends the elapsed time.concurrent (
jobs > 1): drive one aggregateSpinner(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 theSPINNERScatalog withspinner=.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 knowntotal.
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
livechanges 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=Falsesilences 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 thedone/totalcount.jobs (
int) ā the batchās worker count;> 1selects the concurrent rendering (one aggregate spinner),<= 1the sequential one (plain echoed lines).spinner (
SpinnerPreset|None) ā aSpinnerPresetfrom theSPINNERScatalog (spinner=SPINNERS["moon"]) for the concurrent aggregate spinner. Ignored by the sequential and progress-bar renderings, and mutually exclusive withprogress_bar.progress_bar (
bool) ā render the aggregate indicator as a determinateclick.progressbar()instead of a spinner, for a sequential or concurrent batch alike. Requires a positivetotal(a bar needs a length) and is mutually exclusive withspinner.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-timeflag;Trueforces timing on withformat_duration()ās compact clock, a callable(seconds: float) -> strforces it on with a custom format, andFalseforces it off. Per-operation times come from asecondsargument tomark(), filled in automatically by anoperation()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 itstotal). Per-operation and finisher times are always elapsed.visible (
bool) ā whether the trail shows anything.Falsesilences the lines, the finisher and the aggregate indicator, whileok_countkeeps counting.live (
Literal['auto','always','never']) ā where the aggregate indicator may draw:"auto"(the default) on an interactive terminal only, unless--no-progressturns 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 atfinish()instead (seeecho_sequential).stream (
IO[str] |None) ā where to render; defaults tosys.stderrso the trail never mixes intostdoutdata.
- Raises:
ValueError ā if
progress_baris set without a positivetotal, or together withspinner, ifclockis neither"elapsed"nor"eta", or ifliveis not one ofWHEN.
- 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. Whentimeris on it is formatted and appended tomessageas(2.3s). Anoperation()handle fills this in from when it was created; pass it yourself when you already hold a duration.- Return type:
- 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 whentimeris on.A batch finishing inside
delaynever draws its indicator, so none of its buffered lines reached the stream. When the trail is the batchās output (echo_sequentialandvisible), 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:
- 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 (whentimeris 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,Optioncloup.Optionwith the overrides of_ParameterMixin.cloup.Optionsubclassesclick.Optionto let an option join a Cloup option group.Todo
Delete the
human_readable_nameoverride and_CLICK_HAS_PARAMETER_SPEConce this packageās Click floor reaches8.6.0. From that release on, Click names a parameter byParameter.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.0only: from that release on, Click readsParameter.specin its place, and warns about a subclass that overrides this property.Below it, Click returns
self.namehere: 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-cygannounces itself as'apt_cyg', naming a flag no user can type and none of the two they did.click.Argumentalready overrides the property for its own reasons, leavingclick.Optionre-declaring the inherited body verbatim." / "is the separatorclick.Parameter.get_error_hintjoins 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:
objectContains the information of an option group and identifies it. Note that, as far as the clients of this library are concerned, an
OptionGroupsacts 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
hiddenparameter.
- class click_extra.OptionGroupMixin(*args, align_option_groups=None, **kwargs)[source]¶
Bases:
objectImplements 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.ConstraintMixintoo!Added in version 0.14.0: added the āPositional argumentsā help section.
Changed in version 0.8.0: this mixin now relies on
cloup.HelpFormatterto align help sections. If aclick.HelpFormatteris used with aTypeErroris raised.Changed in version 0.8.0: removed
format_option_group. Addedget_default_option_groupandmake_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 MROkwargs (
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
--helpoption; use theget_ungrouped_options()method if you need the real full list (which needs aContextobject).
- get_ungrouped_options(ctx)[source]¶
Return options not explicitly assigned to an option group (eventually including the
--helpoption), i.e. options that will be part of the ādefault option groupā.
- get_argument_help_record(arg, ctx)[source]¶
Like Argument.get_help_record, but it returns a tuple even if help is empty
- make_option_group_help_section(group, ctx)[source]¶
Return a
HelpSectionfor anOptionGroup, 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:
- must_align_option_groups(ctx, default=True)[source]¶
Return
Trueif the help sections of all options groups should have their columns aligned.Added in version 0.8.0.
- Return type:
- class click_extra.OptionKwargs[source]¶
Bases:
_ParamKwargsArguments accepted by
option().Refer to
click.Optionfor their meaning and defaults.- 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]¶
- 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]¶
- nargs: NotRequired[int | None]¶
- metavar: NotRequired[str | None]¶
- expose_value: NotRequired[bool]¶
- class click_extra.ParamStructure[source]¶
Bases:
objectUtilities 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:
ShowParamsOptionfreezes an empty set, whileConfigOptionresolves 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. Askis_excluded()about a parameter of another subcommand.
- included_params: frozenset[str] | None¶
Allowlist of parameter IDs, mutually exclusive with
excluded_params.Nonedisables the allowlist. Otherwisebuild_param_trees()walks only the subcommands an allowed ID lies under, and resolves the parameters it reaches intoexcluded_params.
- static init_tree_dict(*path, leaf=None)[source]¶
Nest one dict per key of
path, the deepest one holdingleaf.An empty
pathreturnsleafitself.- Return type:
- static get_tree_value(tree_dict, *path)[source]¶
Get in the
tree_dictthe value located at thepath.Raises
KeyErrorif no item is found at the providedpath.- Return type:
- 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
descendskips 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.
- 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
strfor unrecognised custom types, since command-line parameters are strings by default.See the list of custom types provided by Click.
- static get_param_type(param)[source]¶
Get the Python type of a Click parameter.
Returns
strfor unrecognised custom types, since command-line parameters are strings by default.A boolean flag is a
booleven 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.
- 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_paramsdoes not name it. So the answer holds for a parameter of a subcommand that the walk ofbuild_param_trees()skipped. Without an allowlist, the parameter is excluded whenexcluded_paramslists it.- Parameters:
param_id (
str) ā the fully-qualified ID of the parameter, its path keys joined withPARAM_PATH_SEP.- Return type:
- 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_paramsblocklist.With an allowlist, the tree holds only the parameters
included_paramsnames. The walk then skips each subcommand that no allowed ID lies under, so it does not import a lazy subcommand of aLazyGroupthat the allowlist leaves out. An empty allowlist walks the root command alone. The parameters the walk reaches and the allowlist leaves out becomeexcluded_params.
- class click_extra.ParamType[_ValueT_co, _InputT_contra = Any][source]¶
Bases:
Generic[_ValueT_co,_InputT_contra],ABCRepresents 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
nameclass attribute must be set.Calling an instance of the type with
Nonemust returnNone. 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
ctxandparamarguments areNone. 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 thatconvert()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 toAny.- 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.
Nonemeans any whitespace. For all parameters the general rule is that whitespace splits them up. The exception are paths and files which are split byos.path.pathsepby 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_missing_message(param, ctx)[source]¶
Optionally might return extra information about a missing parameter.
Added in version 2.0.
- 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
paramandctxarguments may beNonein certain situations, such as when converting prompt input.If the value cannot be converted, call
fail()with a descriptive message.
- 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.
- fail(message, param=None, ctx=None)[source]¶
Helper method to fail with an invalid value message.
- Return type:
- shell_complete(ctx, param, incomplete)[source]¶
Return a list of
CompletionItemobjects 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:
- Return type:
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:
ABCA parameter to a command comes in two versions: they are either
Options orArguments. 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 aParamTypeor 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 asf(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 not1the return value is a tuple instead of single value. The default for nargs is1(except if the type is a tuple, then itās the arity of the tuple). Ifnargs=-1, all remaining parameters are collected.metavar (
str|None) ā how the value is represented in the help page.expose_value (
bool) ā if this isTruethen 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. Takesctx, param, incompleteand must return a list ofCompletionItemor a list of strings.deprecated (
bool|str) ā IfTrueor 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.2.0: Introduction of
deprecated.Changed in version 8.2: Adding duplicate parameter names to a
Commandwill result in aUserWarningbeing shown.Changed in version 8.2: Adding duplicate parameter names to a
Commandwill result in aUserWarningbeing shown.Changed in version 8.0:
process_valuevalidates required parameters and boundednargs, and invokes the parameter callback before returning the value. This allows the callback to validate prompts.full_process_valueis removed.Changed in version 8.0:
autocompletionis renamed toshell_completeand 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 toNone.multiple=Trueornargs=-1will 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'¶
- 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
Nonefor thedefaultif it was not set.Added in version 8.0.
- 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.
- get_default(ctx, call=True)[source]¶
Get the default for the parameter. Tries
Context.lookup_default()first, then the local default.- Overloads:
- Parameters:
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_mapfirst.Changed in version 8.0: Added the
callparameter.
- type_cast_value(ctx, value)[source]¶
Convert and validate a value against the parameterās
type,multiple, andnargs.- Return type:
- 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:
ctxcan beNone.- Return type:
- class click_extra.ParameterSource(*values)[source]¶
Bases:
IntEnumThis is an
IntEnumthat 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
IntEnumand reorder members from most to least explicit. Supports comparison operators.Changed in version 8.0: Use
Enumand drop thevalidatemethod.Changed in version 8.0: Added the
PROMPTvalue.- 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
Pathtype is similar to theFiletype, 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 toTrue, 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). Useopen_file()to handle opening this value.path_type (
type[_PathT_co] |None) ā Convert the incoming path value to this type. IfNone, keep Pythonās default, which isstr. Useful to convert topathlib.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
executableparameter.Changed in version 8.0: Allow passing
path_type=pathlib.Path.Changed in version 6.0: Added the
allow_dashparameter.- 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.
Nonemeans any whitespace. For all parameters the general rule is that whitespace splits them up. The exception are paths and files which are split byos.path.pathsepby 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:
PathInfoDict
- 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
paramandctxarguments may beNonein certain situations, such as when converting prompt input.If the value cannot be converted, call
fail()with a descriptive message.
- 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:
ExtraOptionA pre-configured
--progress/--no-progressflag gating spinner display.Resolves to a single boolean published at
ctx.meta[click_extra.context.PROGRESS], whichSpinner,OperationTrailandprogressbar()read on their own when left at their automatic default. The default isTrue;--accessiblelowers it toFalse(viadefault_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_COLORstrip 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/--quietknob), whileNO_COLORonly affects color. Rich takesTERM=dumb, notNO_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=dumbterminal that cannot move the cursor (see_can_draw());explicit intent:
--no-progressor--accessible.
This option is eager. It never reads
ctx.color, so its position relative toColorOptiondoes not matter.- set_progress(ctx, param, value)[source]¶
Publish whether progress spinners may be shown.
Stores the resolved
--progressflag atPROGRESS. Deliberately independent of color: see theProgressOptionnote for why a spinner is gated on interactivity (TTY /TERM=dumb) and--accessible, never on--no-color/NO_COLOR.- Return type:
- class click_extra.QuietOption(param_decls=None, **kwargs)[source]¶
Bases:
_CounterOption--quiet/-qoption to lower the log level of_VerbosityOptionby one step per repetition.The symmetric counterpart of
VerboseOption: where-vraises the verbosity oneLogLevelstep at a time,-qlowers it. Starting fromVerbosityOption.default(WARNINGby default):-qlowers the level toERROR,-qqlowers the level toCRITICAL,any further repetition is clamped at the quietest level, so
-qqqqqfor example resolves toCRITICAL.
-qshares a single signed counter withVerboseOptionās-v, so the two cancel out:-v -qleaves the level unchanged. See_VerbosityOption.resolve_levelfor 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.Loggerobject is used as it is.The name of the
rootlogger, 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
rootlogger, which the whole process shares. Whichever logger is selected, therootone gets Click Extraās handler for the time of each run of the command: seeadd_to_parser().
- class click_extra.Result(runner, stdout_bytes, stderr_bytes, output_bytes, return_value, exit_code, exception, exc_info=None)[source]¶
Bases:
ResultA
Resultsubclass with automatic traceback formatting.Enhances
__repr__so that pytest assertion failures show the full traceback instead of just the exception type.
- class click_extra.SchemaFieldInfo(key, type_hint, default, summary, description)[source]¶
Bases:
NamedTupleDocumentation record for one option of a configuration schema.
Produced by
schema_field_infos(). Consumed by theclick:configSphinx directive, and by CLIs building their own configuration reference (ashow-configtable, 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 throughclick_extra.config.schema.CONFIG_PATH_METADATA_KEY. Nested dataclass fields contribute one segment per nesting level (test-suite.timeout).
- 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()).
- class click_extra.Section(title, commands=(), is_sorted=False)[source]¶
Bases:
objectA group of (sub)commands to show in the same help section of a
MultiCommand. You can use sections with anyCommandthat inherits fromSectionMixin.Changed in version 0.6.0: removed the deprecated old name
GroupSection.Changed in version 0.5.0: introduced the new name
Sectionand deprecated the oldGroupSection.- Parameters:
- commands: OrderedDict[str, Command]¶
- class click_extra.SectionMixin(*args, commands=None, sections=(), align_sections=None, **kwargs)[source]¶
Bases:
objectAdds to a
click.MultiCommandthe possibility of organizing its subcommands into multiple help sections.Sections can be specified in the following ways:
passing a list of
Sectionobjects to the constructor setting the argumentsectionsusing
add_section()to add a single sectionusing
add_command()with the argumentsectionset
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.HelpFormatterto align help sections. If aclick.HelpFormatteris used with aTypeErroris raised.Changed in version 0.8.0: removed
format_section. Addedmake_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 MROkwargs (
Any) ā keyword arguments forwarded to the next class in the MRO
- add_section(section)[source]¶
Add a
Sectionto this group. You can add the same section object only a single time.- See Also:
- Return type:
- section(title, *commands, **attrs)[source]¶
Create a new
Section, adds it to this group and returns it.- Return type:
- add_command(cmd, name=None, section=None, fallback_to_default_section=True)[source]¶
Add a subcommand to this
Group.Implementation note:
fallback_to_default_sectionlooks 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)section (
Section|None) ā aSectioninstance. The command must not be in the section already.fallback_to_default_section (
bool) ā ifsectionis None and this option is enabled, the command is added to the ādefault sectionā. If disabled, the command is not added to any section unlesssectionis provided. This is useful for internal code and subclasses. Donāt disable it unless you know what you are doing.
- Return type:
- list_sections(ctx, include_default_section=True)[source]¶
Return the list of all sections in the ācorrect orderā.
If
include_default_section=Trueand the default section is non-empty, it will be included at the end of the list.
- 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:
- 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,ParamStructureA pre-configured option adding a
--paramsoption.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 ashow-verb prefix. The class and the@show_params_optiondecorator 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
--paramstable.Each entry is a
click_extra.columns.ColumnSpeccarrying the columnās stableid(used by--columnsand as structured-format key), its displaylabel, and a MyST/Markdowndescriptionconsumed 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).
- classmethod column_ids()[source]¶
Return just the stable IDs of
TABLE_HEADERS(in order).
- classmethod default_columns()[source]¶
Return the columns rendered when
--columnsasks for no projection.Every column but the
optionalones, which stay addressable by ID and out of the way until named.- Return type:
- classmethod default_column_ids()[source]¶
Return the stable IDs of
default_columns()(in order).
- classmethod default_column_labels()[source]¶
Return the display labels of
default_columns()(in order).
- classmethod find_column(column_id)[source]¶
Return the
ColumnSpecmatchingcolumn_id.- Raises:
KeyError ā if no column has this ID. Convert it into a
click.UsageErrorbefore it reaches a user.- Return type:
- classmethod render_doc_table()[source]¶
Render
TABLE_HEADERSas a Markdown table for documentation.Used by the
show_params_columns_tableMyST substitution indocs/conf.pyto feed the Available columns section ofdocs/parameters.md: editing a description here automatically rebuilds the docs table on the nextsphinx-build.- Return type:
- 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 drivingclick-extra wrap --paramsfor foreign CLIs. The live invocation context carries everything the core needs: the capturedRAW_ARGS(attached byCommand/Group) for value and source resolution, plus any sibling--table-format/--columnsoptions.- Return type:
- exception click_extra.SkippedTest[source]¶
Bases:
ExceptionRaised 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:
ExtraOptionA
--sort-byoption 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 inctx.meta[click_extra.context.TABLE_SORT_KEY], whichctx.print_tablepicks up so that table output is automatically sorted, without changing its(table_data, headers)call contract. The option acceptsmultiple=True, so users can repeat--sort-byto define a multi-column sort priority.Column definitions are
ColumnSpecinstances, passed positionally or via thecolumns=keyword. A column markedsortable=Falsekeeps its place in the layout without being offered as a choice. Passing aColumnSpecregistry viacolumns=lets the same tuple drive bothColumnsOption(--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-bydeclared 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 byprint_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 atprint_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 underctx.meta[click_extra.context.TABLE_SORT_KEY], wherectx.print_tablepicks 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.metais shared with every subcommand), resolved per table byprint_table()from the column IDs its headers carry.- Return type:
- 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:
objectA 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 callingstop()) halts the thread and erases the spinner line so it never lingers above the next output.Note
A single
Spinnerinstance drives one animation at a time. A tool running its steps one after another can share one instance and reassign itslabelbetween 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@Spinnerdecorator 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 toSPINNER_FRAMES, or thespinnerpresetās frames when given.spinner (
SpinnerPreset|None) ā aSpinnerPresetfrom theSPINNERScatalog (spinner=SPINNERS["moon"]), supplying both frames and a tuned interval. An explicitframesorintervalstill 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 customframes.interval (
float|None) ā seconds between two frames. Defaults toDEFAULT_INTERVAL, or thespinnerpresetā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) ā aStyleapplied to the spinner glyph, label and timer (Style(fg="cyan", bold=True)). Color is decoupled from animation:--no-color/NO_COLORstrip it while the spinner keeps spinning (seeProgressOption). The strip reaches escapes embedded inlabelitself too, so a label styled by hand is as safe as one styled through these arguments.label_style (
Style|None) ā aStylefor the label alone, in place ofstylethere. It also paints the label of the keptok()/fail()line, whichstyleleaves plain. It outlives a reassignedlabel, 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 finalok()/fail()line.None(the default) follows the CLIās--time/--no-timeflag, as anOperationTraildoes.Trueforces it on withformat_duration()ās compact format (2.3s,1:05, then1:02:03),Falseforces it off, and a callable(seconds: float) -> strformats the duration yourself, liketimer=lambda s: f"{s / 60:.0f}m"for whole minutes.timer_style (
Style|None) ā aStylefor the timer, parentheses included, in place ofstylethere (Style(dim=True)to set the clock back from the label). Atimercallable formats only the duration, so it cannot reach the parentheses: this can. Also paints the timer of the keptok()/fail()line.stream (
IO[str] |None) ā where to draw; defaults tosys.stderrso the spinner never mixes intostdoutdata.live (
Literal['auto','always','never']) ā where the animation may draw:"auto"(the default) on an interactive terminal only, unless--no-progressturns it off,"always"on any stream,"never"nowhere. A spinner that does not draw still writes itsok()/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_styleortimer_stylecarries a color or attribute that cannot be rendered, or ifliveis not one ofWHEN.
- 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 oncestop()is called.Returns
0.0before the spinner has started.
- property shown: bool¶
Whether the spinner has drawn at least one frame to its stream.
Trueonly once an animation frame was actually rendered. It staysFalsefor a disabled spinner (off a TTY, on aTERM=dumbterminal, or withlive="never") and for a call that finishes withindelay, before the first frame. Reset bystart().Use it to gate output that should mirror the spinnerās visibility.
ok()andfail()write their line unconditionally, so an outcome is still recorded in a pipe or log. Guard them withshownwhen 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 waystart()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.
- 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 laterok()/fail()can report a duration).- Return type:
- 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:
- echo(message='')[source]¶
Print
messageon its own line above the running spinner.Clickās
click.progressbar()and a bareprintboth 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, writesmessagefollowed 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(stderrby default), so results written tostdoutnever need it. When the spinner is not animating (disabled, or a non-TTY stream), it degrades to a plain write ofmessagewith no control codes.- Return type:
- 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 withsymbolfollowed by the current label (and the elapsed time whentimeris set), then keeps that line.symboldefaults to the themed success glyphOK_GLYPH(ā), painted with the active themeāssuccessslot unlessstyleoverrides it. Color is stripped under--no-color/NO_COLOR; the glyph stays.- Return type:
- class click_extra.SpinnerPreset(frames, interval)[source]¶
Bases:
NamedTupleA named spinner animation: its frames and the interval they look best at.
Pick one from the
SPINNERScatalog, or build your own, and pass it toSpinnerthrough itsspinnerargument.Create new instance of SpinnerPreset(frames, interval)
- class click_extra.StreamHandler(stream=None)[source]¶
Bases:
StreamHandlerA handler to output logs to the console.
Wraps
logging.StreamHandler, but usesclick.echo()to support color printing.Only
sys.stderrorsys.stdoutare allowed as output stream, andsys.stderris 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 anOperationTrailprogress bar): the record is then printed through itsecho, 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 toclick.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-colorand keep its ANSI codes on a TTY.- Return type:
- 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:
Stylecloup.Stylewith 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,
#rrggbbhex, RGB tuple, or palette index.
- bg: str | tuple[int, int, int] | int | None = None¶
Background color: named ANSI string,
#rrggbbhex, RGB tuple, or palette index.
- cascade(base)[source]¶
Return a copy with
Nonefields filled in from base.The instanceās own non-
Nonevalues always win:cascadeonly fills gaps. Useful for theme inheritance:derived.cascade(parent)keepsderivedās overrides and inherits the rest fromparent.- Return type:
- to_dict()[source]¶
Serialize to a plain dict with only the set fields.
RGB tuples are emitted as
#rrggbbstrings so the result round-trips through TOML/JSON/YAML untouched. Pair withfrom_dict()to rebuild aStyle.
- classmethod from_dict(data)[source]¶
Build a
Stylefrom the plain dict produced byto_dict().Validates that every key in data names a known
Stylefield and raisesTypeErrorotherwise. Pair withto_dict()to round-trip through TOML/JSON/YAML.- Return type:
- 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 inlinestyle="..."attributes on HTML spans.- Return type:
- 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;n256-color extension, and the38;2;r;g;b/48;2;r;g;b24-bit extension. Reset codes (the full0reset, its parameter-less\x1b[mform included, and selective resets like22,39or49) 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 singleStyle.To tokenize a string mixing text and escapes, with resets honored, see
split_ansi().- Return type:
- 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:
- class click_extra.TableFormat(*values)[source]¶
Bases:
EnumEnumeration of supported table formats.
Hard-coded to be in alphabetical order. Content of this enum is checked in unit tests.
Warning
The
youtrackformat 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--coloron 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_FORMATSfor the registry.
- property is_wrappable: bool¶
Whether this format renders a cell wrapped onto several lines.
See
WRAPPABLE_FORMATSfor 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:
ExtraOptionA pre-configured option that is adding a
--table-formatflag 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 therender_table()andprint_table()context methods pick it up as their default format.ctx.metais 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_datais a 2-dimensional iterable of iterables for rows and cells values,headersis a list of string to be used as column headers,**kwargsare any extra keyword arguments supported by the underlying table formatting function.
- init_formatter(ctx, param, table_format)[source]¶
Save the resolved
table_formatin the contextās sharedmeta.The
render_table()andprint_table()context methods read it back at call time.- Return type:
- 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:
ExtraOptionA pre-configured
--telemetry/--no-telemetryoption 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_TRACKforces telemetry off, overriding the user-defined environment variables, the auto-generated values, and configuration files. Only an explicit--telemetryon the command line outranks it.The resolved value is stored in
ctx.meta[click_extra.context.TELEMETRY].See also
- set_telemetry(ctx, param, value)[source]¶
Reconcile the flag with
DO_NOT_TRACKand store the result onctx.meta.An explicit
--telemetry/--no-telemetryon the command line wins. Otherwise a truthyDO_NOT_TRACK(bare presence, or any value not parseable as false, seeparse_envvar_flag()) forces telemetry off. Read viaclick_extra.context.get(ctx, click_extra.context.TELEMETRY).Important
DO_NOT_TRACKbreaks the rule of the other machine-wide variables, which a configuration file and the optionās own variable outrank (seemachine_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>_TELEMETRYvariable 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_TRACKis read here rather than wired through the optionāsenvvar: Clickās environment plumbing feeds the raw value straight to the boolean flag, soDO_NOT_TRACK=1would enable telemetry, inverting the convention. Reading it manually keeps the opt-out meaning, mirroring howColorOptionreadsNO_COLORand friends.- Return type:
- class click_extra.TerminalBackground(*values)[source]¶
Bases:
StrEnumShade 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: seeclick_extra.capture.presets. A capture tells the command it pictures which one it is drawn on through the same variablesresolve_background()reads, seeCAPTURE_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
lightandmanpagethemes 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
--backgroundchoice 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:
ExtraOptionA pre-configured option that adds
--themeto select the help-screen palette.Accepts any name registered in
theme_registryor in the per-invocation overrides loaded byConfigOptionfrom[tool.<cli>.themes.<name>]. Validation goes throughThemeChoice, which reads the live registry at parse time, so config-defined themes appear as valid choices and in the--helpmetavar without any further wiring.The resolved
HelpThemelands on the Click context underclick_extra.context.THEMEand 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. Seeset_theme()for how it ranks against the flag, the<CLI>_THEMEvariable 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 viaresolve_auto_theme()instead of naming a registered theme. Background detection reads environment variables by default; passquery_background=Trueto 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.
ThemeChoicehas already validated value against the live registry (or accepted theAUTO_THEMEdirective) by the time this fires. A plain palette name is looked up unconditionally;autois resolved from the terminal background viaresolve_auto_theme(), leavingctx.metauntouched when no palette can be resolved soget_current_theme()keeps its default.Before that,
THEME_ENVVARis consulted when the value still comes from the optionās own default, as for every machine-wide variable (seemachine_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 explicitenvvarbefore the auto-generated<CLI>_THEME, which would let the machine-wide preference outrank the CLI-specific one, and would list both names in the--paramstable, making the combined string the widest cell of its column. This mirrors howAccessibleOptionreadsACCESSIBLEandColorOptionreadsNO_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:
- 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:
ExtraOptionA pre-configured option that is adding a
--time/--no-timeflag 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 viactx.exit(). That makes--timea 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) ā thetime.perf_counter()reading the run started at.- Return type:
- 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 onctx.metaunderclick_extra.context.START_TIME, and queuesprint_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:
- 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:
ExtraOptionA pre-configured
--treeflag that prints the hierarchy of nested subcommands and exits.Eager and value-less, like
ManOption. Part of the default option set injected bydefault_params(), so every@commandand@groupexposes it. Use@tree_optionto add it to a plain Click CLI.Note
The flag is named
--tree, not--show-treeor--commands.Rendering a hierarchy as a tree is conventionally named
treeacross ecosystems:eza --tree,lsblk --tree,poetry show --tree,cargo tree,pstree(1)andtree(1)itself (ps --forestbeing the lone dissenter).--commandswould suggest the flat listing--helpalready provides.The bare noun also lines up with the neighbouring
--help,--man,--paramsand--versioninformational flags. It is a flag rather than a registeredtreesubcommand, which could collide with the userās own command namespace.
- 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
nargsis set to a fixed count and different types should be used for different items. In this case theTupletype can be used. This type can only be used ifnargsis 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.
- 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 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
paramandctxarguments may beNonein certain situations, such as when converting prompt input.If the value cannot be converted, call
fail()with a descriptive message.
- exception click_extra.UsageError(message, ctx=None)[source]¶
Bases:
ClickExceptionAn internal exception that signals a usage error. This typically aborts any further handling.
- Parameters:
- 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:
ExtraOptionA 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
UNPROCESSEDso it accepts everythingConfigOptionaccepts: a file, a folder, a glob pattern, or anhttp://orhttps://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
ValidationErrorshape so the reported path is always rooted at the configuration file:CLI-parameter strict check on the non-opaque part of the document.
Schema processing, if a
config_schemais configured: catches type errors and unknown keys inside the dataclass-described section.Each registered
ConfigValidatorruns against its declared opaque sub-tree.
Every detected error is emitted before exiting, so a single
--validate-configrun surfaces the full list of fixes the user needs to apply.- Return type:
- exception click_extra.ValidationError(path, message, code=None)[source]¶
Bases:
ValueErrorRaised when a configuration file fails validation.
A single, structured exception type that uniformly carries the dotted
pathof the offending key, a human-readablemessage, and an optionalcodefor programmatic handling. Used by click-extraās built-in strict-mode check and by every user-registeredConfigValidator, so downstream apps and--validate-configsee 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:
objectOutcome 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.
Nonewhen no schema is configured, or when the schema stage raised (in which case the failure is recorded inerrors).
- 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
ValidationErrordetected, in stage order (CLI-flag keys first, then schema errors, then validator failures). Empty on success.With
collect_all=Falsethis 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 payloadload_conf()layers into the contextāsdefault_map, asmerge_default_map()does.Nonewhenparams_templatewasNone(no strict check) or the strict check failed.
- class click_extra.VerboseOption(param_decls=None, **kwargs)[source]¶
Bases:
_CounterOption--verbose/-voption to raise the log level of_VerbosityOptionby one step per repetition.Each
-vraises the verbosity by oneLogLevelstep. 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 atWARNING:-vraises the level toINFO,-vvraises the level toDEBUG,any further repetition is clamped at the loudest level, so
-vvvvvfor example resolves toDEBUG.
-vshares a single signed counter withQuietOptionās-q, so the two cancel out:-v -qleaves the level unchanged. See_VerbosityOption.resolve_levelfor 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.Loggerobject is used as it is.The name of the
rootlogger, 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
rootlogger, which the whole process shares. Whichever logger is selected, therootone gets Click Extraās handler for the time of each run of the command: seeadd_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 LEVELoption 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.Loggerobject is used as it is.The name of the
rootlogger, 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
rootlogger, which the whole process shares. Whichever logger is selected, therootone gets Click Extraās handler for the time of each run of the command: seeadd_to_parser().
- 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:
ExtraOptionGathers 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
--versionoption 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 oftemplate_fields(for example{"version": "1.2.3"}).styles (
Mapping[str,Callable[[str],str] |None] |None) ā mapping of template field name to itsStyle, merged overdefault_styles. PassNoneas a value to clear a fieldās default style. Keys must be members oftemplate_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) ā aVersionScreento draw instead of the one-line message, whenever the terminal can take it. Left unset,--versionprints the one-line message.
- Raises:
TypeError ā when a key of
fieldsorstylesnames 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-providedstylesare 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 defaultdarkpalette,invoked_commandis bright white bold andsuccessis 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_propertythat would otherwise resolve the field, and is recorded soreset_resolution()can tell the two apart. Every caller that pins a field goes through here: a baresetattrsets the value without the record, and the next reset then discards it.
- 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
--versionexample 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:
- 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:
--versionis 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:
modulethen defers to the module of the root commandās callback.- Return type:
- 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 aCliRunnerdriven 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 owninvoke(), inside the Click ecosystem.The Sphinx
click:rundirective is that shape: without this, a documented--versionwould 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
Nonewhen the command has no callback (a bareclick.Group) or its module is not imported, leaving the walkās own answer in place.- Return type:
- property module: ModuleType[source]¶
Returns the module in which the CLI resides.
- property module_file: str | None[source]¶
Returns the moduleās file full path.
Nonefor a module with no file, like the__main__ofpython -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_versionproperty below, which uses the standard libraryimportlib.metadataAPI.Clickās own
version_optionreads the package metadata only (pallets/click#2598). Click Extra reads__version__too, for the scripts and codebases that set it.
- property package_version: str | None[source]¶
Returns the package version if installed.
Resolved from the distribution name (see
_distribution_name) viaimportlib.metadata.version(). ReturnsNoneif 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.Noneif 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.Noneif 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 -mruns it as__main__, while a console script or a compiled binary imports it aspackage.__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 like1.2.3.dev0+abc1234. This helps identify the exact commit a dev build was produced from. Whengit_short_hashfinds 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 like1.2.3.dev0+abc1234+xyz5678.
- property git_repo_path: Path | None[source]¶
Find the Git repository root directory.
Walks up from
_search_startto the first directory holding a.gitentry: seefind_git_root().
- property git_branch: str | None[source]¶
Returns the current Git branch name.
Checks for a pre-baked
__git_branch__dunder first, thengit 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, thengit 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, thengit 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, thengit show -s --format=%ci HEAD, then.git_archival.json(whosenode-dateis strict ISO 8601, like2021-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, thengit describe --tags --exact-match HEAD, then.git_archival.json.Returns
Noneif 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, thengit rev-list -1on the tag returned bygit_tag, then.git_archival.json. ReturnsNoneif 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 parsesgit describe --tags --long, then falls back to.git_archival.json.Nonewhen no tag is reachable or Git is unavailable.
- property git_dirty: str | None[source]¶
Work-tree state:
"dirty","clean"orNone.Checks for a pre-baked
__git_dirty__dunder first, then runsgit status --porcelain.Nonewhen not in a Git repository or Git is unavailable. There is no.git_archival.jsonfallback: 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: seeBUILD_RESOLVERSandresolve_build_time().
- property build_os: str | None[source]¶
The operating system the build ran on.
Reads the pre-baked
__build_os__dunder. Seeresolve_build_os().
- property build_target: str | None[source]¶
The platform a distribution built here installs on.
Reads the pre-baked
__build_target__dunder. Seeresolve_build_target().
- property build_target_arch: str | None[source]¶
The CPU architecture the build ran on.
Reads the pre-baked
__build_target_arch__dunder. Seeresolve_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.
multicalldispatch relies on that, running one CLI under many names in sequence, and aprog_namepassed tomain()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 nofield_idfor the style of the templateās literal segments, which ismessage_stylealone.
- colored_template(template=None)[source]¶
Insert ANSI styles to a message template.
Accepts a custom
templateas 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:
- render_message(template=None)[source]¶
Render the version string from the provided template.
Accepts a custom
templateas parameter, otherwise uses the defaultself.colored_template()produced by the instance.A CLI carrying a
VersionScreengets 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-coloror 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
--accessiblekeeps the plain message.
- Return type:
- class click_extra.VersionScreen(logo, tagline='', facts=<function default_facts>, gutter=' ')[source]¶
Bases:
objectA logo, and the facts to seat beside it, as
--versionshould 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
VersionOptionthrough itsscreenargument, or to a whole CLI throughdefault_params(screen=ā¦).- logo: str | Sequence[str] | Callable[[], str | Sequence[str]]¶
The mark, pre-rendered, or a callable producing it. A string splits on newlines.
A callable defers the rendering to the first
--versionthat draws the screen, asfactsdoes for its values: a mark painted by code, from an image say, then costs nothing to the invocations that never ask for it.
- 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
--versionis asked for.
- 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.
- 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
--versioncannot drift apart on color.
- 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
Nonewhen 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 reportsshutilās 80-column default, wide enough that a redirected-but-forced-color run still gets the screen it asked for.
- 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:
ExtraOptionA pre-configured
-0/--zero-exitoption 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
0as 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
metadict.Read via
click_extra.context.get(ctx, click_extra.context.ZERO_EXIT).- Return type:
- 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
paramsargument, 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[0mbecomes<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:
- click_extra.ansi_to_jira(text)[source]¶
Translate ANSI styling in text to Jira wiki markup.
\x1b[34;1mSummer\x1b[0mbecomes{color:blue}*Summer*{color}.- Return type:
- click_extra.ansi_to_latex(text)[source]¶
Translate ANSI styling in text to LaTeX macros.
\x1b[34;1mSummer\x1b[0mbecomes\textcolor{blue}{\textbf{Summer}}. The colored macros require\usepackage{xcolor}in the document preamble.- Return type:
- click_extra.ansi_to_textile(text)[source]¶
Translate ANSI styling in text to Textile spans.
\x1b[34;1mSummer\x1b[0mbecomes%{color: blue; font-weight: bold}Summer%.- Return type:
- click_extra.args_cleanup(*args)[source]¶
Flatten recursive iterables, remove all
None, and cast each element to strings.Serializes
pathlib.Pathand other objects. Nested iterables andNonevalues are accepted as CLI arguments for convenience: they are flattened and filtered out.
- 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
paramsargument, 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
rootlogger.This function is a wrapper around Python standard libraryās
logging.basicConfig(), but with additional parameters and tweaked defaults.It sets up the global
rootlogger, and optionally adds a file or stream handler to it.Differences in default values:
Argument
basicConfig()defaultlogging.basicConfig()defaultstyle{%format{levelname}: {message}%(levelname)s:%(name)s:%(message)sThis 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 alogging.FileHandlerbe created, using the specified filename, rather than aStreamHandler.filemode (
str) āIf filename is specified, open the file in this
mode.Defaults to
a.Use the specified format string for the handler.
Defaults to
{levelname}: {message}.datefmt (
str|None) ā Use the specified date/time format, as accepted bytime.strftime().style (
Literal['%','{','$']) āIf format is specified, use this style for the format string:
%for printf-style,{forstr.format(),$forstring.Template.
Defaults to
{.level (
int|str|None) ā Set therootlogger level to the specified level.stream (
IO[Any] |None) ā Use the specified stream to initialize theStreamHandler. Note that this argument is incompatible with filename - if both are present, aValueErroris raised.handlers (
Iterable[Handler] |None) ā If specified, this should be an iterable of already created handlers to add to therootlogger. 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, aValueErroris raised.force (
bool) ā If this argument is specified asTrue, any existing handlers attached to therootlogger 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 tologging.FileHandlerfor opening the output file.errors (
str|None) ā Optional string that specifies how encoding and decoding errors are to be handled by thelogging.FileHandler. Defaults tobackslashreplace. Note that ifNoneis specified, it will be passed as such toopen().
- Return type:
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:
stream_handler_class (
type[Handler]) ā Alogging.Handlerclass that will be used inlogging.basicConfig()to create a default stream-based handler. Defaults toStreamHandler.file_handler_class (
type[Handler]) ā Alogging.Handlerclass that will be used inlogging.basicConfig()to create a default file-based handler. Defaults tologging.FileHandler.formatter_class (
type[Formatter]) ā Alogging.Formatterclass of the formatter that will be used inlogging.basicConfig()to setup the default formatter. Defaults toFormatter.
Note
The camel-cased name mirrors the one of Pythonās standard library
logging.basicConfig().
- click_extra.cases_from_data(data)[source]¶
Build
CLITestCaseinstances from already-parsed suite data.The in-memory counterpart to
parse_test_suite()(which parses a string) andload_test_suite()(which reads a file): feed it a suite that is already a Python object, such as the nativecasesmappings declared in a[tool.<cli>.test-suite]config section.A suite is a list of case mappings, each keyed by
CLITestCasedirective names. Formats with no bare top-level array (TOML) carry that list under a top-levelcaseskey, 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:
- click_extra.cell_width(text, term_program=None)[source]¶
Columns
textoccupies 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.widthanswers 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-1for it, which is every styled string. Reach for it only where a consumer reads that value back, astabulatedoes.- Parameters:
text (
str) ā the text to measure.term_program (
str|None) ā name of the terminal drawing the text, as$TERM_PROGRAMholds it. A few of them advance an emoji-presentation sequence by one column where the Unicode tables say two, and naming the terminal applieswcwidthās correction for it.Nonemeasures what the tables say.
- Return type:
- 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:
- 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
paramsargument, 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_columnsa table actually carries.header_defsdescribes the rendered columns:ColumnSpecinstances, withsortable=Falsefor columns that cannot be sorted on. The requestedsort_columnsthe 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
Nonewhen the table carries none of the requested columns, signalling that rows should keep their original order. This is what lets one--sort-byselection 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.
- 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
paramsargument, 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
paramsargument, 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 functionentries, 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.
- 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
paramsargument, 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
--configsupport, no native config file). Follows the conventional mapping:key = Trueā--keykey = "value"(or a number) ā--key=valuekey = ["a", "b"]ā--key=a --key=b(one flag per item)key = Falseis 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.
- 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
Abortexception.- Parameters:
text (
str) ā the question to ask.default (
bool|None) ā The default value to use when no input is given. IfNone, repeat until input is given.abort (
bool) ā if this is set toTruea negative answer aborts the exception by raisingAbort.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 tostderrinstead ofstdout, the same as with echo.
- Return type:
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
defaultisNone.Added in version 4.0: Added the
errparameter.
- click_extra.confirmation_option(*param_decls, **kwargs)[source]¶
Add a
--yesoption which shows a prompt before continuing if not passed. If the prompt is declined, the program will exit.
- 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.
- 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-fileisinput_file).- Return type:
Callable[[F],F]
- click_extra.convert_apidoc_rst_to_myst(content)[source]¶
Convert
sphinx-apidocRST to MyST markdown with{eval-rst}blocks.
- click_extra.convert_directory(directory)[source]¶
Convert all Python files in a directory from reST to MyST docstrings.
- click_extra.convert_rst_files_in_directory(directory)[source]¶
Convert
sphinx-apidocRST files to MyST markdown in the given directory.For each
.rstfile containing.. automodule::directives:If a
.mdfile with the same stem exists, delete the.rst(the existing markdown takes precedence).Otherwise, convert the RST content to MyST and write a
.mdfile, then delete the.rst.
- 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 throughconvert_comment_blocks(). Everything outside docstrings and comments passes through byte-for-byte.- Return type:
- click_extra.corner_header(rows, columns)[source]¶
Name both axes of a two-axis table in its top-left header cell.
rowssays what the first column lists, read downward, andcolumnswhat the other headers list, read rightward:corner_header("City", "Month")returnsCity ā“ \ Month ā.- Return type:
- click_extra.culprit_function(tb, package)[source]¶
The name of the innermost function of
packagein 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:
- click_extra.custom_version_option(callback, *param_decls, **kwargs)[source]¶
Add a
--versionoption whose output is produced bycallback.This is the customizable companion to
version_option(). Whereversion_option()is intentionally limited to a fixed message and a small set of values, this option callscallbackto build the whole string to print. Use it when you need values thatversion_option()does not expose, such as a file path, the Python version, or git metadata.- Parameters:
- 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
paramsargument, 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,
dictpreserving 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
- click_extra.default_params(screen=None)[source]¶
Default additional options added to
@commandand@group.- Parameters:
screen (
VersionScreen|None) āa
VersionScreenfor--versionto draw in place of its one-line message. Reach it through theparamshook, binding the screen withfunctools.partialso each decorated command still gets its own fresh option instances:@group(params=partial(default_params, screen=MY_SCREEN)) def cli(): pass
- Return type:
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).
--time/--no-timeHint
--timeis placed at the top of all other eager options so all other optionsā processing time can be measured.
--config LOCATIONHint
--configis at the top so it can have a direct influence on the default behavior and value of the other options.
--no-config--validate-config LOCATION--export-config FORMAT--accessibleHint
--accessibleis placed before--colorand--table-formatso it can lower their defaults (viadefault_map) before they are resolved.
--color/--no-color--progress/--no-progress--theme--params--table-format FORMAT--verbosity LEVEL-v,--verbose-q,--quiet--debug--tree--man--help-format FORMAT--version-h,--helpAttention
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_prioritiesargument of@commandand@groupreshuffles without touching a single callback. Seeparam_priority()and click_extra#544 issue.Presentation also sorts these options into the sections
DEFAULT_OPTION_GROUPSdeclares, drawn after the commandās own options. The two orders are independent:--timeis 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_LENGTHcharacters.- Return type:
- 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"givespkg), so theconvert-to-mystcommand can run bare from a project root. The package is located under the project root or itssrc/folder, seelocate_package_root(), and assumed under the project root when it is in neither.- Parameters:
directory (
Path|None) ā The project root, holding itspyproject.tomlorsetup.cfg. Defaults to the current working directory.- Return type:
- 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.Pathwithfile_okay=False, path_type=pathlib.Path.- Return type:
- 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 tostdout.err (
bool) ā Write tostderrinstead ofstdout.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:
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, sosys.stdout.write()andprint()will still not support Unicode.Changed in version 4.0: Added the
colorparameter.Added in version 3.0: Added the
errparameter.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
--accessiblethe text is written straight to stdout viaclick.echo()instead. Outside accessibility mode (or with no active context) it defers toclick.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:
- 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,
Noneis returned. In case a file is edited directly the return value is alwaysNoneandrequire_saveandextensionare ignored.- Overloads:
text (
bytes|bytearray), editor (str|None) =None, env (Mapping[str,str] |None) =None, require_save (bool) =False, extension (str) ='.txt'ābytes|Nonetext (
str), editor (str|None) =None, env (Mapping[str,str] |None) =None, require_save (bool) =True, extension (str) ='.txt'āstr|Nonetext (
None) =None, editor (str|None) =None, env (Mapping[str,str] |None) =None, require_save (bool) =True, extension (str) ='.txt', filename (str|PathLike[str] |Iterable[str|PathLike[str]] |None) =NoneāNone
If the editor cannot be opened a
UsageErroris 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
\nas 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:
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 becomeNone.extension (
str) ā the extension to tell the editor about. This defaults to.txtbut 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. Invokeclick.fileonce per file instead if multiple files cannot be managed at once or editing the files serially is desired.
Changed in version 8.2.0:
filenamenow accepts anyIterable[str]in addition to astrif theeditorsupports editing multiple files at once.Changed in version 8.5.0:
filenameacceptsos.PathLikevalues 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
Nonewhenextendis empty or missing, so a child process inherits the environment unchanged.A
Nonevalue 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 (seeparse_envvar_flag()) counts that as activation. Same convention asclick.testing.CliRunner.invoke()ās ownenvargument, and the reasonTEnvVarsvalues are typed optional.
- 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 factsdefault_facts()puts on the version screen, joined for a CLI that would rather spend one line of its plain--versionon them than draw a screen at all:@version_option(message="{prog_name} {version} (" + env_summary() + ")").- Return type:
- 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
paramsargument, 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 withinspect.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 aclick:sourceSphinx directive). Import the schema from a real module to get its docstrings documented.
- 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.Pathwithdir_okay=False, path_type=pathlib.Path.- Return type:
- 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:
sep (
str) ā Separator used to join parent and child keys. Defaults to"_"which produces valid Python identifiers when combined withnormalize_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 asdict[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:
- click_extra.force_unicode_output()[source]¶
Switch
sys.stdoutandsys.stderrto UTF-8 when they do not speak it.Windows gives a redirected stream the encoding of its legacy code page,
cp1252on 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 aUnicodeEncodeErrorthe moment its output is piped or redirected, which is how automation runs a CLI. A narrowPYTHONIOENCODING, likeascii, 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
backslashreplaceerrors instead: an escaped character in the output is ugly, but it loses nothing and does not crash. A stream with noreconfigure(), like anio.StringIOcapture, 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:
- 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(whatclick.echoand the Click and Click Extra help formatters consult). Sphinxās runner additionally flips this one withclick.testing.CliRunner(color=True).Richās, gated by
rich.console.Console.is_terminal, which ignores the above and readsFORCE_COLOR(https://force-color.org). This is the systemrich-clickuses, andcolor=Truenever reaches it.
FORCE_COLORis the only signal common to both systems (Rich reads it directly; Click Extra recognizes it throughCOLOR_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 pinsCOLORTERM=truecolorso the branded 24-bit themes render at full depth instead of being quantized to the 256-color palette (seesupports_truecolor()). The previous environment is restored on exit, so the override never leaks beyond a single capture.
- 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
PROMPTto anyextra_envassignments 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
envvarname, plain=,defaultvalue;each variable to unset as an
option-uand itsenvvarname, after a plainenv;the programās binary name with
invoked_command, its directory plain (seehighlight_bin_name());the
-/--flags withoption; 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
-cscript 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 Doeno longer opens on a dash.A variable mapped to
Noneis oneenv_copy()removes from the childās environment, and no assignment can say that: the line then opens onenv -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.exeneeds none of it to paste back.- Parameters:
extra_env (
Mapping[str,str|None] |None) ā environment assignments to prefix it with, aNonevalue 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 passesPS C:\>;NonekeepsPROMPT, which is this platformās.
- Return type:
- Returns:
the styled prompt line.
- click_extra.format_duration(duration)[source]¶
Render an elapsed duration compactly:
2.3s,1:05, then1: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:05under an hour,1:02:03at or above.The reverse direction, parsing a human-written duration back into a
timedelta, lives inclick_extra.types(seeDuration).
- 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 withstdoutwhen the locale is something likeen_GB.UTF-8.Many scenarios are safe to write surrogates though, due to PEP 538 and PEP 540, including:
Writing to
stderr, which useserrors="backslashreplace".The system has
LANG=C.UTF-8,C, orPOSIX. Python opens stdout and stderr witherrors="surrogateescape".None of
LANG/LC_*are set. Python assumesLANG=C.UTF-8.Python is started in UTF-8 mode with
PYTHONUTF8=1or-X utf8. Python opens stdout and stderr witherrors="surrogateescape".
- 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: theContent-Typeheader is then the only thing typing the payload. The media type is matched against each formatāsmime_types, soapplication/tomlresolves toTOMLandtext/yamltoYAML.formatsrestricts and orders the candidates (the first match wins); it defaults to everyConfigFormat.Parameters are stripped, so a raw
application/yaml; charset=utf-8header 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+jsona private API answers with resolves toJSON. An exact match wins over a suffix.Returns
Nonefor a media type no format claims, which covers the generictext/plainandapplication/octet-streama server falls back to for an extension it does not recognize.- Return type:
- 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, soapp.tomlresolves toTOMLandapp.ymltoYAML.formatsrestricts and orders the candidates (the first match wins); it defaults to everyConfigFormat.- Return type:
- click_extra.format_manpage(roff, width=None)[source]¶
Typeset roff into readable terminal text, or
Noneif nothing can.Tries each
terminaltypesetter ofMAN_TYPESETTERSin turn and returns the output of the first that succeeds. ReturnsNonewhen 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--manto error.
- 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 unambiguousKiB/MiBsymbols,sifor decimal powers withkB/MB, orjedecfor binary powers with the customary but impreciseKB/MB.precision (
int) ā Number of fractional digits for every unit above bytes. A byte count is always rendered as a whole number.
- Return type:
- 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 toTruethen 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:
- 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_HOMEasks every tool to keep its cache there, macOS included. Unlikexdg_dir(), a relative value is ignored, as the XDG specification says: a cache must not move with the working directory.- Return type:
- click_extra.get_current_context(silent=False)[source]¶
Equivalent to
click.get_current_context()but casts the returnedclick.Contextobject tocloup.Context(which is safe when using cloup commands classes and decorators).
- click_extra.get_current_theme()[source]¶
Return the theme active for the current CLI invocation.
Resolution order:
The theme stored on the active Click context under
click_extra.context.THEME(set byThemeOptionfrom--theme).The process-wide fallback returned by
get_default_theme()(the dark default, or whateverpatch_click()set at process start).
Falling back through the active context (instead of reading a module attribute) keeps
--themescoped to the invocation that received it, so a second invocation in the same process starts from the default again.- Return type:
- 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-indarkpalette;patch_click()overrides it viaset_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:
- 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.
- 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()ignoreshidden. An argument has no spec, so it getsNone.
- 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_CONFIGbyConfigOptionwhen aconfig_schemais set, orNoneif no schema was configured or no configuration was loaded.
- 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.
- 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
paramsargument, 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
paramsargument, 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
paramsargument, 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/masrenders with onlymasin the active themeāsinvoked_commandstyle, 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, seeformat_cli_prompt().
- Return type:
- 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
SIGINThandler for the duration of the CLI run that callsterminate_live_processes()before re-raisingKeyboardInterrupt(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 whenctxcloses.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:
- click_extra.install_manpages(command, prog_name=None, **overrides)[source]¶
Write the command treeās man pages where
mancan find them.Targets
$XDG_DATA_HOME/man/man1when that variable is set, else~/.local/share/man/man1, expanded against theHOMEin 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 setsXDG_DATA_HOMEorHOMEfor one invocation (a test, a packaging script staging into a build root) is honored. This mirrorsinstall_carapace_spec(), whose spec directory resolves the same way.
- click_extra.invocation_color()[source]¶
The invocationās resolved color tri-state, reachable from any thread.
Prefers the pinned
ctx.colorof the calling threadās own Click context, then the process-wide mirror published by the color callbacks (publish_invocation_color()).Nonemeans auto: defer to the output streamās TTY status, exactly likectx.colorās own default.This is what makes
--no-colorreach output produced outside the main thread, like the subprocess linesclick_extra.execution.run_cli()streams throughclick_extra.logging.StreamHandler.
- click_extra.is_a_tty(stream)[source]¶
Whether
streamreports itself as an interactive terminal.Probes
isattydefensively throughgetattr(): not every stream object exposes the method (a bare buffer, an in-memory capture, a test double), and a plainstream.isatty()would raise there instead of answering ānot a terminalā.- Return type:
- click_extra.is_dumb_terminal()[source]¶
Whether
TERMnames a terminal inCOLOR_DISABLING_TERMS.Such a terminal renders neither color nor the cursor movements of an animation. Case does not matter, and an unset
TERMis no dumb terminal.- Return type:
- click_extra.is_stdout(path)[source]¶
Return
Truewhen path is the stdout sentinel-.Guards against accidentally creating a file literally named
-in the current directory.- Return type:
- 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
paramsargument, 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
klassinparams, orNone.Unlike
search_params(), this matches the exactklass(no subclasses) and tolerates duplicates: when an option is declared more than once (like an explicit@verbosity_optionstacked 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.
- 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,
0indicates 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-openon Linux does not block.locate (
bool) ā if this is set toTruethen 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:
- 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
paramsargument, 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-capableSUITE_FORMATS(sosuite.tomlparses as TOML,suite.yamlas YAML). Reading and format detection are delegated toclick_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:
- click_extra.log_report(level, headline, title, details, ctx=None)[source]¶
Log the report that
render_report()builds, and save it withsave_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.
ctxdefaults to the context of the running command.- Return type:
- 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_THEMEorNO_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 whileparamholds its built-in default.Call it from the callback of
param, once Click recorded where the value came from.- Return type:
- 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 typeobject_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
- 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:Type-aware flattening. Fields typed as
dict[str, X]are treated as opaque:flatten_config_keysstops at their boundary so the dict value is kept intact.Field metadata. Dataclass fields may carry
click_extra.config_path(a dotted TOML path like"test-matrix.replace") andclick_extra.normalize_keys(Falseto skip key normalization on the extracted value). Fields with an explicit path are extracted from the raw config before normalization and flattening.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.
NonereturnsNone.
- Parameters:
strict (
bool) ā IfTrue, raiseValueErrorwhen the config contains keys that do not match any dataclass field (after normalization and flattening).warn_unknown (
bool) ā IfTrue(andstrictisFalse), 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) ā IfFalse, skipnormalize_config_keyson the remaining config dict. Used internally when recursing into nested dataclasses whose parent opted out of normalization viaclick_extra.normalize_keys = False.
- Return type:
- 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
paramsargument, 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
paramsargument, 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 loggerregistered under thenameparameter, or creates a new one with that name if it doesnāt exist,Set the loggerās
propagateattribute toFalse,Force removal of any existing handlers and formatters attached to the logger,
Attach a new
StreamHandlerwithFormatter,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 therootlogger, 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=Falsethe 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
rootlogger. They attach their handler beside the others, for the time of a run. Seeadd_to_parser().- Parameters:
name (
str) ā ID of the logger to setup. Defaults to the name of Pythonāsrootlogger. 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āspropagateattribute. Defaults toFalse.force (
bool) ā Same as the force parameter fromlogging.basicConfig()andbasicConfig(). Defaults toTrue.kwargs ā Any other keyword parameters supported by
logging.basicConfig()andbasicConfig().
- Return type:
- 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
paramsargument, 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
paramsargument, 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-barbecomesfoo_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 reads1: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 withflatten_config_keysāsopaque_keysto 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:
Note
Click applies the same substitution in
Option._parse_declsandArgument._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
0reset (its parameter-less\x1b[mform included) empties the accumulator, so the result re-opens what text left dangling and nothing else. Escapes come back verbatim rather than folded into aStyle, 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:
- 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 theFileparam type.If
'-'is given to openstdoutorstdin, 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'-'forstdin/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.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:
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
paramsargument, 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:
title (
str), help (str), *options (Callable[[Callable[...,Any]],Callable[...,Any]]), constraint (Constraint|None) =None, hidden (bool) =FalseāCallable[[F],F]title (
str), *options (Callable[[Callable[...,Any]],Callable[...,Any]]), help (str|None) =None, constraint (Constraint|None) =None, hidden (bool) =FalseāCallable[[F],F]
The
helpargument is an optional description and can be provided either as keyword argument or as 2nd positional argument after thenameof 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_groupnow 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 theirhiddenattribute set toTrue).
- click_extra.parse_content(fmt, content)[source]¶
Parse content with a single stateless format.
INIis excluded: it needs the CLI parameter structure for type coercion and is handled byload_ini_config().ARGFILEis excluded for the same reason: it maps command-line tokens to the CLIās parameters and is handled byload_argfile_config().SQLITEis excluded too: it is a binary format, read from its file path byload_sqlite_config()instead of a text payload.PLISTparses here from its XML variant, the only one expressible as a text payload. The binary variant is read from its file path byload_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:
- 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
Durationparameter type: it accepts the same three input shapes but returnsNoneinstead of raising whenvaluematches none of them, so it suits classifying values read from files or other machine sources. UnlikeDuration, it does not collapse a zero duration toNone:parse_duration("0")istimedelta(0), letting callers tell a zero duration from an unparsable value.Noneis returned only for an empty value, a future timestamp, or a value matching no known form.- Parameters:
- Return type:
- Returns:
The parsed
timedelta(possibly zero), orNone.
- 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"istimedelta(0)), orNonefor anything that is not a friendly duration: ISO 8601 forms, calendar units (months, years), and empty or unrecognized values. Seeparse_duration()for the format-detecting umbrella.
- click_extra.parse_iso8601_duration(value)[source]¶
Parse only an ISO 8601 duration (
P7D,PT12H,P1WT6H).Returns the parsed
timedelta(possibly zero, so"PT0S"istimedelta(0)), orNonefor anything that is not an ISO 8601 duration: friendly forms, calendar (year or month) components, and empty or unrecognized values. Seeparse_duration()for the format-detecting umbrella.
- click_extra.parse_test_suite(suite_string, fmt=ConfigFormat.YAML)[source]¶
Parse a serialized test suite string into
CLITestCaseinstances.fmtselects the serialization format, one ofSUITE_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,
fmtcannot express a suite, a mapping suite omitscases, 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:
- click_extra.pass_context(func)[source]¶
Mark a callback as wanting the active
Contextas its first argument.Clickās own
click.pass_context()is typed for the baseclick.Context. A handler annotated with click-extraās enhancedContext(to reach its extra helpers likectx.print_table) therefore fails static type checking: function parameters are contravariant, soCallable[[Context], R]is not assignable where aCallable[[click.Context], R]is expected.This drop-in is typed for the enhanced
Contextand still accepts handlers typed for the baseclick.Context(a wider first parameter is allowed), so both type-check. At runtime it forwards the active context unchanged, exactly likeclick.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
--passwordoption which prompts for a password, hiding input and asking to enter the value again for confirmation.
- 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.Pathwithpath_type=pathlib.Path.- Return type:
- 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
errparameter.
- 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
UnicodeEncodeErrora non-ASCII payload triggers on Windows, where the console defaults tocp1252. For a real path, missing parent directories are created first, absorbing themkdir -pa caller would otherwise need.Note
A
sys.stdoutthat something replaced is returned as-is: Clickās test runner, the Sphinx{click:run}directive that live-renders CLI output in the docs, acontextlib.redirect_stdout()block. The replacement is where the output must go, in the encoding its owner chose. Its descriptor can point somewhere else: underCliRunner(capture="fd"), Click sends descriptors1and2to the capture, butsys.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.
- 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 tostr.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_formatis not installed.- Return type:
- 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.
headersentries carrying a column ID (ColumnSpecinstances) plug the table into the active--sort-byselection: when no explicitsort_keyis given, rows sort by the selected columns this table carries, and keep their original order when it carries none. Seecolumn_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
--coloris 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 tosorted()as thekeyargument. 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, orNonefor no limit. Defaults to themax_widthdeclared byColumnSpecheaders. Silently dropped by formats outsideWRAPPABLE_FORMATS.
- Raises:
MissingExtraError ā the renderer of
table_formatis not installed.- Return type:
- 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
paramsargument, 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--progressand--time.Clickās own progress bar is determinate, the counterpart to the indeterminate
Spinner. This thin wrapper gates its visibility on the samePROGRESSflag the spinner uses, so a single--no-progress(or--accessible, which lowers theprogressdefault) silences both, and gates its estimated-time display on--time.- Parameters:
hidden (
bool|None) ā tri-state. Left at its defaultNone, the bar follows the resolved--progressflag: hidden when the user (or--accessible) turned progress off, shown otherwise. An explicitTrueorFalseforces the bar regardless, mirroring how an explicitcolor=argument overridesctx.coloronclick.echo(). With no active context (the bar used outside a Click command) it defaults to shown.show_eta (
bool|None) ā tri-state, likehidden. Left at its defaultNone, the estimated-time-remaining display follows the--time/--no-timeflag: shown under--time, hidden otherwise (its default, or outside a command). An explicitTrueorFalseforces it, keeping a bare barās timing in step with anOperationTrailāstimer. Clickās own default isTrue.
- Return type:
ProgressBar[V]
Unlike
click.progressbar(), the bar draws onsys.stderrunlessfilesays otherwise, likeSpinnerandOperationTrail. 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 everyDEFAULT_INTERVAL, the cadence of a spinnerās frames, unlessupdate_min_stepssays otherwise. Its position still moves on every step.Note
The
--progressflag gates visibility and--timethe ETA. Color is already handled upstream: Click renders the bar throughclick.echo(), whosecolor=Noneresolves againstctx.color, so--no-color/NO_COLORstrip 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:
text (
str), default (str|None) =None, hide_input (bool) =False, confirmation_prompt (bool|str) =False, type (None) =None, value_proc (None) =None, prompt_suffix (str) =': ', show_default (bool|str) =True, err (bool) =False, show_choices (bool) =Trueāstrtext (
str), default (V|str|None) =None, hide_input (bool) =False, confirmation_prompt (bool|str) =False, type (ParamType[V,str] |type[V] |None) =None, value_proc (Callable[[str],V] |None) =None, prompt_suffix (str) =': ', show_default (bool|str) =True, err (bool) =False, show_choices (bool) =TrueāV
If the user aborts the input by sending an interrupt signal, this function will catch it and raise a
Abortexception.- 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 ofTrueto 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 tostderrinstead ofstdout, 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, ordefaultinstead of beingAny. Runtime behavior is unchanged.Changed in version 8.3.3:
show_defaultcan 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_promptcan be a custom string.Added in version 7.0: Added the
show_choicesparameter.Added in version 6.0: Added unicode support for cmd.exe on Windows.
Added in version 4.0: Added the
errparameter.
- 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
paramsargument, 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()overformats(everyConfigFormatby default), then the content is parsed withparse_content().- Raises:
ValueError ā the file name matches none of the candidate
formats.ImportError ā the matched formatās parser is not available.
- Return type:
- 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
--accessiblethe 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 voicesN\x08NA\x08AM\x08ME\x08Erather than skipping it.- Return type:
- 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
termiosandpty, neither of which Windows ships, and reaching ConPTY means a dependency. Recording a spinner this process hosts needs none of that: hand aScreenRecorderto itsstreamand 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:
args (
str|Path|None|Iterable[str|Path|None|Iterable[Iterable[str|Path|None|Iterable[TNestedArgs]]]]) ā the command line, in the nested formrun_cli()accepts.columns (
int) ā width of the terminal it is run in, in characters.rows (
int) ā height of that terminal, in characters.background (
TerminalBackground) ā chrome the recording is headed for, stated to the command the way a terminal would, seeCAPTURE_TERMINAL_HINTS.duration (
float|None) ā seconds to record before stopping the command.Nonerecords until it exits on its own.clock (
Callable[[],float]) ā what the recorder reads the time off.
- Return type:
- Returns:
the frames the terminal held, in order.
- Raises:
NotImplementedError ā on a platform with no pseudo-terminal.
OSError ā when the command cannot start.
subprocess.Popenraises aFileNotFoundErrorfor a program it cannot find, and aPermissionErrorfor 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.
- click_extra.register_theme(name, theme)[source]¶
Register a named theme in the module-level
theme_registry.
- 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:
- click_extra.render_columns_markdown_table(columns)[source]¶
Render an iterable of
ColumnSpecas a 2-column Markdown table.Output shape:
| Column | Description | | :--- | :--- | | ``Label`` | description | ...
Suitable for inlining into MyST documents via
myst_substitutionsso the Available columns reference can be auto-generated from a single source of truth.- Return type:
- click_extra.render_command_tree(command, prog_name=None, ctx=None, width=None)[source]¶
Render the hierarchy rooted at
commandas a tree with descriptions.Reuses
ctxwhen given (like the live invocation context), otherwise builds a throwaway one withresilient_parsing=True. The root line is labeled withprog_namewhen 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_commandfor the root,subcommandandaliasfor children,metavarfor operands,deprecatedfor that label), so the tree follows--themeand--color. The rail switches from box-drawing to ASCII when accessibility mode is active on the context (seeACCESSIBLE).Descriptions wrap at
width, resolved like help screens when not given (ctx.make_formatter(), honoring theterminal_widthandmax_content_widthcontext 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, underwrap --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:
- click_extra.render_help(command, help_format, prog_name=None, ctx=None, **overrides)[source]¶
Render command in one of the
HelpFormatformats.Reuses
ctxwhen given (like the live invocation context), otherwise builds a throwaway one withresilient_parsing=True, exactly likerender_manpage(). Keyword overrides are passed through toextract_command_doc(), and ignored by thecarapaceformat, which carries no version or authorship of its own.- Raises:
ValueError ā on an unknown format, listing the known ones.
- Return type:
- click_extra.render_manpage(command, prog_name=None, ctx=None, **overrides)[source]¶
Render a single commandās man page as a roff string.
Reuses
ctxwhen given (like the live invocation context), otherwise builds a throwaway one withresilient_parsing=True. Keyword overrides (version,date,manual,authors,copyright) are passed through toextract_command_doc().- Return type:
- 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 (likeweather-forecast.1).
- 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.
headersentries carrying a column ID (ColumnSpecinstances) plug the table into the active--sort-byselection: when no explicitsort_keyis given, rows sort by the selected columns this table carries, and keep their original order when it carries none. Seecolumn_sort_key()for the exact semantics.- Parameters:
sort_key (
Callable[[Sequence[str|None]],Any] |None) ā Optional callable passed tosorted()as thekeyargument. 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, orNonefor no limit. Defaults to themax_widthdeclared byColumnSpecheaders. Silently dropped by formats outsideWRAPPABLE_FORMATS.
- Return type:
- click_extra.replace_region(text, name, content, *, pad=True)[source]¶
Return
textwith the body of a<!-- name -->region swapped forcontent.Finds the
<!-- name [args] -->opening and<!-- name-end -->closing markers (the grammar ofmarker_res()) and replaces everything between them withcontent. The markers themselves are preserved, so the region round-trips: a second call with the samecontentis 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 ofclick_extra.sphinx.matrixand thepython: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 defaultTrue,contentis padded by one blank line on each side, the usual layout for a Markdown block. Set it toFalseto 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 whatmdformat-footnoterequires: 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 emptycontentcollapses to a single blank line between the markers whatever the padding.- Return type:
- click_extra.require_sibling_param(params, requester, klass)[source]¶
Return the sibling
klassparameter declared on the same command, or raise.Some options are inert on their own: they drive machinery owned by a sibling option.
--no-configand--validate-config, for instance, both depend on the--configoption (ConfigOption). This helper centralizes the lookup so every such option raises the sameRuntimeErrorwhen its required sibling is missing, naming the offending flag.
- click_extra.resolve_color_env()[source]¶
Reconcile the recognized color environment variables into a tri-state.
Reads every variable listed in
COLOR_ENVVARSby its own convention, and returns:Trueif 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.Falseif variables only refuse color.Noneif no variable casts a vote, which leaves the caller free to apply its own default (typicallyauto).
An empty value never votes: both NO_COLOR and FORCE_COLOR treat it as unset. Each family then follows its convention:
NO_COLORrefuses color whatever its value,0andfalseincluded. It never asks for color.FORCE_COLORasks for color, except for0,false,noandoff, 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
autodefault: it casts no vote.CLICOLOR_FORCE asks for color unless it is falsy, which casts no vote.
LLMrefuses color unless it is falsy, which casts no vote: it marks an AI agent, not a color preference.COLORtakes the words of--color(seeWHENandCOLOR_WHEN_ALIASES) and booleans. Any other value casts no vote.
The plural and unspaced spellings in
COLOR_ENVVARSfollow the variable they spell.A
dumborunknownTERM(seeCOLOR_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.
- click_extra.resolve_jobs(ctx, count, *, serial_at_debug=False)[source]¶
Resolve how many worker threads to use for a batch of
countitems.Returns the number of items to process in parallel;
1means run sequentially in the calling thread. This is the policy shared byrun_jobs()andrun_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
JobsOptioncount (ctx.meta[click_extra.context.JOBS]) is1or 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--jobscount (and, withserial_at_debug, the verbosity).Noneforces sequential.count (
int) ā how many items are about to be scheduled.serial_at_debug (
bool) ā when set, also collapse to sequential atDEBUGverbosity, where coherent per-worker log narration matters more than the speed-up (interleaved threads would scramble it). Off by default.
- Return type:
- click_extra.resolve_wrap_marker(marker)[source]¶
Read a
wrap_markeroption into the characters written at a fold.The one reading of the option every entry point shares: the
--wrap-markerof 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:
- 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 argsline offormat_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 byinstall_interrupt_handler()) can abort it.
Contract mirrored from
subprocess.run():returns a
subprocess.CompletedProcesswith the full capturedstdoutandstderrdecoded as UTF-8;raises
subprocess.TimeoutExpired(with the partial capture attached) when the child, or the draining of its output, outlivestimeout. The child is stopped first, and so is every descendant it left behind: on POSIX withSIGTERM, thenSIGKILLonce a grace period runs out (see_stop_timed_out_process()), sent to the process group and every group its descendants moved to when spawned withstart_new_session, to the child plus each descendant PID otherwise. Windows ends the whole process tree at once (see_kill_windows_process_tree());a
KeyboardInterruptmid-run kills the child (with the same tree, group or per-PID scope), then propagates.
The child reads from
subprocess.DEVNULLso it can never block onstdin, 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 assubprocess.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,Nonevalues dropped, and every element (Path, versions, ā¦) cast to a string; seeargs_cleanup().extra_env (
Mapping[str,str|None] |None) ā environment variables forced over the inherited environment for this call (seeenv_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.Noneinherits the callerās, which issubprocess.run()ās own default. A relativeargs[0]is resolved by the OS against this directory, not the callerās, so pass an absolute path (or a name on thePATH) when moving the child elsewhere.timeout (
float|None) ā seconds before the child is asked to stop.Nonewaits 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āslabelattribute, whichclick_extra.logging.Formatterrenders glued to the level name and styled like an invoked command (debug:mas: Warning: ...); a foreign formatter can readrecord.labelitself. 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āsstderrintostdoutso the OS interleaves both in write order. The resultāsstderris thenNone, like asubprocess.run()call withstderr=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-onCREATE_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: thetimeoutoverrun, a mid-runKeyboardInterrupt, andterminate_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 withsetsid(), like themake testrun 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 (sudoreading/dev/tty) would fail, andsudoās tty-keyed credential cache would no longer match. That costs the atomicity of a single group signal, not the reaping: thetimeoutandKeyboardInterruptpaths 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 sendsSIGTERM, for a clean exit, and walks the same tree when it sendsSIGKILL. 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 aKeyboardInterrupt. The lever there iswindows_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 tologging.INFO; lower it tologging.DEBUGfor internal probes not worth narrating.output_level (
int) ā logging level of the streamed output lines. Defaults tologging.DEBUG.log (
Logger|None) ā destination logger. Defaults to the root logger, whose level theVerbosityOptionfamily manages.
- Return type:
- 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
ConfigValidatorhooks) behind a single function yielding a single error type. It is not namedvalidate_config: that name belongs tovalidate_config(), the callback powering the--validate-configflag.Stages, in order:
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āsopaque_subtrees.Strict-check the CLI-flag-bound part against
params_template, once its dotted keys are expanded, keeping the merged result as the reportāsmerged_conf(skipped whenparams_templateisNone). A key the dataclass schema reads is left to stage 3.Schema-build the app section through the configured callable, producing the reportās
schema_instance.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. PassNoneto 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, orNone.config_validators (
Sequence[ConfigValidator]) ā Extension validators to run against opaque sub-trees.fallback_sections (
Sequence[str]) ā Legacy section names to try whenapp_nameis 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 (seewarn_unknowninmake_schema_callable()). Ignored whenschema_strictrejects 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) ā WhenTrue(default), run every stage and collect all errors. WhenFalse, the first error short-circuits the rest.
- Return type:
- Returns:
A
ValidationReport.ValidationErroris the single error type recorded by every stage; aValueErrororTypeErrorraised by the schema callable is wrapped into it.
- click_extra.run_jobs(func, items, *, jobs=None, serial_at_debug=False)[source]¶
Run
funcoveritems, parallelized per the resolved--jobscount.The worker count is taken from
jobswhen given, else resolved from the active commandāsJobsOptionvalue byresolve_jobs(), else1. 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, likemap().This is the single-task-per-item special case of
run_lanes(), which runs every item as a lane of its own. Reach forrun_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.itemsis 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.1or fewer forces sequential execution.serial_at_debug (
bool) ā forwarded toresolve_jobs()whenjobsis not given: collapse to sequential atDEBUGverbosity.
- Return type:
- Returns:
An iterator over
funcās results, in the order ofitems.
- click_extra.run_lanes(func, lanes, *, jobs=None, serial_at_debug=False)[source]¶
Run
funcover grouped items: serial within a lane, concurrent across.Each lane is an iterable of items.
funcis 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--jobscount. 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.1or fewer forces fully sequential execution.serial_at_debug (
bool) ā forwarded toresolve_jobs()whenjobsis not given: collapse to sequential atDEBUGverbosity.
- Return type:
- 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(seeclick_extra.jobs.run_jobs()): at one worker they run sequentially and lazily, soexit_on_errorcan 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 aclick_extra.spinner.Spinnerreports progress unlessshow_progressis 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;1runs 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, andcommandis 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:
- Returns:
A
collections.Counterwithtotal,skipped, andfailedkeys. A non-zerofailedcount 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), honoringclick_extra.config.schema.CONFIG_PATH_METADATA_KEYat 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.syncsorts beforeworkflow-pins.sync).Defaults are read off a pristine
schema()instance, so every field must carry a default: configuration schemas are default-complete by construction, sincemake_schema_callable()instantiates them from partial user data.- Raises:
TypeError ā when
schemais not a dataclass type.- Return type:
- click_extra.search_params(params, klass, include_subclasses=True)[source]¶
Return the one parameter of class
klassinparams, orNone.The result is typed as
klassitself, so a caller needs noisinstancecheck to use what it found.- Parameters:
- Raises:
RuntimeError ā if more than one parameter matches.
- Return type:
- click_extra.secho(message=None, file=None, nl=True, err=False, color=None, **styles)[source]¶
This function combines
echo()andstyle()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,bytesare passed directly toecho()without applying style. If you want to style bytes that represent text, callbytes.decode()first.Changed in version 8.0: A non-string
messageis converted to a string. Bytes are passed through without style applied.Added in version 2.0.
- Return type:
- click_extra.select_columns(columns, selected_ids)[source]¶
Filter and reorder
columnsaccording toselected_ids.Returns
columnsunchanged whenselected_idsis falsy (no projection). Otherwise yields the matchingColumnSpecin the orderselected_idsspecifies, SQL-SELECT-style. RaisesKeyErrorfor an unknown ID. A selection reaching here through--columnsis already checked against the registry byMultiChoice, so that guards a caller assemblingselected_idson its own.- Return type:
- click_extra.select_row(row, selected_ids, canonical_ids)[source]¶
Build a positional row by reading cells from
rowin the selection order.Falls back to
canonical_idswhenselected_idsis empty / unset, so the row preserves its canonical column order in the absence of any user selection.- Return type:
- 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 throughkwargs(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,XMLandPLISThave no null type (plistlibeven raises onNonevalues), andXMLexpects a single root mapping, so the caller is responsible for shapingdataaccordingly.INI,SQLITE,ARGFILEandPYPROJECT_TOMLhave no serializer.Note
Optional third-party serializers are imported lazily, at the point of use. Writing
TOMLuses tomlrt (the[toml]extra), unlike reading which relies on the built-intomllib.- Raises:
ValueError ā the format has no serializer.
- Return type:
- 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_FORMATSare 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 tostr, soPathand 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_keysorindentfor JSON).
- Raises:
ValueError ā If the format is not a serialization format.
- Return type:
- click_extra.set_default_theme(theme)[source]¶
Override the process-wide fallback theme.
ThemeOptionwrites its picked theme toctx.metarather 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:
- 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
paramsargument, 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
SortByOptionto a command.Forwards the positional
header_defs(ColumnSpecinstances or bare column IDs) straight to the option constructor and registers it with the same_param_memoprimitive Cloup uses, so the--sort-byoption composes with@option_groupand@constraintlike any other option decorator.Note
Hand-written instead of produced by
decorator_factory()becauseSortByOptionaccepts its column definitions as positional arguments, which conflicts with theparam_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 itsStyle. Unstyled text is yielded with an emptyStyle. 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.
- click_extra.strip_ansi(text)[source]¶
Remove every ANSI escape sequence from
text, leaving its plain text.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
Nis writtenN\x08Nand 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:
- 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)redgreenyellow(might be an orange)bluemagentacyanwhite(might be light gray)bright_blackbright_redbright_greenbright_yellowbright_bluebright_magentabright_cyanbright_whitereset(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:
Changed in version 8.5.0: All invalid color values raise
ValueError. 256-color index0is no longer ignored.Changed in version 8.0: A non-string
messageis 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, andoverlineparameters.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
paramsargument, 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
paramsargument, 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
signumto every subprocess currently running throughrun_cli().Called from the main threadās
SIGINThandler (seeinstall_interrupt_handler()) so a concurrent fan-out aborts promptly: terminating the children unblocks the worker threads parked inrun_cli(), letting the thread pool drain instead of hanging on a child that ignored the terminalās process-groupSIGINT.A child spawned with
start_new_sessionnever receives the terminalāsSIGINTat all (it left the foreground process group), so its whole group is signalled here, with the groups its descendants moved to.Defaults to
SIGTERMrather thanSIGKILLso a child still gets to clean up, notably to restore terminal state asudopassword prompt may have altered. An aborting Click Extra command follows up withSIGKILLfor a child still running after a grace period.SIGTERMgoes to a child sharing the callerās process group alone: stopping what it started is part of its own clean-up.SIGKILLcannot 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 onSIGTERMleft running. Windows has a single forced termination, which ends the whole process tree of each child whateversignumasks 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:
- 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
paramsargument, 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
paramsargument, 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 bymessage.The glyph is the one
trail_glyph()paints.- Return type:
- 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
paramsargument, 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.
- 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
VersionOptionto 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 theversiontemplate 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 leadingversionpositional conflicts with theparam_decls-first convention the factory relies on.
- click_extra.wrap_ansi(text, width)[source]¶
Wrap
texttowidthterminal 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.wrapmeasures 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.
- 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_paragraphsparameter 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
\bcharacter (\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:
Changed in version 8.4.0: Width is measured in visible characters. ANSI escape sequences in
text,initial_indent, orsubsequent_indentno 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_dirif missing. Returns the list of written paths.
- 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 appendspartsto it. An unset or empty variable falls back tofallback, the full default path the XDG spec derives from that variableās own default base, which already carries theparts. A leading~is expanded against theHOMEin 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. Passfallbackin its~form for that: a path expanded at import carries thatHOMEfor good.- Return type:
- 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
paramsargument, 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¶
click_extra.capturepackage- Submodules
click_extra.capture.htmlmoduleclick_extra.capture.presetsmoduleTerminalPaletteWindowButtonsMACOS_BUTTONSWINDOWS_BUTTONSGNOME_BUTTONSCursorShapeCursorAPPLE_ANSICAMPBELL_ANSIONE_HALF_LIGHT_ANSITANGO_ANSITerminalPresetPRESETSDEFAULT_PRESETCAPTURE_FONT_STACKCAPTURE_PALETTESresolve_palette()WINDOWS_TERMINAL_SLOTSread_palette()GENERIC_FONT_FAMILIESparse_font_stack()NO_PAINTOPAQUEWATERMARK_INKDEFAULT_BORDER_WIDTHDEFAULT_RADIUSPACKAGE_NAMEDEFAULT_WATERMARKDEFAULT_MARGINDEFAULT_PADDINGCAPTURE_BORDERSCAPTURE_SHADOWSChromeBARE_CHROME
click_extra.capture.recordingmoduleclick_extra.capture.screenshotmoduleTColumnsAUTO_COLUMNSDEFAULT_COLUMNSMIN_COLUMNSAUTO_CURSORAUTO_TRUNCATIONTRUNCATION_LABELTRUNCATION_RULEDEFAULT_TRUNCATIONAUTO_WRAP_MARKERWRAP_MARKER_LABELDEFAULT_WRAP_MARKERPROMPT_THEMESCAPTURE_TERMINAL_HINTSCAPTURE_HIDDEN_TERMINAL_VARSCaptureFormatcapture_environment()resolve_wrap_marker()parse_columns()auto_columns()prompt_line()append_prompt()capture_output()trim_lines()emphasize_ansi()render()capture()
click_extra.capture.snippetmoduleclick_extra.capture.svgmoduleTHoldTITLEBAR_HEIGHTSHADOW_BLURSHADOW_OFFSETWINDOW_PADDINGWINDOW_INSETCSS_SIDE_ANGLESTITLE_SIZEWATERMARK_SIZEWATERMARK_INSETWATERMARK_URLCELL_HEIGHTFONT_ASPECT_RATIOCELL_WIDTHLINE_HEIGHTCELL_BLEEDCELL_TOP_INSETCURSOR_THICKNESSDEFAULT_CURSOR_SHAPEBLOCK_ELEMENTSSHADE_DENSITYBRAILLE_DOTSBRAILLE_DOT_RADIUSBOX_ARMSBOX_STROKESBOX_DASHESBOX_CURVESDIM_RATIOEMPHASIS_RATIOHIDDEN_FRAME_ATTRIBUTESHIDDEN_GLYPH_ATTRIBUTESANIMATION_METADATA_REFRAME_TIMING_FUNCTIONREDUCED_MOTION_QUERYAUTO_HOLDAUTO_HOLD_SECONDS_PER_LINEAUTO_HOLD_MINAUTO_HOLD_MAXauto_hold()parse_pause()parse_hold()blend()emphasis_paint()palette_color()style_rules()cursor_cell()gradient_svg()titlebar_strip()credit_markup()watermark_svg()window_buttons()cursor_svg()column_segments()glyph_offsets()shape_runs()block_svg()braille_dots()braille_svg()box_strokes()box_svg()shape_svg()animation_digest()animation_metadata()frame_animation_css()blink_css()render_svg()
click_extra.capture.terminalmodule
click_extra.configpackageconfig_table_to_flags()ensure_config_loaded()field_docstrings()flatten_config_keys()format_from_mime()format_from_path()get_tool_config()make_schema_callable()normalize_config_keys()parse_content()read_file()run_config_validation()schema_field_infos()serialize_content()- Submodules
click_extra.config.builtinmoduleclick_extra.config.discoverymoduleclick_extra.config.exportmoduleclick_extra.config.flagsmoduleclick_extra.config.formatsmoduleConfigFormatConfigFormat.TOMLConfigFormat.YAMLConfigFormat.JSONConfigFormat.JSON5ConfigFormat.JSONCConfigFormat.HJSONConfigFormat.INIConfigFormat.XMLConfigFormat.PLISTConfigFormat.SQLITEConfigFormat.ARGFILEConfigFormat.PYPROJECT_TOMLConfigFormat.labelConfigFormat.enabledConfigFormat.patternsConfigFormat.mime_types
SQLITE_CONFIG_TABLEparse_jsonc()parse_xml()serialize_xml()parse_content()SERIALIZABLE_FORMATSserialize_content()format_from_path()format_from_mime()disabled_format_message()read_file()
click_extra.config.optionmoduleget_app_dir()CONFIG_OPTION_NAMEDEFAULT_EXCLUDED_PARAMSTHEMES_CONFIG_KEYSentinelNO_CONFIGVCSConfigOptionConfigOption.file_format_patternsConfigOption.auto_file_formatsConfigOption.show_file_patternsConfigOption.force_posixConfigOption.search_parentsConfigOption.stop_atConfigOption.cascadeConfigOption.extra_excluded_paramsConfigOption.included_paramsConfigOption.strictConfigOption.config_schemaConfigOption.schema_strictConfigOption.fallback_sectionsConfigOption.schema_warn_unknownConfigOption.config_validatorsConfigOption.apply_command_settings()ConfigOption.file_pattern_flagsConfigOption.search_pattern_flagsConfigOption.excluded_paramsConfigOption.file_patternConfigOption.default_pattern()ConfigOption.get_help_extra()ConfigOption.render_default()ConfigOption.collapse_default()ConfigOption.parse_conf()ConfigOption.read_and_parse_all_conf()ConfigOption.read_and_parse_conf()ConfigOption.load_ini_config()ConfigOption.load_argfile_config()ConfigOption.load_sqlite_config()ConfigOption.load_plist_config()ConfigOption.load_xml_config()ConfigOption.merge_default_map()ConfigOption.load_conf()ConfigOption.handle_parse_result()
NoConfigOptionValidateConfigOption
click_extra.config.schemamoduleDEFAULT_SUBCOMMANDS_KEYPREPEND_SUBCOMMANDS_KEYEXTENSION_METADATA_KEYCONFIG_PATH_METADATA_KEYNORMALIZE_KEYS_METADATA_KEYValidationErrorConfigValidatornormalize_config_keys()flatten_config_keys()get_tool_config()SchemaFieldInfofield_docstrings()schema_field_infos()make_schema_callable()ValidationReportrun_config_validation()
click_extra.config.subcommandsmodule
click_extra.markdownpackageclick_extra.sphinxpackageEXEC_DIRECTIVES_OPT_INsetup()- Submodules
click_extra.sphinx.announcementmoduleclick_extra.sphinx.changelogmoduleclick_extra.sphinx.clickmoduleRST_INDENTDEFAULT_SCREENSHOT_DIRRUN_CAPTURE_CONFIGSCREENSHOT_DIR_CONFIGSCREENSHOT_PRESET_CONFIGSCREENSHOT_SYNTAX_STYLE_CONFIGSCREENSHOT_WATERMARK_CONFIGSCREENSHOT_MARKER_STARTSCREENSHOT_MARKER_ENDregister_config()ClickDirectiveClickDirective.has_contentClickDirective.required_argumentsClickDirective.optional_argumentsClickDirective.final_argument_whitespaceClickDirective.option_specClickDirective.default_languageClickDirective.source_languageClickDirective.screenshots_sourceClickDirective.show_source_by_defaultClickDirective.show_results_by_defaultClickDirective.show_prompt_by_defaultClickDirective.runner_methodClickDirective.runner_attrClickDirective.runner_factoryClickDirective.runnerClickDirective.languageClickDirective.code_block_options()ClickDirective.show_sourceClickDirective.show_resultsClickDirective.show_promptClickDirective.evaluate()ClickDirective.render_code_block()ClickDirective.screenshotClickDirective.screenshot_backgroundClickDirective.screenshot_columnsClickDirective.resolve_animation()ClickDirective.refuse_cuts()ClickDirective.screenshot_animationClickDirective.emphasis_specClickDirective.screenshot_emphasis()ClickDirective.numbered()ClickDirective.screenshot_hold()ClickDirective.screenshot_syntax_styleClickDirective.screenshot_schemeClickDirective.screenshot_paletteClickDirective.screenshot_lines()ClickDirective.screenshot_frameClickDirective.invocationClickDirective.closed()ClickDirective.opened()ClickDirective.render_animation()ClickDirective.write_screenshot()ClickDirective.run()
SourceDirectiveRunDirectiverewrite_screenshot_regions()update_screenshot_blocks()cleanup_runner()
click_extra.sphinx.click_referencemoduleclick_extra.sphinx.click_runnermoduleclick_extra.sphinx.crosshairmoduleclick_extra.sphinx.doctreesmoduleclick_extra.sphinx.fail_on_warningsmoduleclick_extra.sphinx.linkcheckmoduleclick_extra.sphinx.manpagesmoduleclick_extra.sphinx.matrixmodulePYTHON_RELEASE_DATESSUPPORTED_CELLFORBIDDEN_CELLUNDECLARED_CELLDEFAULT_TAG_PATTERNDEFAULT_TAGS_SORTNEWEST_FIRSTOLDEST_FIRSTORDER_CHOICESPYPI_JSON_URLPYPI_TIMEOUTPOETRY_VERSION_PATTERNPOETRY_CARET_REPOETRY_TILDE_REPOETRY_WILDCARD_REPythonMatrixGrouppython_versions_released_by()parse_python_spec()memoized_history()python_matrix_groups()python_matrix_table()DependencyMatrixGroupReleasesUnreadabledependency_matrix_groups()dependency_matrix_table()EnvelopeBoundenvelope_bounds()envelope_list()MatrixDirectivesetup()rewrite_matrix_blocks()update_matrix_blocks()
click_extra.sphinx.mermaidmoduleclick_extra.sphinx.myst_docstringsmoduleclick_extra.sphinx.pythonmoduleMIRROR_MARKER_STARTMIRROR_MARKER_ENDMIRROR_SRC_MARKER_ENDPythonRunnerPythonDirectivePythonSourceDirectivePythonRunDirectivePythonRenderBaseDirectivePythonRenderDirectivePythonRenderMystDirectivePythonRenderRstDirectiverewrite_mirrors()update_mirror_blocks()rewrite_python_mirror_regions()PythonDomaincleanup_python_runner()
click_extra.sphinx.tablesmoduleclick_extra.sphinx.tabsmoduleclick_extra.sphinx.theme_docsmoduleclick_extra.sphinx.todosmoduleclick_extra.sphinx.viewcodemodule
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>_ACCESSIBLEvariable Click derives from the option itself. Its bare presence activates the mode, unless its value reads as false (seeparse_envvar_flag()). The flag and the<CLI>_ACCESSIBLEvariable outrank it: seeset_accessible(), which also says why a configuration file does not, and why it is read directly instead of being wired through the optionāsenvvar.
- 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:
ExtraOptionA pre-configured
--accessibleswitch.Turning it on (either via the flag or the
ACCESSIBLEenvironment variable) is equivalent to passing--no-color --no-progress --table-format plain, and additionally streamsecho_via_pager()output without a pager and turnsclear()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-accessiblecounterpart: to opt back out, pass the explicit--color/--table-formatyou 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
--colorand--table-formatoptions, through the contextāsdefault_map. An explicit--color/--table-formaton the command line (or in a configuration file) therefore keeps precedence over--accessible.This option is eager so it lands its defaults before
--colorand--table-formatare 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 theChainMapthatConfigOptionlayers on top ofdefault_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
--accessiblewith theACCESSIBLEenvironment variable, stores the result atACCESSIBLEfor output helpers (clear(),echo_via_pager()) to read, then lowers the--color/--progress/--table-formatdefaults when active. A CLI that never sees--accessible(norACCESSIBLE) keeps every default untouched.ACCESSIBLEis a machine-wide variable, so the command line and the variable of the option outrank it, as they do for every machine-wide variable (seemachine_envvars_apply()). The precedence is:--accessible><CLI>_ACCESSIBLE>ACCESSIBLE> configuration file > built-in default.Important
ACCESSIBLEoutranks a configuration file, where the other machine-wide variables rank below one. The mode works by lowering the defaults of other options, andparse_args()settles it from the command line and the environment before the configuration file loads, so that--helpand--versionrender 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
ACCESSIBLEenvironment variable is read here rather than wired through the optionāsenvvar. Click would otherwise list it alongside the auto-generated<CLI>_ACCESSIBLEvariable in the--paramstable, making the combined string the widest cell of the env-var column and pushing every other rowās padding out. This mirrors howColorOptionreadsNO_COLORand friends.- Return type:
- 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:
- 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
--accessiblethe text is written straight to stdout viaclick.echo()instead. Outside accessibility mode (or with no active context) it defers toclick.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:
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:
ANSI_ESCAPE_PATTERNmatches one escape sequence of any kind, in ECMA-48 syntax.strip_ansi()removes all of them from a string.ANSI_SGR_REmatches the SGR escapes that set colors and text attributes.sgr_params()andapply_sgr_codes()decode them, andopen_ansi()returns the ones a string leaves in effect.hex_to_rgb(),rgb_to_hex(),palette_to_rgb(),nearest_256()andresolve_rgb()convert a color between the forms a terminal knows: a hex string, a 24-bit RGB triplet, an index of the 256-color palette and a name of the 16 colors ofANSI_16_RGB.
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_COLORSand_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_NAMESfor 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[mis a valid, parameter-less full reset. It is captured assgr_params: the lexer ofclick_extra.pygmentscomposes 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
coloris 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.
- click_extra.ansi.hex_to_rgb(value)[source]¶
Parse a hex color (
#rrggbbor shorthand#rgb) to an RGB tuple.
- click_extra.ansi.rgb_to_hex(rgb)[source]¶
Format an
(r, g, b)tuple as a#rrggbbhex 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:
- 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_RGBtable. Indices 16-231 (the 6x6x6 color cube) and 232-255 (the grayscale ramp) are fixed by the xterm 256-color layout.
- 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 (seesupports_truecolor()), and byclick_extra.pygmentsandclick_extra.clifor the same 24-bit-to-8-bit quantization.See also
Previous implementation of full-color to 8-bit quantization.
- Return type:
- 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:
- 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 themclosing an SGR escape or the~closingESC [ 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.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[mis a full reset, and\x1b[;31mcarries a reset followed by a red foreground.
- 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 defaultresets=True) andfrom_ansi()(withresets=False).Style-setting codes add entries to state, keyed by
Stylefield names. When resets is true, the full0reset 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) and55(overline). When resets is false all of them are ignored, lettingfrom_ansi()merge escapes without wiping already-parsed codes.Unknown codes are silently skipped, like terminals do.
- Return type:
- 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
0reset (its parameter-less\x1b[mform included) empties the accumulator, so the result re-opens what text left dangling and nothing else. Escapes come back verbatim rather than folded into aStyle, 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:
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_LENGTHcharacters.- Return type:
- click_extra.bug_report.compact_frames(tb)[source]¶
A traceback as
module:line in functionentries, 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.
- 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-extraCLI, is in it too. So the frame ofcallback, the function of the command, also starts the traceback.- Return type:
- click_extra.bug_report.culprit_function(tb, package)[source]¶
The name of the innermost function of
packagein 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:
- 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:
- 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. Seemasked_value()for the values.
- 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:
- click_extra.bug_report.cli_version(ctx)[source]¶
The version of the root command, as its
--versionoption 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
Nonewhen the version cannot be found.
- click_extra.bug_report.report_form_url(url, title)[source]¶
The URL of the issue form, with
titlefilled in.The query of
urlis kept, like thetemplatethat picks the form of a GitHub repository.- Return type:
- 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_urlof the root command, withtitlefilled in. The block opens with the version of the CLI, the platform and the options of the run, then gives thedetailsof 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:
- click_extra.bug_report.save_report(report, ctx)[source]¶
Write a bug report to a new file in the
REPORTS_FOLDERof 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
Noneif the file cannot be written: the printed report then stands alone.
- click_extra.bug_report.log_report(level, headline, title, details, ctx=None)[source]¶
Log the report that
render_report()builds, and save it withsave_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.
ctxdefaults to the context of the running command.- Return type:
- click_extra.bug_report.report_unexpected_error(ctx, expt)[source]¶
End the run on an error that its command has no rule for.
An
OSErrorcomes 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 fromcli_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:
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 aParamTypethat overridesshell_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 viaCarapaceComplete.
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 appendspartsto it. An unset or empty variable falls back tofallback, the full default path the XDG spec derives from that variableās own default base, which already carries theparts. A leading~is expanded against theHOMEin 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. Passfallbackin its~form for that: a path expanded at import carries thatHOMEfor good.- Return type:
- 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_HOMEasks every tool to keep its cache there, macOS included. Unlikexdg_dir(), a relative value is ignored, as the XDG specification says: a cache must not move with the working directory.- Return type:
- class click_extra.carapace.CarapaceCompletion(flag=dict(), positional=list(), positionalany=list())[source]¶
Bases:
objectThe
completionblock of a command: per-flag and positional actions.
- class click_extra.carapace.CarapaceDocumentation(positional=list(), positionalany='')[source]¶
Bases:
objectThe
documentationblock 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.positionalholds actions, not text. This block is where the upstream schema puts that prose, indexed the same way, socarapace --styleand 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,dashanddashany: the first two would restate whatdescriptionandflagsalready say, and Click has no---separated argument family to feed the last two.
- class click_extra.carapace.CarapaceCommand(name, description='', aliases=(), hidden=False, flags=dict(), persistentflags=dict(), exclusiveflags=list(), completion=CarapaceCompletion(), documentation=CarapaceDocumentation(), commands=list())[source]¶
Bases:
objectOne node of a Carapace spec: a command and its flags, completions and subcommands, mirroring the upstream
Commandschema.Whether the command is hidden from listings (still completable).
- 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.
- 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.
- click_extra.carapace.extract_carapace_command(command, ctx, *, command_path)[source]¶
Build a
CarapaceCommandfrom a Click command and its context.The context must have been created for
command(typically viaclick.Command.make_context()withresilient_parsing=True). Subcommands are discovered dynamically and recursed into.Every option lands in the
flagsof 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. Carapacepersistentflagswould offer it after the subcommand too, where Click rejects it.command_pathis 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:
- 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
ctxwhen given (the live invocation context), otherwise builds a throwaway one withresilient_parsing=True. The returned mapping conforms to thecarapace-specschema and is ready to hand toyaml.safe_dump.- Return type:
- 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, theinvocationcommand line that produced it (when given), and a link to the documentation.- Return type:
- 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.
invocationis recorded in the header comment (seedump_carapace_spec()).- Return type:
- 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>.yamlwhen that variable is set, else~/.config/carapace/specs/<prog>.yaml, both resolved at call time byxdg_dir(): Carapace loads either on startup. Returns the path.- Return type:
- class click_extra.carapace.CarapaceComplete(cli, ctx_args, prog_name, complete_var)[source]¶
Bases:
ShellCompleteClick completion backend that emits Carapaceās value/description lines.
Registered as the
carapaceshell, so_FOO_COMPLETE=carapace_completemakes a Click CLI print completions in thevalue\tdescriptiontext format Carapaceās shell macro parses. This is the callback target of the dynamic actions emitted by_dynamic_action(); it reuses Clickās ownget_completions(), so a parameterās customshell_completeis 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_completecompletion instruction).
- source_template: ClassVar[str] = ''¶
Completion script template formatted by
source(). This must be provided by subclasses.
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
\bescape 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
prebakeits 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]ofpyproject.tomlincludes 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-suitehelp 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-directiveshelp 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-mysthelp 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
--outputpoints.A bare
-prints it instead, seeis_stdout(), throughclick.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,--accessibleandNO_COLORreach a capture, sinceinvocation_color()carries the tri-state all four of them resolve to.
- click_extra.cli_capture.resolve_capture_format(output, fragment)[source]¶
Read the capture format off
--output, and settle--fragmenton it.Both capture commands carry the pair of options, so both carry the same rejection:
--fragmentasks for the bare block of a standalone document, and only HTML has one.- Parameters:
- Return type:
- Returns:
the format to render.
- Raises:
ClickException ā on an extension no format claims, or on
--fragmentagainst anything but HTML.
- click_extra.cli_capture.capture_options(*, columns_help, default_columns=80)[source]¶
Attach every option the two capture commands share.
screenshotpictures what a command printed andsnippetpictures 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--backdropon 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
--helpprints. 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.
- 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
screenshothelp 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
snippethelp 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:
LazyGroupGroup that falls back to the
wrapsubcommand for unknown names.Known subcommands and their aliases are dispatched normally, the lazy ones included. Anything else is treated as a target script and forwarded to
wrap.lazy_subcommandsmaps command names to their import paths.Tip
lazy_subcommandsis a map of the form:{"<command-name>": "<module-name>.<command-object-name>"}
For example:
{"mycmd": "my_cli.commands.mycmd"}
A subcommand needing registration settings on top of its import path is declared with a
LazySubcommandinstead of a bare string:{"mycmd": LazySubcommand("my_cli.commands.mycmd", section=my_section)}
Every section declared that way is registered on the group here, so the help screen orders its sections as the author declared them. Waiting for each subcommand to be imported would instead order them by import, which is alphabetical and says nothing about intent.
- click_extra.cli_wrapper.patch_click(theme=None, color=True)[source]¶
Replace Clickās decorator functions with colorized variants.
Must be called before importing the target CLI module so that
@click.command()and@click.group()decorators produce colorized commands.Note
Only the decorator functions are replaced, not the class names (
click.Command,click.Group). Replacing class names would breakisinstanceandissubclasschecks in Click internals (_param_memo) and Cloupās decorator validators.Note
A decided color (anything but
None) is pinned in two places, because the two kinds of target are colorized by different routes. One built with a plain@click.command()picks up the patched decorator and therefore is a_HelpColorsMixin: the context class installed below carries the decision for it. One carrying an explicitcls=(like FlaskāsFlaskGroup) keeps its own class and a stockclick.Context, and is served by theget_helppatch further down instead. Cover a single route and the flag silently works for half the CLIs in the wild.- Parameters:
theme (
HelpTheme|None) ā Color theme to use, as the process-wide default.Nonekeeps the current default.unpatch_click()gives back the default this replaced.color (
bool|None) ā Tri-state ANSI control mirroringctx.color:Trueforces colors on,Falsestrips them, andNone(the GNUautodefault) defers to the output streamās TTY status.
- Return type:
- click_extra.cli_wrapper.unpatch_click()[source]¶
Restore Clickās original decorator functions and methods.
Reverses the changes made by
patch_click(). Useful in tests to avoid leaking global state between test cases.The process-wide default theme goes back to the one in place before the first
patch_click()call that set a theme. If no call set one, the default stays as it is, so aset_default_theme()call made while patched is kept.- Return type:
- click_extra.cli_wrapper.resolve_target(script)[source]¶
Resolve a script name to a module path and function name.
Resolution order:
console_scriptsentry points from installed packages.A local project directory: its
console_scriptsentry point is read frompyproject.toml/setup.cfgand its package is added tosys.path..pyfile path.Explicit
module:functionnotation.Bare Python module or package name.
- Return type:
- Returns:
(module_path, function_name)tuple. function_name is empty when the target should be invoked as a module or script file.- Raises:
click.ClickException ā If the script cannot be resolved.
Note
Resolving a local project directory has a side effect: the directory holding its top-level package is prepended to
sys.pathso the subsequent import succeeds. The targetās own dependencies must still be importable in the current environment.
- click_extra.cli_wrapper.invoke_target(script, module_path, function_name, args)[source]¶
Import and call the target CLI.
Reconstructs
sys.argvso Clickās argument parsing sees the targetās program name and arguments, and pins__main__.__package__so the program name Click detects is that same script name.Note
A target whose Click command is invoked without an explicit
prog_namefalls back toclick.utils._detect_program_name(), which reads__main__.__package__. That attribute states how click-extra itself was launched: under a documentation build runningpython -m sphinx, a wrapped usage line would readpython -m sphinx.flask, and underpython -m click_extrait would readpython -m click_extra.flask. Emptying it for the call pins the detection on its file-execution branch, which answers the basename ofsys.argv[0]: the script name set above.
- click_extra.cli_wrapper.resolve_target_command(script, subcommands=())[source]¶
Import SCRIPT and return its Click command object and a matching context.
Resolves SCRIPT through
resolve_target(), imports the module, then obtains the command object without running the CLI: the entry-point attribute when it is itself a command, otherwise by scanning the moduleās namespace for Click command instances (preferring groups). Optionalsubcommandsnavigate into nested groups, mirroring the path a user would type.Shared by the introspection modes of the
wrapcommand (--params,--man,--treeand--help-format) and by the man page hook of the Sphinx extension, so all describe the exact same resolved command.- Raises:
click.ClickException ā when no unambiguous Click command can be found, or a requested subcommand does not exist.
- Return type:
- click_extra.cli_wrapper.target_prog_name(script, command)[source]¶
Return the name a user would type to run SCRIPT.
Every rendering of a target is titled with this: a man pageās
.THline, a Carapace specāsname, a Markdown heading, the root of a--tree. None of them wants the string that was typed to reach the command, which is a filesystem path or a dotted import path as often as it is a command name.Three shapes, in the order they are distinguished:
A path (a separator, or a
.pysuffix): its basename, dropping that suffix.path/to/my_cli.pyis run asmy_cli, not as its own path.A dotted or colon-separated import path: the commandās own name, which Click took from the function or an explicit
name=. An import path names a module, never a binary.Anything else is a console-script name, already exactly what a user types, and beats the commandās own name when the two differ (Flaskās entry point is
flask, its group object is namedcli).
Caution
Case 2 is a best effort. A target reached as
python -m my_package.clihas no single name a user types, so the commandās own is the closest thing to one. Pass an explicitprog_nameto the underlying renderer when that is not what you want in the output.- Return type:
- click_extra.cli_wrapper.WRAP_EPILOG = "\x08\nExamples:\n\n\x08\n Run a CLI with Click Extra's colored help:\n $ click-extra wrap -- my-cli --help\n\n\x08\n Read the help of one of its subcommands:\n $ click-extra wrap -- my-cli pick --help\n\n\x08\n Report what a subcommand accepts, and where each value comes from:\n $ click-extra wrap --params -- my-cli pick\n\n\x08\n Write a shell-completion spec where its consumer looks for it:\n $ click-extra wrap --help-format carapace --install -- my-cli\n"¶
Sample invocations closing the
wraphelp screen.
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.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:
Truefor a variable asking for color,Falsefor one refusing it. Each value is read by the convention of its variable, not as a plain boolean: seeresolve_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.
autodecides from the terminal,alwaysuses the feature on any stream, andneverleaves it off. The values of--color=<WHEN>, where the feature is ANSI color, and of theliveargument ofSpinnerandOperationTrail, 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
WHENvalue.GNU
lsacceptsyes/forceforalways,no/noneforneverandtty/if-ttyforauto, alongside the three canonical spellings (seeWHEN). Click Extra mirrors that leniency but keeps the synonyms out of--helpoutput, error messages and shell completion, which only ever advertiseWHEN.
- click_extra.color.COLOR_DISABLING_TERMS = frozenset({'dumb', 'unknown'})¶
TERMvalues marking a terminal too limited for ANSI niceties.A
dumborunknownterminal 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 throughis_dumb_terminal(), which keeps the color and animation axes from drifting apart.An unset
TERMis 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
TERMnames a terminal inCOLOR_DISABLING_TERMS.Such a terminal renders neither color nor the cursor movements of an animation. Case does not matter, and an unset
TERMis no dumb terminal.- Return type:
- click_extra.color.is_a_tty(stream)[source]¶
Whether
streamreports itself as an interactive terminal.Probes
isattydefensively throughgetattr(): not every stream object exposes the method (a bare buffer, an in-memory capture, a test double), and a plainstream.isatty()would raise there instead of answering ānot a terminalā.- Return type:
- click_extra.color.resolve_color_env()[source]¶
Reconcile the recognized color environment variables into a tri-state.
Reads every variable listed in
COLOR_ENVVARSby its own convention, and returns:Trueif 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.Falseif variables only refuse color.Noneif no variable casts a vote, which leaves the caller free to apply its own default (typicallyauto).
An empty value never votes: both NO_COLOR and FORCE_COLOR treat it as unset. Each family then follows its convention:
NO_COLORrefuses color whatever its value,0andfalseincluded. It never asks for color.FORCE_COLORasks for color, except for0,false,noandoff, 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
autodefault: it casts no vote.CLICOLOR_FORCE asks for color unless it is falsy, which casts no vote.
LLMrefuses color unless it is falsy, which casts no vote: it marks an AI agent, not a color preference.COLORtakes the words of--color(seeWHENandCOLOR_WHEN_ALIASES) and booleans. Any other value casts no vote.
The plural and unspaced spellings in
COLOR_ENVVARSfollow the variable they spell.A
dumborunknownTERM(seeCOLOR_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.
- 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(whatclick.echoand the Click and Click Extra help formatters consult). Sphinxās runner additionally flips this one withclick.testing.CliRunner(color=True).Richās, gated by
rich.console.Console.is_terminal, which ignores the above and readsFORCE_COLOR(https://force-color.org). This is the systemrich-clickuses, andcolor=Truenever reaches it.
FORCE_COLORis the only signal common to both systems (Rich reads it directly; Click Extra recognizes it throughCOLOR_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 pinsCOLORTERM=truecolorso the branded 24-bit themes render at full depth instead of being quantized to the 256-color palette (seesupports_truecolor()). The previous environment is restored on exit, so the override never leaks beyond a single capture.
- class click_extra.color.TerminalBackground(*values)[source]¶
Bases:
StrEnumShade 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: seeclick_extra.capture.presets. A capture tells the command it pictures which one it is drawn on through the same variablesresolve_background()reads, seeCAPTURE_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
lightandmanpagethemes 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
--backgroundchoice 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 ; ? BELto the terminal and reads back itsrgb:RRRR/GGGG/BBBBreply, returning the color as an 8-bit(r, g, b)tuple. ReturnsNonewhenever the query cannot run or the terminal stays silent: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 throughtermios.tcsetattr(). Because of this contention, the query is opt-in: it runs only when a caller explicitly allows it (seeresolve_background()andThemeOptionāsquery_background).
- 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
Nonewhen none does (callers then keep their own default). Precedence, highest first:CLITHEMEā the cli-theme convention. Adarkorlightvalue (optionally suffixed with a:variant) is a deliberate override and wins outright;autoand anything unrecognized fall through.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.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 onThemeOption.- Return type:
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):
shell-term-background (POSIX shell) runs the OSC query once at shell startup and caches the answer into
COLORFGBG, with term-background as its Python reader.terminal-light, termbg and terminal-colorsaurus (Rust) query OSC 10/11 live, like
query_osc_background(); the latter two also read the Windows console.
- click_extra.color.publish_invocation_color(ctx)[source]¶
Mirror
ctx.colorinto_invocation_colorfor 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, andclick_extra.context._queue_run_cleanupon the abort path: a callback raising during parameter processing leaves the context never entered, and therefore never closed. ClickāsUsageErrorholds 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.Commanddoes not depend on that timing: itsmain()runs within the_scoped_runblock that calls the cleanup as the run ends, which covers every Click Extra command. The finalizer is what carries a plainclick.commandthat merely borrows the color options.- Return type:
- click_extra.color.invocation_color()[source]¶
The invocationās resolved color tri-state, reachable from any thread.
Prefers the pinned
ctx.colorof the calling threadās own Click context, then the process-wide mirror published by the color callbacks (publish_invocation_color()).Nonemeans auto: defer to the output streamās TTY status, exactly likectx.colorās own default.This is what makes
--no-colorreach output produced outside the main thread, like the subprocess linesclick_extra.execution.run_cli()streams throughclick_extra.logging.StreamHandler.
- class click_extra.color.ColorWhenChoice(choices, case_sensitive=True)[source]¶
Bases:
Choiceclick.ChoiceoverWHENthat 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
WHENvalues reach--help, error messages and shell completion, because the publicchoicesstay canonical. Synonyms and booleans are accepted silently and normalized, so downstream code (ColorOption.set_color(),_WHEN_TO_TRISTATE) only ever seesauto,alwaysornever.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
boolonly reaches this method from a structured configuration file: TOML or JSON booleans, or YAMLās coercion ofyes/no/on/off/true/false.Truemaps toalwaysandFalsetonever, consistent with a bare--colorand--no-color. The command line always delivers strings, so this never turns--color=trueinto a valid CLI spelling.Caution
A configuration boolean therefore diverges from gitās color.ui, where
truemeansauto. Click Extra keepstrueequal toalwaysso theyesstring synonym and YAMLās coercion ofyestoTrueresolve identically across file formats.- Return type:
- 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:
ExtraOptionA pre-configured
--color[=WHEN]tri-state option.Mirrors the GNU coreutils convention:
WHENis one ofWHEN(auto,alwaysornever), and a bare--color(no value) meansalways. The negative alias--no-coloris carried by the separateNoColorOption, because Click forbids attaching/--no-xsecondary flags to a value option.The resolved tri-state lands on
ctx.color, the Click-standard attribute thatecho()reads through itsresolve_color_default()āshould_strip_ansi()chain:Truekeeps ANSI codes,Falsestrips 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
--coloris deliberately not wired to anenvvar. The color environment variables (NO_COLOR,FORCE_COLOR, ā¦) are read manually throughresolve_color_env(). Letting Click manage them would dump the wholeCOLOR_ENVVARSset into the--paramsenv-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
--colorto the next token whenever it does not look like an option, somycli --color subcommandwould consumesubcommandas 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
--colorreplays 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:
- set_color(ctx, param, value)[source]¶
Resolve
--color=<WHEN>against the environment and pinctx.color.Precedence, highest first:
An explicit
--coloron the command line.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-DEFAULTsource) therefore wins over the environment, matchingAccessibleOption.A color state already pinned by
--no-color, a forced test runner, or an explicitContext(color=...): preserved when this option only resolves toautofrom its default.The
autodefault, leavingctx.coloratNonefor 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. ANO_COLORbuild environment would then strip the output of every later CLI carrying no color option of its own.- Return type:
- 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-colorflag that forces--color=never.Click rejects
/--no-xsecondary flags on a value option, so the negative alias of the tri-stateColorOptioncannot live on it and is provided here as a standalone boolean flag. When set, it pinsctx.colortoFalse; when absent it is a no-op, leaving the resolution toColorOption.Shown on its own line directly below
--color(mirroring--no-configbelow--config), since every other negative in the default option set is visible too. Eager by default, likeColorOption, so the color state is settled before other eager options render.- set_no_color(ctx, param, value)[source]¶
Force
ctx.coloroff 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:
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:
objectRich description of a single column in a rendered table.
Three fields describe the column.
descriptiondefaults to empty, so a quick prototype does not have to write a sentence for every column:id: stable, snake_case identifier used by--columnsto address the column, to key structured-format serializations, and to thread state throughclick_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,optionalandsortable.Note
Frozen: instances are immutable, so a tuple of
ColumnSpeccan be shared as a module-level constant (likeclick_extra.show_params.ShowParamsOption.TABLE_HEADERS).- 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_tableMyST 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--columnsprojection that drops or reorders columns.
- optional: bool = False¶
Whether the column is left out of the table until
--columnsasks 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.
- click_extra.columns.render_columns_markdown_table(columns)[source]¶
Render an iterable of
ColumnSpecas a 2-column Markdown table.Output shape:
| Column | Description | | :--- | :--- | | ``Label`` | description | ...
Suitable for inlining into MyST documents via
myst_substitutionsso the Available columns reference can be auto-generated from a single source of truth.- Return type:
- click_extra.columns.select_columns(columns, selected_ids)[source]¶
Filter and reorder
columnsaccording toselected_ids.Returns
columnsunchanged whenselected_idsis falsy (no projection). Otherwise yields the matchingColumnSpecin the orderselected_idsspecifies, SQL-SELECT-style. RaisesKeyErrorfor an unknown ID. A selection reaching here through--columnsis already checked against the registry byMultiChoice, so that guards a caller assemblingselected_idson its own.- Return type:
- click_extra.columns.select_row(row, selected_ids, canonical_ids)[source]¶
Build a positional row by reading cells from
rowin the selection order.Falls back to
canonical_idswhenselected_idsis empty / unset, so the row preserves its canonical column order in the absence of any user selection.- Return type:
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 noconsole_scriptsentry point;discovering subcommands dynamically through
click.Group.list_commands()/click.Group.get_command()with a live context;honoring Clickās
\bno-rewrap marker (rendered as roff.nf/.fi);rendering boolean flags (
--foo/--no-foo) and skipping hidden commands and options;mirroring Cloup option groups as
.SSsubsections of OPTIONS (ungrouped options fall under anOther optionsheading), matching the help screen;emitting ENVIRONMENT (from auto-generated env vars), FILES (from the
--configsearch 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
2for usage errors (UsageError),1for aborts, and0on success. A real Ctrl+C ends the process bySIGINTinstead, which a shell reports as130.
- click_extra.command_doc.normalize_examples(examples)[source]¶
Validate and freeze a commandās
examplesinto(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.
Noneand an empty sequence both yield an empty tuple.
- class click_extra.command_doc.DocOptionItem(names, metavar, help, required, optional_value=False, choices=())[source]¶
Bases:
objectA single OPTIONS entry, extracted from a Click option.
- names: tuple[str, ...]¶
All literal spellings: primary
optsfollowed bysecondary_opts(so--foo/--no-fooboolean flags render both).
- metavar: str | None¶
The rendered metavar, or
Nonewhen the option takes no value (boolean flags and counters).
- 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. Seeunlisted_choicesfor the rendered subset.
- property unlisted_choices: tuple[str, ...]¶
The choices the metavar does not already spell out.
A
Choicerenders 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.
- class click_extra.command_doc.DocSubcommand(name, short_help, aliases=())[source]¶
Bases:
objectOne COMMANDS entry: a subcommand as its parent lists it.
- short_help: str¶
Its one-line description, from
full_short_help().
- class click_extra.command_doc.DocOptionGroup(options, title=None, help=None)[source]¶
Bases:
objectA 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 withtitle=None: it renders as a flat OPTIONS list with no.SSsubsection 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.Nonefor the implicit single group of an ungrouped command (no heading emitted).
- 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:
objectA whole man page in structured form, ready to render to roff.
One
CommandDocmaps to one command (or subcommand). Its fields are the man-pages(7) sections, in the order Man-page documents them. Build it withextract_command_doc()and serialize withto_roff().- synopsis_pieces: tuple[str, ...] = ()¶
Usage metavars after the command name (
[OPTIONS],CITY, ā¦).
- 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.
- 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
examplesattribute (seeclick_extra.commands.Command.examples). Empty for a command that declares none, in which case every backend omits the section entirely.
- to_markdown()[source]¶
Render the whole document as Markdown.
Same sections as
to_roff(), in the same order, minus the roff.THheader, 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:
- 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.
- click_extra.command_doc.extract_command_doc(command, ctx, *, version=None, date=None, manual=None, authors=None, copyright=None)[source]¶
Build a
CommandDocfrom a Click command and its context.The context must have been created for
command(for example viaclick.Command.make_context()withresilient_parsing=True), so that auto-generated environment-variable prefixes resolve correctly.A
version,dateorauthorsleft atNoneis resolved from the distribution metadata and the build moment, see_fill_overrides.- Return type:
- 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 ownname. Hidden commands are skipped. Each context is built withresilient_parsing=Trueto avoid triggering required-argument errors, prompts, or eager-option side effects.
- 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 aCommandDoc. 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.
- 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
ctxwhen given (like the live invocation context), otherwise builds a throwaway one withresilient_parsing=True. Keyword overrides (version,date,manual,authors,copyright) are passed through toextract_command_doc().- Return type:
- 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 (likeweather-forecast.1).
- 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_dirif missing. Returns the list of written paths.
- click_extra.command_doc.install_manpages(command, prog_name=None, **overrides)[source]¶
Write the command treeās man pages where
mancan find them.Targets
$XDG_DATA_HOME/man/man1when that variable is set, else~/.local/share/man/man1, expanded against theHOMEin 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 setsXDG_DATA_HOMEorHOMEfor one invocation (a test, a packaging script staging into a build root) is honored. This mirrorsinstall_carapace_spec(), whose spec directory resolves the same way.
- class click_extra.command_doc.HelpFormat(*values)[source]¶
Bases:
StrEnumThe formats
render_help()renders.The value is the spelling
--help-formattakes. Members are ordered alphabetically, which is also the order--help-formatadvertises them in. Adding a format is a member here, a description inHELP_FORMATSand a branch inrender_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
-fullvariants 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-fullvariants 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
mandirectory, a Carapace spec under Carapaceās. These are the two renderings that are installed rather than read, which is what letsclick-extra wrapoffer 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
HelpFormatformats.Reuses
ctxwhen given (like the live invocation context), otherwise builds a throwaway one withresilient_parsing=True, exactly likerender_manpage(). Keyword overrides are passed through toextract_command_doc(), and ignored by thecarapaceformat, which carries no version or authorship of its own.- Raises:
ValueError ā on an unknown format, listing the known ones.
- Return type:
- 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.groffis the GNU implementation found nearly everywhere a man page is;mandoccovers the BSDs and Alpine, which ship it instead.terminal: the textformat_manpage()sends to the pager for--man, read on stdin.html: the pageclick_extra.sphinx.manpagespublishes beside each man page, read from a file.mandoccomes first there: its HTML gives every section and option a semanticidanchor (#NAME,#SYNOPSIS,#configā¦), which prose can deep-link to.
Note
-P-chands-cdown togrotty, groffās terminal driver, pinning the emphasis it produces to the character-backspace pairsstrip_overstrike()removes, andread_manpage()with it under--accessible. Left to its own default agrottyrecent 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.mandocneeds no counterpart: it overstrikes already.Note
The
manbinary is deliberately not in this list, even though it is the tool being imitated. Reading roff from stdin is where the implementations diverge: GNUmantakes-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
PATHfor each program ofMAN_TYPESETTERSand skips the absent ones. Each command line starts with the programās resolved path, and its arguments are filled fromfields, likewidth.- Parameters:
mode (
str) ā theMAN_TYPESETTERSkey naming the output,terminalorhtml.- Return type:
- 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
groffandmandocwrite in whatever the locale of the platform.- Parameters:
- Raises:
subprocess.SubprocessError ā the typesetter exits with an error or outlives
timeout.OSError ā the typesetter cannot start.
- Return type:
- click_extra.command_doc.format_manpage(roff, width=None)[source]¶
Typeset roff into readable terminal text, or
Noneif nothing can.Tries each
terminaltypesetter ofMAN_TYPESETTERSin turn and returns the output of the first that succeeds. ReturnsNonewhen 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--manto error.
- click_extra.command_doc.strip_overstrike(text)[source]¶
Remove the character-backspace pairs a roff typesetter emits for emphasis.
A bold
Nis writtenN\x08Nand 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:
- 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
--accessiblethe 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 voicesN\x08NA\x08AM\x08ME\x08Erather than skipping it.- Return type:
- 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:
ExtraOptionA pre-configured
--manflag that typesets the commandās manual, pages it, and exits.Eager and value-less, like
ShowParamsOption. Part of the default option set injected bydefault_params(), so every@commandand@groupexposes it. Use@man_optionto add it to a plain Click CLI.Note
The flag is named
--man, not--show-manor--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 (BSDmdoc) or generated at build time from--helpoutput (GNUhelp2man). Click Extra already covers that build-time path withwrite_manpages(), itshelp2manequivalent.The one ecosystem that exposes a runtime flag is Perlās
Pod::Usage, whose convention is--helpfor the brief usage and bare--manfor the full manual.--manalso lines up with the neighbouring--helpand--versioninformational flags, which use bare nouns with noshow-prefix.--show-manand--man-pagehave 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
manitself 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?
- 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:
ExtraOptionA pre-configured
--help-formatoption printing the command in one of theHelpFormatformats and exiting.Eager and value-taking, unlike its
--manneighbour. That bare flag typesets the same page and sends it to the pager, where--help-format manprints its roff source. It stays a flag of its own because a runtime manual flag has its own tradition (seeManOption).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-markdownand--help-carapaceflags would widen the label column of every screen, forever, one line per format anyone ever adds. Here a new format costs aHelpFormatmember and nothing on screen.Note
The rendered output is deliberately colorless whatever
--colorsays. 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.--helpremains the colorized human view.
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 ofhelp_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
Groupand the options of aCommand, lowest first. Anything the author did not number sits on this line, so a lone{"prep": 1}promotesprepwithout displacing the rest, and a number above100demotes.Note
Priorities are floats, not integers, so a new entry can be wedged between two existing ones without renumbering:
1.5lands between1and2.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 from1.01to31.99. BASIC numbered lines with plain integers, and its10, 20, 30convention 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:
OptionGroupAn 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, whichCommandreads the same way to push click-extraās own options to the end ofparams.- Parameters:
priority (
float) ā rank of the group among the other trailing groups, lowest first. Defaults toDEFAULT_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
OptionGroupsacts 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
hiddenparameter.
- 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
ExtraOptionGroupcarries as a priority so it survives the reshufflingCommanddoes toparams.The last section gathers the options that replace the run instead of configuring it: each one prints and exits.
--timeis 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
--configends it too when a file fails to load, and would be misfiled.-h/--helpis 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
@commandand@group.- Parameters:
screen (
VersionScreen|None) āa
VersionScreenfor--versionto draw in place of its one-line message. Reach it through theparamshook, binding the screen withfunctools.partialso each decorated command still gets its own fresh option instances:@group(params=partial(default_params, screen=MY_SCREEN)) def cli(): pass
- Return type:
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).
--time/--no-timeHint
--timeis placed at the top of all other eager options so all other optionsā processing time can be measured.
--config LOCATIONHint
--configis at the top so it can have a direct influence on the default behavior and value of the other options.
--no-config--validate-config LOCATION--export-config FORMAT--accessibleHint
--accessibleis placed before--colorand--table-formatso it can lower their defaults (viadefault_map) before they are resolved.
--color/--no-color--progress/--no-progress--theme--params--table-format FORMAT--verbosity LEVEL-v,--verbose-q,--quiet--debug--tree--man--help-format FORMAT--version-h,--helpAttention
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_prioritiesargument of@commandand@groupreshuffles without touching a single callback. Seeparam_priority()and click_extra#544 issue.Presentation also sorts these options into the sections
DEFAULT_OPTION_GROUPSdeclares, drawn after the commandās own options. The two orders are independent:--timeis 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
getoptsemantics),Contextforcesallow_interspersed_argstoFalseso option parsing stops at the first positional argument.
- class click_extra.commands.Context(*args, meta=None, sort_subcommands=None, **kwargs)[source]¶
Bases:
ContextLike
cloup.Context, but with the ability to populate the contextāsmetaproperty at instantiation.Also pre-seeds
colorfor root contexts (those without a parent) from the color environment variables, so the eager help and version screens honorFORCE_COLOR,NO_COLORand their siblings (seeresolve_color_env()). With none of them set,colorstays at ClickāsNonedefault, which auto-detects a TTY. Child contexts inherit the color of their parent, as Click does.When the
POSIXLY_CORRECTenvironment variable is set, this context forcesallow_interspersed_argstoFalseso option parsing stops at the first positional argument, as GNU getopt-based tools do. SeePOSIXLY_CORRECT_ENVVAR.Carries the
sort_subcommandssetting read byclick_extra.commands.Group.must_sort_subcommands(), so a whole command tree can settle its subcommand listings in one place.Todo
Propose addition of
metakeyword upstream to Click.Like parentās context but with an extra
metakeyword-argument.Also pre-seed
colorfrom the color environment variables for a parentless context when the user did not provide it, and forceallow_interspersed_argstoFalsewhenPOSIXLY_CORRECTis set in the environment.- Parameters:
sort_subcommands (
bool|None) ā whether groups list their subcommands alphabetically. Inherited from the parent context when left toNone, the way Cloup inheritsalign_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(), withtable_formatandsort_keydefaulting to the values resolved by the--table-formatand--sort-byoptions (read fromTABLE_FORMATandTABLE_SORT_KEY).ctx.metais 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:
- 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 oftable_formatandsort_keyfrom the contextās sharedmeta, delegating toclick_extra.table.print_table()(which also handles ANSI translation and colorization policy).- Return type:
- 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,CommandLike
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, likehttps://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. Seeinvoke().version_fields (
dict[str,Any] |None) ā dictionary ofVersionOptiontemplate field overrides forwarded to the version option. Accepts any field fromVersionOption.template_fields(likeprog_name,version,git_branch). Lets you customize--versionoutput from the command decorator without replacing the defaultparamslist.config_strict (
bool) ā forwarded to the defaultConfigOptionāsstrictsetting: configuration keys not matching any CLI parameter raise an error instead of being silently ignored. Like the otherconfig_*and*_paramsforwards, it spares you from replacing the whole defaultparamslist to customize the config option.config_cascade (
bool) ā forwarded to the defaultConfigOptionāscascadesetting: 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 defaultConfigOptionāsexcluded_paramsblocklist. Additive, unlike the option-levelexcluded_paramswhich replaces the default blocklist entirely. Items are fully-qualified parameter IDs (likemycli.mail_sources). Mutually exclusive withincluded_params.extra_keywords (
HelpKeywords|None) ā aHelpKeywordsinstance whose entries are merged into the auto-collected keyword set. Use this to inject additional strings for help screen highlighting.excluded_keywords (
HelpKeywords|None) ā aHelpKeywordsinstance 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 anExamples:section of the help screen, in the man page, and in every āhelp-format rendering. A malformed pair raisesTypeErrorhere, at command construction, rather than on the first--helpa user runs.extra_option_at_end (
bool) ā reorders all parameters attached to the command, by moving all instances ofExtraOptionat 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 toDEFAULT_PRIORITY, lowest shown first. Keys are matched against each parameterās long and short flags first, then its destination name, so the--config/--no-configpair (which shares theconfigdestination) 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 ofclickwhich 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:
auto_envvar_prefix = self.name(Click feature)Auto-generate environment variables for all options, using the command ID as prefix. The prefix is normalized to be uppercased and all non-alphanumerics replaced by underscores.
help_option_names = ("--help", "-h")(Click feature)Allow help screen to be invoked with either āhelp or -h options.
show_default = True(Click feature)Show all default values in help screen.
Additionally, these Cloup context settings are set:
align_option_groups = True(Cloup feature)Aligns option groups in help screen.
Every command carries the sections of
DEFAULT_OPTION_GROUPS, so leaving each to compute its own column width would step the help text left and right from one section to the next. Aligned, a commandās own options keep the column click-extraās widest option sets, which is what thedefault_options_*_helpfixtures ofclick_extra.pytestmatch against.show_constraints = True(Cloup feature)show_subcommand_aliases = True(Cloup feature)
Click Extra also adds its own
context_settings:show_choices = None(Click Extra feature)If set to
TrueorFalse, 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 whosepromptproperty is set.Defaults to
None, which will leave all options untouched, and let them decide of their ownshow_choicessetting.show_envvar = None(Click Extra feature)If set to
TrueorFalse, 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 ownshow_envvarsetting. The rationale being that discoverability of environment variables is enabled by the--paramsoption, 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_settingsparameter:@command( context_settings={ "show_default": False, ... } )
- report_url: str | None = None¶
URL of the issue form that a bug report links to, or
Noneto report none.Set from the
report_urlconstructor argument. Declared here so the attribute exists on every command, asinvoke()reads it off the root command.
- examples: tuple[tuple[str, str], ...] = ()¶
(description, command)pairs showing the command in use.Normalized from the
examplesconstructor argument bynormalize_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 everyHelpFormatbackend) then need no guard.
- param_priority(param)[source]¶
Priority of param in the help screen.
Defaults to
DEFAULT_PRIORITY, and is otherwise resolved againstoption_prioritiesby trying each of the parameterās flags in turn, then its destination name.Important
This orders the help screen alone. The order of
self.paramsdecides when each callback fires:click.core.iter_params_for_processingsorts 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--timeahead of everything it measures and--accessibleahead of the--colordefault 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:
- 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
ExtraOptionGroupgoes past the ungrouped section, ordered by itspriority.Important
This is the one place the section order is decided. The help screen (
format_params()), the man page and every otherHelpFormatbackend (_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--helpand 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 thehelpattribute as is. Resolution goes throughresolve_param_help()instead, the same helper the man page and every otherHelpFormatbackend reads, so an operand carries one description whatever renders it. An argument without help gets an empty string, notNone.
- format_params(ctx, formatter)[source]¶
Draw the parameter sections of the help screen.
Reimplements
cloup.OptionGroupMixin.format_paramsto honor the ordersplit_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 plainOptionsheading.- Return type:
- 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
--helpor--version).Sets the default CLIās
prog_nameto 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 calledpython -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
rootlogger, the levels the verbosity options set, and the color the color options publish. Seeclick_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:
- invoke(ctx)[source]¶
Like parentās
invoke, but prints theAborted!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: seereport_unexpected_error(). The innermost command catches it, as its context still holds the options of the run. Clickāsmain()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 thatclick-extra wrapruns.- Return type:
- make_context(info_name, args, parent=None, **extra)[source]¶
Like parentās
make_context, but seedsctx.metawith the raw arguments.A copy of the raw, pre-parsed arguments goes under
RAW_ARGS, whichprint_params()re-parses to draw the--paramstable. A root context also records the name the CLI was invoked under, asINVOCATION_NAME.See also
See
click_extra.context.RAW_ARGSfor the full rationale and the upstream-proposal notes (related: click#1279).- Return type:
- format_examples(ctx, formatter)[source]¶
Write an
Examples:section listing the commandāsexamples.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\bno-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:
- 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:
- parse_args(ctx, args)[source]¶
Like parentās
parse_argsbut with better error messages for single-dash multi-character tokens.Also settles the presentation options before delegating, so
--color,--no-color,--accessibleand--themereach the eager help and version screens regardless of their position on the command line. See_resolve_presentation_eagerly.
- 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,CommandClick Command with help colorization but no extra params.
Mixes in
_HelpColorsMixinfor keyword highlighting and usesContextfor the colorized formatter, without inheriting fromCommand(which would injectdefault_params).Watches what its run ends on, like
Command: a patched CLI runs under Clickās ownmain(), inside thewrapcommand, 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 (viapatch_click()).
- 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,GroupClick Group with help colorization but no extra params.
Same as
ColorizedCommandbut for groups.
- 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:
_InjectedCommandSynthetic subcommand that displays help for the parent group or a subcommand.
Auto-injected into every
Group. Supports nested resolution:mycli help subgroup subcmdshows the help forsubcmdwithinsubgroup.
- class click_extra.commands.Group(*args, help_command=True, sort_subcommands=None, subcommand_priorities=None, **kwargs)[source]¶
Bases:
Command,GroupLike
cloup.Group, with sane defaults and extra help screen colorization.Like
Command.__init__, but auto-injects ahelpsubcommand.- Parameters:
help_command (
bool) ā whenTrue(the default), ahelpsubcommand is automatically registered. Set toFalseto suppress it, or register your ownhelpsubcommand to override it.sort_subcommands (
bool|None) ā how subcommands sharing a priority are broken apart.Truelists them alphabetically,Falsein the order they were registered.None(the default) defers to thesort_subcommandscontext setting, then toTrue. Seemust_sort_subcommands().subcommand_priorities (
Mapping[str,float] |None) ā maps a subcommand name to its priority relative toDEFAULT_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
Groupbe instances ofCommand.That way all subcommands created from a
Groupbenefits 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
Groupproduce sub-groups that are also ofGrouptype.See: https://click.palletsprojects.com/en/stable/api/#click.Group.group_class
alias of
type
- 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 toTrue. This is the resolution order Cloup uses foralign_sections, and it is what lets a singlecontext_settings={"sort_subcommands": False}on the root group reach every subgroup below it instead of being repeated on each.- Return type:
- subcommand_priority(name)[source]¶
Priority of the name subcommand.
Defaults to
DEFAULT_PRIORITY.- Return type:
- listed_command(ctx, name)[source]¶
The command the help screen describes under name: the subcommand.
The extension point
LazyGroupoverrides 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.
- list_commands(ctx)[source]¶
Subcommand names in presentation order.
Sorted on
subcommand_prioritiesfirst, then broken apart bymust_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__appendshelpbefore any@cli.command()decorator runs, while acommands=[ā¦]constructor argument lands it after, so its natural position says nothing about the authorās intent. Mirrors whatextra_option_at_enddoes to options.
- 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 overridinglist_commands()alone leaves the help screen alphabetical: the screen is rendered from sections and never calls it. Rebuild that section fromlist_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 aSectioninstance should not have it rewritten underneath them. Priorities andsort_subcommandstherefore address the default section and the flat listings (--tree, man pages, completion specs), not the contents of an explicit section.
- class click_extra.commands.LazySubcommand(import_path, section=None, fallback_to_default_section=True, short_help=None)[source]¶
Bases:
objectDeclaration 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.- 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
Sectioninstance can be shared with eagerly-registered subcommands.
- fallback_to_default_section: bool = True¶
Whether to file the subcommand under the default section when
sectionisNone.Set to
Falseto 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:
GroupA
Groupthat 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_optionin click_extra#1332 issue.lazy_subcommandsmaps command names to their import paths.Tip
lazy_subcommandsis a map of the form:{"<command-name>": "<module-name>.<command-object-name>"}
For example:
{"mycmd": "my_cli.commands.mycmd"}
A subcommand needing registration settings on top of its import path is declared with a
LazySubcommandinstead of a bare string:{"mycmd": LazySubcommand("my_cli.commands.mycmd", section=my_section)}
Every section declared that way is registered on the group here, so the help screen orders its sections as the author declared them. Waiting for each subcommand to be imported would instead order them by import, which is alphabetical and says nothing about intent.
- lazy_subcommands: dict[str, LazySubcommand]¶
- listed_command(ctx, name)[source]¶
Like the parent, but describing a lazy subcommand not imported yet by the stand-in its
short_helpbuilds.
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.metakey Click Extra writes.Reserved for entries the framework owns. Downstream consumers picking their own
ctx.metakeys 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
argvslice fed to the current command.Written by
click_extra.commands.Command.make_contextso thatclick_extra.show_params.ShowParamsOptioncan re-parse the original arguments for the--paramstable without re-running the callbacks. Consumers normalize the parserāsUNSETsentinel back toNoneon read, matching whatclick.Command.parse_argsdoes forctx.params.Todo
Open a narrowly-scoped Click issue and PR for a public
click.Contextaccessor 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--paramstable and the configuration dump. Theclick-extra wrap --paramspath 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.mdunder ā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_contexton the root context only (ctx.metais shared down the whole hierarchy, so a subcommand must not overwrite it). Equals Clickās rootinfo_name: the entry-point script name, the symlink name inmulticallpersonality mode, or an explicitprog_nameoverride passed tomain(). Read it withclick.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_confafter a configuration file is found and parsed.Noneif 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 byclick_extra.commands.Group(for subcommand inheritance) and byclick_extra.cli_wrapper.invoke_target()(to forward the loaded config to wrapped CLIs).With
cascade=Truethis 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_confas 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 whencascade=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 aconfig_schemais set. Read viaclick_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 ofctx.command_pathstrings. Thismetadict 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_subcommandstwice.
- click_extra.context.VERBOSITY_LEVEL: Final[str] = 'click_extra.verbosity_level'¶
The reconciled
LogLevelchosen for the run.Written by
_VerbosityOption.apply_verbosity, which reconciles every verbosity-related option (--verbosity,--verbose/-vand--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 LEVELas the user passed it.Written by
click_extra.logging.VerbosityOption.set_level(). Stored alongsideVERBOSITY_LEVELso downstream code can tell whether the final level came from--verbosityor from-v/-qrepetitions.
- click_extra.context.DEBUG: Final[str] = 'click_extra.debug'¶
Whether
--debugwas passed.Written by the
set_levelcallback ofclick_extra.logging.DebugOption. Read by_VerbosityOption.resolve_level, which answers it before anything else:--debugnames 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_levelcallback ofclick_extra.logging.VerboseOption. Combined withQUIETinto the signedverbose - quietcounter that_VerbosityOption.resolve_levelshifts the base level by.
- click_extra.context.QUIET: Final[str] = 'click_extra.quiet'¶
Raw repetition count of
--quiet/-q.Written by the
set_levelcallback ofclick_extra.logging.QuietOption. The quiet counterpart ofVERBOSE: each-qsubtracts one step from theverbose - quietnet 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--timeis 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
TableFormatchosen via--table-format.Written by
click_extra.table_options.TableFormatOption.init_formatter. Read byrender_table()andprint_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-byselection.Written by
click_extra.table_options.SortByOption.init_sortwhen its column definitions are known at declaration time (labeled mode). Read byrender_table()andprint_table()as their defaultsort_key. Absent in field-vocabulary mode, where the sort is resolved per table byclick_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 (likeclick_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
HelpThemeactive for this invocation.Written by
click_extra.theme.ThemeOption.set_theme. Read viaclick_extra.theme.get_current_theme(), which falls back toclick_extra.theme.default_themewhen 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.ConfigOptionwhen it sees[tool.<cli>.themes.<name>]tables: each table is built into aHelpTheme(cascading on top of an existing theme when name matches one already intheme_registry). Read byclick_extra.theme.get_theme_registry()so--themecan pick the new themes without leaking them into sibling invocations sharing the same process.
- click_extra.context.TELEMETRY: Final[str] = 'click_extra.telemetry'¶
Trueif the user opted into telemetry,Falseotherwise.Written by
click_extra.telemetry.TelemetryOption.set_telemetryafter reconciling--telemetry/--no-telemetrywith the standardDO_NOT_TRACKenvironment variable. Downstream code reads this to decide whether to emit usage data.
- click_extra.context.PROGRESS: Final[str] = 'click_extra.progress'¶
Truewhen the CLI may display progress spinners,Falseotherwise.Written by
click_extra.spinner.ProgressOption.set_progressfrom the--progress/--no-progressflag (which--accessiblelowers toFalse).Spinner,OperationTrailandprogressbar()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. SeeProgressOptionfor the rationale.
- click_extra.context.ACCESSIBLE: Final[str] = 'click_extra.accessible'¶
Truewhen the user requested screen-reader-friendly output.Written by
set_accessible()after reconciling the--accessibleflag with theACCESSIBLEenvironment variable. Read by output helpers that must degrade a cursor-driven element to a linear stream:clear()becomes a no-op andecho_via_pager()writes its text straight to stdout instead of spawning a pager.This is the readable counterpart to the
--color/--progress/--table-formatdefaults that--accessiblealso 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'¶
Truewhen 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 return0as long as the run itself succeeded.
- click_extra.context.pass_context(func)[source]¶
Mark a callback as wanting the active
Contextas its first argument.Clickās own
click.pass_context()is typed for the baseclick.Context. A handler annotated with click-extraās enhancedContext(to reach its extra helpers likectx.print_table) therefore fails static type checking: function parameters are contravariant, soCallable[[Context], R]is not assignable where aCallable[[click.Context], R]is expected.This drop-in is typed for the enhanced
Contextand still accepts handlers typed for the baseclick.Context(a wider first parameter is allowed), so both type-check. At runtime it forwards the active context unchanged, exactly likeclick.pass_context().- Return type:
Callable[P,R]
- click_extra.context.get(ctx, key, default=None)[source]¶
Read
keyfrom the current contextās sharedmetadict.Equivalent to
ctx.meta.get(key, default). Clickāsmetais 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:
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:
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 (
clsis aclick.Commandsubclass) report the resulting command class, while parameter-style decorators (clsis aclick.Parametersubclass, or absent) return the decorated callback unchanged. Both overloads model the optional-parenthesis behaviour added byallow_missing_parenthesis, which plain inference cannot recover. SeeCommandDecoratorandParameterDecoratorfor the produced shapes.Attention
The
clsargument passed to the factory is used as the reference class from which the produced decoratorāsclsargument must inherit.That way the
@commanddecorator re-implemented by Click Extra always produces a subclass ofCommand, even when the user overrides theclsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
VersionOptionto 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 theversiontemplate 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 leadingversionpositional conflicts with theparam_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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
paramsargument, 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
SortByOptionto a command.Forwards the positional
header_defs(ColumnSpecinstances or bare column IDs) straight to the option constructor and registers it with the same_param_memoprimitive Cloup uses, so the--sort-byoption composes with@option_groupand@constraintlike any other option decorator.Note
Hand-written instead of produced by
decorator_factory()becauseSortByOptionaccepts its column definitions as positional arguments, which conflicts with theparam_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 spellingsBOOLEAN_STATESlists, 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, seeresolve_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:
- 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_THEMEorNO_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 whileparamholds its built-in default.Call it from the callback of
param, once Click recorded where the value came from.- Return type:
- 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:
- 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.
Nonevalues are ignored.Variable names are deduplicated while preserving their initial order.
Caution
On Windows, environment variable names are case-insensitive, so they are normalized to uppercase as the standard library does.
Returns a tuple of strings. The result is ready to be used as the
envvarparameter for Clickās options or arguments.
- 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.
Attention
This utility does not try to reproduce the current behavior of Click, which is not consistent regarding case-handling of environment variable.
- Return type:
- 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()andclick.core.Option.resolve_envvar_value().
- 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().
- 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.environand 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.
- 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
Nonewhenextendis empty or missing, so a child process inherits the environment unchanged.A
Nonevalue 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 (seeparse_envvar_flag()) counts that as activation. Same convention asclick.testing.CliRunner.invoke()ās ownenvargument, and the reasonTEnvVarsvalues are typed optional.
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 guardtests/test_execution.pyrecognizes.- Return type:
- 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:
ExtraOptionA pre-configured option that is adding a
--time/--no-timeflag 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 viactx.exit(). That makes--timea 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) ā thetime.perf_counter()reading the run started at.- Return type:
- 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 onctx.metaunderclick_extra.context.START_TIME, and queuesprint_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:
- 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:
ExtraOptionA pre-configured
-0/--zero-exitoption 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
0as 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
metadict.Read via
click_extra.context.get(ctx, click_extra.context.ZERO_EXIT).- Return type:
- 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.Pathand other objects. Nested iterables andNonevalues are accepted as CLI arguments for convenience: they are flattened and filtered out.
- 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/masrenders with onlymasin the active themeāsinvoked_commandstyle, 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, seeformat_cli_prompt().
- Return type:
- 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
PROMPTto anyextra_envassignments 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
envvarname, plain=,defaultvalue;each variable to unset as an
option-uand itsenvvarname, after a plainenv;the programās binary name with
invoked_command, its directory plain (seehighlight_bin_name());the
-/--flags withoption; 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
-cscript 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 Doeno longer opens on a dash.A variable mapped to
Noneis oneenv_copy()removes from the childās environment, and no assignment can say that: the line then opens onenv -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.exeneeds none of it to paste back.- Parameters:
extra_env (
Mapping[str,str|None] |None) ā environment assignments to prefix it with, aNonevalue 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 passesPS C:\>;NonekeepsPROMPT, which is this platformās.
- Return type:
- Returns:
the styled prompt line.
- click_extra.execution.terminate_live_processes(signum=Signals.SIGTERM)[source]¶
Send
signumto every subprocess currently running throughrun_cli().Called from the main threadās
SIGINThandler (seeinstall_interrupt_handler()) so a concurrent fan-out aborts promptly: terminating the children unblocks the worker threads parked inrun_cli(), letting the thread pool drain instead of hanging on a child that ignored the terminalās process-groupSIGINT.A child spawned with
start_new_sessionnever receives the terminalāsSIGINTat all (it left the foreground process group), so its whole group is signalled here, with the groups its descendants moved to.Defaults to
SIGTERMrather thanSIGKILLso a child still gets to clean up, notably to restore terminal state asudopassword prompt may have altered. An aborting Click Extra command follows up withSIGKILLfor a child still running after a grace period.SIGTERMgoes to a child sharing the callerās process group alone: stopping what it started is part of its own clean-up.SIGKILLcannot 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 onSIGTERMleft running. Windows has a single forced termination, which ends the whole process tree of each child whateversignumasks 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:
- click_extra.execution.install_interrupt_handler(ctx)[source]¶
Make the first Ctrl+C terminate in-flight subprocesses, then abort as usual.
Installs a
SIGINThandler for the duration of the CLI run that callsterminate_live_processes()before re-raisingKeyboardInterrupt(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 whenctxcloses.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:
- 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 argsline offormat_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 byinstall_interrupt_handler()) can abort it.
Contract mirrored from
subprocess.run():returns a
subprocess.CompletedProcesswith the full capturedstdoutandstderrdecoded as UTF-8;raises
subprocess.TimeoutExpired(with the partial capture attached) when the child, or the draining of its output, outlivestimeout. The child is stopped first, and so is every descendant it left behind: on POSIX withSIGTERM, thenSIGKILLonce a grace period runs out (see_stop_timed_out_process()), sent to the process group and every group its descendants moved to when spawned withstart_new_session, to the child plus each descendant PID otherwise. Windows ends the whole process tree at once (see_kill_windows_process_tree());a
KeyboardInterruptmid-run kills the child (with the same tree, group or per-PID scope), then propagates.
The child reads from
subprocess.DEVNULLso it can never block onstdin, 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 assubprocess.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,Nonevalues dropped, and every element (Path, versions, ā¦) cast to a string; seeargs_cleanup().extra_env (
Mapping[str,str|None] |None) ā environment variables forced over the inherited environment for this call (seeenv_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.Noneinherits the callerās, which issubprocess.run()ās own default. A relativeargs[0]is resolved by the OS against this directory, not the callerās, so pass an absolute path (or a name on thePATH) when moving the child elsewhere.timeout (
float|None) ā seconds before the child is asked to stop.Nonewaits 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āslabelattribute, whichclick_extra.logging.Formatterrenders glued to the level name and styled like an invoked command (debug:mas: Warning: ...); a foreign formatter can readrecord.labelitself. 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āsstderrintostdoutso the OS interleaves both in write order. The resultāsstderris thenNone, like asubprocess.run()call withstderr=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-onCREATE_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: thetimeoutoverrun, a mid-runKeyboardInterrupt, andterminate_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 withsetsid(), like themake testrun 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 (sudoreading/dev/tty) would fail, andsudoās tty-keyed credential cache would no longer match. That costs the atomicity of a single group signal, not the reaping: thetimeoutandKeyboardInterruptpaths 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 sendsSIGTERM, for a clean exit, and walks the same tree when it sendsSIGKILL. 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 aKeyboardInterrupt. The lever there iswindows_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 tologging.INFO; lower it tologging.DEBUGfor internal probes not worth narrating.output_level (
int) ā logging level of the streamed output lines. Defaults tologging.DEBUG.log (
Logger|None) ā destination logger. Defaults to the root logger, whose level theVerbosityOptionfamily manages.
- Return type:
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_labelhelper; 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:
objectStructured collection of keywords extracted from a Click context for help screen highlighting.
Each field corresponds to a semantic category with its own styling.
- deprecated: set[str]¶
Markers a CLI paints with the
deprecatedslot beside Clickās own.DEPRECATED_REcovers 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.
- class click_extra.highlight.HelpFormatter(*args, **kwargs)[source]¶
Bases:
HelpFormatterExtends 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 ofThemeOption, or the process-wide default when no context is active. A plaincloup.HelpThemelends the slots it declares to that active theme, which keeps the slots cloup lacks.- keywords: HelpKeywords¶
Keywords to highlight, collected from the rendered commandās context.
Instance state, initialized per formatter:
_HelpColorsMixin.format_helpfills it before rendering, andhighlight_extra_keywords()mutates it (see theexcluded_keywordssubtraction), 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:
- 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 theinvoked_commandslot. A subcommandās path ends on a name the parent screen lists undersubcommand, and the same word in two colors across two screens reads as two different things.- Return type:
- 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 requiredclick.Choiceoperand),[json|xml|csv](an optional one) or[id,spec,value](Click Extraās multi-pickMultiChoice), and paints every known value withtheme.choice. A part that is not one is a type placeholder, like theINTEGERof a hybrid[auto|max|INTEGER], and takestheme.metavar.Shared by the help screen and by
render_command_tree(), so one operand reads the same wherever it is drawn.
- click_extra.highlight.highlight(content, patterns, styling_func, ignore_case=False)[source]¶
Highlights parts of the
contentthat matchespatterns.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Ćestring matching theStrassecontent.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:
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 unambiguousKiB/MiBsymbols,sifor decimal powers withkB/MB, orjedecfor binary powers with the customary but impreciseKB/MB.precision (
int) ā Number of fractional digits for every unit above bytes. A byte count is always rendered as a whole number.
- Return type:
- 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, then1: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:05under an hour,1:02:03at or above.The reverse direction, parsing a human-written duration back into a
timedelta, lives inclick_extra.types(seeDuration).
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
Noneif undetermined.A count of logical processors (hardware threads), resolved by
_logical_cpu_count():os.process_cpu_count()on Python 3.13+, falling back toos.cpu_count()on older runtimes. On a CPU with simultaneous multi-threading (Intel Hyper-Threading, AMD SMT) a 4-physical-core chip reports8. It is therefore not a count of physical cores, and is usually larger than what physical-core tools report, such aspsutil.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_COUNTminus 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
1and 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:
ParamTypeParse a
--jobsvalue: an integer or theauto/maxkeyword.Resolves the symbolic keywords against the hostās logical CPU count (
CPU_COUNT), counting hardware threads, not physical cores:autoresolves toDEFAULT_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.maxresolves toCPU_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 plainint, so consumers never have to know about the keywords.- choices = ('auto', 'max')¶
Symbolic keywords accepted besides an integer count, in render order.
Exposed as
choicesso the help colorizer highlights them likeclick.Choicevalues: the keyword collector duck-types on this attribute (see thegetattr(param.type, "choices", ...)branch in_HelpColorsMixin._collect_params). It is also the single source of truth reused byget_metavar()andconvert(), so the metavar and the parser never drift apart.
- get_metavar(param, ctx)[source]¶
Render
[auto|max|INTEGER](brackets included, asChoicedoes).- Return type:
- 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:
- shell_complete(ctx, param, incomplete)[source]¶
Suggest the
auto/maxkeywords; 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, yetconvert()still accepts one.- Return type:
- 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:
ExtraOptionA pre-configured
--jobsoption 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) andmax(every available logical CPU core). A value of0disables 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/maxresolve to a single job andJobCountlogs 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
intinctx.meta[click_extra.context.JOBS].Warning
JobsOptiononly resolves and publishes the job count: it does not drive any concurrency by itself. Pass it torun_jobs()(which reads the resolvedctx.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.
JobCounthas already resolved anyauto/maxkeyword to an integer by the time this runs. A value of0disables parallelism: it is rounded up to1(sequential execution) with a warning. Negative values are likewise clamped to1. A count above the available cores is honored: the pool is aThreadPoolExecutor, 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:
- click_extra.jobs.resolve_jobs(ctx, count, *, serial_at_debug=False)[source]¶
Resolve how many worker threads to use for a batch of
countitems.Returns the number of items to process in parallel;
1means run sequentially in the calling thread. This is the policy shared byrun_jobs()andrun_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
JobsOptioncount (ctx.meta[click_extra.context.JOBS]) is1or 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--jobscount (and, withserial_at_debug, the verbosity).Noneforces sequential.count (
int) ā how many items are about to be scheduled.serial_at_debug (
bool) ā when set, also collapse to sequential atDEBUGverbosity, where coherent per-worker log narration matters more than the speed-up (interleaved threads would scramble it). Off by default.
- Return type:
- click_extra.jobs.run_jobs(func, items, *, jobs=None, serial_at_debug=False)[source]¶
Run
funcoveritems, parallelized per the resolved--jobscount.The worker count is taken from
jobswhen given, else resolved from the active commandāsJobsOptionvalue byresolve_jobs(), else1. 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, likemap().This is the single-task-per-item special case of
run_lanes(), which runs every item as a lane of its own. Reach forrun_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.itemsis 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.1or fewer forces sequential execution.serial_at_debug (
bool) ā forwarded toresolve_jobs()whenjobsis not given: collapse to sequential atDEBUGverbosity.
- Return type:
- Returns:
An iterator over
funcās results, in the order ofitems.
- click_extra.jobs.run_lanes(func, lanes, *, jobs=None, serial_at_debug=False)[source]¶
Run
funcover grouped items: serial within a lane, concurrent across.Each lane is an iterable of items.
funcis 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--jobscount. 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.1or fewer forces fully sequential execution.serial_at_debug (
bool) ā forwarded toresolve_jobs()whenjobsis not given: collapse to sequential atDEBUGverbosity.
- Return type:
- 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 themesand 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
textoccupies 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.widthanswers 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-1for it, which is every styled string. Reach for it only where a consumer reads that value back, astabulatedoes.- Parameters:
text (
str) ā the text to measure.term_program (
str|None) ā name of the terminal drawing the text, as$TERM_PROGRAMholds it. A few of them advance an emoji-presentation sequence by one column where the Unicode tables say two, and naming the terminal applieswcwidthās correction for it.Nonemeasures what the tables say.
- Return type:
- Returns:
the number of cells it occupies, never negative.
- click_extra.layout.pad_to(text, width)[source]¶
Pad
textwith blanks until it occupieswidthcells.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 leastwidthcells 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.
- click_extra.layout.center_in_rule(label, width, rule='ā', opening='[ ', closing=' ]', color='bright_black')[source]¶
One line of
widthcells:labelcentered in a rule drawn withrule.labelmay arrive already styled:cell_width()discounts its escapes, so a caller paints the label its own way and hands the whole thing over.colorpaints the rule and the two brackets, which is the half a caller cannot pre-style without knowing where they fall.A
Noneor 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
lenby one column per glyph.- Parameters:
label (
str|None) ā the text the rule is drawn around, styled or not, orNonefor an unbroken rule.width (
int) ā columns the line occupies.rule (
str) ā character the rule is drawn with.opening (
str) ā bracket written between the rule andlabel.closing (
str) ā bracket written betweenlabeland the rule.color (
str|None) ā color the rule and brackets are painted, orNoneto leave them as they are.labelis never repainted: a caller styles it itself, or leaves it in the terminalās own ink.
- Return type:
- 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. Seeis_bidirectional().
- click_extra.layout.number_lines(text, start=1, digits=0)[source]¶
Prefix each line of
textwith 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, seenumber_frames(). The widest number oftextstill fits when it has more.
- Return type:
- 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.
- click_extra.layout.is_bidirectional(text)[source]¶
Whether
textcarries 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.
- 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:
- Return type:
- 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
columnssoft-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_markercloses 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 withRULE_COLORrather 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:
- Return type:
- Returns:
one list of
(style, text, column)runs per row.
- click_extra.layout.wrap_ansi(text, width)[source]¶
Wrap
texttowidthterminal 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.wrapmeasures 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.
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
TRACEpseudo-level belowLogLevel.DEBUG(numeric value5, mirroringlogging.DEBUG - 5) so repeated-vcan surface finer-grained tracing pastDEBUG;a
SILENTpseudo-level aboveLogLevel.CRITICAL(any value abovelogging.CRITICAL) so repeated-qcan suppress every record, includingLogLevel.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:
IntEnumMapping of canonical log level names to their integer level.
Mirrors logging._nameToLevel, but:
sorted from lowest to highest verbosity,
- excludes the following levels:
NOTSET, which is considered internalWARN, whichis obsoleteFATAL, which shouldnāt be used and has been replaced by CRITICAL
- 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 therootlogger 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 ofstr.format().The default of
basicConfig(), wherelogging.basicConfig()defaults to%.
- class click_extra.logging.StreamHandler(stream=None)[source]¶
Bases:
StreamHandlerA handler to output logs to the console.
Wraps
logging.StreamHandler, but usesclick.echo()to support color printing.Only
sys.stderrorsys.stdoutare allowed as output stream, andsys.stderris 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 anOperationTrailprogress bar): the record is then printed through itsecho, 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 toclick.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-colorand keep its ANSI codes on a TTY.- Return type:
- class click_extra.logging.Formatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)[source]¶
Bases:
FormatterClick 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 orstring.Templateformatting in your format string.Changed in version 3.2: Added the
styleparameter.- 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 viaclick_extra.theme.get_current_theme().A record carrying a
labelattribute (each linerun_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 renderrecord.labelits 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
levelnameandmessageare 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:
- 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
rootlogger.This function is a wrapper around Python standard libraryās
logging.basicConfig(), but with additional parameters and tweaked defaults.It sets up the global
rootlogger, and optionally adds a file or stream handler to it.Differences in default values:
Argument
basicConfig()defaultlogging.basicConfig()defaultstyle{%format{levelname}: {message}%(levelname)s:%(name)s:%(message)sThis 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 alogging.FileHandlerbe created, using the specified filename, rather than aStreamHandler.filemode (
str) āIf filename is specified, open the file in this
mode.Defaults to
a.Use the specified format string for the handler.
Defaults to
{levelname}: {message}.datefmt (
str|None) ā Use the specified date/time format, as accepted bytime.strftime().style (
Literal['%','{','$']) āIf format is specified, use this style for the format string:
%for printf-style,{forstr.format(),$forstring.Template.
Defaults to
{.level (
int|str|None) ā Set therootlogger level to the specified level.stream (
IO[Any] |None) ā Use the specified stream to initialize theStreamHandler. Note that this argument is incompatible with filename - if both are present, aValueErroris raised.handlers (
Iterable[Handler] |None) ā If specified, this should be an iterable of already created handlers to add to therootlogger. 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, aValueErroris raised.force (
bool) ā If this argument is specified asTrue, any existing handlers attached to therootlogger 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 tologging.FileHandlerfor opening the output file.errors (
str|None) ā Optional string that specifies how encoding and decoding errors are to be handled by thelogging.FileHandler. Defaults tobackslashreplace. Note that ifNoneis specified, it will be passed as such toopen().
- Return type:
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:
stream_handler_class (
type[Handler]) ā Alogging.Handlerclass that will be used inlogging.basicConfig()to create a default stream-based handler. Defaults toStreamHandler.file_handler_class (
type[Handler]) ā Alogging.Handlerclass that will be used inlogging.basicConfig()to create a default file-based handler. Defaults tologging.FileHandler.formatter_class (
type[Formatter]) ā Alogging.Formatterclass of the formatter that will be used inlogging.basicConfig()to setup the default formatter. Defaults toFormatter.
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 loggerregistered under thenameparameter, or creates a new one with that name if it doesnāt exist,Set the loggerās
propagateattribute toFalse,Force removal of any existing handlers and formatters attached to the logger,
Attach a new
StreamHandlerwithFormatter,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 therootlogger, 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=Falsethe 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
rootlogger. They attach their handler beside the others, for the time of a run. Seeadd_to_parser().- Parameters:
name (
str) ā ID of the logger to setup. Defaults to the name of Pythonāsrootlogger. 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āspropagateattribute. Defaults toFalse.force (
bool) ā Same as the force parameter fromlogging.basicConfig()andbasicConfig(). Defaults toTrue.kwargs ā Any other keyword parameters supported by
logging.basicConfig()andbasicConfig().
- Return type:
- 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 LEVELoption 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.Loggerobject is used as it is.The name of the
rootlogger, 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
rootlogger, which the whole process shares. Whichever logger is selected, therootone gets Click Extraās handler for the time of each run of the command: seeadd_to_parser().
- 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--debugflag, 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:
-qwalks down it, repeatably.Note
It outranks
--verbosity,-vand-qalike 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.Loggerobject is used as it is.The name of the
rootlogger, 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
rootlogger, which the whole process shares. Whichever logger is selected, therootone gets Click Extraās handler for the time of each run of the command: seeadd_to_parser().
- class click_extra.logging.VerboseOption(param_decls=None, **kwargs)[source]¶
Bases:
_CounterOption--verbose/-voption to raise the log level of_VerbosityOptionby one step per repetition.Each
-vraises the verbosity by oneLogLevelstep. 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 atWARNING:-vraises the level toINFO,-vvraises the level toDEBUG,any further repetition is clamped at the loudest level, so
-vvvvvfor example resolves toDEBUG.
-vshares a single signed counter withQuietOptionās-q, so the two cancel out:-v -qleaves the level unchanged. See_VerbosityOption.resolve_levelfor 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.Loggerobject is used as it is.The name of the
rootlogger, 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
rootlogger, which the whole process shares. Whichever logger is selected, therootone gets Click Extraās handler for the time of each run of the command: seeadd_to_parser().
- class click_extra.logging.QuietOption(param_decls=None, **kwargs)[source]¶
Bases:
_CounterOption--quiet/-qoption to lower the log level of_VerbosityOptionby one step per repetition.The symmetric counterpart of
VerboseOption: where-vraises the verbosity oneLogLevelstep at a time,-qlowers it. Starting fromVerbosityOption.default(WARNINGby default):-qlowers the level toERROR,-qqlowers the level toCRITICAL,any further repetition is clamped at the quietest level, so
-qqqqqfor example resolves toCRITICAL.
-qshares a single signed counter withVerboseOptionās-v, so the two cancel out:-v -qleaves the level unchanged. See_VerbosityOption.resolve_levelfor 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.Loggerobject is used as it is.The name of the
rootlogger, 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
rootlogger, which the whole process shares. Whichever logger is selected, therootone gets Click Extraās handler for the time of each run of the command: seeadd_to_parser().
- click_extra.logging.requested_level(ctx, opts)[source]¶
The level the verbosity options of
ctx.commandwill 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.ConfigOptionrelies on it: it loads the configuration before any verbosity option applies a level, yet-qand a quieter--verbositystill silence its status lines.Returns
Nonewhen the command carries no verbosity option, or when a value does not convert: the regular parse reports that error in its turn.
click_extra.logo module¶
Terminal rendition of the Click Extra brand mark.
The mark of docs/assets/logo-square.svg is six cubes stacked three-two-one. Here
they are rebuilt as flat shaded solids, with one color per face and no outline
anywhere, and painted with half blocks, two sub-pixels to a terminal line.
Flat faces are what let one palette serve a light terminal and a dark one. An
outlined mark carries its shape in the outline, so every stroke has to out-contrast
whatever sits behind it, and the artworkās own palette spans too wide a range for
that: six of its colors vanish on white, two more on black. A flat mark carries its
shape in the difference between its three planes, which no background can touch,
leaving only the silhouette to keep its distance. That fits comfortably in the middle
of the range, which is where FACE_COLORS sits.
Caution
The markās structure is carried by color: strip the ANSI codes and it collapses
into one silhouette. VersionScreen therefore only draws
it where color reaches the output, falling back to the plain --version line
everywhere else, which is also the form machine readers parse.
- click_extra.logo.TAGLINE = 'Drop-in replacement for Click and Cloup'¶
What the project is, spelled out under the program name.
- click_extra.logo.UNIT = 2¶
Scale of the whole mark, in sub-pixels.
Every dimension is a multiple of it, so the mark is
12 * UNITcolumns wide and5 * UNITlines tall. Two is the largest that still seats the mark beside the version screenās facts inside eighty columns: 24 columns of mark, three of gutter and fifty of facts comes to 77. Three would need 89, and the screen would decline to draw itself on any standard terminal.
- click_extra.logo.LEVELS: tuple[tuple[int, int], ...] = ((0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (2, 0))¶
Each cubeās (row, column) up the pyramid, bottom row first.
Also the order
FACE_COLORSis written in, and the order the mark is painted in: a cube resting on two others has to be laid down after them.
- click_extra.logo.BRAND_HUES: tuple[int, ...] = (41, 94, 306, 279, 210, 156)¶
Each cubeās hue in degrees, in
LEVELSorder.Read off the ribbon that outlines each cubeās top face in the artwork. The mark has no per-cube hue of its own: cube one alone carries gold, green and olive across its six ribbons. So this is a reading of the artwork rather than a recovery of it. It keeps the terminal mark recognizably the same six colors people already associate with the logo, which an evenly spaced spectrum would not.
- click_extra.logo.SATURATION = 0.62¶
HLS saturation shared by every face. Vivid enough to tell six hues apart.
- click_extra.logo.PLANE_LUMINANCE: dict[str, float] = {'l': 0.13, 'r': 0.22, 't': 0.36}¶
WCAG relative luminance per plane: the lid, then the two walls.
Chosen as a band rather than per color, so every hue is equally far from both backgrounds. The floor of the band is what the mark shows against white and the ceiling what it shows against black, which is why it sits in the middle: the widest band tried reads beautifully on black and falls to 1.74:1 on white.
The 2.25:1 it leaves between a cubeās lid and its dark wall is well past what an eye needs to see a facet, and it survives every dichromacy, planes differing in luminance alone.
- click_extra.logo.FACE_COLORS: tuple[dict[str, str], ...] = ({'l': '#7F611E', 'r': '#A37B26', 't': '#CB9A30'}, {'l': '#40721B', 'r': '#519122', 't': '#66B52A'}, {'l': '#AD28A1', 'r': '#D344C6', 't': '#E17FD8'}, {'l': '#9730CC', 'r': '#AE5ED9', 't': '#C58CE4'}, {'l': '#2767A8', 'r': '#3985D0', 't': '#70A7DD'}, {'l': '#1B724F', 'r': '#229265', 't': '#2BB87F'})¶
Each cubeās three face colors, in
LEVELSorder.Derived, not picked: every entry is its cubeās
BRAND_HUEShue atSATURATION, taken to the luminance its plane declares inPLANE_LUMINANCE. Written out rather than computed at import so the palette stays greppable and a designer can hand-tune one value;test_palette_follows_its_derivationfails if a tuned value drifts off the system.Emitted as 24-bit color. The 256-color cube cannot separate all eighteen, and the usual reason to prefer it does not apply: no touching pair of faces collides there, so a terminal that downsamples still shows six distinct cubes.
- click_extra.logo.geometry()[source]¶
One cubeās dimensions, in sub-pixels.
A lid four units wide and two tall is 2:1 dimetric, and the smallest such rhombus whose half-height is a whole number, which the row pitch needs. The body matches the lidās width over two, making every box a true cube.
- click_extra.logo.LOGO_WIDTH = 24¶
Columns the mark occupies.
- click_extra.logo.LOGO_LINES = 10¶
Terminal lines the mark renders to, two sub-pixel rows making one.
- click_extra.logo.faces()[source]¶
Every visible face, bottom row first, as whole-sub-pixel polygons.
2:1 dimetric rather than the artworkās 30 degrees, and integer vertices rather than a sampled rendering, for the same reason: a 30-degree edge advances 1.732 sub-pixels per row, which no grid can hold, so it comes out as a stair of uneven treads that the eye reads as fraying. Two across for every one down tiles a square grid exactly, and every tread is then the same.
- click_extra.logo.sub_pixels()[source]¶
The mark as a grid of flat colors, hit-tested against the face polygons.
Rasterizing the mark and reading pixels back would hand the antialiaser a say in the palette: every boundary it smooths mints a color belonging to neither face, and a rendition this size comes back carrying over a hundred of them. Testing each sub-pixelās centre against the polygons keeps it to the eighteen declared, three per cube, which is what makes the edges read as steps rather than smudge.
- click_extra.logo.render_logo()[source]¶
Paint the mark into styled lines, each exactly
LOGO_WIDTHwide.A cell whose two sub-pixels carry different colors paints the top one as foreground over the bottom one as background, which is what fits two independent colors on one line. Runs of cells sharing a color pair are styled together rather than one escape sequence per character, keeping the mark from tripling in size.
Trailing blanks are kept:
VersionScreenpads a ragged logo for us, but a mark that arrives square costs it nothing to measure.Cached: the mark never changes, so it is painted on the first call that needs it and read back by every later one.
- click_extra.logo.brand_facts()[source]¶
The interpreter and platform every screen reports, plus this projectās own.
- click_extra.logo.BRAND_SCREEN = VersionScreen(logo=<functools._lru_cache_wrapper object>, tagline='Drop-in replacement for Click and Cloup', facts=<function brand_facts>, gutter=' ')¶
Click Extraās own
--versionscreen.Mounted on the
click-extraCLI, and the shape a CLI of your own would copy:from functools import partial from click_extra import group from click_extra.commands import default_params @group(params=partial(default_params, screen=BRAND_SCREEN)) def cli(): pass
Both
render_logo()andbrand_facts()are passed uncalled, so the mark is painted and the facts are read when--versionis drawn, not when this module is imported: the habit that keeps a costlier value from being charged to every invocation. The mark is then cached, since it never changes.
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-clickfor 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_cssbyAnsiColorPlugin.on_config()so every page links it, and written into the build output byAnsiColorPlugin.on_post_build().
- class click_extra.mkdocs.AnsiColorPlugin[SomeConfig: Config][source]¶
Bases:
BasePluginMkDocs plugin that adds ANSI color support to Pygments code blocks.
Monkey-patches
pymdownx.highlightās block and inline formatter classes to inherit fromAnsiHtmlFormatter. This gives every code block in the MkDocs site full ANSI color rendering: compound tokens likeToken.Ansi.Bold.Cyanare decomposed into individual CSS classes, and a generated stylesheet (written byon_post_build()and registered inextra_cssbyon_config()) supplies the color rules for the 256-color indexed palette and all SGR text attributes.When
mkdocs-clickis installed, its code-block generators are also patched to use theansi-outputlexer 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_STYLESHEETtoextra_cssmakes MkDocs link it from every page (resolving the relative path per page, including underuse_directory_urls). The file itself is written later, inon_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 inon_config()emit carry no color. Runs after the theme copied its own assets, so the file survives the site-directory cleanup.- Return type:
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:
bakereads its configuration from thebakeapp dir and theBAKE_*environment variables, the way a standalone binary would, and not from the groupāskitchennamespace.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
.exeshims, so a symlink namedbakelands inargv[0]asbake.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:
- 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:
_InjectedCommandSynthetic subcommand listing every name a
MulticallGroupanswers to.Auto-injected into every
MulticallGroup, the wayHelpCommandis injected into everyGroup: 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.
- class click_extra.multicall.MulticallGroup(*args, personalities=None, personalities_command=True, **kwargs)[source]¶
Bases:
GroupA
Groupdispatching 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:
an explicit
prog_namepassed tomain()(whatclick_extra.testing.CliRunneruses to simulate a symlink),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 trailingWINDOWS_EXE_SUFFIXis stripped for Windows console-script shims. Clickās own_detect_program_name()is deliberately not used: it reads__main__.__package__and answerspython -m ā¦in the module case. Seeclick_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, whereargv[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 toNone, every non-hidden, non-synthetic subcommand is its own personality.personalities_command (
bool) ā whenTrue(the default), apersonalitiessubcommand is auto-registered on the group, listing every invocation name the binary answers to. Register your ownpersonalitiessubcommand 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.exestripped on Windows.
- list_personalities()[source]¶
Every personality name mapped to the tokens it invokes.
The explicit
personalitiesmapping when one was declared, else every subcommand_is_default_personalityadmits, mapped to itself. The lazy subcommands of a lazy group are imported to be judged, which a listing has to pay for.
- 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:
- 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
paramsattribute is patched after the fact. Two reasons make the re-instantiation mandatory:Cloup computes its help layout (
arguments,option_groups,ungrouped_options) fromparamsinside__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_endreordering, option priorities, auto envvar population and help-keyword collection.
Every parameter is deep-copied, because
Command.__init__re-runspopulate_auto_envvarsover the merged set under the personalityās ownauto_envvar_prefix: sharing instances would rewrite the groupās and subcommandāsenvvarattributes and leak that back into group mode. This is the same class of leaky statedefault_params()warns about.- Return type:
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
--outputvalue asking for stdout instead of a file on disk.
- exception click_extra.output.MissingExtraError(extra, *, subject, package='click-extra')[source]¶
Bases:
ClickException,ImportErrorA 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 status1, with no traceback.It is an
ImportErroras 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 installcommand that installs the extra, in the wording every other optional-dependency error of the package uses.
- click_extra.output.is_stdout(path)[source]¶
Return
Truewhen path is the stdout sentinel-.Guards against accidentally creating a file literally named
-in the current directory.- Return type:
- 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
UnicodeEncodeErrora non-ASCII payload triggers on Windows, where the console defaults tocp1252. For a real path, missing parent directories are created first, absorbing themkdir -pa caller would otherwise need.Note
A
sys.stdoutthat something replaced is returned as-is: Clickās test runner, the Sphinx{click:run}directive that live-renders CLI output in the docs, acontextlib.redirect_stdout()block. The replacement is where the output must go, in the encoding its owner chose. Its descriptor can point somewhere else: underCliRunner(capture="fd"), Click sends descriptors1and2to the capture, butsys.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.
- click_extra.output.force_unicode_output()[source]¶
Switch
sys.stdoutandsys.stderrto UTF-8 when they do not speak it.Windows gives a redirected stream the encoding of its legacy code page,
cp1252on 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 aUnicodeEncodeErrorthe moment its output is piped or redirected, which is how automation runs a CLI. A narrowPYTHONIOENCODING, likeascii, 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
backslashreplaceerrors instead: an escaped character in the output is ugly, but it loses nothing and does not crash. A stream with noreconfigure(), like anio.StringIOcapture, 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:
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, lettingsearch_params(),last_param()andrequire_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 intonodes.literal.
- click_extra.param_tools.iter_inline_literals(text)[source]¶
Walk
textand yield(segment, is_literal)pairs.Split on
INLINE_LITERAL_REso the consumer can apply different rendering to the literal segments (bold for roff, aliteralnode for docutils) without re-parsing the regex.
- 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/.fipair: only the control character has to go, or it lands in the output as a stray byte.- Return type:
- click_extra.param_tools.choice_values(param_type)[source]¶
The values a
click.Choice-like type accepts, spelled as Click completes them.An
Enummember is named by itsname, asclick.Choice.normalize_choice()does before it folds case, and anything else bystr(). A type carrying nochoicesattribute, 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.
- click_extra.param_tools.search_params(params, klass, include_subclasses=True)[source]¶
Return the one parameter of class
klassinparams, orNone.The result is typed as
klassitself, so a caller needs noisinstancecheck to use what it found.- Parameters:
- Raises:
RuntimeError ā if more than one parameter matches.
- Return type:
- click_extra.param_tools.last_param(params, klass)[source]¶
Return the last parameter of exactly
klassinparams, orNone.Unlike
search_params(), this matches the exactklass(no subclasses) and tolerates duplicates: when an option is declared more than once (like an explicit@verbosity_optionstacked 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.
- click_extra.param_tools.require_sibling_param(params, requester, klass)[source]¶
Return the sibling
klassparameter declared on the same command, or raise.Some options are inert on their own: they drive machinery owned by a sibling option.
--no-configand--validate-config, for instance, both depend on the--configoption (ConfigOption). This helper centralizes the lookup so every such option raises the sameRuntimeErrorwhen its required sibling is missing, naming the offending flag.
- 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_helpwins, otherwise the first paragraph ofcommand.helpis joined into one line. A truthydeprecatedflag appends Clickās own label, so a listing reads the same marker Clickāsget_short_help_str()produces, reason string included.- Return type:
- click_extra.param_tools.resolve_param_help(param, ctx)[source]¶
Return a parameterās help text, including the dynamically-generated ones.
Reading
param.helpcovers the options that carry a static string, and misses the ones that compute their help from the context: Click Extraās own-v/-qderive theirs from the resolved base verbosity, and leave the attribute atNone(seeVerboseOption.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.
- 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-Baranswersfoo_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-Barand--FOO-BARanswer the same name, as do--foo--barand--foo__bar, and--K(the Kelvin sign,U+212A) lands on the samekas--k. Case folding reaches every script and is not length-preserving:--įŗanswersĆ, whose upper case is the two lettersSS, and a composedcafĆ©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 parameterFoo_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
Optionshould keep the case of an identifier declaration, as it does today, or fold it the wayArgumentalready does. Should Click fold both, no parameter can be namedFoo_Barany more: drop the caution above, and with it the ambiguity branch of_merge_into_templateinclick_extra.config.schema, which exists only to tell two such names apart.- Return type:
- click_extra.param_tools.param_spellings(param)[source]¶
All literal spellings of a parameter: primary
optsthensecondary_opts.A boolean flag pair yields both forms (
--foo,--no-foo); a plain option yields just its declared names.
- 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.
- 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 customflag_value(--no-config), or a counter (-v)."optional": the value may be omitted. Click models this asis_flag=Falsewith aflag_valueset, so a bare--colorstands for the flag value while--color=neverpasses an explicit one."required": consumes a value (--config LOCATION).
Note
The discriminator is Clickās
is_flag(pluscount), notis_bool_flag: a flag carrying a customflag_valuesuch asNoConfigOptionreportsis_bool_flag=Falseyet 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.Nonefor a plain option, a counter or an argument,Truefor a boolean flag, and the declared value otherwise (--colorstanding foralways).Read from Clickās
Option.flag_activation_value, not fromflag_value: Click keeps theUNSETsentinel there when no value was declared, and the sentinel stored anywhere it is read back as a value turns the flag off.- Return type:
- click_extra.param_tools.is_repeatable(param)[source]¶
Whether the parameter may be supplied several times (
multipleorcount).- Return type:
- class click_extra.param_tools.ParamStructure[source]¶
Bases:
objectUtilities 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:
ShowParamsOptionfreezes an empty set, whileConfigOptionresolves 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. Askis_excluded()about a parameter of another subcommand.
- included_params: frozenset[str] | None¶
Allowlist of parameter IDs, mutually exclusive with
excluded_params.Nonedisables the allowlist. Otherwisebuild_param_trees()walks only the subcommands an allowed ID lies under, and resolves the parameters it reaches intoexcluded_params.
- static init_tree_dict(*path, leaf=None)[source]¶
Nest one dict per key of
path, the deepest one holdingleaf.An empty
pathreturnsleafitself.- Return type:
- static get_tree_value(tree_dict, *path)[source]¶
Get in the
tree_dictthe value located at thepath.Raises
KeyErrorif no item is found at the providedpath.- Return type:
- 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
descendskips 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.
- 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
strfor unrecognised custom types, since command-line parameters are strings by default.See the list of custom types provided by Click.
- static get_param_type(param)[source]¶
Get the Python type of a Click parameter.
Returns
strfor unrecognised custom types, since command-line parameters are strings by default.A boolean flag is a
booleven 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.
- 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_paramsdoes not name it. So the answer holds for a parameter of a subcommand that the walk ofbuild_param_trees()skipped. Without an allowlist, the parameter is excluded whenexcluded_paramslists it.- Parameters:
param_id (
str) ā the fully-qualified ID of the parameter, its path keys joined withPARAM_PATH_SEP.- Return type:
- 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_paramsblocklist.With an allowlist, the tree holds only the parameters
included_paramsnames. The walk then skips each subcommand that no allowed ID lies under, so it does not import a lazy subcommand of aLazyGroupthat the allowlist leaves out. An empty allowlist walks the root command alone. The parameters the walk reaches and the allowlist leaves out becomeexcluded_params.
- 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()ignoreshidden. An argument has no spec, so it getsNone.
- 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=Trueso required-argument errors, prompts and eager-option side effects stay dormant: the canonical way to materialize aclick.Contextpurely to read a commandās structure (its parameters, env-var prefix and subcommands), shared by the man-page and Carapace exporters.
- 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 owncontext_classandcontext_settings, so the context reads like the one a real invocation gets: a subcommand setting its ownauto_envvar_prefixnames its environment variables after it, where a bareclick.Contextwould derive them from the parentās prefix. Unlikemake_resilient_context(), no parameter is processed, so a walk over a live invocation never re-runs a callback.- Return type:
- 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 toNoneis skipped, and hidden subcommands are skipped unlessskip_hiddenisFalse(completion specs keep them, flagged hidden; documentation drops them).
- 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()withmake_resilient_context(): every renderer walking a command tree (the man pages, the Markdown and JSON documents, the Carapace spec, the--treeview) descends through here, so a lazy subcommand, the orderclick.Group.list_commands()sets and a name resolving toNoneare handled the same way in all of them.Each context is built under
ctxand named after the subcommandās registration name, so itscommand_pathand its environment variable prefix are the ones a run reaches.
- 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.paramsis the processing order, which decides when each callback fires, while the help screen reads the presentation order Cloup caches inarguments,option_groupsandungrouped_options, sectioned byclick_extra.commands.Command.split_option_groups()and sorted within a section byparam_priority(). Readingget_params()therefore renders a man page, a Markdown document or a completion spec whose flags no longer match the--helpits 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.
- 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 oncmdand, recursively, on each subcommand. Each subcommand is walked under its own freshly-built child context (seechild_context()), so context-sensitive metadata (notably the auto-generated environment variable, which derives fromContext.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.
- 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_ARGSwas captured on the context (byCommand/Group), replaying it through a fresh parser rebuilds theoptsmapping thatParameter.consume_valueconsults, without re-firing eager callbacks:handle_parse_resultis never called here, only the parser.Returns an empty mapping when no raw arguments were captured, so callers can fall back to parameter defaults.
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,Argumentclick.Argumentwith the overrides of_ParameterMixin.Inherits from Click directly:
cloup.Argumentisclick.Argumentitself.
- class click_extra.parameters.Option(*args, group=None, **attrs)[source]¶
Bases:
_ParameterMixin,Optioncloup.Optionwith the overrides of_ParameterMixin.cloup.Optionsubclassesclick.Optionto let an option join a Cloup option group.Todo
Delete the
human_readable_nameoverride and_CLICK_HAS_PARAMETER_SPEConce this packageās Click floor reaches8.6.0. From that release on, Click names a parameter byParameter.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.0only: from that release on, Click readsParameter.specin its place, and warns about a subclass that overrides this property.Below it, Click returns
self.namehere: 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-cygannounces itself as'apt_cyg', naming a flag no user can type and none of the two they did.click.Argumentalready overrides the property for its own reasons, leavingclick.Optionre-declaring the inherited body verbatim." / "is the separatorclick.Parameter.get_error_hintjoins 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:
OptionBase class of the options Click Extra implements itself.
Identifies Click Extraās own options with certainty.
Note
The one Click Extra class carrying the
Extraprefix: every other one takes the name of the Click or Cloup class it shadows. The plainOptionname belongs to the user-facing wrapper this class subclasses, and the prefix marks Click Extraās own built-in options apart from it.Commandreads that mark: it sorts parameters withisinstance(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 inHelpFormatter._style_bracket_fields(), which uses the structured data fromOption.get_help_extra()to identify each field by its label.Note
Built-in option subclasses share a common shape: their
__init__defaultsparam_declsto the optionās canonical flags and wires an eager callback viakwargs.setdefault("callback", self.<callback>). Every callback name encodes its role with a verb prefix. The common roles are:set_<key>publishes a resolved value toctx.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 actxhelper 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.
ConfigOptionwiresload_confto read, parse, and merge a configuration file, andNoConfigOptionwirescheck_sibling_config_optionto assert that a sibling--configoption exists.- add_to_parser(parser, ctx)[source]¶
Register the option, then give the
rootlogger 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 ofJobsOption. 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). Seeclick_extra.logging._hold_invocation_handlerfor the other rules, and for how the handler leaves.- Return type:
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.versionproperty: a Nuitka or PyInstaller binary cannot rungitat runtime, so the hash must be baked into__version__in the source file before compilation.Only a
.devversion 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:
- Return type:
- Returns:
the new version, or
Nonewhen 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_pathonce, then writes it once, with every placeholder offieldsthat 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 (togit, say) runs for the placeholders that need it, never for a file carrying none. A callable answeringNoneor 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__ = "", notNone). The AST matcher only recognizes string literals, and the empty string acts as a falsy sentinel that stays type-consistent with baked values (alwaysstr).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:
- Return type:
- 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 nonameassignment 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:
- Return type:
- Returns:
the value written, or
Nonewhen 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--progressand--time.Clickās own progress bar is determinate, the counterpart to the indeterminate
Spinner. This thin wrapper gates its visibility on the samePROGRESSflag the spinner uses, so a single--no-progress(or--accessible, which lowers theprogressdefault) silences both, and gates its estimated-time display on--time.- Parameters:
hidden (
bool|None) ā tri-state. Left at its defaultNone, the bar follows the resolved--progressflag: hidden when the user (or--accessible) turned progress off, shown otherwise. An explicitTrueorFalseforces the bar regardless, mirroring how an explicitcolor=argument overridesctx.coloronclick.echo(). With no active context (the bar used outside a Click command) it defaults to shown.show_eta (
bool|None) ā tri-state, likehidden. Left at its defaultNone, the estimated-time-remaining display follows the--time/--no-timeflag: shown under--time, hidden otherwise (its default, or outside a command). An explicitTrueorFalseforces it, keeping a bare barās timing in step with anOperationTrailāstimer. Clickās own default isTrue.
- Return type:
ProgressBar[V]
Unlike
click.progressbar(), the bar draws onsys.stderrunlessfilesays otherwise, likeSpinnerandOperationTrail. 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 everyDEFAULT_INTERVAL, the cadence of a spinnerās frames, unlessupdate_min_stepssays otherwise. Its position still moves on every step.Note
The
--progressflag gates visibility and--timethe ETA. Color is already handled upstream: Click renders the bar throughclick.echo(), whosecolor=Noneresolves againstctx.color, so--no-color/NO_COLORstrip 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]inpyproject.tomlfirst, thenconsole_scriptsunder[options.entry_points]insetup.cfg. The dynamicsetup.pyform cannot be parsed statically and is ignored.
- click_extra.project.entry_point_package(target)[source]¶
The top-level package an entry point target lives in.
orchard.cli:mainandorchard:mainboth answerorchard: the module path before the colon, cut at its first dot.
- click_extra.project.locate_package_root(directory, top_package)[source]¶
Find which directory must be on
sys.pathto importtop_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}.pyall count.- Parameters:
directory (
Path) ā the project root.top_package (
str) ā the top-level package name, asentry_point_package()reads it off an entry point.
- Return type:
- Returns:
the directory to prepend to
sys.path, orNonewhen the package cannot be located on disk.
- class click_extra.project.ProjectEntryPoint(target, root)[source]¶
Bases:
NamedTupleThe console-script entry point a project directory resolves to.
Create new instance of ProjectEntryPoint(target, root)
- root: Path | None¶
The directory to put on
sys.pathto import the target, orNonewhen its package is not on disk.
- 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 withlocate_package_root().The ambiguity rule: the console scripts must name a single
module:functiontarget. 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 itspyproject.tomlorsetup.cfg.- Return type:
- Returns:
the entry point, whose
rootisNonewhen 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"givespkg), so theconvert-to-mystcommand can run bare from a project root. The package is located under the project root or itssrc/folder, seelocate_package_root(), and assumed under the project root when it is in neither.- Parameters:
directory (
Path|None) ā The project root, holding itspyproject.tomlorsetup.cfg. Defaults to the current working directory.- Return type:
- 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__.pyof each package a projectās console scripts enter.Reads the console scripts of the project in
directorywithread_project_scripts(), takes the top-level package of each entry point and locates it on disk withlocate_package_root(), so a src-layout project resolves like a flat one.
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 (likeToken.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.Outputtokens, 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_coloroption every ANSI lexer and filter of this module takes:AnsiColorLexer,AnsiFilter, and the session lexers ofLEXER_MAP, which hand the option down to the lexers they wrap.
- class click_extra.pygments.AnsiColorLexer(**options)[source]¶
Bases:
LexerLexer 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 emitToken.AnsiLinkStart/Token.AnsiLinkEndstructural 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 byAnsiHtmlFormatter. 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 asToken.Ansi.FG_{rrggbb}/Token.Ansi.BG_{rrggbb}tokens, whichAnsiHtmlFormatterrenders as inlinestyle="color: #rrggbb"/style="background-color: #rrggbb"attributes (CSS classes cannot enumerate 16.7M colors). PassFalseto quantize 24-bit RGB to the nearest entry in the 256-color palette and emitToken.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
textand yield styled tokens.SGR sequences update the styling state, through the decoder of
click_extra.ansi: an escape reads the same here as insplit_ansi(), so an empty parameter is a0reset and\x1b[;31mis a reset followed by a red foreground. OSC 8 hyperlinks emit structuralToken.AnsiLinkStart/Token.AnsiLinkEndtokens. All other escape sequences are consumed and stripped.
- class click_extra.pygments.AnsiFilter(**options)[source]¶
Bases:
FilterCustom filter transforming a particular kind of token (
Generic.Outputby default) into ANSI tokens.Initialize an
AnsiColorLexerand configure thetoken_typeto be colorized.- Parameters:
true_color ā Forwarded to the inner
AnsiColorLexerto control whether 24-bit RGB sequences are preserved asFG_/BG_hex tokens for inline-style rendering (defaultDEFAULT_TRUE_COLOR) or quantized to the 256-color palette. SeeAnsiColorLexerfor details.
Note
Only one
token_typeis supported. All Pygments session lexers (ShellSessionBaseLexerand the manually-maintained list incollect_session_lexers) emit terminal output exclusively asGeneric.Output. No upstream issue or PR proposes splitting output into additional token types (likeGeneric.Errorfor 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.
- 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.
- 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.Ansicomponent names to CSS declarations, taken fromclick_extra.styling._ATTR_CSSso an attribute renders the same in a documentation code block as in the HTMLto_css()writes.Blinkalone takes_BLINK_CSS. The rules are kept out of the Pygments style dict (_ANSI_STYLES) to prevent Furoās dark-mode CSS generator from injectingcolor: #D0D0D0fallbacks that conflict with foreground color tokens.Used by
AnsiHtmlFormatter.get_token_style_defsto inject CSS rules that both standalonepygmentizeand Furoās dark-mode CSS generator pick up.
- class click_extra.pygments.AnsiBashSessionLexer(**options)¶
Bases:
_AnsiFilterMixin,BashSessionLexerANSI-capable variant of
BashSessionLexer.Add
TokenMergeFilterandAnsiFilterto 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.Outputtoken. TheTokenMergeFilterconsolidates contiguous output lines into a single token, thenAnsiFiltertransforms 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. DefaultDEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. PassFalseto 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,DylanConsoleLexerANSI-capable variant of
DylanConsoleLexer.Add
TokenMergeFilterandAnsiFilterto 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.Outputtoken. TheTokenMergeFilterconsolidates contiguous output lines into a single token, thenAnsiFiltertransforms 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. DefaultDEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. PassFalseto 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,ElixirConsoleLexerANSI-capable variant of
ElixirConsoleLexer.Add
TokenMergeFilterandAnsiFilterto 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.Outputtoken. TheTokenMergeFilterconsolidates contiguous output lines into a single token, thenAnsiFiltertransforms 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. DefaultDEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. PassFalseto 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,ErlangShellLexerANSI-capable variant of
ErlangShellLexer.Add
TokenMergeFilterandAnsiFilterto 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.Outputtoken. TheTokenMergeFilterconsolidates contiguous output lines into a single token, thenAnsiFiltertransforms 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. DefaultDEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. PassFalseto 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,GAPConsoleLexerANSI-capable variant of
GAPConsoleLexer.Add
TokenMergeFilterandAnsiFilterto 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.Outputtoken. TheTokenMergeFilterconsolidates contiguous output lines into a single token, thenAnsiFiltertransforms 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. DefaultDEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. PassFalseto 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,JuliaConsoleLexerANSI-capable variant of
JuliaConsoleLexer.Add
TokenMergeFilterandAnsiFilterto 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.Outputtoken. TheTokenMergeFilterconsolidates contiguous output lines into a single token, thenAnsiFiltertransforms 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. DefaultDEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. PassFalseto 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,MSDOSSessionLexerANSI-capable variant of
MSDOSSessionLexer.Add
TokenMergeFilterandAnsiFilterto 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.Outputtoken. TheTokenMergeFilterconsolidates contiguous output lines into a single token, thenAnsiFiltertransforms 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. DefaultDEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. PassFalseto 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,MatlabSessionLexerANSI-capable variant of
MatlabSessionLexer.Add
TokenMergeFilterandAnsiFilterto 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.Outputtoken. TheTokenMergeFilterconsolidates contiguous output lines into a single token, thenAnsiFiltertransforms 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. DefaultDEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. PassFalseto 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,OutputLexerANSI-capable variant of
OutputLexer.Add
TokenMergeFilterandAnsiFilterto 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.Outputtoken. TheTokenMergeFilterconsolidates contiguous output lines into a single token, thenAnsiFiltertransforms 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. DefaultDEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. PassFalseto 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,PostgresConsoleLexerANSI-capable variant of
PostgresConsoleLexer.Add
TokenMergeFilterandAnsiFilterto 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.Outputtoken. TheTokenMergeFilterconsolidates contiguous output lines into a single token, thenAnsiFiltertransforms 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. DefaultDEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. PassFalseto 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,PowerShellSessionLexerANSI-capable variant of
PowerShellSessionLexer.Add
TokenMergeFilterandAnsiFilterto 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.Outputtoken. TheTokenMergeFilterconsolidates contiguous output lines into a single token, thenAnsiFiltertransforms 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. DefaultDEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. PassFalseto 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,PsyshConsoleLexerANSI-capable variant of
PsyshConsoleLexer.Add
TokenMergeFilterandAnsiFilterto 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.Outputtoken. TheTokenMergeFilterconsolidates contiguous output lines into a single token, thenAnsiFiltertransforms 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. DefaultDEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. PassFalseto 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,PythonConsoleLexerANSI-capable variant of
PythonConsoleLexer.Add
TokenMergeFilterandAnsiFilterto 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.Outputtoken. TheTokenMergeFilterconsolidates contiguous output lines into a single token, thenAnsiFiltertransforms 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. DefaultDEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. PassFalseto 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,RConsoleLexerANSI-capable variant of
RConsoleLexer.Add
TokenMergeFilterandAnsiFilterto 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.Outputtoken. TheTokenMergeFilterconsolidates contiguous output lines into a single token, thenAnsiFiltertransforms 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. DefaultDEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. PassFalseto 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,RubyConsoleLexerANSI-capable variant of
RubyConsoleLexer.Add
TokenMergeFilterandAnsiFilterto 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.Outputtoken. TheTokenMergeFilterconsolidates contiguous output lines into a single token, thenAnsiFiltertransforms 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. DefaultDEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. PassFalseto 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,SqliteConsoleLexerANSI-capable variant of
SqliteConsoleLexer.Add
TokenMergeFilterandAnsiFilterto 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.Outputtoken. TheTokenMergeFilterconsolidates contiguous output lines into a single token, thenAnsiFiltertransforms 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. DefaultDEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. PassFalseto 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,TcshSessionLexerANSI-capable variant of
TcshSessionLexer.Add
TokenMergeFilterandAnsiFilterto 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.Outputtoken. TheTokenMergeFilterconsolidates contiguous output lines into a single token, thenAnsiFiltertransforms 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. DefaultDEFAULT_TRUE_COLOR: 24-bit RGB renders via inline styles. PassFalseto 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:
HtmlFormatterHTML formatter with ANSI color and hyperlink support.
Extends Pygmentsā
HtmlFormatterto handle compoundToken.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
styleargument to augment it with ANSI color support.The formatter runs on a subclass of the style provided by the user, whose
stylesattribute 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.AnsiLinkEndwith Unicode Private Use Area markers, stripsFG_/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:
- 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 thanget_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_linesadds. 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:
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āsHOME: hermetic builders setHOME=/homeless-shelter, which would otherwise leak into those assertions.XDG_CACHE_HOMEis pinned too, soget_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 aFORCE_COLORorCLICOLOR_FORCEin the callerās shell would otherwise leave ANSI codes in the output a test matches as plain text. A test that wants them passesenv=orforce_color=Truetoinvoke().The environment is patched directly (via
temporary_env()) rather than through themonkeypatchfixture on purpose: depending onmonkeypatchhere would tear it down afterisolated_filesystemremoved the working directory it tries to restore, breaking unrelated tests thatchdirwithin the runner. For the same reason, an autouse fixture that patches the environment must use its ownpytest.MonkeyPatch.context(), not themonkeypatchfixture, 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
--configsearch pattern derives fromclick.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(bothclickā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 pinsHOMEand 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 interceptsget_app_dirdirectly, covering any in-process invocation, without touchingHOME(a suite may need the real one elsewhere) and without leaking into subprocesses.To make a whole suite hermetic, alias it to an
autousefixture in yourconftest.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:
- Returns:
Pytest parameters covering each command-like decorator variant:
click.commandclick.command()cloup.commandcloup.command()click_extra.commandclick_extra.command()click.groupclick.group()cloup.groupcloup.group()click_extra.groupclick_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:
- Returns:
Pytest parameters covering each parameter-like decorator variant:
click.optionclick.option()cloup.optioncloup.option()click_extra.optionclick_extra.option()click.argumentclick.argument()cloup.argumentcloup.argument()click_extra.argumentclick_extra.argument()
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_mapvalue.keysis the parameterās fully-qualified path, root command name first and parameter name last, as yielded bywalk_command_params(). A local file is returned as aPath, a remote one as its URL, astr. ReturnsNonewhen no configuration file was loaded, when the parameter is absent from every loaded layer, or when the context carries no layereddefault_mapat all.The walk mirrors how Click resolves
default_map, so the attribution matches the value Click actually picks. The root contextāsdefault_mapis a~collections.ChainMapwhose first layers are the loaded files, in the order ofCONF_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.
- click_extra.show_params.render_params_table(subject_ctx, *, default_columns=None)[source]¶
Introspect
subject_ctx.commandand 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(seeTABLE_FORMATandCOLUMNS); when neither is set, a sibling--table-format/--columnsoption on the command is consulted, then thedefault_columnsfallback, then the canonical order.When
subject_ctx.metacarries pre-parsedRAW_ARGS, thevalueandsourcecolumns 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 theclick-extra wrap --paramspath (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 byCommand/Group) through the command parser, callingconsume_value()rather thanhandle_parse_result()so eager callbacks are not re-triggered.- Return type:
- 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,ParamStructureA pre-configured option adding a
--paramsoption.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 ashow-verb prefix. The class and the@show_params_optiondecorator 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
--paramstable.Each entry is a
click_extra.columns.ColumnSpeccarrying the columnās stableid(used by--columnsand as structured-format key), its displaylabel, and a MyST/Markdowndescriptionconsumed 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).
- classmethod column_ids()[source]¶
Return just the stable IDs of
TABLE_HEADERS(in order).
- classmethod default_columns()[source]¶
Return the columns rendered when
--columnsasks for no projection.Every column but the
optionalones, which stay addressable by ID and out of the way until named.- Return type:
- classmethod default_column_ids()[source]¶
Return the stable IDs of
default_columns()(in order).
- classmethod default_column_labels()[source]¶
Return the display labels of
default_columns()(in order).
- classmethod find_column(column_id)[source]¶
Return the
ColumnSpecmatchingcolumn_id.- Raises:
KeyError ā if no column has this ID. Convert it into a
click.UsageErrorbefore it reaches a user.- Return type:
- classmethod render_doc_table()[source]¶
Render
TABLE_HEADERSas a Markdown table for documentation.Used by the
show_params_columns_tableMyST substitution indocs/conf.pyto feed the Available columns section ofdocs/parameters.md: editing a description here automatically rebuilds the docs table on the nextsphinx-build.- Return type:
- 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 drivingclick-extra wrap --paramsfor foreign CLIs. The live invocation context carries everything the core needs: the capturedRAW_ARGS(attached byCommand/Group) for value and source resolution, plus any sibling--table-format/--columnsoptions.- Return type:
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
Spinnergiven 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
Spinnercurrently animating, orNone.A spinner-typed view of
_active_line(), skipping any progress-bar indicator that may own the line instead. Withstreamgiven, only a spinner drawing on that very stream matches.
- 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_GLYPHpainted with the active themeāssuccessslot, or the failure glyphKO_GLYPHpainted with itserrorslot.- 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:
- 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:
objectA 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 callingstop()) halts the thread and erases the spinner line so it never lingers above the next output.Note
A single
Spinnerinstance drives one animation at a time. A tool running its steps one after another can share one instance and reassign itslabelbetween 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@Spinnerdecorator 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 toSPINNER_FRAMES, or thespinnerpresetās frames when given.spinner (
SpinnerPreset|None) ā aSpinnerPresetfrom theSPINNERScatalog (spinner=SPINNERS["moon"]), supplying both frames and a tuned interval. An explicitframesorintervalstill 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 customframes.interval (
float|None) ā seconds between two frames. Defaults toDEFAULT_INTERVAL, or thespinnerpresetā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) ā aStyleapplied to the spinner glyph, label and timer (Style(fg="cyan", bold=True)). Color is decoupled from animation:--no-color/NO_COLORstrip it while the spinner keeps spinning (seeProgressOption). The strip reaches escapes embedded inlabelitself too, so a label styled by hand is as safe as one styled through these arguments.label_style (
Style|None) ā aStylefor the label alone, in place ofstylethere. It also paints the label of the keptok()/fail()line, whichstyleleaves plain. It outlives a reassignedlabel, 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 finalok()/fail()line.None(the default) follows the CLIās--time/--no-timeflag, as anOperationTraildoes.Trueforces it on withformat_duration()ās compact format (2.3s,1:05, then1:02:03),Falseforces it off, and a callable(seconds: float) -> strformats the duration yourself, liketimer=lambda s: f"{s / 60:.0f}m"for whole minutes.timer_style (
Style|None) ā aStylefor the timer, parentheses included, in place ofstylethere (Style(dim=True)to set the clock back from the label). Atimercallable formats only the duration, so it cannot reach the parentheses: this can. Also paints the timer of the keptok()/fail()line.stream (
IO[str] |None) ā where to draw; defaults tosys.stderrso the spinner never mixes intostdoutdata.live (
Literal['auto','always','never']) ā where the animation may draw:"auto"(the default) on an interactive terminal only, unless--no-progressturns it off,"always"on any stream,"never"nowhere. A spinner that does not draw still writes itsok()/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_styleortimer_stylecarries a color or attribute that cannot be rendered, or ifliveis not one ofWHEN.
- 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 oncestop()is called.Returns
0.0before the spinner has started.
- property shown: bool¶
Whether the spinner has drawn at least one frame to its stream.
Trueonly once an animation frame was actually rendered. It staysFalsefor a disabled spinner (off a TTY, on aTERM=dumbterminal, or withlive="never") and for a call that finishes withindelay, before the first frame. Reset bystart().Use it to gate output that should mirror the spinnerās visibility.
ok()andfail()write their line unconditionally, so an outcome is still recorded in a pipe or log. Guard them withshownwhen 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 waystart()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.
- 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 laterok()/fail()can report a duration).- Return type:
- 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:
- echo(message='')[source]¶
Print
messageon its own line above the running spinner.Clickās
click.progressbar()and a bareprintboth 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, writesmessagefollowed 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(stderrby default), so results written tostdoutnever need it. When the spinner is not animating (disabled, or a non-TTY stream), it degrades to a plain write ofmessagewith no control codes.- Return type:
- 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 withsymbolfollowed by the current label (and the elapsed time whentimeris set), then keeps that line.symboldefaults to the themed success glyphOK_GLYPH(ā), painted with the active themeāssuccessslot unlessstyleoverrides it. Color is stripped under--no-color/NO_COLOR; the glyph stays.- Return type:
- 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:
ExtraOptionA pre-configured
--progress/--no-progressflag gating spinner display.Resolves to a single boolean published at
ctx.meta[click_extra.context.PROGRESS], whichSpinner,OperationTrailandprogressbar()read on their own when left at their automatic default. The default isTrue;--accessiblelowers it toFalse(viadefault_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_COLORstrip 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/--quietknob), whileNO_COLORonly affects color. Rich takesTERM=dumb, notNO_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=dumbterminal that cannot move the cursor (see_can_draw());explicit intent:
--no-progressor--accessible.
This option is eager. It never reads
ctx.color, so its position relative toColorOptiondoes not matter.- set_progress(ctx, param, value)[source]¶
Publish whether progress spinners may be shown.
Stores the resolved
--progressflag atPROGRESS. Deliberately independent of color: see theProgressOptionnote for why a spinner is gated on interactivity (TTY /TERM=dumb) and--accessible, never on--no-color/NO_COLOR.- Return type:
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_FRAMESwhere Braille glyphs are unavailable.
- class click_extra.spinner_presets.SpinnerPreset(frames, interval)[source]¶
Bases:
NamedTupleA named spinner animation: its frames and the interval they look best at.
Pick one from the
SPINNERScatalog, or build your own, and pass it toSpinnerthrough itsspinnerargument.Create new instance of SpinnerPreset(frames, interval)
- 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
SpinnerPresetbundling frames and a tuned interval. Select one withSpinnerāsspinnerargument:from click_extra import SPINNERS, Spinner with Spinner("Brewing tea", spinner=SPINNERS["moon"]): ...
Unlike the upstream
\b-based renderers,Spinnerredraws 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 aStyleequals thecloup.Stylecarrying the same fields.A compact, single-line
__repr__that hidesNoneand falsy attributes and renders RGB tuples as#rrggbbhex.Hex-string color shorthand:
Style(fg="#f1fa8c")works alongsideStyle(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 | bthat merges two styles, with the right operand winning on conflicts.A
Style.cascade()method that fills the styleāsNonefields 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 aStyleinstance.Style.contrast_ratio()returning the WCAG contrast ratio between two foreground colors. Useful for theme designers checking accessibility.split_ansi()andrender_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 inwrap_ansi(), with the rest of the terminal-grid measures.The
ansi_to_html(),ansi_to_jira(),ansi_to_latex()andansi_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_valueapplied to every kept value. Use to convert RGB tuples to#rrggbbstrings, nested dataclasses to dicts, etc. Defaults to the identity.keep (
Callable[[Any,Any],bool]) ā callable(field, value) -> booldeciding whether a non-default field is emitted. Defaults to keeping all of them.
- Return type:
- 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:
- Raises:
TypeError ā listing every key that names no field of cls, so callers can build a constructor call without validating first.
- Return type:
- 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-bit38;2;r;g;bsequence and quantizing it to the nearest38;5;n256-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:
COLORTERMoftruecolor/24bit(see_TRUECOLOR_COLORTERMS) keeps 24-bit.Any other non-empty
COLORTERMquantizes: an explicit lower advertisement.A
TERMending in-16colorquantizes: an unambiguous sub-256 terminal.*-256coloris deliberately not treated as a downgrade, since truecolor terminals routinely report it while advertising their 24-bit support throughCOLORTERMinstead. Honoring it would strip truecolor from the very terminals this optimistic default protects.Otherwise keeps 24-bit.
A
dumb/unknownTERMnever reaches this decision for CLI output: it has already disabled color upstream throughresolve_color_env().- Return type:
- 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:
Stylecloup.Stylewith 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,
#rrggbbhex, RGB tuple, or palette index.
- bg: str | tuple[int, int, int] | int | None = None¶
Background color: named ANSI string,
#rrggbbhex, RGB tuple, or palette index.
- cascade(base)[source]¶
Return a copy with
Nonefields filled in from base.The instanceās own non-
Nonevalues always win:cascadeonly fills gaps. Useful for theme inheritance:derived.cascade(parent)keepsderivedās overrides and inherits the rest fromparent.- Return type:
- to_dict()[source]¶
Serialize to a plain dict with only the set fields.
RGB tuples are emitted as
#rrggbbstrings so the result round-trips through TOML/JSON/YAML untouched. Pair withfrom_dict()to rebuild aStyle.
- classmethod from_dict(data)[source]¶
Build a
Stylefrom the plain dict produced byto_dict().Validates that every key in data names a known
Stylefield and raisesTypeErrorotherwise. Pair withto_dict()to round-trip through TOML/JSON/YAML.- Return type:
- 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 inlinestyle="..."attributes on HTML spans.- Return type:
- 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;n256-color extension, and the38;2;r;g;b/48;2;r;g;b24-bit extension. Reset codes (the full0reset, its parameter-less\x1b[mform included, and selective resets like22,39or49) 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 singleStyle.To tokenize a string mixing text and escapes, with resets honored, see
split_ansi().- Return type:
- 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:
- 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 itsStyle. Unstyled text is yielded with an emptyStyle. 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.
- 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:
- click_extra.styling.ansi_to_html(text)[source]¶
Translate ANSI styling in text to inline-styled HTML
<span>tags.\x1b[34mSummer\x1b[0mbecomes<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:
- click_extra.styling.ansi_to_jira(text)[source]¶
Translate ANSI styling in text to Jira wiki markup.
\x1b[34;1mSummer\x1b[0mbecomes{color:blue}*Summer*{color}.- Return type:
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 aColumnSpec.
- click_extra.table.TColumnDef: TypeAlias¶
One column definition of
SortByOptionorcolumn_sort_key().A
ColumnSpec, or a bare column ID.
- class click_extra.table.TableFormat(*values)[source]¶
Bases:
EnumEnumeration of supported table formats.
Hard-coded to be in alphabetical order. Content of this enum is checked in unit tests.
Warning
The
youtrackformat 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--coloron 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_FORMATSfor the registry.
- property is_wrappable: bool¶
Whether this format renders a cell wrapped onto several lines.
See
WRAPPABLE_FORMATSfor 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 (
htmlescapes HTML entities, non-rawlatexvariants 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
csvmodule, 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
Finalso it narrows toLiteral["auto"]instead ofstr, which is what lets it stand in for the raw string anywhere aColumnWidthis expected.
- click_extra.table.MIN_COLUMN_WIDTH = 8¶
Floor applied to an
AUTO_WIDTHcolumn, 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_widthsunusable, 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 theSERIALIZATION_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.
rowssays what the first column lists, read downward, andcolumnswhat the other headers list, read rightward:corner_header("City", "Month")returnsCity ā“ \ Month ā.- Return type:
- 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.
headersentries carrying a column ID (ColumnSpecinstances) plug the table into the active--sort-byselection: when no explicitsort_keyis given, rows sort by the selected columns this table carries, and keep their original order when it carries none. Seecolumn_sort_key()for the exact semantics.- Parameters:
sort_key (
Callable[[Sequence[str|None]],Any] |None) ā Optional callable passed tosorted()as thekeyargument. 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, orNonefor no limit. Defaults to themax_widthdeclared byColumnSpecheaders. Silently dropped by formats outsideWRAPPABLE_FORMATS.
- Return type:
- 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.
headersentries carrying a column ID (ColumnSpecinstances) plug the table into the active--sort-byselection: when no explicitsort_keyis given, rows sort by the selected columns this table carries, and keep their original order when it carries none. Seecolumn_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
--coloris 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 tosorted()as thekeyargument. 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, orNonefor no limit. Defaults to themax_widthdeclared byColumnSpecheaders. Silently dropped by formats outsideWRAPPABLE_FORMATS.
- Raises:
MissingExtraError ā the renderer of
table_formatis not installed.- Return type:
- 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_FORMATSare 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 tostr, soPathand 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_keysorindentfor JSON).
- Raises:
ValueError ā If the format is not a serialization format.
- Return type:
- 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 tostr.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_formatis not installed.- Return type:
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:
ExtraOptionA pre-configured option that is adding a
--table-formatflag 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 therender_table()andprint_table()context methods pick it up as their default format.ctx.metais 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_datais a 2-dimensional iterable of iterables for rows and cells values,headersis a list of string to be used as column headers,**kwargsare any extra keyword arguments supported by the underlying table formatting function.
- init_formatter(ctx, param, table_format)[source]¶
Save the resolved
table_formatin the contextās sharedmeta.The
render_table()andprint_table()context methods read it back at call time.- Return type:
- click_extra.table_options.column_sort_key(header_defs, sort_columns=None, cell_key=None)[source]¶
Build a row sort key from the
sort_columnsa table actually carries.header_defsdescribes the rendered columns:ColumnSpecinstances, withsortable=Falsefor columns that cannot be sorted on. The requestedsort_columnsthe 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
Nonewhen the table carries none of the requested columns, signalling that rows should keep their original order. This is what lets one--sort-byselection 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.
- class click_extra.table_options.ColumnsType(choices=())[source]¶
Bases:
MultiChoiceMultiChoiceover 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
COLUMNSinstead of the genericMULTI.Initialize the type.
- Parameters:
choices (
Sequence[str]) ā the accepted values. When non-empty,convert()rejects unknown tokens withfail. 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 ofchoicesexactly. By default tokens match case-insensitively, as withEnumChoiceandThemeChoice, and the returned tuple holds the canonical (original-case) values fromchoices.
- 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:
ExtraOptionA
--columnsoption 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 (likeclick_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 aclick.UsageError. Withoutcolumns=, 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
--columnsat all.- columns: tuple[ColumnSpec, ...]¶
Column registry this option advertises and validates against (may be empty).
- 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:
ExtraOptionA
--sort-byoption 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 inctx.meta[click_extra.context.TABLE_SORT_KEY], whichctx.print_tablepicks up so that table output is automatically sorted, without changing its(table_data, headers)call contract. The option acceptsmultiple=True, so users can repeat--sort-byto define a multi-column sort priority.Column definitions are
ColumnSpecinstances, passed positionally or via thecolumns=keyword. A column markedsortable=Falsekeeps its place in the layout without being offered as a choice. Passing aColumnSpecregistry viacolumns=lets the same tuple drive bothColumnsOption(--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-bydeclared 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 byprint_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 atprint_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 underctx.meta[click_extra.context.TABLE_SORT_KEY], wherectx.print_tablepicks 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.metais shared with every subcommand), resolved per table byprint_table()from the column IDs its headers carry.- Return type:
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:
ExtraOptionA pre-configured
--telemetry/--no-telemetryoption 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_TRACKforces telemetry off, overriding the user-defined environment variables, the auto-generated values, and configuration files. Only an explicit--telemetryon the command line outranks it.The resolved value is stored in
ctx.meta[click_extra.context.TELEMETRY].See also
- set_telemetry(ctx, param, value)[source]¶
Reconcile the flag with
DO_NOT_TRACKand store the result onctx.meta.An explicit
--telemetry/--no-telemetryon the command line wins. Otherwise a truthyDO_NOT_TRACK(bare presence, or any value not parseable as false, seeparse_envvar_flag()) forces telemetry off. Read viaclick_extra.context.get(ctx, click_extra.context.TELEMETRY).Important
DO_NOT_TRACKbreaks the rule of the other machine-wide variables, which a configuration file and the optionās own variable outrank (seemachine_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>_TELEMETRYvariable 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_TRACKis read here rather than wired through the optionāsenvvar: Clickās environment plumbing feeds the raw value straight to the boolean flag, soDO_NOT_TRACK=1would enable telemetry, inverting the convention. Reading it manually keeps the opt-out meaning, mirroring howColorOptionreadsNO_COLORand friends.- Return type:
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 matchingclick-extra[ā¦]extra. TOML has no bare top-level array, so a TOML suite lists its cases under a[[cases]]array of tables (seeparse_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 anImportErrorpointing at its extra at parse time.
- exception click_extra.test_suite.SkippedTest[source]¶
Bases:
ExceptionRaised 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:
objectA single CLI test case: how to invoke the command and what to expect.
Each case runs the command-under-test once with
cli_parametersappended, then checks the captured result against the expectation directives below. A case with no expectation only asserts the command ran (plusexit_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:
shlexon POSIX,CommandLineToArgvWon 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_parametersflag, a variable cannot. Values must be strings, so a number or a boolean is quoted ("1", not1): an environment holds strings only, and coercing would have to pick betweenTrueandtrueon the authorās behalf.Applied to that one child process, never to the suite runnerās own environment, so cases stay independent under
--jobs. Seeunset_envto take a variable away instead.
- unset_env: tuple[str, ...] | str¶
Environment variables removed from the inherited environment.
The half
envcannot express. Assigning the empty string leaves a variable set, and a flag read by bare presence (likeACCESSIBLEorDO_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
nullvalue inenvbecause 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_platformsidentifiers such aslinux,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
--timeoutdefault, then to no limit.
- 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 thestdout_*/stderr_*ones: a single subprocess run captures either the merged stream or the separate ones, not both.
- output_regex_matches: tuple[Pattern | str, ...] | str¶
Regexes that must each match somewhere in the combined output (searched,
re.DOTALL). Seeoutput_containsfor 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_containsfor 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_*orstderr_*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
commandcan 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
envandunset_envdirectives are layered over the inherited environment for this child process only.work_directoryis the directory the command runs in, defaulting to the one the runner itself is in.commandis 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:
- click_extra.test_suite.cases_from_data(data)[source]¶
Build
CLITestCaseinstances from already-parsed suite data.The in-memory counterpart to
parse_test_suite()(which parses a string) andload_test_suite()(which reads a file): feed it a suite that is already a Python object, such as the nativecasesmappings declared in a[tool.<cli>.test-suite]config section.A suite is a list of case mappings, each keyed by
CLITestCasedirective names. Formats with no bare top-level array (TOML) carry that list under a top-levelcaseskey, 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:
- click_extra.test_suite.parse_test_suite(suite_string, fmt=ConfigFormat.YAML)[source]¶
Parse a serialized test suite string into
CLITestCaseinstances.fmtselects the serialization format, one ofSUITE_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,
fmtcannot express a suite, a mapping suite omitscases, 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:
- 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-capableSUITE_FORMATS(sosuite.tomlparses as TOML,suite.yamlas YAML). Reading and format detection are delegated toclick_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:
- 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(seeclick_extra.jobs.run_jobs()): at one worker they run sequentially and lazily, soexit_on_errorcan 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 aclick_extra.spinner.Spinnerreports progress unlessshow_progressis 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;1runs 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, andcommandis 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:
- Returns:
A
collections.Counterwithtotal,skipped, andfailedkeys. A non-zerofailedcount 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 reachesContextthrough a patchedCommand.main()call instead (pallets/click#2110).Todo
pallets/click#3896 adds a
context_settingsparameter toclick.testing.CliRunner.invoke(). It sets the context color without theCommand.main()patch ininvoke().On a Click release that carries it, this constant also catches
context_settings, and the patch sends it toContext, which rejects it. On such a release, keepcontext_settingsout of the collision set and passforce_colorthrough 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
StreamViewattribute.output_*directives target the merged stream;stdout_*andstderr_*target the separate streams. Bothrender_cli_run()andclick_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:
objectNormalized 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 separatestdoutandstderrstreams, never both: the unused fields stay empty.- output: str = ''¶
Captured merged stream (stdout and stderr interleaved), or empty when the separate streams were captured.
- classmethod from_result(result)[source]¶
Build a view from an in-process
click.testing.Result.Click always exposes
stdout,stderrand the interleavedoutputtogether, so all three are carried over verbatim.- Return type:
- 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) reportsresult.stderrasNone: that case is rendered as the interleavedoutputstream. Otherwise the two streams are kept separate.- Return type:
- 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:
- class click_extra.testing.Result(runner, stdout_bytes, stderr_bytes, output_bytes, return_value, exit_code, exception, exc_info=None)[source]¶
Bases:
ResultA
Resultsubclass with automatic traceback formatting.Enhances
__repr__so that pytest assertion failures show the full traceback instead of just the exception type.
- 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 in9.0. Click points attempfile.TemporaryDirectoryand pytestāstmp_pathfixture, and neither replaces it: what isolates a CLI here is the working directory, which a command reads through relative paths and configuration-file globs. Therunnerpytest fixture and theclick:runSphinx 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.
- class click_extra.testing.CliRunner(charset='utf-8', env=None, echo_stdin=False, catch_exceptions=True, capture='sys')[source]¶
Bases:
CliRunnerAugment
click.testing.CliRunnerwith extra features and bug fixes.- force_color: bool = False¶
Default of the
force_colorargument ofinvoke(), for every run.A call passing
color=Falsestill 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 initializingContext.color = True.click.testing.CliRunner.invoke()cannot express it, itscolorparameter colliding with theContextone (pallets/click#2110). Theforce_colorclass attribute sets it for every run.Strips all ANSI codes from results if
colorwas explicitly set toFalse.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 ofstr,pathlib.Pathobjects andNonevalues. The nested structure will be flattened andNonevalues will be filtered out. Then all elements will be cast tostr. Seeargs_cleanup()for details.input (
str|bytes|IO|None) ā same asclick.testing.CliRunner.invoke().env (
Mapping[str,str|None] |None) ā same asclick.testing.CliRunner.invoke().catch_exceptions (
bool|None) ā same asclick.testing.CliRunner.invoke():None(the default) follows the runnerās owncatch_exceptions.color (
bool|None) ā whether the captured streams keep ANSI codes, passed toclick.testing.CliRunner.isolation().Falsealso scrubs the result bytes.force_color (
bool|None) ā keep the ANSI codes and initialize the invoked CLIāsContext.colortoTrue, so it takes its colored branch.None(the default) follows theforce_colorclass attribute.extra (
Any) ā same asclick.testing.CliRunner.invoke(), but colliding parameters are allowed and properly passed on to the invoked CLI.
- Raises:
ValueError ā if
force_color=Trueis passed withcolor=False.- Return type:
- 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 Click9.0removes it.
- click_extra.testing.unescape_regex(text)[source]¶
De-obfuscate a regex for better readability.
This is like the reverse of
re.escape().- Return type:
- exception click_extra.testing.RegexLineMismatch(regex_line, content_line, line_number)[source]¶
Bases:
AssertionErrorRaised 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
contentmatches the givenregex.If the
regexdoes not fully match thecontent, raise anAssertionError, with a message showing the first mismatching line.This is useful when comparing large walls of text, such as CLI output.
- Return type:
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>_THEMEvariable 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 withclick-extra wrap. It accepts the same values as--theme, theAUTO_THEMEdirective included.Read by
set_theme()as a last resort, so a--themeflag, a<CLI>_THEMEvariable and a configuration file each outrank it. See that method for why it is read directly instead of being wired through the optionāsenvvar.
- 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:
HelpThemeExtends
cloup.HelpThemewith 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_THEMESprovide the visual styling by setting the relevant slots; user-defined themes can be authored as plain mappings and loaded viafrom_dict().- critical()¶
Style applied to the
CRITICALlevel name in log records.Example:
CRITICAL: Database connection lost.Rendered with the default
darktheme:CRITICAL: Database connection lost.- Return type:
T
- error()¶
Style applied to the
ERRORlevel name in log records.Example:
ERROR: Configuration file not found.Rendered with the default
darktheme:ERROR: Configuration file not found.- Return type:
T
- warning()¶
Style applied to the
WARNINGlevel 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
darktheme: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
INFOlevel name in log records.Usually left at
identity:INFOis the default verbosity and shouldnāt stand out from regular output.Rendered with the default
darktheme:INFO: Loaded 23 records.
- Return type:
T
- debug()¶
Style applied to the
DEBUGlevel name in log records.Example:
DEBUG: Resolved /etc/myapp/config.toml.Rendered with the default
darktheme: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 (whencross_ref_highlightis enabled).Rendered with the default
darktheme:--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
darktheme:Commands: backup Snapshot the data store. restore Restore from a snapshot.
- Return type:
T
- choice()¶
Style applied to each individual value inside a
click.Choicemetavar (likejson,csv,xmlwithin[json|csv|xml]) and to those values referenced in option descriptions.Rendered with the default
darktheme:--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
darktheme:--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 atidentity. A theme that only setsbrackettherefore 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
darktheme:--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 tobracketwhen left atidentity, so a theme that only stylesbracketstill gets a consistent rendering inside bracket fields.Rendered with the default
darktheme:--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 tobracketwhen left atidentity.Rendered with the default
darktheme:--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 forIntRangeandFloatRangeoptions. Falls back tobracketwhen left atidentity.Rendered with the default
darktheme:--level INTEGER RANGE Verbosity level. [0<=x<=9] --port INTEGER RANGE Bind port. [x>=1024]
- Return type:
T
- required()¶
Style applied to the
requiredlabel inside bracket fields on mandatory options. Falls back tobracketwhen left atidentity.Rendered with the default
darktheme:--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
darktheme: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
darktheme:--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
darktheme:--retry-budget INTEGER The retry budget.
- Return type:
T
- success()¶
Style applied to success glyphs in pre-rendered UI elements (the
āinOK_GLYPH) and any text passed through this slot by downstream code.Rendered with the default
darktheme:ā 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):subheadingis 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
darktheme:ā¼ 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.
Noneis a value like any other, not a slot left alone.
- 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 forBUILTIN_THEMESinstead.- Return type:
- classmethod light()[source]¶
A theme assuming a light terminal background color.
Carries cloupās palette, like
dark().- Return type:
- to_dict()[source]¶
Serialize the theme to a plain dict suitable for TOML/JSON/YAML.
Each
Styleslot is emitted viaStyle.to_dict. Slots left at their default (identityorNone) are omitted, so the output only carries what the theme actually overrides. Pair withfrom_dict()to round-trip.
- 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
StyleviaStyle.from_dict, whilecross_ref_highlightis read as a plainbool. Unknown keys raiseTypeErrorso typos surface immediately.- Return type:
- cascade(base)[source]¶
Layer this themeās set slots on top of base.
Mirrors
Style.cascadeat 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.
- click_extra.theme.LITERAL_STYLES: frozenset[str] = frozenset({'alias', 'alias_secondary', 'choice', 'invoked_command', 'option', 'separator', 'subcommand'})¶
Names of the
HelpThemeslots 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 aclick.Choice(jsonin[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 (
\fBin roff) āeven in the SYNOPSIS sectionā. Paired withREPLACEABLE_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_STYLESitalic, mirroring a man page even in the color palettes.tests/test_theme.pyenforces the invariant, and themanpagebuilt-in theme is its pure-monochrome embodiment (bold/italic, no color). The man-page generator ofclick_extra.command_docfollows the same split, setting each token in\fBor\fI.
- click_extra.theme.REPLACEABLE_STYLES: frozenset[str] = frozenset({'argument', 'metavar'})¶
Names of the
HelpThemeslots 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 (
\fIin roff). SeeLITERAL_STYLESfor 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
HelpThemeinstances.Each theme is built from its definition in this module on its first lookup, and the same instance is returned from then on.
theme_registrystarts with the same entries.Index by name to access any palette, like
BUILTIN_THEMES["dark"]orBUILTIN_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-indarkpalette;patch_click()overrides it viaset_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:
- click_extra.theme.set_default_theme(theme)[source]¶
Override the process-wide fallback theme.
ThemeOptionwrites its picked theme toctx.metarather 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:
- click_extra.theme.get_current_theme()[source]¶
Return the theme active for the current CLI invocation.
Resolution order:
The theme stored on the active Click context under
click_extra.context.THEME(set byThemeOptionfrom--theme).The process-wide fallback returned by
get_default_theme()(the dark default, or whateverpatch_click()set at process start).
Falling back through the active context (instead of reading a module attribute) keeps
--themescoped to the invocation that received it, so a second invocation in the same process starts from the default again.- Return type:
- 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
HelpThemeinstance. It starts with the entries ofBUILTIN_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 throughConfigOption, lands onctx.meta(seeclick_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.
- click_extra.theme.get_theme_registry(ctx=None)[source]¶
Return the theme registry visible to ctx.
Merges the module-level
theme_registrywith any per-invocation overrides stored onctx.metaunderclick_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-indarkpalette for one invocation without touching the global registry.When ctx is
Noneor 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:
- click_extra.theme.AUTO_THEME: str = 'auto'¶
Reserved
--themevalue resolving the palette from the terminal background.Unlike the named built-in palettes,
autois not a registry entry: it is a directive handled byThemeOption, which callsresolve_auto_theme()to pickdarkorlightfrom the detected background, mirroring--color=auto.It is advertised all the same, in the
--helpmetavar 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.--colorlists its ownautobesidealwaysandneverfor 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:
- Returns:
the chosen
HelpTheme, orNonewhen neither the detected palette nor thedarkfallback is registered (both were removed from the registry). ANoneleavesctx.metauntouched soget_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
HelpThemeviaHelpTheme.from_dict(). If name matches an existing key intheme_registry, the new theme is layered on top viaHelpTheme.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.
- click_extra.theme.validate_themes_config(themes_subtree)[source]¶
Validate a
[tool.<cli>.themes]sub-tree.Registered as a built-in
ConfigValidatorbyConfigOptionso malformed theme tables surface asValidationErrorwith a rooted path (my-cli.themes.<name>) rather than a deepTypeErrorfromHelpTheme.from_dict().- Return type:
- class click_extra.theme.ThemeChoice(case_sensitive=False)[source]¶
Bases:
ParamTypeA
click.ParamTypewhosechoicestrack the live theme registry.Implements the
click.Choice-shaped duck interface (choices,case_sensitive,normalize_choice) soclick_extra.highlightcan collect theme names for per-token highlighting through the same code path it uses for Clickās ownChoice. Thechoicesattribute is a property that queriesget_theme_registry()at every lookup, so themes registered late (typically byConfigOptionparsing[tool.<cli>.themes.<name>]tables before--themeis processed) are valid choices and appear in the--helpmetavar.A plain
click.ParamTyperather than aclick.Choicesubclass:click.Choice.__init__assignsself.choices, which a read-only property cannot take.- property choices: tuple[str, ...]¶
Values
--themetakes, 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:
- 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,
Nonewhen no themes are registered at all (an inert--theme), and callsfailwhen value is not a string or does not match any registered theme.
- shell_complete(ctx, param, incomplete)[source]¶
Return a list of
CompletionItemobjects 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:
- Return type:
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:
ExtraOptionA pre-configured option that adds
--themeto select the help-screen palette.Accepts any name registered in
theme_registryor in the per-invocation overrides loaded byConfigOptionfrom[tool.<cli>.themes.<name>]. Validation goes throughThemeChoice, which reads the live registry at parse time, so config-defined themes appear as valid choices and in the--helpmetavar without any further wiring.The resolved
HelpThemelands on the Click context underclick_extra.context.THEMEand 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. Seeset_theme()for how it ranks against the flag, the<CLI>_THEMEvariable 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 viaresolve_auto_theme()instead of naming a registered theme. Background detection reads environment variables by default; passquery_background=Trueto 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.
ThemeChoicehas already validated value against the live registry (or accepted theAUTO_THEMEdirective) by the time this fires. A plain palette name is looked up unconditionally;autois resolved from the terminal background viaresolve_auto_theme(), leavingctx.metauntouched when no palette can be resolved soget_current_theme()keeps its default.Before that,
THEME_ENVVARis consulted when the value still comes from the optionās own default, as for every machine-wide variable (seemachine_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 explicitenvvarbefore the auto-generated<CLI>_THEME, which would let the machine-wide preference outrank the CLI-specific one, and would list both names in the--paramstable, making the combined string the widest cell of its column. This mirrors howAccessibleOptionreadsACCESSIBLEandColorOptionreadsNO_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:
- click_extra.theme.OK_GLYPH: str = 'ā'¶
Plain check-mark glyph for success indicators.
Style at the call site with the active themeās
successslot: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.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 bymessage.The glyph is the one
trail_glyph()paints.- Return type:
- 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:
objectA
ā/āprogress trail and finisher for a batch of operations.Where
Spinnernarrates one long-running call,OperationTrailreports a batch of them: each completed operation leaves a persistenttrail_line()on screen, a runningdone/totaltally keeps the batchās pulse visible, andfinish()closes with a persistent summary line. The natural reporting companion of the concurrency primitivesrun_jobs()andrun_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-callSpinner).finish()appends the elapsed time.concurrent (
jobs > 1): drive one aggregateSpinner(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 theSPINNERScatalog withspinner=.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 knowntotal.
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
livechanges 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=Falsesilences 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 thedone/totalcount.jobs (
int) ā the batchās worker count;> 1selects the concurrent rendering (one aggregate spinner),<= 1the sequential one (plain echoed lines).spinner (
SpinnerPreset|None) ā aSpinnerPresetfrom theSPINNERScatalog (spinner=SPINNERS["moon"]) for the concurrent aggregate spinner. Ignored by the sequential and progress-bar renderings, and mutually exclusive withprogress_bar.progress_bar (
bool) ā render the aggregate indicator as a determinateclick.progressbar()instead of a spinner, for a sequential or concurrent batch alike. Requires a positivetotal(a bar needs a length) and is mutually exclusive withspinner.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-timeflag;Trueforces timing on withformat_duration()ās compact clock, a callable(seconds: float) -> strforces it on with a custom format, andFalseforces it off. Per-operation times come from asecondsargument tomark(), filled in automatically by anoperation()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 itstotal). Per-operation and finisher times are always elapsed.visible (
bool) ā whether the trail shows anything.Falsesilences the lines, the finisher and the aggregate indicator, whileok_countkeeps counting.live (
Literal['auto','always','never']) ā where the aggregate indicator may draw:"auto"(the default) on an interactive terminal only, unless--no-progressturns 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 atfinish()instead (seeecho_sequential).stream (
IO[str] |None) ā where to render; defaults tosys.stderrso the trail never mixes intostdoutdata.
- Raises:
ValueError ā if
progress_baris set without a positivetotal, or together withspinner, ifclockis neither"elapsed"nor"eta", or ifliveis not one ofWHEN.
- 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. Whentimeris on it is formatted and appended tomessageas(2.3s). Anoperation()handle fills this in from when it was created; pass it yourself when you already hold a duration.- Return type:
- 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 whentimeris on.A batch finishing inside
delaynever draws its indicator, so none of its buffered lines reached the stream. When the trail is the batchās output (echo_sequentialandvisible), 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:
- 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 (whentimeris 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:
objectThe four drawing strings composing a treeās left-hand rail.
- 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
commandas a tree with descriptions.Reuses
ctxwhen given (like the live invocation context), otherwise builds a throwaway one withresilient_parsing=True. The root line is labeled withprog_namewhen 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_commandfor the root,subcommandandaliasfor children,metavarfor operands,deprecatedfor that label), so the tree follows--themeand--color. The rail switches from box-drawing to ASCII when accessibility mode is active on the context (seeACCESSIBLE).Descriptions wrap at
width, resolved like help screens when not given (ctx.make_formatter(), honoring theterminal_widthandmax_content_widthcontext 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, underwrap --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:
- 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:
ExtraOptionA pre-configured
--treeflag that prints the hierarchy of nested subcommands and exits.Eager and value-less, like
ManOption. Part of the default option set injected bydefault_params(), so every@commandand@groupexposes it. Use@tree_optionto add it to a plain Click CLI.Note
The flag is named
--tree, not--show-treeor--commands.Rendering a hierarchy as a tree is conventionally named
treeacross ecosystems:eza --tree,lsblk --tree,poetry show --tree,cargo tree,pstree(1)andtree(1)itself (ps --forestbeing the lone dissenter).--commandswould suggest the flat listing--helpalready provides.The bare noun also lines up with the neighbouring
--help,--man,--paramsand--versioninformational flags. It is a flag rather than a registeredtreesubcommand, which could collide with the userās own command namespace.
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:
ParamTypeComma-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 configurableseparator(defaults to,), parses it into atuple[str, ...]and validates each value againstchoiceswhen that set is non-empty.The rendered metavar is
[a,b,c](separator-joined, parallel toChoiceās[a|b|c]):click_extra.highlight._HelpColorsMixinauto-detects the separator and highlights each individual value the same way it does forChoice.Note
Click ships no single-token equivalent: its idiom is
click.Choicewithmultiple=True, which repeats the flag (--tag a --tag b). pallets/click#2771 asks for a separator-based variant.MultiChoicefollows the SQLSELECT a, b, cconvention of the tabular use cases Click Extra supports, withclick_extra.table_options.ColumnsOptionas the headline consumer.Initialize the type.
- Parameters:
choices (
Sequence[str]) ā the accepted values. When non-empty,convert()rejects unknown tokens withfail. 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) ā whenTrue, a token must match one ofchoicesexactly. By default tokens match case-insensitively, as withEnumChoiceandThemeChoice, and the returned tuple holds the canonical (original-case) values fromchoices.
- get_metavar(param, ctx)[source]¶
Render
[a<sep>b<sep>c]whenchoicesis set,Noneotherwise.Nonefalls back to Clickās default rendering (the uppercasedname, likeMULTI).
- convert(value, param, ctx)[source]¶
Split
valueonseparatorand 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.
- class click_extra.types.LazyChoice(load, case_sensitive=True)[source]¶
Bases:
ChoiceA
Choicewhose values are produced on first use rather than at decoration.click.Choicefreezes 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. EveryChoicemethod readschoices, so the help screen, the generated documents and shell completion see the loaded values like any other.Keep the
loadcallable, which is called on each read ofchoices.- Parameters:
load (
Callable[[],Iterable[str]]) ā returns the accepted values. Called on each access ofchoices, so a cheap loader, or a cached one, is expected.case_sensitive (
bool) ā as forclick.Choice.
- class click_extra.types.ChoiceSource(*values)[source]¶
Bases:
EnumSource 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:
ChoiceChoice type for
Enum.Allows to select which part of the members to use as choice strings, by setting the
choice_sourceparameter to one of:ChoiceSource.KEYorChoiceSource.NAMEto use the key (thenameproperty),ChoiceSource.VALUEto use thevalue,ChoiceSource.STRto use thestr()string representation, orA custom callable that takes an
Enummember and returns a string.
Defaults to
ChoiceSource.STR, which only requires you to define the__str__()method on yourEnumto produce beautiful choice strings.The
transformparameter 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 whileshow_aliasesis on: aliases are reachable throughChoiceSource.KEY,ChoiceSource.NAMEandChoiceSource.VALUEalone, which are stuck on raw Python identifiers.Same as
click.Choice, but takes anEnumaschoices.Also defaults to case-insensitive matching.
- Raises:
TypeError ā if
choicesis not anEnumsubclass.ValueError ā if
choice_sourceis a string naming noChoiceSourcemember.
- choices: tuple[str, ...]¶
The strings available as choice.
Hint
Contrary to the parent
Choiceclass, we store choices directly as strings, not theEnummembers 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āsmember.The string produced by the choice source is passed through
transform.- Return type:
- 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
Durationparameter type: it accepts the same three input shapes but returnsNoneinstead of raising whenvaluematches none of them, so it suits classifying values read from files or other machine sources. UnlikeDuration, it does not collapse a zero duration toNone:parse_duration("0")istimedelta(0), letting callers tell a zero duration from an unparsable value.Noneis returned only for an empty value, a future timestamp, or a value matching no known form.- Parameters:
- Return type:
- Returns:
The parsed
timedelta(possibly zero), orNone.
- 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"istimedelta(0)), orNonefor anything that is not a friendly duration: ISO 8601 forms, calendar units (months, years), and empty or unrecognized values. Seeparse_duration()for the format-detecting umbrella.
- 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"istimedelta(0)), orNonefor anything that is not an ISO 8601 duration: friendly forms, calendar (year or month) components, and empty or unrecognized values. Seeparse_duration()for the format-detecting umbrella.
- class click_extra.types.Duration[source]¶
Bases:
ParamTypeParse 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 like7. Case-insensitive.ISO 8601 duration:
P7D,PT12H,P1WT6H. Case-insensitive.RFC 3339 absolute timestamp:
2024-05-01T00:00:00Zor with an offset like+02:00. Converted at parse time to its age,now - timestamp.
Some inputs parse to
Noneinstead of atimedelta: a zero duration, an empty string, and a timestamp in the future. Cutoff options (cooldowns, timeouts, retention windows, cache TTLs) readNoneas āno cutoffā, so a0on 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 returnsNoneinstead 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
daysorweeksinstead.
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
VersionScreentake 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 fromCLI_ECOSYSTEM_PACKAGESeven when it sits under one of those packages, asclick_extra.__main__does in Click Extraās own binary.- Return type:
- 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_THEMEand the background-sniffingautoalike, and drops its color under the monochromemanpagepalette. A style captured at import would paint every theme with one palette: the bright white program name ofdarkis 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.
- click_extra.version.unstyled(text)[source]¶
Identity style, for a segment left with no color of its own.
- Return type:
- class click_extra.version.VersionScreen(logo, tagline='', facts=<function default_facts>, gutter=' ')[source]¶
Bases:
objectA logo, and the facts to seat beside it, as
--versionshould 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
VersionOptionthrough itsscreenargument, or to a whole CLI throughdefault_params(screen=ā¦).- logo: str | Sequence[str] | Callable[[], str | Sequence[str]]¶
The mark, pre-rendered, or a callable producing it. A string splits on newlines.
A callable defers the rendering to the first
--versionthat draws the screen, asfactsdoes for its values: a mark painted by code, from an image say, then costs nothing to the invocations that never ask for it.
- 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
--versionis asked for.
- 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.
- 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
--versioncannot drift apart on color.
- 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
Nonewhen 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 reportsshutilās 80-column default, wide enough that a redirected-but-forced-color run still gets the screen it asked for.
- 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
autodefault, exactly asclick.echodoes when it decides whether to strip the codes itself.Note
The stream probed is
sys.stdout, not Clickās own resolution of it.click.echoreaches stdout through a private cached wrapper, which fixes the output encoding and delegatesisatty()to the stream beneath it, so both answer alike. Click deprecates the public accessor of that wrapper,click.get_text_stream().- Return type:
- 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 oftemplate, in order: the literal text before the field, the identifier the field resolves on the option (modulefor{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.
- 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:
ExtraOptionGathers 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
--versionoption 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 oftemplate_fields(for example{"version": "1.2.3"}).styles (
Mapping[str,Callable[[str],str] |None] |None) ā mapping of template field name to itsStyle, merged overdefault_styles. PassNoneas a value to clear a fieldās default style. Keys must be members oftemplate_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) ā aVersionScreento draw instead of the one-line message, whenever the terminal can take it. Left unset,--versionprints the one-line message.
- Raises:
TypeError ā when a key of
fieldsorstylesnames 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-providedstylesare 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 defaultdarkpalette,invoked_commandis bright white bold andsuccessis 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_propertythat would otherwise resolve the field, and is recorded soreset_resolution()can tell the two apart. Every caller that pins a field goes through here: a baresetattrsets the value without the record, and the next reset then discards it.
- 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
--versionexample 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:
- 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:
--versionis 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:
modulethen defers to the module of the root commandās callback.- Return type:
- 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 aCliRunnerdriven 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 owninvoke(), inside the Click ecosystem.The Sphinx
click:rundirective is that shape: without this, a documented--versionwould 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
Nonewhen the command has no callback (a bareclick.Group) or its module is not imported, leaving the walkās own answer in place.- Return type:
- property module: ModuleType[source]¶
Returns the module in which the CLI resides.
- property module_file: str | None[source]¶
Returns the moduleās file full path.
Nonefor a module with no file, like the__main__ofpython -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_versionproperty below, which uses the standard libraryimportlib.metadataAPI.Clickās own
version_optionreads the package metadata only (pallets/click#2598). Click Extra reads__version__too, for the scripts and codebases that set it.
- property package_version: str | None[source]¶
Returns the package version if installed.
Resolved from the distribution name (see
_distribution_name) viaimportlib.metadata.version(). ReturnsNoneif 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.Noneif 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.Noneif 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 -mruns it as__main__, while a console script or a compiled binary imports it aspackage.__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 like1.2.3.dev0+abc1234. This helps identify the exact commit a dev build was produced from. Whengit_short_hashfinds 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 like1.2.3.dev0+abc1234+xyz5678.
- property git_repo_path: Path | None[source]¶
Find the Git repository root directory.
Walks up from
_search_startto the first directory holding a.gitentry: seefind_git_root().
- property git_branch: str | None[source]¶
Returns the current Git branch name.
Checks for a pre-baked
__git_branch__dunder first, thengit 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, thengit 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, thengit 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, thengit show -s --format=%ci HEAD, then.git_archival.json(whosenode-dateis strict ISO 8601, like2021-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, thengit describe --tags --exact-match HEAD, then.git_archival.json.Returns
Noneif 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, thengit rev-list -1on the tag returned bygit_tag, then.git_archival.json. ReturnsNoneif 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 parsesgit describe --tags --long, then falls back to.git_archival.json.Nonewhen no tag is reachable or Git is unavailable.
- property git_dirty: str | None[source]¶
Work-tree state:
"dirty","clean"orNone.Checks for a pre-baked
__git_dirty__dunder first, then runsgit status --porcelain.Nonewhen not in a Git repository or Git is unavailable. There is no.git_archival.jsonfallback: 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: seeBUILD_RESOLVERSandresolve_build_time().
- property build_os: str | None[source]¶
The operating system the build ran on.
Reads the pre-baked
__build_os__dunder. Seeresolve_build_os().
- property build_target: str | None[source]¶
The platform a distribution built here installs on.
Reads the pre-baked
__build_target__dunder. Seeresolve_build_target().
- property build_target_arch: str | None[source]¶
The CPU architecture the build ran on.
Reads the pre-baked
__build_target_arch__dunder. Seeresolve_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.
multicalldispatch relies on that, running one CLI under many names in sequence, and aprog_namepassed tomain()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 nofield_idfor the style of the templateās literal segments, which ismessage_stylealone.
- colored_template(template=None)[source]¶
Insert ANSI styles to a message template.
Accepts a custom
templateas 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:
- render_message(template=None)[source]¶
Render the version string from the provided template.
Accepts a custom
templateas parameter, otherwise uses the defaultself.colored_template()produced by the instance.A CLI carrying a
VersionScreengets 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-coloror 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
--accessiblekeeps the plain message.
- Return type:
- click_extra.version.reset_version_resolution(command)[source]¶
Reset every
VersionOptionin 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--versioncallback, which resolves the very chain this function clears.- Return type:
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 (
PILvsPillow,jwtvsPyJWT). A name already matching an installed distribution is returned as-is; otherwise it is resolved throughimportlib.metadata.packages_distributions(). Ambiguous mappings (one import name to several distributions) returnNone: passpackage_nameexplicitly to disambiguate.Returns
Nonewhen nothing installed provides the name, which is what makes it usable as a test of whether a module belongs to a real distribution.
- 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
gitsubcommand, mapped to that subcommandās args.git_tag_sha,git_distanceandgit_dirtyare excluded: their resolution is not a single staticgitinvocation whose stripped output is the value.git_tag_shadereferences the tag (git rev-list -1 <tag>),git_distanceparsesgit describeandgit_dirtymaps the porcelain status to a label. Seeresolve_git_tag_sha(),resolve_git_distance()andresolve_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 agitcommand 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
gitcommand and return its output, without the final newline.A command that fails returns
None: nogiton thePATH, a non-zero exit status, like the one of acwdoutside a repository, or a command still running aftertimeoutseconds. Setcheckto raise instead: anOSErrorwhengitdoes not start, asubprocess.CalledProcessErroron a non-zero exit status, and asubprocess.TimeoutExpiredwhen the time runs out.By default an empty output returns
Nonetoo, like a failure. Setallow_emptyto keep the empty string, which some commands use meaningfully:git status --porcelainprints 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.
- click_extra.version_facts.resolve_git_dirty(cwd=None)[source]¶
Report the work-tree state as
"dirty","clean"orNone.Returns
"dirty"whengit status --porcelainreports uncommitted changes,"clean"when it reports none, andNonewhen the state cannot be determined (not a Git repository, orgitis unavailable).The empty output of a clean work tree is meaningful here, so the command is run with
allow_emptyto tell it apart from a failure.
- 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>. ReturnsNonewhen no tag is reachable, the directory is not a Git repository, orgitis unavailable.
- click_extra.version_facts.resolve_git_tag_sha(cwd=None)[source]¶
Resolve the commit SHA the tag at
HEADpoints at, orNone.Runs
git describe --tags --exact-match HEADto find the tag, thengit rev-list -1 <tag>to dereference it to a commit SHA. ReturnsNonewhenHEADis not at a tagged commit, the directory is not a Git repository, orgitis unavailable.
- 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(orNonewhen 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.jsonfallbacks.the
click-extra prebake allcommand, 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.
- click_extra.version_facts.build_moment()[source]¶
The instant a build happens, in UTC.
Reads
SOURCE_DATE_EPOCHwhen the build sets it, so two runs of a reproducible build stamp the same instant. Falls back to the current time.- Return type:
- 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:
- click_extra.version_facts.resolve_build_os()[source]¶
The operating system the build runs on.
- Return type:
- 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-arm64says the binary needs macOS 15, whereresolve_build_os()only says it was built on macOS.- Return type:
- click_extra.version_facts.resolve_build_target_arch()[source]¶
The CPU architecture the build runs on.
- Return type:
- 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_RESOLVERSandenv_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 itsBUILD_TIME,BUILD_OSandBUILD_TARGETconstants.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 allis the only thing that ever writes these. A field left unbaked stays empty, and itsVersionOptionaccessor answersNone.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_branchis baked as__git_branch__: the one spellingVersionOptionreads back, andclick-extra prebakewrites. Keeping the contract in one place is what lets the two sides stay agreed.- Return type:
- click_extra.version_facts.find_git_root(start)[source]¶
Walk up from start to the first folder holding a
.gitentry.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.
- click_extra.version_facts.find_archival_file(start)[source]¶
Walk up from start to find a
.git_archival.jsonfile.Returns the first match in start or any of its parents, or
None.
- click_extra.version_facts.read_archival(path)[source]¶
Parse a
.git_archival.jsonfile into a string mapping.Returns an empty mapping when the file is missing, unreadable, or not a valid JSON object.
- click_extra.version_facts.archival_field(data, field_id)[source]¶
Resolve a
git_*field from parsed.git_archival.jsondata.data follows the setuptools-scm archival schema:
node(full hash),node-date,describe-nameandref-names. The same file is read by setuptools-scm and Dunamai, so a single committed.git_archival.jsonserves all three.Returns
Nonewhen the field is absent, empty, or still holds an unsubstituted$Format:ā¦$placeholder. That last case is what a plain checkout contains:git archiveperforms 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.
- click_extra.version_facts.read_direct_url(distribution)[source]¶
Parse the
direct_url.jsonrecord 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://...orpip 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.
- click_extra.version_facts.direct_url_field(data, field_id)[source]¶
Resolve a
git_*field from a parseddirect_url.jsonrecord.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 answersgit_long_hash, and its first 7 charactersgit_short_hash.Every other field answers
None. Thevcs_info.requested_revisionthe record may also hold names a branch, a tag or a commit, with nothing to tell which.
- 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.
- click_extra.version_facts.meta_value(meta, *keys)[source]¶
Return the first non-empty value among core-metadata keys.
Each key is tested with
inbefore[]reads it:[]on a missing key returnsNonewith aDeprecationWarning, and is to raiseKeyError.
- click_extra.version_facts.resolve_author(meta)[source]¶
Return the author(s) from metaās core metadata, or
None.Prefers the
Authorfield, then theMaintainerfield, then the display name parsed out of theAuthor-email/Maintainer-emailfields (Name <email>). ReturnsNonewhen meta isNoneor no author can be determined.
- click_extra.version_facts.resolve_license(meta)[source]¶
Return the license from metaās core metadata, or
None.Prefers the SPDX
License-Expressionfield (core metadata 2.4+). Falls back to the human-readable name of the firstLicense ::trove classifier, then to the free-formLicensefield (which may hold the full license text). ReturnsNonewhen meta isNoneor no license can be determined.
- click_extra.version_facts.platform_label()[source]¶
Current platform and CPU architecture, as displayed to the user.
- Return type:
- 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 factsdefault_facts()puts on the version screen, joined for a CLI that would rather spend one line of its plain--versionon them than draw a screen at all:@version_option(message="{prog_name} {version} (" + env_summary() + ")").- Return type:
- 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:
- 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,
dictpreserving 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