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.

get_help_record(ctx)[source]#
click_extra.argument(*param_decls, cls=None, **attrs)[source]#
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.

New 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.

New 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).

New in version 2.0.

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

  • param_hint (Optional[str]) – 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.

format_message()[source]#
Return type:

str

class click_extra.BaseCommand(name, context_settings=None)[source]#

Bases: object

The base command implements the minimal API contract of commands. Most code will never use this as it does not implement a lot of useful functionality but it can act as the direct subclass of alternative parsing methods that do not depend on the Click parser.

For instance, this can be used to bridge Click and other systems like argparse or docopt.

Because base commands do not implement a lot of the API that other parts of Click take for granted, they are not supported for all operations. For instance, they cannot be used with the decorators usually and they have no built-in callback system.

Changed in version 2.0: Added the context_settings parameter.

Parameters:
  • name (Optional[str]) – the name of the command to use unless a group overrides it.

  • context_settings (Optional[MutableMapping[str, Any]]) – an optional dictionary with defaults that are passed to the context object.

context_class#

alias of Context

allow_extra_args = False#

the default for the Context.allow_extra_args flag.

allow_interspersed_args = True#

the default for the Context.allow_interspersed_args flag.

ignore_unknown_options = False#

the default for the Context.ignore_unknown_options flag.

name#

the name the command thinks it has. Upon registering a command on a Group the group will default the command name with this information. You should instead use the Context's info_name attribute.

context_settings: MutableMapping[str, Any]#

an optional dictionary with defaults passed to the context.

to_info_dict(ctx)[source]#

Gather information that could be useful for a tool generating user-facing documentation. This traverses the entire structure below this command.

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

Parameters:

ctx (Context) – A Context representing this command.

Return type:

Dict[str, Any]

New in version 8.0.

get_usage(ctx)[source]#
Return type:

str

get_help(ctx)[source]#
Return type:

str

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

This function when given an info name and arguments will kick off the parsing and create a new Context. It does not invoke the actual command callback though.

To quickly customize the context class used without overriding this method, set the context_class attribute.

Parameters:
  • info_name (Optional[str]) – the info name for this invocation. Generally this is the most descriptive name for the script or command. For the toplevel script it’s usually the name of the script, for commands below it’s the name of the command.

  • args (List[str]) – the arguments to parse as list of strings.

  • parent (Optional[Context]) – the parent context if available.

  • extra (Any) – extra keyword arguments forwarded to the context constructor.

Return type:

Context

Changed in version 8.0: Added the context_class attribute.

parse_args(ctx, args)[source]#

Given a context and a list of arguments this creates the parser and parses the arguments, then modifies the context as necessary. This is automatically invoked by make_context().

Return type:

List[str]

invoke(ctx)[source]#

Given a context, this invokes the command. The default implementation is raising a not implemented error.

Return type:

Any

shell_complete(ctx, incomplete)[source]#

Return a list of completions for the incomplete value. Looks at the names of chained multi-commands.

Any command could be part of a chained multi-command, so sibling commands are valid at any point during command completion. Other command classes will return more completions.

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

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

Return type:

List[CompletionItem]

New in version 8.0.

main(args=None, prog_name=None, complete_var=None, standalone_mode=True, windows_expand_args=True, **extra)[source]#

This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted, SystemExit needs to be caught.

This method is also available by directly calling the instance of a Command.

Parameters:
  • args (Optional[Sequence[str]]) – the arguments that should be used for parsing. If not provided, sys.argv[1:] is used.

  • prog_name (Optional[str]) – the program name that should be used. By default the program name is constructed by taking the file name from sys.argv[0].

  • complete_var (Optional[str]) – the environment variable that controls the bash completion support. The default is "_<prog_name>_COMPLETE" with prog_name in uppercase.

  • standalone_mode (bool) – the default behavior is to invoke the script in standalone mode. Click will then handle exceptions and convert them into error messages and the function will never return but shut down the interpreter. If this is set to False they will be propagated to the caller and the return value of this function is the return value of invoke().

  • windows_expand_args (bool) – Expand glob patterns, user dir, and env vars in command line args on Windows.

  • extra (Any) – extra keyword arguments are forwarded to the context constructor. See Context for more information.

Return type:

Any

Changed in version 8.0.1: Added the windows_expand_args parameter to allow disabling command line arg expansion on Windows.

Changed in version 8.0: When taking arguments from sys.argv on Windows, glob patterns, user dir, and env vars are expanded.

Changed in version 3.0: Added the standalone_mode parameter.

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

Bases: ParamType

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

You should only pass a list or tuple of choices. Other iterables (like generators) may lead to surprising results.

The resulting value will always be one of the originally passed choices regardless of case_sensitive or any ctx.token_normalize_func being specified.

See choice-opts for an example.

Parameters:

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

name: str = 'choice'#

the descriptive name of this type

to_info_dict()[source]#

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

Use click.Context.to_info_dict() to traverse the entire CLI structure. :rtype: Dict[str, Any]

New in version 8.0.

get_metavar(param)[source]#

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

Return type:

str

get_missing_message(param)[source]#

Optionally might return extra information about a missing parameter. :rtype: str

New in version 2.0.

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

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

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

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

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

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

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

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

Return type:

Any

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]

New 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

New 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.

format_message()[source]#
Return type:

str

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

None

class click_extra.Color[source]#

Bases: FrozenSpace

Colors accepted by Style and click.style().

black = 'black'#
red = 'red'#
green = 'green'#
yellow = 'yellow'#
blue = 'blue'#
magenta = 'magenta'#
cyan = 'cyan'#
white = 'white'#
reset = 'reset'#
bright_black = 'bright_black'#
bright_red = 'bright_red'#
bright_green = 'bright_green'#
bright_yellow = 'bright_yellow'#
bright_blue = 'bright_blue'#
bright_magenta = 'bright_magenta'#
bright_cyan = 'bright_cyan'#
bright_white = 'bright_white'#
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.

static disable_colors(ctx, param, value)[source]#

Callback disabling all coloring utilities.

Re-inspect the environment for existence of colorization flags to re-interpret the provided value.

Return type:

None

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.

New 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 MRO

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

context_class#

alias of Context

aliases: List[str]#

HelpFormatter options that are merged with Context.formatter_settings (eventually overriding some values).

get_normalized_epilog()[source]#
Return type:

str

format_epilog(ctx, formatter)[source]#

Writes the epilog into the formatter if it exists.

Return type:

None

format_help_text(ctx, formatter)[source]#

Writes the help text to the formatter if it exists.

Return type:

None

format_aliases(ctx, formatter)[source]#
Return type:

None

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

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, **attrs)[source]#

Bases: MultiCommand

A command collection is a multi command that merges multiple multi commands together into one. This is a straightforward implementation that accepts a list of different multi commands as sources and provides all the commands for each of them.

See MultiCommand and Command for the description of name and attrs.

sources: List[MultiCommand]#

The list of registered multi commands.

add_source(multi_cmd)[source]#

Adds a new multi command to the chain dispatcher.

Return type:

None

get_command(ctx, cmd_name)[source]#

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

Return type:

Optional[Command]

list_commands(ctx)[source]#

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

Return type:

List[str]

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: ('toml', )>, <Formats.YAML: ('yaml', 'yml')>, <Formats.JSON: ('json', )>, <Formats.INI: ('ini', )>, <Formats.XML: ('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’s callback gets the opportunity to set the default_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 and force_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 to ParamStructure.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 the roaming and force_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 set

  • an 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.

Return type:

tuple[str, str] | None

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 with http:// or https://.

Returns an iterator of the normalized configuration location and its textual content, for each file/URL matching the pattern.

Return type:

Iterable[tuple[Path | URL, str]]

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.

Return type:

dict[str, Any] | None

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.

Return type:

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

load_ini_config(content)[source]#

Utility method to parse INI configuration file.

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

Returns a ready-to-use data structure.

Return type:

dict[str, Any]

recursive_update(a, b)[source]#

Like standard dict.update(), but recursive so sub-dict gets updated.

Ignore elements present in b but not in a.

Return type:

dict[str, Any]

merge_default_map(ctx, user_conf)[source]#

Save the user configuration into the context’s default_map.

Merge the user configuration into the pre-computed template structure, which 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:

None

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:

None

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 (Optional[bool]) – The default value to use when no input is given. If None, repeat until input is given.

  • abort (bool) – if this is set to True a negative answer aborts the exception by raising Abort.

  • prompt_suffix (str) – a suffix that should be added to the prompt.

  • show_default (bool) – shows or hides the default value in the prompt.

  • err (bool) – if set to true the file defaults to stderr instead of stdout, the same as with echo.

Return type:

bool

Changed in version 8.0: Repeat until input is given if default is None.

New in version 4.0: Added the err parameter.

click_extra.confirmation_option(*param_decls, **kwargs)[source]#

Add a --yes option which shows a prompt before continuing if not passed. If the prompt is declined, the program will exit.

Parameters:
  • param_decls (str) – One or more option names. Defaults to the single value "--yes".

  • kwargs (Any) – Extra arguments are passed to option().

Return type:

Callable[[TypeVar(FC, bound= Union[Callable[..., Any], Command])], TypeVar(FC, bound= Union[Callable[..., Any], Command])]

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.

New in version 0.9.0.

Parameters:
  • constr (Constraint) – an instance of Constraint

  • param_adders (Callable[[Callable[..., Any]], Callable[..., Any]]) – function decorators, each attaching a single parameter to the decorated function.

Return type:

Callable[[TypeVar(F, bound= Callable[..., Any])], TypeVar(F, bound= Callable[..., Any])]

click_extra.constraint(constr, params)[source]#

Register a constraint on a list of parameters specified by (destination) name (e.g. the default name of --input-file is input_file).

Return type:

Callable[[TypeVar(F, bound= Callable[..., Any])], TypeVar(F, bound= Callable[..., Any])]

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 MRO

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

optgroup_constraints#

Constraints applied to OptionGroup instances.

param_constraints: Tuple[BoundConstraint, ...]#

Constraints registered using @constraint (or equivalent method).

all_constraints#

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

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

List[str]

get_param_by_name(name)[source]#
Return type:

Parameter

get_params_by_name(names)[source]#
Return type:

Sequence[Parameter]

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

None

must_show_constraints(ctx)[source]#
Return type:

bool

class click_extra.Context(*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.

New in version 0.9.0: added the check_constraints_consistency parameter.

New in version 0.8.0.

Parameters:
  • ctx_args (Any) – arguments forwarded to click.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 of Command (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 of Group (but you probably shouldn’t: be consistent).

  • show_subcommand_aliases (Optional[bool]) – whether to show the aliases of subcommands in the help of a cloup.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 (see cloup.Constraint.check_consistency()).

  • formatter_settings (Dict[str, Any]) – keyword arguments forwarded to HelpFormatter in make_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 method HelpFormatter.settings() to create this dictionary, so that you can be guided by your IDE.

  • ctx_kwargs (Any) – keyword arguments forwarded to click.Context.

formatter_class#

alias of HelpFormatter

formatter_settings#

Keyword arguments for the HelpFormatter. Obtained by merging the options of the parent context with the one passed to this context. Before creating the help formatter, these options are merged with the (eventual) options provided to the command (having higher priority).

get_formatter_settings()[source]#
Return type:

Dict[str, Any]

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.

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’s show_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 of Command (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 of Group (but you probably shouldn’t: be consistent).

  • show_subcommand_aliases (Union[_Missing, bool]) – whether to show the aliases of subcommands in the help of a cloup.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 (see cloup.Constraint.check_consistency()).

  • formatter_settings (Union[_Missing, Dict[str, Any]]) – keyword arguments forwarded to HelpFormatter in make_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 method HelpFormatter.settings() to create this dictionary, so that you can be guided by your IDE.

Return type:

Dict[str, Any]

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

name: str = 'datetime'#

the descriptive name of this type

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]

New in version 8.0.

get_metavar(param)[source]#

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

Return type:

str

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

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

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

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

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

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

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

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

Return type:

Any

click_extra.dir_path(*, path_type=<class 'pathlib.Path'>, exists=False, writable=False, readable=True, resolve_path=False, allow_dash=False)[source]#

Shortcut for click.Path with file_okay=False, path_type=pathlib.Path.

Return type:

Path

click_extra.echo(message=None, file=None, nl=True, err=False, color=None)[source]#

Print a message and newline to stdout or a file. This should be used instead of print() because it provides better support for different data, files, and environments.

Compared to print(), this does the following:

  • Ensures that the output encoding is not misconfigured on Linux.

  • Supports Unicode in the Windows console.

  • Supports writing to binary outputs, and supports writing bytes to text outputs.

  • 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 (Optional[Any]) – The string or bytes to output. Other objects are converted to strings.

  • file (Optional[IO[Any]]) – The file to write to. Defaults to stdout.

  • err (bool) – Write to stderr instead of stdout.

  • nl (bool) – Print a newline after the message. Enabled by default.

  • color (Optional[bool]) – Force showing or hiding colors and other styles. By default Click will remove color if the output does not look like an interactive terminal.

Return type:

None

Changed in version 6.0: Support Unicode output on the Windows console. Click does not modify sys.stdout, so sys.stdout.write() and print() will still not support Unicode.

Changed in version 4.0: Added the color parameter.

New 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.

Parameters:
  • text_or_generator (Union[Iterable[str], Callable[[], Iterable[str]], str]) – the text to page, or alternatively, a generator emitting the text to page.

  • color (Optional[bool]) – controls if the pager supports ANSI colors or not. The default is autodetection.

Return type:

None

click_extra.edit(text=None, editor=None, env=None, require_save=True, extension='.txt', filename=None)[source]#

Edits the given text in the defined editor. If an editor is given (should be the full path to the executable but the regular operating system search path is used for finding the executable) it overrides the detected editor. Optionally, some environment variables can be used. If the editor is closed without changes, None is returned. In case a file is edited directly the return value is always None and require_save and extension are ignored.

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:
  • text (Optional[AnyStr]) – the text to edit.

  • editor (Optional[str]) – optionally the editor to use. Defaults to automatic detection.

  • env (Optional[Mapping[str, str]]) – 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 (Optional[str]) – 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.

Return type:

Optional[AnyStr]

click_extra.extra_basic_config(logger_name=None, format='{levelname}: {message}', datefmt=None, style='{', level=None, handlers=None, force=True, handler_class=<class 'click_extra.logging.ExtraLogHandler'>, formatter_class=<class 'click_extra.logging.ExtraLogFormatter'>)[source]#

Setup and configure a logger.

Reimplements logging.basicConfig, but with sane defaults and more parameters.

Parameters:
  • logger_name (str | None) – ID of the logger to setup. If None, Python’s root logger will be used.

  • format (str | None) – Use the specified format string for the handler. Defaults to levelname and message separated by a colon.

  • datefmt (str | None) – Use the specified date/time format, as accepted by time.strftime().

  • style (Literal['%', '{', '$']) – If format is specified, use this style for the format string. One of %, { or $ for printf-style, str.format() or string.Template respectively. Defaults to {.

  • level (int | None) – Set the logger level to the specified level.

  • handlers (Iterable[Handler] | None) – A list of logging.Handler instances to attach to the logger. If not provided, a new handler of the class set by the handler_class parameter will be created. Any handler in the list which does not have a formatter assigned will be assigned the formatter created in this function.

  • force (bool) – Remove and close any existing handlers attached to the logger before carrying out the configuration as specified by the other arguments. Default to True so we always starts from a clean state each time we configure a logger. This is a life-saver in unittests in which loggers pollutes output.

  • handler_class (type[TypeVar(THandler, bound= Handler)]) – Handler class to be used to create a new handler if none provided. Defaults to ExtraLogHandler.

  • formatter_class (type[TypeVar(TFormatter, bound= Formatter)]) – Class of the formatter that will be setup on each handler if none found. Defaults to ExtraLogFormatter.

Return type:

Logger

Todo

Add more parameters for even greater configurability of the logger, by re-implementing those supported by logging.basicConfig.

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.

class click_extra.ExtraCliRunner(charset='utf-8', env=None, echo_stdin=False, mix_stderr=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 in invoke.

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.

isolation(input=None, env=None, color=False)[source]#

Copy of click.testing.CliRunner.isolation() with extra features. :rtype: Iterator[tuple[BytesIO, BytesIO, BytesIO]]

  • An additional output stream is returned, which is a mix of <stdout> and <stderr> streams if mix_stderr=True.

  • Always returns the <stderr> stream.

Caution

This is a hard-copy of the modified isolation() method from click#2523 PR which has not been merged upstream yet.

Todo

Reduce the code duplication here by using clever monkeypatching?

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: ExtraResult

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 via force_color attribute.

  • Adds a special case in the form of color="forced" parameter, which allows colored output to be kept, while forcing the initialization of Context.color = True. This is not allowed in current implementation of click.testing.CliRunner.invoke() because of colliding parameters.

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

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

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

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

  • *args –

    can be nested iterables composed of str, pathlib.Path objects and None values. The nested structure will be flattened and None values will be filtered out. Then all elements will be casted to str. See args_cleanup() for details.

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

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

  • catch_exceptions (bool) – same as click.testing.CliRunner.invoke().

  • color (Union[bool, Literal['forced'], None]) – If a boolean, the parameter will be passed as-is to click.testing.CliRunner.isolation(). If "forced", the parameter will be passed as True to click.testing.CliRunner.isolation() and an extra color=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:

Result

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 of ExtraVersionOption 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.

By default, these Click context settings are applied:

Additionally, these Cloup context settings are set:

Click Extra also adds its own context_settings:

  • show_choices = None (Click Extra feature)

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

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

  • show_envvar = None (Click Extra feature)

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

    Defaults to None, which will leave all options untouched, and let them decide of their own show_envvar setting. The rationale being that discoverability of environment variables is enabled by the --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.BaseCommand.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’s meta property under our own click_extra.raw_args entry. This will be used in ShowParamsOption.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.

invoke(ctx)[source]#

Main execution of the command, just after the context has been instantiated in main().

Return type:

Any

class click_extra.ExtraContext(*args, meta=None, **kwargs)[source]#

Bases: Context

Like cloup._context.Context, but with the ability to populate the context’s meta 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#

alias of HelpExtraFormatter

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.

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 of ExtraVersionOption 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.

By default, these Click context settings are applied:

Additionally, these Cloup context settings are set:

Click Extra also adds its own context_settings:

  • show_choices = None (Click Extra feature)

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

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

  • show_envvar = None (Click Extra feature)

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

    Defaults to None, which will leave all options untouched, and let them decide of their own show_envvar setting. The rationale being that discoverability of environment variables is enabled by the --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

group_class#

alias of type

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

Bases: Formatter

Initialize the formatter with specified format strings.

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

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

Changed in version 3.2: Added the style parameter.

formatMessage(record)[source]#

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

Return type:

str

class click_extra.ExtraLogHandler(level=0)[source]#

Bases: Handler

A handler to output logs to console’s <stderr>.

Initializes the instance - basically setting the formatter to None and the filter list to empty.

emit(record)[source]#

Use click.echo to print to <stderr> and supports colors.

Return type:

None

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.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:
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:

FrameType

property module: module#

Returns the module in which the CLI resides.

property module_name: str#

Returns the full module name or ``__main__`.

property module_file: str | None#

Returns the module’s file full path.

property module_version: str | None#

Returns the string found in the local __version__ variable.

property package_name: str | None#

Returns the package name.

property package_version: str | None#

Returns the package version if installed.

Will raise an error if the package is not installed, or if the package version cannot be determined from the package metadata.

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 prog_name: str | None#

Return the name of the CLI, from Click’s point of view.

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:

str

render_message(template=None)[source]#

Render the version string from the provided template.

Accepts a custom template as parameter, otherwise uses the default self.colored_template() produced by the instance.

Return type:

str

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)?

print_and_exit(ctx, param, value)[source]#

Print the version string and exits.

Also stores all version string elements in the Context’s meta dict.

Return type:

None

class click_extra.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.

Starting with Click 2.0, 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-args for more information.

name: str = 'filename'#

the descriptive name of this type

envvar_list_splitter: ClassVar[str] = ':'#

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

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]

New in version 8.0.

resolve_lazy_flag(value)[source]#
Return type:

bool

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

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

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

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

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

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

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

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

Return type:

IO[Any]

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

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

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

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

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

Return type:

List[CompletionItem]

New in version 8.0.

click_extra.file_path(*, path_type=<class 'pathlib.Path'>, exists=False, writable=False, readable=True, resolve_path=False, allow_dash=False)[source]#

Shortcut for click.Path with dir_okay=False, path_type=pathlib.Path.

Return type:

Path

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

Bases: ClickException

Raised if a file cannot be opened.

format_message()[source]#
Return type:

str

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

Bases: _NumberRangeBase, FloatParamType

Restrict a click.FLOAT value to a range of accepted values. See ranges.

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

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

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

name: str = 'float range'#

the descriptive name of this type

click_extra.format_filename(filename, shorten=False)[source]#

Format a filename as a string for display. Ensures the filename can be displayed by replacing any invalid bytes or surrogate escapes in the name with the replacement character οΏ½.

Invalid bytes or surrogate escapes will raise an error when written to a stream with errors="strict". This will typically happen with ``stdout when the locale is something like en_GB.UTF-8.

Many scenarios are safe to write surrogates though, due to PEP 538 and PEP 540, including:

  • Writing to stderr, which uses errors="backslashreplace".

  • The system has LANG=C.UTF-8, C, or POSIX. Python opens stdout and stderr with errors="surrogateescape".

  • None of LANG/LC_* are set. Python assumes LANG=C.UTF-8.

  • Python is started in UTF-8 mode with PYTHONUTF8=1 or -X utf8. Python opens stdout and stderr with errors="surrogateescape".

Parameters:
  • filename (Union[str, bytes, PathLike[str], PathLike[bytes]]) – formats a filename for UI display. This will also convert the filename into unicode without failing.

  • shorten (bool) – this optionally shortens the filename to strip of the path that leads up to it.

Return type:

str

click_extra.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

New in version 2.0.

Parameters:
  • app_name (str) – the application name. This should be properly capitalized and can contain whitespace.

  • roaming (bool) – controls if the folder should be roaming or not on Windows. Has no effect otherwise.

  • force_posix (bool) – if this is set to True then on any POSIX system the folder will be stored in the home folder with a leading dot instead of the XDG config home or darwin’s application support folder.

Return type:

str

click_extra.get_binary_stream(name)[source]#

Returns a system stream for byte processing.

Parameters:

name (te.Literal[β€˜stdin’, β€˜stdout’, β€˜stderr’]) – the name of the stream to open. Valid names are 'stdin', 'stdout' and 'stderr'

Return type:

BinaryIO

click_extra.get_current_context(silent=False)[source]#

Equivalent to click.get_current_context() but casts the returned click.Context object to cloup.Context (which is safe when using cloup commands classes and decorators).

Return type:

Optional[Context]

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.

Parameters:
  • name (te.Literal[β€˜stdin’, β€˜stdout’, β€˜stderr’]) – the name of the stream to open. Valid names are 'stdin', 'stdout' and 'stderr'

  • encoding (Optional[str]) – overrides the detected default encoding.

  • errors (Optional[str]) – overrides the default error mode.

Return type:

TextIO

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.

New in version 2.0.

Parameters:

echo (bool) – if set to True, the character read will also show up on the terminal. The default is to not show it.

Return type:

str

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 type cloup.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.

New 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 MRO

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

SHOW_SUBCOMMAND_ALIASES: bool = False#
show_subcommand_aliases#

Whether to show subcommand aliases.

alias2name: Dict[str, str]#

Dictionary mapping each alias to a command name.

add_multiple_commands(commands)[source]#
Return type:

None

add_command(cmd, name=None, section=None, fallback_to_default_section=True)[source]#

Add a subcommand to this Group.

Implementation note: fallback_to_default_section looks not very clean but, even if it’s not immediate to see (it wasn’t for me), I chose it over apparently cleaner options.

Parameters:
  • cmd (Command) –

  • name (Optional[str]) –

  • section (Optional[Section]) – a Section instance. The command must not be in the section already.

  • fallback_to_default_section (bool) – if section is None and this option is enabled, the command is added to the β€œdefault section”. If disabled, the command is not added to any section unless section is provided. This is useful for internal code and subclasses. Don’t disable it unless you know what you are doing.

Return type:

None

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.

Return type:

Optional[str]

resolve_command(ctx, args)[source]#
Return type:

Tuple[Optional[str], Optional[Command], List[str]]

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:

UsageError

Returns:

the original error or a new one.

must_show_subcommand_aliases(ctx)[source]#
Return type:

bool

format_subcommand_name(ctx, name, cmd)[source]#

Used to format the name of the subcommands. This method is useful when you combine this extension with other click extensions that override format_commands(). Most of these, like click-default-group, just add something to the name of the subcommands, which is exactly what this method allows you to do without overriding bigger methods.

Return type:

str

static format_subcommand_aliases(aliases, theme)[source]#
Return type:

str

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:

Return type:

Callable[[Callable[..., Any]], Union[Command, TypeVar(C, bound= Command)]]

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.

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:

Return type:

Callable[[Callable[..., Any]], Union[Group, TypeVar(G, bound= Group)]]

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.

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 own HelpExtraTheme.

theme: HelpExtraTheme#
cli_names: set[str] = {}#
subcommands: set[str] = {}#
command_aliases: set[str] = {}#
long_options: set[str] = {}#
short_options: set[str] = {}#
choices: set[str] = {}#
metavars: set[str] = {}#
envvars: set[str] = {}#
defaults: set[str] = {}#
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 and bracket_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:

str

colorize_group(str_to_style, group_id)[source]#

Colorize a string according to the style of the group ID.

Return type:

str

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 the match.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.

getvalue()[source]#

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

Return type:

str

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 with logging.levels and extra properties.

critical()#
Return type:

TypeVar(T)

error()#
Return type:

TypeVar(T)

warning()#
Return type:

TypeVar(T)

info()#
Return type:

TypeVar(T)

debug()#

Log levels from Python’s logging module.

Return type:

TypeVar(T)

option()#
Return type:

TypeVar(T)

subcommand()#
Return type:

TypeVar(T)

choice()#
Return type:

TypeVar(T)

metavar()#
Return type:

TypeVar(T)

bracket()#
Return type:

TypeVar(T)

envvar()#
Return type:

TypeVar(T)

default()#
Return type:

TypeVar(T)

deprecated()#
Return type:

TypeVar(T)

search()#
Return type:

TypeVar(T)

success()#

Click Extra new coloring properties.

Return type:

TypeVar(T)

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:

HelpExtraTheme

static dark()[source]#

A theme assuming a dark terminal background color.

Return type:

HelpExtraTheme

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 in write_dl() that allows Cloup to align multiple definition lists without resorting to hacks

  • a β€œ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 exceed col1_max_width (called col_max in write_dl for compatibility with Click).

Changed in version 0.9.0: the row_sep parameter now:

  • is set to None by default and row_sep="" corresponds to an empty line between rows

  • must not ends with \n; the formatter writes a newline just after it (when it’s not None), so a newline at the end is always enforced

  • accepts instances of SepGenerator and RowSepPolicy.

New 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 to min(terminal_width - 1, max_width) where max_width is another argument.

  • max_width (Optional[int]) – maximum content line width (equivalent to Context.max_content_width). Used to compute width 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 (or math.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, pass row_sep="". Read Row separators for more.

  • theme (HelpTheme) – an HelpTheme 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.

Return type:

Dict[str, Any]

property available_width: int#
write(*strings)[source]#

Writes a unicode string into the internal buffer.

Return type:

None

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

Writes a usage line into the buffer.

Parameters:
  • prog (str) – the program name.

  • args (str) – whitespace separated list of arguments.

  • prefix (Optional[str]) – The prefix for the first line. Defaults to "Usage: ".

Return type:

None

write_aliases(aliases)[source]#
Return type:

None

write_command_help_text(cmd)[source]#
Return type:

None

write_heading(heading, newline=True)[source]#

Writes a heading into the buffer.

Return type:

None

write_many_sections(sections, aligned=True)[source]#
Return type:

None

write_aligned_sections(sections)[source]#

Write multiple aligned definition lists.

Return type:

None

write_section(s, col1_width=None)[source]#
Return type:

None

write_text(text, style=<function identity>)[source]#

Writes re-indented text into the buffer. This rewraps and preserves paragraphs.

Return type:

None

compute_col1_width(rows, max_width)[source]#
Return type:

int

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 one indent_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 attribute self.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 overrides self.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 under self.col1_max_width; useful when you need to align multiple definition lists.

Return type:

None

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:

None

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:

None

write_epilog(epilog)[source]#
Return type:

None

class click_extra.HelpOption(param_decls=None, is_flag=True, expose_value=False, is_eager=True, help='Show this message and exit.', **kwargs)[source]#

Bases: ExtraOption

Like Click’s @help_option but made into a reusable class-based option.

Note

Keep implementation in sync with upstream for drop-in replacement compatibility.

Todo

Reuse Click’s HelpOption once this PR is merged: https://github.com/pallets/click/pull/2563

Same defaults as Click’s @help_option but with -h short option.

See: https://github.com/pallets/click/blob/d9af5cf/src/click/decorators.py#L563C23-L563C34

static print_help(ctx, param, value)[source]#

Prints help text and exits.

Exact same behavior as Click’s original @help_option callback, but forces the closing of the context before exiting.

Return type:

None

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

Bases: object

A container for a help section data.

heading: str#

Help section title.

definitions: Sequence[Tuple[str, Union[str, Callable[[int], str]]]]#

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

help: Optional[str] = None#

(Optional) long description of the section.

constraint: Optional[str] = None#

(Optional) option group constraint description.

class click_extra.HelpTheme(invoked_command=<function identity>, command_help=<function identity>, heading=<function identity>, constraint=<function identity>, section_help=<function identity>, col1=<function identity>, col2=<function identity>, alias=<function identity>, alias_secondary=None, epilog=<function identity>)[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 the click.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).

  • epilog (Callable[[str], str]) – Style of the epilog.

  • 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, the alias style will be used.

invoked_command()#

Style of the invoked command name (in Usage).

Return type:

TypeVar(T)

command_help()#

Style of the invoked command description (below Usage).

Return type:

TypeVar(T)

heading()#

Style of help section headings.

Return type:

TypeVar(T)

constraint()#

Style of an option group constraint description.

Return type:

TypeVar(T)

section_help()#

Style of the help text of a section (the optional paragraph below the heading).

Return type:

TypeVar(T)

col1()#

Style of the first column of a definition list (options and command names).

Return type:

TypeVar(T)

col2()#

Style of the second column of a definition list (help text).

Return type:

TypeVar(T)

alias()#

Style of subcommand aliases in a definition lists.

Return type:

TypeVar(T)

alias_secondary: Optional[Callable[[str], str]] = None#

Style of separator and eventual parenthesis/brackets in subcommand alias lists. If not provided, the alias style will be used.

epilog()#

Style of the epilog.

Return type:

TypeVar(T)

with_(invoked_command=None, command_help=None, heading=None, constraint=None, section_help=None, col1=None, col2=None, alias=None, alias_secondary=_Missing.flag, epilog=None)[source]#
Return type:

HelpTheme

static dark()[source]#

A theme assuming a dark terminal background color.

Return type:

HelpTheme

static light()[source]#

A theme assuming a light terminal background color.

Return type:

HelpTheme

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 ranges.

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

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

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

name: str = 'integer range'#

the descriptive name of this type

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)

New in version 2.0.

Parameters:
  • url (str) – URL or filename of the thing to launch.

  • wait (bool) – Wait for the program to exit before returning. This only works if the launched program blocks. In particular, xdg-open on Linux does not block.

  • locate (bool) – if this is set to True then instead of launching the application associated with the URL it will attempt to launch a file manager with the file located. This might have weird effects if the URL does not point to the filesystem.

Return type:

int

click_extra.make_pass_decorator(object_type, ensure=False)[source]#

Given an object type this creates a decorator that will work similar to pass_obj() but instead of passing the object of the current context, it will find the innermost context of type object_type().

This generates a decorator that works roughly like this:

from functools import update_wrapper

def decorator(f):
    @pass_context
    def new_func(ctx, *args, **kwargs):
        obj = ctx.find_object(object_type)
        return ctx.invoke(f, obj, *args, **kwargs)
    return update_wrapper(new_func, f)
return decorator
Parameters:
  • object_type (Type[TypeVar(T)]) – the type of the object to pass.

  • ensure (bool) – if set to True, a new object will be created and remembered on the context if it’s not there yet.

Return type:

Callable[[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.

New in version 4.0.

Parameters:

param_type (Optional[str]) – 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'.

format_message()[source]#
Return type:

str

class click_extra.MultiCommand(name=None, invoke_without_command=False, no_args_is_help=None, subcommand_metavar=None, chain=False, result_callback=None, **attrs)[source]#

Bases: Command

A multi command is the basic implementation of a command that dispatches to subcommands. The most common version is the Group.

Parameters:
  • invoke_without_command (bool) – this controls how the multi command itself is invoked. By default it’s only invoked if a subcommand is provided.

  • no_args_is_help (Optional[bool]) – this controls what happens if no arguments are provided. This option is enabled by default if invoke_without_command is disabled or disabled if it’s enabled. If enabled this will add --help as argument if no arguments are passed.

  • subcommand_metavar (Optional[str]) – the string that is used in the documentation to indicate the subcommand place.

  • chain (bool) – if this is set to True chaining of multiple subcommands is enabled. This restricts the form of commands in that they cannot have optional arguments but it allows multiple commands to be chained together.

  • result_callback (Optional[Callable[..., Any]]) – The result callback to attach to this multi command. This can be set or changed later with the result_callback() decorator.

  • attrs (Any) – Other command arguments described in Command.

allow_extra_args = True#

the default for the Context.allow_extra_args flag.

allow_interspersed_args = False#

the default for the Context.allow_interspersed_args flag.

to_info_dict(ctx)[source]#

Gather information that could be useful for a tool generating user-facing documentation. This traverses the entire structure below this command.

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

Parameters:

ctx (Context) – A Context representing this command.

Return type:

Dict[str, Any]

New in version 8.0.

collect_usage_pieces(ctx)[source]#

Returns all the pieces that go into the usage line and returns it as a list of strings.

Return type:

List[str]

format_options(ctx, formatter)[source]#

Writes all the options into the formatter if they exist.

Return type:

None

result_callback(replace=False)[source]#

Adds a result callback to the command. By default if a result callback is already registered this will chain them but this can be disabled with the replace parameter. The result callback is invoked with the return value of the subcommand (or the list of return values from all subcommands if chaining is enabled) as well as the parameters as they would be passed to the main callback.

Example:

@click.group()
@click.option('-i', '--input', default=23)
def cli(input):
    return 42

@cli.result_callback()
def process_result(result, input):
    return result + input
Parameters:

replace (bool) – if set to True an already existing result callback will be removed.

Return type:

Callable[[TypeVar(F, bound= Callable[..., Any])], TypeVar(F, bound= Callable[..., Any])]

Changed in version 8.0: Renamed from resultcallback.

New in version 3.0.

format_commands(ctx, formatter)[source]#

Extra format methods for multi methods that adds all the commands after the options.

Return type:

None

parse_args(ctx, args)[source]#

Given a context and a list of arguments this creates the parser and parses the arguments, then modifies the context as necessary. This is automatically invoked by make_context().

Return type:

List[str]

invoke(ctx)[source]#

Given a context, this invokes the attached callback (if it exists) in the right way.

Return type:

Any

resolve_command(ctx, args)[source]#
Return type:

Tuple[Optional[str], Optional[Command], List[str]]

get_command(ctx, cmd_name)[source]#

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

Return type:

Optional[Command]

list_commands(ctx)[source]#

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

Return type:

List[str]

shell_complete(ctx, incomplete)[source]#

Return a list of completions for the incomplete value. Looks at the names of options, subcommands, and chained multi-commands.

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

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

Return type:

List[CompletionItem]

New in version 8.0.

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.

New in version 4.0.

format_message()[source]#
Return type:

str

click_extra.open_file(filename, mode='r', encoding=None, errors='strict', lazy=False, atomic=False)[source]#

Open a file, with extra behavior to handle '-' to indicate a standard stream, lazy open on write, and atomic write. Similar to the behavior of the File param type.

If '-' is given to open stdout or stdin, the stream is wrapped so that using it in a context manager will not close it. This makes it possible to use the function without accidentally closing a standard stream:

with open_file(filename) as f:
    ...
Parameters:
  • filename (str) – The name of the file to open, or '-' for stdin/stdout.

  • mode (str) – The mode in which to open the file.

  • encoding (Optional[str]) – The encoding to decode or encode a file opened in text mode.

  • errors (Optional[str]) – The error handling mode.

  • lazy (bool) – Wait to open the file until it is accessed. For read mode, the file is temporarily opened to raise access errors early, then closed until it is read again.

  • atomic (bool) – Write to a temporary file and replace the given file on close.

Return type:

IO[Any]

New in version 3.0.

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

Bases: Option

A click.Option with an extra field group of type OptionGroup.

click_extra.option(*param_decls, cls=None, group=None, **attrs)[source]#

Attach an Option to the command. Refer to click.Option and click.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 the name of the group:

# help as keyword argument
@option_group(name, *options, help=None, ...)

# help as 2nd positional argument
@option_group(name, help, *options, ...)

Changed in version 0.9.0: in order to support the decorator cloup.constrained_params(), @option_group now allows each input decorators to add multiple options.

Parameters:
  • title (str) – title of the help section describing the option group.

  • help – an optional description shown below the name; can be provided as keyword argument or 2nd positional argument.

  • options – an arbitrary number of decorators like click.option, which attach one or multiple options to the decorated command function.

  • constraint – an optional instance of Constraint (see Constraints for more info); a description of the constraint will be shown between squared brackets aside the option group title (or below it if too long).

  • hidden – if True, the option group and all its options are hidden from the help page (all contained options will have their hidden attribute set to True).

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.

New in version 0.8.0: The hidden parameter.

property options: Sequence[Option]#
get_help_records(ctx)[source]#
Return type:

List[Tuple[str, str]]

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

Refer to cloup.option().

Return type:

Callable[[TypeVar(F, bound= Callable[..., Any])], TypeVar(F, bound= Callable[..., Any])]

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!

New in version 0.14.0: added the β€œPositional arguments” help section.

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

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

New 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 MRO

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

option_groups#

List of all option groups, except the β€œdefault option group”.

ungrouped_options#

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

get_ungrouped_options(ctx)[source]#

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

Return type:

Sequence[Option]

get_argument_help_record(arg, ctx)[source]#
Return type:

Tuple[str, str]

get_arguments_help_section(ctx)[source]#
Return type:

Optional[HelpSection]

make_option_group_help_section(group, ctx)[source]#

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

New 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

New in version 0.8.0.

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

New in version 0.8.0.

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

None

class click_extra.OptionParser(ctx=None)[source]#

Bases: object

The option parser is an internal class that is ultimately used to parse options and arguments. It’s modelled after optparse and brings a similar but vastly simplified API. It should generally not be used directly as the high level Click classes wrap it for you.

It’s not nearly as extensible as optparse or argparse as it does not implement features that are implemented on a higher level (such as types or defaults).

Parameters:

ctx (Optional[Context]) – optionally the Context where this parser should go with.

ctx#

The Context for this parser. This might be None for some advanced use cases.

allow_interspersed_args: bool#

This controls how the parser deals with interspersed arguments. If this is set to False, the parser will stop on the first non-option. Click uses this to implement nested subcommands safely.

ignore_unknown_options: bool#

This tells the parser how to deal with unknown options. By default it will error out (which is sensible), but there is a second mode where it will ignore it and continue processing after shifting all the unknown options into the resulting args.

add_option(obj, opts, dest, action=None, nargs=1, const=None)[source]#

Adds a new option named dest to the parser. The destination is not inferred (unlike with optparse) and needs to be explicitly provided. Action can be any of store, store_const, append, append_const or count.

The obj can be used to identify the option in the order list that is returned from the parser.

Return type:

None

add_argument(obj, dest, nargs=1)[source]#

Adds a positional argument named dest to the parser.

The obj can be used to identify the option in the order list that is returned from the parser.

Return type:

None

parse_args(args)[source]#

Parses positional arguments and returns (values, args, order) for the parsed options and arguments as well as the leftover arguments if there are any. The order is a list of objects as they appear on the command line. If arguments appear multiple times they will be memorized multiple times as well.

Return type:

Tuple[Dict[str, Any], List[str], List[CoreParameter]]

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)[source]#

Bases: object

A parameter to a command comes in two versions: they are either Options or Arguments. Other subclasses are currently not supported by design as some of the internals for parsing are intentionally not finalized.

Some settings are supported by both options and arguments.

Parameters:
  • param_decls (Optional[Sequence[str]]) – the parameter declarations for this option or argument. This is a list of flags or argument names.

  • type (Union[ParamType, 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 (Union[Any, Callable[[], Any], None]) – the default value if omitted. This can also be a callable, in which case it’s invoked when the default is needed without any arguments.

  • callback (Optional[Callable[[Context, Parameter, Any], Any]]) – 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 (Optional[int]) – the number of arguments to match. If not 1 the return value is a tuple instead of single value. The default for nargs is 1 (except if the type is a tuple, then it’s the arity of the tuple). If nargs=-1, all remaining parameters are collected.

  • metavar (Optional[str]) – 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 (Union[Sequence[str], str, None]) – a string or list of strings that are environment variables that should be checked.

  • shell_complete (Optional[Callable[[Context, Parameter, str], Union[List[CompletionItem], List[str]]]]) – A function that returns custom shell completions. Used instead of the param’s type completion if given. Takes ctx, param, incomplete and must return a list of CompletionItem or a list of strings.

Changed in version 8.0: process_value validates required parameters and bounded nargs, and invokes the parameter callback before returning the value. This allows the callback to validate prompts. full_process_value is removed.

Changed in version 8.0: autocompletion is renamed to shell_complete and has new semantics described above. The old name is deprecated and will be removed in 8.1, until then it will be wrapped to match the new requirements.

Changed in version 8.0: For multiple=True, nargs>1, the default must be a list of tuples.

Changed in version 8.0: Setting a default is no longer required for nargs>1, it will default to None. multiple=True or nargs=-1 will default to ().

Changed in version 7.1: Empty environment variables are ignored rather than taking the empty string value. This makes it possible for scripts to clear variables if they can’t unset them.

Changed in version 2.0: Changed signature for parameter callback to also be passed the parameter. The old callback format will still work, but it will raise a warning to give you a chance to migrate the code easier.

param_type_name = 'parameter'#
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]

New in version 8.0.

property human_readable_name: str#

Returns the human readable name of this parameter. This is the same as the name for options, but the metavar for arguments.

make_metavar()[source]#
Return type:

str

get_default(ctx, call=True)[source]#

Get the default for the parameter. Tries Context.lookup_default() first, then the local default.

Parameters:
  • ctx (Context) – Current context.

  • call (bool) – If the default is a callable, call it. Disable to return the callable instead.

Return type:

Union[Any, Callable[[], Any], None]

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.

add_to_parser(parser, ctx)[source]#
Return type:

None

consume_value(ctx, opts)[source]#
Return type:

Tuple[Any, ParameterSource]

type_cast_value(ctx, value)[source]#

Convert and validate a value against the option’s type, multiple, and nargs.

Return type:

Any

value_is_missing(value)[source]#
Return type:

bool

process_value(ctx, value)[source]#
Return type:

Any

resolve_envvar_value(ctx)[source]#
Return type:

Optional[str]

value_from_envvar(ctx)[source]#
Return type:

Optional[Any]

handle_parse_result(ctx, opts, args)[source]#
Return type:

Tuple[Any, List[str]]

get_help_record(ctx)[source]#
Return type:

Optional[Tuple[str, str]]

get_usage_pieces(ctx)[source]#
Return type:

List[str]

get_error_hint(ctx)[source]#

Get a stringified version of the param for use in error messages to indicate which param caused the error.

Return type:

str

shell_complete(ctx, incomplete)[source]#

Return a list of completions for the incomplete value. If a shell_complete function was given during init, it is used. Otherwise, the type shell_complete() function is used.

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

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

Return type:

List[CompletionItem]

New in version 8.0.

class click_extra.ParameterSource(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[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 the validate 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 cached self.excluded_params property to compute the default value on first use.

SEP: str = '.'#

Use a dot . as a separator between levels of the tree-like parameter structure.

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 of leaf.

Return type:

Any

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

Get in the tree_dict the value located at the path.

Return type:

Any | None

flatten_tree_dict(tree_dict, parent_key=None)[source]#

Recursively traverse the tree-like dict and produce a flat dict whose keys are path and values are the leaf’s content.

Return type:

dict[str, Any]

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.

Return type:

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

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.StringParamType'>: <class 'str'>, <class 'click.types.IntParamType'>: <class 'int'>, <class 'click.types.FloatParamType'>: <class 'float'>, <class 'click.types.BoolParamType'>: <class 'bool'>, <class 'click.types.UUIDParameterType'>: <class 'str'>, <class 'click.types.UnprocessedParamType'>: <class 'str'>, <class 'click.types.File'>: <class 'str'>, <class 'click.types.Path'>: <class 'str'>, <class 'click.types.Choice'>: <class 'str'>, <class 'click.types.IntRange'>: <class 'int'>, <class 'click.types.FloatRange'>: <class 'float'>, <class 'click.types.DateTime'>: <class 'str'>, <class 'click.types.Tuple'>: <class 'list'>}#

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.

Return type:

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

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:

None

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.

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.

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 return None. This is already implemented by default.

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

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

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

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

the descriptive name of this type

envvar_list_splitter: ClassVar[Optional[str]] = None#

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

to_info_dict()[source]#

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

Use click.Context.to_info_dict() to traverse the entire CLI structure. :rtype: Dict[str, Any]

New in version 8.0.

get_metavar(param)[source]#

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

Return type:

Optional[str]

get_missing_message(param)[source]#

Optionally might return extra information about a missing parameter. :rtype: Optional[str]

New in version 2.0.

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

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

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

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

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

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

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

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

Return type:

Any

split_envvar_value(rv)[source]#

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

If the splitter is set to None, which means that whitespace splits, then leading and trailing whitespace is ignored. Otherwise, leading and trailing splitters usually lead to empty items being included.

Return type:

Sequence[str]

fail(message, param=None, ctx=None)[source]#

Helper method to fail with an invalid value message.

Return type:

t.NoReturn

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

Return a list of 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]

New in version 8.0.

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 type cloup.Context.

Return type:

Callable[[ParamSpec(P, bound= None)], TypeVar(R)]

click_extra.pass_obj(f)[source]#

Similar to pass_context(), but only pass the object on the context onwards (Context.obj). This is useful if that object represents the state of a nested system.

Return type:

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.

Parameters:
  • param_decls (str) – One or more option names. Defaults to the single value "--password".

  • kwargs (Any) – Extra arguments are passed to option().

Return type:

Callable[[TypeVar(FC, bound= Union[Callable[..., Any], Command])], TypeVar(FC, bound= Union[Callable[..., Any], Command])]

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 the File type, but returns the filename instead of an open file. Various checks can be enabled to validate the type of file and permissions.

Parameters:
  • exists (bool) – The file or directory needs to exist for the value to be valid. If this is not set to True, and the file does not exist, then all further checks are silently skipped.

  • file_okay (bool) – Allow a file as a value.

  • dir_okay (bool) – Allow a directory as a value.

  • readable (bool) – if true, a readable check is performed.

  • writable (bool) – if true, a writable check is performed.

  • executable (bool) – if true, an executable check is performed.

  • resolve_path (bool) – Make the value absolute and resolve any symlinks. A ~ is not expanded, as this is supposed to be done by the shell only.

  • allow_dash (bool) – Allow a single dash as a value, which indicates a standard stream (but does not open it). Use open_file() to handle opening this value.

  • path_type (Optional[Type[Any]]) – Convert the incoming path value to this type. If None, keep Python’s default, which is str. Useful to convert to pathlib.Path.

Changed in version 8.1: Added the executable parameter.

Changed in version 8.0: Allow passing path_type=pathlib.Path.

Changed in version 6.0: Added the allow_dash parameter.

envvar_list_splitter: ClassVar[str] = ':'#

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

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]

New in version 8.0.

coerce_path_result(value)[source]#
Return type:

Union[str, bytes, PathLike[str]]

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

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

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

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

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

Parameters:
  • value (t.Union[str, os.PathLike[str]]) – The value to convert.

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

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

Return type:

t.Union[str, bytes, os.PathLike[str]]

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

Return a special completion marker that tells the completion system to use the shell to provide path completions for only directories or any paths.

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

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

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

Return type:

List[CompletionItem]

New in version 8.0.

click_extra.path(*, path_type=<class 'pathlib.Path'>, exists=False, file_okay=True, dir_okay=True, writable=False, readable=True, resolve_path=False, allow_dash=False)[source]#

Shortcut for click.Path with path_type=pathlib.Path.

Return type:

Path

click_extra.pause(info=None, err=False)[source]#

This command stops execution and waits for the user to press any key to continue. This is similar to the Windows batch β€œpause” command. If the program is not run through a terminal, this command will instead do nothing.

New in version 2.0.

New in version 4.0: Added the err parameter.

Parameters:
  • info (Optional[str]) – The message to print before pausing. Defaults to "Press any key to continue...".

  • err (bool) – if set to message goes to stderr instead of stdout, the same as with echo.

Return type:

None

click_extra.progressbar(iterable=None, length=None, label=None, 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 the current_item at the new position. This is useful when used together with item_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 (Optional[Iterable[TypeVar(V)]]) – an iterable to iterate over. If not provided the length is required.

  • length (Optional[int]) – 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 (Optional[str]) – the label to show next to the progress bar.

  • show_eta (bool) – enables or disables the estimated time display. This is automatically disabled if the length cannot be determined.

  • show_percent (Optional[bool]) – 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 (Optional[Callable[[Optional[TypeVar(V)]], Optional[str]]]) – 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 be None, 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 and info 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 (Optional[TextIO]) – The file to write to. If this is not a terminal then only the label is printed.

  • color (Optional[bool]) – 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]

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.

New in version 8.0: Added the update_min_steps parameter.

Changed in version 4.0: Added the color parameter. Added the update method to the object.

New 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 (Optional[Any]) – 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 (Union[bool, str]) – Prompt a second time to confirm the value. Can be set to a string instead of True to customize the message.

  • type (Union[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 to stderr instead of stdout, the same as with echo.

  • show_choices (bool) – Show or hide choices if the passed type is a Choice. For example if type is a Choice of either day or week, show_choices is true and text is β€œGroup by” then the prompt will be β€œGroup by (day, week): β€œ.

Return type:

Any

New in version 8.0: confirmation_prompt can be a custom string.

New in version 7.0: Added the show_choices parameter.

New in version 6.0: Added unicode support for cmd.exe on Windows.

New in version 4.0: Added the err parameter.

click_extra.search_params(params, klass, 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.

  • unique (bool) – if True, raise an error if more than one parameter of the provided klass is found.

Return type:

list[Parameter] | Parameter | None

click_extra.secho(message=None, file=None, nl=True, err=False, color=None, **styles)[source]#

This function combines echo() and style() into one call. As such the following two calls are the same:

click.secho('Hello World!', fg='green')
click.echo(click.style('Hello World!', fg='green'))

All keyword arguments are forwarded to the underlying functions depending on which one they go with.

Non-string types will be converted to str. However, bytes are passed directly to echo() without applying style. If you want to style bytes that represent text, call bytes.decode() first. :rtype: None

Changed in version 8.0: A non-string message is converted to a string. Bytes are passed through without style applied.

New 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 from SectionMixin.

Changed in version 0.6.0: removed the deprecated old name GroupSection.

Changed in version 0.5.0: introduced the new name Section and deprecated the old GroupSection.

Parameters:
  • title (str) –

  • commands (Union[Iterable[Command], Dict[str, Command]]) – sequence of commands or dict of commands keyed by name

  • is_sorted (bool) – if True, list_commands() returns the commands in lexicographic order

classmethod sorted(title, commands=())[source]#
Return type:

Section

add_command(cmd, name=None)[source]#
Return type:

None

list_commands()[source]#
Return type:

List[Tuple[str, Command]]

class click_extra.SectionMixin(*args, commands=None, sections=(), align_sections=None, **kwargs)[source]#

Bases: object

Adds to a click.MultiCommand the possibility of organizing its subcommands into multiple help sections.

Sections can be specified in the following ways:

  1. passing a list of Section objects to the constructor setting the argument sections

  2. using add_section() to add a single section

  3. using add_command() with the argument section set

Commands not assigned to any user-defined section are added to the β€œdefault section”, whose title is β€œCommands” or β€œOther commands” depending on whether it is the only section or not. The default section is the last shown section in the help and its commands are listed in lexicographic order.

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

Changed in version 0.8.0: removed format_section. Added make_commands_help_section.

New 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 MRO

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

add_section(section)[source]#

Add a Section to this group. You can add the same section object only a single time.

Return type:

None

See Also:

section()

section(title, *commands, **attrs)[source]#

Create a new Section, adds it to this group and returns it.

Return type:

Section

add_command(cmd, name=None, section=None, fallback_to_default_section=True)[source]#

Add a subcommand to this Group.

Implementation note: fallback_to_default_section looks not very clean but, even if it’s not immediate to see (it wasn’t for me), I chose it over apparently cleaner options.

Parameters:
  • cmd (Command) –

  • name (Optional[str]) –

  • section (Optional[Section]) – a Section instance. The command must not be in the section already.

  • fallback_to_default_section (bool) – if section is None and this option is enabled, the command is added to the β€œdefault section”. If disabled, the command is not added to any section unless section is provided. This is useful for internal code and subclasses. Don’t disable it unless you know what you are doing.

Return type:

None

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

Return the list of all sections in the β€œcorrect order”.

If include_default_section=True and the default section is non-empty, it will be included at the end of the list.

Return type:

List[Section]

format_subcommand_name(ctx, name, cmd)[source]#

Used to format the name of the subcommands. This method is useful when you combine this extension with other click extensions that override format_commands(). Most of these, like click-default-group, just add something to the name of the subcommands, which is exactly what this method allows you to do without overriding bigger methods.

Return type:

str

make_commands_help_section(ctx, section)[source]#
Return type:

Optional[HelpSection]

must_align_sections(ctx, default=True)[source]#
Return type:

bool

format_commands(ctx, formatter)[source]#
Return type:

None

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 cached self.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 a click_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 with HelpTheme.

Available colors are defined as static constants in Color.

Arguments are set to None by default. Passing False to boolean args or Color.reset as color causes a reset code to be inserted.

With respect to click.style(), this class:

  • has an argument less, reset, which is always True

  • add the text_transform.

Warning

The arguments overline, italic and strikethrough are only supported in Click 8 and will be ignored if you are using Click 7.

Parameters:

New in version 0.8.0.

fg: Optional[str] = None#
bg: Optional[str] = None#
bold: Optional[bool] = None#
dim: Optional[bool] = None#
underline: Optional[bool] = None#
overline: Optional[bool] = None#
italic: Optional[bool] = None#
reverse: Optional[bool] = None#
strikethrough: Optional[bool] = None#
text_transform: Optional[Callable[[str], str]] = None#
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 (Union[int, Tuple[int, int, int], str, None]) – if provided this will become the foreground color.

  • bg (Union[int, Tuple[int, int, int], str, None]) – if provided this will become the background color.

  • bold (Optional[bool]) – if provided this will enable or disable bold mode.

  • dim (Optional[bool]) – if provided this will enable or disable dim mode. This is badly supported.

  • underline (Optional[bool]) – if provided this will enable or disable underline.

  • overline (Optional[bool]) – if provided this will enable or disable overline.

  • italic (Optional[bool]) – if provided this will enable or disable italic.

  • blink (Optional[bool]) – if provided this will enable or disable blinking.

  • reverse (Optional[bool]) – if provided this will enable or disable inverse rendering (foreground becomes background and the other way round).

  • strikethrough (Optional[bool]) – if provided this will enable or disable striking through text.

  • reset (bool) – by default a reset-all code is added at the end of the string which means that styles do not carry over. This can be disabled to compose styles.

Return type:

str

Changed in version 8.0: A non-string message is converted to a string.

Changed in version 8.0: Added support for 256 and RGB color codes.

Changed in version 8.0: Added the strikethrough, italic, and overline parameters.

Changed in version 7.0: Added support for bright colors.

New 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:

None

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.

save_telemetry(ctx, param, value)[source]#

Save the option value in the context, in ctx.telemetry.

Return type:

None

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, 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"].

print_timer()[source]#

Compute and print elapsed execution time.

register_timer_on_close(ctx, param, value)[source]#

Callback setting up all timer’s machinery.

Computes and print the execution time at the end of the CLI, if option has been activated.

Return type:

None

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 tuple-type.

This can be selected by using a Python tuple literal as a type.

Parameters:

types (Sequence[Union[Type[Any], ParamType]]) – a list of types that should be used for the tuple items.

to_info_dict()[source]#

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

Use click.Context.to_info_dict() to traverse the entire CLI structure. :rtype: Dict[str, Any]

New in version 8.0.

property name: str#
property arity: int#

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by β€˜+’ or β€˜-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(β€˜0b100’, base=0) 4

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

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

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

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

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

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

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

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

Return type:

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.

New in version 2.0.

Parameters:

text (str) – the text to remove style information from.

Return type:

str

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 (Optional[Context]) – 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.

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

None

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=None, default='WARNING', metavar='LEVEL', type=Choice(['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG']), expose_value=False, help='Either CRITICAL, ERROR, WARNING, INFO, DEBUG.', is_eager=True, **kwargs)[source]#

Bases: ExtraOption

A pre-configured --verbosity/-v option.

Sets the level of the provided logger.

The selected verbosity level name is made available in the context in ctx.meta["click_extra.verbosity"].

Important

The internal click_extra logger level will be aligned to the value set via this option.

Set up the verbosity option.

Parameters:

default_logger (Logger | str | None) – If an instance of logging.Logger is provided, that’s the instance to which we will set the level set via the option. If the parameter is a string, we will fetch it with logging.getLogger. If not provided or None, the default Python root logger is used.

Todo

Write more documentation to detail in which case the user is responsible for setting up the logger, and when extra_basic_config is used.

property all_loggers: Generator[Logger, None, None]#

Returns the list of logger IDs affected by the verbosity option.

Will returns Click Extra’s internal logger first, then the option’s custom logger.

reset_loggers()[source]#

Forces all loggers managed by the option to be reset to the default level.

Reset loggers in reverse order to ensure the internal logger is reset last. :rtype: None

Danger

Resseting loggers is extremely important for unittests. Because they’re global, loggers have tendency to leak and pollute their state between multiple test calls.

set_levels(ctx, param, value)[source]#

Set level of all loggers configured on the option.

Save the verbosity level name in the context.

Also prints the chosen value as a debug message via the internal click_extra logger.

Return type:

None

logger_name: str#

The ID of the logger to set the level to.

This will be provided to logging.getLogger method to fetch the logger object, and as such, can be a dot-separated string to build hierarchical loggers.

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 using importlib.metadata.version() to get the version for the package_name. On Python < 3.8, the importlib_metadata backport must be installed.

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 (Optional[str]) – 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 (Optional[str]) – The package name to detect the version from. If not provided, Click will try to detect it.

  • prog_name (Optional[str]) – The name of the CLI to show in the message. If not provided, it will be detected from the command.

  • message (Optional[str]) – The message to show. The values %(prog)s, %(package)s, and %(version)s are available. Defaults to "%(prog)s, version %(version)s".

  • kwargs (Any) – Extra arguments are passed to option().

Raises:

RuntimeError – version could not be detected.

Return type:

Callable[[TypeVar(FC, bound= Union[Callable[..., Any], Command])], TypeVar(FC, bound= Union[Callable[..., Any], 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 of pkg_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 with package_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:

str

Subpackages#

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 with logging.levels and extra properties.

critical()#
Return type:

TypeVar(T)

error()#
Return type:

TypeVar(T)

warning()#
Return type:

TypeVar(T)

info()#
Return type:

TypeVar(T)

debug()#

Log levels from Python’s logging module.

Return type:

TypeVar(T)

option()#
Return type:

TypeVar(T)

subcommand()#
Return type:

TypeVar(T)

choice()#
Return type:

TypeVar(T)

metavar()#
Return type:

TypeVar(T)

bracket()#
Return type:

TypeVar(T)

envvar()#
Return type:

TypeVar(T)

default()#
Return type:

TypeVar(T)

deprecated()#
Return type:

TypeVar(T)

search()#
Return type:

TypeVar(T)

success()#

Click Extra new coloring properties.

Return type:

TypeVar(T)

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:

HelpExtraTheme

static dark()[source]#

A theme assuming a dark terminal background color.

Return type:

HelpExtraTheme

static light()[source]#

A theme assuming a light terminal background color. :rtype: HelpExtraTheme

Todo

Tweak colors to make them more readable.

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.

Source: https://github.com/pallets/click/issues/558

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.

static disable_colors(ctx, param, value)[source]#

Callback disabling all coloring utilities.

Re-inspect the environment for existence of colorization flags to re-interpret the provided value.

Return type:

None

class click_extra.colorize.HelpOption(param_decls=None, is_flag=True, expose_value=False, is_eager=True, help='Show this message and exit.', **kwargs)[source]#

Bases: ExtraOption

Like Click’s @help_option but made into a reusable class-based option.

Note

Keep implementation in sync with upstream for drop-in replacement compatibility.

Todo

Reuse Click’s HelpOption once this PR is merged: https://github.com/pallets/click/pull/2563

Same defaults as Click’s @help_option but with -h short option.

See: https://github.com/pallets/click/blob/d9af5cf/src/click/decorators.py#L563C23-L563C34

static print_help(ctx, param, value)[source]#

Prints help text and exits.

Exact same behavior as Click’s original @help_option callback, but forces the closing of the context before exiting.

Return type:

None

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.

get_help_option(ctx)[source]#

Returns our custom help option object instead of Click’s default one.

Return type:

Option | None

get_help(ctx)[source]#

Replace default formatter by our own.

Return type:

str

format_help(ctx, formatter)[source]#

Feed our custom formatter instance with the keywords to highlight.

Return type:

None

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:

str

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 own HelpExtraTheme.

theme: HelpExtraTheme#
cli_names: set[str] = {}#
subcommands: set[str] = {}#
command_aliases: set[str] = {}#
long_options: set[str] = {}#
short_options: set[str] = {}#
choices: set[str] = {}#
metavars: set[str] = {}#
envvars: set[str] = {}#
defaults: set[str] = {}#
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 and bracket_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:

str

width: int#
buffer: t.List[str]#
colorize_group(str_to_style, group_id)[source]#

Colorize a string according to the style of the group ID.

Return type:

str

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 the match.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.

getvalue()[source]#

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

Return type:

str

click_extra.colorize.highlight(string, substrings, styling_method, ignore_case=False)[source]#

Highlights parts of the string that matches substrings.

Takes care of overlapping parts within the string.

Return type:

str

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’s meta 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

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.

click_extra.commands.default_extra_params()[source]#

Default additional options added to extra_command and extra_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).

  1. --time / --no-time

    Hint

    --time is placed at the top so all other options can be timed.

  2. -C, --config CONFIG_PATH

    Attention

    --config is at the top so it can have a direct influence on the default behavior and value of the other options.

  3. --color, --ansi / --no-color, --no-ansi

  4. --show-params

  5. -v, --verbosity LEVEL

  6. --version

  7. -h, --help

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.

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.

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 of ExtraVersionOption 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.

By default, these Click context settings are applied:

Additionally, these Cloup context settings are set:

Click Extra also adds its own context_settings:

  • show_choices = None (Click Extra feature)

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

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

  • show_envvar = None (Click Extra feature)

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

    Defaults to None, which will leave all options untouched, and let them decide of their own show_envvar setting. The rationale being that discoverability of environment variables is enabled by the --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.BaseCommand.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’s meta property under our own click_extra.raw_args entry. This will be used in ShowParamsOption.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.

invoke(ctx)[source]#

Main execution of the command, just after the context has been instantiated in main().

Return type:

Any

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 of ExtraVersionOption 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.

By default, these Click context settings are applied:

Additionally, these Cloup context settings are set:

Click Extra also adds its own context_settings:

  • show_choices = None (Click Extra feature)

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

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

  • show_envvar = None (Click Extra feature)

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

    Defaults to None, which will leave all options untouched, and let them decide of their own show_envvar setting. The rationale being that discoverability of environment variables is enabled by the --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 of ExtraCommand.

That way all subcommands created from an ExtraGroup benefits from the same defaults and extra help screen colorization.

See: https://click.palletsprojects.com/en/8.1.x/api/#click.Group.command_class

alias of ExtraCommand

group_class#

Let ExtraGroup produce sub-groups that are also of ExtraGroup type.

See: https://click.palletsprojects.com/en/8.1.x/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(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[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: ('toml', )>, <Formats.YAML: ('yaml', 'yml')>, <Formats.JSON: ('json', )>, <Formats.INI: ('ini', )>, <Formats.XML: ('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’s callback gets the opportunity to set the default_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 and force_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 to ParamStructure.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 the roaming and force_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 set

  • an 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.

Return type:

tuple[str, str] | None

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 with http:// or https://.

Returns an iterator of the normalized configuration location and its textual content, for each file/URL matching the pattern.

Return type:

Iterable[tuple[Path | URL, str]]

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.

Return type:

dict[str, Any] | None

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.

Return type:

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

default: t.Union[t.Any, t.Callable[[], t.Any]]#
type: types.ParamType#
is_flag: bool#
is_bool_flag: bool#
flag_value: t.Any#
name: t.Optional[str]#
opts: t.List[str]#
secondary_opts: t.List[str]#
load_ini_config(content)[source]#

Utility method to parse INI configuration file.

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

Returns a ready-to-use data structure.

Return type:

dict[str, Any]

recursive_update(a, b)[source]#

Like standard dict.update(), but recursive so sub-dict gets updated.

Ignore elements present in b but not in a.

Return type:

dict[str, Any]

merge_default_map(ctx, user_conf)[source]#

Save the user configuration into the context’s default_map.

Merge the user configuration into the pre-computed template structure, which 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:

None

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:

None

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_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.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.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.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.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, start_tag, end_tag, new_content)[source]#

Replace in the provided file the content surrounded by the provided tags.

Return type:

None

click_extra.docs_update.generate_lexer_table()[source]#

Generate a Markdown table mapping original Pygments’ lexers to their new ANSI variants implemented by Click Extra.

Return type:

str

click_extra.docs_update.generate_platforms_graph(graph_id, description, groups)[source]#

Generates an Euler diagram of platform and their grouping.

Euler diagrams are not supported by mermaid yet so we fallback on a flowchart without arrows.

Returns a ready to use and properly indented MyST block.

Return type:

str

click_extra.docs_update.update_docs()[source]#

Update documentation with dynamic content.

Return type:

None

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 IDs.

Sorted from lowest to highest verbosity.

Are ignored:

click_extra.logging.DEFAULT_LEVEL_NAME: str = 'WARNING'#

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 of the --verbosity option below.

class click_extra.logging.THandler#

Custom types to be used in type hints below.

alias of TypeVar(β€˜THandler’, bound=Handler)

class click_extra.logging.ExtraLogHandler(level=0)[source]#

Bases: Handler

A handler to output logs to console’s <stderr>.

Initializes the instance - basically setting the formatter to None and the filter list to empty.

emit(record)[source]#

Use click.echo to print to <stderr> and supports colors.

Return type:

None

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

Bases: Formatter

Initialize the formatter with specified format strings.

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

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

Changed in version 3.2: Added the style parameter.

formatMessage(record)[source]#

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

Return type:

str

click_extra.logging.extra_basic_config(logger_name=None, format='{levelname}: {message}', datefmt=None, style='{', level=None, handlers=None, force=True, handler_class=<class 'click_extra.logging.ExtraLogHandler'>, formatter_class=<class 'click_extra.logging.ExtraLogFormatter'>)[source]#

Setup and configure a logger.

Reimplements logging.basicConfig, but with sane defaults and more parameters.

Parameters:
  • logger_name (str | None) – ID of the logger to setup. If None, Python’s root logger will be used.

  • format (str | None) – Use the specified format string for the handler. Defaults to levelname and message separated by a colon.

  • datefmt (str | None) – Use the specified date/time format, as accepted by time.strftime().

  • style (Literal['%', '{', '$']) – If format is specified, use this style for the format string. One of %, { or $ for printf-style, str.format() or string.Template respectively. Defaults to {.

  • level (int | None) – Set the logger level to the specified level.

  • handlers (Iterable[Handler] | None) – A list of logging.Handler instances to attach to the logger. If not provided, a new handler of the class set by the handler_class parameter will be created. Any handler in the list which does not have a formatter assigned will be assigned the formatter created in this function.

  • force (bool) – Remove and close any existing handlers attached to the logger before carrying out the configuration as specified by the other arguments. Default to True so we always starts from a clean state each time we configure a logger. This is a life-saver in unittests in which loggers pollutes output.

  • handler_class (type[TypeVar(THandler, bound= Handler)]) – Handler class to be used to create a new handler if none provided. Defaults to ExtraLogHandler.

  • formatter_class (type[TypeVar(TFormatter, bound= Formatter)]) – Class of the formatter that will be setup on each handler if none found. Defaults to ExtraLogFormatter.

Return type:

Logger

Todo

Add more parameters for even greater configurability of the logger, by re-implementing those supported by logging.basicConfig.

class click_extra.logging.VerbosityOption(param_decls=None, default_logger=None, default='WARNING', metavar='LEVEL', type=Choice(['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG']), expose_value=False, help='Either CRITICAL, ERROR, WARNING, INFO, DEBUG.', is_eager=True, **kwargs)[source]#

Bases: ExtraOption

A pre-configured --verbosity/-v option.

Sets the level of the provided logger.

The selected verbosity level name is made available in the context in ctx.meta["click_extra.verbosity"].

Important

The internal click_extra logger level will be aligned to the value set via this option.

Set up the verbosity option.

Parameters:

default_logger (Logger | str | None) –

If an instance of logging.Logger is provided, that’s the instance to which we will set the level set via the option. If the parameter is a string, we will fetch it with logging.getLogger. If not provided or None, the default Python root logger is used.

Todo

Write more documentation to detail in which case the user is responsible for setting up the logger, and when extra_basic_config is used.

property all_loggers: Generator[Logger, None, None]#

Returns the list of logger IDs affected by the verbosity option.

Will returns Click Extra’s internal logger first, then the option’s custom logger.

default: t.Union[t.Any, t.Callable[[], t.Any]]#
type: types.ParamType#
is_flag: bool#
is_bool_flag: bool#
flag_value: t.Any#
name: t.Optional[str]#
opts: t.List[str]#
secondary_opts: t.List[str]#
reset_loggers()[source]#

Forces all loggers managed by the option to be reset to the default level.

Reset loggers in reverse order to ensure the internal logger is reset last. :rtype: None

Danger

Resseting loggers is extremely important for unittests. Because they’re global, loggers have tendency to leak and pollute their state between multiple test calls.

set_levels(ctx, param, value)[source]#

Set level of all loggers configured on the option.

Save the verbosity level name in the context.

Also prints the chosen value as a debug message via the internal click_extra logger.

Return type:

None

logger_name: str#

The ID of the logger to set the level to.

This will be provided to logging.getLogger method to fetch the logger object, and as such, can be a dot-separated string to build hierarchical loggers.

click_extra.parameters module#

Our own flavor of Option, Argument and parameters.

Also implements environment variable utilities.

click_extra.parameters.auto_envvar(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() and click.core.Option.resolve_envvar_value().

Return type:

str | None

click_extra.parameters.extend_envvars(envvars_1, envvars_2)[source]#

Utility to build environment variables value to be fed to options.

Variable names are deduplicated while preserving their initial order.

Returns a tuple of environment variable strings. The result is ready to be used as the envvar parameter for options or arguments.

Return type:

tuple[str, ...]

click_extra.parameters.normalize_envvar(envvar)[source]#

Utility to normalize an environment variable name.

The normalization process separates all contiguous alphanumeric string segments, eliminate empty strings, join them with an underscore and uppercase the result.

Return type:

str

click_extra.parameters.all_envvars(param, ctx, normalize=False)[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().

If normalize is True, the returned value is normalized. By default it is False to perfectly reproduce the current behavior of Click, which is subject to discussions.

Return type:

tuple[str, ...]

click_extra.parameters.search_params(params, klass, 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.

  • unique (bool) – if True, raise an error if more than one parameter of the provided klass is found.

Return type:

list[Parameter] | Parameter | None

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 cached self.excluded_params property to compute the default value on first use.

SEP: str = '.'#

Use a dot . as a separator between levels of the tree-like parameter structure.

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 of leaf.

Return type:

Any

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

Get in the tree_dict the value located at the path.

Return type:

Any | None

flatten_tree_dict(tree_dict, parent_key=None)[source]#

Recursively traverse the tree-like dict and produce a flat dict whose keys are path and values are the leaf’s content.

Return type:

dict[str, Any]

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.

Return type:

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

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.StringParamType'>: <class 'str'>, <class 'click.types.IntParamType'>: <class 'int'>, <class 'click.types.FloatParamType'>: <class 'float'>, <class 'click.types.BoolParamType'>: <class 'bool'>, <class 'click.types.UUIDParameterType'>: <class 'str'>, <class 'click.types.UnprocessedParamType'>: <class 'str'>, <class 'click.types.File'>: <class 'str'>, <class 'click.types.Path'>: <class 'str'>, <class 'click.types.Choice'>: <class 'str'>, <class 'click.types.IntRange'>: <class 'int'>, <class 'click.types.FloatRange'>: <class 'float'>, <class 'click.types.DateTime'>: <class 'str'>, <class 'click.types.Tuple'>: <class 'list'>}#

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.

Return type:

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

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:

None

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.

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.

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 cached self.excluded_params property to compute the default value on first use.

default: t.Union[t.Any, t.Callable[[], t.Any]]#
type: types.ParamType#
is_flag: bool#
is_bool_flag: bool#
flag_value: t.Any#
name: t.Optional[str]#
opts: t.List[str]#
secondary_opts: t.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 a click_extra.raw_args metadata entry to the context.

click_extra.platforms module#

Helpers and utilities to identify platforms.

Everything here can be aggressively cached and frozen, as it’s only compute platform-dependent values.

See also

A nice alternative would be to use the excellent distro package, but it does not yet support detection of macOS and Windows.

click_extra.platforms.is_aix()[source]#

Return True only if current platform is of the AIX family.

Return type:

bool

click_extra.platforms.is_cygwin()[source]#

Return True only if current platform is of the Cygwin family.

Return type:

bool

click_extra.platforms.is_freebsd()[source]#

Return True only if current platform is of the FreeBSD family.

Return type:

bool

click_extra.platforms.is_hurd()[source]#

Return True only if current platform is of the GNU/Hurd family.

Return type:

bool

click_extra.platforms.is_linux()[source]#

Return True only if current platform is of the Linux family.

Excludes WSL1 and WSL2 from this check to avoid false positives.

Return type:

bool

click_extra.platforms.is_macos()[source]#

Return True only if current platform is of the macOS family.

Return type:

bool

click_extra.platforms.is_netbsd()[source]#

Return True only if current platform is of the NetBSD family.

Return type:

bool

click_extra.platforms.is_openbsd()[source]#

Return True only if current platform is of the OpenBSD family.

Return type:

bool

click_extra.platforms.is_solaris()[source]#

Return True only if current platform is of the Solaris family.

Return type:

bool

click_extra.platforms.is_sunos()[source]#

Return True only if current platform is of the SunOS family.

Return type:

bool

click_extra.platforms.is_windows()[source]#

Return True only if current platform is of the Windows family.

Return type:

bool

click_extra.platforms.is_wsl1()[source]#

Return True only if current platform is Windows Subsystem for Linux v1. :rtype: bool

Caution

The only difference between WSL1 and WSL2 is the case of the kernel release version:

  • WSL 1:

    $ uname -r
    4.4.0-22572-Microsoft
    
  • WSL 2:

    $ uname -r
    5.10.102.1-microsoft-standard-WSL2
    
click_extra.platforms.is_wsl2()[source]#

Return True only if current platform is Windows Subsystem for Linux v2.

Return type:

bool

class click_extra.platforms.Platform(id, name)[source]#

Bases: object

A platform can identify multiple distributions or OSes with the same characteristics.

It has a unique ID, a human-readable name, and boolean to flag current platform.

id: str#

Unique ID of the platform.

name: str#

User-friendly name of the platform.

current: bool#

True if current environment runs on this platform.

click_extra.platforms.AIX = Platform(id='aix', name='AIX', current=False)#

Identify distributions of the AIX family.

click_extra.platforms.CYGWIN = Platform(id='cygwin', name='Cygwin', current=False)#

Identify distributions of the Cygwin family.

click_extra.platforms.FREEBSD = Platform(id='freebsd', name='FreeBSD', current=False)#

Identify distributions of the FreeBSD family.

click_extra.platforms.HURD = Platform(id='hurd', name='GNU/Hurd', current=False)#

Identify distributions of the GNU/Hurd family.

click_extra.platforms.LINUX = Platform(id='linux', name='Linux', current=True)#

Identify distributions of the Linux family.

click_extra.platforms.MACOS = Platform(id='macos', name='macOS', current=False)#

Identify distributions of the macOS family.

click_extra.platforms.NETBSD = Platform(id='netbsd', name='NetBSD', current=False)#

Identify distributions of the NetBSD family.

click_extra.platforms.OPENBSD = Platform(id='openbsd', name='OpenBSD', current=False)#

Identify distributions of the OpenBSD family.

click_extra.platforms.SOLARIS = Platform(id='solaris', name='Solaris', current=False)#

Identify distributions of the Solaris family.

click_extra.platforms.SUNOS = Platform(id='sunos', name='SunOS', current=False)#

Identify distributions of the SunOS family.

click_extra.platforms.WINDOWS = Platform(id='windows', name='Windows', current=False)#

Identify distributions of the Windows family.

click_extra.platforms.WSL1 = Platform(id='wsl1', name='Windows Subsystem for Linux v1', current=False)#

Identify Windows Subsystem for Linux v1.

click_extra.platforms.WSL2 = Platform(id='wsl2', name='Windows Subsystem for Linux v2', current=False)#

Identify Windows Subsystem for Linux v2.

class click_extra.platforms.Group(id, name, platforms=<factory>, platform_ids=<factory>, icon=None)[source]#

Bases: object

A Group identify a collection of Platform.

Used to group platforms of the same family.

id: str#

Unique ID of the group.

name: str#

User-friendly description of a group.

platforms: tuple[Platform, ...]#

Sorted list of platforms that belong to this group.

platform_ids: frozenset[str]#

Set of platform IDs that belong to this group.

Used to test platform overlaps between groups.

icon: str | None = None#

Optional icon of the group.

isdisjoint(other)[source]#

Return True if the group has no platforms in common with other.

Return type:

bool

fullyintersects(other)[source]#

Return True if the group has all platforms in common with other.

We cannot just compare Groups with the == equality operator as the latter takes all attributes into account, as per dataclass default behavior.

Return type:

bool

issubset(other)[source]#
Return type:

bool

issuperset(other)[source]#
Return type:

bool

click_extra.platforms.ALL_PLATFORMS: Group = Group(id='all_platforms', name='Any platforms', platform_ids=frozenset({'linux', 'macos', 'wsl1', 'windows', 'openbsd', 'freebsd', 'hurd', 'solaris', 'sunos', 'netbsd', 'wsl2', 'aix', 'cygwin'}))#

All recognized platforms.

click_extra.platforms.ALL_WINDOWS = Group(id='all_windows', name='Any Windows', platform_ids=frozenset({'windows'}))#

All Windows operating systems.

click_extra.platforms.UNIX = Group(id='unix', name='Any Unix', platform_ids=frozenset({'linux', 'macos', 'wsl1', 'openbsd', 'freebsd', 'hurd', 'solaris', 'sunos', 'netbsd', 'wsl2', 'aix', 'cygwin'}))#

All Unix-like operating systems and compatibility layers.

click_extra.platforms.UNIX_WITHOUT_MACOS = Group(id='unix_without_macos', name='Any Unix but macOS', platform_ids=frozenset({'linux', 'wsl1', 'openbsd', 'freebsd', 'hurd', 'solaris', 'sunos', 'netbsd', 'wsl2', 'aix', 'cygwin'}))#

All Unix platforms, without macOS.

This is useful to avoid macOS-specific workarounds on Unix platforms.

click_extra.platforms.BSD = Group(id='bsd', name='Any BSD', platform_ids=frozenset({'sunos', 'macos', 'openbsd', 'netbsd', 'freebsd'}))#

All BSD platforms.

Note

Are considered of this family (according Wikipedia):

  • 386BSD (FreeBSD, NetBSD, OpenBSD, DragonFly BSD)

  • NeXTSTEP

  • Darwin (macOS, iOS, audioOS, iPadOS, tvOS, watchOS, bridgeOS)

  • SunOS

  • Ultrix

click_extra.platforms.BSD_WITHOUT_MACOS = Group(id='bsd_without_macos', name='Any BSD but macOS', platform_ids=frozenset({'openbsd', 'netbsd', 'freebsd', 'sunos'}))#

All BSD platforms, without macOS.

This is useful to avoid macOS-specific workarounds on BSD platforms.

click_extra.platforms.ALL_LINUX = Group(id='all_linux', name='Any Linux', platform_ids=frozenset({'linux'}))#

All Unix platforms based on a Linux kernel.

Note

Are considered of this family (according Wikipedia):

  • Android

  • ChromeOS

  • any other distribution

click_extra.platforms.LINUX_LAYERS = Group(id='linux_layers', name='Any Linux compatibility layers', platform_ids=frozenset({'wsl1', 'wsl2'}))#

Interfaces that allows Linux binaries to run on a different host system.

Note

Are considered of this family (according Wikipedia):

  • Windows Subsystem for Linux

click_extra.platforms.SYSTEM_V = Group(id='system_v', name='Any Unix derived from AT&T System Five', platform_ids=frozenset({'aix', 'solaris'}))#

All Unix platforms derived from AT&T System Five.

Note

Are considered of this family (according Wikipedia):

  • A/UX

  • AIX

  • HP-UX

  • IRIX

  • OpenServer

  • Solaris

  • OpenSolaris

  • Illumos

  • Tru64

  • UNIX

  • UnixWare

click_extra.platforms.UNIX_LAYERS = Group(id='unix_layers', name='Any Unix compatibility layers', platform_ids=frozenset({'cygwin'}))#

Interfaces that allows Unix binaries to run on a different host system.

Note

Are considered of this family (according Wikipedia):

  • Cygwin

  • Darling

  • Eunice

  • GNV

  • Interix

  • MachTen

  • Microsoft POSIX subsystem

  • MKS Toolkit

  • PASE

  • P.I.P.S.

  • PWS/VSE-AF

  • UNIX System Services

  • UserLAnd Technologies

  • Windows Services for UNIX

click_extra.platforms.OTHER_UNIX = Group(id='other_unix', name='Any other Unix', platform_ids=frozenset({'hurd'}))#

All other Unix platforms.

Note

Are considered of this family (according Wikipedia):

  • Coherent

  • GNU/Hurd

  • HarmonyOS

  • LiteOS

  • LynxOS

  • Minix

  • MOS

  • OSF/1

  • QNX

  • BlackBerry 10

  • Research Unix

  • SerenityOS

click_extra.platforms.NON_OVERLAPPING_GROUPS: frozenset[click_extra.platforms.Group] = frozenset({Group(id='system_v', name='Any Unix derived from AT&T System Five', platform_ids=frozenset({'aix', 'solaris'})), Group(id='other_unix', name='Any other Unix', platform_ids=frozenset({'hurd'})), Group(id='unix_layers', name='Any Unix compatibility layers', platform_ids=frozenset({'cygwin'})), Group(id='all_windows', name='Any Windows', platform_ids=frozenset({'windows'})), Group(id='all_linux', name='Any Linux', platform_ids=frozenset({'linux'})), Group(id='linux_layers', name='Any Linux compatibility layers', platform_ids=frozenset({'wsl1', 'wsl2'})), Group(id='bsd', name='Any BSD', platform_ids=frozenset({'sunos', 'macos', 'openbsd', 'netbsd', 'freebsd'}))})#

Non-overlapping groups.

click_extra.platforms.EXTRA_GROUPS: frozenset[click_extra.platforms.Group] = frozenset({Group(id='unix', name='Any Unix', platform_ids=frozenset({'linux', 'macos', 'wsl1', 'openbsd', 'freebsd', 'hurd', 'solaris', 'sunos', 'netbsd', 'wsl2', 'aix', 'cygwin'})), Group(id='bsd_without_macos', name='Any BSD but macOS', platform_ids=frozenset({'openbsd', 'netbsd', 'freebsd', 'sunos'})), Group(id='all_platforms', name='Any platforms', platform_ids=frozenset({'linux', 'macos', 'wsl1', 'windows', 'openbsd', 'freebsd', 'hurd', 'solaris', 'sunos', 'netbsd', 'wsl2', 'aix', 'cygwin'})), Group(id='unix_without_macos', name='Any Unix but macOS', platform_ids=frozenset({'linux', 'wsl1', 'openbsd', 'freebsd', 'hurd', 'solaris', 'sunos', 'netbsd', 'wsl2', 'aix', 'cygwin'}))})#

Overlapping groups, defined for convenience.

click_extra.platforms.ALL_GROUPS: frozenset[click_extra.platforms.Group] = frozenset({Group(id='system_v', name='Any Unix derived from AT&T System Five', platform_ids=frozenset({'aix', 'solaris'})), Group(id='other_unix', name='Any other Unix', platform_ids=frozenset({'hurd'})), Group(id='bsd_without_macos', name='Any BSD but macOS', platform_ids=frozenset({'openbsd', 'netbsd', 'freebsd', 'sunos'})), Group(id='unix_layers', name='Any Unix compatibility layers', platform_ids=frozenset({'cygwin'})), Group(id='all_windows', name='Any Windows', platform_ids=frozenset({'windows'})), Group(id='unix_without_macos', name='Any Unix but macOS', platform_ids=frozenset({'linux', 'wsl1', 'openbsd', 'freebsd', 'hurd', 'solaris', 'sunos', 'netbsd', 'wsl2', 'aix', 'cygwin'})), Group(id='all_linux', name='Any Linux', platform_ids=frozenset({'linux'})), Group(id='unix', name='Any Unix', platform_ids=frozenset({'linux', 'macos', 'wsl1', 'openbsd', 'freebsd', 'hurd', 'solaris', 'sunos', 'netbsd', 'wsl2', 'aix', 'cygwin'})), Group(id='linux_layers', name='Any Linux compatibility layers', platform_ids=frozenset({'wsl1', 'wsl2'})), Group(id='all_platforms', name='Any platforms', platform_ids=frozenset({'linux', 'macos', 'wsl1', 'windows', 'openbsd', 'freebsd', 'hurd', 'solaris', 'sunos', 'netbsd', 'wsl2', 'aix', 'cygwin'})), Group(id='bsd', name='Any BSD', platform_ids=frozenset({'sunos', 'macos', 'openbsd', 'netbsd', 'freebsd'}))})#

All groups.

click_extra.platforms.ALL_OS_LABELS: frozenset[str] = frozenset({'AIX', 'Cygwin', 'FreeBSD', 'GNU/Hurd', 'Linux', 'NetBSD', 'OpenBSD', 'Solaris', 'SunOS', 'Windows', 'Windows Subsystem for Linux v1', 'Windows Subsystem for Linux v2', 'macOS'})#

Sets of all recognized labels.

click_extra.platforms.reduce(items)[source]#

Reduce a collection of Group and Platform to a minimal set.

Returns a deduplicated set of Group and Platform that covers the same exact platforms as the original input, but group as much platforms as possible, to reduce the number of items. :rtype: set[Group | Platform]

Hint

Maybe this could be solved with some Euler diagram algorithms, like those implemented in eule.

This is being discussed upstream at trouchet/eule#120.

click_extra.platforms.os_label(os_id)[source]#

Return platform label for user-friendly output.

Return type:

str | None

click_extra.platforms.current_os()[source]#

Return the current platform.

Return type:

Platform

click_extra.platforms.CURRENT_OS_LABEL: str = 'Linux'#

Constants about the current platform.

click_extra.pygments module#

Helpers and utilities to allow Pygments to parse and render ANSI codes.

click_extra.pygments.DEFAULT_TOKEN_TYPE = Token.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 the token_type to be colorized.

Todo

Allow multiple token_type to be configured for colorization (if traditions are changed on Pygments’ side).

filter(lexer, stream)[source]#

Transform each token of token_type type into a stream of ANSI tokens.

Return type:

Iterator[tuple[_TokenType, str]]

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-.

class click_extra.pygments.AnsiLexerFiltersMixin(*args, **kwargs)[source]#

Bases: Lexer

Adds a TokenMergeFilter and AnsiOutputFilter 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 the TokenMergeFilter filter to reduce noise and have each contiguous output lines part of the same single token.

Then we apply our custom AnsiOutputFilter to transform any Generic.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.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.algebra.GAPConsoleLexer'>: <class 'pygments.lexer.AnsiGAPConsoleLexer'>, <class 'pygments.lexers.julia.JuliaConsoleLexer'>: <class 'pygments.lexer.AnsiJuliaConsoleLexer'>, <class 'pygments.lexers.matlab.MatlabSessionLexer'>: <class 'pygments.lexer.AnsiMatlabSessionLexer'>, <class 'pygments.lexers.special.OutputLexer'>: <class 'pygments.lexer.AnsiOutputLexer'>, <class 'pygments.lexers.sql.PostgresConsoleLexer'>: <class 'pygments.lexer.AnsiPostgresConsoleLexer'>, <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.sql.SqliteConsoleLexer'>: <class 'pygments.lexer.AnsiSqliteConsoleLexer'>, <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'>}#

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 from pygments_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.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.

class click_extra.sphinx.PatchedViewList(initlist=None, source=None, items=None, parent=None, parent_offset=None)[source]#

Bases: ViewList

Force the rendering of ANSI shell session.

Replaces the .. sourcecode:: shell-session code block produced by .. click:run:: directive with an ANSI Shell Session: .. code-block:: ansi-shell-session.

.. sourcecode:: shell-session has been released in Pallets-Sphinx-Themes 2.1.0.

append(*args, **kwargs)[source]#

Search the default code block and replace it with our own version.

Return type:

None

click_extra.sphinx.setup(app)[source]#

Register new directives, augmented with ANSI coloring.

Return type:

None

New directives:
  • .. click:example::

  • .. click:run::

Danger

This function activates lots of monkey-patches:

  • sphinx.highlighting.PygmentsBridge is updated to set its default HTML formatter to an ANSI capable one for the whole Sphinx app.

  • pallets_sphinx_themes.themes.click.domain.ViewList is patched to force an ANSI lexer on the rST code block.

  • pallets_sphinx_themes.themes.click.domain.ExampleRunner is replaced with click_extra.testing.ExtraCliRunner to have full control of contextual color settings by the way of the color parameter. It also produce unfiltered ANSI codes so that the other PatchedViewList monkey-patch can do its job and render colors in the HTML output.

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.

Return type:

str | None

click_extra.tabulate.render_csv(tabular_data, headers=(), **kwargs)[source]#
Return type:

None

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:

None

click_extra.tabulate.render_table(tabular_data, headers=(), **kwargs)[source]#

Render a table with tabulate and output it via echo.

Return type:

None

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:

None

click_extra.telemetry module#

Telemetry utilities.

class click_extra.telemetry.TelemetryOption(param_decls=None, default=False, expose_value=False, envvar=None, show_envvar=True, help='Collect telemetry and usage data.', **kwargs)[source]#

Bases: ExtraOption

A pre-configured --telemetry/--no-telemetry option flag.

Respects the proposed DO_NOT_TRACK environment variable as a unified standard to opt-out of telemetry for TUI/console apps.

The DO_NOT_TRACK convention takes precedence over the user-defined environment variables and the auto-generated values.

save_telemetry(ctx, param, value)[source]#

Save the option value in the context, in ctx.telemetry.

Return type:

None

click_extra.testing module#

CLI testing and simulation of their execution.

click_extra.testing.INDENT = '  '#

Constants for rendering of CLI execution.

click_extra.testing.EnvVars#

Type for dict-like environment variables.

alias of Mapping[str, Optional[str]]

click_extra.testing.NestedArgs#

Types for arbitrary nested CLI arguments.

Arguments can be str, pathlib.Path objects or None values.

alias of Iterable[Union[str, Path, None, Iterable[NestedArgs]]]

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.

Return type:

tuple[str, ...]

click_extra.testing.format_cli_prompt(cmd_args, extra_env=None)[source]#

Simulate the console prompt used to invoke the CLI.

Return type:

str

click_extra.testing.print_cli_run(args, result, env=None)[source]#

Prints the full simulation of CLI execution, including output.

Mostly used to print debug traces to user or in test results.

Return type:

None

click_extra.testing.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 no extend content are provided.

Environment variables are expected to be a dict of str:str.

Return type:

Optional[Mapping[str, str | None]]

click_extra.testing.run_cmd(*args, extra_env=None, print_output=True)[source]#

Run a system command, print output and return results.

Return type:

tuple[int, str, str]

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.

flush()[source]#

Does nothing.

Return type:

None

write(b)[source]#

Write bytes to file.

Return the number of bytes written.

Return type:

int

class click_extra.testing.StreamMixer(mix_stderr)[source]#

Bases: object

Mixes <stdout> and <stderr> streams if mix_stderr=True.

The result is available in the output attribute.

If mix_stderr=False, the <stdout> and <stderr> streams are kept independent and the output is the same as the <stdout> stream.

Caution

This has been proposed upstream to Click project but has not been merged yet.

class click_extra.testing.ExtraResult(runner, stdout_bytes, stderr_bytes, output_bytes, return_value, exit_code, exception, exc_info=None)[source]#

Bases: Result

Like click.testing.Result, with finer <stdout> and <stderr> streams.

Caution

This has been proposed upstream to Click project but has not been merged yet.

Same as original but adds output_bytes parameter.

Also makes stderr_bytes mandatory.

stderr_bytes: bytes#

Makes stderr_bytes mandatory.

property output: str#

The terminal output as unicode string, as the user would see it.

Caution

Contrary to original click.testing.Result.output, it is not a proxy for self.stdout. It now possess its own stream to mix <stdout> and <stderr> depending on the mix_stderr value.

property stderr: str#

The standard error as unicode string.

Caution

Contrary to original click.testing.Result.stderr, it no longer raise an exception, and always returns the <stderr> string.

class click_extra.testing.ExtraCliRunner(charset='utf-8', env=None, echo_stdin=False, mix_stderr=True)[source]#

Bases: CliRunner

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

env: t.Mapping[str, t.Optional[str]]#
force_color: bool = False#

Global class attribute to override the color parameter in invoke.

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.

isolation(input=None, env=None, color=False)[source]#

Copy of click.testing.CliRunner.isolation() with extra features. :rtype: Iterator[tuple[BytesIO, BytesIO, BytesIO]]

  • An additional output stream is returned, which is a mix of <stdout> and <stderr> streams if mix_stderr=True.

  • Always returns the <stderr> stream.

Caution

This is a hard-copy of the modified isolation() method from click#2523 PR which has not been merged upstream yet.

Todo

Reduce the code duplication here by using clever monkeypatching?

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: ExtraResult

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 via force_color attribute.

  • Adds a special case in the form of color="forced" parameter, which allows colored output to be kept, while forcing the initialization of Context.color = True. This is not allowed in current implementation of click.testing.CliRunner.invoke() because of colliding parameters.

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

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

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

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

  • *args –

    can be nested iterables composed of str, pathlib.Path objects and None values. The nested structure will be flattened and None values will be filtered out. Then all elements will be casted to str. See args_cleanup() for details.

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

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

  • catch_exceptions (bool) – same as click.testing.CliRunner.invoke().

  • color (Union[bool, Literal['forced'], None]) – If a boolean, the parameter will be passed as-is to click.testing.CliRunner.isolation(). If "forced", the parameter will be passed as True to click.testing.CliRunner.isolation() and an extra color=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:

Result

click_extra.timer module#

Command execution time measurement.

class click_extra.timer.TimerOption(param_decls=None, default=False, expose_value=False, 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"].

print_timer()[source]#

Compute and print elapsed execution time.

register_timer_on_close(ctx, param, value)[source]#

Callback setting up all timer’s machinery.

Computes and print the execution time at the end of the CLI, if option has been activated.

Return type:

None

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:
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:

FrameType

property module: module#

Returns the module in which the CLI resides.

property module_name: str#

Returns the full module name or ``__main__`.

property module_file: str | None#

Returns the module’s file full path.

property module_version: str | None#

Returns the string found in the local __version__ variable.

property package_name: str | None#

Returns the package name.

property package_version: str | None#

Returns the package version if installed.

Will raise an error if the package is not installed, or if the package version cannot be determined from the package metadata.

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 prog_name: str | None#

Return the name of the CLI, from Click’s point of view.

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:

str

render_message(template=None)[source]#

Render the version string from the provided template.

Accepts a custom template as parameter, otherwise uses the default self.colored_template() produced by the instance.

Return type:

str

default: t.Union[t.Any, t.Callable[[], t.Any]]#
type: types.ParamType#
is_flag: bool#
is_bool_flag: bool#
flag_value: t.Any#
name: t.Optional[str]#
opts: t.List[str]#
secondary_opts: t.List[str]#
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)?

print_and_exit(ctx, param, value)[source]#

Print the version string and exits.

Also stores all version string elements in the Context’s meta dict.

Return type:

None