click_extra package¶
Expose package-wide elements.
- 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 plain, 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.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--show-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(*args, help=None, **attrs)[source]¶
Bases:
_ParameterMixin,ArgumentWrap
cloup.Argument, itself inheriting fromclick.Argument.Inherits first from
_ParameterMixinto allow future overrides of Click’sParametermethods.
- 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 (cabc.Sequence[str] | str | None) – a string that shows up as parameter name. This can be used as alternative to param in cases where custom validation should happen. If it is a string it’s used as such, if it’s a list then each item is quoted and separated.
- class click_extra.CLITestCase(cli_parameters=<factory>, skip_platforms=<factory>, only_platforms=<factory>, timeout=None, exit_code=None, strip_ansi=False, output_contains=<factory>, stdout_contains=<factory>, stderr_contains=<factory>, output_regex_matches=<factory>, stdout_regex_matches=<factory>, stderr_regex_matches=<factory>, output_regex_fullmatch=None, stdout_regex_fullmatch=None, stderr_regex_fullmatch=None, execution_trace=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_parameters appended, then checks the captured result against the expectation directives below. A case with no expectation only asserts the command ran (plus exit_code, if set).
- cli_parameters: tuple[str, ...] | str¶
Arguments and options appended to the command-under-test.
A plain string is split into arguments (on spaces on Windows, with shlex elsewhere); a list or tuple is used as-is.
- skip_platforms: Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[_TNestedReferences]]¶
Platforms (or platform-group IDs) on which to skip this case.
Accepts extra_platforms identifiers such as linux, macos, windows, in any case, mixed freely with group IDs.
- only_platforms: Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[_TNestedReferences]]¶
Restrict this case to these platforms; skip it everywhere else.
The mirror image of skip_platforms, using the same identifiers.
- timeout: float | str | None = None¶
Seconds before the command is killed and the case fails as a timeout.
Falls back to the command’s –timeout default, then to no limit.
- 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). See output_contains for the merged-stream semantics.
- stdout_regex_matches: tuple[Pattern | str, ...] | str¶
Regexes that must each match somewhere in stdout (searched, re.DOTALL).
- stderr_regex_matches: tuple[Pattern | str, ...] | str¶
Regexes that must each match somewhere in stderr (searched, re.DOTALL).
- output_regex_fullmatch: Pattern | str | None = None¶
Regex that must fully match the combined output, line by line. See output_contains for the merged-stream semantics.
- stdout_regex_fullmatch: Pattern | str | None = None¶
Regex that must fully match stdout, line by line.
- stderr_regex_fullmatch: Pattern | str | None = None¶
Regex that must fully match stderr, line by line.
- execution_trace: str | None = None¶
Rendering of the command execution and its output.
Populated after the case runs, for inspection on failure; not a directive you set in a test plan.
- property has_separate_stream_directives: bool¶
Whether any
stdout_*orstderr_*directive (separate streams) is set.
- run_cli_test(command, additional_skip_platforms, default_timeout)[source]¶
Run a CLI command and check its output against the test case.
The provided command can be either:
a path to a binary or script to execute;
a command name to be searched in the PATH,
a command line with arguments to be parsed and executed by the shell.
`{todo} Add support for environment variables. `- Return type:
- class click_extra.Choice(choices, case_sensitive=True)[source]¶
Bases:
ParamType[ParamTypeValue],Generic[ParamTypeValue]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
- normalize_choice(choice, ctx)[source]¶
Normalize a choice value, used to map a passed string to a choice. Each choice must have a unique normalized value.
By default uses
Context.token_normalize_func()and if not case sensitive, convert it to a casefolded value.Added in version 8.2.0.
- Return type:
str
- get_metavar(param, ctx)[source]¶
Returns the metavar default for this param if it provides one.
- Return type:
str | None
- get_missing_message(param, ctx)[source]¶
Message shown when no choice is passed.
Changed in version 8.2.0: Added
ctxargument.- Return type:
str
- convert(value, param, ctx)[source]¶
For a given value from the parser, normalize it and find its matching normalized value in the list of choices. Then return the matched “original” choice.
- Return type:
ParamTypeValue
- get_invalid_choice_message(value, ctx)[source]¶
Get the error message when the given choice is invalid.
- Parameters:
value (t.Any) – The invalid value.
Added in version 8.2.
- Return type:
str
- shell_complete(ctx, param, incomplete)[source]¶
Complete choices that start with the incomplete value.
- Parameters:
ctx (Context) – Invocation context for this command.
param (Parameter) – The parameter that is requesting completion.
incomplete (str) – Value being completed. May be empty.
Added in version 8.0.
- Return type:
list[CompletionItem]
- 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.- invoke(cli, *args, input=None, env=None, catch_exceptions=True, 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.
Allow forcing of the
colorproperty at the class-level viaforce_colorattribute.Adds a special case in the form of
color="forced"parameter, which allows colored output to be kept, while forcing the initialization ofContext.color = True. This is not allowed in current implementation ofclick.testing.CliRunner.invoke()because of colliding parameters.Strips all ANSI codes from results if
colorwas explicirely 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 casted 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) – same asclick.testing.CliRunner.invoke().color (
bool|Literal['forced'] |None) – If a boolean, the parameter will be passed as-is toclick.testing.CliRunner.isolation(). If"forced", the parameter will be passed asTruetoclick.testing.CliRunner.isolation()and an extracolor=Trueparameter will be passed to the invoked CLI.extra (
Any) – same asclick.testing.CliRunner.invoke(), but colliding parameters are allowed and properly passed on to the invoked CLI.
- Return type:
- exception click_extra.ClickException(message)[source]¶
Bases:
ExceptionAn exception that Click can handle and show to the user.
- exit_code = 1¶
The exit code for this exception.
- class click_extra.ClickExtraConfig(test_plan=<factory>, prebake=<factory>)[source]¶
Bases:
objectSchema for the
[tool.click-extra]configuration section.Wired as the
config_schemaof the top-levelclick-extragroup, so every subcommand reads the same section and pulls its own sub-table throughget_tool_config().- test_plan: TestPlanConfig¶
The
[tool.click-extra.test-plan]sub-table (file/inline/timeout).
- prebake: PrebakeConfig¶
The
[tool.click-extra.prebake]sub-table (target module).
- 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 ofCOLOR_WHEN(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--show-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. 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.
- Return type:
- class click_extra.ColumnSpec(id, label, description='')[source]¶
Bases:
objectRich description of a single column in a rendered table.
Three fields, all required-by-convention even though
descriptiondefaults to empty so quick prototypes do 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.
Note
Frozen + slots: instances are immutable and lightweight. Tuples of
ColumnSpecare intended to be defined as module-level constants (likeclick_extra.parameters.ShowParamsOption.TABLE_HEADERS).
- class click_extra.ColumnsOption(param_decls=None, columns=None, type=None, 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 --show-params
The selection is stored in
ctx.meta[click_extra.context.COLUMNS]and consumed by table-rendering callbacks (likeclick_extra.parameters.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, version_fields=None, config_schema=None, schema_strict=False, fallback_sections=(), config_validators=(), included_params=None, extra_option_at_end=True, populate_auto_envvars=True, extra_keywords=None, excluded_keywords=None, **kwargs)[source]¶
Bases:
_HelpColorsMixin,CommandLike
cloup.command, with sane defaults and extra help screen colorization.List of extra parameters:
- Parameters:
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.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.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.populate_auto_envvars (
bool) – forces all parameters to have their auto-generated environment variables registered. This address the shortcoming ofclickwhich only evaluates them dynamically. By forcing their registration, the auto-generated environment variables gets displayed in the help screen, fixing click#2483 issue. On Windows, environment variable names are case-insensitive, so we normalize them 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 = False(Cloup feature)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--show-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, ... } )
- 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.- Return type:
- make_context(info_name, args, parent=None, **extra)[source]¶
Intercept the call to the original
click.core.Command.make_contextso we can keep a copy of the raw, pre-parsed arguments provided to the CLI.The result are passed to our own
Contextconstructor which is able to initialize the context’smetaproperty under our ownclick_extra.context.RAW_ARGSentry. This will be used inShowParamsOption.print_params()to print the table of parameters fed to the CLI.See also
See
click_extra.context.RAW_ARGSfor the full rationale and the upstream-proposal notes (related: click#1279).- 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 color options before delegating, so
--color/--no-colorcolorize the eager help and version screens regardless of their position on the command line. See_resolve_color_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.ConfigFormat(*values)[source]¶
Bases:
EnumAll configuration formats, associated to their support status.
The first element of the tuple is a sequence of file extensions associated to the format. Patterns are fed to
wcmatch.globfor matching, and are influenced by the flags set on theConfigOptioninstance.The second element indicates whether the format is supported or not, depending on the availability of the required third-party packages. This evaluation is performed at runtime when this module is imported.
Caution
The order is important for both format members and file patterns. It defines the priority order in which formats are tried when multiple candidate files are found.
- TOML = (('*.toml',), True, 'TOML')¶
- YAML = (('*.yaml', '*.yml'), True, 'YAML')¶
- JSON = (('*.json',), True, 'JSON')¶
- JSON5 = (('*.json5',), True, 'JSON5')¶
- JSONC = (('*.jsonc',), True, 'JSONC')¶
- HJSON = (('*.hjson',), True, 'Hjson')¶
- INI = (('*.ini',), True, 'INI')¶
- XML = (('*.xml',), True, 'XML')¶
- PYPROJECT_TOML = (('pyproject.toml',), True, 'pyproject.toml')¶
- class click_extra.ConfigOption(param_decls=None, metavar='CONFIG_PATH', 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=4104, roaming=True, force_posix=False, search_pattern_flags=285504, search_parents=False, stop_at=Sentinel.VCS, excluded_params=None, included_params=None, strict=False, config_schema=None, schema_strict=False, fallback_sections=(), config_validators=(), **kwargs)[source]¶
Bases:
ExtraOption,ParamStructureA pre-configured option adding
--config CONFIG_PATH.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--show-params. Will default to the value ofDEFAULT_EXCLUDED_PARAMS.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.
- file_pattern_flags¶
Flags provided to all calls of
wcmatch.fnmatch.Applies to the matching of file names against supported format patterns specified in
file_format_patterns.Important
The
SPLITflag is always forced, as our multi-pattern design relies on it.
- 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_pattern_flags¶
Flags provided to all calls of
wcmatch.glob.Applies to both the default pattern and any user-provided pattern.
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.
- 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 (.gitor.hg) (default).A
Pathorstr: stop at that directory.
- included_params: frozenset[str] | None¶
Allowlist of parameter IDs, mutually exclusive with
excluded_params.Nonedisables the allowlist. It is resolved intoexcluded_paramsbybuild_param_trees(), once every parameter ID is known.
- 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 via get_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, silently ignore unrecognized keys.
Note
This is distinct from
strict, which controls whethermerge_default_maprejects config keys not matching CLI parameters.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.
- 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 (currently 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_pathsimply runs alongside the built-in: both validators are called, both sets of errors surface.
- property excluded_params: frozenset[str][source]¶
Generates the default list of fully-qualified IDs to exclude.
Danger
It is only called once to produce the default exclusion list if the user did not provided its own.
It was not implemented in the constructor but made as a property, to allow for a just-in-time call within the current context. Without this trick we could not have fetched the CLI name.
- 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
<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.Todo
Use platformdirs for more advanced configuration folder detection?
- 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.- Return type:
OptionHelpExtra
- parent_patterns(pattern)[source]¶
Generate
(root_dir, file_pattern)pairs for searching.Each yielded pair can be passed directly to
glob.iglob(file_pattern, root_dir=root_dir)so that every sub-pattern (whether fromBRACEorSPLITexpansion) is correctly scoped to the same directory.root_dirisNonefor entirely magic patterns that will be evaluated relative to the current working directory.Stops when reaching the root folder, the
stop_atboundary, or an inaccessible directory.
- search_and_read_file(pattern)[source]¶
Search filesystem or URL for files matching the
pattern.If
patternis an URL, download its content. A pattern is considered an URL only if it validates as one and starts withhttp://orhttps://. All other patterns are considered glob patterns for local filesystem search.Returns an iterator of the normalized location and its raw content, for each one matching the pattern. Only files are returned, directories are silently skipped.
This method returns the raw content of all matching patterns, without trying to parse them. If the content is empty, it is still returned as-is.
Also includes lookups into parents directories if
self.search_parentsisTrue.Raises
FileNotFoundErrorif no file was found after searching all locations.
- parse_conf(content, formats)[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.Attention
Formats whose parsing raises an exception or does not return a
dictare considered a failure and are skipped.This follows the parse, don’t validate principle.
- 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,
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.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 the CLI-parameter strict check, so user-controlled keys (like mappings whose keys are data, not flag names) don’t tripstrict=True.Note
This recomputes the filtered config that
run_config_validation()already produces asmerged_conf.load_conf()installs that result directly and skips this method; it stays as the standalone entry point for external callers.- 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.
By relying on Click’s
default_map, we make sure that precedence is respected. 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.We intentionally do not add a custom
ParameterSource.CONFIG_FILEenum member:ParameterSourceis a closed enum in Click, and monkeypatching it would be fragile. Besides, config values end up indefault_map, so Click already reports them asParameterSource.DEFAULT_MAP, which is accurate.- Return type:
- class click_extra.ConfigValidator(extension_path, validator, description='')[source]¶
Bases:
objectRegister an app-defined extension validator for one sub-tree of the configuration file.
Apps register validators via the
config_validators=kwarg onConfigOption(or the matching decorator) to extend click-extra’s built-in CLI-parameter strict check with custom validation logic. Each validator targets a single dottedextension_pathrelative to the app’s configuration section. Click-extra passes the matching sub-tree straight through to the registered validator: the strict check skips it, the schema machinery treats it as opaque, and the user’s logic owns the result. The validator runs both during--validate-configand during normal config loading.- Parameters:
extension_path (
str) – Dotted path of the sub-tree the validator owns, relative to the app’s section in the configuration file. For example, an app namedmy-cliwithextension_path="managers"receives the contents of the[my-cli.managers]table.validator (
Callable[[dict[str,Any]],None]) – Callable taking the sub-tree dict and raisingValidationErroron failure. Must be a pure function: no side effects on the click context, no print statements. The caller decides how to surface the error.description (
str) – Optional human-readable summary of what the validator checks. Surfaces in documentation generators that introspect the decorator (like autodoc), and may be reused in--helptext in a future release.
- 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, **kwargs)[source]¶
Bases:
ContextLike
cloup._context.Context, but with the ability to populate the context’smetaproperty at instantiation.Also defaults
colortoTruefor root contexts (those without a parent), so help screens are always colorized, even when piped. Click’s own default isNone(auto-detect via TTY), which strips colors in non-interactive contexts.Parent-to-child color inheritance is handled by Click itself at
Context.__init__time, so no property override is needed.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.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.- formatter_class¶
alias of
HelpFormatter
- class click_extra.DateTime(formats=None)[source]¶
-
The DateTime type converts date strings into datetime objects.
The format strings which are checked are configurable, but default to some common (non-timezone aware) ISO 8601 formats.
When specifying DateTime formats, you should only pass a list or a tuple. Other iterables, like generators, may lead to surprising results.
The format strings are processed using
datetime.strptime, and this consequently defines the format strings which are allowed.Parsing is tried using each format, in order, and the first format which parses successfully is used.
- Parameters:
formats (
Sequence[str] |None) – A list or tuple of date format strings, in the order in which they should be tried. Defaults to'%Y-%m-%d','%Y-%m-%dT%H:%M:%S','%Y-%m-%d %H:%M:%S'.
- to_info_dict()[source]¶
Gather information that could be useful for a tool generating user-facing documentation.
Use
click.Context.to_info_dict()to traverse the entire CLI structure.Added in version 8.0.
- Return type:
DateTimeInfoDict
- get_metavar(param, ctx)[source]¶
Returns the metavar default for this param if it provides one.
- Return type:
str | None
- convert(value, param, ctx)[source]¶
Convert the value to the correct type. This is not called if the value is
None(the missing value).This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.
The
paramandctxarguments may beNonein certain situations, such as when converting prompt input.If the value cannot be converted, call
fail()with a descriptive message.- Parameters:
value (t.Any) – The value to convert.
param (Parameter | None) – The parameter that is using this type to convert its value. May be
None.ctx (Context | None) – The current context that arrived at this value. May be
None.
- Return type:
datetime
- class click_extra.EnumChoice(choices, case_sensitive=False, choice_source=ChoiceSource.STR, show_aliases=False)[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.Same as
click.Choice, but takes anEnumaschoices.Also defaults to case-insensitive matching.
- 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.- Return type:
- class click_extra.ExtraOption(*args, group=None, **attrs)[source]¶
Bases:
OptionDedicated to option implemented by
click-extraitself.Provides a way to identify Click Extra’s own options with certainty, and restores the pre-Click-8.4.0 contract that eager callbacks can introspect their own parameter source from within their own callback.
Note
This is the one click-extra class that deliberately keeps the
Extraprefix. The8.0.0cleanup dropped it everywhere else (ExtraCommandbecameCommand,ExtraContextbecameContext, and so on), shadowing the matching Cloup or Click class. Here the plainOptionname is already taken by the user-facing enhanced wrapper this class subclasses, so the prefix is not legacy baggage but a real distinction:ExtraOptionmarks click-extra’s own built-in options. That marker is load-bearing, sinceCommandsorts 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.- handle_parse_result(ctx, opts, args)[source]¶
Record the parameter source before delegating to the base implementation.
Warning
Click
8.4.0(PR pallets/click#3404) reorderedParameter.handle_parse_resultsoctx.set_parameter_sourceruns afterprocess_value. Eager callbacks that introspect their own provenance viactx.get_parameter_source(self.name)therefore readNoneinstead of the actual source.ColorOption,ConfigOption, andShowParamsOptionall rely on this introspection to decide whether an env var should override the default (--color), whether the--configpath was user-supplied, and what to render in theSourcecolumn of--show-params.Click
8.4.1restored the pre-8.4.0contract upstream (PR pallets/click#3484), so this override only matters for Click8.4.0itself, which sits inside click-extra’s supported>= 8.3.1range. Pre-recording the source here for eager options keeps that contract on every supported Click.super().handle_parse_resultre-records the same value at the canonical time, so the slot arbitration logic introduced by #3404 is unaffected:slot_emptyis computed fromctx.params, not from_parameter_source.consume_valueruns twice as a side effect: once here and once insuper. Both calls are pure for click-extra’s existing eager flag-style options (no env var side effects, no prompt). Should a future eager subclass need prompt behavior, this override would need to cache the result instead.The pre-record is skipped when the slot already carries a source from an earlier option sharing the same
name(Click’s feature-switch pattern), so the arbitration logic insuperstill sees the originalexisting_sourcerather than a stale rewrite from this option.
- 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 lazy flag controls if the file should be opened immediately or upon first IO. The default is to be non-lazy for standard input and output streams as well as files opened for reading, lazy otherwise. When opening a file lazily for reading, it is still opened temporarily for validation, but will not be held open until first IO. lazy is mainly useful when opening for writing to avoid creating the file until it is needed.
Files can also be opened atomically in which case all writes go into a separate file in the same folder and upon completion the file will be moved over to the original location. This is useful if a file regularly read by other users is modified.
See File Arguments for more information.
Changed in version 2.0: Added the
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. None means any whitespace. For all parameters the general rule is that whitespace splits them up. The exception are paths and files which are split by
os.path.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.- Parameters:
value (str | os.PathLike[str] | t.IO[t.Any]) – The value to convert.
param (Parameter | None) – The parameter that is using this type to convert its value. May be
None.ctx (Context | None) – The current context that arrived at this value. May be
None.
- Return type:
t.IO[t.Any]
- shell_complete(ctx, param, incomplete)[source]¶
Return a special completion marker that tells the completion system to use the shell to provide file path completions.
- Parameters:
ctx (Context) – Invocation context for this command.
param (Parameter) – The parameter that is requesting completion.
incomplete (str) – Value being completed. May be empty.
Added in version 8.0.
- Return type:
list[CompletionItem]
- 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],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().- Return type:
- class click_extra.Group(*args, help_command=True, **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.
- add_command(cmd, name=None, **kwargs)[source]¶
Like
cloup.Group.add_command, but replaces an auto-injectedHelpCommandwhen the user registers their ownhelpsubcommand.- Return type:
- invoke(ctx)[source]¶
Inject
_default_subcommandsand_prepend_subcommandsfrom config.If the user has not provided any subcommands explicitly, and the loaded configuration contains a
_default_subcommandslist for this group, those subcommands are injected intoctx.protected_argsso that Click’s normalGroup.invoke()dispatches them._prepend_subcommandsalways prepends subcommands to the invocation, regardless of whether CLI subcommands were provided. Only works withchain=Truegroups.- Return type:
- 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:
ColorizedCommandSynthetic 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.HelpFormatter(*args, **kwargs)[source]¶
Bases:
HelpFormatterExtends Cloup’s custom HelpFormatter to highlights options, choices, metavars and default values.
This is being discussed for upstream integration at:
Forces theme to the active one for the current Click context.
Also transform Cloup’s standard
HelpThemeto our ownHelpTheme.Resolves the active theme via
click_extra.theme.get_current_theme(), which reads the per-invocation pick from the Click context (set byThemeOption) and falls back to the module-level default when no context is active.- write_usage(prog, args='', prefix=None)[source]¶
ANSI-aware override of
cloup.HelpFormatter.write_usage.On Click
8.3.x,click.formatting.wrap_textmeasures line length with rawlen(), counting every byte of the ANSI escape sequences embedded ininitial_indent(the styledUsage:heading + invoked-command name). With 24-bit RGB themes (like Solarized Dark, Dracula, Nord, Monokai), each styled token carries 17+ extra bytes of escape, which inflates the measured line beyond the width budget and causes premature wraps mid-token:[OPTIONS\n ].Cloup styles
prefixandprogthen delegates to click’sHelpFormatter.write_usage(), inheriting the bug. This override re-applies the same styling, then bypasseswrap_textwhenever the visible content fits on a single line: the common case for short usage strings where wrapping is unnecessary. Lines that genuinely overflow the visible width fall back to click’s implementation: the wrap point may still be sub-optimal but the output stays syntactically valid.Note
Click
8.4.0(PR pallets/click#3420) madeclick.formatting.TextWrapperANSI-aware by counting visible width instead of raw bytes, so this override is a no-op fast path on Click>= 8.4.0and only fixes wrapping on the Click8.3.xreleases click-extra still supports.Todo
Drop this override once the minimum supported Click rises to
8.4.0(which includespallets/click#3420). Theterm_len-based visible-width check below becomes redundant once Click’s own wrapper counts visible width.- Return type:
- keywords: HelpKeywords = 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())¶
- excluded_keywords: HelpKeywords | None = 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:
- class click_extra.HelpKeywords(cli_names=<factory>, subcommands=<factory>, command_aliases=<factory>, arguments=<factory>, long_options=<factory>, short_options=<factory>, choices=<factory>, choice_metavars=<factory>, metavars=<factory>, envvars=<factory>, defaults=<factory>)[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.
- 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>, 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:
TypeVar(T)
- error()¶
Style applied to the
ERRORlevel name in log records.Example:
ERROR: Configuration file not found.- Return type:
TypeVar(T)
- warning()¶
Style applied to the
WARNINGlevel name in log records.Example:
WARNING: Requested 16 jobs exceeds available CPU cores (8).- Return type:
TypeVar(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:
TypeVar(T)
- debug()¶
Style applied to the
DEBUGlevel name in log records.Example:
DEBUG: Resolved /etc/myapp/config.toml.- Return type:
TypeVar(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:
TypeVar(T)
- subcommand()¶
Style applied to subcommand names: in a group’s command list and wherever they are referenced in prose.
- Return type:
TypeVar(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:
TypeVar(T)
- metavar()¶
Style applied to type metavars (
INTEGER,TEXT,PATH,FILE, …) that follow an option name in the synopsis column.- Return type:
TypeVar(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:
TypeVar(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:
TypeVar(T)
- default()¶
Style applied to the default-value content inside
[default: ...]bracket fields. Falls back tobracketwhen left atidentity.- Return type:
TypeVar(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:
TypeVar(T)
- required()¶
Style applied to the
requiredlabel inside bracket fields on mandatory options. Falls back tobracketwhen left atidentity.- Return type:
TypeVar(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:
TypeVar(T)
- deprecated()¶
Style applied to
(DEPRECATED)/(Deprecated: reason)markers appended to options and commands.- Return type:
TypeVar(T)
- search()¶
Style applied to substring matches in <cli> help --search output, so users can spot where their query matched.
- Return type:
TypeVar(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:
TypeVar(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:
TypeVar(T)
- with_(**kwargs)[source]¶
Derives a new theme from the current one, with some styles overridden.
Returns the same instance if the provided styles are the same as the current.
- 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],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.execution.JobCount object>, help="Number of parallel jobs. Accepts an integer, 'auto' (one fewer than the host's logical CPUs) or 'max' (all logical CPUs). 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) andmax(every available logical CPU core). A value of0disables parallelism and runs sequentially.The core count is the number of logical CPUs (hardware threads) reported by
os.cpu_count(), not physical cores: seeCPU_COUNT. On a host with too few logical CPUs,auto/maxresolve to a single job andJobCountlogs a warning that execution will be sequential.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, and a count above the available cores is honored but warned about. 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.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"}
- get_command(ctx, cmd_name)[source]¶
Get a command by name, loading lazily if necessary.
Todo
Allow passing extra parameters to the
self.lazy_subcommandsso we can register commands with custom settings like Cloup’ssectionorfallback_to_default_section:section: Section | None = None,
fallback_to_default_section: bool = True,
See: https://github.com/janluke/cloup/blob/master/cloup/_sections.py#L169
- class click_extra.LogLevel(*values)[source]¶
Bases:
IntEnumMapping of canonical log level names to their integer level.
That’s our own version of 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¶
- class click_extra.ManOption(param_decls=None, is_flag=True, expose_value=False, is_eager=True, help="Show the command's man page (roff) and exit.", **kwargs)[source]¶
Bases:
ExtraOptionA pre-configured
--manflag that prints the command’s man page (roff) to stdout 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.
- class click_extra.ManPage(name, short_help='', section='1', synopsis_pieces=(), description='', operands=(), option_groups=(), subcommands=(), environment=(), files=(), exit_status=(('0', 'Success.'), ('1', 'A runtime error, or an aborted prompt (Ctrl-C, a declined confirmation).'), ('2', 'A usage error: unknown option, invalid value, missing operand, or an unparsable configuration file.')), version=None, date='', manual=None, authors=None, copyright=None)[source]¶
Bases:
objectA whole man page in structured form, ready to render to roff.
One
ManPagemaps to one command (or subcommand). Its fields are the man-pages(7) sections, in the order Man-page documents them. Build it withextract_manpage()and serialize withto_roff().- option_groups: tuple[ManOptionGroup, ...] = ()¶
The OPTIONS entries, partitioned into one or more groups. A command without explicit option groups carries a single untitled group.
- subcommands: tuple[tuple[str, str], ...] = ()¶
For groups:
(name, short_help)pairs for the COMMANDS section.
- exit_status: tuple[tuple[str, str], ...] = (('0', 'Success.'), ('1', 'A runtime error, or an aborted prompt (Ctrl-C, a declined confirmation).'), ('2', 'A usage error: unknown option, invalid value, missing operand, or an unparsable configuration file.'))¶
EXIT STATUS entries as
(code, meaning)pairs.
- 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.
- Parameters:
param_type (str | None) – a string that indicates the type of the parameter. The default is to inherit the parameter type from the given param. Valid values are
'parameter','option'or'argument'.
- class click_extra.MultiChoice(choices=(), separator=',', case_sensitive=True)[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 does not ship a built-in equivalent. The closest idiomatic approach is
click.Choice([...]) + multiple=True, which requires the flag to be repeated (--tag a --tag b --tag c) rather than comma-separated. The lack of a single-token, separator-based variant upstream has been raised in:pallets/click#2771 (open): request for
nargs=-1with a non-whitespace separator, covering exactly this use case.pallets/click#2537 (closed as not planned): earlier request for space-separated multi values via
nargs=-1on options.
Maintainers have leaned on the orthogonality argument:
multiple=Truealready exists, separator conventions vary across communities (,vs.:vs.;), and escaping breaks down when a value contains the chosen separator.MultiChoiceships the convention anyway because SQL-styleSELECT a, b, csyntax reads more naturally for the tabular use casesclick-extrasupports (click_extra.table.ColumnsOptionis 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) – whenFalse, tokens matchchoicescase-insensitively and the returned tuple holds the canonical (original-case) values fromchoices.
- get_metavar(param, ctx=None)[source]¶
Render
[a<sep>b<sep>c]whenchoicesis set,Noneotherwise.Nonefalls back to Click’s default rendering (the uppercasedname, likeMULTI).
- 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.
- class click_extra.NoConfigOption(param_decls=None, type=UNPROCESSED, 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. Click8.4.0(PR pallets/click#3363) auto-detectstype=UNPROCESSEDfor non-basicflag_valuetypes, but click-extra still supports Click8.3.xwhere that auto-detection is absent, so thetype=UNPROCESSEDoverride is kept explicit to let the sentinel pass throughOptionunchanged on every supported Click.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.Option(*args, group=None, **attrs)[source]¶
Bases:
_ParameterMixin,OptionWrap
cloup.Option, itself inheriting fromclick.Option.Inherits first from
_ParameterMixinto allow future overrides of Click’sParametermethods.
- 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”.
- 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.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.
- included_params: frozenset[str] | None¶
Allowlist of parameter IDs, mutually exclusive with
excluded_params.Nonedisables the allowlist. It is resolved intoexcluded_paramsbybuild_param_trees(), once every parameter ID is known.
- static init_tree_dict(*path, leaf=None)[source]¶
Utility method to recursively create a nested dict structure whose keys are provided by
pathlist and at the end is populated by a copy ofleaf.- 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()[source]¶
Generate an unfiltered list of all CLI parameters.
Everything is included, from top-level groups to subcommands, and from options to arguments.
- Yields a 2-element tuple:
a tuple of keys leading to the parameter;
the parameter object itself.
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 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.See the list of custom types provided by Click.
- build_param_trees()[source]¶
Build the parameters tree structure and cache it.
This removes parameters whose fully-qualified IDs are in the
excluded_paramsblocklist.If
included_paramswas provided, it is resolved intoexcluded_paramshere, where all parameter IDs are available.- Return type:
- class click_extra.ParamType[source]¶
Bases:
Generic[ParamTypeValue],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.- envvar_list_splitter: ClassVar[str | None] = None¶
if a list of this type is expected and the value is pulled from a string environment variable, this is what splits it up. None means any whitespace. For all parameters the general rule is that whitespace splits them up. The exception are paths and files which are split by
os.path.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_metavar(param, ctx)[source]¶
Returns the metavar default for this param if it provides one.
- Return type:
str | None
- get_missing_message(param, ctx)[source]¶
Optionally might return extra information about a missing parameter.
Added in version 2.0.
- Return type:
str | None
- convert(value, param, ctx)[source]¶
Convert the value to the correct type. This is not called if the value is
None(the missing value).This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.
The
paramandctxarguments may beNonein certain situations, such as when converting prompt input.If the value cannot be converted, call
fail()with a descriptive message.- Parameters:
value (t.Any) – The value to convert.
param (Parameter | None) – The parameter that is using this type to convert its value. May be
None.ctx (Context | None) – The current context that arrived at this value. May be
None.
- Return type:
ParamTypeValue
- 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:
t.NoReturn
- 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:
ctx (Context) – Invocation context for this command.
param (Parameter) – The parameter that is requesting completion.
incomplete (str) – Value being completed. May be empty.
Added in version 8.0.
- Return type:
list[CompletionItem]
- 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)[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 (cabc.Sequence[str] | None) – the parameter declarations for this option or argument. This is a list of flags or argument names.
type (types.ParamType[t.Any] | t.Any | None) – the type that should be used. Either a
ParamTypeor a Python type. The latter is converted into the former automatically if supported.required (bool) – controls if this is optional or not.
default (t.Any | t.Callable[[], t.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 (t.Callable[[Context, Parameter, t.Any], t.Any] | None) – A function to further process or validate the value after type conversion. It is called as
f(ctx, param, value)and must return the value. It is called for all sources, including prompts.nargs (int | None) – the number of arguments to match. If not
1the 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 is True then the value is passed onwards to the command callback and stored on the context, otherwise it’s skipped.
is_eager (bool) – eager values are processed before non eager ones. This should not be set for arguments or it will inverse the order of processing.
envvar (str | cabc.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 (t.Callable[[Context, Parameter, str], list[CompletionItem] | list[str]] | None) – A function that returns custom shell completions. Used instead of the param’s type completion if given. Takes
ctx, param, incompleteand must return a list ofCompletionItemor a list of strings.deprecated (bool | str) – If
Trueor 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.
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]¶
- Overloads:
self, ctx (Context), call (t.Literal[True]) → t.Any | None
self, ctx (Context), call (bool) → t.Any | t.Callable[[], t.Any] | None
Get the default for the parameter. Tries
Context.lookup_default()first, then the local default.- 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:
- shell_complete(ctx, incomplete)[source]¶
Return a list of completions for the incomplete value. If a
shell_completefunction was given during init, it is used. Otherwise, thetypeshell_complete()function is used.- Parameters:
ctx (Context) – Invocation context for this command.
incomplete (str) – Value being completed. May be empty.
Added in version 8.0.
- Return type:
list[CompletionItem]
- 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(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[str|bytes|PathLike[str]]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[Any] |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.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. None means any whitespace. For all parameters the general rule is that whitespace splits them up. The exception are paths and files which are split by
os.path.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.- Parameters:
value (str | os.PathLike[str]) – The value to convert.
param (Parameter | None) – The parameter that is using this type to convert its value. May be
None.ctx (Context | None) – The current context that arrived at this value. May be
None.
- Return type:
str | bytes | os.PathLike[str]
- shell_complete(ctx, param, incomplete)[source]¶
Return a special completion marker that tells the completion system to use the shell to provide path completions for only directories or any paths.
- Parameters:
ctx (Context) – Invocation context for this command.
param (Parameter) – The parameter that is requesting completion.
incomplete (str) – Value being completed. May be empty.
Added in version 8.0.
- Return type:
list[CompletionItem]
- class click_extra.PrebakeConfig(module=None)[source]¶
Bases:
objectConfig schema for the prebake commands, read from
[tool.<cli>.prebake].Lets a project pin the target
__init__.pyonce for its build pipeline, instead of passing--moduleto everyclick-extra prebakecommand.
- 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], which a CLI reads to decide whether to start aSpinner. The default isTrue;--accessiblelowers it toFalse(viadefault_map) so a screen reader is never handed a spinning glyph.Note
Spinner display is intentionally 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 explicitly 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.This matches how the wider ecosystem treats the two axes as orthogonal: cargo, npm, pip, Rich, indicatif and ora all gate progress on the terminal (and a dedicated
--progress/--quietknob), whileNO_COLORonly affects color. Rich usesTERM=dumb– notNO_COLOR– as the signal to drop cursor-moving features like progress bars.The spinner is therefore silenced by two things only, neither of them color:
non-interactive output – a pipe, file, CI log, or
TERM=dumbterminal that cannot move the cursor (seeSpinner._resolve_enabled);explicit intent –
--no-progressor--accessible.
This option is eager. It no longer reads
ctx.color, so its position relative toColorOptionis not load-bearing.- 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, count=True, **kwargs)[source]¶
Bases:
_VerbosityOption--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 – If a
logging.Loggerobject is provided, that’s the instance to which we will set the level to. If the parameter is a string and is found in the global registry, we will use it as the logger’s ID. Otherwise, we will create a new logger withnew_logger()Default to the globalrootlogger.
- 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.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 any Command that 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:
- 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 argument section set
Commands not assigned to any user-defined section are added to the “default section”, whose title is “Commands” or “Other commands” depending on whether it is the only section or not. The default section is the last shown section in the help and its commands are listed in lexicographic order.
Changed in version 0.8.0: this mixin now relies on
cloup.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.- Return type:
- See Also:
- 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
--show-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 print information about the parameters that will be fed to the CLI.
- 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.'), 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).'), 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))."), 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.'), 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.parameters.ParamStructure.get_param_type) from the Click `Param type`.'), 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."), 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 `--show-params` and `--help` typically run a callback and exit, so they are not exposed."), 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.parameters.ParamStructure.excluded_params) and [`included_params`](#click_extra.parameters.ParamStructure.included_params). Empty when the CLI has no [`--config` option](config.md).'), 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)."), 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()`.'), 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)."), 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')`)."), 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.'), 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."), 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."), 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."), 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."), 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).'), 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`.'))¶
Rich column registry for the
--show-paramstable.Each entry is a
click_extra.table.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 find_column(column_id)[source]¶
Return the
ColumnSpecmatchingcolumn_id.Raises
KeyErrorif no column has this ID; callers should convert the error into aclick.UsageErrorwhen surfaced to a user.
- 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:
- excluded_params¶
Deactivates the blocking of any parameter.
- included_params¶
No allowlist filter; show all parameters.
- print_params(ctx, param, value)[source]¶
Introspect the current CLI and print its parameter metadata table.
Thin wrapper over
render_params_table(), the shared rendering core also drivingclick-extra wrap --show-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, 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 bakes a row sort intoctx.print_tableso 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.@command @table_format_option @sort_by_option( ("Package ID", "package_id"), ("Name", "package_name"), ("Manager", "manager_id"), ("Version", None), ) @pass_context def my_cmd(ctx): ctx.print_table(rows, headers)
- init_sort(ctx, param, sort_columns)[source]¶
Bake the row sort key into
ctx.print_table.Builds the sort key from this option’s column definitions and the selected
sort_columns, then rebindsctx.print_tabletoprint_table()with that key applied. The call contract is the same sorted or not:ctx.print_table(table_data, headers).- Return type:
- class click_extra.Spinner(label='', *, frames=None, spinner=None, reverse=False, interval=None, delay=0.0, style=None, timer=False, stream=None, enabled=None, 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. mpm and similar tools run their subprocesses sequentially, so one shared instance whoselabelis reassigned between steps is enough; for concurrent work, use 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 to0.1, 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).timer (
bool|Callable[[float],str]) – append the elapsed wall-clock time to the spinner, and to any finalok()/fail()line.Trueuses the default compact format (2.3s,1:05, then1:02:03). Pass a callable(seconds: float) -> strto format the duration yourself, liketimer=lambda s: f"{s / 60:.0f}m"for whole minutes.stream (
IO[str] |None) – where to draw; defaults tosys.stderrso the spinner never mixes intostdoutdata.enabled (
bool|None) – force the spinner on or off.None(the default) auto-detects, animating only whenstreamis a TTY.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
stylecarries a color or attribute that cannot be rendered.
- 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 withenabled=False) 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()
- start()[source]¶
Begin animating on a background thread, unless the spinner is disabled.
A disabled spinner (non-TTY stream, or
enabled=False) 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: tuple[str, ...], interval: float)[source]¶
Bases:
NamedTupleA named spinner animation: its frames and the interval they look best at.
The
SPINNERScatalog is ported from cli-spinners, with intervals converted from milliseconds to seconds. Pass one toSpinnervia 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 useclick.echo()to support color printing.Only
<stderr>or<stdout>are allowed as output stream.If stream is not specified,
<stderr>is used by defaultInitialize 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.- 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 styling, equality, hashing,
with_()) is otherwise identical tocloup.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 (0) are ignored. Multiple back-to-back escapes (as click emits when combining colors with attributes:\x1b[31m\x1b[1m) are merged into a singleStyle.- 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'¶
- 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'), 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], and two helper methods are added to the context: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.
- 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.
The
DO_NOT_TRACKconvention takes precedence over the user-defined environment variables and the auto-generated values.The resolved value is stored in
ctx.meta[click_extra.context.TELEMETRY], aligning with every other Click Extra option’s per-invocation context-meta storage pattern.See also
- set_telemetry(ctx, param, value)[source]¶
Store the resolved telemetry opt-in flag on the context’s
metadict.Reads via
click_extra.context.get(ctx, click_extra.context.TELEMETRY). Renamed fromsave_telemetryto align with theset_<key>convention used by every other ctx.meta-writing callback.- Return type:
- class click_extra.TestPlanConfig(file='./tests/cli-test-plan.yaml', inline=None, timeout=None)[source]¶
Bases:
objectConfig schema for a project’s test plan, read from
[tool.<cli>.test-plan].The
test-planCLI command resolves its cases from this config when no plan is given on the command line. Map it onto an app’s config section with a field carryingmetadata={"click_extra.config_path": "test-plan"}.
- class click_extra.ThemeOption(param_decls=None, default='dark', is_eager=True, expose_value=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.- 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 by the time this fires, so the lookup is unconditional.- 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()[source]¶
Compute and print elapsed execution time.
Always prints, even when a sibling eager option (
--version,--show-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.- 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,--show-params…) short-circuits the command body.Renamed from
register_timer_on_closeto align with theinit_<system>convention shared withinit_formatterandinit_sort.- Return type:
- class click_extra.Tuple(types)[source]¶
Bases:
CompositeParamType[tuple[Any, …]]The default behavior of Click is to apply a type on a value directly. This works well in most cases, except for when nargs is set to a fixed count and different types should be used for different items. In this case the
Tupletype can be used. This type can only be used if nargs is set to a fixed number.For more information see Multi Value Options as Tuples.
This can be selected by using a Python tuple literal as a type.
- Parameters:
types (
Sequence[type[Any] |ParamType[Any]]) – a list of types that should be used for the tuple items.
- 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 iteral. >>> 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.- Parameters:
value (t.Any) – The value to convert.
param (Parameter | None) – The parameter that is using this type to convert its value. May be
None.ctx (Context | None) – The current context that arrived at this value. May be
None.
- Return type:
tuple[t.Any, …]
- exception click_extra.UsageError(message, ctx=None)[source]¶
Bases:
ClickExceptionAn internal exception that signals a usage error. This typically aborts any further handling.
- Parameters:
message (str) – the error message to display.
ctx (Context | None) – optionally the context that caused this error. Click will fill in the context automatically in some situations.
- exit_code = 2¶
The exit code for this exception.
- class click_extra.ValidateConfigOption(param_decls=None, type=<click.types.Path object>, is_eager=True, expose_value=False, help='Validate the configuration file and exit.', **kwargs)[source]¶
Bases:
ExtraOptionA pre-configured option adding
--validate-config CONFIG_PATH.Loads the config file at the given path, validates it against the CLI’s parameter structure in strict mode, reports results, and exits.
- 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:
ExceptionRaised 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.- 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 (unknown 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 payload_install_default_map()layers into the context’sdefault_map.Nonewhenparams_templatewasNone(no strict check) or the strict check raised. Read it only on a successful report: it is the same valuemerge_default_map()would recompute, so reusing it avoids a second normalize/strip/merge pass.
- class click_extra.VerboseOption(param_decls=None, count=True, **kwargs)[source]¶
Bases:
_VerbosityOption--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 – If a
logging.Loggerobject is provided, that’s the instance to which we will set the level to. If the parameter is a string and is found in the global registry, we will use it as the logger’s ID. Otherwise, we will create a new logger withnew_logger()Default to the globalrootlogger.
- 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) – If alogging.Loggerobject is provided, that’s the instance to which we will set the level to. If the parameter is a string and is found in the global registry, we will use it as the logger’s ID. Otherwise, we will create a new logger withnew_logger()Default to the globalrootlogger.
- class click_extra.VersionOption(param_decls=None, message=None, fields=None, styles=None, message_style=None, is_flag=True, expose_value=False, is_eager=True, help='Show the version and exit.', **kwargs)[source]¶
Bases:
ExtraOptionGather CLI metadata and prints a colored version string.
Note
This started as a copy of the standard @click.version_option() decorator, but is no longer a drop-in replacement. Hence the
Extraprefix.This address 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.
- 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', 'prog_name', 'env_info')¶
List of field IDs recognized by the message template.
- default_styles: ClassVar[dict[str, Callable[[str], str]]] = {'env_info': Style(fg='bright_black'), 'exec_name': Style(fg='bright_white', bold), 'git_branch': Style(fg='cyan'), 'git_date': Style(fg='bright_black'), 'git_dirty': Style(fg='red'), 'git_distance': Style(fg='green'), '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': Style(fg='bright_white', bold), 'module_version': Style(fg='green'), 'package_name': Style(fg='bright_white', bold), 'package_version': Style(fg='green'), 'prog_name': Style(fg='bright_white', bold), 'version': Style(fg='green')}¶
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.
- message: str = '{prog_name}, version {version}'¶
Default message template used to render the version string.
- static cli_frame()[source]¶
Returns the frame in which the CLI is implemented.
Inspects the execution stack frames to find the package in which the user’s CLI is implemented.
Returns the frame itself.
- Return type:
- property module: ModuleType[source]¶
Returns the module in which the CLI resides.
- property module_version: str | None[source]¶
Returns the string found in the local
__version__variable.Hint
__version__is an old pattern from early Python packaging. It is not a standard variable and is not defined in the packaging PEPs.You should prefer using the
package_versionproperty below instead, which uses the standard library importlib.metadata API.We’re still supporting it for backward compatibility with existing codebases, as Click removed it in version 8.2.0.
- 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.
Delegates to
resolve_author(): prefers theAuthorfield, then theMaintainerfield, then the display name parsed out of theAuthor-email/Maintainer-emailfields (Name <email>). ReturnsNoneif no author can be determined.
- property license: str | None[source]¶
Returns the package license from its core metadata.
Delegates to
resolve_license(): prefers the SPDXLicense-Expressionfield, falls back to the human-readable name of the firstLicense ::trove classifier, then to the free-formLicensefield. ReturnsNoneif no license can be determined.
- property exec_name: str[source]¶
User-friendly name of the executed CLI.
Returns the module name. But if the later is
__main__, returns the package name.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).
- 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. If Git is unavailable, 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_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.
- 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(where it is derived 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 env_info: dict[str, Any][source]¶
Various environment info.
Returns the data produced by boltons.ecoutils.get_profile().
- 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.This step is necessary because we need to linearize the template to apply the ANSI codes on the string segments. This is a consequence of the nature of ANSI, directives which cannot be encapsulated within another (unlike markup tags like 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.- Return type:
- 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], aligning with every other Click Extra option’s per-invocation context-meta storage pattern.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(*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.argument(*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.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 anStreamHandler.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
I don’t like the camel-cased name of this function and would have called it
basic_config(), but it’s kept this way for consistency with Python’s standard librarylogging.basicConfig().
- 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(*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.columns_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.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.config_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.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 to True a 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.
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.- Return type:
- 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).
- 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.
Supports colors and styles on Windows.
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.
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.
- Return type:
- 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]¶
- Overloads:
text (bytes | bytearray), editor (str | None), env (cabc.Mapping[str, str] | None), require_save (bool), extension (str) → bytes | None
text (str), editor (str | None), env (cabc.Mapping[str, str] | None), require_save (bool), extension (str) → str | None
text (None), editor (str | None), env (cabc.Mapping[str, str] | None), require_save (bool), extension (str), filename (str | cabc.Iterable[str] | None) → None
Edits the given text in the defined editor. If an editor is given (should be the full path to the executable but the regular operating system search path is used for finding the executable) it overrides the detected editor. Optionally, some environment variables can be used. If the editor is closed without changes, None is returned. In case a file is edited directly the return value is always None and require_save and extension are ignored.
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.- 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 become None.extension (
str) – the extension to tell the editor about. This defaults to .txt but changing this might change syntax highlighting.filename (
str|Iterable[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. If the editor supports editing multiple files at once, a sequence of files may be passed as well. Invoke click.file once per file instead if multiple files cannot be managed at once or editing the files serially is desired.
Changed in version 8.2.0:
filenamenow accepts anyIterable[str]in addition to astrif theeditorsupports editing multiple files at once.
- 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 with normalize_config_keys.opaque_keys (
frozenset[str]) – Fully-qualified key names where flattening stops. When the accumulated key matches an entry in this set, the dict value is kept as-is instead of being recursively flattened. This is useful for fields typed 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.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_param_row(param, ctx, path, is_structured)[source]¶
Compute the structural table cells for a Click parameter.
Returns a
dict[column_id, cell]covering every column that can be derived from the parameter object alone (no runtime invocation state or config-file context). Specifically:id,spec,class,param_type,python_type,hidden,exposed,envvars,default,is_flag,flag_value,is_bool_flag,multiple,nargs,prompt, andconfirmation_prompt.Attributes only defined on
click.Option(hidden,is_flag,flag_value,is_bool_flag,prompt,confirmation_prompt) yieldNoneforclick.Argumentparameters: empty cell in visual formats,nullin structured ones.For structured formats (JSON, YAML, etc.), values are native Python types. For visual formats, values are themed strings matching help-screen styling.
The remaining table columns (
allowed_in_conf,value,source) require live context and are filled in byrender_params_table().
- click_extra.get_app_dir(app_name, roaming=True, force_posix=False)[source]¶
Returns the config folder for the application. The default behavior is to return whatever is most appropriate for the operating system.
To give you an idea, for an app called
"Foo Bar", something like the following folders could be returned:- Mac OS X:
~/Library/Application Support/Foo Bar- Mac OS X (POSIX):
~/.foo-bar- Unix:
~/.config/foo-bar- Unix (POSIX):
~/.foo-bar- Windows (roaming):
C:\Users\<user>\AppData\Roaming\Foo Bar- Windows (not roaming):
C:\Users\<user>\AppData\Local\Foo Bar
Added in version 2.0.
- Parameters:
app_name (
str) – the application name. This should be properly capitalized and can contain whitespace.roaming (
bool) – controls if the folder should be roaming or not on Windows. Has no effect otherwise.force_posix (
bool) – if this is set to True then on any POSIX system the folder will be stored in the home folder with a leading dot instead of the XDG config home or darwin’s application support folder.
- Return type:
- click_extra.get_current_context(silent=False)[source]¶
- Overloads:
→ Context
silent (bool) → Optional[Context]
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: capturing
default_themeas a default function parameter (the previous pattern) would freeze 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.Temporarily unhides hidden options so their help record can be produced.
Note
The
hiddenproperty is only supported byOption, notArgument.Todo
Submit a PR to Click to separate production of param spec and help record. That way we can always produce the param spec even if the parameter is hidden. See: https://github.com/kdeldycke/click-extra/issues/689
- click_extra.get_text_stream(name, encoding=None, errors='strict')[source]¶
Returns a system stream for text processing. This usually returns a wrapped stream around a binary stream returned from
get_binary_stream()but it also can take shortcuts for already correctly configured streams.
- 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_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.jobs_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.last_param(params, klass)[source]¶
Return the last parameter of exactly
klassin params, 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 to True then instead of launching the application associated with the URL it will attempt to launch a file manager with the file located. This might have weird effects if the URL does not point to the filesystem.
- Return type:
- 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.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
- Parameters:
object_type (type[T]) – the type of the object to pass.
ensure (bool) – if set to True, a new object will be created and remembered on the context if it’s not there yet.
- Return type:
t.Callable[[t.Callable[te.Concatenate[T, P], R]], t.Callable[P, R]]
- click_extra.make_schema_callable(schema, *, strict=False, normalize=True)[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).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(*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.- Parameters:
name (
str) – ID of the logger to setup. IfNone, Python’srootlogger will be used. 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(*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.no_config_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.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). Click does not expose this as a public function, so we replicate the one-liner here.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.- 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.
Todo
Propose upstream to Click to extract the inline
name.replace("-", "_")into a private_normalize_param_namehelper, so downstream projects like Click Extra can reuse it instead of duplicating the transform.
- 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.
Added in version 3.0.
- click_extra.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.option_group(title, *args, **kwargs)[source]¶
- Overloads:
title (str), help (str), options (Decorator), constraint (Optional[Constraint]), hidden (bool) → Callable[[F], F]
title (str), options (Decorator), help (Optional[str]), constraint (Optional[Constraint]), hidden (bool) → Callable[[F], F]
Return a decorator that annotates a function with an option group.
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_test_plan(plan_string)[source]¶
Parse a YAML test plan into
CLITestCaseinstances.The plan must be a YAML list of mappings, each keyed by
CLITestCasedirective names. Requires theyamlextra.- Raises:
ValueError – the plan is empty or a case uses unknown directives.
TypeError – the plan is not a list, or a case is not a mapping.
ImportError – YAML support 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().
- 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:
t.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 err parameter.
- 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.
- Return type:
- click_extra.print_table(table_data, headers=None, table_format=None, sort_key=None, **kwargs)[source]¶
Render a table and print it to the console.
For markup formats, ANSI color codes are stripped from cell values before rendering unless
--coloris explicitly set.
- click_extra.progressbar(iterable=None, length=None, label=None, hidden=None, **kwargs)[source]¶
Drop-in for
click.progressbar()honoring--progress/--no-progress.Click’s own progress bar is determinate, the counterpart to the indeterminate
Spinner. This thin wrapper gates it on the samePROGRESSflag the spinner uses, so a single--no-progress(or--accessible, which lowers theprogressdefault) silences both.- 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.- Return type:
ProgressBar[TypeVar(V)]
Note
Only
--no-progressis wired here. 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.
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 (
Any|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[Any] |Any|None) – the type to use to check the value against.value_proc (
Callable[[str],Any] |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.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 err parameter.
- Return type:
- click_extra.quiet_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.register_theme(name, theme)[source]¶
Register a named theme in the module-level
theme_registry.
- 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_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_manpage().- 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, **kwargs)[source]¶
Render a table and return it as a string.
- click_extra.require_sibling_param(params, requester, klass)[source]¶
Return the sibling klass parameter declared on the same command, or raise.
Some options are inert on their own: they drive machinery owned by a sibling option.
--no-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.- Parameters:
- Return type:
- click_extra.run_config_validation(user_conf, *, app_name, params_template, config_schema=None, config_validators=(), fallback_sections=(), schema_strict=False, strict=False, collect_all=True)[source]¶
Validate a parsed configuration document in one schema-driven pass.
This is the module-level entry point that unifies click-extra’s three historical validation paths (CLI-parameter strict check, dataclass schema, and app-registered
ConfigValidatorhooks) behind a single function yielding a single error type. It is deliberately not namedvalidate_config: that name belongs tovalidate_config(), the callback powering the--validate-configflag.Stages, in order:
Normalize. Strip reserved keys and expand dotted keys.
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 inValidationReport.opaque_subtrees.Strict-check the CLI-flag-bound part against
params_template, keeping the merged result asValidationReport.merged_conf(skipped whenparams_templateisNone).Schema-build the app section through the configured callable, producing
ValidationReport.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.strict (
bool) – Reject keys the CLI-parameter template does not recognize.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;ValueError/TypeErrorraised by the strict check or schema callable are wrapped into it.
- click_extra.run_jobs(func, items, *, jobs=None)[source]¶
Run
funcoveritems, parallelized per the resolved--jobscount.The worker count is taken from
jobswhen given, else from the active command’sJobsOptionvalue (ctx.meta[click_extra.context.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().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.- Parameters:
func (
Callable[[TypeVar(T)],TypeVar(R)]) – Called once per item; its return value is yielded.items (
Iterable[TypeVar(T)]) – The work items. Materialized up front to size the pool.jobs (
int|None) – Override the worker count instead of reading it from the context.1or fewer forces sequential execution.
- Return type:
- Returns:
An iterator over
func’s results, in the order ofitems.
- click_extra.run_test_plan(command, cases, *, jobs=1, select_test=None, skip_platform=None, timeout=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.execution.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.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.search_params(params, klass, include_subclasses=True, unique=True)[source]¶
Search a particular class of parameter in a list and return them.
- Parameters:
params (
Iterable[Parameter]) – list of parameter instances to search in.klass (
type[Parameter]) – the class of the parameters to look for.include_subclasses (
bool) – ifTrue, includes in the results all parameters subclassing the providedklass. IfFalse, only matches parameters which are strictly instances ofklass. Defaults toTrue.unique (
bool) – ifTrue, raise an error if more than one parameter of the providedklassis found. Defaults toTrue.
- 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 unknown IDs so the caller can convert it into aclick.UsageError.- 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_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(*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.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.
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.
- Return type:
- click_extra.table_format_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.telemetry_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.theme_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.timer_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.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(*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.verbose_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.verbosity_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.version_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.wrap_text(text, width=78, initial_indent='', subsequent_indent='', preserve_paragraphs=False)[source]¶
A helper function that intelligently wraps text. By default, it assumes that it operates on a single paragraph of text but if the preserve_paragraphs parameter is provided it will intelligently handle paragraphs (defined by two empty lines).
If paragraphs are handled, a paragraph can be prefixed with an empty line containing the
\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.
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.- Return type:
- 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.zero_exit_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.
Subpackages¶
click_extra.configpackageClickExtraConfigConfigFormatConfigOptionConfigOption.file_format_patternsConfigOption.file_pattern_flagsConfigOption.force_posixConfigOption.search_pattern_flagsConfigOption.search_parentsConfigOption.stop_atConfigOption.included_paramsConfigOption.strictConfigOption.config_schemaConfigOption.schema_strictConfigOption.fallback_sectionsConfigOption.config_validatorsConfigOption.excluded_paramsConfigOption.file_patternConfigOption.default_pattern()ConfigOption.get_help_extra()ConfigOption.parent_patterns()ConfigOption.search_and_read_file()ConfigOption.parse_conf()ConfigOption.read_and_parse_conf()ConfigOption.load_ini_config()ConfigOption.merge_default_map()ConfigOption.load_conf()
ConfigValidatorNoConfigOptionPrebakeConfigTestPlanConfigValidateConfigOptionValidationErrorValidationReportflatten_config_keys()get_tool_config()make_schema_callable()normalize_config_keys()run_config_validation()- Submodules
click_extra.config.formatsmoduleclick_extra.config.optionmoduleVCS_DIRSCONFIG_OPTION_NAMEDEFAULT_EXCLUDED_PARAMSSentinelNO_CONFIGVCSConfigOptionConfigOption.file_format_patternsConfigOption.file_pattern_flagsConfigOption.force_posixConfigOption.search_pattern_flagsConfigOption.search_parentsConfigOption.stop_atConfigOption.included_paramsConfigOption.strictConfigOption.config_schemaConfigOption.schema_strictConfigOption.fallback_sectionsConfigOption.config_validatorsConfigOption.excluded_paramsConfigOption.file_patternConfigOption.default_pattern()ConfigOption.get_help_extra()ConfigOption.parent_patterns()ConfigOption.search_and_read_file()ConfigOption.parse_conf()ConfigOption.read_and_parse_conf()ConfigOption.load_ini_config()ConfigOption.merge_default_map()ConfigOption.load_conf()
NoConfigOptionValidateConfigOptionTestPlanConfigPrebakeConfigClickExtraConfig
click_extra.config.schemamodule
- click_extra.sphinx package
MYST_NATIVE_ALERTS_VERSIONEXEC_DIRECTIVES_OPT_INRUN_CAPTURE_CONFIGsetup()- Submodules
- click_extra.sphinx.alerts module
GITHUB_ALERT_PATTERNQUOTE_PREFIX_PATTERNCODE_FENCE_PATTERNINDENTED_CODE_BLOCK_PATTERNAlertFenceStateParserStatecheck_colon_fence()count_quote_depth()process_fence()close_alerts_to_depth()mark_parent_nested()open_alert()process_quoted_line()replace_github_alerts()convert_github_alerts()
- click_extra.sphinx.click module
RST_INDENTTerminatedEchoingStdinpatch_subprocess()ClickRunnerClickDirectiveClickDirective.has_contentClickDirective.required_argumentsClickDirective.optional_argumentsClickDirective.final_argument_whitespaceClickDirective.option_specClickDirective.default_languageClickDirective.show_source_by_defaultClickDirective.show_results_by_defaultClickDirective.runner_methodClickDirective.runner_attrClickDirective.runner_factoryClickDirective.runnerClickDirective.languageClickDirective.code_block_options()ClickDirective.show_sourceClickDirective.show_resultsClickDirective.is_myst_syntaxClickDirective.render_code_block()ClickDirective.run()
SourceDirectiveRunDirectiveTreeDirectiveClickDomaincleanup_runner()
- click_extra.sphinx.manpages module
Submodules¶
click_extra.cli module¶
Click Extra CLI with pre-baking utilities.
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 --show-params and --man 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, help_command=True, **kwargs)[source]¶
Bases:
GroupGroup that falls back to the
wrapsubcommand for unknown names.Known subcommands and their aliases are dispatched normally. Anything else is treated as a target script and forwarded to
wrap.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.
- 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.
- 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.- 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.Explicit
module:functionnotation..pyfile path.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.
- 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.
- 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
wrapcommand’s--show-paramsand--manmodes so both introspect 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.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), and the
tri-state WHEN resolution. 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 = {'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}¶
List of environment variables recognized as flags to switch color rendering on or off.
The key is the name of the variable and the boolean value the value to pass to
--coloroption flag when encountered.Source:
- 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._resolve_enabled) treat these two values as a hard opt-out. Sharing the set 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.resolve_color_env()[source]¶
Reconcile the recognized color environment variables into a tri-state.
Inspects every variable listed in
color_envvarsand returns:Trueif at least one enabling variable (FORCE_COLOR,CLICOLOR, …) is set. Enabling wins over disabling, so a single one is enough to keep colors.Falseif only disabling variables (NO_COLOR,LLM, …) are set.Nonewhen no recognized variable is present, leaving the caller free to apply its own default (typicallyauto).
A bare variable (no value), or one whose value cannot be parsed as a boolean, counts as activation, in the permissive spirit of the NO_COLOR and FORCE_COLOR conventions.
A
dumborunknownTERM(seeCOLOR_DISABLING_TERMS) casts a disabling vote as well, so a terminal that cannot render ANSI is treated as color-off even when it still reports as a TTY. Because enabling wins, an explicitFORCE_COLORstays authoritative 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 it is the lever we set here. We also clear the color-disabling variables Click Extra recognizes (NO_COLOR,LLM, …) so an opt-out in the build environment cannot suppress the rendering, and pinCOLORTERM=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.color.COLOR_WHEN = ('auto', 'always', 'never')¶
GNU-canonical tri-state values accepted by
--color=<WHEN>.autodefers to terminal detection,alwaysforces ANSI on,neverstrips it. 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
COLOR_WHENvalue.GNU
lsacceptsyes/forceforalways,no/noneforneverandtty/if-ttyforauto, alongside the three canonical spellings (seeCOLOR_WHEN). Click Extra mirrors that leniency but keeps the synonyms out of--helpoutput, error messages and shell completion, which only ever advertiseCOLOR_WHEN.
- class click_extra.color.ColorWhenChoice(choices, case_sensitive=True)[source]¶
Bases:
Choiceclick.ChoiceoverCOLOR_WHENthat 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
COLOR_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 ofCOLOR_WHEN(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--show-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. 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.
- 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.
click_extra.commands module¶
Wraps vanilla Click and Cloup commands with extra features.
Our flavor of commands, groups and context are all subclasses of their vanilla counterparts, but are pre-configured with good and common defaults. You can still use the mixins in here to build up your own custom variants.
- click_extra.commands.default_params()[source]¶
Default additional options added to
@commandand@group.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 CONFIG_PATHHint
--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 CONFIG_PATH--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--show-params--table-format FORMAT--verbosity LEVEL-v,--verbose-q,--quiet--man--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.
Todo
For bullet-proof handling of edge-cases, we should probably add an indirection layer to have the processing order of options (the one below) different from the presentation order of options in the help screen.
This is probably something that has been requested in issue #544.
- 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.Command(*args, version_fields=None, config_schema=None, schema_strict=False, fallback_sections=(), config_validators=(), included_params=None, extra_option_at_end=True, populate_auto_envvars=True, extra_keywords=None, excluded_keywords=None, **kwargs)[source]¶
Bases:
_HelpColorsMixin,CommandLike
cloup.command, with sane defaults and extra help screen colorization.List of extra parameters:
- Parameters:
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.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.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.populate_auto_envvars (
bool) – forces all parameters to have their auto-generated environment variables registered. This address the shortcoming ofclickwhich only evaluates them dynamically. By forcing their registration, the auto-generated environment variables gets displayed in the help screen, fixing click#2483 issue. On Windows, environment variable names are case-insensitive, so we normalize them 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 = False(Cloup feature)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--show-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, ... } )
- 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.- Return type:
- make_context(info_name, args, parent=None, **extra)[source]¶
Intercept the call to the original
click.core.Command.make_contextso we can keep a copy of the raw, pre-parsed arguments provided to the CLI.The result are passed to our own
Contextconstructor which is able to initialize the context’smetaproperty under our ownclick_extra.context.RAW_ARGSentry. This will be used inShowParamsOption.print_params()to print the table of parameters fed to the CLI.See also
See
click_extra.context.RAW_ARGSfor the full rationale and the upstream-proposal notes (related: click#1279).- 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 color options before delegating, so
--color/--no-colorcolorize the eager help and version screens regardless of their position on the command line. See_resolve_color_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,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).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,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:
ColorizedCommandSynthetic 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, **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.
- 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
- add_command(cmd, name=None, **kwargs)[source]¶
Like
cloup.Group.add_command, but replaces an auto-injectedHelpCommandwhen the user registers their ownhelpsubcommand.- Return type:
- invoke(ctx)[source]¶
Inject
_default_subcommandsand_prepend_subcommandsfrom config.If the user has not provided any subcommands explicitly, and the loaded configuration contains a
_default_subcommandslist for this group, those subcommands are injected intoctx.protected_argsso that Click’s normalGroup.invoke()dispatches them._prepend_subcommandsalways prepends subcommands to the invocation, regardless of whether CLI subcommands were provided. Only works withchain=Truegroups.- Return type:
- 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"}
- get_command(ctx, cmd_name)[source]¶
Get a command by name, loading lazily if necessary.
Todo
Allow passing extra parameters to the
self.lazy_subcommandsso we can register commands with custom settings like Cloup’ssectionorfallback_to_default_section:section: Section | None = None,
fallback_to_default_section: bool = True,
See: https://github.com/janluke/cloup/blob/master/cloup/_sections.py#L169
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.
Used to create our own collection of decorators for our custom options, based on Cloup’s.
Attention
The cls argument passed to the factory is used as the reference class from which the produced decorator’s cls argument must inherit.
The idea is to ensure that, for example, the @command decorator re-implemented by Click Extra is always a subclass of Command, even when the user overrides the cls argument. That way it can always rely on the additional properties and methods defined in the Click Extra framework, where we have extended Cloup and Click so much that we want to prevent surprising side effects.
- 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, **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.argument(*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.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(*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.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.accessible_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.color_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.columns_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.config_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.jobs_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.man_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.no_color_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.no_config_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.quiet_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.validate_config_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.show_params_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.table_format_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.telemetry_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.theme_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.timer_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.verbose_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.verbosity_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.zero_exit_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.envvar module¶
Implements environment variable utilities.
- click_extra.envvar.TEnvVarID = str | None¶
Type of environment variable names.
- click_extra.envvar.TNestedEnvVarIDs¶
Type for arbitrary nested environment variable names.
- click_extra.envvar.TEnvVars¶
Type for
dict-like environment variables.
- 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 we normalize them 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
We do not rely too much on this utility to 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.env_copy(extend=None)[source]¶
Returns a copy of the current environment variables and eventually
extendit.Mimics Python’s original implementation by returning
Noneif noextendcontent are provided.Environment variables are expected to be a
dictofstr:str.
click_extra.execution module¶
Options controlling how a CLI runs: timing, parallelism and exit code.
These options share the same shape: each is a pre-configured
ExtraOption that publishes its resolved value
on ctx.meta for downstream code to consume. Only TimerOption acts
on its own (printing the elapsed time); JobsOption and
ZeroExitOption are contracts the framework records but does not enforce.
- click_extra.execution.CPU_COUNT = 1¶
Number of logical CPUs available, or
Noneif undetermined.This is
os.cpu_count(), which counts logical processors (hardware threads). 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.execution.DEFAULT_JOBS = 1¶
Default number of parallel jobs: one fewer than
CPU_COUNT(logical CPUs).Leaves one logical CPU free for the main process and system tasks. Falls back to
1(sequential) when the count cannot be determined.Caution
This resolves to
1not only on single-core hosts but also on two-core hosts, since it reserves one core. There, the default silently runs sequentially.JobCount.convert()logs a warning whenever a parallel-intent keyword collapses to a single job this way.
- class click_extra.execution.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), 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=None)[source]¶
Render
[auto|max|INTEGER](brackets included, asChoicedoes).
- 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, a warning is logged: the request reads as “use several cores”, but the host has too few logical CPUs, so execution is silently sequential.- 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.execution.JobsOption(param_decls=None, default='auto', expose_value=False, show_default=True, type=<click_extra.execution.JobCount object>, help="Number of parallel jobs. Accepts an integer, 'auto' (one fewer than the host's logical CPUs) or 'max' (all logical CPUs). 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) andmax(every available logical CPU core). A value of0disables parallelism and runs sequentially.The core count is the number of logical CPUs (hardware threads) reported by
os.cpu_count(), not physical cores: seeCPU_COUNT. On a host with too few logical CPUs,auto/maxresolve to a single job andJobCountlogs a warning that execution will be sequential.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, and a count above the available cores is honored but warned about. 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.execution.run_jobs(func, items, *, jobs=None)[source]¶
Run
funcoveritems, parallelized per the resolved--jobscount.The worker count is taken from
jobswhen given, else from the active command’sJobsOptionvalue (ctx.meta[click_extra.context.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().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.- Parameters:
func (
Callable[[TypeVar(T)],TypeVar(R)]) – Called once per item; its return value is yielded.items (
Iterable[TypeVar(T)]) – The work items. Materialized up front to size the pool.jobs (
int|None) – Override the worker count instead of reading it from the context.1or fewer forces sequential execution.
- Return type:
- Returns:
An iterator over
func’s results, in the order ofitems.
- 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()[source]¶
Compute and print elapsed execution time.
Always prints, even when a sibling eager option (
--version,--show-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.- 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,--show-params…) short-circuits the command body.Renamed from
register_timer_on_closeto align with theinit_<system>convention shared withinit_formatterandinit_sort.- 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], aligning with every other Click Extra option’s per-invocation context-meta storage pattern.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.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. Split out of
click_extra.color, which now focuses on --color/--no-color
resolution.
- class click_extra.highlight.HelpKeywords(cli_names=<factory>, subcommands=<factory>, command_aliases=<factory>, arguments=<factory>, long_options=<factory>, short_options=<factory>, choices=<factory>, choice_metavars=<factory>, metavars=<factory>, envvars=<factory>, defaults=<factory>)[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.
- class click_extra.highlight.HelpFormatter(*args, **kwargs)[source]¶
Bases:
HelpFormatterExtends Cloup’s custom HelpFormatter to highlights options, choices, metavars and default values.
This is being discussed for upstream integration at:
Forces theme to the active one for the current Click context.
Also transform Cloup’s standard
HelpThemeto our ownHelpTheme.Resolves the active theme via
click_extra.theme.get_current_theme(), which reads the per-invocation pick from the Click context (set byThemeOption) and falls back to the module-level default when no context is active.- write_usage(prog, args='', prefix=None)[source]¶
ANSI-aware override of
cloup.HelpFormatter.write_usage.On Click
8.3.x,click.formatting.wrap_textmeasures line length with rawlen(), counting every byte of the ANSI escape sequences embedded ininitial_indent(the styledUsage:heading + invoked-command name). With 24-bit RGB themes (like Solarized Dark, Dracula, Nord, Monokai), each styled token carries 17+ extra bytes of escape, which inflates the measured line beyond the width budget and causes premature wraps mid-token:[OPTIONS\n ].Cloup styles
prefixandprogthen delegates to click’sHelpFormatter.write_usage(), inheriting the bug. This override re-applies the same styling, then bypasseswrap_textwhenever the visible content fits on a single line: the common case for short usage strings where wrapping is unnecessary. Lines that genuinely overflow the visible width fall back to click’s implementation: the wrap point may still be sub-optimal but the output stays syntactically valid.Note
Click
8.4.0(PR pallets/click#3420) madeclick.formatting.TextWrapperANSI-aware by counting visible width instead of raw bytes, so this override is a no-op fast path on Click>= 8.4.0and only fixes wrapping on the Click8.3.xreleases click-extra still supports.Todo
Drop this override once the minimum supported Click rises to
8.4.0(which includespallets/click#3420). Theterm_len-based visible-width check below becomes redundant once Click’s own wrapper counts visible width.- Return type:
- keywords: HelpKeywords = 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())¶
- excluded_keywords: HelpKeywords | None = 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:
- 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-foldeing, 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.logging module¶
Logging utilities.
- class click_extra.logging.LogLevel(*values)[source]¶
Bases:
IntEnumMapping of canonical log level names to their integer level.
That’s our own version of 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_LEVEL: LogLevel = LogLevel.WARNING¶
WARNINGis the default level we expect any loggers to starts their lives at.WARNINGhas been chosen as it is the level at which the default Python’s global root logger is set up.This value is also used as the default level for
VerbosityOption.
- class click_extra.logging.StreamHandler(stream=None)[source]¶
Bases:
StreamHandlerA handler to output logs to the console.
Wraps
logging.StreamHandler, but useclick.echo()to support color printing.Only
<stderr>or<stdout>are allowed as output stream.If stream is not specified,
<stderr>is used by defaultInitialize 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.- 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().- 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 anStreamHandler.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
I don’t like the camel-cased name of this function and would have called it
basic_config(), but it’s kept this way for consistency with Python’s standard librarylogging.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.- Parameters:
name (
str) – ID of the logger to setup. IfNone, Python’srootlogger will be used. 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) – If alogging.Loggerobject is provided, that’s the instance to which we will set the level to. If the parameter is a string and is found in the global registry, we will use it as the logger’s ID. Otherwise, we will create a new logger withnew_logger()Default to the globalrootlogger.
- class click_extra.logging.VerboseOption(param_decls=None, count=True, **kwargs)[source]¶
Bases:
_VerbosityOption--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 – If a
logging.Loggerobject is provided, that’s the instance to which we will set the level to. If the parameter is a string and is found in the global registry, we will use it as the logger’s ID. Otherwise, we will create a new logger withnew_logger()Default to the globalrootlogger.
- class click_extra.logging.QuietOption(param_decls=None, count=True, **kwargs)[source]¶
Bases:
_VerbosityOption--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 – If a
logging.Loggerobject is provided, that’s the instance to which we will set the level to. If the parameter is a string and is found in the global registry, we will use it as the logger’s ID. Otherwise, we will create a new logger withnew_logger()Default to the globalrootlogger.
click_extra.parameters module¶
Our own flavor of Option, Argument and parameters.
- class click_extra.parameters.P¶
Type variable bound to
click.Parameter, lettingrequire_sibling_param()return the exact subclass it was asked to find.alias of TypeVar(‘P’, bound=
Parameter)
- click_extra.parameters.PARAM_PATH_SEP = '.'¶
Separator joining the keys of a parameter’s fully-qualified path (
cli.subcommand.param).
- click_extra.parameters.patch_attr(obj, name, value)[source]¶
Temporarily set
obj.nametovalue, restoring the original on exit.A minimal, dependency-free stand-in for
unittest.mock.patch.objectfor the simple save-set-restore monkeypatching Click Extra performs at runtime (inlogging,parametersandtesting).Note
unittest.mockdrags the whole test framework, and its heavy transitive imports, into the startup path of every CLI built with Click Extra. Reimplementing the single feature actually used keeps that cost out of import time. Do not swap this back forunittest.mock.Like
patch.objectwithoutcreate=True, the attribute must already exist: a missingnameraisesAttributeError.
- click_extra.parameters.search_params(params, klass, include_subclasses=True, unique=True)[source]¶
Search a particular class of parameter in a list and return them.
- Parameters:
params (
Iterable[Parameter]) – list of parameter instances to search in.klass (
type[Parameter]) – the class of the parameters to look for.include_subclasses (
bool) – ifTrue, includes in the results all parameters subclassing the providedklass. IfFalse, only matches parameters which are strictly instances ofklass. Defaults toTrue.unique (
bool) – ifTrue, raise an error if more than one parameter of the providedklassis found. Defaults toTrue.
- Return type:
- click_extra.parameters.last_param(params, klass)[source]¶
Return the last parameter of exactly
klassin params, 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.parameters.require_sibling_param(params, requester, klass)[source]¶
Return the sibling klass parameter declared on the same command, or raise.
Some options are inert on their own: they drive machinery owned by a sibling option.
--no-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.- Parameters:
- Return type:
- class click_extra.parameters.Argument(*args, help=None, **attrs)[source]¶
Bases:
_ParameterMixin,ArgumentWrap
cloup.Argument, itself inheriting fromclick.Argument.Inherits first from
_ParameterMixinto allow future overrides of Click’sParametermethods.
- class click_extra.parameters.Option(*args, group=None, **attrs)[source]¶
Bases:
_ParameterMixin,OptionWrap
cloup.Option, itself inheriting fromclick.Option.Inherits first from
_ParameterMixinto allow future overrides of Click’sParametermethods.
- class click_extra.parameters.ExtraOption(*args, group=None, **attrs)[source]¶
Bases:
OptionDedicated to option implemented by
click-extraitself.Provides a way to identify Click Extra’s own options with certainty, and restores the pre-Click-8.4.0 contract that eager callbacks can introspect their own parameter source from within their own callback.
Note
This is the one click-extra class that deliberately keeps the
Extraprefix. The8.0.0cleanup dropped it everywhere else (ExtraCommandbecameCommand,ExtraContextbecameContext, and so on), shadowing the matching Cloup or Click class. Here the plainOptionname is already taken by the user-facing enhanced wrapper this class subclasses, so the prefix is not legacy baggage but a real distinction:ExtraOptionmarks click-extra’s own built-in options. That marker is load-bearing, sinceCommandsorts 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.- handle_parse_result(ctx, opts, args)[source]¶
Record the parameter source before delegating to the base implementation.
Warning
Click
8.4.0(PR pallets/click#3404) reorderedParameter.handle_parse_resultsoctx.set_parameter_sourceruns afterprocess_value. Eager callbacks that introspect their own provenance viactx.get_parameter_source(self.name)therefore readNoneinstead of the actual source.ColorOption,ConfigOption, andShowParamsOptionall rely on this introspection to decide whether an env var should override the default (--color), whether the--configpath was user-supplied, and what to render in theSourcecolumn of--show-params.Click
8.4.1restored the pre-8.4.0contract upstream (PR pallets/click#3484), so this override only matters for Click8.4.0itself, which sits inside click-extra’s supported>= 8.3.1range. Pre-recording the source here for eager options keeps that contract on every supported Click.super().handle_parse_resultre-records the same value at the canonical time, so the slot arbitration logic introduced by #3404 is unaffected:slot_emptyis computed fromctx.params, not from_parameter_source.consume_valueruns twice as a side effect: once here and once insuper. Both calls are pure for click-extra’s existing eager flag-style options (no env var side effects, no prompt). Should a future eager subclass need prompt behavior, this override would need to cache the result instead.The pre-record is skipped when the slot already carries a source from an earlier option sharing the same
name(Click’s feature-switch pattern), so the arbitration logic insuperstill sees the originalexisting_sourcerather than a stale rewrite from this option.
- class click_extra.parameters.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.
- included_params: frozenset[str] | None¶
Allowlist of parameter IDs, mutually exclusive with
excluded_params.Nonedisables the allowlist. It is resolved intoexcluded_paramsbybuild_param_trees(), once every parameter ID is known.
- static init_tree_dict(*path, leaf=None)[source]¶
Utility method to recursively create a nested dict structure whose keys are provided by
pathlist and at the end is populated by a copy ofleaf.- 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()[source]¶
Generate an unfiltered list of all CLI parameters.
Everything is included, from top-level groups to subcommands, and from options to arguments.
- Yields a 2-element tuple:
a tuple of keys leading to the parameter;
the parameter object itself.
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 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.See the list of custom types provided by Click.
- build_param_trees()[source]¶
Build the parameters tree structure and cache it.
This removes parameters whose fully-qualified IDs are in the
excluded_paramsblocklist.If
included_paramswas provided, it is resolved intoexcluded_paramshere, where all parameter IDs are available.- Return type:
- click_extra.parameters.get_param_spec(param, ctx)[source]¶
Extract the option-spec string (like
-v, --verbose) from a parameter.Temporarily unhides hidden options so their help record can be produced.
Note
The
hiddenproperty is only supported byOption, notArgument.Todo
Submit a PR to Click to separate production of param spec and help record. That way we can always produce the param spec even if the parameter is hidden. See: https://github.com/kdeldycke/click-extra/issues/689
- click_extra.parameters.format_param_row(param, ctx, path, is_structured)[source]¶
Compute the structural table cells for a Click parameter.
Returns a
dict[column_id, cell]covering every column that can be derived from the parameter object alone (no runtime invocation state or config-file context). Specifically:id,spec,class,param_type,python_type,hidden,exposed,envvars,default,is_flag,flag_value,is_bool_flag,multiple,nargs,prompt, andconfirmation_prompt.Attributes only defined on
click.Option(hidden,is_flag,flag_value,is_bool_flag,prompt,confirmation_prompt) yieldNoneforclick.Argumentparameters: empty cell in visual formats,nullin structured ones.For structured formats (JSON, YAML, etc.), values are native Python types. For visual formats, values are themed strings matching help-screen styling.
The remaining table columns (
allowed_in_conf,value,source) require live context and are filled in byrender_params_table().
- click_extra.parameters.walk_command_params(cmd, ctx, parent_keys=())[source]¶
Walk the parameter tree of a Click command and all its subcommands.
Yields
(path_keys, param, owning_ctx)for every parameter found on cmd and, recursively, on each subcommand. Each subcommand is walked under its own freshly-built child context, so context-sensitive metadata (notably the auto-generated environment variable, which derives fromContext.auto_envvar_prefix) is computed at the correct nesting level 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.parameters.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 the default_columns fallback, 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 --show-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.parameters.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
--show-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 print information about the parameters that will be fed to the CLI.
- 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.'), 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).'), 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))."), 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.'), 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.parameters.ParamStructure.get_param_type) from the Click `Param type`.'), 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."), 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 `--show-params` and `--help` typically run a callback and exit, so they are not exposed."), 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.parameters.ParamStructure.excluded_params) and [`included_params`](#click_extra.parameters.ParamStructure.included_params). Empty when the CLI has no [`--config` option](config.md).'), 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)."), 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()`.'), 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)."), 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')`)."), 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.'), 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."), 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."), 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."), 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."), 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).'), 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`.'))¶
Rich column registry for the
--show-paramstable.Each entry is a
click_extra.table.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 find_column(column_id)[source]¶
Return the
ColumnSpecmatchingcolumn_id.Raises
KeyErrorif no column has this ID; callers should convert the error into aclick.UsageErrorwhen surfaced to a user.
- 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:
- excluded_params¶
Deactivates the blocking of any parameter.
- included_params¶
No allowlist filter; show all parameters.
- print_params(ctx, param, value)[source]¶
Introspect the current CLI and print its parameter metadata table.
Thin wrapper over
render_params_table(), the shared rendering core also drivingclick-extra wrap --show-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.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.
Todo
Add the following build-time template fields, mirroring the constants shadow-rs injects:
{build_time}: when the distribution was built (shadow-rs exposes it asBUILD_TIME, with RFC 2822 and RFC 3339 variantsBUILD_TIME_2822/BUILD_TIME_3339).{build_os}/{build_target}/{build_target_arch}: the OS, target triple and architecture the build ran on. These describe the build host, unlike{env_info}which reports the runtime Python, OS and architecture, so both are worth keeping for cross-built binaries.
- click_extra.prebake.prebake_version(file_path, local_version)[source]¶
Pre-bake a
__version__string with a PEP 440 local version identifier.Reads file_path, finds the
__version__assignment viaast, and, if the version contains.devand does not already contain+, appends+<local_version>.This is the compile-time complement to the runtime
click_extra.version.VersionOption.versionproperty: Nuitka/PyInstaller binaries cannot rungitat runtime, so the hash must be baked into__version__in the source file before compilation.Returns the new version string on success, or
Noneif no change was made (release version, already pre-baked, or no__version__found).
- click_extra.prebake.prebake_dunder(file_path, name, value)[source]¶
Replace an empty dunder variable’s value in a Python source file.
Reads file_path, finds a top-level
name = ""assignment viaast, and, if the current value is an empty string, replaces it with value.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).This is the generic counterpart to
prebake_version(): whereprebake_versionappends a PEP 440 local identifier to__version__, this function does a full replacement of any dunder variable that starts empty. Typical use case: injecting a release commit SHA into__git_tag_sha__ = ""at build time.Returns the new value on success, or
Noneif no change was made (variable not found, or already has a non-empty value).
- click_extra.prebake.discover_package_init_files()[source]¶
Discover
__init__.pyfiles from[project.scripts].Reads the
pyproject.tomlin the current working directory, extracts[project.scripts]entry points, and returns the unique__init__.pypaths for each top-level package.Only returns paths that exist on disk. Returns an empty list if
pyproject.tomlis missing or has no[project.scripts].
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.
- class click_extra.pygments.AnsiColorLexer(*args, **kwargs)[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), quantized to the nearest 256-color entry.
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
True. 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().
- 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 (defaultTrue) 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.
This function contains a manually-maintained list of lexers, to which we dynamically add lexers inheriting from
ShellSessionBaseLexer.Hint
To help maintain this list, there is a test that will fail if a new REPL/terminal-like lexer is added to Pygments but not referenced here.
- click_extra.pygments.LEXER_MAP: dict[type[Lexer], type[Lexer]] = {<class 'pygments.lexers.algebra.GAPConsoleLexer'>: <class 'pygments.lexer.AnsiGAPConsoleLexer'>, <class 'pygments.lexers.dylan.DylanConsoleLexer'>: <class 'pygments.lexer.AnsiDylanConsoleLexer'>, <class 'pygments.lexers.erlang.ElixirConsoleLexer'>: <class 'pygments.lexer.AnsiElixirConsoleLexer'>, <class 'pygments.lexers.erlang.ErlangShellLexer'>: <class 'pygments.lexer.AnsiErlangShellLexer'>, <class 'pygments.lexers.julia.JuliaConsoleLexer'>: <class 'pygments.lexer.AnsiJuliaConsoleLexer'>, <class 'pygments.lexers.matlab.MatlabSessionLexer'>: <class 'pygments.lexer.AnsiMatlabSessionLexer'>, <class 'pygments.lexers.php.PsyshConsoleLexer'>: <class 'pygments.lexer.AnsiPsyshConsoleLexer'>, <class 'pygments.lexers.python.PythonConsoleLexer'>: <class 'pygments.lexer.AnsiPythonConsoleLexer'>, <class 'pygments.lexers.r.RConsoleLexer'>: <class 'pygments.lexer.AnsiRConsoleLexer'>, <class 'pygments.lexers.ruby.RubyConsoleLexer'>: <class 'pygments.lexer.AnsiRubyConsoleLexer'>, <class 'pygments.lexers.shell.BashSessionLexer'>: <class 'pygments.lexer.AnsiBashSessionLexer'>, <class 'pygments.lexers.shell.MSDOSSessionLexer'>: <class 'pygments.lexer.AnsiMSDOSSessionLexer'>, <class 'pygments.lexers.shell.PowerShellSessionLexer'>: <class 'pygments.lexer.AnsiPowerShellSessionLexer'>, <class 'pygments.lexers.shell.TcshSessionLexer'>: <class 'pygments.lexer.AnsiTcshSessionLexer'>, <class 'pygments.lexers.special.OutputLexer'>: <class 'pygments.lexer.AnsiOutputLexer'>, <class 'pygments.lexers.sql.PostgresConsoleLexer'>: <class 'pygments.lexer.AnsiPostgresConsoleLexer'>, <class 'pygments.lexers.sql.SqliteConsoleLexer'>: <class 'pygments.lexer.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.5', '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. These 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.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.Creates a new style instance that inherits from the one provided by the user, but updates its
stylesattribute with ANSI token definitions from_ANSI_STYLES.- 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.
- click_extra.pytest.invoke(runner)[source]¶
Invoke fixture shorthand for
click_extra.testing.CliRunner.invoke().
- 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]¶
Returns collection of Pytest parameters to test all command-like decorators.
- 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]¶
Returns collection of Pytest parameters to test all parameter-like decorators.
- 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.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.
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 enabled is forced. 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.
- class click_extra.spinner.Spinner(label='', *, frames=None, spinner=None, reverse=False, interval=None, delay=0.0, style=None, timer=False, stream=None, enabled=None, 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. mpm and similar tools run their subprocesses sequentially, so one shared instance whoselabelis reassigned between steps is enough; for concurrent work, use 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 to0.1, 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).timer (
bool|Callable[[float],str]) – append the elapsed wall-clock time to the spinner, and to any finalok()/fail()line.Trueuses the default compact format (2.3s,1:05, then1:02:03). Pass a callable(seconds: float) -> strto format the duration yourself, liketimer=lambda s: f"{s / 60:.0f}m"for whole minutes.stream (
IO[str] |None) – where to draw; defaults tosys.stderrso the spinner never mixes intostdoutdata.enabled (
bool|None) – force the spinner on or off.None(the default) auto-detects, animating only whenstreamis a TTY.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
stylecarries a color or attribute that cannot be rendered.
- 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 withenabled=False) 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()
- start()[source]¶
Begin animating on a background thread, unless the spinner is disabled.
A disabled spinner (non-TTY stream, or
enabled=False) 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], which a CLI reads to decide whether to start aSpinner. The default isTrue;--accessiblelowers it toFalse(viadefault_map) so a screen reader is never handed a spinning glyph.Note
Spinner display is intentionally 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 explicitly 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.This matches how the wider ecosystem treats the two axes as orthogonal: cargo, npm, pip, Rich, indicatif and ora all gate progress on the terminal (and a dedicated
--progress/--quietknob), whileNO_COLORonly affects color. Rich usesTERM=dumb– notNO_COLOR– as the signal to drop cursor-moving features like progress bars.The spinner is therefore silenced by two things only, neither of them color:
non-interactive output – a pipe, file, CI log, or
TERM=dumbterminal that cannot move the cursor (seeSpinner._resolve_enabled);explicit intent –
--no-progressor--accessible.
This option is eager. It no longer reads
ctx.color, so its position relative toColorOptionis not load-bearing.- 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.progressbar(iterable=None, length=None, label=None, hidden=None, **kwargs)[source]¶
Drop-in for
click.progressbar()honoring--progress/--no-progress.Click’s own progress bar is determinate, the counterpart to the indeterminate
Spinner. This thin wrapper gates it on the samePROGRESSflag the spinner uses, so a single--no-progress(or--accessible, which lowers theprogressdefault) silences both.- 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.- Return type:
ProgressBar[TypeVar(V)]
Note
Only
--no-progressis wired here. 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.spinner_presets module¶
The bundled catalog of terminal spinner presets.
Ported from cli-spinners, with frame intervals converted from milliseconds to seconds.
- 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: tuple[str, ...], interval: float)[source]¶
Bases:
NamedTupleA named spinner animation: its frames and the interval they look best at.
The
SPINNERScatalog is ported from cli-spinners, with intervals converted from milliseconds to seconds. Pass one toSpinnervia 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), 'betaWave': (('ρββββββ', 'βρβββββ', 'ββρββββ', 'βββρβββ', 'ββββρββ', 'βββββρβ', 'ββββββρ'), 0.08), 'binary': (('010010', '001100', '100101', '111010', '111101', '010111', '101011', '111000', '110011', '110101'), 0.08), 'bluePulse': (('🔹 ', '🔷 ', '🔵 ', '🔵 ', '🔷 '), 0.1), 'bounce': (('⠁', '⠂', '⠄', '⠂'), 0.12), 'bouncingBall': (('( ● )', '( ● )', '( ● )', '( ● )', '( ●)', '( ● )', '( ● )', '( ● )', '( ● )', '(● )'), 0.08), 'bouncingBar': (('[ ]', '[= ]', '[== ]', '[=== ]', '[====]', '[ ===]', '[ ==]', '[ =]', '[ ]', '[ =]', '[ ==]', '[ ===]', '[====]', '[=== ]', '[== ]', '[= ]'), 0.08), 'boxBounce': (('▖', '▘', '▝', '▗'), 0.12), 'boxBounce2': (('▌', '▀', '▐', '▄'), 0.1), 'christmas': (('🌲', '🎄'), 0.4), 'circle': (('◡', '⊙', '◠'), 0.12), 'circleHalves': (('◐', '◓', '◑', '◒'), 0.05), 'circleQuarters': (('◴', '◷', '◶', '◵'), 0.12), 'clock': (('🕛 ', '🕐 ', '🕑 ', '🕒 ', '🕓 ', '🕔 ', '🕕 ', '🕖 ', '🕗 ', '🕘 ', '🕙 ', '🕚 '), 0.1), 'dots': (('⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'), 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), 'dots8Bit': (('⠀', '⠁', '⠂', '⠃', '⠄', '⠅', '⠆', '⠇', '⡀', '⡁', '⡂', '⡃', '⡄', '⡅', '⡆', '⡇', '⠈', '⠉', '⠊', '⠋', '⠌', '⠍', '⠎', '⠏', '⡈', '⡉', '⡊', '⡋', '⡌', '⡍', '⡎', '⡏', '⠐', '⠑', '⠒', '⠓', '⠔', '⠕', '⠖', '⠗', '⡐', '⡑', '⡒', '⡓', '⡔', '⡕', '⡖', '⡗', '⠘', '⠙', '⠚', '⠛', '⠜', '⠝', '⠞', '⠟', '⡘', '⡙', '⡚', '⡛', '⡜', '⡝', '⡞', '⡟', '⠠', '⠡', '⠢', '⠣', '⠤', '⠥', '⠦', '⠧', '⡠', '⡡', '⡢', '⡣', '⡤', '⡥', '⡦', '⡧', '⠨', '⠩', '⠪', '⠫', '⠬', '⠭', '⠮', '⠯', '⡨', '⡩', '⡪', '⡫', '⡬', '⡭', '⡮', '⡯', '⠰', '⠱', '⠲', '⠳', '⠴', '⠵', '⠶', '⠷', '⡰', '⡱', '⡲', '⡳', '⡴', '⡵', '⡶', '⡷', '⠸', '⠹', '⠺', '⠻', '⠼', '⠽', '⠾', '⠿', '⡸', '⡹', '⡺', '⡻', '⡼', '⡽', '⡾', '⡿', '⢀', '⢁', '⢂', '⢃', '⢄', '⢅', '⢆', '⢇', '⣀', '⣁', '⣂', '⣃', '⣄', '⣅', '⣆', '⣇', '⢈', '⢉', '⢊', '⢋', '⢌', '⢍', '⢎', '⢏', '⣈', '⣉', '⣊', '⣋', '⣌', '⣍', '⣎', '⣏', '⢐', '⢑', '⢒', '⢓', '⢔', '⢕', '⢖', '⢗', '⣐', '⣑', '⣒', '⣓', '⣔', '⣕', '⣖', '⣗', '⢘', '⢙', '⢚', '⢛', '⢜', '⢝', '⢞', '⢟', '⣘', '⣙', '⣚', '⣛', '⣜', '⣝', '⣞', '⣟', '⢠', '⢡', '⢢', '⢣', '⢤', '⢥', '⢦', '⢧', '⣠', '⣡', '⣢', '⣣', '⣤', '⣥', '⣦', '⣧', '⢨', '⢩', '⢪', '⢫', '⢬', '⢭', '⢮', '⢯', '⣨', '⣩', '⣪', '⣫', '⣬', '⣭', '⣮', '⣯', '⢰', '⢱', '⢲', '⢳', '⢴', '⢵', '⢶', '⢷', '⣰', '⣱', '⣲', '⣳', '⣴', '⣵', '⣶', '⣷', '⢸', '⢹', '⢺', '⢻', '⢼', '⢽', '⢾', '⢿', '⣸', '⣹', '⣺', '⣻', '⣼', '⣽', '⣾', '⣿'), 0.08), 'dots9': (('⢹', '⢺', '⢼', '⣸', '⣇', '⡧', '⡗', '⡏'), 0.08), 'dotsCircle': (('⢎ ', '⠎⠁', '⠊⠑', '⠈⠱', ' ⡱', '⢀⡰', '⢄⡠', '⢆⡀'), 0.08), 'dqpb': (('d', 'q', 'p', 'b'), 0.1), 'dwarfFortress': ((' ██████£££ ', '☺██████£££ ', '☺██████£££ ', '☺▓█████£££ ', '☺▓█████£££ ', '☺▒█████£££ ', '☺▒█████£££ ', '☺░█████£££ ', '☺░█████£££ ', '☺ █████£££ ', ' ☺█████£££ ', ' ☺█████£££ ', ' ☺▓████£££ ', ' ☺▓████£££ ', ' ☺▒████£££ ', ' ☺▒████£££ ', ' ☺░████£££ ', ' ☺░████£££ ', ' ☺ ████£££ ', ' ☺████£££ ', ' ☺████£££ ', ' ☺▓███£££ ', ' ☺▓███£££ ', ' ☺▒███£££ ', ' ☺▒███£££ ', ' ☺░███£££ ', ' ☺░███£££ ', ' ☺ ███£££ ', ' ☺███£££ ', ' ☺███£££ ', ' ☺▓██£££ ', ' ☺▓██£££ ', ' ☺▒██£££ ', ' ☺▒██£££ ', ' ☺░██£££ ', ' ☺░██£££ ', ' ☺ ██£££ ', ' ☺██£££ ', ' ☺██£££ ', ' ☺▓█£££ ', ' ☺▓█£££ ', ' ☺▒█£££ ', ' ☺▒█£££ ', ' ☺░█£££ ', ' ☺░█£££ ', ' ☺ █£££ ', ' ☺█£££ ', ' ☺█£££ ', ' ☺▓£££ ', ' ☺▓£££ ', ' ☺▒£££ ', ' ☺▒£££ ', ' ☺░£££ ', ' ☺░£££ ', ' ☺ £££ ', ' ☺£££ ', ' ☺£££ ', ' ☺▓££ ', ' ☺▓££ ', ' ☺▒££ ', ' ☺▒££ ', ' ☺░££ ', ' ☺░££ ', ' ☺ ££ ', ' ☺££ ', ' ☺££ ', ' ☺▓£ ', ' ☺▓£ ', ' ☺▒£ ', ' ☺▒£ ', ' ☺░£ ', ' ☺░£ ', ' ☺ £ ', ' ☺£ ', ' ☺£ ', ' ☺▓ ', ' ☺▓ ', ' ☺▒ ', ' ☺▒ ', ' ☺░ ', ' ☺░ ', ' ☺ ', ' ☺ &', ' ☺ ☼&', ' ☺ ☼ &', ' ☺☼ &', ' ☺☼ & ', ' ‼ & ', ' ☺ & ', ' ‼ & ', ' ☺ & ', ' ‼ & ', ' ☺ & ', '‼ & ', ' & ', ' & ', ' & ░ ', ' & ▒ ', ' & ▓ ', ' & £ ', ' & ░£ ', ' & ▒£ ', ' & ▓£ ', ' & ££ ', ' & ░££ ', ' & ▒££ ', '& ▓££ ', '& £££ ', ' ░£££ ', ' ▒£££ ', ' ▓£££ ', ' █£££ ', ' ░█£££ ', ' ▒█£££ ', ' ▓█£££ ', ' ██£££ ', ' ░██£££ ', ' ▒██£££ ', ' ▓██£££ ', ' ███£££ ', ' ░███£££ ', ' ▒███£££ ', ' ▓███£££ ', ' ████£££ ', ' ░████£££ ', ' ▒████£££ ', ' ▓████£££ ', ' █████£££ ', ' ░█████£££ ', ' ▒█████£££ ', ' ▓█████£££ ', ' ██████£££ ', ' ██████£££ '), 0.08), 'earth': (('🌍 ', '🌎 ', '🌏 '), 0.18), 'fingerDance': (('🤘 ', '🤟 ', '🖖 ', '✋ ', '🤚 ', '👆 '), 0.16), 'fish': (('~~~~~~~~~~~~~~~~~~~~', '> ~~~~~~~~~~~~~~~~~~', 'º> ~~~~~~~~~~~~~~~~~', '(º> ~~~~~~~~~~~~~~~~', '((º> ~~~~~~~~~~~~~~~', '<((º> ~~~~~~~~~~~~~~', '><((º> ~~~~~~~~~~~~~', ' ><((º> ~~~~~~~~~~~~', '~ ><((º> ~~~~~~~~~~~', '~~ <>((º> ~~~~~~~~~~', '~~~ ><((º> ~~~~~~~~~', '~~~~ <>((º> ~~~~~~~~', '~~~~~ ><((º> ~~~~~~~', '~~~~~~ <>((º> ~~~~~~', '~~~~~~~ ><((º> ~~~~~', '~~~~~~~~ <>((º> ~~~~', '~~~~~~~~~ ><((º> ~~~', '~~~~~~~~~~ <>((º> ~~', '~~~~~~~~~~~ ><((º> ~', '~~~~~~~~~~~~ <>((º> ', '~~~~~~~~~~~~~ ><((º>', '~~~~~~~~~~~~~~ <>((º', '~~~~~~~~~~~~~~~ ><((', '~~~~~~~~~~~~~~~~ <>(', '~~~~~~~~~~~~~~~~~ ><', '~~~~~~~~~~~~~~~~~~ <', '~~~~~~~~~~~~~~~~~~~~'), 0.08), 'fistBump': (('🤜\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), 'growHorizontal': (('▏', '▎', '▍', '▌', '▋', '▊', '▉', '▊', '▋', '▌', '▍', '▎'), 0.12), 'growVertical': (('▁', '▃', '▄', '▅', '▆', '▇', '▆', '▅', '▄', '▃'), 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), 'orangeBluePulse': (('🔸 ', '🔶 ', '🟠 ', '🟠 ', '🔶 ', '🔹 ', '🔷 ', '🔵 ', '🔵 ', '🔷 '), 0.1), 'orangePulse': (('🔸 ', '🔶 ', '🟠 ', '🟠 ', '🔶 '), 0.1), 'pipe': (('┤', '┘', '┴', '└', '├', '┌', '┬', '┐'), 0.1), 'point': (('∙∙∙', '●∙∙', '∙●∙', '∙∙●', '∙∙∙'), 0.125), 'pong': (('▐⠂ ▌', '▐⠈ ▌', '▐ ⠂ ▌', '▐ ⠠ ▌', '▐ ⡀ ▌', '▐ ⠠ ▌', '▐ ⠂ ▌', '▐ ⠈ ▌', '▐ ⠂ ▌', '▐ ⠠ ▌', '▐ ⡀ ▌', '▐ ⠠ ▌', '▐ ⠂ ▌', '▐ ⠈ ▌', '▐ ⠂▌', '▐ ⠠▌', '▐ ⡀▌', '▐ ⠠ ▌', '▐ ⠂ ▌', '▐ ⠈ ▌', '▐ ⠂ ▌', '▐ ⠠ ▌', '▐ ⡀ ▌', '▐ ⠠ ▌', '▐ ⠂ ▌', '▐ ⠈ ▌', '▐ ⠂ ▌', '▐ ⠠ ▌', '▐ ⡀ ▌', '▐⠠ ▌'), 0.08), 'rollingLine': (('/ ', ' - ', ' \\ ', ' |', ' |', ' \\ ', ' - ', '/ '), 0.08), 'runner': (('🚶 ', '🏃 '), 0.14), 'sand': (('⠁', '⠂', '⠄', '⡀', '⡈', '⡐', '⡠', '⣀', '⣁', '⣂', '⣄', '⣌', '⣔', '⣤', '⣥', '⣦', '⣮', '⣶', '⣷', '⣿', '⡿', '⠿', '⢟', '⠟', '⡛', '⠛', '⠫', '⢋', '⠋', '⠍', '⡉', '⠉', '⠑', '⠡', '⢁'), 0.08), 'shark': (('▐|\\____________▌', '▐_|\\___________▌', '▐__|\\__________▌', '▐___|\\_________▌', '▐____|\\________▌', '▐_____|\\_______▌', '▐______|\\______▌', '▐_______|\\_____▌', '▐________|\\____▌', '▐_________|\\___▌', '▐__________|\\__▌', '▐___________|\\_▌', '▐____________|\\▌', '▐____________/|▌', '▐___________/|_▌', '▐__________/|__▌', '▐_________/|___▌', '▐________/|____▌', '▐_______/|_____▌', '▐______/|______▌', '▐_____/|_______▌', '▐____/|________▌', '▐___/|_________▌', '▐__/|__________▌', '▐_/|___________▌', '▐/|____________▌'), 0.12), 'simpleDots': (('. ', '.. ', '...', ' '), 0.4), 'simpleDotsScrolling': (('. ', '.. ', '...', ' ..', ' .', ' '), 0.2), 'smiley': (('😄 ', '😝 '), 0.2), 'soccerHeader': ((' 🧑⚽️ 🧑 ', '🧑 ⚽️ 🧑 ', '🧑 ⚽️ 🧑 ', '🧑 ⚽️ 🧑 ', '🧑 ⚽️ 🧑 ', '🧑 ⚽️ 🧑 ', '🧑 ⚽️🧑 ', '🧑 ⚽️ 🧑 ', '🧑 ⚽️ 🧑 ', '🧑 ⚽️ 🧑 ', '🧑 ⚽️ 🧑 ', '🧑 ⚽️ 🧑 '), 0.08), 'speaker': (('🔈 ', '🔉 ', '🔊 ', '🔉 '), 0.16), 'squareCorners': (('◰', '◳', '◲', '◱'), 0.18), 'squish': (('╫', '╪'), 0.1), 'star': (('✶', '✸', '✹', '✺', '✹', '✷'), 0.07), 'star2': (('+', 'x', '*'), 0.08), 'timeTravel': (('🕛 ', '🕚 ', '🕙 ', '🕘 ', '🕗 ', '🕖 ', '🕕 ', '🕔 ', '🕓 ', '🕒 ', '🕑 ', '🕐 '), 0.1), '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 Spinner, SPINNERS with Spinner("Brewing tea", spinner=SPINNERS["moon"]): ...
Unlike the upstream
\b-based renderers,Spinnerredraws the whole line, so the multi-character animations (bouncingBar,pong,shark, …) render correctly here.
click_extra.table module¶
Collection of table rendering utilities.
- 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'¶
- 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.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.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.render_table(table_data, headers=None, table_format=None, sort_key=None, **kwargs)[source]¶
Render a table and return it as a string.
- click_extra.table.print_table(table_data, headers=None, table_format=None, sort_key=None, **kwargs)[source]¶
Render a table and print it to the console.
For markup formats, ANSI color codes are stripped from cell values before rendering unless
--coloris explicitly set.
- 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.
- Return type:
- class click_extra.table.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'), 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], and two helper methods are added to the context: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.
- class click_extra.table.ColumnSpec(id, label, description='')[source]¶
Bases:
objectRich description of a single column in a rendered table.
Three fields, all required-by-convention even though
descriptiondefaults to empty so quick prototypes do 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.
Note
Frozen + slots: instances are immutable and lightweight. Tuples of
ColumnSpecare intended to be defined as module-level constants (likeclick_extra.parameters.ShowParamsOption.TABLE_HEADERS).
- click_extra.table.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.table.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 unknown IDs so the caller can convert it into aclick.UsageError.- Return type:
- click_extra.table.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:
- class click_extra.table.ColumnsType(accepted_ids=())[source]¶
Bases:
MultiChoiceColumn-flavored alias of
click_extra.types.MultiChoice.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. Theaccepted_idsconstructor keyword is a column-flavored alias ofMultiChoice.choices.Initialize the type.
- Parameters:
choices – 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
False, tokens matchchoicescase-insensitively and the returned tuple holds the canonical (original-case) values fromchoices.
- class click_extra.table.ColumnsOption(param_decls=None, columns=None, type=None, 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 --show-params
The selection is stored in
ctx.meta[click_extra.context.COLUMNS]and consumed by table-rendering callbacks (likeclick_extra.parameters.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.SortByOption(*header_defs, param_decls=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 bakes a row sort intoctx.print_tableso 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.@command @table_format_option @sort_by_option( ("Package ID", "package_id"), ("Name", "package_name"), ("Manager", "manager_id"), ("Version", None), ) @pass_context def my_cmd(ctx): ctx.print_table(rows, headers)
- init_sort(ctx, param, sort_columns)[source]¶
Bake the row sort key into
ctx.print_table.Builds the sort key from this option’s column definitions and the selected
sort_columns, then rebindsctx.print_tabletoprint_table()with that key applied. The call contract is the same sorted or not:ctx.print_table(table_data, headers).- 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.
The
DO_NOT_TRACKconvention takes precedence over the user-defined environment variables and the auto-generated values.The resolved value is stored in
ctx.meta[click_extra.context.TELEMETRY], aligning with every other Click Extra option’s per-invocation context-meta storage pattern.See also
- set_telemetry(ctx, param, value)[source]¶
Store the resolved telemetry opt-in flag on the context’s
metadict.Reads via
click_extra.context.get(ctx, click_extra.context.TELEMETRY). Renamed fromsave_telemetryto align with theset_<key>convention used by every other ctx.meta-writing callback.- Return type:
click_extra.test_plan module¶
Declarative, black-box CLI test plans.
A test plan 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 plan runs across operating systems unchanged.
Plans are usually written as YAML and loaded with parse_test_plan(),
which needs the optional click-extra[yaml] extra. run_test_plan()
drives a list of cases against a target, parallelized per the resolved
--jobs count (see click_extra.execution.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.
- exception click_extra.test_plan.SkippedTest[source]¶
Bases:
ExceptionRaised when a test case should be skipped.
- class click_extra.test_plan.CLITestCase(cli_parameters=<factory>, skip_platforms=<factory>, only_platforms=<factory>, timeout=None, exit_code=None, strip_ansi=False, output_contains=<factory>, stdout_contains=<factory>, stderr_contains=<factory>, output_regex_matches=<factory>, stdout_regex_matches=<factory>, stderr_regex_matches=<factory>, output_regex_fullmatch=None, stdout_regex_fullmatch=None, stderr_regex_fullmatch=None, execution_trace=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_parameters appended, then checks the captured result against the expectation directives below. A case with no expectation only asserts the command ran (plus exit_code, if set).
- cli_parameters: tuple[str, ...] | str¶
Arguments and options appended to the command-under-test.
A plain string is split into arguments (on spaces on Windows, with shlex elsewhere); a list or tuple is used as-is.
- skip_platforms: Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[_TNestedReferences]]¶
Platforms (or platform-group IDs) on which to skip this case.
Accepts extra_platforms identifiers such as linux, macos, windows, in any case, mixed freely with group IDs.
- only_platforms: Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[_TNestedReferences]]¶
Restrict this case to these platforms; skip it everywhere else.
The mirror image of skip_platforms, using the same identifiers.
- timeout: float | str | None = None¶
Seconds before the command is killed and the case fails as a timeout.
Falls back to the command’s –timeout default, then to no limit.
- 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). See output_contains for the merged-stream semantics.
- stdout_regex_matches: tuple[Pattern | str, ...] | str¶
Regexes that must each match somewhere in stdout (searched, re.DOTALL).
- stderr_regex_matches: tuple[Pattern | str, ...] | str¶
Regexes that must each match somewhere in stderr (searched, re.DOTALL).
- output_regex_fullmatch: Pattern | str | None = None¶
Regex that must fully match the combined output, line by line. See output_contains for the merged-stream semantics.
- stdout_regex_fullmatch: Pattern | str | None = None¶
Regex that must fully match stdout, line by line.
- stderr_regex_fullmatch: Pattern | str | None = None¶
Regex that must fully match stderr, line by line.
- execution_trace: str | None = None¶
Rendering of the command execution and its output.
Populated after the case runs, for inspection on failure; not a directive you set in a test plan.
- property has_separate_stream_directives: bool¶
Whether any
stdout_*orstderr_*directive (separate streams) is set.
- run_cli_test(command, additional_skip_platforms, default_timeout)[source]¶
Run a CLI command and check its output against the test case.
The provided command can be either:
a path to a binary or script to execute;
a command name to be searched in the PATH,
a command line with arguments to be parsed and executed by the shell.
`{todo} Add support for environment variables. `- Return type:
- click_extra.test_plan.parse_test_plan(plan_string)[source]¶
Parse a YAML test plan into
CLITestCaseinstances.The plan must be a YAML list of mappings, each keyed by
CLITestCasedirective names. Requires theyamlextra.- Raises:
ValueError – the plan is empty or a case uses unknown directives.
TypeError – the plan is not a list, or a case is not a mapping.
ImportError – YAML support is not installed.
- Return type:
- click_extra.test_plan.run_test_plan(command, cases, *, jobs=1, select_test=None, skip_platform=None, timeout=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.execution.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.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.TNestedArgs¶
Type for arbitrary nested CLI arguments.
Arguments can be
str,pathlib.Pathobjects orNonevalues.alias of
Iterable[str|Path|None|Iterable[TNestedArgs]]
- click_extra.testing.PROMPT = '$ '¶
Prompt used to simulate the CLI execution.
Hint
Use ASCII characters to avoid issues with Windows terminals.
- click_extra.testing.INDENT = ' '¶
Constants for rendering of CLI 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.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_plan.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.args_cleanup(*args)[source]¶
Flatten recursive iterables, remove all
None, and cast each element to strings.Helps serialize
pathlib.Pathand other objects.It also allows for nested iterables and
Nonevalues as CLI arguments for convenience. We just need to flatten and filters them out.
- click_extra.testing.render_cli_run(args, result, env=None)[source]¶
Generates the full simulation of CLI execution, including output.
Mostly used to print debug traces to user or in test results.
- Return type:
- click_extra.testing.INVOKE_ARGS = {'args', 'catch_exceptions', 'cli', 'color', 'env', 'input', 'self'}¶
Parameter IDs of
click.testing.CliRunner.invoke().We need to collect them to help us identify which extra parameters passed to
invoke()collides with its original signature.Warning
This has been reported upstream to Click project but has been rejected and not considered an issue worth fixing.
- 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.
- 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.- invoke(cli, *args, input=None, env=None, catch_exceptions=True, 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.
Allow forcing of the
colorproperty at the class-level viaforce_colorattribute.Adds a special case in the form of
color="forced"parameter, which allows colored output to be kept, while forcing the initialization ofContext.color = True. This is not allowed in current implementation ofclick.testing.CliRunner.invoke()because of colliding parameters.Strips all ANSI codes from results if
colorwas explicirely 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 casted 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) – same asclick.testing.CliRunner.invoke().color (
bool|Literal['forced'] |None) – If a boolean, the parameter will be passed as-is toclick.testing.CliRunner.isolation(). If"forced", the parameter will be passed asTruetoclick.testing.CliRunner.isolation()and an extracolor=Trueparameter will be passed to the invoked CLI.extra (
Any) – same asclick.testing.CliRunner.invoke(), but colliding parameters are allowed and properly passed on to the invoked CLI.
- Return type:
- 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_NEWLINE = '\\n'¶
Newline token used to split a multi-line regex pattern for line-by-line matching.
- 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_docs module¶
Render a theme palette as an inline-styled HTML fragment for documentation.
palette_html() is called from docs/theme.md to render every
built-in theme’s palette at Sphinx build time.
inject_slot_example_docstring() is registered as a Sphinx
autodoc-process-docstring hook from docs/conf.py to inject a colored
example into each HelpTheme slot’s autodoc block. This is build-time
documentation code, kept out of the runtime theme module.
- click_extra.theme_docs.inject_slot_example_docstring(app, what, name, obj, options, lines)[source]¶
Sphinx
autodoc-process-docstringhook injecting per-slot colored examples.For every
HelpThemeslot that has an entry in_PALETTE_EXAMPLES, append anansi-colorcode block to the slot’s autodoc lines. The example is rendered through_render_slot_ansi, which callsBUILTIN_THEMES["dark"].<slot>(text)to obtain the actual ANSI escapes click-extra would emit at runtime.Wire this up from a Sphinx
conf.pywith:from click_extra.theme_docs import inject_slot_example_docstring def setup(app): app.connect("autodoc-process-docstring", inject_slot_example_docstring)
The hook intentionally targets only
click_extra.theme.HelpTheme.<slot>names so it won’t accidentally rewrite unrelated docstrings; downstream projects can register the hook in their ownconf.pyif they consume HelpTheme docstrings.- Return type:
- click_extra.theme_docs.palette_html(theme)[source]¶
Render a theme’s palette as an inline-styled HTML
<dl>fragment.The output is a two-column definition list (slot name → styled swatch plus attribute decorations) safe to inject into MyST or reST host documents via the
python:renderSphinx directive (or anyraw:: htmlblock). Used bydocs/theme.mdto render every built-in theme’s palette at Sphinx build time without hand-maintaining swatch tables. Downstream projects with their own custom themes can call the same helper to get matching swatch listings in their own docs:```{python:render} from click_extra.theme_docs import palette_html from my_app.themes import MY_THEME print(palette_html(MY_THEME)) ```Slots that hold
identity(no styling applied), the booleancross_ref_highlighttoggle, the internal_style_kwargscache, and a handful of inherited cloup slots that built-ins never style are skipped: every emitted row corresponds to a real palette choice in the theme.- Return type:
click_extra.types module¶
Custom click.ParamType subclasses for multi-pick and Enum choices.
- class click_extra.types.MultiChoice(choices=(), separator=',', case_sensitive=True)[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 does not ship a built-in equivalent. The closest idiomatic approach is
click.Choice([...]) + multiple=True, which requires the flag to be repeated (--tag a --tag b --tag c) rather than comma-separated. The lack of a single-token, separator-based variant upstream has been raised in:pallets/click#2771 (open): request for
nargs=-1with a non-whitespace separator, covering exactly this use case.pallets/click#2537 (closed as not planned): earlier request for space-separated multi values via
nargs=-1on options.
Maintainers have leaned on the orthogonality argument:
multiple=Truealready exists, separator conventions vary across communities (,vs.:vs.;), and escaping breaks down when a value contains the chosen separator.MultiChoiceships the convention anyway because SQL-styleSELECT a, b, csyntax reads more naturally for the tabular use casesclick-extrasupports (click_extra.table.ColumnsOptionis 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) – whenFalse, tokens matchchoicescase-insensitively and the returned tuple holds the canonical (original-case) values fromchoices.
- get_metavar(param, ctx=None)[source]¶
Render
[a<sep>b<sep>c]whenchoicesis set,Noneotherwise.Nonefalls back to Click’s default rendering (the uppercasedname, likeMULTI).
- 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)[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.Same as
click.Choice, but takes anEnumaschoices.Also defaults to case-insensitive matching.
- 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.- Return type:
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 two fallbacks for git-less environments: a
pre-baked __<field>__ dunder in the CLI module (injected before build by
click_extra.prebake), then a committed .git_archival.json populated
by git archive.
- click_extra.version.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.run_git(*args, cwd=None, allow_empty=False)[source]¶
Run a
gitcommand and return its stripped output, orNone.cwd defaults to the current working directory when not provided.
By default an empty output is collapsed to
None(treated like a failure). Set allow_empty to keep an empty string instead, which some commands use meaningfully:git status --porcelainprints nothing for a clean work tree, and that is distinct from the command failing.
- click_extra.version.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.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.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.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.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.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.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.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 (for example the program name with-/_variants) before reading its metadata.
- click_extra.version.meta_value(meta, *keys)[source]¶
Return the first non-empty value among core-metadata keys.
Accessed through
in+[](rather than.get()) to dodge the deprecated implicit-Nonereturn on missing keys.
- click_extra.version.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.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.
- class click_extra.version.VersionOption(param_decls=None, message=None, fields=None, styles=None, message_style=None, is_flag=True, expose_value=False, is_eager=True, help='Show the version and exit.', **kwargs)[source]¶
Bases:
ExtraOptionGather CLI metadata and prints a colored version string.
Note
This started as a copy of the standard @click.version_option() decorator, but is no longer a drop-in replacement. Hence the
Extraprefix.This address 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.
- 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', 'prog_name', 'env_info')¶
List of field IDs recognized by the message template.
- default_styles: ClassVar[dict[str, Callable[[str], str]]] = {'env_info': Style(fg='bright_black'), 'exec_name': Style(fg='bright_white', bold), 'git_branch': Style(fg='cyan'), 'git_date': Style(fg='bright_black'), 'git_dirty': Style(fg='red'), 'git_distance': Style(fg='green'), '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': Style(fg='bright_white', bold), 'module_version': Style(fg='green'), 'package_name': Style(fg='bright_white', bold), 'package_version': Style(fg='green'), 'prog_name': Style(fg='bright_white', bold), 'version': Style(fg='green')}¶
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.
- message: str = '{prog_name}, version {version}'¶
Default message template used to render the version string.
- static cli_frame()[source]¶
Returns the frame in which the CLI is implemented.
Inspects the execution stack frames to find the package in which the user’s CLI is implemented.
Returns the frame itself.
- Return type:
- property module: ModuleType[source]¶
Returns the module in which the CLI resides.
- property module_version: str | None[source]¶
Returns the string found in the local
__version__variable.Hint
__version__is an old pattern from early Python packaging. It is not a standard variable and is not defined in the packaging PEPs.You should prefer using the
package_versionproperty below instead, which uses the standard library importlib.metadata API.We’re still supporting it for backward compatibility with existing codebases, as Click removed it in version 8.2.0.
- 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.
Delegates to
resolve_author(): prefers theAuthorfield, then theMaintainerfield, then the display name parsed out of theAuthor-email/Maintainer-emailfields (Name <email>). ReturnsNoneif no author can be determined.
- property license: str | None[source]¶
Returns the package license from its core metadata.
Delegates to
resolve_license(): prefers the SPDXLicense-Expressionfield, falls back to the human-readable name of the firstLicense ::trove classifier, then to the free-formLicensefield. ReturnsNoneif no license can be determined.
- property exec_name: str[source]¶
User-friendly name of the executed CLI.
Returns the module name. But if the later is
__main__, returns the package name.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).
- 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. If Git is unavailable, 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_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.
- 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(where it is derived 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 env_info: dict[str, Any][source]¶
Various environment info.
Returns the data produced by boltons.ecoutils.get_profile().
- 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.This step is necessary because we need to linearize the template to apply the ANSI codes on the string segments. This is a consequence of the nature of ANSI, directives which cannot be encapsulated within another (unlike markup tags like 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.- Return type: