Skip to content
Myr

Apply format guidelines to commits since latest 8.3.2 release (#3343)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Rowlando13 · committed by GitHub · parents 4a35225, bb59ba0 · Browse files · 9 files+178 added−82 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

9 files+178 added−82 removed

  • other:+178 added−82 removed

9 files+178 added−82 removed

modified:docs/arguments.md+29 added-9 removed
modified:docs/commands-and-groups.md+37 added-12 removed
1 unmodified line
23```{currentmodule} click4```56Commands and Groups are the building blocks for Click applications. {class}`Command` wraps a function to make it into a cli command. {class}`Group` wraps Commands and Groups to make them into applications. {class}`Context` is how groups and commands communicate.6Commands and Groups are the building blocks for Click applications.7{class}`Command` wraps a function to make it into a cli command. {class}`Group`8wraps Commands and Groups to make them into applications. {class}`Context` is9how groups and commands communicate.1011```{contents}12---13depth: 2
21 unmodified lines
35```3637### Renaming Commands3836By default the command is the function name with underscores replaced by dashes. To change this pass the desired name into the first positional argument.39By default the command is the function name with underscores replaced by dashes.40To change this pass the desired name into the first positional argument.4142```{eval-rst}43.. click:example::44
27 unmodified lines
72## Groups7374### Basic Group Example7572A group wraps one or more commands. After being wrapped, the commands are nested under that group. You can see that on the help pages and in the execution. By default, invoking the group with no command shows the help page.76A group wraps one or more commands. After being wrapped, the commands are nested77under that group. You can see that on the help pages and in the execution. By78default, invoking the group with no command shows the help page.7980```{eval-rst}81.. click:example::82
20 unmodified lines
103 invoke(greeting, args=['say-hello'])104 invoke(greeting, args=['say-hello', '--help'])105```106101As you can see from the above example, the function wrapped by the group decorator executes unless it is interrupted (for example by calling the help).107As you can see from the above example, the function wrapped by the group108decorator executes unless it is interrupted (for example by calling the help).109110### Renaming Groups111105To have a name other than the decorated function name as the group name, pass it in as the first positional argument.112To have a name other than the decorated function name as the group name, pass it113in as the first positional argument.114115```{eval-rst}116.. click:example::117
13 unmodified lines
131```132133### Group Invocation Without Command134127By default, if a group is passed without a command, the group is not invoked and a command automatically passes `--help`. To change this, pass `invoke_without_command=True` to the group. The context object also includes information about whether or not the group invocation would go to a command nested under it.135By default, if a group is passed without a command, the group is not invoked and136a command automatically passes `--help`. To change this, pass137`invoke_without_command=True` to the group. The context object also includes138information about whether or not the group invocation would go to a command139nested under it.140141```{eval-rst}142.. click:example::143
44 unmodified lines
188 invoke(greeting, args=['goodbye', '--count', '2'])189 invoke(greeting)190```191180Additionally parameters for a given group belong only to that group and not to the commands under it. What this means is that options and arguments for a specific command have to be specified *after* the command name itself, but *before* any other command names.192Additionally parameters for a given group belong only to that group and not to193the commands under it. What this means is that options and arguments for a194specific command have to be specified *after* the command name itself, but195*before* any other command names.196182This behavior is observable with the `--help` option. Suppose we have a group called `tool` containing a command called `sub`.197This behavior is observable with the `--help` option. Suppose we have a group198called `tool` containing a command called `sub`.199200- `tool --help` returns the help for the whole program (listing subcommands).201- `tool sub --help` returns the help for the `sub` subcommand.186- But `tool --help sub` treats `--help` as an argument for the main program. Click then invokes the callback for `--help`, which prints the help and aborts the program before click can process the subcommand.202- But `tool --help sub` treats `--help` as an argument for the main program.203 Click then invokes the callback for `--help`, which prints the help and aborts204 the program before click can process the subcommand.205206### Arbitrary Nesting207208{class}`Commands <Command>` are attached to a {class}`Group`. Multiple groups can be attached to another group. Groups containing multiple groups can be attached to a group, and so on. To invoke a command nested under multiple groups, all the groups under which it is nested must be invoked.
24 unmodified lines
233```234235### Lazily Attaching Commands236219Most examples so far have attached the commands to a group immediately, but commands may be registered later. This could be used to split commands into multiple Python modules. Regardless of how they are attached, the commands are invoked identically.237Most examples so far have attached the commands to a group immediately, but238commands may be registered later. This could be used to split commands into239multiple Python modules. Regardless of how they are attached, the commands are240invoked identically.241242```{eval-rst}243.. click:example::244
21 unmodified lines
266The {class}`Context` object is how commands and groups communicate.267268### Auto Envvar Prefix269249Automatically built environment variables are supported for options only. To enable this feature, the `auto_envvar_prefix` parameter needs to be passed to the script that is invoked. Each command and parameter is then added as an uppercase underscore-separated variable. If you have a subcommand250called `run` taking an option called `reload` and the prefix is `WEB`, then the variable is `WEB_RUN_RELOAD`.270Automatically built environment variables are supported for options only. To271enable this feature, the `auto_envvar_prefix` parameter needs to be passed to272the script that is invoked. Each command and parameter is then added as an273uppercase underscore-separated variable. If you have a subcommand274called `run` taking an option called `reload` and the prefix is `WEB`, then the275variable is `WEB_RUN_RELOAD`.276277Example usage:278279```{eval-rst}
147 unmodified lines
modified:docs/commands.md+2 added-1 removed
1 unmodified line
23```{currentmodule} click4```56In addition to the capabilities covered in the previous section, Groups have more advanced capabilities that leverage the Context.6In addition to the capabilities covered in the previous section, Groups have7more advanced capabilities that leverage the Context.89```{contents}10---11depth: 1
427 unmodified lines
modified:docs/options.md+80 added-31 removed
5 unmodified lines
6.. currentmodule:: click7```89Adding options to commands can be accomplished with the {func}`option`10decorator. At runtime the decorator invokes the {class}`Option` class. Options in Click are distinct from {ref}`positional arguments <arguments>`.10decorator. At runtime the decorator invokes the {class}`Option` class. Options11in Click are distinct from {ref}`positional arguments <arguments>`.1213Useful and often used kwargs are:1415- `default`: Passes a default.
8 unmodified lines
24```2526## Option Decorator2727The {func}`option()` decorator is usually passed two positional arguments: the option name and the decorated function argument name.28The {func}`option()` decorator is usually passed two positional arguments: the29option name and the decorated function argument name.3031```{eval-rst}32.. click:example::33
7 unmodified lines
4142 invoke(echo, args=['--help'])43```4443However, if the decorated function argument name is not passed in, then Click will try to infer it. A simple way to name the option so that Click will infer it correctly is by taking the function argument, adding two dashes to the front and converting underscores to dashes.45However, if the decorated function argument name is not passed in, then Click46will try to infer it. A simple way to name the option so that Click will infer47it correctly is by taking the function argument, adding two dashes to the front48and converting underscores to dashes.4950```{eval-rst}51.. click:example::52
6 unmodified lines
5960 invoke(echo, args=['--string-to-echo', 'Hi!'])61```6258More formally, Click will try to infer the decorated function argument name as follows:63More formally, Click will try to infer the decorated function argument name as64follows:65661. If a positional argument is a valid [Python identifier](https://docs.python.org/3/reference/lexical_analysis.html#identifiers) (and thus does not have dashes), it is chosen.612. If multiple positional arguments are prefixed with `--`, the first one declared is chosen.672. If multiple positional arguments are prefixed with `--`, the first one68 declared is chosen.693. Otherwise, the first positional argument prefixed with `-` is chosen.7064To get the argument name, the chosen positional argument is converted to lower case, a leading `-` or `--` is removed if found, and any remaining `-` characters are replaced with `_`.71To get the argument name, the chosen positional argument is converted to lower72case, a leading `-` or `--` is removed if found, and any remaining `-`73characters are replaced with `_`.7475```{eval-rst}76.. list-table:: Examples77 :widths: 15 15
18 unmodified lines
96```9798## Basic Example9991A simple {class}`click.Option` takes one option name. By default, it's assumed that the decorated function argument is not required and the expected type is `str`. If the decorated function takes a positional argument but the option is not passed with the command, then `None` is passed.100A simple {class}`click.Option` takes one option name. By default, it's assumed101that the decorated function argument is not required and the expected type is102`str`. If the decorated function takes a positional argument but the option is103not passed with the command, then `None` is passed.104105```{eval-rst}106.. click:example::107
17 unmodified lines
125```126127## Setting a Default128117Instead of setting the `type`, you may set a default and Click will try to infer the type.129Instead of setting the `type`, you may set a default and Click will try to infer130the type.131132```{eval-rst}133.. click:example::134
8 unmodified lines
143```144145## Multi Value Options146134To make an option take multiple values, pass in `nargs`. Note you may pass in any positive integer, but not -1. The values are passed to the decorated function as a tuple.147To make an option take multiple values, pass in `nargs`. Note you may pass in148any positive integer, but not -1. The values are passed to the decorated149function as a tuple.150151```{eval-rst}152.. click:example::153
16 unmodified lines
170```{versionadded} 4.0171```172173By setting `nargs` to a specific number, each item in159the resulting tuple is of the same type. Alternatively, you might want to use different types for different indexes in174the resulting tuple is of the same type. Alternatively, you might want to use175different types for different indexes in176the tuple. For this you can directly specify a tuple as `type`:177178```{eval-rst}179.. click:example::
29 unmodified lines
209(multiple-options)=210211## Multiple Options212197The multiple options format allows options to take an arbitrary number of arguments (which is called variadic). The arguments are passed to the decorated function as a tuple. If set, `default` must be a list or tuple. Setting a string as `default` will be interpreted as a list of characters.213The multiple options format allows options to take an arbitrary number of214arguments (which is called variadic). The arguments are passed to the decorated215function as a tuple. If set, `default` must be a list or tuple. Setting a string216as `default` will be interpreted as a list of characters.217218```{eval-rst}219.. click:example::220
10 unmodified lines
231```232233## Counting234216To count the occurrence of an option, set `count=True`. If the option is not passed on the command line, then the count is 0. Counting is commonly used for verbosity.235To count the occurrence of an option, set `count=True`. If the option is not236passed on the command line, then the count is 0. Counting is commonly used for237verbosity.238239```{eval-rst}240.. click:example::241
11 unmodified lines
253(option-boolean-flag)=254255## Boolean256236Boolean options (boolean flags) take the values `True` or `False`. The simplest case sets the default value to `False` if the flag is not passed, and `True` if it is.257Boolean options (boolean flags) take the values `True` or `False`. The simplest258case sets the default value to `False` if the flag is not passed, and `True` if259it is.260261```{eval-rst}262.. click:example::263
14 unmodified lines
278 invoke(info, args=['--shout'])279280```281259To implement this more explicitly, declare `--{on-option}/--{off-option}`. Click will automatically set `is_flag=True`.282To implement this more explicitly, declare `--{on-option}/--{off-option}`. Click283will automatically set `is_flag=True`.284285```{eval-rst}286.. click:example::287
15 unmodified lines
303```304305Use cases for this more explicit pattern include:306283* The default can be dynamic so the user can explicitly specify the option with either on or off option, or pass in no option to use the dynamic default.307* The default can be dynamic so the user can explicitly specify the option with308 either on or off option, or pass in no option to use the dynamic default.309* Shell scripts sometimes want to be explicit even when it's the default285* Shell aliases can set a flag, then an invocation can add a negation of the flag310* Shell aliases can set a flag, then an invocation can add a negation of the311 flag312287If a forward slash(`/`) is contained in your option name already, you can split the parameters using `;`. In Windows `/` is commonly used as the prefix character.313If a forward slash(`/`) is contained in your option name already, you can split314the parameters using `;`. In Windows `/` is commonly used as the prefix315character.316317```{eval-rst}318.. click:example::319
5 unmodified lines
325326```{versionchanged} 6.0327```328301If you want to define an alias for the second option only, then you will need to use leading whitespace to disambiguate the format string.329If you want to define an alias for the second option only, then you will need to330use leading whitespace to disambiguate the format string.331332```{eval-rst}333.. click:example::334
13 unmodified lines
348```349350## Flag Value351323To have a flag pass a value to the decorated function set `flag_value`. This automatically sets `is_flag=True`. To mark the flag as default, set `default=True`. Setting flag values can be used to create patterns like this:352To have a flag pass a value to the decorated function set `flag_value`. This353automatically sets `is_flag=True`. To mark the flag as default, set354`default=True`. Setting flag values can be used to create patterns like this:355356```{eval-rst}357.. click:example::358
154 unmodified lines
513```514515Variable names are:516 - [Case-insensitive on Windows but not on other platforms](https://github.com/python/cpython/blob/aa9eb5f757ceff461e6e996f12c89e5d9b583b01/Lib/os.py#L777-L789).486 - Not stripped of whitespace and should match the exact name provided to the `envvar` argument.517 - Not stripped of whitespace and should match the exact name provided to the518 `envvar` argument.519488For flag options, there are two concepts to consider: the activation of the flag driven by the environment variable, and the value of the flag if it is activated.520For flag options, there are two concepts to consider: the activation of the flag521driven by the environment variable, and the value of the flag if it is522activated.523490The values read from environment variables are always strings and will require extra processing. We need to transform these strings into boolean values that will determine if the flag is activated or not.524The values read from environment variables are always strings and will require525extra processing. We need to transform these strings into boolean values that526will determine if the flag is activated or not.527528Here are the rules used to parse environment variable values for flag options:529 - `true`, `1`, `yes`, `on`, `t`, `y` are interpreted as activating the flag494 - `false`, `0`, `no`, `off`, `f`, `n` are interpreted as deactivating the flag495 - The presence of the environment variable without value is interpreted as deactivating the flag530 - `false`, `0`, `no`, `off`, `f`, `n` are interpreted as deactivating the531 flag532 - The presence of the environment variable without value is interpreted as533 deactivating the flag534 - Empty strings are interpreted as deactivating the flag497 - Values are case-insensitive, so the `True`, `TRUE`, `tRuE` strings are all interpreted as activating the flag498 - Values are stripped of leading and trailing whitespace before being interpreted, so the `" True "` string is transformed to `"true"` and thus activates the flag499 - If the flag option has a `flag_value` argument, passing that value in the environment variable will activate the flag, in addition to all the cases described above535 - Values are case-insensitive, so the `True`, `TRUE`, `tRuE` strings are all536 interpreted as activating the flag537 - Values are stripped of leading and trailing whitespace before being538 interpreted, so the `" True "` string is transformed to `"true"` and thus539 activates the flag540 - If the flag option has a `flag_value` argument, passing that value in the541 environment variable will activate the flag, in addition to all the cases542 described above543 - Any other value is interpreted as deactivating the flag544545```{caution}546For boolean flags with a pair of values, the only recognized environment variable is the one provided to the `envvar` argument.547548So an option defined as `--flag\--no-flag`, with a `envvar="FLAG"` parameter, there is no magical `NO_FLAG=<anything>` variable that is recognized. Only the `FLAG=<anything>` environment variable is recognized.549```550508If the flag is activated, its value is set to `flag_value`. Otherwise, the value defaults to `None`.551If the flag is activated, its value is set to `flag_value`. Otherwise, the value552defaults to `None`.553554## Multiple Options from Environment Values555556As options can accept multiple values, pulling in such values from513environment variables (which are strings) is a bit more complex. Click handles this by deferring customization of the behavior to the `type`. For both `multiple` and `nargs` with values other than557environment variables (which are strings) is a bit more complex. Click handles558this by deferring customization of the behavior to the `type`. For both559`multiple` and `nargs` with values other than560`1`, Click will invoke the {meth}`ParamType.split_envvar_value` method to561perform the splitting.562563The default implementation for all types is to split on whitespace. The
22 unmodified lines
586```587588## Other Prefix Characters589544Click can deal with prefix characters besides `-` for options, including `/` and `+`, as well as others. Note that alternative prefix characters are generally used very sparingly if at all within POSIX.590Click can deal with prefix characters besides `-` for options, including `/` and591`+`, as well as others. Note that alternative prefix characters are generally592used very sparingly if at all within POSIX.593594```{eval-rst}595.. click:example::596
7 unmodified lines
604 invoke(chmod, args=['+w'])605 invoke(chmod, args=['-w'])606```607560There are special considerations for using `/` as prefix character. See {ref}`option-boolean-flag` for more.608There are special considerations for using `/` as prefix character. See609{ref}`option-boolean-flag` for more.610611(optional-value)=612613## Optional Value
23 unmodified lines
modified:docs/testing.md+13 added-6 removed
2 unmodified lines
3```{eval-rst}4.. currentmodule:: click.testing5```67Click provides the {ref}`click.testing <testing>` module to help you invoke command line applications and check their behavior.7Click provides the {ref}`click.testing <testing>` module to help you invoke8command line applications and check their behavior.910These tools should only be used for testing since they change11the entire interpreter state for simplicity. They are not thread-safe!12
7 unmodified lines
20## Basic Example2122The key pieces are:23 - {class}`CliRunner` - used to invoke commands as command line scripts.23 - {class}`Result` - returned from {meth}`CliRunner.invoke`. Captures output data, exit code, optional exception, and captures the output as bytes and binary data.24 - {class}`Result` - returned from {meth}`CliRunner.invoke`. Captures output25 data, exit code, optional exception, and captures the output as bytes and26 binary data.2728```{code-block} python29:caption: hello.py30
19 unmodified lines
50```5152## Subcommands5351A subcommand name must be specified in the `args` parameter {meth}`CliRunner.invoke`:54A subcommand name must be specified in the `args` parameter55{meth}`CliRunner.invoke`:5657```{code-block} python58:caption: sync.py59
24 unmodified lines
84```8586## Context Settings8784Additional keyword arguments passed to {meth}`CliRunner.invoke` will be used to construct the initial {class}`Context object <click.Context>`.88Additional keyword arguments passed to {meth}`CliRunner.invoke` will be used to89construct the initial {class}`Context object <click.Context>`.90For example, setting a fixed terminal width equal to 60:9192```{code-block} python93:caption: sync.py
24 unmodified lines
118```119120## File System Isolation121117The {meth}`CliRunner.isolated_filesystem` context manager sets the current working directory to a new, empty folder.122The {meth}`CliRunner.isolated_filesystem` context manager sets the current123working directory to a new, empty folder.124125```{code-block} python126:caption: cat.py127
44 unmodified lines
172```173174## Input Streams175170The test wrapper can provide input data for the input stream (stdin). This is very useful for testing prompts.176The test wrapper can provide input data for the input stream (stdin). This is177very useful for testing prompts.178179```{code-block} python180:caption: prompt.py181
72 unmodified lines
modified:src/click/_termui_impl.py+3 added-4 removed
378 unmodified lines
379 return _nullpager(stdout, generator, color)380381 # Split using POSIX mode (the default) so that quote characters are382 # stripped from tokens and quoted Windows paths are preserved.383 # posix=False was rejected (PR #1477) because it retains quotes in384 # tokens, and the shlex.quote approach was also reverted (PR #1543).385 # See also: issue #1026, PR #2775.383 # Non-POSIX mode retains quotes in tokens, and wrapping tokens384 # with shlex.quote re-introduces quoting issues on Windows.385 pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""))386 if pager_cmd_parts:387 if WIN:388 if _tempfilepager(generator, pager_cmd_parts, color):
232 unmodified lines
621622 try:623 # Split in POSIX mode (the default) for the same reasons as624 # in pager(): strips quotes from tokens and preserves quoted626 # Windows paths. See issue #1026, PR #1477.625 # Windows paths.626 c = subprocess.Popen(627 args=shlex.split(editor) + list(filenames),628 env=environ,629 )
241 unmodified lines
modified:src/click/core.py+13 added-15 removed
2914 unmodified lines
29152916 def get_default(2917 self, ctx: Context, call: bool = True2918 ) -> t.Any | t.Callable[[], t.Any] | None:2919 """For non-boolean flag options, ``default=True`` is treated as a2920 sentinel meaning "activate this flag by default" and is resolved to2921 :attr:`flag_value`. This resolution is performed lazily here (rather2922 than eagerly in :meth:`__init__`) to prevent callable ``flag_value``2923 values (like classes) from being instantiated prematurely.2919 """Return the default value for this option.29202925 For example, with ``--upper/--lower`` feature switches where2926 ``flag_value="upper"`` and ``default=True``, the default resolves2927 to ``"upper"``.2921 For non-boolean flag options, ``default=True`` is treated as a sentinel2922 meaning "activate this flag by default" and is resolved to2923 :attr:`flag_value`. For example, with ``--upper/--lower`` feature2924 switches where ``flag_value="upper"`` and ``default=True``, the default2925 resolves to ``"upper"``.29262927 .. caution::2930 This substitution only applies to **non-boolean** flags2928 This substitution only applies to non-boolean flags2929 (:attr:`is_bool_flag` is ``False``). For boolean flags, ``True`` is2932 not a sentinel but a legitimate Python value, so ``default=True`` is2933 returned as-is. Without this distinction, ``flag_value=False,2934 default=True`` would silently always return ``False``, regardless of2935 whether the flag was passed or not.2930 a legitimate Python value and ``default=True`` is returned as-is.29312932 .. versionchanged:: 8.3.32933 ``default=True`` is no longer substituted with ``flag_value`` for2939 boolean flags, fixing negative boolean flags like ``flag_value=False,2940 default=True``.2934 boolean flags, fixing negative boolean flags like2935 ``flag_value=False, default=True``.2936 """2937 value = super().get_default(ctx, call=False)29382939 # Resolve default=True to flag_value lazily (here instead of2940 # __init__) to prevent callable flag_values (like classes) from2941 # being instantiated by the callable check below.2942 if value is True and self.is_flag and not self.is_bool_flag:2943 value = self.flag_value2944 elif call and callable(value):2945 value = value()
531 unmodified lines
modified:src/click/testing.py-3 removed
477 unmodified lines
478 ``pdb.Pdb`` (ipdb, pdbpp). Explicit ``stdin``/``stdout``479 arguments are honored and not overridden. Debuggers that480 do not subclass ``pdb.Pdb`` (pudb, debugpy) are not481 covered.482483 See: https://github.com/pallets/click/issues/654 and484 https://github.com/pallets/click/issues/824482 """483 if stdin is None:484 stdin = sys.__stdin__485 if stdout is None:
184 unmodified lines
modified:CHANGES.rst+1 added-1 removed
24 unmodified lines
25- Add contributor documentation for running stress tests, randomized26 parallel tests, and Flask smoke tests. :pr:`3151` :pr:`3177`27- Show custom ``show_default`` string in prompts, matching the existing28 help text behavior. :issue:`2836` :pr:`2837` :pr:`3165` :pr:`3262` :pr:`3280`29 :pr:`3328``29 :pr:`3328`30- Fix ``default=True`` with boolean ``flag_value`` always returning the31 ``flag_value`` instead of ``True``. The ``default=True`` to ``flag_value``32 substitution now only applies to non-boolean flags, where ``True`` acts as a33 sentinel meaning "activate this flag by default". For boolean flags,
1336 unmodified lines