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.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.Choice(choices, case_sensitive=True)[source]¶
Bases:
ParamType,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.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.
- 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'¶
- 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.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=True, default=True, is_eager=True, expose_value=False, help='Strip out all colors and all ANSI codes from output.', **kwargs)[source]¶
Bases:
ExtraOptionA pre-configured option that is adding a
--color/--no-color(aliased by--ansi/--no-ansi) to keep or strip colors and ANSI codes from CLI output.This option is eager by default to allow for other eager options (like
--version) to be rendered colorless.Todo
Should we switch to
--color=<auto|never|always>as GNU tools does?Also see how the isatty property defaults with this option, and how it can be implemented in Python.
Todo
Support the TERM environment variable convention?
- set_color(ctx, param, value)[source]¶
Reconcile
--color/--no-color/--ansi/--no-ansiwith environment variables.The reconciliation pass re-inspects the environment for any of the recognised colorization flags (
NO_COLOR,FORCE_COLOR,CLICOLOR, …): when the user hasn’t explicitly passed--color/--no-coloron the command line, the env vars take precedence. The final reconciled value lands onctx.color(the Click-standard attribute thatecho()reads). Renamed fromdisable_colorsbecause the callback handles enable as well as disable: the previous name only described half the behavior.- Return type:
- class click_extra.Command(*args, aliases=None, formatter_settings=None, **kwargs)[source]¶
Bases:
ConstraintMixin,OptionGroupMixin,CommandA
click.Commandsupporting option groups and constraints.Refer to superclasses for the documentation of all accepted parameters:
Besides other things, this class also:
adds a
formatter_settingsinstance attribute.
Refer to
click.Commandfor the documentation of all parameters.Added in version 0.8.0.
- Parameters:
constraints – 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 – 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
- aliases: List[str]¶
HelpFormatter options that are merged with
Context.formatter_settings(eventually overriding some values).
- format_epilog(ctx, formatter)[source]¶
Writes the epilog into the formatter if it exists.
- Return type:
- format_help_text(ctx, formatter)[source]¶
Writes the help text to the formatter if it exists.
- Return type:
- 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.
- 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 (e.g.[tool.myapp.sub-section]) to map directly to flat dataclass fields (e.g.sub_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 byself.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 will filter out all unrecognized options not supported by the command. Then cleans up blank values and update the context’s
default_map.Uses a ~collections.ChainMap so each config source keeps its own layer. The first layer wins on key lookup, which makes parameter-source precedence explicit and future-proofs for multi-file config loading.
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 (e.g. mappings whose keys are data, not flag names) don’t tripstrict=True.- 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.- Return type:
- ..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.
- 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 (e.g. 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(*ctx_args, align_option_groups=None, align_sections=None, show_subcommand_aliases=None, show_constraints=None, check_constraints_consistency=None, formatter_settings={}, **ctx_kwargs)[source]¶
Bases:
ContextA custom context for Cloup.
Look up
click.Contextfor the list of all arguments.Added in version 0.9.0: added the
check_constraints_consistencyparameter.Added in version 0.8.0.
- Parameters:
ctx_args (
Any) – arguments forwarded toclick.Context.align_option_groups (
bool|None) – if True, align the definition lists of all option groups of a command. You can override this by setting the corresponding argument ofCommand(but you probably shouldn’t: be consistent).align_sections (
bool|None) – if True, align the definition lists of all subcommands of a group. You can override this by setting the corresponding argument ofGroup(but you probably shouldn’t: be consistent).show_subcommand_aliases (
bool|None) – whether to show the aliases of subcommands in the help of acloup.Group.show_constraints (
bool|None) – whether to include a “Constraint” section in the command help (if at least one constraint is defined).check_constraints_consistency (
bool|None) – enable additional checks for constraints which detects mistakes of the developer (seecloup.Constraint.check_consistency()).formatter_settings (
Dict[str,Any]) – keyword arguments forwarded toHelpFormatterinmake_formatter. This args are merged with those of the (eventual) parent context and then merged again (being overridden) by those of the command. Tip: use the static methodHelpFormatter.settings()to create this dictionary, so that you can be guided by your IDE.ctx_kwargs (
Any) – keyword arguments forwarded toclick.Context.
- formatter_class¶
alias of
HelpFormatter
- formatter_settings¶
Keyword arguments for the HelpFormatter. Obtained by merging the options of the parent context with the one passed to this context. Before creating the help formatter, these options are merged with the (eventual) options provided to the command (having higher priority).
- make_formatter()[source]¶
Creates the
HelpFormatterfor the help and usage output.To quickly customize the formatter class used without overriding this method, set the
formatter_classattribute.Changed in version 8.0: Added the
formatter_classattribute.- Return type:
- static settings(*, auto_envvar_prefix=_Missing.flag, default_map=_Missing.flag, terminal_width=_Missing.flag, max_content_width=_Missing.flag, resilient_parsing=_Missing.flag, allow_extra_args=_Missing.flag, allow_interspersed_args=_Missing.flag, ignore_unknown_options=_Missing.flag, help_option_names=_Missing.flag, token_normalize_func=_Missing.flag, color=_Missing.flag, show_default=_Missing.flag, align_option_groups=_Missing.flag, align_sections=_Missing.flag, show_subcommand_aliases=_Missing.flag, show_constraints=_Missing.flag, check_constraints_consistency=_Missing.flag, formatter_settings=_Missing.flag)[source]¶
Utility method for creating a
context_settingsdictionary.- Parameters:
auto_envvar_prefix (
_Missing|str) – the prefix to use for automatic environment variables. If this is None then reading from environment variables is disabled. This does not affect manually set environment variables which are always read.default_map (
_Missing|Dict[str,Any]) – a dictionary (like object) with default values for parameters.terminal_width (
_Missing|int) – the width of the terminal. The default is inherited from parent context. If no context defines the terminal width then auto-detection will be applied.max_content_width (
_Missing|int) – the maximum width for content rendered by Click (this currently only affects help pages). This defaults to 80 characters if not overridden. In other words: even if the terminal is larger than that, Click will not format things wider than 80 characters by default. In addition to that, formatters might add some safety mapping on the right.resilient_parsing (
_Missing|bool) – if this flag is enabled then Click will parse without any interactivity or callback invocation. Default values will also be ignored. This is useful for implementing things such as completion support.allow_extra_args (
_Missing|bool) – if this is set to True then extra arguments at the end will not raise an error and will be kept on the context. The default is to inherit from the command.allow_interspersed_args (
_Missing|bool) – if this is set to False then options and arguments cannot be mixed. The default is to inherit from the command.ignore_unknown_options (
_Missing|bool) – instructs click to ignore options it does not know and keeps them for later processing.help_option_names (
_Missing|List[str]) – optionally a list of strings that define how the default help parameter is named. The default is['--help'].token_normalize_func (
_Missing|Callable[[str],str]) – an optional function that is used to normalize tokens (options, choices, etc.). This for instance can be used to implement case-insensitive behavior.color (
_Missing|bool) – controls if the terminal supports ANSI colors or not. The default is auto-detection. This is only needed if ANSI codes are used in texts that Click prints which is by default not the case. This for instance would affect help output.show_default (
_Missing|bool) – Show defaults for all options. If not set, defaults to the value from a parent context. Overrides an option’sshow_defaultargument.align_option_groups (
_Missing|bool) – if True, align the definition lists of all option groups of a command. You can override this by setting the corresponding argument ofCommand(but you probably shouldn’t: be consistent).align_sections (
_Missing|bool) – if True, align the definition lists of all subcommands of a group. You can override this by setting the corresponding argument ofGroup(but you probably shouldn’t: be consistent).show_subcommand_aliases (
_Missing|bool) – whether to show the aliases of subcommands in the help of acloup.Group.show_constraints (
_Missing|bool) – whether to include a “Constraint” section in the command help (if at least one constraint is defined).check_constraints_consistency (
_Missing|bool) – enable additional checks for constraints which detects mistakes of the developer (seecloup.Constraint.check_consistency()).formatter_settings (
_Missing|Dict[str,Any]) – keyword arguments forwarded toHelpFormatterinmake_formatter. This args are merged with those of the (eventual) parent context and then merged again (being overridden) by those of the command. Tip: use the static methodHelpFormatter.settings()to create this dictionary, so that you can be guided by your IDE.
- Return type:
- class click_extra.DateTime(formats=None)[source]¶
Bases:
ParamTypeThe 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.
- 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:
t.Any
- 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 (i.e. thenameproperty),ChoiceSource.VALUEto use thevalue,ChoiceSource.STRto use thestr()string representation, orA custom callable that takes an
Enummember and returns a string.
Default to
ChoiceSource.STR, which makes you to only have 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]¶
Derivate the choice string from the given
Enum’smember.- Return type:
- class click_extra.ExtraCliRunner(charset='utf-8', env=None, echo_stdin=False, catch_exceptions=True)[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 –
can be nested iterables composed of
str,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 –
same as
click.testing.CliRunner.invoke(), but colliding parameters are allowed and properly passed on to the invoked CLI.
- Return type:
- class click_extra.ExtraCommand(*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:
ExtraHelpColorsMixin,CommandLike
cloup.command, with sane defaults and extra help screen colorization.List of extra parameters:
- Parameters:
version_fields (
dict[str,Any] |None) – dictionary ofExtraVersionOptiontemplate field overrides forwarded to the version option. Accepts any field fromExtraVersionOption.template_fields(e.g.prog_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 dynamiccaly. 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, ... } )
- context_class¶
alias of
ExtraContext
- 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
ExtraContextconstructor 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
This workaround is being discussed upstream in click#1279.
- Return type:
- class click_extra.ExtraContext(*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 (i.e. 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.Todo
Propose addition of
metakeyword upstream to Click.Like parent’s context but with an extra
metakeyword-argument.Also force
colordefault toTrueif not provided by user and this context has no parent.- formatter_class¶
alias of
HelpExtraFormatter
- class click_extra.ExtraFormatter(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.HelpExtraTheme, resolved per-invocation viaclick_extra.theme.get_current_theme().- Return type:
- class click_extra.ExtraGroup(*args, help_command=True, **kwargs)[source]¶
Bases:
ExtraCommand,GroupLike
cloup.Group, with sane defaults and extra help screen colorization.Like
ExtraCommand.__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¶
alias of
ExtraCommand
- 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.ExtraOption(*args, group=None, **attrs)[source]¶
Bases:
OptionDedicated to option implemented by
click-extraitself.Does nothing in particular for now but provides a way to identify Click Extra’s own options with certainty.
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 inHelpExtraFormatter._style_bracket_fields(), which uses the structured data fromOption.get_help_extra()to identify each field by its label.
- class click_extra.ExtraStreamHandler(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.ExtraVersionOption(param_decls=None, message=None, module=None, module_name=None, module_file=None, module_version=None, package_name=None, package_version=None, exec_name=None, version=None, git_repo_path=None, git_branch=None, git_long_hash=None, git_short_hash=None, git_date=None, git_tag=None, git_tag_sha=None, prog_name=None, env_info=None, message_style=None, module_style=None, module_name_style=Style(fg='bright_white'), module_file_style=None, module_version_style=Style(fg='green'), package_name_style=Style(fg='bright_white'), package_version_style=Style(fg='green'), exec_name_style=Style(fg='bright_white'), version_style=Style(fg='green'), git_repo_path_style=Style(fg='bright_black'), git_branch_style=Style(fg='cyan'), git_long_hash_style=Style(fg='yellow'), git_short_hash_style=Style(fg='yellow'), git_date_style=Style(fg='bright_black'), git_tag_style=Style(fg='cyan'), git_tag_sha_style=Style(fg='yellow'), prog_name_style=Style(fg='bright_white'), env_info_style=Style(fg='bright_black'), 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}.module_name (
str|None) – forces the value of{module_name}.module_file (
str|None) – forces the value of{module_file}.module_version (
str|None) – forces the value of{module_version}.package_name (
str|None) – forces the value of{package_name}.package_version (
str|None) – forces the value of{package_version}.git_repo_path (
str|None) – forces the value of{git_repo_path}.git_long_hash (
str|None) – forces the value of{git_long_hash}.git_short_hash (
str|None) – forces the value of{git_short_hash}.git_tag_sha (
str|None) – forces the value of{git_tag_sha}.env_info (
dict[str,str] |None) – forces the value of{env_info}.message_style (
Callable[[str],str] |None) – default style of the message.module_style (
Callable[[str],str] |None) – style of{module}.module_name_style (
Callable[[str],str] |None) – style of{module_name}.module_file_style (
Callable[[str],str] |None) – style of{module_file}.module_version_style (
Callable[[str],str] |None) – style of{module_version}.package_name_style (
Callable[[str],str] |None) – style of{package_name}.package_version_style (
Callable[[str],str] |None) – style of{package_version}.exec_name_style (
Callable[[str],str] |None) – style of{exec_name}.version_style (
Callable[[str],str] |None) – style of{version}.git_repo_path_style (
Callable[[str],str] |None) – style of{git_repo_path}.git_branch_style (
Callable[[str],str] |None) – style of{git_branch}.git_long_hash_style (
Callable[[str],str] |None) – style of{git_long_hash}.git_short_hash_style (
Callable[[str],str] |None) – style of{git_short_hash}.git_date_style (
Callable[[str],str] |None) – style of{git_date}.git_tag_style (
Callable[[str],str] |None) – style of{git_tag}.git_tag_sha_style (
Callable[[str],str] |None) – style of{git_tag_sha}.prog_name_style (
Callable[[str],str] |None) – style of{prog_name}.env_info_style (
Callable[[str],str] |None) – style of{env_info}.
- template_fields: tuple[str, ...] = ('module', 'module_name', 'module_file', 'module_version', 'package_name', 'package_version', 'exec_name', 'version', 'git_repo_path', 'git_branch', 'git_long_hash', 'git_short_hash', 'git_date', 'git_tag', 'git_tag_sha', 'prog_name', 'env_info')¶
List of field IDs recognized by the message template.
- 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 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
+(i.e., 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, then falls back togit rev-parse --abbrev-ref HEAD.
- property git_long_hash: str | None[source]¶
Returns the full Git commit hash.
Checks for a pre-baked
__git_long_hash__dunder first, then falls back togit rev-parse HEAD.
- property git_short_hash: str | None[source]¶
Returns the short Git commit hash.
Checks for a pre-baked
__git_short_hash__dunder first, then falls back togit rev-parse --short HEAD.Hint
The short hash is usually the first 7 characters of the full hash, but this is not guaranteed to be the case.
But it is at least guaranteed to be unique within the repository, and a minimum of 4 characters.
- property git_date: str | None[source]¶
Returns the commit date in ISO format:
YYYY-MM-DD HH:MM:SS +ZZZZ.Checks for a pre-baked
__git_date__dunder first, then falls back togit show -s --format=%ci HEAD.
- property git_tag: str | None[source]¶
Returns the Git tag pointing at HEAD, if any.
Checks for a pre-baked
__git_tag__dunder first, then falls back togit describe --tags --exact-match HEAD.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, then falls back togit rev-list -1on the tag returned bygit_tag. ReturnsNoneif HEAD is not at a tag.
- 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.File(mode='r', encoding=None, errors='strict', lazy=None, atomic=False)[source]¶
Bases:
ParamTypeDeclares 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.
- 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,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.Group(*args, show_subcommand_aliases=None, commands=None, **kwargs)[source]¶
Bases:
SectionMixin,Command,GroupA
click.Groupthat allows to organize its subcommands in multiple help sections and whose subcommands are, by default, of typecloup.Command.Refer to superclasses for the documentation of all accepted parameters:
Apart from superclasses arguments, the following is the only additional parameter:
show_subcommand_aliases:Optional[bool] = Nonewhether to show subcommand aliases; aliases are shown by default and can be disabled using this argument or the homonym context setting.
Changed in version 0.14.0: this class now supports option groups and constraints.
Added in version 0.10.0: the “command aliases” feature, including the
show_subcommand_aliasesparameter/attribute.Changed in version 0.8.0: this class now inherits from
cloup.BaseCommand.- Parameters:
align_sections – 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
- show_subcommand_aliases¶
Whether to show subcommand aliases.
- 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:
- resolve_command_name(ctx, name)[source]¶
Map a string supposed to be a command name or an alias to a normalized command name. If no match is found, it returns
None.
- handle_bad_command_name(bad_name, valid_names, error)[source]¶
This method is called when a command name cannot be resolved. Useful to implement the “Did you mean <x>?” feature.
- Parameters:
bad_name (
str) – the command name that could not be resolved.valid_names (
List[str]) – the list of valid command names, including aliases.error (
UsageError) – the original error coming from Click.
- Return type:
- Returns:
the original error or a new one.
- 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:
- command(name=None, *, aliases=None, cls=None, section=None, **kwargs)[source]¶
- Overloads:
self, name (Optional[str]), aliases (Optional[Iterable[str]]), cls (None), section (Optional[Section]), context_settings (Optional[Dict[str, Any]]), formatter_settings (Optional[Dict[str, Any]]), help (Optional[str]), epilog (Optional[str]), short_help (Optional[str]), options_metavar (Optional[str]), add_help_option (bool), no_args_is_help (bool), hidden (bool), deprecated (bool), align_option_groups (Optional[bool]), show_constraints (Optional[bool]), params (Optional[List[click.Parameter]]) → Callable[[AnyCallable], click.Command]
self, name (Optional[str]), aliases (Optional[Iterable[str]]), cls (Type[C]), section (Optional[Section]), context_settings (Optional[Dict[str, Any]]), help (Optional[str]), epilog (Optional[str]), short_help (Optional[str]), options_metavar (Optional[str]), add_help_option (bool), no_args_is_help (bool), hidden (bool), deprecated (bool), params (Optional[List[click.Parameter]]), kwargs (Any) → Callable[[AnyCallable], C]
Return a decorator that creates a new subcommand of this
Groupusing the decorated function as callback.It takes the same arguments of
command()plus:section:Optional[Section]if provided, put the subcommand in this section.
Changed in version 0.10.0: all arguments but
nameare now keyword-only.
- group(name=None, *, cls=None, aliases=None, section=None, **kwargs)[source]¶
- Overloads:
self, name (Optional[str]), aliases (Optional[Iterable[str]]), cls (None), section (Optional[Section]), sections (Iterable[Section]), align_sections (Optional[bool]), invoke_without_command (bool), no_args_is_help (bool), context_settings (Optional[Dict[str, Any]]), formatter_settings (Dict[str, Any]), help (Optional[str]), epilog (Optional[str]), short_help (Optional[str]), options_metavar (Optional[str]), subcommand_metavar (Optional[str]), add_help_option (bool), chain (bool), hidden (bool), deprecated (bool), show_subcommand_aliases (bool) → Callable[[AnyCallable], click.Group]
self, name (Optional[str]), aliases (Optional[Iterable[str]]), cls (Optional[Type[G]]), section (Optional[Section]), invoke_without_command (bool), no_args_is_help (bool), context_settings (Optional[Dict[str, Any]]), help (Optional[str]), epilog (Optional[str]), short_help (Optional[str]), options_metavar (Optional[str]), subcommand_metavar (Optional[str]), add_help_option (bool), chain (bool), hidden (bool), deprecated (bool), params (Optional[List[click.Parameter]]), kwargs (Any) → Callable[[AnyCallable], G]
Return a decorator that creates a new subcommand of this
Groupusing the decorated function as callback.It takes the same argument of
group()plus:section:Optional[Section]if provided, put the subcommand in this section.
Changed in version 0.10.0: all arguments but
nameare now keyword-only.
- 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
ExtraGroup. Supports nested resolution:mycli help subgroup subcmdshows the help forsubcmdwithinsubgroup.
- class click_extra.HelpExtraFormatter(*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 ownHelpExtraTheme.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.- theme: HelpExtraTheme¶
- write_usage(prog, args='', prefix=None)[source]¶
ANSI-aware override of
cloup.HelpFormatter.write_usage().Click’s
click.formatting.wrap_text()measures 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 (e.g. 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.See also
Upstream fix proposed at https://github.com/pallets/click/pull/3420, which makes
click.formatting.TextWrapperANSI-aware by counting visible width instead of raw bytes. Once that lands in a Click release, this override can be removed.Todo
Drop this override once the minimum supported Click pins to the release that includes
pallets/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.HelpExtraTheme(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.Example:
INFO: Loaded 23 records.
- 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,--ansi/--no-ansi) wherever they appear: synopsis column, free-form descriptions, and docstrings (whencross_ref_highlightis enabled).Example:
--config CONFIG_PATH Location of the configuration file. -v, --verbose Increase verbosity.
- Return type:
TypeVar(T)
- subcommand()¶
Style applied to subcommand names: in a group’s command list and wherever they are referenced in prose.
Example:
Commands: backup Snapshot the data store. restore Restore from a snapshot. show (ls) Show the current state.
- Return type:
TypeVar(T)
- choice()¶
Style applied to each individual value inside a
click.Choicemetavar and to those values referenced in option descriptions.Example:
--format [json|csv|xml] Output format. Defaults to json.
- Return type:
TypeVar(T)
- metavar()¶
Style applied to type metavars (
INTEGER,TEXT,PATH,FILE, …) that follow an option name in the synopsis column.Example:
--output TEXT Destination file. --workers INTEGER Worker count.
- Return type:
TypeVar(T)
- bracket()¶
Style applied to the literal bracket characters and label prefixes of trailing fields:
[,],default:,env var:,required, and the field separators between them.Example:
--port INTEGER [default: 8080; env var: PORT; required]
- Return type:
TypeVar(T)
- envvar()¶
Style applied to environment-variable values inside
[env var: ...]bracket fields, and to envvar names mentioned in option descriptions.Example:
--threshold INTEGER Acceptable error rate. [env var: THRESHOLD, TEST_THRESHOLD]
- Return type:
TypeVar(T)
- default()¶
Style applied to the default-value content inside
[default: ...]bracket fields.Example:
--output FILENAME Destination file. [default: out.csv] --retries INTEGER Retry budget. [default: 5]
- 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.Example:
--level INTEGER RANGE Verbosity level. [0<=x<=9] --port INTEGER RANGE Bind port. [x>=1024]
- Return type:
TypeVar(T)
- required()¶
Style applied to the
requiredlabel inside bracket fields on mandatory options.Example:
--token TEXT Authentication token. [required]
- 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.Example:
Usage: cp [OPTIONS] SRC DST Usage: pack [OPTIONS] [FILES]... [OUTPUT]
- Return type:
TypeVar(T)
- deprecated()¶
Style applied to
(DEPRECATED)/(Deprecated: reason)markers appended to options and commands.Example:
--old-api Legacy endpoint. (DEPRECATED: use --new-api instead) --legacy Kept for compatibility. (deprecated: will be removed in v9)
- Return type:
TypeVar(T)
- search()¶
Style applied to substring matches in <cli> help --search output, so users can spot where their query matched.
Example: running
my-cli help --search retryhighlights every occurrence of retry in the rendered help output, including--retries,RetryError, and prose mentions of “retry budget”.- 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.Example:
✓ database migration completed ✓ 1,245 records imported
- 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.Example:
◼ 3 mails sharing hash a1b2c3d4 ◼ 7 mails sharing hash e5f6a7b8
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.- Raises:
TypeError – when base is not a
HelpExtraTheme.- Return type:
- class click_extra.HelpFormatter(indent_increment=2, width=None, max_width=None, col1_max_width=30, col2_min_width=35, col_spacing=2, row_sep=None, theme=HelpTheme(invoked_command=<function identity>, command_help=<function identity>, heading=<function identity>, constraint=<function identity>, section_help=<function identity>, col1=<function identity>, col2=<function identity>, alias=<function identity>, alias_secondary=None, epilog=<function identity>))[source]¶
Bases:
HelpFormatterA custom help formatter. Features include:
more attributes for controlling the output of the formatter
a
col1_widthparameter inwrite_dl()that allows Cloup to align multiple definition lists without resorting to hacksa “linear layout” for definition lists that kicks in when the available terminal width is not enough for the standard 2-column layout (see argument
col2_min_width)the first column width, when not explicitly given in
write_dlis computed excluding the rows that exceedcol1_max_width(calledcol_maxinwrite_dlfor compatibility with Click).
Changed in version 0.9.0: the
row_sepparameter now:is set to
Noneby default androw_sep=""corresponds to an empty line between rowsmust not ends with
\n; the formatter writes a newline just after it (when it’s notNone), so a newline at the end is always enforcedaccepts instances of
SepGeneratorandRowSepPolicy.
Added in version 0.8.0.
- Parameters:
indent_increment (
int) – width of each indentation increment.width (
int|None) – content line width, excluding the newline character; by default it’s initialized tomin(terminal_width - 1, max_width)wheremax_widthis another argument.max_width (
int|None) – maximum content line width (equivalent toContext.max_content_width). Used to computewidthwhen it is not provided, ignored otherwise.col1_max_width (
int) – the maximum width of the first column of a definition list; as in Click, if the text of a row exceeds this threshold, the 2nd column is printed on a new line.col2_min_width (
int) – the minimum width for the second column of a definition list; if the available space is less than this value, the formatter switches from the standard 2-column layout to the “linear layout” (that this decision is taken for each definition list). If you want to always use the linear layout, you can set this argument to a very high number (ormath.inf). If you never want it (not recommended), you can set this argument to zero.col_spacing (
int) – the number of spaces between the column boundaries of a definition list.row_sep (
None|str|SepGenerator|RowSepPolicy) – an “extra” separator to insert between the rows of a definition list (in addition to the normal newline between definitions). If you want an empty line between rows, passrow_sep="". Read Row separators for more.theme (
HelpTheme) – anHelpThemeinstance specifying how to style the various elements of the help page.
- static settings(*, width=_Missing.flag, max_width=_Missing.flag, indent_increment=_Missing.flag, col1_max_width=_Missing.flag, col2_min_width=_Missing.flag, col_spacing=_Missing.flag, row_sep=_Missing.flag, theme=_Missing.flag)[source]¶
A utility method for creating a
formatter_settingsdictionary to pass as context settings or command attribute. This method exists for one only reason: it enables auto-complete for formatter options, thus improving the developer experience.Parameters are described in
HelpFormatter.
- write_text(text, style=<function identity>)[source]¶
Writes re-indented text into the buffer. This rewraps and preserves paragraphs.
- Return type:
- write_dl(rows, col_max=None, col_spacing=None, col1_width=None)[source]¶
Write a definition list into the buffer. This is how options and commands are usually formatted.
If there’s enough space, definition lists are rendered as a 2-column pseudo-table: if the first column text of a row doesn’t fit in the provided/computed
col1_width, the 2nd column is printed on the following line.If the available space for the 2nd column is below
self.col2_min_width, the 2nd “column” is always printed below the 1st, indented with a minimum of 3 spaces (or oneindent_incrementif that’s greater than 3).- Parameters:
rows (
Sequence[Tuple[str,str|Callable[[int],str]]]) – a list of two item tuples for the terms and values.col_max (
int|None) – the maximum width for the 1st column of a definition list; this argument is here to not break compatibility with Click; if provided, it overrides the attributeself.col1_max_width.col_spacing (
int|None) – number of spaces between the first and second column; this argument is here to not break compatibility with Click; if provided, it overridesself.col_spacing.col1_width (
int|None) – the width to use for the first column; if not provided, it’s computed as the length of the longest string underself.col1_max_width; useful when you need to align multiple definition lists.
- Return type:
- write_tabular_dl(rows, col1_width, col_spacing, col2_width)[source]¶
Format a definition list as a 2-column “pseudo-table”. If the first column of a row exceeds
col1_width, the 2nd column is written on the subsequent line. This is the standard way of formatting definition lists and it’s the default if there’s enough space.- 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>)[source]¶
Bases:
objectA collection of styles for several elements of the help page.
A “style” is just a function or a callable that takes a string and returns a styled version of it. This means you can use your favorite styling/color library (like rich, colorful etc). Nonetheless, given that Click has some basic styling functionality built-in, Cloup provides the
Styleclass, which is a wrapper of theclick.stylefunction.- Parameters:
invoked_command (
Callable[[str],str]) – Style of the invoked command name (in Usage).command_help (
Callable[[str],str]) – Style of the invoked command description (below Usage).heading (
Callable[[str],str]) – Style of help section headings.constraint (
Callable[[str],str]) – Style of an option group constraint description.section_help (
Callable[[str],str]) – Style of the help text of a section (the optional paragraph below the heading).col1 (
Callable[[str],str]) – Style of the first column of a definition list (options and command names).col2 (
Callable[[str],str]) – Style of the second column of a definition list (help text).alias (
Callable[[str],str]) – Style of subcommand aliases in a definition lists.alias_secondary (
Callable[[str],str] |None) – Style of separator and eventual parenthesis/brackets in subcommand alias lists. If not provided, thealiasstyle will be used.
- section_help()¶
Style of the help text of a section (the optional paragraph below the heading).
- Return type:
TypeVar(T)
- col1()¶
Style of the first column of a definition list (options and command names).
- Return type:
TypeVar(T)
- alias_secondary: Callable[[str], str] | None = None¶
Style of separator and eventual parenthesis/brackets in subcommand alias lists. If not provided, the
aliasstyle will be used.
- class click_extra.IntRange(min=None, max=None, min_open=False, max_open=False, clamp=False)[source]¶
Bases:
_NumberRangeBase,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=1, expose_value=False, show_default=True, type=<class 'int'>, help='Number of parallel jobs. Defaults to one less than available CPUs.', **kwargs)[source]¶
Bases:
ExtraOptionA pre-configured
--jobsoption to control parallel execution.Defaults to one fewer than the number of available CPU cores, leaving one core free for the main process and system tasks.
The resolved value is stored in
ctx.meta[click_extra.context.JOBS].Warning
This option is a placeholder for future parallel execution utilities. It does not drive any concurrency by itself: downstream code must read
ctx.meta[click_extra.context.JOBS]and act on it.
- class click_extra.LazyGroup(*args, lazy_subcommands=None, **kwargs)[source]¶
Bases:
ExtraGroupAn
ExtraGroupthat 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>"}
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: Optional[Section] = 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¶
- 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.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.
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.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(*args, excluded_params=None, included_params=None, **kwargs)[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
..Todo
Evaluates the possibility of replacing all key-based access to the tree-like structure by a Box object, as it provides lots of utilities to merge its content.
Allow a list of paramerers to be blocked from the parameter structure.
Items of
excluded_paramsare expected to be the fully-qualified ID of the parameter. Which is the dot-separated ID that is prefixed by the CLI name, featured in the first column of the table.included_paramsis the inverse: only the listed parameters will be allowed. Cannot be used together withexcluded_params.- 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:
- flatten_tree_dict(tree_dict, parent_key=None)[source]¶
Recursively traverse the tree-like
dictand produce a flatdictwhose keys are path and values are the leaf’s content.
- walk_params()[source]¶
Generates an unfiltered list of all CLI parameters.
Everything is included, from top-level groups to subcommands, and from options to arguments.
- Returns a 2-elements tuple:
the first being a tuple of keys leading to the parameter
the second being the parameter object itself
- TYPE_MAP: ClassVar[dict[type[ParamType], type[str | int | float | bool | list]]] = {<class 'click.types.BoolParamType'>: <class 'bool'>, <class 'click.types.Choice'>: <class 'str'>, <class 'click.types.DateTime'>: <class 'str'>, <class 'click.types.File'>: <class 'str'>, <class 'click.types.FloatParamType'>: <class 'float'>, <class 'click.types.FloatRange'>: <class 'float'>, <class 'click.types.IntParamType'>: <class 'int'>, <class 'click.types.IntRange'>: <class 'int'>, <class 'click.types.Path'>: <class 'str'>, <class 'click.types.StringParamType'>: <class 'str'>, <class 'click.types.Tuple'>: <class 'list'>, <class 'click.types.UUIDParameterType'>: <class 'str'>, <class 'click.types.UnprocessedParamType'>: <class 'str'>}¶
Map Click types to their Python equivalent.
Keys are subclasses of
click.types.ParamType. Values are expected to be simple builtins Python types.This mapping can be seen as a reverse of the
click.types.convert_type()method.
- static 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:
objectRepresents 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.
- 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.
- 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:
t.Any
- 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:
objectA 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 | 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.
- 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:
ParamTypeThe
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.
- 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.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:
- commands: OrderedDict[str, Command]¶
- class click_extra.SectionMixin(*args, commands=None, sections=(), align_sections=None, **kwargs)[source]¶
Bases:
objectAdds to a
click.MultiCommandthe possibility of organizing its subcommands into multiple help sections.Sections can be specified in the following ways:
passing a list of
Sectionobjects to the constructor setting the argumentsectionsusing
add_section()to add a single sectionusing
add_command()with the 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 = ('ID', 'Spec.', 'Class', 'Param type', 'Python type', 'Hidden', 'Exposed', 'Allowed in conf?', 'Env. vars.', 'Default', 'Value', 'Source')¶
Hard-coded list of table headers.
- print_params(ctx, param, value)[source]¶
Introspects current CLI and list its parameters and metadata.
Important
Click doesn’t keep a list of all parsed arguments and their origin. So we need to emulate here what’s happening during CLI invocation.
Unfortunately we cannot even do that because the raw, pre-parsed arguments are not available anywhere within Click’s internals.
Our workaround consist in leveraging our custom
ExtraCommand/ExtraGroupclasses, in which we are attaching aclick_extra.raw_argsmetadata entry to the context.- Return type:
- 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 replacesctx.print_tablewithprint_sorted_table()so that table output is automatically sorted. 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(header_defs, rows)
- 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 returnsthe 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 tableformatting 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.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
HelpExtraThemelands on the Click context underclick_extra.context.THEMEand applies for the duration of the current invocation only.
- 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:
CompositeParamTypeThe 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]) – 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.
- property arity: int¶
int([x]) -> integer int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating-point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4
- convert(value, param, ctx)[source]¶
Convert the value to the correct type. This is not called if the value is
None(the missing value).This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.
The
paramandctxarguments may beNonein certain situations, such as when converting prompt input.If the value cannot be converted, call
fail()with a descriptive message.- 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:
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 (e.g."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 (e.g."unknown_field") for callers that want to dispatch on error type without parsing the message string.
- class click_extra.VerboseOption(param_decls=None, count=True, **kwargs)[source]¶
Bases:
ExtraVerbosity--verbose/-v`option to increase the log level ofExtraVerbosityby a number of steps.If
-vis passed to a CLI, then it will increase the verbosity level by one step. The option can be provided multiple times by the user. So if-vv(or -v -v) is passed, the verbosity will be increase by 2 levels.The default base-level from which we start incrementing is sourced from
VerbosityOption.default. So with--verbosity’s default set toWARNING:-vwill increase the level toINFO,-vvwill increase the level toDEBUG,any number of repetition above that point will be set to the maximum level, so for
-vvvvvfor example will be capped atDEBUG.
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_extra_logger()Default to the globalrootlogger.
- get_base_level(ctx)[source]¶
Returns the default base-level from which the option will start incrementing.
We try first to get the default level from any instance of
VerbosityOptiondefined on the current command. If none is found, it’s because the--verboseoption is used standalone. In which case we defaults toDEFAULT_LEVEL.- Return type:
- get_help_record(ctx)[source]¶
Dynamiccaly generates the default help message.
We need that patch because
get_base_level()depends on the context, so we cannot hard-code the help message asVerboseOption.__init__()default.
- 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:
ExtraVerbosity--verbosity LEVELoption to set the the log level ofExtraVerbosity.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_extra_logger()Default to the globalrootlogger.
- 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.clear()[source]¶
Clears the terminal screen. This will have the effect of clearing the whole visible space of the terminal and moving the cursor to the top left. This does not do anything if not connected to a terminal.
Added in version 2.0.
- 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.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 (
Any|None) – 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]¶
This function takes a text and shows it via an environment specific pager on stdout.
Changed in version 3.0: Added the color flag.
- 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.extraBasicConfig(*, 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.ExtraStreamHandler'>, file_handler_class=<class 'logging.FileHandler'>, formatter_class=<class 'click_extra.logging.ExtraFormatter'>)[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
extraBasicConfig()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 anExtraStreamHandler.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 theExtraStreamHandler. 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 toExtraStreamHandler.file_handler_class (
type[Handler]) – Alogging.Handlerclass that will be used inlogging.basicConfig()to create a default file-based handler. Defaults toFileHandler.formatter_class (
type[Formatter]) – Alogging.Formatterclass of the formatter that will be used inlogging.basicConfig()to setup the default formatter. Defaults toExtraFormatter.
Note
I don’t like the camel-cased name of this function and would have called it
extra_basic_config(), but it’s kept this way for consistency with Python’s standard library.
- 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 (e.g. 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 (e.g. 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]¶
Format the common parameter table cells.
Returns a tuple of 8 cells in column order: ID, Spec., Class, Param type, Python type, Hidden, Env. vars., Default.
For structured formats (JSON, YAML, etc.), cells are native Python values. For visual formats, cells are themed strings matching help-screen styling.
- Return type:
- 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 whateverclick_extra.wrap.patch_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;click_extra.wrap.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_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.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.new_extra_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
ExtraStreamHandlerwithExtraFormatter,Return the logger object.
This function is a wrapper around
extraBasicConfig()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()andextraBasicConfig(). Defaults toTrue.kwargs – Any other keyword parameters supported by
logging.basicConfig()andextraBasicConfig().
- Return type:
- 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 (e.g.--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 (e.g. 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.pass_context(f)[source]¶
Marks a callback as wanting to receive the current context object as first argument. Equivalent to
click.pass_context()but assumes the current context is of typecloup.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_sorted_table(header_defs, table_data, sort_columns=None, table_format=None, *, cell_key=None, **kwargs)[source]¶
Sort and print a table using named column definitions.
header_defsis an ordered sequence of(label, column_id)tuples. Columns withcolumn_id=Noneare not selectable for sorting but still participate in tie-breaking.- Parameters:
header_defs (
Sequence[tuple[str,str|None]]) – Column definitions as(label, column_id)pairs.table_data (
Sequence[Sequence[str|None]]) – Rows of cell values.sort_columns (
Sequence[str] |None) – Column IDs to sort by, in priority order. Falls back to natural header order.table_format (
TableFormat|None) – Rendering format.cell_key (
Callable[[str|None],Any] |None) – Per-cell comparison key. Defaults to ANSI-stripped, case-folded string comparison.
- 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=False, show_eta=True, show_percent=None, show_pos=False, item_show_func=None, fill_char='#', empty_char='-', bar_template='%(label)s [%(bar)s] %(info)s', info_sep=' ', width=36, file=None, color=None, update_min_steps=1)[source]¶
- Overloads:
length (int), label (str | None), hidden (bool), show_eta (bool), show_percent (bool | None), show_pos (bool), fill_char (str), empty_char (str), bar_template (str), info_sep (str), width (int), file (t.TextIO | None), color (bool | None), update_min_steps (int) → ProgressBar[int]
iterable (cabc.Iterable[V] | None), length (int | None), label (str | None), hidden (bool), show_eta (bool), show_percent (bool | None), show_pos (bool), item_show_func (t.Callable[[V | None], str | None] | None), fill_char (str), empty_char (str), bar_template (str), info_sep (str), width (int), file (t.TextIO | None), color (bool | None), update_min_steps (int) → ProgressBar[V]
This function creates an iterable context manager that can be used to iterate over something while showing a progress bar. It will either iterate over the iterable or length items (that are counted up). While iteration happens, this function will print a rendered progress bar to the given file (defaults to stdout) and will attempt to calculate remaining time and more. By default, this progress bar will not be rendered if the file is not a terminal.
The context manager creates the progress bar. When the context manager is entered the progress bar is already created. With every iteration over the progress bar, the iterable passed to the bar is advanced and the bar is updated. When the context manager exits, a newline is printed and the progress bar is finalized on screen.
Note: The progress bar is currently designed for use cases where the total progress can be expected to take at least several seconds. Because of this, the ProgressBar class object won’t display progress that is considered too fast, and progress where the time between steps is less than a second.
No printing must happen or the progress bar will be unintentionally destroyed.
Example usage:
with progressbar(items) as bar: for item in bar: do_something_with(item)
Alternatively, if no iterable is specified, one can manually update the progress bar through the update() method instead of directly iterating over the progress bar. The update method accepts the number of steps to increment the bar with:
with progressbar(length=chunks.total_bytes) as bar: for chunk in chunks: process_chunk(chunk) bar.update(chunks.bytes)
The
update()method also takes an optional value specifying thecurrent_itemat the new position. This is useful when used together withitem_show_functo customize the output for each manual step:with click.progressbar( length=total_size, label='Unzipping archive', item_show_func=lambda a: a.filename ) as bar: for archive in zip_file: archive.extract() bar.update(archive.size, archive)
- Parameters:
iterable (cabc.Iterable[V] | None) – an iterable to iterate over. If not provided the length is required.
length (int | None) – the number of items to iterate over. By default the progressbar will attempt to ask the iterator about its length, which might or might not work. If an iterable is also provided this parameter can be used to override the length. If an iterable is not provided the progress bar will iterate over a range of that length.
label (str | None) – the label to show next to the progress bar.
hidden (bool) – hide the progressbar. Defaults to
False. When no tty is detected, it will only print the progressbar label. Setting this toFalsealso disables that.show_eta (bool) – enables or disables the estimated time display. This is automatically disabled if the length cannot be determined.
show_percent (bool | None) – enables or disables the percentage display. The default is True if the iterable has a length or False if not.
show_pos (bool) – enables or disables the absolute position display. The default is False.
item_show_func (t.Callable[[V | None], str | None] | None) – A function called with the current item which can return a string to show next to the progress bar. If the function returns
Nonenothing is shown. The current item can beNone, such as when entering and exiting the bar.fill_char (str) – the character to use to show the filled part of the progress bar.
empty_char (str) – the character to use to show the non-filled part of the progress bar.
bar_template (str) – the format string to use as template for the bar. The parameters in it are
labelfor the label,barfor the progress bar andinfofor the info section.info_sep (str) – the separator between multiple info items (eta etc.)
width (int) – the width of the progress bar in characters, 0 means full terminal width
file (t.TextIO | None) – The file to write to. If this is not a terminal then only the label is printed.
color (bool | None) – controls if the terminal supports ANSI colors or not. The default is autodetection. This is only needed if ANSI codes are included anywhere in the progress bar output which is not the case by default.
update_min_steps (int) – Render only when this many updates have completed. This allows tuning for very fast iterators.
Added in version 8.2: The
hiddenargument.Changed in version 8.0: Output is shown even if execution time is less than 0.5 seconds.
Changed in version 8.0:
item_show_funcshows the current item, not the previous one.Changed in version 8.0: Labels are echoed if the output is not a TTY. Reverts a change in 7.0 that removed all output.
Added in version 8.0: The
update_min_stepsparameter.Added in version 4.0: The
colorparameter andupdatemethod.Added in version 2.0.
- 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|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.register_theme(name, theme)[source]¶
Register a named theme in the module-level
theme_registry.- Parameters:
name (
str) – Lowercase identifier used as the--themechoice value.theme (
HelpExtraTheme) – AHelpExtraThemeinstance.
- Return type:
- 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.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.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 (e.g.
sort_keys,indentfor 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 —click_extra.wrap.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.
- Return type:
Subpackages¶
- click_extra.sphinx package
EXEC_DIRECTIVES_OPT_INsetup()- 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()
SourceDirectiveRunDirectiveDeprecatedExampleDirectiveClickDomaincleanup_runner()
Submodules¶
click_extra.cli module¶
Click Extra CLI with pre-baking utilities.
click_extra.colorize module¶
Helpers and utilities to apply ANSI coloring to terminal content.
Note
_nearest_256 (24-bit RGB to 256-color quantization) lives here rather than in
pygments.py because both cli.py and pygments.py need it, and
pygments.py is gated behind the optional pygments extra. Placing it in
colorize.py (which has no optional dependencies) keeps the function available
to the CLI regardless of whether Pygments is installed.
- click_extra.colorize.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:
- class click_extra.colorize.ColorOption(param_decls=None, is_flag=True, default=True, is_eager=True, expose_value=False, help='Strip out all colors and all ANSI codes from output.', **kwargs)[source]¶
Bases:
ExtraOptionA pre-configured option that is adding a
--color/--no-color(aliased by--ansi/--no-ansi) to keep or strip colors and ANSI codes from CLI output.This option is eager by default to allow for other eager options (like
--version) to be rendered colorless.Todo
Should we switch to
--color=<auto|never|always>as GNU tools does?Also see how the isatty property defaults with this option, and how it can be implemented in Python.
Todo
Support the TERM environment variable convention?
- set_color(ctx, param, value)[source]¶
Reconcile
--color/--no-color/--ansi/--no-ansiwith environment variables.The reconciliation pass re-inspects the environment for any of the recognised colorization flags (
NO_COLOR,FORCE_COLOR,CLICOLOR, …): when the user hasn’t explicitly passed--color/--no-coloron the command line, the env vars take precedence. The final reconciled value lands onctx.color(the Click-standard attribute thatecho()reads). Renamed fromdisable_colorsbecause the callback handles enable as well as disable: the previous name only described half the behavior.- Return type:
- class click_extra.colorize.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.colorize.ExtraHelpColorsMixin[source]¶
Bases:
objectAdds extra-keywords highlighting to Click commands.
This mixin for
click.Command-like classes intercepts the top-level helper- generation method to initialize the formatter with dynamic settings. This is implemented at this stage so we have access to the global context.- extra_keywords: HelpKeywords | None = None¶
Extra keywords to merge into the auto-collected set. Consumers can set this attribute on a command instance to inject additional keywords for help screen highlighting (e.g. placeholder option names like
--<manager-id>that appear in prose but are not real parameters).
- excluded_keywords: HelpKeywords | None = None¶
Keywords to remove from the auto-collected set. Mirror of
extra_keywords: any string listed here will not be highlighted even if it was collected from the Click context.
- class click_extra.colorize.HelpExtraFormatter(*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 ownHelpExtraTheme.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.- theme: HelpExtraTheme¶
- write_usage(prog, args='', prefix=None)[source]¶
ANSI-aware override of
cloup.HelpFormatter.write_usage().Click’s
click.formatting.wrap_text()measures 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 (e.g. 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.See also
Upstream fix proposed at https://github.com/pallets/click/pull/3420, which makes
click.formatting.TextWrapperANSI-aware by counting visible width instead of raw bytes. Once that lands in a Click release, this override can be removed.Todo
Drop this override once the minimum supported Click pins to the release that includes
pallets/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.colorize.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.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 leverage the mixins in here to build up your own custom variants.
- click_extra.commands.default_extra_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 unittests.
You can still override this hard-coded order for easthetic 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 naturraly reset after each invocation (which is not the case in unitests).
--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--color,--ansi/--no-color,--no-ansi--theme--show-params--table-format FORMAT--verbosity LEVEL-v,--verbose--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.
Important
Sensitivity to order still remains to be proven. With the code of Click Extra and its dependencies moving fast, there is a non-zero chance that all the options are now sound enough to be re-ordered in a more natural way.
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.
- class click_extra.commands.ExtraCommand(*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:
ExtraHelpColorsMixin,CommandLike
cloup.command, with sane defaults and extra help screen colorization.List of extra parameters:
- Parameters:
version_fields (
dict[str,Any] |None) – dictionary ofExtraVersionOptiontemplate field overrides forwarded to the version option. Accepts any field fromExtraVersionOption.template_fields(e.g.prog_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 dynamiccaly. 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, ... } )
- context_class¶
alias of
ExtraContext
- 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
ExtraContextconstructor 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
This workaround is being discussed upstream in click#1279.
- Return type:
- 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:
ExtraHelpColorsMixin,CommandClick Command with help colorization but no extra params.
Mixes in
ExtraHelpColorsMixinfor keyword highlighting and usesExtraContextfor the colorized formatter, without inheriting fromExtraCommand(which would injectdefault_extra_params).Use this as a base for lightweight subcommands (like
help) or for monkey-patching third-party CLIs (viapatch_click()).- context_class¶
alias of
ExtraContext
- 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:
ExtraHelpColorsMixin,GroupClick Group with help colorization but no extra params.
Same as
ColorizedCommandbut for groups.- context_class¶
alias of
ExtraContext
- 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
ExtraGroup. Supports nested resolution:mycli help subgroup subcmdshows the help forsubcmdwithinsubgroup.
- class click_extra.commands.ExtraGroup(*args, help_command=True, **kwargs)[source]¶
Bases:
ExtraCommand,GroupLike
cloup.Group, with sane defaults and extra help screen colorization.Like
ExtraCommand.__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 an
ExtraGroupbe instances ofExtraCommand.That way all subcommands created from an
ExtraGroupbenefits from the same defaults and extra help screen colorization.See: https://click.palletsprojects.com/en/stable/api/#click.Group.command_class
alias of
ExtraCommand
- group_class¶
Let
ExtraGroupproduce sub-groups that are also ofExtraGrouptype.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:
ExtraGroupAn
ExtraGroupthat 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>"}
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: Optional[Section] = None,
fallback_to_default_section: bool = True,
See: https://github.com/janluke/cloup/blob/master/cloup/_sections.py#L169
click_extra.config module¶
Utilities to load parameters and options from a configuration file.
Hint
Why config?
That whole namespace is using the common config short-name to designate
configuration files.
Not conf, not cfg, not configuration, not settings. Just config.
A quick survey of existing practices, and poll to my friends informed me that
config is more explicit and less likely to be misunderstood.
After all, is there a chance for it to be misunderstood, in the context of a CLI, for something else? Confirm? Conference? Conflict Confuse?…
So yes, config is good enough.
Todo
Add a --dump-config or --export-config option to write down the current
configuration (or a template) into a file or <stdout>.
Help message would be: you can use this option with other options or environment variables to have them set in the generated configuration.
Dotted keys in configuration files (e.g. "subcommand.option": value) are
automatically expanded into nested dicts before merging, so users can freely mix
flat dot-notation and nested structures in any supported format.
- click_extra.config.VCS_DIRS = ('.git', '.hg', '.svn', '.bzr', 'CVS', '.darcs')¶
VCS directory names used to identify version control system roots.
Includes: -
.git— Git -.hg— Mercurial -.svn— Subversion -.bzr— Bazaar -CVS— CVS (note: uppercase, no leading dot) -.darcs— Darcs
- class click_extra.config.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')¶
- click_extra.config.CONFIG_OPTION_NAME = 'config'¶
Hardcoded name of the configuration option.
This name is going to be shared by both the
--configand--no-configoptions below, so they can compete with each other to either set a path pattern or disable the use of any configuration file at all.
- click_extra.config.DEFAULT_EXCLUDED_PARAMS = ('config', 'help', 'show_params', 'version')¶
Default parameter IDs to exclude from the configuration file.
Defaults to:
--configoption, which cannot be used to recursively load another configuration file.--help, as it makes no sense to have the configurable file always forces a CLI to show the help and exit.--show-paramsflag, which is like--helpand stops the CLI execution.--version, which is not a configurable option per-se.
- click_extra.config.DEFAULT_SUBCOMMANDS_KEY = '_default_subcommands'¶
Reserved configuration key for specifying default subcommands.
When a group is invoked without explicit subcommands on the CLI, the subcommands listed under this key execute automatically in order. CLI always wins: if the user names subcommands explicitly, the config is ignored.
Example TOML configuration:
[my-cli] _default_subcommands = ["backup", "sync"] [my-cli.backup] path = "/home"
- click_extra.config.PREPEND_SUBCOMMANDS_KEY = '_prepend_subcommands'¶
Reserved configuration key for prepending subcommands to every invocation.
Unlike
_default_subcommandswhich only fires when no subcommands are given on the CLI,_prepend_subcommandsalways prepends the listed subcommands. This is useful for always injecting adebugsubcommand on a dev machine, for example.Only works with
chain=Truegroups (non-chained groups resolve exactly one subcommand, so prepending would break the user’s intended command).Example TOML configuration:
[my-cli] _prepend_subcommands = ["debug"]
- click_extra.config.EXTENSION_METADATA_KEY = 'click_extra.extension'¶
Dataclass field metadata flag marking a field as an extension point.
Schema authors set
metadata={EXTENSION_METADATA_KEY: True}on a field when its sub-tree should pass through click-extra’s CLI-parameter strict check and be validated by app-specific logic instead. Equivalent to typing the field asdict[str, X]: both forms are recognized by_collect_opaque_paths_from_schema()(the internal pipeline still calls these paths “opaque” since they’re skipped by the normalize/flatten/strict machinery). The metadata form is useful when the underlying Python type is something other than adict(for example, a nested dataclass that nonetheless represents user-extensible content).
- click_extra.config.THEMES_CONFIG_KEY: str = 'themes'¶
Sub-key under
[tool.<cli>]where user-defined themes live in config.Used by
ConfigOptionto find[tool.<cli>.themes.<name>]tables, build them viaHelpExtraTheme.from_dict, and stash the result onctx.meta[click_extra.context.THEME_OVERRIDES]. The constant is the single source of truth shared by_builtin_config_validators(),ConfigOption._apply_theme_overrides(), andclick_extra.theme.themes_from_config().
- exception click_extra.config.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 (e.g."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 (e.g."unknown_field") for callers that want to dispatch on error type without parsing the message string.
- class click_extra.config.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 (e.g. autodoc), and may be reused in--helptext in a future release.
- click_extra.config.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 (e.g.--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 (e.g. 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.config.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 (e.g. 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 (e.g. 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.config.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.
- class click_extra.config.Sentinel(*values)[source]¶
Bases:
EnumEnum used to define sentinel values.
Note
This reuse the same pattern as
Click._utils.Sentinel.See also
- NO_CONFIG = <object object>¶
- VCS = <object object>¶
- click_extra.config.NO_CONFIG = Sentinel.NO_CONFIG¶
Sentinel used to indicate that no configuration file must be used at all.
- click_extra.config.VCS = Sentinel.VCS¶
Sentinel used to stop parent directory walking at the nearest VCS root.
- class click_extra.config.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.
- 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 (e.g.[tool.myapp.sub-section]) to map directly to flat dataclass fields (e.g.sub_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 byself.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 will filter out all unrecognized options not supported by the command. Then cleans up blank values and update the context’s
default_map.Uses a ~collections.ChainMap so each config source keeps its own layer. The first layer wins on key lookup, which makes parameter-source precedence explicit and future-proofs for multi-file config loading.
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 (e.g. mappings whose keys are data, not flag names) don’t tripstrict=True.- 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.- Return type:
- ..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.
- class click_extra.config.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.
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.
- class click_extra.config.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:
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 ExtraCommand, 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.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.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.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.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.envvar module¶
Implements environment variable utilities.
- 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 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 as it is exactly computed within Click’s internals, i.e.
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().
- 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.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.ExtraStreamHandler(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.ExtraFormatter(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.HelpExtraTheme, resolved per-invocation viaclick_extra.theme.get_current_theme().- Return type:
- click_extra.logging.extraBasicConfig(*, 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.ExtraStreamHandler'>, file_handler_class=<class 'logging.FileHandler'>, formatter_class=<class 'click_extra.logging.ExtraFormatter'>)[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
extraBasicConfig()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 anExtraStreamHandler.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 theExtraStreamHandler. 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 toExtraStreamHandler.file_handler_class (
type[Handler]) – Alogging.Handlerclass that will be used inlogging.basicConfig()to create a default file-based handler. Defaults toFileHandler.formatter_class (
type[Formatter]) – Alogging.Formatterclass of the formatter that will be used inlogging.basicConfig()to setup the default formatter. Defaults toExtraFormatter.
Note
I don’t like the camel-cased name of this function and would have called it
extra_basic_config(), but it’s kept this way for consistency with Python’s standard library.
- click_extra.logging.new_extra_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
ExtraStreamHandlerwithExtraFormatter,Return the logger object.
This function is a wrapper around
extraBasicConfig()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()andextraBasicConfig(). Defaults toTrue.kwargs – Any other keyword parameters supported by
logging.basicConfig()andextraBasicConfig().
- Return type:
- class click_extra.logging.ExtraVerbosity(param_decls=None, default_logger='root', expose_value=False, is_eager=True, **kwargs)[source]¶
Bases:
ExtraOptionA base class implementing all the common helpers to manipulated logger’s verbosity.
Sets the level of the provided logger. If no logger is provided, sets the level of the global
rootlogger.Important
The internal
click_extralogger will be aligned to the level set through this class.Caution
This class is not intended to be used as-is. It is an internal place to reconcile the verbosity level selected by the competing logger options implemented below:
--verbosity--verbose/-v
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_extra_logger()Default to the globalrootlogger.
- property all_loggers: Generator[Logger, None, None]¶
Returns the list of logger IDs affected by the verbosity option.
Will returns
click_extrainternal logger first, then the option’slogger_name.
- reset_loggers()[source]¶
Forces all loggers managed by the option to be reset to
DEFAULT_LEVEL.Important
Loggers are reset in reverse order to ensure the internal logger is changed last. That way the internal
click_extralogger can report its ongoing logger-altering operations while using the logging facilities itself.Danger
Resetting loggers is extremely important for unittests. Because they’re global, loggers have tendency to leak and pollute their state between multiple test calls.
- Return type:
- set_level(ctx, param, level)[source]¶
Set level of all loggers configured on the option.
All verbosity-related options are attached to this callback, so that’s where we reconcile the multiple values provided by different options. In case of a conflict, the highest versbosity level always takes precedence.
The final reconciled level chosen for the logger will be saved in
ctx.meta[click_extra.context.VERBOSITY_LEVEL]. This context entry served as a kind of global state shared by all verbosity-related options.- Return type:
- logger_name: str¶
The ID of the logger to set the level to.
This will be provided to
logging.getLogger()to fetch the logger object, and as such, can be a dot-separated string to build hierarchical loggers.
- 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:
ExtraVerbosity--verbosity LEVELoption to set the the log level ofExtraVerbosity.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_extra_logger()Default to the globalrootlogger.
- class click_extra.logging.VerboseOption(param_decls=None, count=True, **kwargs)[source]¶
Bases:
ExtraVerbosity--verbose/-v`option to increase the log level ofExtraVerbosityby a number of steps.If
-vis passed to a CLI, then it will increase the verbosity level by one step. The option can be provided multiple times by the user. So if-vv(or -v -v) is passed, the verbosity will be increase by 2 levels.The default base-level from which we start incrementing is sourced from
VerbosityOption.default. So with--verbosity’s default set toWARNING:-vwill increase the level toINFO,-vvwill increase the level toDEBUG,any number of repetition above that point will be set to the maximum level, so for
-vvvvvfor example will be capped atDEBUG.
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_extra_logger()Default to the globalrootlogger.
- get_base_level(ctx)[source]¶
Returns the default base-level from which the option will start incrementing.
We try first to get the default level from any instance of
VerbosityOptiondefined on the current command. If none is found, it’s because the--verboseoption is used standalone. In which case we defaults toDEFAULT_LEVEL.- Return type:
- get_help_record(ctx)[source]¶
Dynamiccaly generates the default help message.
We need that patch because
get_base_level()depends on the context, so we cannot hard-code the help message asVerboseOption.__init__()default.
click_extra.parameters module¶
Our own flavor of Option, Argument and parameters.
- 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:
- 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.Does nothing in particular for now but provides a way to identify Click Extra’s own options with certainty.
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 inHelpExtraFormatter._style_bracket_fields(), which uses the structured data fromOption.get_help_extra()to identify each field by its label.
- class click_extra.parameters.ParamStructure(*args, excluded_params=None, included_params=None, **kwargs)[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
..Todo
Evaluates the possibility of replacing all key-based access to the tree-like structure by a Box object, as it provides lots of utilities to merge its content.
Allow a list of paramerers to be blocked from the parameter structure.
Items of
excluded_paramsare expected to be the fully-qualified ID of the parameter. Which is the dot-separated ID that is prefixed by the CLI name, featured in the first column of the table.included_paramsis the inverse: only the listed parameters will be allowed. Cannot be used together withexcluded_params.- 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:
- flatten_tree_dict(tree_dict, parent_key=None)[source]¶
Recursively traverse the tree-like
dictand produce a flatdictwhose keys are path and values are the leaf’s content.
- walk_params()[source]¶
Generates an unfiltered list of all CLI parameters.
Everything is included, from top-level groups to subcommands, and from options to arguments.
- Returns a 2-elements tuple:
the first being a tuple of keys leading to the parameter
the second being the parameter object itself
- TYPE_MAP: ClassVar[dict[type[ParamType], type[str | int | float | bool | list]]] = {<class 'click.types.BoolParamType'>: <class 'bool'>, <class 'click.types.Choice'>: <class 'str'>, <class 'click.types.DateTime'>: <class 'str'>, <class 'click.types.File'>: <class 'str'>, <class 'click.types.FloatParamType'>: <class 'float'>, <class 'click.types.FloatRange'>: <class 'float'>, <class 'click.types.IntParamType'>: <class 'int'>, <class 'click.types.IntRange'>: <class 'int'>, <class 'click.types.Path'>: <class 'str'>, <class 'click.types.StringParamType'>: <class 'str'>, <class 'click.types.Tuple'>: <class 'list'>, <class 'click.types.UUIDParameterType'>: <class 'str'>, <class 'click.types.UnprocessedParamType'>: <class 'str'>}¶
Map Click types to their Python equivalent.
Keys are subclasses of
click.types.ParamType. Values are expected to be simple builtins Python types.This mapping can be seen as a reverse of the
click.types.convert_type()method.
- static 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]¶
Format the common parameter table cells.
Returns a tuple of 8 cells in column order: ID, Spec., Class, Param type, Python type, Hidden, Env. vars., Default.
For structured formats (JSON, YAML, etc.), cells are native Python values. For visual formats, cells are themed strings matching help-screen styling.
- 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 = ('ID', 'Spec.', 'Class', 'Param type', 'Python type', 'Hidden', 'Exposed', 'Allowed in conf?', 'Env. vars.', 'Default', 'Value', 'Source')¶
Hard-coded list of table headers.
- print_params(ctx, param, value)[source]¶
Introspects current CLI and list its parameters and metadata.
Important
Click doesn’t keep a list of all parsed arguments and their origin. So we need to emulate here what’s happening during CLI invocation.
Unfortunately we cannot even do that because the raw, pre-parsed arguments are not available anywhere within Click’s internals.
Our workaround consist in leveraging our custom
ExtraCommand/ExtraGroupclasses, in which we are attaching aclick_extra.raw_argsmetadata entry to the context.- Return type:
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.
Pygments’ style strings support
bold,italic, andunderline, but have no keywords for faint, blink, reverse, strikethrough, or overline. This override appends dedicated CSS rules fromEXTRA_ANSI_CSSafter the standard Pygments token CSS output.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.
click_extra.pytest module¶
Pytest fixtures and marks to help testing Click CLIs.
- click_extra.pytest.invoke(extra_runner)[source]¶
Invoke fixture shorthand for
click.testing.ExtraCliRunner.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.
Returns:
click.command
click.command()
cloup.command
cloup.command()
click_extra.command
click_extra.command()
click.group
click.group()
cloup.group
cloup.group()
click_extra.group
click_extra.group()
- click_extra.pytest.option_decorators(no_options=False, no_arguments=False, no_click=False, no_cloup=False, no_extra=False, with_parenthesis=True, with_types=False)[source]¶
Returns collection of Pytest parameters to test all parameter-like decorators.
Returns:
click.option
click.option()
cloup.option
cloup.option()
click_extra.option
click_extra.option()
click.argument
click.argument()
cloup.argument
cloup.argument()
click_extra.argument
click_extra.argument()
click_extra.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 (e.g.
sort_keys,indentfor 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 returnsthe 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 tableformatting function.
- click_extra.table.print_sorted_table(header_defs, table_data, sort_columns=None, table_format=None, *, cell_key=None, **kwargs)[source]¶
Sort and print a table using named column definitions.
header_defsis an ordered sequence of(label, column_id)tuples. Columns withcolumn_id=Noneare not selectable for sorting but still participate in tie-breaking.- Parameters:
header_defs (
Sequence[tuple[str,str|None]]) – Column definitions as(label, column_id)pairs.table_data (
Sequence[Sequence[str|None]]) – Rows of cell values.sort_columns (
Sequence[str] |None) – Column IDs to sort by, in priority order. Falls back to natural header order.table_format (
TableFormat|None) – Rendering format.cell_key (
Callable[[str|None],Any] |None) – Per-cell comparison key. Defaults to ANSI-stripped, case-folded string comparison.
- Return type:
- 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 replacesctx.print_tablewithprint_sorted_table()so that table output is automatically sorted. 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(header_defs, rows)
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.testing module¶
CLI testing and simulation of their execution.
- 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.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.format_cli_prompt(cmd_args, extra_env=None)[source]¶
Simulate the console prompt used to invoke the CLI.
- Return type:
- 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.print_cli_run(args, result, env=None)[source]¶
Prints the full simulation of CLI execution, including output.
- 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.ExtraResult(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.ExtraCliRunner(charset='utf-8', env=None, echo_stdin=False, catch_exceptions=True)[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 –
can be nested iterables composed of
str,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 –
same as
click.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 representation in the regexes above.
- 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.timer module¶
Command execution time measurement.
- class click_extra.timer.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:
click_extra.types module¶
- 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 (i.e. thenameproperty),ChoiceSource.VALUEto use thevalue,ChoiceSource.STRto use thestr()string representation, orA custom callable that takes an
Enummember and returns a string.
Default to
ChoiceSource.STR, which makes you to only have 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]¶
Derivate the choice string from the given
Enum’smember.- Return type:
click_extra.version module¶
Gather CLI metadata and print them.
Pre-baking is inspired by shadow-rs, which injects build-time
constants (BRANCH, SHORT_COMMIT, COMMIT_HASH,
COMMIT_DATE, TAG, …) into Rust binaries at compile time.
Todo
shadow-rs also provides constants not yet covered here:
BUILD_TIME, BUILD_TIME_2822, BUILD_TIME_3339,
BUILD_OS, BUILD_TARGET, BUILD_TARGET_ARCH. Some overlap
with data already in {env_info} (Python version, OS,
architecture). Others like BUILD_TIME could be added as new
template fields.
- 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 that can be pre-baked, mapped to their
gitsubcommand args.git_tag_shais excluded because its resolution depends ongit_tag(it runsgit rev-list -1 <tag>), so it cannot be expressed as a static argument tuple.
- click_extra.version.run_git(*args, cwd=None)[source]¶
Run a
gitcommand and return its stripped output, orNone.cwd defaults to the current working directory when not provided.
- click_extra.version.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
ExtraVersionOption.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.version.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 serves 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.version.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].
- class click_extra.version.ExtraVersionOption(param_decls=None, message=None, module=None, module_name=None, module_file=None, module_version=None, package_name=None, package_version=None, exec_name=None, version=None, git_repo_path=None, git_branch=None, git_long_hash=None, git_short_hash=None, git_date=None, git_tag=None, git_tag_sha=None, prog_name=None, env_info=None, message_style=None, module_style=None, module_name_style=Style(fg='bright_white'), module_file_style=None, module_version_style=Style(fg='green'), package_name_style=Style(fg='bright_white'), package_version_style=Style(fg='green'), exec_name_style=Style(fg='bright_white'), version_style=Style(fg='green'), git_repo_path_style=Style(fg='bright_black'), git_branch_style=Style(fg='cyan'), git_long_hash_style=Style(fg='yellow'), git_short_hash_style=Style(fg='yellow'), git_date_style=Style(fg='bright_black'), git_tag_style=Style(fg='cyan'), git_tag_sha_style=Style(fg='yellow'), prog_name_style=Style(fg='bright_white'), env_info_style=Style(fg='bright_black'), 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}.module_name (
str|None) – forces the value of{module_name}.module_file (
str|None) – forces the value of{module_file}.module_version (
str|None) – forces the value of{module_version}.package_name (
str|None) – forces the value of{package_name}.package_version (
str|None) – forces the value of{package_version}.git_repo_path (
str|None) – forces the value of{git_repo_path}.git_long_hash (
str|None) – forces the value of{git_long_hash}.git_short_hash (
str|None) – forces the value of{git_short_hash}.git_tag_sha (
str|None) – forces the value of{git_tag_sha}.env_info (
dict[str,str] |None) – forces the value of{env_info}.message_style (
Callable[[str],str] |None) – default style of the message.module_style (
Callable[[str],str] |None) – style of{module}.module_name_style (
Callable[[str],str] |None) – style of{module_name}.module_file_style (
Callable[[str],str] |None) – style of{module_file}.module_version_style (
Callable[[str],str] |None) – style of{module_version}.package_name_style (
Callable[[str],str] |None) – style of{package_name}.package_version_style (
Callable[[str],str] |None) – style of{package_version}.exec_name_style (
Callable[[str],str] |None) – style of{exec_name}.version_style (
Callable[[str],str] |None) – style of{version}.git_repo_path_style (
Callable[[str],str] |None) – style of{git_repo_path}.git_branch_style (
Callable[[str],str] |None) – style of{git_branch}.git_long_hash_style (
Callable[[str],str] |None) – style of{git_long_hash}.git_short_hash_style (
Callable[[str],str] |None) – style of{git_short_hash}.git_date_style (
Callable[[str],str] |None) – style of{git_date}.git_tag_style (
Callable[[str],str] |None) – style of{git_tag}.git_tag_sha_style (
Callable[[str],str] |None) – style of{git_tag_sha}.prog_name_style (
Callable[[str],str] |None) – style of{prog_name}.env_info_style (
Callable[[str],str] |None) – style of{env_info}.
- template_fields: tuple[str, ...] = ('module', 'module_name', 'module_file', 'module_version', 'package_name', 'package_version', 'exec_name', 'version', 'git_repo_path', 'git_branch', 'git_long_hash', 'git_short_hash', 'git_date', 'git_tag', 'git_tag_sha', 'prog_name', 'env_info')¶
List of field IDs recognized by the message template.
- 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 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
+(i.e., 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, then falls back togit rev-parse --abbrev-ref HEAD.
- property git_long_hash: str | None[source]¶
Returns the full Git commit hash.
Checks for a pre-baked
__git_long_hash__dunder first, then falls back togit rev-parse HEAD.
- property git_short_hash: str | None[source]¶
Returns the short Git commit hash.
Checks for a pre-baked
__git_short_hash__dunder first, then falls back togit rev-parse --short HEAD.Hint
The short hash is usually the first 7 characters of the full hash, but this is not guaranteed to be the case.
But it is at least guaranteed to be unique within the repository, and a minimum of 4 characters.
- property git_date: str | None[source]¶
Returns the commit date in ISO format:
YYYY-MM-DD HH:MM:SS +ZZZZ.Checks for a pre-baked
__git_date__dunder first, then falls back togit show -s --format=%ci HEAD.
- property git_tag: str | None[source]¶
Returns the Git tag pointing at HEAD, if any.
Checks for a pre-baked
__git_tag__dunder first, then falls back togit describe --tags --exact-match HEAD.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, then falls back togit rev-list -1on the tag returned bygit_tag. ReturnsNoneif HEAD is not at a tag.
- 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: