click_extra packageΒΆ
Expose package-wide elements.
- exception click_extra.Abort[source]ΒΆ
Bases:
RuntimeError
An internal signalling exception that signals Click to abort.
- class click_extra.Argument(*args, help=None, **attrs)[source]ΒΆ
Bases:
Argument
A
click.Argument
with help text.
- exception click_extra.BadArgumentUsage(message, ctx=None)[source]ΒΆ
Bases:
UsageError
Raised if an argument is generally supplied but the use of the argument was incorrect. This is for instance raised if the number of values for an argument is not correct.
Added in version 6.0.
- exception click_extra.BadOptionUsage(option_name, message, ctx=None)[source]ΒΆ
Bases:
UsageError
Raised if an option is generally supplied but the use of the option was incorrect. This is for instance raised if the number of arguments for an option is not correct.
Added in version 4.0.
- Parameters:
option_name (str) β the name of the option being used incorrectly.
- exception click_extra.BadParameter(message, ctx=None, param=None, param_hint=None)[source]ΒΆ
Bases:
UsageError
An exception that formats out a standardized error message for a bad parameter. This is useful when thrown from a callback or type as Click will attach contextual information to it (for instance, which parameter it is).
Added in version 2.0.
- Parameters:
param (Parameter | None) β the parameter object that caused this error. This can be left out, and Click will attach this info itself if possible.
param_hint (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 Options 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-
str
choices
are now supported. It can additionally be any iterable. Before you were not recommended to pass anything but a list or tuple.Added in version 8.2.0: Choice normalization can be overridden via
normalize_choice()
.- 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.
- Return type:
str
Added in version 8.2.
- 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. :rtype: str
Changed in version 8.2.0: Added
ctx
argument.
- 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. :rtype: strAdded in version 8.2.0.
- shell_complete(ctx, param, incomplete)[source]ΒΆ
Complete choices that start with the incomplete value.
- Parameters:
ctx (Context) β Invocation context for this command.
param (Parameter) β The parameter that is requesting completion.
incomplete (str) β Value being completed. May be empty.
- Return type:
list[CompletionItem]
Added in version 8.0.
- 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. :rtype:
None
Added in version 2.0.
- exception click_extra.ClickException(message)[source]ΒΆ
Bases:
Exception
An 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:
FrozenSpace
Colors accepted by
Style
andclick.style()
.- black = 'black'ΒΆ
- blue = 'blue'ΒΆ
- bright_black = 'bright_black'ΒΆ
- bright_blue = 'bright_blue'ΒΆ
- bright_cyan = 'bright_cyan'ΒΆ
- bright_green = 'bright_green'ΒΆ
- bright_magenta = 'bright_magenta'ΒΆ
- bright_red = 'bright_red'ΒΆ
- bright_white = 'bright_white'ΒΆ
- bright_yellow = 'bright_yellow'ΒΆ
- cyan = 'cyan'ΒΆ
- green = 'green'ΒΆ
- magenta = 'magenta'ΒΆ
- red = 'red'ΒΆ
- reset = 'reset'ΒΆ
- white = 'white'ΒΆ
- yellow = 'yellow'ΒΆ
- 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
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- 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:
ExtraOption
A pre-configured option that is adding a
--color
/--no-color
(aliased by--ansi
/--no-ansi
) option 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?
- class click_extra.Command(*args, aliases=None, formatter_settings=None, **kwargs)[source]ΒΆ
Bases:
ConstraintMixin
,OptionGroupMixin
,Command
A
click.Command
supporting option groups and constraints.Refer to superclasses for the documentation of all accepted parameters:
Besides other things, this class also:
adds a
formatter_settings
instance attribute.
Refer to
click.Command
for 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
- format_epilog(ctx, formatter)[source]ΒΆ
Writes the epilog into the formatter if it exists.
- Return type:
- format_help(ctx, formatter)[source]ΒΆ
Writes the help into the formatter if it exists.
This is a low-level method called by
get_help()
.This calls the following methods: :rtype:
None
format_usage()
format_options()
- format_help_text(ctx, formatter)[source]ΒΆ
Writes the help text to the formatter if it exists.
- Return type:
- aliases: List[str]ΒΆ
HelpFormatter options that are merged with
Context.formatter_settings
(eventually overriding some values).
- click_extra.command(*args, **kwargs)ΒΆ
Returns a new decorator instantiated with custom defaults.
These defaults values are merged with the userβs own arguments.
A special case is made for the
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- class click_extra.CommandCollection(name=None, sources=None, **kwargs)[source]ΒΆ
Bases:
Group
A
Group
that looks up subcommands on other groups. If a command is not found on this group, each registered source is checked in order. Parameters on a source are not added to this group, and a sourceβs callback is not invoked when invoking its commands. In other words, this βflattensβ commands in many groups into this one group.- Parameters:
Changed in version 8.2: This is a subclass of
Group
. Commands are looked up first on this group, then each of its sources.- get_command(ctx, cmd_name)[source]ΒΆ
Given a context and a command name, this returns a
Command
object if it exists or returnsNone
.
- 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
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- class click_extra.ConfigOption(param_decls=None, metavar='CONFIG_PATH', type=STRING, help='Location of the configuration file. Supports glob pattern of local path and remote URL.', is_eager=True, expose_value=False, formats=(Formats.TOML, Formats.YAML, Formats.JSON, Formats.INI, Formats.XML), roaming=True, force_posix=False, excluded_params=None, strict=False, **kwargs)[source]ΒΆ
Bases:
ExtraOption
,ParamStructure
A pre-configured option adding
--config
/-C
option.Takes as input a glob pattern or an URL.
Glob patterns must follow the syntax of wcmatch.glob.
is_eager
is active by default so the config optionβscallback
gets the opportunity to set thedefault_map
values before the other options use them.formats
is the ordered list of formats that the configuration file will be tried to be read with. Can be a single one.roaming
andforce_posix
are fed to click.get_app_dir() to setup the default configuration folder.excluded_params
is a list of options to ignore by the configuration parser. Defaults toParamStructure.DEFAULT_EXCLUDED_PARAMS
.strict
If
True
, raise an error if the configuration file contain unrecognized content.If
False
, silently ignore unsupported configuration option.
- default_pattern()[source]ΒΆ
Returns the default pattern used to search for the configuration file.
Defaults to
/<app_dir>/*.{toml,yaml,yml,json,ini,xml}
. Where<app_dir>
is produced by the clickget_app_dir() method. The result depends on OS and is influenced by theroaming
andforce_posix
properties of this instance.In that folder, weβre looking for any file matching the extensions derived from the
self.formats
property: :rtype:str
a simple
*.ext
pattern if only one format is setan expanded
*.{ext1,ext2,...}
pattern if multiple formats are set
- get_help_record(ctx)[source]ΒΆ
Replaces the default value by the pretty version of the configuration matching pattern.
- load_conf(ctx, param, path_pattern)[source]ΒΆ
Fetch parameters values from configuration file and sets 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. And direct CLI parameters, environment variables or interactive prompts takes precedence over any values from the config file.
- Return type:
- 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 ofINI
format 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
.- Return type:
- parse_conf(conf_text)[source]ΒΆ
Try to parse the provided content with each format in the order provided by the user.
A successful parsing in any format is supposed to return a
dict
. Any other result, including any raised exception, is considered a failure and the next format is tried.
- read_and_parse_conf(pattern)[source]ΒΆ
Search for a configuration file matching the provided pattern.
Returns the location and parsed content of the first valid configuration file that is not blank, or (None, None) if no file was found.
- search_and_read_conf(pattern)[source]ΒΆ
Search on local file system or remote URL files matching the provided pattern.
pattern
is considered an URL only if it is parseable as such and starts withhttp://
orhttps://
.Returns an iterator of the normalized configuration location and its textual content, for each file/URL matching the pattern.
- formats: Sequence[Formats]ΒΆ
- roaming: boolΒΆ
- force_posix: boolΒΆ
- strict: boolΒΆ
- click_extra.confirm(text, default=False, abort=False, prompt_suffix=': ', show_default=True, err=False)[source]ΒΆ
Prompts for confirmation (yes/no question).
If the user aborts the input by sending a interrupt signal this function will catch it and raise a
Abort
exception.- Parameters:
text (
str
) β the question to ask.default (
bool
|None
) β The default value to use when no input is given. 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 tostderr
instead ofstdout
, the same as with echo.
- Return type:
Changed in version 8.0: Repeat until input is given if
default
isNone
.Added in version 4.0: Added the
err
parameter.
- click_extra.confirmation_option(*param_decls, **kwargs)[source]ΒΆ
Add a
--yes
option which shows a prompt before continuing if not passed. If the prompt is declined, the program will exit.
- 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-file
isinput_file
).
- class click_extra.ConstraintMixin(*args, constraints=(), show_constraints=None, **kwargs)[source]ΒΆ
Bases:
object
Provides support for constraints.
- Parameters:
constraints (
Sequence
[Union
[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 (
Optional
[bool
]) β 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
OptionGroup
instances.
-
param_constraints:
Tuple
[BoundConstraint
,...
]ΒΆ Constraints registered using
@constraint
(or equivalent method).
- all_constraintsΒΆ
All constraints applied to parameter/option groups of this command.
- 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:
Context
A custom context for Cloup.
Look up
click.Context
for the list of all arguments.Added in version 0.9.0: added the
check_constraints_consistency
parameter.Added in version 0.8.0.
- Parameters:
ctx_args (
Any
) β arguments forwarded toclick.Context
.align_option_groups (
Optional
[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 (
Optional
[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 (
Optional
[bool
]) β whether to show the aliases of subcommands in the help of acloup.Group
.show_constraints (
Optional
[bool
]) β whether to include a βConstraintβ section in the command help (if at least one constraint is defined).check_constraints_consistency (
Optional
[bool
]) β enable additional checks for constraints which detects mistakes of the developer (seecloup.Constraint.check_consistency()
).formatter_settings (
Dict
[str
,Any
]) β keyword arguments forwarded toHelpFormatter
inmake_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
.
- exit(code=0)ΒΆ
Exits the application with a given exit code.
Forces the context to close before exiting, so callbacks attached to parameters will be called to clean up their state. This is not important in normal CLI execution as the Python process will just be destroyed. But it will lead to leaky states in unitttests. :rtype:
NoReturn
See also
This fix has been proposed upstream to Click.
- formatter_classΒΆ
alias of
HelpFormatter
- make_formatter()[source]ΒΆ
Creates the
HelpFormatter
for the help and usage output.To quickly customize the formatter class used without overriding this method, set the
formatter_class
attribute. :rtype:HelpFormatter
Changed in version 8.0: Added the
formatter_class
attribute.
- 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_settings
dictionary.- Parameters:
auto_envvar_prefix (
Union
[_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 (
Union
[_Missing
,Dict
[str
,Any
]]) β a dictionary (like object) with default values for parameters.terminal_width (
Union
[_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 (
Union
[_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 (
Union
[_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 (
Union
[_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 (
Union
[_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 (
Union
[_Missing
,bool
]) β instructs click to ignore options it does not know and keeps them for later processing.help_option_names (
Union
[_Missing
,List
[str
]]) β optionally a list of strings that define how the default help parameter is named. The default is['--help']
.token_normalize_func (
Union
[_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 (
Union
[_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 (
Union
[_Missing
,bool
]) β Show defaults for all options. If not set, defaults to the value from a parent context. Overrides an optionβsshow_default
argument.align_option_groups (
Union
[_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 (
Union
[_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 (
Union
[_Missing
,bool
]) β whether to show the aliases of subcommands in the help of acloup.Group
.show_constraints (
Union
[_Missing
,bool
]) β whether to include a βConstraintβ section in the command help (if at least one constraint is defined).check_constraints_consistency (
Union
[_Missing
,bool
]) β enable additional checks for constraints which detects mistakes of the developer (seecloup.Constraint.check_consistency()
).formatter_settings (
Union
[_Missing
,Dict
[str
,Any
]]) β keyword arguments forwarded toHelpFormatter
inmake_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:
- 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).
- class click_extra.DateTime(formats=None)[source]ΒΆ
Bases:
ParamType
The DateTime type converts date strings into datetime objects.
The format strings which are checked are configurable, but default to some common (non-timezone aware) ISO 8601 formats.
When specifying DateTime formats, you should only pass a list or a tuple. Other iterables, like generators, may lead to surprising results.
The format strings are processed using
datetime.strptime
, and this consequently defines the format strings which are allowed.Parsing is tried using each format, in order, and the first format which parses successfully is used.
- Parameters:
formats (
Sequence
[str
] |None
) β A list or tuple of date format strings, in the order in which they should be tried. Defaults to'%Y-%m-%d'
,'%Y-%m-%dT%H:%M:%S'
,'%Y-%m-%d %H:%M:%S'
.
- convert(value, param, ctx)[source]ΒΆ
Convert the value to the correct type. This is not called if the value is
None
(the missing value).This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.
The
param
andctx
arguments may beNone
in 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
- click_extra.dir_path(*, path_type=<class 'pathlib.Path'>, exists=False, readable=True, writable=False, executable=False, resolve_path=False, allow_dash=False)[source]ΒΆ
Shortcut for
click.Path
withfile_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 (
Optional
[IO
[Any
]]) β The file to write to. Defaults tostdout
.err (
bool
) β Write tostderr
instead ofstdout
.nl (
bool
) β Print a newline after the message. Enabled by default.color (
bool
|None
) β Force showing or hiding colors and other styles. By default Click will remove color if the output does not look like an interactive terminal.
- Return type:
Changed in version 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
color
parameter.Added in version 3.0: Added the
err
parameter.Changed in version 2.0: Support colors on Windows if colorama is installed.
- click_extra.echo_via_pager(text_or_generator, color=None)[source]ΒΆ
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]ΒΆ
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
UsageError
is raised.Note for Windows: to simplify cross-platform usage, the newlines are automatically converted from POSIX to Windows and vice versa. As such, the message here will have
\n
as newline markers.- 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.
- Return type:
Changed in version 8.2.0:
filename
now accepts anyIterable[str]
in addition to astr
if theeditor
supports editing multiple files at once.
- click_extra.extra_command(*args, **kwargs)ΒΆ
Returns a new decorator instantiated with custom defaults.
These defaults values are merged with the userβs own arguments.
A special case is made for the
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- click_extra.extra_group(*args, **kwargs)ΒΆ
Returns a new decorator instantiated with custom defaults.
These defaults values are merged with the userβs own arguments.
A special case is made for the
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- click_extra.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
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- click_extra.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
root
logger.This function is a wrapper around Python standard libraryβs
logging.basicConfig()
, but with additional parameters and tweaked defaults.It sets up the global
root
logger, and optionally adds a file or stream handler to it.Differences in default values:
Argument
extraBasicConfig()
defaultlogging.basicConfig()
defaultstyle
{
%
format
{levelname}: {message}
%(levelname)s:%(name)s:%(message)s
This function takes the same parameters as
logging.basicConfig()
, but require them to be all passed as explicit keywords arguments.- Parameters:
filename (
str
|None
) β Specifies that alogging.FileHandler
be 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 theroot
logger level to the specified level.stream (
Optional
[IO
[Any
]]) β Use the specified stream to initialize theExtraStreamHandler
. Note that this argument is incompatible with filename - if both are present, aValueError
is raised.handlers (
Iterable
[Handler
] |None
) β If specified, this should be an iterable of already created handlers to add to theroot
logger. Any handlers which donβt already have a formatter set will be assigned the default formatter created in this function. Note that this argument is incompatible with filename or stream - if both are present, aValueError
is raised.force (
bool
) β If this argument is specified asTrue
, any existing handlers attached to theroot
logger are removed and closed, before carrying out the configuration as specified by the other arguments.encoding (
str
|None
) β Name of the encoding used to decode or encode the file. To be specified along with filename, and passed tologging.FileHandler
for 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 ifNone
is 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
[TypeVar
(THandler
, bound=Handler
)]) β Alogging.Handler
class that will be used inlogging.basicConfig()
to create a default stream-based handler. Defaults toExtraStreamHandler
.file_handler_class (
type
[TypeVar
(THandler
, bound=Handler
)]) β Alogging.Handler
class that will be used inlogging.basicConfig()
to create a default file-based handler. Defaults toFileHandler
.formatter_class (
type
[TypeVar
(TFormatter
, bound=Formatter
)]) β Alogging.Formatter
class 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.
- class click_extra.ExtraCliRunner(charset='utf-8', env=None, echo_stdin=False, catch_exceptions=True)[source]ΒΆ
Bases:
CliRunner
Augment
click.testing.CliRunner
with extra features and bug fixes.- force_color: bool = FalseΒΆ
Global class attribute to override the
color
parameter ininvoke
.Note
This was initially developed to force the initialization of the runner during the setup of Sphinx new directives. This was the only way we found, as to patch some code we had to operate at the class level.
- 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
color
property at the class-level viaforce_color
attribute.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
color
was 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.Path
objects andNone
values. The nested structure will be flattened andNone
values 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 (
Optional
[Mapping
[str
,str
|None
]]) β same asclick.testing.CliRunner.invoke()
.catch_exceptions (
bool
) β same asclick.testing.CliRunner.invoke()
.color (
Union
[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 asTrue
toclick.testing.CliRunner.isolation()
and an extracolor=True
parameter 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:
- invoke2(cli, args=None, input=None, env=None, catch_exceptions=True, color=False, **extra)[source]ΒΆ
Copy of
click.testing.CliRunner.invoke()
with extra<output>
stream. :rtype:Result
Caution
This is a hard-copy of the modified
invoke()
method from click#2523 PR which has not been merged upstream yet.Todo
Reduce the code duplication here by using clever monkeypatching?
- class click_extra.ExtraCommand(*args, version=None, extra_option_at_end=True, populate_auto_envvars=True, **kwargs)[source]ΒΆ
Bases:
ExtraHelpColorsMixin
,Command
Like
cloup.command
, with sane defaults and extra help screen colorization.List of extra parameters:
- Parameters:
version (
str
|None
) β allows a version string to be set directly on the command. Will be passed to the first instance ofExtraVersionOption
parameter attached to the command.extra_option_at_end (
bool
) β reorders all parameters attached to the command, by moving all instances ofExtraOption
at 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 ofclick
which 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
True
orFalse
, 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 whoseprompt
property is set.Defaults to
None
, which will leave all options untouched, and let them decide of their ownshow_choices
setting.show_envvar = None
(Click Extra feature)If set to
True
orFalse
, 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_envvar
setting. The rationale being that discoverability of environment variables is enabled by the--show-params
option, which is active by default on extra commands. So there is no need to surcharge the help screen.This addresses the click#2313 issue.
To override these defaults, you can pass your own settings with the
context_settings
parameter:@extra_command( context_settings={ "show_default": False, ... } )
- context_classΒΆ
alias of
ExtraContext
- invoke(ctx)[source]ΒΆ
Main execution of the command, just after the context has been instantiated in
main()
.- Return type:
- main(*args, **kwargs)[source]ΒΆ
Pre-invocation step that is instantiating the context, then call
invoke()
within it.During context instantiation, each optionβs callbacks are called. Beware that these might break the execution flow (like
--help
or--version
).
- make_context(info_name, args, parent=None, **extra)[source]ΒΆ
Intercept the call to the original
click.core.Command.make_context
so we can keep a copy of the raw, pre-parsed arguments provided to the CLI.The result are passed to our own
ExtraContext
constructor which is able to initialize the contextβsmeta
property under our ownclick_extra.raw_args
entry. This will be used inShowParamsOption.print_params()
to print the table of parameters fed to the CLI. :rtype:Any
See also
This workaround is being discussed upstream in click#1279.
- class click_extra.ExtraContext(*args, meta=None, **kwargs)[source]ΒΆ
Bases:
Context
Like
cloup._context.Context
, but with the ability to populate the contextβsmeta
property at instantiation.Also inherits
color
property from parent context. And sets it to True for parentless contexts at instantiatiom, so we can always have colorized output.Todo
Propose addition of
meta
keyword upstream to Click.Like parentβs context but with an extra
meta
keyword-argument.Also force
color
property default to True if not provided by user and this context has no parent.- property color: bool | NoneΒΆ
Overrides
Context.color
to allow inheritance from parent context.Returns the color setting of the parent context if it exists and the color is not set on the current context.
- formatter_classΒΆ
alias of
HelpExtraFormatter
- class click_extra.ExtraFormatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)[source]ΒΆ
Bases:
Formatter
Click Extraβs default log formatter.
Initialize the formatter with specified format strings.
Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format.
Use a style parameter of β%β, β{β or β$β to specify that you want to use one of %-formatting,
str.format()
({}
) formatting orstring.Template
formatting in your format string.Changed in version 3.2: Added the
style
parameter.- formatMessage(record)[source]ΒΆ
Colorize the recordβs log level name before calling the standard formatter.
Colors are sourced from a
click_extra.colorize.HelpExtraTheme
. Default colors are configured onclick_extra.colorize.default_theme
.- Return type:
- class click_extra.ExtraGroup(*args, version=None, extra_option_at_end=True, populate_auto_envvars=True, **kwargs)[source]ΒΆ
Bases:
ExtraCommand
,Group
Like``cloup.Group``, with sane defaults and extra help screen colorization.
List of extra parameters:
- Parameters:
version (
str
|None
) β allows a version string to be set directly on the command. Will be passed to the first instance ofExtraVersionOption
parameter attached to the command.extra_option_at_end (
bool
) βreorders all parameters attached to the command, by moving all instances of
ExtraOption
at the end of the parameter list. The original order of the options is preserved among themselves.populate_auto_envvars (
bool
) βforces all parameters to have their auto-generated environment variables registered. This address the shortcoming of
click
which 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
True
orFalse
, 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 whoseprompt
property is set.Defaults to
None
, which will leave all options untouched, and let them decide of their ownshow_choices
setting.show_envvar = None
(Click Extra feature)If set to
True
orFalse
, 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_envvar
setting. The rationale being that discoverability of environment variables is enabled by the--show-params
option, which is active by default on extra commands. So there is no need to surcharge the help screen.This addresses the click#2313 issue.
To override these defaults, you can pass your own settings with the
context_settings
parameter:@extra_command( context_settings={ "show_default": False, ... } )
- command_classΒΆ
alias of
ExtraCommand
- class click_extra.ExtraOption(*args, group=None, **attrs)[source]ΒΆ
Bases:
Option
All new options implemented by
click-extra
inherits this class.Does nothing in particular for now but provides a way to identify Click Extraβs own options with certainty.
Also contains Option-specific code that should be contributed upstream to Click.
- static get_help_default(option, ctx)[source]ΒΆ
Produce the string to be displayed in the help as optionβs default. :rtype:
str
|None
Caution
This is a copy of Clickβs default value rendering of the default
This code should be keep in sync with Clickβs implementation.
Attention
This doesnβt work with our own
--config
option because we are also monkey-patching ConfigOption.get_help_record() to display the dynamic default value.So the results of this method call is:
<bound method ConfigOption.default_pattern of <ConfigOption config>>
instead of the expected:
~/(...)/multiple_envvars.py/*.{toml,yaml,yml,json,ini,xml}
Todo
A better solution has been proposed upstream to Click: - https://github.com/pallets/click/issues/2516 - https://github.com/pallets/click/pull/2517
- class click_extra.ExtraStreamHandler(stream=None)[source]ΒΆ
Bases:
StreamHandler
A 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.
- emit(record)[source]ΒΆ
Use
click.echo()
to print to the console.- Return type:
- 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.
- 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, prog_name=None, env_info=None, message_style=None, module_style=None, module_name_style=Style(fg='bright_white', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), module_file_style=None, module_version_style=Style(fg='green', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), package_name_style=Style(fg='bright_white', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), package_version_style=Style(fg='green', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), exec_name_style=Style(fg='bright_white', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), version_style=Style(fg='green', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), prog_name_style=Style(fg='bright_white', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), env_info_style=Style(fg='bright_black', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), is_flag=True, expose_value=False, is_eager=True, help='Show the version and exit.', **kwargs)[source]ΒΆ
Bases:
ExtraOption
Gather 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
Extra
prefix.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
--version
option 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}
.env_info (
dict
[str
,str
] |None
) β forces the value of{env_info}
.message_style (
Optional
[Callable
[[str
],str
]]) β default style of the message.module_style (
Optional
[Callable
[[str
],str
]]) β style of{module}
.module_name_style (
Optional
[Callable
[[str
],str
]]) β style of{module_name}
.module_file_style (
Optional
[Callable
[[str
],str
]]) β style of{module_file}
.module_version_style (
Optional
[Callable
[[str
],str
]]) β style of{module_version}
.package_name_style (
Optional
[Callable
[[str
],str
]]) β style of{package_name}
.package_version_style (
Optional
[Callable
[[str
],str
]]) β style of{package_version}
.exec_name_style (
Optional
[Callable
[[str
],str
]]) β style of{exec_name}
.version_style (
Optional
[Callable
[[str
],str
]]) β style of{version}
.prog_name_style (
Optional
[Callable
[[str
],str
]]) β style of{prog_name}
.env_info_style (
Optional
[Callable
[[str
],str
]]) β style of{env_info}
.
- 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 name, the frame itself, and the frame chain for debugging.
- Return type:
- colored_template(template=None)[source]ΒΆ
Insert ANSI styles to a message template.
Accepts a custom
template
as parameter, otherwise uses the default message defined on the Option instance.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:
- property env_info: dict[str, str]ΒΆ
Various environment info.
Returns the data produced by boltons.ecoutils.get_profile().
- property exec_name: strΒΆ
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).
- message: str = '{prog_name}, version {version}'ΒΆ
Default message template used to render the version string.
- property module: ModuleTypeΒΆ
Returns the module in which the CLI resides.
- print_and_exit(ctx, param, value)[source]ΒΆ
Print the version string and exits.
Also stores all version string elements in the Contextβs
meta
dict.- Return type:
- print_debug_message()[source]ΒΆ
Render in debug logs all template fields in color. :rtype:
None
Todo
Pretty print JSON output (easier to read in bug reports)?
- render_message(template=None)[source]ΒΆ
Render the version string from the provided template.
Accepts a custom
template
as parameter, otherwise uses the defaultself.colored_template()
produced by the instance.- Return type:
- template_fields: tuple[str, ...] = ('module', 'module_name', 'module_file', 'module_version', 'package_name', 'package_version', 'exec_name', 'version', 'prog_name', 'env_info')ΒΆ
List of field IDs recognized by the message template.
- property version: str | NoneΒΆ
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().
- class click_extra.File(mode='r', encoding=None, errors='strict', lazy=None, atomic=False)[source]ΒΆ
Bases:
ParamType
Declares a parameter to be a file for reading or writing. The file is automatically closed once the context tears down (after the command finished working).
Files can be opened for reading or writing. The special value
-
indicates stdin or stdout depending on the mode.By default, the file is opened for reading text data, but it can also be opened in binary mode or for writing. The encoding parameter can be used to force a specific encoding.
The lazy flag controls if the file should be opened immediately or upon first IO. The default is to be non-lazy for standard input and output streams as well as files opened for reading, lazy otherwise. When opening a file lazily for reading, it is still opened temporarily for validation, but will not be held open until first IO. lazy is mainly useful when opening for writing to avoid creating the file until it is needed.
Files can also be opened atomically in which case all writes go into a separate file in the same folder and upon completion the file will be moved over to the original location. This is useful if a file regularly read by other users is modified.
See File Arguments for more information.
Changed in version 2.0: Added the
atomic
parameter.- convert(value, param, ctx)[source]ΒΆ
Convert the value to the correct type. This is not called if the value is
None
(the missing value).This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.
The
param
andctx
arguments may beNone
in 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]
-
envvar_list_splitter:
ClassVar
[str
] = ':'ΒΆ if a list of this type is expected and the value is pulled from a string environment variable, this is what splits it up. None means any whitespace. For all parameters the general rule is that whitespace splits them up. The exception are paths and files which are split by
os.path.pathsep
by default (β:β on Unix and β;β on Windows).
- shell_complete(ctx, param, incomplete)[source]ΒΆ
Return a special completion marker that tells the completion system to use the shell to provide file path completions.
- Parameters:
ctx (Context) β Invocation context for this command.
param (Parameter) β The parameter that is requesting completion.
incomplete (str) β Value being completed. May be empty.
- Return type:
list[CompletionItem]
Added in version 8.0.
- click_extra.file_path(*, path_type=<class 'pathlib.Path'>, exists=False, readable=True, writable=False, executable=False, resolve_path=False, allow_dash=False)[source]ΒΆ
Shortcut for
click.Path
withdir_okay=False, path_type=pathlib.Path
.- Return type:
- exception click_extra.FileError(filename, hint=None)[source]ΒΆ
Bases:
ClickException
Raised 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
,FloatParamType
Restrict a
click.FLOAT
value to a range of accepted values. See Range Options.If
min
ormax
are not passed, any value is accepted in that direction. Ifmin_open
ormax_open
are enabled, the corresponding boundary is not included in the range.If
clamp
is enabled, a value outside the range is clamped to the boundary instead of failing. This is not supported if either boundary is markedopen
.Changed in version 8.0: Added the
min_open
andmax_open
parameters.
- 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 withstdout
when 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=1
or-X utf8
. Python opens stdout and stderr witherrors="surrogateescape"
.
- 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]ΒΆ
Equivalent to
click.get_current_context()
but casts the returnedclick.Context
object tocloup.Context
(which is safe when using cloup commands classes and decorators).
- 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.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.
- class click_extra.Group(*args, show_subcommand_aliases=None, commands=None, **kwargs)[source]ΒΆ
Bases:
SectionMixin
,Command
,Group
A
click.Group
that 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] = None
whether 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_aliases
parameter/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
- add_command(cmd, name=None, section=None, fallback_to_default_section=True)[source]ΒΆ
Add a subcommand to this
Group
.Implementation note:
fallback_to_default_section
looks not very clean but, even if itβs not immediate to see (it wasnβt for me), I chose it over apparently cleaner options.- Parameters:
cmd (
Command
)section (
Optional
[Section
]) β aSection
instance. The command must not be in the section already.fallback_to_default_section (
bool
) β ifsection
is None and this option is enabled, the command is added to the βdefault sectionβ. If disabled, the command is not added to any section unlesssection
is provided. This is useful for internal code and subclasses. Donβt disable it unless you know what you are doing.
- Return type:
- command(name=None, *, aliases=None, cls=None, section=None, **kwargs)[source]ΒΆ
Return a decorator that creates a new subcommand of this
Group
using 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
name
are now keyword-only.
- 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:
- group(name=None, *, cls=None, aliases=None, section=None, **kwargs)[source]ΒΆ
Return a decorator that creates a new subcommand of this
Group
using 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
name
are now keyword-only.
- 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.
- 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
.
- show_subcommand_aliasesΒΆ
Whether to show subcommand aliases.
- alias2name: Dict[str, str]ΒΆ
Dictionary mapping each alias to a command name.
- click_extra.group(*args, **kwargs)ΒΆ
Returns a new decorator instantiated with custom defaults.
These defaults values are merged with the userβs own arguments.
A special case is made for the
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- click_extra.help_option(*args, **kwargs)ΒΆ
Returns a new decorator instantiated with custom defaults.
These defaults values are merged with the userβs own arguments.
A special case is made for the
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- class click_extra.HelpExtraFormatter(*args, **kwargs)[source]ΒΆ
Bases:
HelpFormatter
Extends Cloupβs custom HelpFormatter to highlights options, choices, metavars and default values.
This is being discussed for upstream integration at:
Forces theme to our default.
Also transform Cloupβs standard
HelpTheme
to our ownHelpExtraTheme
.- colorize(match)[source]ΒΆ
Colorize all groups with IDs in the provided matching result.
All groups without IDs are left as-is.
All groups are processed in the order they appear in the
match
object. Then all groups are concatenated to form the final string that is returned. :rtype:str
Caution
Implementation is a bit funky here because there is no way to iterate over both unnamed and named groups, in the order they appear in the regex, while keeping track of the group ID.
So we have to iterate over the list of matching strings and pick up the corresponding group ID along the way, from the
match.groupdict()
dictionary. This also means we assume that thematch.groupdict()
is returning an ordered dictionary. Which is supposed to be true as of Python 3.7.
- colorize_group(str_to_style, group_id)[source]ΒΆ
Colorize a string according to the style of the group ID.
- Return type:
- get_style_id(group_id)[source]ΒΆ
Get the style ID to apply to a group.
Return the style which has the same ID as the group, unless it is defined in the
style_aliases
mapping above.- Return type:
- getvalue()[source]ΒΆ
Wrap original Click.HelpFormatter.getvalue() to force extra-colorization on rendering.
- Return type:
- highlight_extra_keywords(help_text)[source]ΒΆ
Highlight extra keywords in help screens based on the theme.
It is based on regular expressions. While this is not a bullet-proof method, it is good enough. After all, help screens are not consumed by machine but are designed for humans. :rtype:
str
Danger
All the regular expressions below are designed to match its original string into a sequence of contiguous groups.
This means each part of the matching result must be encapsulated in a group. And subgroups are not allowed (unless their are explicitly set as non-matching with
(?:...)
prefix).Groups with a name must have a corresponding style.
- style_aliases = {'bracket_1': 'bracket', 'bracket_2': 'bracket', 'default_label': 'bracket', 'envvar_label': 'bracket', 'label_sep_1': 'bracket', 'label_sep_2': 'bracket', 'label_sep_3': 'bracket', 'long_option': 'option', 'range': 'bracket', 'required_label': 'bracket', 'short_option': 'option'}ΒΆ
Map regexβs group IDs to styles.
Most of the time, the style name is the same as the group ID. But some regular expression implementations requires us to work around group IDs limitations, like
bracket_1
andbracket_2
. In which case we use this mapping to apply back the canonical style to that regex-specific group ID.
-
theme:
HelpExtraTheme
ΒΆ
- 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>, deprecated=<function identity>, search=<function identity>, success=<function identity>, subheading=<function identity>)[source]ΒΆ
Bases:
HelpTheme
Extends
cloup.HelpTheme
withlogging.levels
and extra properties.- static light()[source]ΒΆ
A theme assuming a light terminal background color. :rtype:
HelpExtraTheme
Todo
Tweak colors to make them more readable.
- 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:
HelpFormatter
A custom help formatter. Features include:
more attributes for controlling the output of the formatter
a
col1_width
parameter 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_dl
is computed excluding the rows that exceedcol1_max_width
(calledcol_max
inwrite_dl
for compatibility with Click).
Changed in version 0.9.0: the
row_sep
parameter now:is set to
None
by 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
SepGenerator
andRowSepPolicy
.
Added in version 0.8.0.
- Parameters:
indent_increment (
int
) β width of each indentation increment.width (
Optional
[int
]) β content line width, excluding the newline character; by default itβs initialized tomin(terminal_width - 1, max_width)
wheremax_width
is another argument.max_width (
Optional
[int
]) β maximum content line width (equivalent toContext.max_content_width
). Used to computewidth
when 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 (
Union
[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
) β anHelpTheme
instance 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_settings
dictionary 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_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_increment
if thatβs greater than 3).- Parameters:
rows (
Sequence
[Tuple
[str
,Union
[str
,Callable
[[int
],str
]]]]) β a list of two item tuples for the terms and values.col_max (
Optional
[int
]) β 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 (
Optional
[int
]) β 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 (
Optional
[int
]) β 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_linear_dl(dl)[source]ΒΆ
Format a definition list as a βlinear listβ. This is the default when the available width for the definitions (2nd column) is below
self.col2_min_width
.- 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.HelpSection(heading, definitions, help=None, constraint=None)[source]ΒΆ
Bases:
object
A 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:
object
A 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
Style
class, which is a wrapper of theclick.style
function.- 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 (
Optional
[Callable
[[str
],str
]]) β Style of separator and eventual parenthesis/brackets in subcommand alias lists. If not provided, thealias
style will be used.
- class click_extra.IntRange(min=None, max=None, min_open=False, max_open=False, clamp=False)[source]ΒΆ
Bases:
_NumberRangeBase
,IntParamType
Restrict an
click.INT
value to a range of accepted values. See Range Options.If
min
ormax
are not passed, any value is accepted in that direction. Ifmin_open
ormax_open
are enabled, the corresponding boundary is not included in the range.If
clamp
is enabled, a value outside the range is clamped to the boundary instead of failing.Changed in version 8.0: Added the
min_open
andmax_open
parameters.
- click_extra.launch(url, wait=False, locate=False)[source]ΒΆ
This function launches the given URL (or filename) in the default viewer application for this file type. If this is an executable, it might launch the executable in a new session. The return value is the exit code of the launched application. Usually,
0
indicates success.Examples:
click.launch('https://click.palletsprojects.com/') click.launch('/my/downloaded/file', locate=True)
Added in version 2.0.
- Parameters:
url (
str
) β URL or filename of the thing to launch.wait (
bool
) β Wait for the program to exit before returning. This only works if the launched program blocks. In particular,xdg-open
on Linux does not block.locate (
bool
) β if this is set to True then instead of launching the application associated with the URL it will attempt to launch a file manager with the file located. This might have weird effects if the URL does not point to the filesystem.
- Return type:
- 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]]
- exception click_extra.MissingParameter(message=None, ctx=None, param=None, param_hint=None, param_type=None)[source]ΒΆ
Bases:
BadParameter
Raised if click required an option or argument but it was not provided when invoking the script.
Added in version 4.0.
- Parameters:
param_type (str | None) β a string that indicates the type of the parameter. The default is to inherit the parameter type from the given param. Valid values are
'parameter'
,'option'
or'argument'
.
- 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 logger
registered under thename
parameter, or creates a new one with that name if it doesnβt exist,Set the loggerβs
propagate
attribute toFalse
,Force removal of any existing handlers and formatters attached to the logger,
Attach a new
ExtraStreamHandler
withExtraFormatter
,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βsroot
logger 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βspropagate
attribute. 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:
- exception click_extra.NoSuchOption(option_name, message=None, possibilities=None, ctx=None)[source]ΒΆ
Bases:
UsageError
Raised if click attempted to handle an option that does not exist.
Added in version 4.0.
- 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 theFile
param type.If
'-'
is given to openstdout
orstdin
, the stream is wrapped so that using it in a context manager will not close it. This makes it possible to use the function without accidentally closing a standard stream:with open_file(filename) as f: ...
- Parameters:
filename (
str
|PathLike
[str
]) β The name or Path of the file to open, or'-'
forstdin
/stdout
.mode (
str
) β The mode in which to open the file.encoding (
str
|None
) β The encoding to decode or encode a file opened in text mode.lazy (
bool
) β Wait to open the file until it is accessed. For read mode, the file is temporarily opened to raise access errors early, then closed until it is read again.atomic (
bool
) β Write to a temporary file and replace the given file on close.
- Return type:
Added in version 3.0.
- class click_extra.Option(*args, group=None, **attrs)[source]ΒΆ
Bases:
Option
A
click.Option
with an extra fieldgroup
of typeOptionGroup
.
- click_extra.option(*param_decls, cls=None, group=None, **attrs)[source]ΒΆ
Attach an
Option
to the command. Refer toclick.Option
andclick.Parameter
for more info about the accepted parameters.In your IDE, you wonβt see arguments relating to shell completion, because they are different in Click 7 and 8 (both supported by Cloup):
in Click 7, itβs
autocompletion
in Click 8, itβs
shell_complete
.
These arguments have different semantics, refer to Clickβs docs.
- click_extra.option_group(title, *args, **kwargs)[source]ΒΆ
Return a decorator that annotates a function with an option group.
The
help
argument is an optional description and can be provided either as keyword argument or as 2nd positional argument after thename
of the group:# help as keyword argument @option_group(name, *options, help=None, ...) # help as 2nd positional argument @option_group(name, help, *options, ...)
Changed in version 0.9.0: in order to support the decorator
cloup.constrained_params()
,@option_group
now allows each input decorators to add multiple options.- Parameters:
title (
str
) β title of the help section describing the option group.help β an optional description shown below the name; can be provided as keyword argument or 2nd positional argument.
options β an arbitrary number of decorators like
click.option
, which attach one or multiple options to the decorated command function.constraint β an optional instance of
Constraint
(see Constraints for more info); a description of the constraint will be shown between squared brackets aside the option group title (or below it if too long).hidden β if
True
, the option group and all its options are hidden from the help page (all contained options will have theirhidden
attribute set toTrue
).
- Return type:
Callable
[[TypeVar
(F
, bound=Callable
[...
,Any
])],TypeVar
(F
, bound=Callable
[...
,Any
])]
- class click_extra.OptionGroup(title, help=None, constraint=None, hidden=False)[source]ΒΆ
Bases:
object
Contains the information of an option group and identifies it. Note that, as far as the clients of this library are concerned, an
OptionGroups
acts as a βmarkerβ for options, not as a container for related options. When you call@optgroup.option(...)
you are not adding an option to a container, you are just adding an option marked with this option group.Added in version 0.8.0: The
hidden
parameter.
- class click_extra.OptionGroupMixin(*args, align_option_groups=None, **kwargs)[source]ΒΆ
Bases:
object
Implements support for:
option groups
the βPositional argumentsβ help section; this section is shown only if at least one of your arguments has non-empty
help
.
Important
In order to check the constraints defined on the option groups, a command must inherits from
cloup.ConstraintMixin
too!Added in version 0.14.0: added the βPositional argumentsβ help section.
Changed in version 0.8.0: this mixin now relies on
cloup.HelpFormatter
to align help sections. If aclick.HelpFormatter
is used with aTypeError
is raised.Changed in version 0.8.0: removed
format_option_group
. Addedget_default_option_group
andmake_option_group_help_section
.Added in version 0.5.0.
- Parameters:
align_option_groups (
Optional
[bool
]) β 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
- get_default_option_group(ctx, is_the_only_visible_option_group=False)[source]ΒΆ
Return an
OptionGroup
instance for the options not explicitly assigned to an option group, eventually including the--help
option. :rtype:OptionGroup
Added in version 0.8.0.
- get_ungrouped_options(ctx)[source]ΒΆ
Return options not explicitly assigned to an option group (eventually including the
--help
option), i.e. options that will be part of the βdefault option groupβ.
- make_option_group_help_section(group, ctx)[source]ΒΆ
Return a
HelpSection
for anOptionGroup
, i.e. an object containing the title, the optional description and the optionsβ definitions for this option group. :rtype:HelpSection
Added in version 0.8.0.
- must_align_option_groups(ctx, default=True)[source]ΒΆ
Return
True
if the help sections of all options groups should have their columns aligned. :rtype:bool
Added in version 0.8.0.
- option_groupsΒΆ
List of all option groups, except the βdefault option groupβ.
- ungrouped_optionsΒΆ
List of options not explicitly assigned to an user-defined option group. These options will be included in the βdefault option groupβ. Note: this list does not include options added automatically by Click based on context settings, like the
--help
option; use theget_ungrouped_options()
method if you need the real full list (which needs aContext
object).
- class click_extra.Parameter(param_decls=None, type=None, required=False, default=None, callback=None, nargs=None, multiple=False, metavar=None, expose_value=True, is_eager=False, envvar=None, shell_complete=None, deprecated=False)[source]ΒΆ
Bases:
object
A parameter to a command comes in two versions: they are either
Option
s orArgument
s. 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
ParamType
or a Python type. The latter is converted into the former automatically if supported.required (bool) β controls if this is optional or not.
default (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
1
the 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) β a string or list of strings that are environment variables that should be checked.
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, incomplete
and must return a list ofCompletionItem
or a list of strings.deprecated (bool | str) β If
True
or non-empty string, issues a message indicating that the argument is deprecated and highlights its deprecation in βhelp. The message can be customized by using a string as the value. A deprecated parameter cannot be required, a ValueError will be raised otherwise.
Changed in version 8.2.0: Introduction of
deprecated
.Changed in version 8.2: Adding duplicate parameter names to a
Command
will result in aUserWarning
being shown.Changed in version 8.2: Adding duplicate parameter names to a
Command
will result in aUserWarning
being shown.Changed in version 8.0:
process_value
validates required parameters and boundednargs
, and invokes the parameter callback before returning the value. This allows the callback to validate prompts.full_process_value
is removed.Changed in version 8.0:
autocompletion
is renamed toshell_complete
and has new semantics described above. The old name is deprecated and will be removed in 8.1, until then it will be wrapped to match the new requirements.Changed in version 8.0: For
multiple=True, nargs>1
, the default must be a list of tuples.Changed in version 8.0: Setting a default is no longer required for
nargs>1
, it will default toNone
.multiple=True
ornargs=-1
will default to()
.Changed in version 7.1: Empty environment variables are ignored rather than taking the empty string value. This makes it possible for scripts to clear variables if they canβt unset them.
Changed in version 2.0: Changed signature for parameter callback to also be passed the parameter. The old callback format will still work, but it will raise a warning to give you a chance to migrate the code easier.
- get_default(ctx, call=True)[source]ΒΆ
Get the default for the parameter. Tries
Context.lookup_default()
first, then the local default.- Parameters:
- Return type:
Changed in version 8.0.2: Type casting is no longer performed when getting a default.
Changed in version 8.0.1: Type casting can fail in resilient parsing mode. Invalid defaults will not prevent showing help text.
Changed in version 8.0: Looks at
ctx.default_map
first.Changed in version 8.0: Added the
call
parameter.
- 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:
- 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.
- param_type_name = 'parameter'ΒΆ
- shell_complete(ctx, incomplete)[source]ΒΆ
Return a list of completions for the incomplete value. If a
shell_complete
function was given during init, it is used. Otherwise, thetype
shell_complete()
function is used.- Parameters:
ctx (Context) β Invocation context for this command.
incomplete (str) β Value being completed. May be empty.
- Return type:
list[CompletionItem]
Added in version 8.0.
- 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. :rtype:dict
[str
,Any
]Added in version 8.0.
- class click_extra.ParameterSource(*values)[source]ΒΆ
Bases:
Enum
This is an
Enum
that indicates the source of a parameterβs value.Use
click.Context.get_parameter_source()
to get the source for a parameter by name.Changed in version 8.0: Use
Enum
and drop thevalidate
method.Changed in version 8.0: Added the
PROMPT
value.- COMMANDLINE = 1ΒΆ
The value was provided by the command line args.
- ENVIRONMENT = 2ΒΆ
The value was provided with an environment variable.
- DEFAULT = 3ΒΆ
Used the default specified by the parameter.
- DEFAULT_MAP = 4ΒΆ
Used a default provided by
Context.default_map
.
- PROMPT = 5ΒΆ
Used a prompt to confirm a default or provide a value.
- class click_extra.ParamStructure(*args, excluded_params=None, **kwargs)[source]ΒΆ
Bases:
object
Utilities to introspect CLI options and commands structure.
Structures are represented by a tree-like
dict
.Access to a node is available using a serialized path string composed of the keys to descend to that node, separated by a dot
.
.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.
If
excluded_params
is not provided, let the dynamic and cachedself.excluded_params
property to compute the default value on first use.-
DEFAULT_EXCLUDED_PARAMS:
Iterable
[str
] = ('config', 'help', 'show_params', 'version')ΒΆ List of root parameters to exclude from configuration by default:
-C
/--config
option, 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-params
flag, which is like--help
and stops the CLI execution.--version
, which is not a configurable option per-se.
-
TYPE_MAP:
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.
- build_param_trees()[source]ΒΆ
Build all parameters tree structure in one go and cache them.
This removes parameters whose fully-qualified IDs are in the
excluded_params
blocklist.- Return type:
- property excluded_params: Iterable[str]ΒΆ
List of parameter IDs to exclude from the parameter structure.
Elements of this list are expected to be the fully-qualified ID of the parameter, i.e. the dot-separated ID that is prefixed by the CLI name.
Caution
It is only called once to produce the list of default parameters to exclude, if the user did not provided its own list to the constructor.
It was not implemented in the constructor but made as a property, to allow for a just-in-time call to the current context. Without this trick we could not have fetched the CLI name.
- flatten_tree_dict(tree_dict, parent_key=None)[source]ΒΆ
Recursively traverse the tree-like
dict
and produce a flatdict
whose keys are path and values are the leafβs content.
- get_param_type(param)[source]ΒΆ
Get the Python type of a Click parameter.
See the list of custom types provided by Click.
- static get_tree_value(tree_dict, *path)[source]ΒΆ
Get in the
tree_dict
the value located at thepath
.
- static init_tree_dict(*path, leaf=None)[source]ΒΆ
Utility method to recursively create a nested dict structure whose keys are provided by
path
list and at the end is populated by a copy ofleaf
.- Return type:
- property params_objects: dict[str, Any]ΒΆ
Returns a tree-like dictionary whose keys shadows the CLI options and subcommands and values are parameter objects.
Perfect to parse configuration files and user-provided parameters.
- property params_template: dict[str, Any]ΒΆ
Returns a tree-like dictionary whose keys shadows the CLI options and subcommands and values are
None
.Perfect to serve as a template for configuration files.
- property params_types: dict[str, Any]ΒΆ
Returns a tree-like dictionary whose keys shadows the CLI options and subcommands and values are their expected Python type.
Perfect to parse configuration files and user-provided parameters.
-
DEFAULT_EXCLUDED_PARAMS:
- class click_extra.ParamType[source]ΒΆ
Bases:
object
Represents the type of a parameter. Validates and converts values from the command line or Python into the correct type.
To implement a custom type, subclass and implement at least the following:
The
name
class attribute must be set.Calling an instance of the type with
None
must 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
ctx
andparam
arguments areNone
. This can occur when converting prompt input.
- convert(value, param, ctx)[source]ΒΆ
Convert the value to the correct type. This is not called if the value is
None
(the missing value).This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.
The
param
andctx
arguments may beNone
in 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
-
envvar_list_splitter:
ClassVar
[str
|None
] = NoneΒΆ if a list of this type is expected and the value is pulled from a string environment variable, this is what splits it up. None means any whitespace. For all parameters the general rule is that whitespace splits them up. The exception are paths and files which are split by
os.path.pathsep
by default (β:β on Unix and β;β on Windows).
- fail(message, param=None, ctx=None)[source]ΒΆ
Helper method to fail with an invalid value message.
- Return type:
t.NoReturn
- 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. :rtype: str | None
Added in version 2.0.
- shell_complete(ctx, param, incomplete)[source]ΒΆ
Return a list of
CompletionItem
objects for the incomplete value. Most types do not provide completions, but some do, and this allows custom types to provide custom completions as well.- Parameters:
ctx (Context) β Invocation context for this command.
param (Parameter) β The parameter that is requesting completion.
incomplete (str) β Value being completed. May be empty.
- Return type:
list[CompletionItem]
Added in version 8.0.
- 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.
- 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
--password
option which prompts for a password, hiding input and asking to enter the value again for confirmation.
- class click_extra.Path(exists=False, file_okay=True, dir_okay=True, writable=False, readable=True, resolve_path=False, allow_dash=False, path_type=None, executable=False)[source]ΒΆ
Bases:
ParamType
The
Path
type is similar to theFile
type, but returns the filename instead of an open file. Various checks can be enabled to validate the type of file and permissions.- Parameters:
exists (
bool
) β The file or directory needs to exist for the value to be valid. If this is not set 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
executable
parameter.Changed in version 8.0: Allow passing
path_type=pathlib.Path
.Changed in version 6.0: Added the
allow_dash
parameter.- convert(value, param, ctx)[source]ΒΆ
Convert the value to the correct type. This is not called if the value is
None
(the missing value).This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.
The
param
andctx
arguments may beNone
in 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]
-
envvar_list_splitter:
ClassVar
[str
] = ':'ΒΆ if a list of this type is expected and the value is pulled from a string environment variable, this is what splits it up. None means any whitespace. For all parameters the general rule is that whitespace splits them up. The exception are paths and files which are split by
os.path.pathsep
by default (β:β on Unix and β;β on Windows).
- shell_complete(ctx, param, incomplete)[source]ΒΆ
Return a special completion marker that tells the completion system to use the shell to provide path completions for only directories or any paths.
- Parameters:
ctx (Context) β Invocation context for this command.
param (Parameter) β The parameter that is requesting completion.
incomplete (str) β Value being completed. May be empty.
- Return type:
list[CompletionItem]
Added in version 8.0.
- click_extra.path(*, path_type=<class 'pathlib.Path'>, exists=False, file_okay=True, dir_okay=True, readable=True, writable=False, executable=False, resolve_path=False, allow_dash=False)[source]ΒΆ
Shortcut for
click.Path
withpath_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.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]ΒΆ
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_item
at the new position. This is useful when used together withitem_show_func
to 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 toFalse
also 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
None
nothing 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
label
for the label,bar
for the progress bar andinfo
for 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.
- Return type:
ProgressBar[V]
Added in version 8.2: The
hidden
argument.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_func
shows 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_steps
parameter.Added in version 4.0: The
color
parameter andupdate
method.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
Abort
exception.- 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 ofTrue
to customize the message.type (
ParamType
|Any
|None
) β the type to use to check the value against.value_proc (
Optional
[Callable
[[str
],Any
]]) β 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
) β shows or hides the default value in the prompt.err (
bool
) β if set to true the file defaults tostderr
instead 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): β.
- Return type:
Added in version 8.0:
confirmation_prompt
can be a custom string.Added in version 7.0: Added the
show_choices
parameter.Added in version 6.0: Added unicode support for cmd.exe on Windows.
Added in version 4.0: Added the err parameter.
- click_extra.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 providedklass
is 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,bytes
are passed directly toecho()
without applying style. If you want to style bytes that represent text, callbytes.decode()
first. :rtype:None
Changed in version 8.0: A non-string
message
is converted to a string. Bytes are passed through without style applied.Added in version 2.0.
- class click_extra.Section(title, commands=(), is_sorted=False)[source]ΒΆ
Bases:
object
A group of (sub)commands to show in the same help section of a
MultiCommand
. You can use sections with any Command that inherits fromSectionMixin
.Changed in version 0.6.0: removed the deprecated old name
GroupSection
.Changed in version 0.5.0: introduced the new name
Section
and deprecated the oldGroupSection
.- Parameters:
- class click_extra.SectionMixin(*args, commands=None, sections=(), align_sections=None, **kwargs)[source]ΒΆ
Bases:
object
Adds to a
click.MultiCommand
the possibility of organizing its subcommands into multiple help sections.Sections can be specified in the following ways:
passing a list of
Section
objects to the constructor setting the argumentsections
using
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.HelpFormatter
to align help sections. If aclick.HelpFormatter
is used with aTypeError
is raised.Changed in version 0.8.0: removed
format_section
. Addedmake_commands_help_section
.Added in version 0.5.0.
- Parameters:
align_sections (
Optional
[bool
]) β 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_command(cmd, name=None, section=None, fallback_to_default_section=True)[source]ΒΆ
Add a subcommand to this
Group
.Implementation note:
fallback_to_default_section
looks not very clean but, even if itβs not immediate to see (it wasnβt for me), I chose it over apparently cleaner options.- Parameters:
cmd (
Command
)section (
Optional
[Section
]) β aSection
instance. The command must not be in the section already.fallback_to_default_section (
bool
) β ifsection
is None and this option is enabled, the command is added to the βdefault sectionβ. If disabled, the command is not added to any section unlesssection
is provided. This is useful for internal code and subclasses. Donβt disable it unless you know what you are doing.
- Return type:
- add_section(section)[source]ΒΆ
Add a
Section
to this group. You can add the same section object only a single time.- Return type:
- See Also:
- 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:
- list_sections(ctx, include_default_section=True)[source]ΒΆ
Return the list of all sections in the βcorrect orderβ.
If
include_default_section=True
and the default section is non-empty, it will be included at the end of the list.
- 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
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- class click_extra.ShowParamsOption(param_decls=None, is_flag=True, expose_value=False, is_eager=True, help='Show all CLI parameters, their provenance, defaults and value, then exit.', **kwargs)[source]ΒΆ
Bases:
ExtraOption
,ParamStructure
A pre-configured option adding a
--show-params
option.Between configuration files, default values and environment variables, it might be hard to guess under which set of parameters the CLI will be executed. This option print information about the parameters that will be fed to the CLI.
Allow a list of paramerers to be blocked from the parameter structure.
If
excluded_params
is not provided, let the dynamic and cachedself.excluded_params
property to compute the default value on first use.- TABLE_HEADERS = ('ID', 'Class', 'Spec.', '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. :rtype:
None
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
/ExtraGroup
classes, in which we are attaching aclick_extra.raw_args
metadata entry to the context.
- 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:
object
Wraps
click.style()
for a better integration withHelpTheme
.Available colors are defined as static constants in
Color
.Arguments are set to
None
by default. PassingFalse
to boolean args orColor.reset
as color causes a reset code to be inserted.With respect to
click.style()
, this class:has an argument less,
reset
, which is alwaysTrue
add the
text_transform
.
Warning
The arguments
overline
,italic
andstrikethrough
are only supported in Click 8 and will be ignored if you are using Click 7.- Parameters:
Added in version 0.8.0.
- click_extra.style(text, fg=None, bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, reset=True)[source]ΒΆ
Styles a text with ANSI styles and returns the new string. By default the styling is self contained which means that at the end of the string a reset code is issued. This can be prevented by passing
reset=False
.Examples:
click.echo(click.style('Hello World!', fg='green')) click.echo(click.style('ATTENTION!', blink=True)) click.echo(click.style('Some things', reverse=True, fg='cyan')) click.echo(click.style('More colors', fg=(255, 12, 128), bg=117))
Supported color names:
black
(might be a gray)red
green
yellow
(might be an orange)blue
magenta
cyan
white
(might be light gray)bright_black
bright_red
bright_green
bright_yellow
bright_blue
bright_magenta
bright_cyan
bright_white
reset
(reset the color code only)
If the terminal supports it, color may also be specified as:
An integer in the interval [0, 255]. The terminal must support 8-bit/256-color mode.
An RGB tuple of three integers in [0, 255]. The terminal must support 24-bit/true-color mode.
See https://en.wikipedia.org/wiki/ANSI_color and https://gist.github.com/XVilka/8346728 for more information.
- Parameters:
text (
Any
) β the string to style with ansi codes.fg (
int
|tuple
[int
,int
,int
] |str
|None
) β if provided this will become the foreground color.bg (
int
|tuple
[int
,int
,int
] |str
|None
) β if provided this will become the background color.bold (
bool
|None
) β if provided this will enable or disable bold mode.dim (
bool
|None
) β if provided this will enable or disable dim mode. This is badly supported.underline (
bool
|None
) β if provided this will enable or disable underline.overline (
bool
|None
) β if provided this will enable or disable overline.italic (
bool
|None
) β if provided this will enable or disable italic.blink (
bool
|None
) β if provided this will enable or disable blinking.reverse (
bool
|None
) β if provided this will enable or disable inverse rendering (foreground becomes background and the other way round).strikethrough (
bool
|None
) β if provided this will enable or disable striking through text.reset (
bool
) β by default a reset-all code is added at the end of the string which means that styles do not carry over. This can be disabled to compose styles.
- Return type:
Changed in version 8.0: A non-string
message
is converted to a string.Changed in version 8.0: Added support for 256 and RGB color codes.
Changed in version 8.0: Added the
strikethrough
,italic
, andoverline
parameters.Changed in version 7.0: Added support for bright colors.
Added in version 2.0.
- 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
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- class click_extra.TableFormatOption(param_decls=None, type=Choice(['asciidoc', 'csv', 'csv-excel', 'csv-excel-tab', 'csv-unix', 'double_grid', 'double_outline', 'fancy_grid', 'fancy_outline', 'github', 'grid', 'heavy_grid', 'heavy_outline', 'html', 'jira', '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', 'tsv', 'unsafehtml', 'vertical', 'youtrack']), default='rounded_outline', expose_value=False, help='Rendering style of tables.', **kwargs)[source]ΒΆ
Bases:
ExtraOption
A pre-configured option that is adding a
-t
/--table-format
flag to select the rendering style of a table.The selected table format ID is made available in the context in
ctx.meta["click_extra.table_format"]
.- init_formatter(ctx, param, value)[source]ΒΆ
Save table format ID in the context, and adds
print_table()
to it.The
print_table(tabular_data, headers)
method added to the context is a ready-to-use helper that takes for parameters: -tabular_data
, a 2-dimensional iterable of iterables for cell values, -headers
, a list of string to be used as headers.- Return type:
- 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
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- class click_extra.TelemetryOption(param_decls=None, default=False, expose_value=False, envvar=None, show_envvar=True, help='Collect telemetry and usage data.', **kwargs)[source]ΒΆ
Bases:
ExtraOption
A pre-configured
--telemetry
/--no-telemetry
option flag.Respects the proposed DO_NOT_TRACK environment variable as a unified standard to opt-out of telemetry for TUI/console apps.
The
DO_NOT_TRACK
convention takes precedence over the user-defined environment variables and the auto-generated values.See also
- 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
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- class click_extra.TimerOption(param_decls=None, default=False, expose_value=False, is_eager=True, help='Measure and print elapsed execution time.', **kwargs)[source]ΒΆ
Bases:
ExtraOption
A pre-configured option that is adding a
--time
/--no-time
flag to print elapsed time at the end of CLI execution.The start time is made available in the context in
ctx.meta["click_extra.start_time"]
.
- class click_extra.Tuple(types)[source]ΒΆ
Bases:
CompositeParamType
The default behavior of Click is to apply a type on a value directly. This works well in most cases, except for when nargs is set to a fixed count and different types should be used for different items. In this case the
Tuple
type can be used. This type can only be used if nargs is set to a fixed number.For more information see Tuples as Multi Value Options.
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.
- property arity: intΒΆ
int([x]) -> integer int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by β+β or β-β and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(β0b100β, base=0) 4
- convert(value, param, ctx)[source]ΒΆ
Convert the value to the correct type. This is not called if the value is
None
(the missing value).This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.
The
param
andctx
arguments may beNone
in 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
- 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.
- exception click_extra.UsageError(message, ctx=None)[source]ΒΆ
Bases:
ClickException
An internal exception that signals a usage error. This typically aborts any further handling.
- Parameters:
message (str) β the error message to display.
ctx (Context | None) β optionally the context that caused this error. Click will fill in the context automatically in some situations.
- exit_code = 2ΒΆ
The exit code for this exception.
- 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
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- class click_extra.VerboseOption(param_decls=None, count=True, **kwargs)[source]ΒΆ
Bases:
ExtraVerbosity
--verbose
/-v`
option to increase the log level ofExtraVerbosity
by a number of steps.If
-v
is 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
:-v
will increase the level toINFO
,-vv
will increase the level toDEBUG
,any number of repetition above that point will be set to the maximum level, so for
-vvvvv
for example will be capped atDEBUG
.
Set up a verbosity-altering option.
- Parameters:
default_logger β If a
logging.Logger
object 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 globalroot
logger.
- 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
VerbosityOption
defined on the current command. If none is found, itβs because the--verbose
option is used standalone. In which case we defaults toDEFAULT_LEVEL_NAME
.- 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.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
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- class click_extra.VerbosityOption(param_decls=None, default_logger='root', default='WARNING', metavar='LEVEL', type=Choice(['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG']), help='Either CRITICAL, ERROR, WARNING, INFO, DEBUG.', **kwargs)[source]ΒΆ
Bases:
ExtraVerbosity
--verbosity
option to set the the log level ofExtraVerbosity
.Set up a verbosity-altering option.
- Parameters:
default_logger (
Logger
|str
) β If alogging.Logger
object 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 globalroot
logger.
- click_extra.version_option(version=None, *param_decls, package_name=None, prog_name=None, message=None, **kwargs)[source]ΒΆ
Add a
--version
option which immediately prints the version number and exits the program.If
version
is not provided, Click will try to detect it usingimportlib.metadata.version()
to get the version for thepackage_name
.If
package_name
is not provided, Click will try to detect it by inspecting the stack frames. This will be used to detect the version, so it must match the name of the installed package.- Parameters:
version (
str
|None
) β The version number to show. If not provided, Click will try to detect it.param_decls (
str
) β One or more option names. Defaults to the single value"--version"
.package_name (
str
|None
) β The package name to detect the version from. If not provided, Click will try to detect it.prog_name (
str
|None
) β The name of the CLI to show in the message. If not provided, it will be detected from the command.message (
str
|None
) β The message to show. The values%(prog)s
,%(package)s
, and%(version)s
are available. Defaults to"%(prog)s, version %(version)s"
.
- Raises:
RuntimeError β
version
could not be detected.- Return type:
Callable
[[TypeVar
(FC
, bound= _AnyCallable | Command)],TypeVar
(FC
, bound= _AnyCallable | Command)]
Changed in version 8.0: Add the
package_name
parameter, and the%(package)s
value for messages.Changed in version 8.0: Use
importlib.metadata
instead ofpkg_resources
. The version is detected based on the package name, not the entry point name. The Python package name must match the installed package name, or be passed withpackage_name=
.
- click_extra.wrap_text(text, width=78, initial_indent='', subsequent_indent='', preserve_paragraphs=False)[source]ΒΆ
A helper function that intelligently wraps text. By default, it assumes that it operates on a single paragraph of text but if the preserve_paragraphs parameter is provided it will intelligently handle paragraphs (defined by two empty lines).
If paragraphs are handled, a paragraph can be prefixed with an empty line containing the
\b
character (\x08
) to indicate that no rewrapping should happen in that block.- Parameters:
text (
str
) β the text that should be rewrapped.width (
int
) β the maximum width for the text.initial_indent (
str
) β the initial indent that should be placed on the first line as a string.subsequent_indent (
str
) β the indent string that should be placed on each consecutive line.preserve_paragraphs (
bool
) β if this flag is set then the wrapping will intelligently handle paragraphs.
- Return type:
SubmodulesΒΆ
click_extra.colorize moduleΒΆ
Helpers and utilities to apply ANSI coloring to terminal content.
- class click_extra.colorize.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>, deprecated=<function identity>, search=<function identity>, success=<function identity>, subheading=<function identity>)[source]ΒΆ
Bases:
HelpTheme
Extends
cloup.HelpTheme
withlogging.levels
and extra properties.- subheading()ΒΆ
Non-canonical Click Extra properties. :rtype:
TypeVar
(T
)Note
Subheading is used for sub-sections, like in the help of mail-deduplicate.
Todo
Maybe this shouldnβt be in Click Extra because it is a legacy inheritance from one of my other project.
- 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:
- static light()[source]ΒΆ
A theme assuming a light terminal background color. :rtype:
HelpExtraTheme
Todo
Tweak colors to make them more readable.
- click_extra.colorize.default_theme: HelpExtraTheme = HelpExtraTheme(invoked_command=Style(fg='bright_white', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), command_help=<function identity>, heading=Style(fg='bright_blue', bg=None, bold=True, dim=None, underline=True, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), constraint=Style(fg='magenta', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), section_help=<function identity>, col1=<function identity>, col2=<function identity>, alias=Style(fg='cyan', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), alias_secondary=Style(fg='cyan', bg=None, bold=None, dim=True, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), epilog=<function identity>, critical=Style(fg='red', bg=None, bold=True, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), error=Style(fg='red', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs={'fg': 'red', 'bg': None, 'bold': None, 'dim': None, 'underline': None, 'overline': None, 'italic': None, 'blink': None, 'reverse': None, 'strikethrough': None}), warning=Style(fg='yellow', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), info=<function identity>, debug=Style(fg='blue', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), option=Style(fg='cyan', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), subcommand=Style(fg='cyan', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), choice=Style(fg='magenta', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), metavar=Style(fg='cyan', bg=None, bold=None, dim=True, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), bracket=Style(fg=None, bg=None, bold=None, dim=True, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), envvar=Style(fg='yellow', bg=None, bold=None, dim=True, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), default=Style(fg='green', bg=None, bold=None, dim=True, underline=None, overline=None, italic=True, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), deprecated=Style(fg='bright_yellow', bg=None, bold=True, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), search=Style(fg='green', bg=None, bold=True, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), success=Style(fg='green', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs={'fg': 'green', 'bg': None, 'bold': None, 'dim': None, 'underline': None, 'overline': None, 'italic': None, 'blink': None, 'reverse': None, 'strikethrough': None}), subheading=Style(fg='blue', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None))ΒΆ
Default color theme for Click Extra.
- click_extra.colorize.nocolor_theme: HelpExtraTheme = 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>, deprecated=<function identity>, search=<function identity>, success=<function identity>, subheading=<function identity>)ΒΆ
Color theme for Click Extra to force no colors.
- click_extra.colorize.KO = '\x1b[31mβ\x1b[0m'ΒΆ
Pre-rendered UI-elements.
- click_extra.colorize.color_env_vars = {'CLICOLOR': True, 'CLICOLORS': True, 'CLICOLORS_FORCE': True, 'CLICOLOR_FORCE': True, 'COLOR': True, 'COLORS': True, 'FORCE_COLOR': True, 'FORCE_COLORS': True, '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
--color
option flag when encountered.
- 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:
ExtraOption
A pre-configured option that is adding a
--color
/--no-color
(aliased by--ansi
/--no-ansi
) option 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?
- class click_extra.colorize.ExtraHelpColorsMixin[source]ΒΆ
Bases:
object
Adds 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.
- click_extra.colorize.escape_for_help_screen(text)[source]ΒΆ
Prepares a string to be used in a regular expression for matches in help screen.
Applies re.escape, then accounts for long strings being wrapped on multiple lines and padded with spaces to fit the columnar layout.
- Return type:
It allows for: - additional number of optional blank characters (line-returns, spaces, tabs, β¦)
after a dash, as the help renderer is free to wrap strings after a dash.
a space to be replaced by any number of blank characters.
- class click_extra.colorize.HelpExtraFormatter(*args, **kwargs)[source]ΒΆ
Bases:
HelpFormatter
Extends Cloupβs custom HelpFormatter to highlights options, choices, metavars and default values.
This is being discussed for upstream integration at:
Forces theme to our default.
Also transform Cloupβs standard
HelpTheme
to our ownHelpExtraTheme
.-
theme:
HelpExtraTheme
ΒΆ
- style_aliases = {'bracket_1': 'bracket', 'bracket_2': 'bracket', 'default_label': 'bracket', 'envvar_label': 'bracket', 'label_sep_1': 'bracket', 'label_sep_2': 'bracket', 'label_sep_3': 'bracket', 'long_option': 'option', 'range': 'bracket', 'required_label': 'bracket', 'short_option': 'option'}ΒΆ
Map regexβs group IDs to styles.
Most of the time, the style name is the same as the group ID. But some regular expression implementations requires us to work around group IDs limitations, like
bracket_1
andbracket_2
. In which case we use this mapping to apply back the canonical style to that regex-specific group ID.
- get_style_id(group_id)[source]ΒΆ
Get the style ID to apply to a group.
Return the style which has the same ID as the group, unless it is defined in the
style_aliases
mapping above.- Return type:
- colorize_group(str_to_style, group_id)[source]ΒΆ
Colorize a string according to the style of the group ID.
- Return type:
- colorize(match)[source]ΒΆ
Colorize all groups with IDs in the provided matching result.
All groups without IDs are left as-is.
All groups are processed in the order they appear in the
match
object. Then all groups are concatenated to form the final string that is returned. :rtype:str
Caution
Implementation is a bit funky here because there is no way to iterate over both unnamed and named groups, in the order they appear in the regex, while keeping track of the group ID.
So we have to iterate over the list of matching strings and pick up the corresponding group ID along the way, from the
match.groupdict()
dictionary. This also means we assume that thematch.groupdict()
is returning an ordered dictionary. Which is supposed to be true as of Python 3.7.
- highlight_extra_keywords(help_text)[source]ΒΆ
Highlight extra keywords in help screens based on the theme.
It is based on regular expressions. While this is not a bullet-proof method, it is good enough. After all, help screens are not consumed by machine but are designed for humans. :rtype:
str
Danger
All the regular expressions below are designed to match its original string into a sequence of contiguous groups.
This means each part of the matching result must be encapsulated in a group. And subgroups are not allowed (unless their are explicitly set as non-matching with
(?:...)
prefix).Groups with a name must have a corresponding style.
-
theme:
- click_extra.colorize.highlight(content, substrings, styling_method, ignore_case=False)[source]ΒΆ
Highlights parts of the
string
that matchessubstrings
.Takes care of overlapping parts within the
string
.- Return type:
- ..todo:
Same as the
ignore_case
parameter, should we support case-folding? As in βStraΓeβ => βStrasseβ? Beware, it messes with string length and characters indexβ¦
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.patched_exit(self, code=0)[source]ΒΆ
Exits the application with a given exit code.
Forces the context to close before exiting, so callbacks attached to parameters will be called to clean up their state. This is not important in normal CLI execution as the Python process will just be destroyed. But it will lead to leaky states in unitttests. :rtype:
NoReturn
See also
This fix has been proposed upstream to Click.
- class click_extra.commands.ExtraContext(*args, meta=None, **kwargs)[source]ΒΆ
Bases:
Context
Like
cloup._context.Context
, but with the ability to populate the contextβsmeta
property at instantiation.Also inherits
color
property from parent context. And sets it to True for parentless contexts at instantiatiom, so we can always have colorized output.Todo
Propose addition of
meta
keyword upstream to Click.Like parentβs context but with an extra
meta
keyword-argument.Also force
color
property default to True if not provided by user and this context has no parent.- formatter_classΒΆ
Use our own formatter to colorize the help screen.
alias of
HelpExtraFormatter
- click_extra.commands.default_extra_params()[source]ΒΆ
Default additional options added to
extra_command
andextra_group
. :rtype:list
[Option
]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-time
Hint
--time
is placed at the top of all other eager options so all other optionsβ processing time can be measured.
-C
,--config CONFIG_PATH
Hint
--config
is at the top so it can have a direct influence on the default behavior and value of the other options.
--color
,--ansi
/--no-color
,--no-ansi
--show-params
--verbosity LEVEL
-v
,--verbose
--version
-h
,--help
Attention
This is the option produced by the @click.decorators.help_option decorator.
It is not explicitly referenced in the implementation of this function.
Thatβs because itβs going to be added by Click itself, at the end of the list of options. By letting Click handle this, we ensure that the help option will take into account the help_option_names setting.
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=None, extra_option_at_end=True, populate_auto_envvars=True, **kwargs)[source]ΒΆ
Bases:
ExtraHelpColorsMixin
,Command
Like
cloup.command
, with sane defaults and extra help screen colorization.List of extra parameters:
- Parameters:
version (
str
|None
) β allows a version string to be set directly on the command. Will be passed to the first instance ofExtraVersionOption
parameter attached to the command.extra_option_at_end (
bool
) βreorders all parameters attached to the command, by moving all instances of
ExtraOption
at the end of the parameter list. The original order of the options is preserved among themselves.populate_auto_envvars (
bool
) βforces all parameters to have their auto-generated environment variables registered. This address the shortcoming of
click
which 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
True
orFalse
, 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 whoseprompt
property is set.Defaults to
None
, which will leave all options untouched, and let them decide of their ownshow_choices
setting.show_envvar = None
(Click Extra feature)If set to
True
orFalse
, 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_envvar
setting. The rationale being that discoverability of environment variables is enabled by the--show-params
option, which is active by default on extra commands. So there is no need to surcharge the help screen.This addresses the click#2313 issue.
To override these defaults, you can pass your own settings with the
context_settings
parameter:@extra_command( context_settings={ "show_default": False, ... } )
- context_classΒΆ
alias of
ExtraContext
- main(*args, **kwargs)[source]ΒΆ
Pre-invocation step that is instantiating the context, then call
invoke()
within it.During context instantiation, each optionβs callbacks are called. Beware that these might break the execution flow (like
--help
or--version
).
- make_context(info_name, args, parent=None, **extra)[source]ΒΆ
Intercept the call to the original
click.core.Command.make_context
so we can keep a copy of the raw, pre-parsed arguments provided to the CLI.The result are passed to our own
ExtraContext
constructor which is able to initialize the contextβsmeta
property under our ownclick_extra.raw_args
entry. This will be used inShowParamsOption.print_params()
to print the table of parameters fed to the CLI. :rtype:Any
See also
This workaround is being discussed upstream in click#1279.
- class click_extra.commands.ExtraGroup(*args, version=None, extra_option_at_end=True, populate_auto_envvars=True, **kwargs)[source]ΒΆ
Bases:
ExtraCommand
,Group
Like``cloup.Group``, with sane defaults and extra help screen colorization.
List of extra parameters:
- Parameters:
version (
str
|None
) β allows a version string to be set directly on the command. Will be passed to the first instance ofExtraVersionOption
parameter attached to the command.extra_option_at_end (
bool
) βreorders all parameters attached to the command, by moving all instances of
ExtraOption
at the end of the parameter list. The original order of the options is preserved among themselves.populate_auto_envvars (
bool
) βforces all parameters to have their auto-generated environment variables registered. This address the shortcoming of
click
which 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
True
orFalse
, 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 whoseprompt
property is set.Defaults to
None
, which will leave all options untouched, and let them decide of their ownshow_choices
setting.show_envvar = None
(Click Extra feature)If set to
True
orFalse
, 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_envvar
setting. The rationale being that discoverability of environment variables is enabled by the--show-params
option, which is active by default on extra commands. So there is no need to surcharge the help screen.This addresses the click#2313 issue.
To override these defaults, you can pass your own settings with the
context_settings
parameter:@extra_command( context_settings={ "show_default": False, ... } )
- command_classΒΆ
Makes commands of an
ExtraGroup
be instances ofExtraCommand
.That way all subcommands created from an
ExtraGroup
benefits 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
ExtraGroup
produce sub-groups that are also ofExtraGroup
type.See: https://click.palletsprojects.com/en/stable/api/#click.Group.group_class
alias of
type
click_extra.config moduleΒΆ
Utilities to load parameters and options from a configuration file.
- class click_extra.config.Formats(*values)[source]ΒΆ
Bases:
Enum
Supported configuration formats and the list of their default extensions.
The default order set the priority by which each format is searched for the default configuration file.
- TOML = ('toml',)ΒΆ
- YAML = ('yaml', 'yml')ΒΆ
- JSON = ('json',)ΒΆ
- INI = ('ini',)ΒΆ
- XML = ('xml',)ΒΆ
- class click_extra.config.ConfigOption(param_decls=None, metavar='CONFIG_PATH', type=STRING, help='Location of the configuration file. Supports glob pattern of local path and remote URL.', is_eager=True, expose_value=False, formats=(Formats.TOML, Formats.YAML, Formats.JSON, Formats.INI, Formats.XML), roaming=True, force_posix=False, excluded_params=None, strict=False, **kwargs)[source]ΒΆ
Bases:
ExtraOption
,ParamStructure
A pre-configured option adding
--config
/-C
option.Takes as input a glob pattern or an URL.
Glob patterns must follow the syntax of wcmatch.glob.
is_eager
is active by default so the config optionβscallback
gets the opportunity to set thedefault_map
values before the other options use them.formats
is the ordered list of formats that the configuration file will be tried to be read with. Can be a single one.roaming
andforce_posix
are fed to click.get_app_dir() to setup the default configuration folder.excluded_params
is a list of options to ignore by the configuration parser. Defaults toParamStructure.DEFAULT_EXCLUDED_PARAMS
.strict
If
True
, raise an error if the configuration file contain unrecognized content.If
False
, silently ignore unsupported configuration option.
- formats: Sequence[Formats]ΒΆ
- roaming: boolΒΆ
- force_posix: boolΒΆ
- strict: boolΒΆ
- default_pattern()[source]ΒΆ
Returns the default pattern used to search for the configuration file.
Defaults to
/<app_dir>/*.{toml,yaml,yml,json,ini,xml}
. Where<app_dir>
is produced by the clickget_app_dir() method. The result depends on OS and is influenced by theroaming
andforce_posix
properties of this instance.In that folder, weβre looking for any file matching the extensions derived from the
self.formats
property: :rtype:str
a simple
*.ext
pattern if only one format is setan expanded
*.{ext1,ext2,...}
pattern if multiple formats are set
- get_help_record(ctx)[source]ΒΆ
Replaces the default value by the pretty version of the configuration matching pattern.
- search_and_read_conf(pattern)[source]ΒΆ
Search on local file system or remote URL files matching the provided pattern.
pattern
is considered an URL only if it is parseable as such and starts withhttp://
orhttps://
.Returns an iterator of the normalized configuration location and its textual content, for each file/URL matching the pattern.
- parse_conf(conf_text)[source]ΒΆ
Try to parse the provided content with each format in the order provided by the user.
A successful parsing in any format is supposed to return a
dict
. Any other result, including any raised exception, is considered a failure and the next format is tried.
- read_and_parse_conf(pattern)[source]ΒΆ
Search for a configuration file matching the provided pattern.
Returns the location and parsed content of the first valid configuration file that is not blank, or (None, None) if no file was found.
- default: t.Any | t.Callable[[], t.Any]ΒΆ
- type: types.ParamTypeΒΆ
- is_flag: boolΒΆ
- is_bool_flag: boolΒΆ
- flag_value: t.AnyΒΆ
- name: str | NoneΒΆ
- opts: list[str]ΒΆ
- secondary_opts: list[str]ΒΆ
- 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 ofINI
format 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
.- Return type:
- load_conf(ctx, param, path_pattern)[source]ΒΆ
Fetch parameters values from configuration file and sets 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. And direct CLI parameters, environment variables or interactive prompts takes precedence over any values from the config file.
- 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.
- click_extra.decorators.command(*args, **kwargs)ΒΆ
Returns a new decorator instantiated with custom defaults.
These defaults values are merged with the userβs own arguments.
A special case is made for the
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- click_extra.decorators.group(*args, **kwargs)ΒΆ
Returns a new decorator instantiated with custom defaults.
These defaults values are merged with the userβs own arguments.
A special case is made for the
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- click_extra.decorators.help_option(*args, **kwargs)ΒΆ
Returns a new decorator instantiated with custom defaults.
These defaults values are merged with the userβs own arguments.
A special case is made for the
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- click_extra.decorators.extra_command(*args, **kwargs)ΒΆ
Returns a new decorator instantiated with custom defaults.
These defaults values are merged with the userβs own arguments.
A special case is made for the
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- click_extra.decorators.extra_group(*args, **kwargs)ΒΆ
Returns a new decorator instantiated with custom defaults.
These defaults values are merged with the userβs own arguments.
A special case is made for the
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- click_extra.decorators.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
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- click_extra.decorators.color_option(*args, **kwargs)ΒΆ
Returns a new decorator instantiated with custom defaults.
These defaults values are merged with the userβs own arguments.
A special case is made for the
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- click_extra.decorators.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
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- click_extra.decorators.show_params_option(*args, **kwargs)ΒΆ
Returns a new decorator instantiated with custom defaults.
These defaults values are merged with the userβs own arguments.
A special case is made for the
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- click_extra.decorators.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
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- click_extra.decorators.telemetry_option(*args, **kwargs)ΒΆ
Returns a new decorator instantiated with custom defaults.
These defaults values are merged with the userβs own arguments.
A special case is made for the
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- click_extra.decorators.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
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- click_extra.decorators.verbose_option(*args, **kwargs)ΒΆ
Returns a new decorator instantiated with custom defaults.
These defaults values are merged with the userβs own arguments.
A special case is made for the
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
- click_extra.decorators.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
params
argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.This decorator can be used with or without arguments.
click_extra.docs_update moduleΒΆ
Automation to keep click-extra documentation up-to-date.
Tip
When the module is called directly, it will update all documentation files in-place:
$ run python -m click_extra.docs_update
See how it is used in .github/workflows/docs.yaml workflow.
- click_extra.docs_update.replace_content(filepath, new_content, start_tag, end_tag=None)[source]ΒΆ
Replace in a file the content surrounded by the provided start end end tags.
If no end tag is provided, the whole content found after the start tag will be replaced.
- Return type:
click_extra.envvar moduleΒΆ
Implements environment variable utilities.
- click_extra.envvar.TNestedEnvVarIDsΒΆ
Types environment variable names.
alias of
Iterable
[str
|None
|Iterable
[TNestedEnvVarIDs
]]
- click_extra.envvar.TEnvVarsΒΆ
Type for
dict
-like environment variables.
- click_extra.envvar.merge_envvar_ids(*envvar_ids)[source]ΒΆ
Merge and deduplicate environment variables.
Multiple parameters are accepted and can be single strings or arbitrary-nested iterables of strings.
None
values are ignored.Variable names are deduplicated while preserving their initial order. :rtype:
tuple
[str
,...
]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
envvar
parameter 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. :rtype:
str
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.
- 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()
. :rtype:tuple
[str
,...
]
- click_extra.envvar.env_copy(extend=None)[source]ΒΆ
Returns a copy of the current environment variables and eventually
extend
it.Mimics Pythonβs original implementation by returning
None
if noextend
content are provided.Environment variables are expected to be a
dict
ofstr:str
.
click_extra.logging moduleΒΆ
Logging utilities.
- click_extra.logging.LOG_LEVELS: dict[str, int] = {'CRITICAL': 50, 'DEBUG': 10, 'ERROR': 40, 'INFO': 20, 'WARNING': 30}ΒΆ
Mapping 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:
WARNING
, which is considered internalWARN
, whichis obsolete
FATAL
, which shouldnβt be used and has been replaced by CRITICAL
- click_extra.logging.DEFAULT_LEVEL: int = 30ΒΆ
WARNING
is the default level we expect any loggers to starts their lives at.WARNING
has 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
.
- click_extra.logging.DEFAULT_LEVEL_NAME: str = 'WARNING'ΒΆ
Name of the
DEFAULT_LEVEL
.
- class click_extra.logging.THandlerΒΆ
Custom types to be used in type hints below.
alias of TypeVar(βTHandlerβ, bound=
Handler
)
- class click_extra.logging.ExtraStreamHandler(stream=None)[source]ΒΆ
Bases:
StreamHandler
A 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:
Formatter
Click Extraβs default log formatter.
Initialize the formatter with specified format strings.
Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format.
Use a style parameter of β%β, β{β or β$β to specify that you want to use one of %-formatting,
str.format()
({}
) formatting orstring.Template
formatting in your format string.Changed in version 3.2: Added the
style
parameter.- formatMessage(record)[source]ΒΆ
Colorize the recordβs log level name before calling the standard formatter.
Colors are sourced from a
click_extra.colorize.HelpExtraTheme
. Default colors are configured onclick_extra.colorize.default_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
root
logger.This function is a wrapper around Python standard libraryβs
logging.basicConfig()
, but with additional parameters and tweaked defaults.It sets up the global
root
logger, and optionally adds a file or stream handler to it.Differences in default values:
Argument
extraBasicConfig()
defaultlogging.basicConfig()
defaultstyle
{
%
format
{levelname}: {message}
%(levelname)s:%(name)s:%(message)s
This function takes the same parameters as
logging.basicConfig()
, but require them to be all passed as explicit keywords arguments.- Parameters:
filename (
str
|None
) β Specifies that alogging.FileHandler
be 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 theroot
logger level to the specified level.stream (
Optional
[IO
[Any
]]) β Use the specified stream to initialize theExtraStreamHandler
. Note that this argument is incompatible with filename - if both are present, aValueError
is raised.handlers (
Iterable
[Handler
] |None
) β If specified, this should be an iterable of already created handlers to add to theroot
logger. Any handlers which donβt already have a formatter set will be assigned the default formatter created in this function. Note that this argument is incompatible with filename or stream - if both are present, aValueError
is raised.force (
bool
) β If this argument is specified asTrue
, any existing handlers attached to theroot
logger are removed and closed, before carrying out the configuration as specified by the other arguments.encoding (
str
|None
) β Name of the encoding used to decode or encode the file. To be specified along with filename, and passed tologging.FileHandler
for 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 ifNone
is 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
[TypeVar
(THandler
, bound=Handler
)]) β Alogging.Handler
class that will be used inlogging.basicConfig()
to create a default stream-based handler. Defaults toExtraStreamHandler
.file_handler_class (
type
[TypeVar
(THandler
, bound=Handler
)]) β Alogging.Handler
class that will be used inlogging.basicConfig()
to create a default file-based handler. Defaults toFileHandler
.formatter_class (
type
[TypeVar
(TFormatter
, bound=Formatter
)]) β Alogging.Formatter
class 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 logger
registered under thename
parameter, or creates a new one with that name if it doesnβt exist,Set the loggerβs
propagate
attribute toFalse
,Force removal of any existing handlers and formatters attached to the logger,
Attach a new
ExtraStreamHandler
withExtraFormatter
,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βsroot
logger 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βspropagate
attribute. 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:
ExtraOption
A base class implementing all the common halpers to manipulated loggerβs verbosity.
Sets the level of the provided logger. If no logger is provided, sets the level of the global
root
logger.Important
The internal
click_extra
logger 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.Logger
object 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 globalroot
logger.
- property all_loggers: Generator[Logger, None, None]ΒΆ
Returns the list of logger IDs affected by the verbosity option.
Will returns
click_extra
internal logger first, then the optionβslogger_name
.
- reset_loggers()[source]ΒΆ
Forces all loggers managed by the option to be reset to
DEFAULT_LEVEL
. :rtype:None
Important
Loggers are reset in reverse order to ensure the internal logger is changed last. That way the internal
click_extra
logger 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.
- set_level(ctx, param, value)[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.verbosity_level"]
. This context property 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='WARNING', metavar='LEVEL', type=Choice(['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG']), help='Either CRITICAL, ERROR, WARNING, INFO, DEBUG.', **kwargs)[source]ΒΆ
Bases:
ExtraVerbosity
--verbosity
option to set the the log level ofExtraVerbosity
.Set up a verbosity-altering option.
- Parameters:
default_logger (
Logger
|str
) β If alogging.Logger
object 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 globalroot
logger.
- class click_extra.logging.VerboseOption(param_decls=None, count=True, **kwargs)[source]ΒΆ
Bases:
ExtraVerbosity
--verbose
/-v`
option to increase the log level ofExtraVerbosity
by a number of steps.If
-v
is 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
:-v
will increase the level toINFO
,-vv
will increase the level toDEBUG
,any number of repetition above that point will be set to the maximum level, so for
-vvvvv
for example will be capped atDEBUG
.
Set up a verbosity-altering option.
- Parameters:
default_logger β If a
logging.Logger
object 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 globalroot
logger.
- 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
VerbosityOption
defined on the current command. If none is found, itβs because the--verbose
option is used standalone. In which case we defaults toDEFAULT_LEVEL_NAME
.- 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 providedklass
is found. Defaults toTrue
.
- Return type:
- class click_extra.parameters.ExtraOption(*args, group=None, **attrs)[source]ΒΆ
Bases:
Option
All new options implemented by
click-extra
inherits this class.Does nothing in particular for now but provides a way to identify Click Extraβs own options with certainty.
Also contains Option-specific code that should be contributed upstream to Click.
- static get_help_default(option, ctx)[source]ΒΆ
Produce the string to be displayed in the help as optionβs default. :rtype:
str
|None
Caution
This is a copy of Clickβs default value rendering of the default
This code should be keep in sync with Clickβs implementation.
Attention
This doesnβt work with our own
--config
option because we are also monkey-patching ConfigOption.get_help_record() to display the dynamic default value.So the results of this method call is:
<bound method ConfigOption.default_pattern of <ConfigOption config>>
instead of the expected:
~/(...)/multiple_envvars.py/*.{toml,yaml,yml,json,ini,xml}
Todo
A better solution has been proposed upstream to Click: - https://github.com/pallets/click/issues/2516 - https://github.com/pallets/click/pull/2517
- class click_extra.parameters.ParamStructure(*args, excluded_params=None, **kwargs)[source]ΒΆ
Bases:
object
Utilities to introspect CLI options and commands structure.
Structures are represented by a tree-like
dict
.Access to a node is available using a serialized path string composed of the keys to descend to that node, separated by a dot
.
.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.
If
excluded_params
is not provided, let the dynamic and cachedself.excluded_params
property to compute the default value on first use.-
DEFAULT_EXCLUDED_PARAMS:
Iterable
[str
] = ('config', 'help', 'show_params', 'version')ΒΆ List of root parameters to exclude from configuration by default:
-C
/--config
option, 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-params
flag, which is like--help
and stops the CLI execution.--version
, which is not a configurable option per-se.
- static init_tree_dict(*path, leaf=None)[source]ΒΆ
Utility method to recursively create a nested dict structure whose keys are provided by
path
list and at the end is populated by a copy ofleaf
.- Return type:
- static get_tree_value(tree_dict, *path)[source]ΒΆ
Get in the
tree_dict
the value located at thepath
.
- flatten_tree_dict(tree_dict, parent_key=None)[source]ΒΆ
Recursively traverse the tree-like
dict
and produce a flatdict
whose 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:
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.
- get_param_type(param)[source]ΒΆ
Get the Python type of a Click parameter.
See the list of custom types provided by Click.
- property excluded_params: Iterable[str]ΒΆ
List of parameter IDs to exclude from the parameter structure.
Elements of this list are expected to be the fully-qualified ID of the parameter, i.e. the dot-separated ID that is prefixed by the CLI name.
Caution
It is only called once to produce the list of default parameters to exclude, if the user did not provided its own list to the constructor.
It was not implemented in the constructor but made as a property, to allow for a just-in-time call to the current context. Without this trick we could not have fetched the CLI name.
- build_param_trees()[source]ΒΆ
Build all parameters tree structure in one go and cache them.
This removes parameters whose fully-qualified IDs are in the
excluded_params
blocklist.- Return type:
- property params_template: dict[str, Any]ΒΆ
Returns a tree-like dictionary whose keys shadows the CLI options and subcommands and values are
None
.Perfect to serve as a template for configuration files.
-
DEFAULT_EXCLUDED_PARAMS:
- 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
,ParamStructure
A pre-configured option adding a
--show-params
option.Between configuration files, default values and environment variables, it might be hard to guess under which set of parameters the CLI will be executed. This option print information about the parameters that will be fed to the CLI.
Allow a list of paramerers to be blocked from the parameter structure.
If
excluded_params
is not provided, let the dynamic and cachedself.excluded_params
property to compute the default value on first use.- default: t.Any | t.Callable[[], t.Any]ΒΆ
- type: types.ParamTypeΒΆ
- is_flag: boolΒΆ
- is_bool_flag: boolΒΆ
- flag_value: t.AnyΒΆ
- name: str | NoneΒΆ
- opts: list[str]ΒΆ
- secondary_opts: list[str]ΒΆ
- TABLE_HEADERS = ('ID', 'Class', 'Spec.', '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. :rtype:
None
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
/ExtraGroup
classes, in which we are attaching aclick_extra.raw_args
metadata entry to the context.
click_extra.pygments moduleΒΆ
Helpers and utilities to allow Pygments to parse and render ANSI codes.
- click_extra.pygments.DEFAULT_TOKEN_TYPE = ('Generic', 'Output')ΒΆ
Default Pygmentsβ token type to render with ANSI support.
We defaults to
Generic.Output
tokens, as this is the token type used by all REPL- like and terminal lexers.
- class click_extra.pygments.AnsiFilter(**options)[source]ΒΆ
Bases:
Filter
Custom filter transforming a particular kind of token (
Generic.Output
by defaults) into ANSI tokens.Initialize a
AnsiColorLexer
and configure thetoken_type
to be colorized.Todo
Allow multiple
token_type
to be configured for colorization (if traditions are changed on Pygmentsβ side).
- class click_extra.pygments.AnsiSessionLexer(name, bases, dct)[source]ΒΆ
Bases:
LexerMeta
Custom metaclass used as a class factory to derive an ANSI variant of default shell session lexers.
Setup class propertiesβ defaults for new ANSI-capable lexers.
Adds an
ANSI
prefix to the lexerβs name.- Replaces all
aliases
IDs from the parent lexer with variants prefixed with ansi-
.
- Replaces all
- class click_extra.pygments.AnsiLexerFiltersMixin(*args, **kwargs)[source]ΒΆ
Bases:
Lexer
Adds a
TokenMergeFilter
andAnsiOutputFilter
to the list of filters.The session lexers we inherits from are parsing the code block line by line so they can differentiate inputs and outputs. Each output line ends up encapsulated into a
Generic.Output
token. We apply theTokenMergeFilter
filter to reduce noise and have each contiguous output lines part of the same single token.Then we apply our custom
AnsiOutputFilter
to transform anyGeneric.Output
monoblocks into ANSI tokens.
- click_extra.pygments.collect_session_lexers()[source]ΒΆ
Retrieve all lexers producing shell-like sessions in Pygments.
This function contain a manually-maintained list of lexers, to which we dynamiccaly adds lexers inheriting from
ShellSessionBaseLexer
. :rtype:Iterator
[type
[Lexer
]]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 = {<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 lexer to their ANSI variant.
- class click_extra.pygments.AnsiHtmlFormatter(**kwargs)[source]ΒΆ
Bases:
ExtendedColorHtmlFormatterMixin
,HtmlFormatter
Extend standard Pygmentsβ
HtmlFormatter
.Adds support for ANSI 256 colors.
Intercept the
style
argument to augment it with ANSI colors support.Creates a new style instance that inherits from the one provided by the user, but updates its
styles
attribute to add ANSI colors support frompygments_ansi_color
.- name = 'ANSI HTML'ΒΆ
Full name for the formatter, in human-readable form.
- aliases = ['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()
.
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.skip_naked(*args, **kwargs) = MarkDecorator(mark=Mark(name='skip', args=(), kwargs={'reason': 'Naked decorator not supported yet.'}))ΒΆ
Mark to skip Cloup decorators without parenthesis.
- click_extra.pytest.command_decorators(no_commands=False, no_groups=False, no_click=False, no_cloup=False, no_redefined=False, no_extra=False, with_parenthesis=True, with_types=False)[source]ΒΆ
Returns collection of Pytest parameters to test all forms of click/cloup/click- extra command-like decorators.
click_extra.sphinx moduleΒΆ
Helpers and utilities for Sphinx rendering of CLI based on Click Extra.
Danger
This module is quite janky but does the job. Still, it would benefits from a total
clean rewrite. This would require a better understanding of Sphinx, Click and MyST
internals. And as a side effect will eliminate the dependency on
pallets_sphinx_themes
.
If youβre up to the task, you can try to refactor it. Iβll probably start by moving
the whole pallets_sphinx_themes.themes.click.domain
code here, merge it with
the local collection of monkey-patches below, then clean the whole code to make it
more readable and maintainable. And finally, address all the todo-list below.
Todo
Add support for plain MyST directives to remove the need of wrapping rST into an
{eval-rst}
block. Ideally, this would allow for the following simpler syntax in
MyST:
```{click-example}
from click_extra import echo, extra_command, option, style
@extra_command
@option("--name", prompt="Your name", help="The person to greet.")
def hello_world(name):
"Simple program that greets NAME."
echo(f"Hello, {style(name, fg='red')}!")
```
```{click-run}
invoke(hello_world, args=["--help"])
```
Todo
Fix the need to have both .. click:example::
and .. click:run::
directives
in the same {eval-rst}
block in MyST. This is required to have both directives
shares states and context.
See also
This is based on Palletsβ Sphinx Themes, released under a BSD-3-Clause license.
Compared to the latter, it: - Forces the rendering of CLI results into ANSI shell sessions, via the
.. code-block:: ansi-shell-session
directive.
- class click_extra.sphinx.EofEchoingStdin(input, output)[source]ΒΆ
Bases:
EchoingStdin
Like
click.testing.EchoingStdin
but adds a visible^D
in place of the EOT character ().
ExampleRunner.invoke()
addswhen
terminate_input=True
.
- click_extra.sphinx.patch_modules()[source]ΒΆ
Patch modules to work better with
ExampleRunner.invoke()
.subprocess.call` output is redirected to ``click.echo
so it shows up in the example output.
- class click_extra.sphinx.ExampleRunner[source]ΒΆ
Bases:
ExtraCliRunner
click.testing.CliRunner
with additional features.This class inherits from
click_extra.testing.ExtraCliRunner
to have full control of contextual color settings by the way of thecolor
parameter. It also produce unfiltered ANSI codes so that theDirective
sub-classes below can render colors in the HTML output.- force_color: bool = TrueΒΆ
Force color rendering in
invoke
calls.
- isolation(*args, **kwargs)[source]ΒΆ
A context manager that sets up the isolation for invoking of a command line tool. This sets up <stdin> with the given input data and os.environ with the overrides from the given dictionary. This also rebinds some internals in Click to be mocked (like the prompt functionality).
This is automatically done in the
invoke()
method.- Parameters:
input β the input stream to put into sys.stdin.
env β the environment overrides as dictionary.
color β whether the output should contain color codes. The application can still override this explicitly.
Added in version 8.2: An additional output stream is returned, which is a mix of <stdout> and <stderr> streams.
Changed in version 8.2: Always returns the <stderr> stream.
Changed in version 8.0: <stderr> is opened with
errors="backslashreplace"
instead of the default"strict"
.Changed in version 4.0: Added the
color
parameter.
- invoke(cli, args=None, prog_name=None, input=None, terminate_input=False, env=None, _output_lines=None, **extra)[source]ΒΆ
Like
CliRunner.invoke()
but displays what the user would enter in the terminal for env vars, command args, and prompts.- Parameters:
terminate_input β Whether to display β^Dβ after a list of input.
_output_lines β A list used internally to collect lines to be displayed.
- run_example(source)[source]ΒΆ
Run commands by executing the given code, returning the lines of input and output. The code should be a series of the following functions:
invoke()
: Invoke a command, adding env vars, input, and output to the output.println(text="")
: Add a line of text to the output.isolated_filesystem()
: A context manager that changes to a temporary directory while executing the block.
- click_extra.sphinx.get_example_runner(document)[source]ΒΆ
Get or create the
ExampleRunner
instance associated with a document.
- class click_extra.sphinx.DeclareExampleDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]ΒΆ
Bases:
Directive
Add the source contained in the directiveβs content to the documentβs
ExampleRunner
, to be run usingRunExampleDirective
.See
ExampleRunner.declare_example()
.- has_content = TrueΒΆ
May the directive have content?
- required_arguments = 0ΒΆ
Number of required directive arguments.
- optional_arguments = 0ΒΆ
Number of optional arguments after the required arguments.
- final_argument_whitespace = FalseΒΆ
May the final argument contain whitespace?
- class click_extra.sphinx.RunExampleDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]ΒΆ
Bases:
Directive
Run commands from
DeclareExampleDirective
and display the input and output.See
ExampleRunner.run_example()
.- has_content = TrueΒΆ
May the directive have content?
- required_arguments = 0ΒΆ
Number of required directive arguments.
- optional_arguments = 0ΒΆ
Number of optional arguments after the required arguments.
- final_argument_whitespace = FalseΒΆ
May the final argument contain whitespace?
- class click_extra.sphinx.ClickDomain(env)[source]ΒΆ
Bases:
Domain
Declares new directives: -
.. click:example::
-.. click:run::
- name = 'click'ΒΆ
domain name: should be short, but unique
- label = 'Click'ΒΆ
domain label: longer, more descriptive (used in messages)
- directives: dict[str, type[Directive]] = {'example': <class 'click_extra.sphinx.DeclareExampleDirective'>, 'run': <class 'click_extra.sphinx.RunExampleDirective'>}ΒΆ
directive name -> directive class
- click_extra.sphinx.delete_example_runner_state(app, doctree)[source]ΒΆ
Close and remove the
ExampleRunner
instance once the document has been read.
click_extra.tabulate moduleΒΆ
Collection of table rendering utilities.
- click_extra.tabulate.output_formats: list[str] = ['asciidoc', 'csv', 'csv-excel', 'csv-excel-tab', 'csv-unix', 'double_grid', 'double_outline', 'fancy_grid', 'fancy_outline', 'github', 'grid', 'heavy_grid', 'heavy_outline', 'html', 'jira', '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', 'tsv', 'unsafehtml', 'vertical', 'youtrack']ΒΆ
All output formats supported by click-extra.
- click_extra.tabulate.get_csv_dialect(format_id)[source]ΒΆ
Extract, validate and normalize CSV dialect ID from format.
- click_extra.tabulate.render_vertical(tabular_data, headers=(), **kwargs)[source]ΒΆ
Re-implements
cli-helpers
βs vertical table layout.See cli-helpers source for reference.
- Return type:
- click_extra.tabulate.render_table(tabular_data, headers=(), **kwargs)[source]ΒΆ
Render a table with tabulate and output it via echo.
- Return type:
- class click_extra.tabulate.TableFormatOption(param_decls=None, type=Choice(['asciidoc', 'csv', 'csv-excel', 'csv-excel-tab', 'csv-unix', 'double_grid', 'double_outline', 'fancy_grid', 'fancy_outline', 'github', 'grid', 'heavy_grid', 'heavy_outline', 'html', 'jira', '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', 'tsv', 'unsafehtml', 'vertical', 'youtrack']), default='rounded_outline', expose_value=False, help='Rendering style of tables.', **kwargs)[source]ΒΆ
Bases:
ExtraOption
A pre-configured option that is adding a
-t
/--table-format
flag to select the rendering style of a table.The selected table format ID is made available in the context in
ctx.meta["click_extra.table_format"]
.- init_formatter(ctx, param, value)[source]ΒΆ
Save table format ID in the context, and adds
print_table()
to it.The
print_table(tabular_data, headers)
method added to the context is a ready-to-use helper that takes for parameters: -tabular_data
, a 2-dimensional iterable of iterables for cell values, -headers
, a list of string to be used as headers.- Return type:
click_extra.telemetry moduleΒΆ
Telemetry utilities.
- class click_extra.telemetry.TelemetryOption(param_decls=None, default=False, expose_value=False, envvar=None, show_envvar=True, help='Collect telemetry and usage data.', **kwargs)[source]ΒΆ
Bases:
ExtraOption
A pre-configured
--telemetry
/--no-telemetry
option flag.Respects the proposed DO_NOT_TRACK environment variable as a unified standard to opt-out of telemetry for TUI/console apps.
The
DO_NOT_TRACK
convention takes precedence over the user-defined environment variables and the auto-generated values.See also
click_extra.testing moduleΒΆ
CLI testing and simulation of their execution.
- click_extra.testing.INDENT = ' 'ΒΆ
Constants for rendering of CLI execution.
- click_extra.testing.TNestedArgsΒΆ
Types for arbitrary nested CLI arguments.
Arguments can be
str
,pathlib.Path
objects orNone
values.alias of
Iterable
[str
|Path
|None
|Iterable
[TNestedArgs
]]
- click_extra.testing.args_cleanup(*args)[source]ΒΆ
Flatten recursive iterables, remove all
None
, and cast each element to strings.Helps serialize
pathlib.Path
and other objects.It also allows for nested iterables and
None
values 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.BytesIOCopy(copy_to)[source]ΒΆ
Bases:
BytesIO
Patch
io.BytesIO
to let the written stream be copied to another.Caution
This has been proposed upstream to Click project but has not been merged yet.
- class click_extra.testing.ExtraCliRunner(charset='utf-8', env=None, echo_stdin=False, catch_exceptions=True)[source]ΒΆ
Bases:
CliRunner
Augment
click.testing.CliRunner
with extra features and bug fixes.- env: cabc.Mapping[str, str | None]ΒΆ
- force_color: bool = FalseΒΆ
Global class attribute to override the
color
parameter ininvoke
.Note
This was initially developed to force the initialization of the runner during the setup of Sphinx new directives. This was the only way we found, as to patch some code we had to operate at the class level.
- invoke2(cli, args=None, input=None, env=None, catch_exceptions=True, color=False, **extra)[source]ΒΆ
Copy of
click.testing.CliRunner.invoke()
with extra<output>
stream. :rtype:Result
Caution
This is a hard-copy of the modified
invoke()
method from click#2523 PR which has not been merged upstream yet.Todo
Reduce the code duplication here by using clever monkeypatching?
- 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
color
property at the class-level viaforce_color
attribute.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
color
was 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.Path
objects andNone
values. The nested structure will be flattened andNone
values 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 (
Optional
[Mapping
[str
,str
|None
]]) β same asclick.testing.CliRunner.invoke()
.catch_exceptions (
bool
) β same asclick.testing.CliRunner.invoke()
.color (
Union
[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 asTrue
toclick.testing.CliRunner.isolation()
and an extracolor=True
parameter 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.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:
ExtraOption
A pre-configured option that is adding a
--time
/--no-time
flag to print elapsed time at the end of CLI execution.The start time is made available in the context in
ctx.meta["click_extra.start_time"]
.
click_extra.version moduleΒΆ
Gather CLI metadata and print them.
- 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, prog_name=None, env_info=None, message_style=None, module_style=None, module_name_style=Style(fg='bright_white', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), module_file_style=None, module_version_style=Style(fg='green', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), package_name_style=Style(fg='bright_white', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), package_version_style=Style(fg='green', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), exec_name_style=Style(fg='bright_white', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), version_style=Style(fg='green', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), prog_name_style=Style(fg='bright_white', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), env_info_style=Style(fg='bright_black', bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None, _style_kwargs=None), is_flag=True, expose_value=False, is_eager=True, help='Show the version and exit.', **kwargs)[source]ΒΆ
Bases:
ExtraOption
Gather 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
Extra
prefix.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
--version
option flag.- Parameters:
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}
.env_info (
dict
[str
,str
] |None
) β forces the value of{env_info}
.message_style (
Optional
[Callable
[[str
],str
]]) β default style of the message.module_style (
Optional
[Callable
[[str
],str
]]) β style of{module}
.module_name_style (
Optional
[Callable
[[str
],str
]]) β style of{module_name}
.module_file_style (
Optional
[Callable
[[str
],str
]]) β style of{module_file}
.module_version_style (
Optional
[Callable
[[str
],str
]]) β style of{module_version}
.package_name_style (
Optional
[Callable
[[str
],str
]]) β style of{package_name}
.package_version_style (
Optional
[Callable
[[str
],str
]]) β style of{package_version}
.exec_name_style (
Optional
[Callable
[[str
],str
]]) β style of{exec_name}
.version_style (
Optional
[Callable
[[str
],str
]]) β style of{version}
.prog_name_style (
Optional
[Callable
[[str
],str
]]) β style of{prog_name}
.env_info_style (
Optional
[Callable
[[str
],str
]]) β style of{env_info}
.
- template_fields: tuple[str, ...] = ('module', 'module_name', 'module_file', 'module_version', 'package_name', 'package_version', 'exec_name', 'version', '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 name, the frame itself, and the frame chain for debugging.
- Return type:
- property module: ModuleTypeΒΆ
Returns the module in which the CLI resides.
- property exec_name: strΒΆ
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ΒΆ
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().
- property env_info: dict[str, str]ΒΆ
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
template
as 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
template
as parameter, otherwise uses the defaultself.colored_template()
produced by the instance.- Return type:
- default: t.Any | t.Callable[[], t.Any]ΒΆ
- type: types.ParamTypeΒΆ
- is_flag: boolΒΆ
- is_bool_flag: boolΒΆ
- flag_value: t.AnyΒΆ
- name: str | NoneΒΆ
- opts: list[str]ΒΆ
- secondary_opts: list[str]ΒΆ