Merge branch 'main' into fix_prompt_suffix
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Gene Wood · committed by GitHub · parents 812b800, 81a482f · Browse files · 32 files·+2972 added−1346 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
32 files+2972 added−1346 removed
- tests:+1660 added−261 removed
- other:+1312 added−1085 removed
Provenance
- Commit
2608132- Tree
655b59d- Author
Gene Wood <gene_wood@cementhorizon.com>- Committer
GitHub <noreply@github.com>- Parent 1
812b800- Parent 2
81a482f
32 files changed+2972 added−1346 removed
modified:docs/documentation.md+1 added-1 removed
145 unmodified lines146 ```147 148 ## Click's Wrapping Behavior149 150-Click's default wrapping ignores single new lines and rewraps the text based on the width of the terminal, to a maximum of 80 characters. In the example notice how the second grouping of three lines is rewrapped into a single paragraph.150+Click's default wrapping ignores single new lines and rewraps the text based on the width of the terminal to a maximum of 80 characters by default, but this can be modified with {attr}`~Context.max_content_width`. In the example notice how the second grouping of three lines is rewrapped into a single paragraph.151 152 ```{eval-rst}153 .. click:example::154 123 unmodified linesmodified:docs/options.md+25 added-4 removed
312 unmodified lines313 ```314 315 ## Flag Value316 317-To have an flag pass a value to the underlying function set `flag_value`. This automatically sets `is_flag=True`. To set a default flag, set `default=True`. Setting flag values can be used to create patterns like this:317+To have an flag pass a value to the underlying 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:318 319 ```{eval-rst}320 .. click:example::321 12 unmodified lines334 invoke(info, args=['--lower'])335 invoke(info)336 ```337 338+````{note}339+The `default` value is given to the underlying function as-is. So if you set `default=None`, the value passed to the function is the `None` Python value. Same for any other type.340+341+But there is a special case for flags. If a flag has a `flag_value`, then setting `default=True` is interpreted as *the flag should be activated by default*. So instead of the underlying function receiving the `True` Python value, it will receive the `flag_value`.342+343+Which means, in example above, this option:344+345+```python346+@click.option('--upper', 'transformation', flag_value='upper', default=True)347+```348+349+is equivalent to:350+351+```python352+@click.option('--upper', 'transformation', flag_value='upper', default='upper')353+```354+355+Because the two are equivalent, it is recommended to always use the second form, and set `default` to the actual value you want to pass. And not use the special `True` case. This makes the code more explicit and predictable.356+````357+358 ## Values from Environment Variables359 360 To pass in a value in from a specific environment variable use `envvar`.361 43 unmodified lines405 - Values are stripped of leading and trailing whitespaces before being interpreted, so the `" True "` string is transformed to `"true"` and so activates the flag406 - 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 above407 - Any other value is interpreted as deactivating the flag408 389-.. caution::390- For boolean flags with a pair of values, the only recognized environment variable is the one provided to the `envvar` argument.409+```{caution}410+For boolean flags with a pair of values, the only recognized environment variable is the one provided to the `envvar` argument.411 392- So 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.412+So 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.413+```414 415 Once the status of the flag has been determine to be activated or not, the `flag_value` is used as the value of the flag if it is activated. If the flag is not activated, the value of the flag is set to `None` by default.416 417 ## Multiple Options from Environment Values80 unmodified linesadded:docs/parameter-types.md+186 added
1+(parameter-types)=2+3+# Parameter Types4+5+```{currentmodule} click6+```7+8+When the parameter type is set using `type`, Click will leverage the type to make your life easier, for example adding9+data to your help pages. Most examples are done with options, but types are available to options and arguments.10+11+```{contents}12+---13+depth: 214+local: true15+---16+```17+18+## Built-in Types Examples19+20+(choice-opts)=21+22+### Choice23+24+Sometimes, you want to have a parameter be a choice of a list of values. In that case you can use {class}`Choice` type.25+It can be instantiated with a list of valid values. The originally passed choice will be returned, not the str passed on26+the command line. Token normalization functions and `case_sensitive=False` can cause the two to be different but still27+match. {meth}`Choice.normalize_choice` for more info.28+29+30+Example:31+32+```{eval-rst}33+.. click:example::34+35+ import enum36+37+ class HashType(enum.Enum):38+ MD5 = enum.auto()39+ SHA1 = enum.auto()40+41+ @click.command()42+ @click.option('--hash-type',43+ type=click.Choice(HashType, case_sensitive=False))44+ def digest(hash_type: HashType):45+ click.echo(hash_type)46+47+What it looks like:48+49+.. click:run::50+51+ invoke(digest, args=['--hash-type=MD5'])52+ println()53+ invoke(digest, args=['--hash-type=md5'])54+ println()55+ invoke(digest, args=['--hash-type=foo'])56+ println()57+ invoke(digest, args=['--help'])58+```59+60+Any iterable may be passed to {class}`Choice`. If an `Enum` is passed, the names of the enum members will be used as61+valid choices.62+63+Choices work with options that have `multiple=True`. If a `default` value is given with `multiple=True`, it should be a64+list or tuple of valid choices.65+66+Choices should be unique after normalization, see {meth}`Choice.normalize_choice` for more info.67+68+```{versionchanged} 7.169+The resulting value from an option will always be one of the originally passed choices70+regardless of `case_sensitive`.71+```72+73+(ranges)=74+75+### Int and Float Ranges76+77+The {class}`IntRange` type extends the {data}`INT` type to ensure the value is contained in the given range. The78+{class}`FloatRange` type does the same for {data}`FLOAT`.79+80+If `min` or `max` is omitted, that side is *unbounded*. Any value in that direction is accepted. By default, both bounds81+are *closed*, which means the boundary value is included in the accepted range. `min_open` and `max_open` can be used to82+exclude that boundary from the range.83+84+If `clamp` mode is enabled, a value that is outside the range is set to the boundary instead of failing. For example,85+the range `0, 5` would return `5` for the value `10`, or `0` for the value `-1`. When using {class}`FloatRange`, `clamp`86+can only be enabled if both bounds are *closed* (the default).87+88+```{eval-rst}89+.. click:example::90+91+ @click.command()92+ @click.option("--count", type=click.IntRange(0, 20, clamp=True))93+ @click.option("--digit", type=click.IntRange(0, 9))94+ def repeat(count, digit):95+ click.echo(str(digit) * count)96+97+.. click:run::98+99+ invoke(repeat, args=['--count=100', '--digit=5'])100+ invoke(repeat, args=['--count=6', '--digit=12'])101+```102+103+## Built-in Types Listing104+105+The supported parameter {ref}`click-api-types` are106+107+- `str` / {data}`click.STRING`: The default parameter type which indicates unicode strings.108+109+- `int` / {data}`click.INT`: A parameter that only accepts integers.110+111+- `float` / {data}`click.FLOAT`: A parameter that only accepts floating point values.112+113+- `bool` / {data}`click.BOOL`: A parameter that accepts boolean values. This is automatically used for boolean flags.114+ The string values "1", "true", "t", "yes", "y", and "on" convert to `True`. "0", "false", "f", "no", "n", and "off"115+ convert to `False`.116+117+- {data}`click.UUID`: A parameter that accepts UUID values. This is not automatically guessed but represented as118+ {class}`uuid.UUID`.119+120+```{eval-rst}121+* .. autoclass:: Choice122+ :noindex:123+```124+125+```{eval-rst}126+* .. autoclass:: DateTime127+ :noindex:128+```129+130+```{eval-rst}131+* .. autoclass:: File132+ :noindex:133+```134+135+```{eval-rst}136+* .. autoclass:: FloatRange137+ :noindex:138+```139+140+```{eval-rst}141+* .. autoclass:: IntRange142+ :noindex:143+```144+145+```{eval-rst}146+* .. autoclass:: Path147+ :noindex:148+```149+150+## How to Implement Custom Types151+152+To implement a custom type, you need to subclass the {class}`ParamType` class. For simple cases, passing a Python153+function that fails with a `ValueError` is also supported, though discouraged. Override the {meth}`~ParamType.convert`154+method to convert the value from a string to the correct type.155+156+The following code implements an integer type that accepts hex and octal numbers in addition to normal integers, and157+converts them into regular integers.158+159+```python160+import click161+162+class BasedIntParamType(click.ParamType):163+ name = "integer"164+165+ def convert(self, value, param, ctx):166+ if isinstance(value, int):167+ return value168+169+ try:170+ if value[:2].lower() == "0x":171+ return int(value[2:], 16)172+ elif value[:1] == "0":173+ return int(value, 8)174+ return int(value, 10)175+ except ValueError:176+ self.fail(f"{value!r} is not a valid integer", param, ctx)177+178+BASED_INT = BasedIntParamType()179+```180+181+The {attr}`~ParamType.name` attribute is optional and is used for documentation. Call {meth}`~ParamType.fail` if182+conversion fails. The `param` and `ctx` arguments may be `None` in some cases such as prompts.183+184+Values from user input or the command line will be strings, but default values and Python arguments may already be the185+correct type. The custom type should check at the top if the value is already valid and pass it through to support those186+cases.deleted:docs/parameter-types.rst-181 removed
1-.. _parameter-types:2-3-Parameter Types4-==================5-6-.. currentmodule:: click7-8-When the parameter type is set using ``type``, Click will leverage the type to make your life easier, for example adding data to your help pages. Most examples are done with options, but types are available to options and arguments.9-10-.. contents::11- :depth: 212- :local:13-14-Built-in Types Examples15-------------------------16-17-.. _choice-opts:18-19-Choice20-^^^^^^^^^^^^^^^^^^^^^^21-22-Sometimes, you want to have a parameter be a choice of a list of values.23-In that case you can use :class:`Choice` type. It can be instantiated24-with a list of valid values. The originally passed choice will be returned,25-not the str passed on the command line. Token normalization functions and26-``case_sensitive=False`` can cause the two to be different but still match.27-:meth:`Choice.normalize_choice` for more info.28-29-Example:30-31-.. click:example::32-33- import enum34-35- class HashType(enum.Enum):36- MD5 = enum.auto()37- SHA1 = enum.auto()38-39- @click.command()40- @click.option('--hash-type',41- type=click.Choice(HashType, case_sensitive=False))42- def digest(hash_type: HashType):43- click.echo(hash_type)44-45-What it looks like:46-47-.. click:run::48-49- invoke(digest, args=['--hash-type=MD5'])50- println()51- invoke(digest, args=['--hash-type=md5'])52- println()53- invoke(digest, args=['--hash-type=foo'])54- println()55- invoke(digest, args=['--help'])56-57-Any iterable may be passed to :class:`Choice`. If an ``Enum`` is passed, the58-names of the enum members will be used as valid choices.59-60-Choices work with options that have ``multiple=True``. If a ``default``61-value is given with ``multiple=True``, it should be a list or tuple of62-valid choices.63-64-Choices should be unique after normalization, see65-:meth:`Choice.normalize_choice` for more info.66-67-.. versionchanged:: 7.168- The resulting value from an option will always be one of the69- originally passed choices regardless of ``case_sensitive``.70-71-.. _ranges:72-73-Int and Float Ranges74-^^^^^^^^^^^^^^^^^^^^^^^75-76-The :class:`IntRange` type extends the :data:`INT` type to ensure the77-value is contained in the given range. The :class:`FloatRange` type does78-the same for :data:`FLOAT`.79-80-If ``min`` or ``max`` is omitted, that side is *unbounded*. Any value in81-that direction is accepted. By default, both bounds are *closed*, which82-means the boundary value is included in the accepted range. ``min_open``83-and ``max_open`` can be used to exclude that boundary from the range.84-85-If ``clamp`` mode is enabled, a value that is outside the range is set86-to the boundary instead of failing. For example, the range ``0, 5``87-would return ``5`` for the value ``10``, or ``0`` for the value ``-1``.88-When using :class:`FloatRange`, ``clamp`` can only be enabled if both89-bounds are *closed* (the default).90-91-.. click:example::92-93- @click.command()94- @click.option("--count", type=click.IntRange(0, 20, clamp=True))95- @click.option("--digit", type=click.IntRange(0, 9))96- def repeat(count, digit):97- click.echo(str(digit) * count)98-99-.. click:run::100-101- invoke(repeat, args=['--count=100', '--digit=5'])102- invoke(repeat, args=['--count=6', '--digit=12'])103-104-105-Built-in Types Listing106------------------------107-The supported parameter :ref:`click-api-types` are:108-109-* ``str`` / :data:`click.STRING`: The default parameter type which indicates unicode strings.110-111-* ``int`` / :data:`click.INT`: A parameter that only accepts integers.112-113-* ``float`` / :data:`click.FLOAT`: A parameter that only accepts floating point values.114-115-* ``bool`` / :data:`click.BOOL`: A parameter that accepts boolean values. This is automatically used116- for boolean flags. The string values "1", "true", "t", "yes", "y",117- and "on" convert to ``True``. "0", "false", "f", "no", "n", and118- "off" convert to ``False``.119-120-* :data:`click.UUID`:121- A parameter that accepts UUID values. This is not automatically122- guessed but represented as :class:`uuid.UUID`.123-124-* .. autoclass:: Choice125- :noindex:126-127-* .. autoclass:: DateTime128- :noindex:129-130-* .. autoclass:: File131- :noindex:132-133-* .. autoclass:: FloatRange134- :noindex:135-136-* .. autoclass:: IntRange137- :noindex:138-139-* .. autoclass:: Path140- :noindex:141-142-How to Implement Custom Types143--------------------------------144-145-To implement a custom type, you need to subclass the :class:`ParamType` class. For simple cases, passing a Python function that fails with a `ValueError` is also supported, though discouraged. Override the :meth:`~ParamType.convert` method to convert the value from a string to the correct type.146-147-The following code implements an integer type that accepts hex and octal148-numbers in addition to normal integers, and converts them into regular149-integers.150-151-.. code-block:: python152-153- import click154-155- class BasedIntParamType(click.ParamType):156- name = "integer"157-158- def convert(self, value, param, ctx):159- if isinstance(value, int):160- return value161-162- try:163- if value[:2].lower() == "0x":164- return int(value[2:], 16)165- elif value[:1] == "0":166- return int(value, 8)167- return int(value, 10)168- except ValueError:169- self.fail(f"{value!r} is not a valid integer", param, ctx)170-171- BASED_INT = BasedIntParamType()172-173-The :attr:`~ParamType.name` attribute is optional and is used for174-documentation. Call :meth:`~ParamType.fail` if conversion fails. The175-``param`` and ``ctx`` arguments may be ``None`` in some cases such as176-prompts.177-178-Values from user input or the command line will be strings, but default179-values and Python arguments may already be the correct type. The custom180-type should check at the top if the value is already valid and pass it181-through to support those cases.added:docs/prompts.md+168 added
1+# User Input Prompts2+3+```{currentmodule} click4+```5+6+Click supports prompts in two different places. The first is automated prompts when the parameter handling happens, and7+the second is to ask for prompts at a later point independently.8+9+This can be accomplished with the {func}`prompt` function, which asks for valid input according to a type, or the10+{func}`confirm` function, which asks for confirmation (yes/no).11+12+```{contents}13+---14+depth: 215+local: true16+---17+```18+19+(option-prompting)=20+21+## Option Prompts22+23+Option prompts are integrated into the option interface. Internally, it automatically calls either {func}`prompt` or24+{func}`confirm` as necessary.25+26+In some cases, you want parameters that can be provided from the command line, but if not provided, ask for user input27+instead. This can be implemented with Click by defining a prompt string.28+29+Example:30+31+```{eval-rst}32+.. click:example::33+34+ @click.command()35+ @click.option('--name', prompt=True)36+ def hello(name):37+ click.echo(f"Hello {name}!")38+39+And what it looks like:40+41+.. click:run::42+43+ invoke(hello, args=['--name=John'])44+ invoke(hello, input=['John'])45+```46+47+If you are not happy with the default prompt string, you can ask for48+a different one:49+50+```{eval-rst}51+.. click:example::52+53+ @click.command()54+ @click.option('--name', prompt='Your name please')55+ def hello(name):56+ click.echo(f"Hello {name}!")57+58+What it looks like:59+60+.. click:run::61+62+ invoke(hello, input=['John'])63+```64+65+It is advised that prompt not be used in conjunction with the multiple flag set to True. Instead, prompt in the function66+interactively.67+68+By default, the user will be prompted for an input if one was not passed through the command line. To turn this behavior69+off, see {ref}`optional-value`.70+71+## Input Prompts72+73+To manually ask for user input, you can use the {func}`prompt` function. By default, it accepts any Unicode string, but74+you can ask for any other type. For instance, you can ask for a valid integer:75+76+```python77+value = click.prompt('Please enter a valid integer', type=int)78+```79+80+Additionally, the type will be determined automatically if a default value is provided. For instance, the following will81+only accept floats:82+83+```python84+value = click.prompt('Please enter a number', default=42.0)85+```86+87+## Optional Prompts88+89+If the option has `prompt` enabled, then setting `prompt_required=False` tells Click to only show the prompt if the90+option's flag is given, instead of if the option is not provided at all.91+92+```{eval-rst}93+.. click:example::94+95+ @click.command()96+ @click.option('--name', prompt=True, prompt_required=False, default="Default")97+ def hello(name):98+ click.echo(f"Hello {name}!")99+100+.. click:run::101+102+ invoke(hello)103+ invoke(hello, args=["--name", "Value"])104+ invoke(hello, args=["--name"], input="Prompt")105+```106+107+If `required=True`, then the option will still prompt if it is not given, but it will also prompt if only the flag is108+given.109+110+## Confirmation Prompts111+112+To ask if a user wants to continue with an action, the {func}`confirm` function comes in handy. By default, it returns113+the result of the prompt as a boolean value:114+115+```python116+if click.confirm('Do you want to continue?'):117+ click.echo('Well done!')118+```119+120+There is also the option to make the function automatically abort the execution of the program if it does not return121+`True`:122+123+```python124+click.confirm('Do you want to continue?', abort=True)125+```126+127+## Dynamic Defaults for Prompts128+129+The `auto_envvar_prefix` and `default_map` options for the context allow the program to read option values from the130+environment or a configuration file. However, this overrides the prompting mechanism, so that the user does not get the131+option to change the value interactively.132+133+If you want to let the user configure the default value, but still be prompted if the option isn't specified on the134+command line, you can do so by supplying a callable as the default value. For example, to get a default from the135+environment:136+137+```python138+import os139+140+@click.command()141+@click.option(142+ "--username", prompt=True,143+ default=lambda: os.environ.get("USER", "")144+)145+def hello(username):146+ click.echo(f"Hello, {username}!")147+```148+149+To describe what the default value will be, set it in ``show_default``.150+151+```{eval-rst}152+.. click:example::153+154+ import os155+156+ @click.command()157+ @click.option(158+ "--username", prompt=True,159+ default=lambda: os.environ.get("USER", ""),160+ show_default="current user"161+ )162+ def hello(username):163+ click.echo(f"Hello, {username}!")164+165+.. click:run::166+167+ invoke(hello, args=["--help"])168+```deleted:docs/prompts.rst-162 removed
1-User Input Prompts2-==================3-4-.. currentmodule:: click5-6-Click supports prompts in two different places. The first is automated7-prompts when the parameter handling happens, and the second is to ask for8-prompts at a later point independently.9-10-This can be accomplished with the :func:`prompt` function, which asks for11-valid input according to a type, or the :func:`confirm` function, which asks12-for confirmation (yes/no).13-14-.. contents::15- :depth: 216- :local:17-18-.. _option-prompting:19-20-Option Prompts21---------------22-23-Option prompts are integrated into the option interface. Internally, it24-automatically calls either :func:`prompt` or :func:`confirm` as necessary.25-26-In some cases, you want parameters that can be provided from the command line,27-but if not provided, ask for user input instead. This can be implemented with28-Click by defining a prompt string.29-30-Example:31-32-.. click:example::33-34- @click.command()35- @click.option('--name', prompt=True)36- def hello(name):37- click.echo(f"Hello {name}!")38-39-And what it looks like:40-41-.. click:run::42-43- invoke(hello, args=['--name=John'])44- invoke(hello, input=['John'])45-46-If you are not happy with the default prompt string, you can ask for47-a different one:48-49-.. click:example::50-51- @click.command()52- @click.option('--name', prompt='Your name please')53- def hello(name):54- click.echo(f"Hello {name}!")55-56-What it looks like:57-58-.. click:run::59-60- invoke(hello, input=['John'])61-62-It is advised that prompt not be used in conjunction with the multiple63-flag set to True. Instead, prompt in the function interactively.64-65-By default, the user will be prompted for an input if one was not passed66-through the command line. To turn this behavior off, see67-:ref:`optional-value`.68-69-Input Prompts70--------------71-72-To manually ask for user input, you can use the :func:`prompt` function.73-By default, it accepts any Unicode string, but you can ask for any other74-type. For instance, you can ask for a valid integer::75-76- value = click.prompt('Please enter a valid integer', type=int)77-78-Additionally, the type will be determined automatically if a default value is79-provided. For instance, the following will only accept floats::80-81- value = click.prompt('Please enter a number', default=42.0)82-83-Optional Prompts84-------------------85-If the option has ``prompt`` enabled, then setting86-``prompt_required=False`` tells Click to only show the prompt if the87-option's flag is given, instead of if the option is not provided at all.88-89-.. click:example::90-91- @click.command()92- @click.option('--name', prompt=True, prompt_required=False, default="Default")93- def hello(name):94- click.echo(f"Hello {name}!")95-96-.. click:run::97-98- invoke(hello)99- invoke(hello, args=["--name", "Value"])100- invoke(hello, args=["--name"], input="Prompt")101-102-If ``required=True``, then the option will still prompt if it is not103-given, but it will also prompt if only the flag is given.104-105-Confirmation Prompts106---------------------107-108-To ask if a user wants to continue with an action, the :func:`confirm`109-function comes in handy. By default, it returns the result of the prompt110-as a boolean value::111-112- if click.confirm('Do you want to continue?'):113- click.echo('Well done!')114-115-There is also the option to make the function automatically abort the116-execution of the program if it does not return ``True``::117-118- click.confirm('Do you want to continue?', abort=True)119-120-Dynamic Defaults for Prompts121-----------------------------122-123-The ``auto_envvar_prefix`` and ``default_map`` options for the context124-allow the program to read option values from the environment or a125-configuration file. However, this overrides the prompting mechanism, so126-that the user does not get the option to change the value interactively.127-128-If you want to let the user configure the default value, but still be129-prompted if the option isn't specified on the command line, you can do so130-by supplying a callable as the default value. For example, to get a default131-from the environment:132-133-.. code-block:: python134-135- import os136-137- @click.command()138- @click.option(139- "--username", prompt=True,140- default=lambda: os.environ.get("USER", "")141- )142- def hello(username):143- click.echo(f"Hello, {username}!")144-145-To describe what the default value will be, set it in ``show_default``.146-147-.. click:example::148-149- import os150-151- @click.command()152- @click.option(153- "--username", prompt=True,154- default=lambda: os.environ.get("USER", ""),155- show_default="current user"156- )157- def hello(username):158- click.echo(f"Hello, {username}!")159-160-.. click:run::161-162- invoke(hello, args=["--help"])added:docs/quickstart.md+196 added
1+# Quickstart2+3+```{currentmodule} click4+```5+6+## Install7+8+Install from PyPI:9+10+```console11+pip install click12+```13+14+Installing into a virtual environment is highly recommended. We suggest {ref}`virtualenv-heading`.15+16+## Examples17+18+Some standalone examples of Click applications are packaged with Click. They are available in the19+[examples folder](https://github.com/pallets/click/tree/main/examples) of the repo.20+21+- [inout](https://github.com/pallets/click/tree/main/examples/inout) : A very simple example of an application that can22+ read from files and write to files and also accept input from stdin or write to stdout.23+- [validation](https://github.com/pallets/click/tree/main/examples/validation) : A simple example of an application that24+ performs custom validation of parameters in different ways.25+- [naval](https://github.com/pallets/click/tree/main/examples/naval) : Port of the [docopt](http://docopt.org/) naval26+ example.27+- [colors](https://github.com/pallets/click/tree/main/examples/colors) : A simple example that colorizes text. Uses28+ colorama on Windows.29+- [aliases](https://github.com/pallets/click/tree/main/examples/aliases) : An advanced example that implements30+ {ref}`aliases`.31+- [imagepipe](https://github.com/pallets/click/tree/main/examples/imagepipe) : A complex example that implements some32+ {ref}`command-pipelines` . It chains together image processing instructions. Requires pillow.33+- [repo](https://github.com/pallets/click/tree/main/examples/repo) : An advanced example that implements a34+ Git-/Mercurial-like command line interface.35+- [complex](https://github.com/pallets/click/tree/main/examples/complex) : A very advanced example that implements36+ loading subcommands dynamically from a plugin folder.37+- [termui](https://github.com/pallets/click/tree/main/examples/termui) : A simple example that showcases terminal UI38+ helpers provided by click.39+40+## Basic Concepts - Creating a Command41+42+Click is based on declaring commands through decorators. Internally, there is a non-decorator interface for advanced use43+cases, but it's discouraged for high-level usage.44+45+A function becomes a Click command line tool by decorating it through {func}`command`. At its simplest, just46+decorating a function with this decorator will make it into a callable script:47+48+49+```{eval-rst}50+.. click:example::51+ import click52+53+ @click.command()54+ def hello():55+ click.echo('Hello World!')56+57+What's happening is that the decorator converts the function into a :class:`Command` which then can be invoked:58+59+.. click:example::60+ if __name__ == '__main__':61+ hello()62+63+And what it looks like:64+65+.. click:run::66+ invoke(hello, args=[], prog_name='python hello.py')67+68+And the corresponding help page:69+70+.. click:run::71+ invoke(hello, args=['--help'], prog_name='python hello.py')72+```73+74+## Echoing75+76+Why does this example use {func}`echo` instead of the regular {func}`print` function? The answer to this question is77+that Click attempts to support different environments consistently and to be very robust even when the environment is78+misconfigured. Click wants to be functional at least on a basic level even if everything is completely broken.79+80+What this means is that the {func}`echo` function applies some error correction in case the terminal is misconfigured81+instead of dying with a {exc}`UnicodeError`.82+83+The echo function also supports color and other styles in output. It will automatically remove styles if the output84+stream is a file. On Windows, colorama is automatically installed and used. See {ref}`ansi-colors`.85+86+If you don't need this, you can also use the `print()` construct / function.87+88+## Nesting Commands89+90+Commands can be attached to other commands of type {class}`Group`. This allows arbitrary nesting of scripts. As an91+example here is a script that implements two commands for managing databases:92+93+```{eval-rst}94+.. click:example::95+ @click.group()96+ def cli():97+ pass98+99+ @click.command()100+ def initdb():101+ click.echo('Initialized the database')102+103+ @click.command()104+ def dropdb():105+ click.echo('Dropped the database')106+107+ cli.add_command(initdb)108+ cli.add_command(dropdb)109+```110+111+As you can see, the {func}`group` decorator works like the {func}`command` decorator, but creates a {class}`Group`112+object instead which can be given multiple subcommands that can be attached with {meth}`Group.add_command`.113+114+For simple scripts, it's also possible to automatically attach and create a command by using the {meth}`Group.command`115+decorator instead. The above script can instead be written like this:116+117+```{eval-rst}118+.. click:example::119+ @click.group()120+ def cli():121+ pass122+123+ @cli.command()124+ def initdb():125+ click.echo('Initialized the database')126+127+ @cli.command()128+ def dropdb():129+ click.echo('Dropped the database')130+131+You would then invoke the :class:`Group` in your entry points or other invocations:132+133+.. click:example::134+ if __name__ == '__main__':135+ cli()136+```137+138+## Registering Commands Later139+140+Instead of using the `@group.command()` decorator, commands can be decorated with the plain `@command()` decorator141+and registered with a group later with `group.add_command()`. This could be used to split commands into multiple Python142+modules.143+144+```{code-block} python145+ @click.command()146+ def greet():147+ click.echo("Hello, World!")148+```149+150+```{code-block} python151+ @click.group()152+ def group():153+ pass154+155+ group.add_command(greet)156+```157+158+## Adding Parameters159+160+To add parameters, use the {func}`option` and {func}`argument` decorators:161+162+```{eval-rst}163+.. click:example::164+ @click.command()165+ @click.option('--count', default=1, help='number of greetings')166+ @click.argument('name')167+ def hello(count, name):168+ for x in range(count):169+ click.echo(f"Hello {name}!")170+171+What it looks like:172+173+.. click:run::174+ invoke(hello, args=['--help'], prog_name='python hello.py')175+```176+177+## Switching to Entry Points178+179+In the code you wrote so far there is a block at the end of the file which looks like this:180+`if __name__ == '__main__':`. This is traditionally how a standalone Python file looks like. With Click you can continue181+doing that, but a better way is to package your app with an entry point.182+183+There are two main (and many more) reasons for this:184+185+The first one is that installers automatically generate executable wrappers for Windows so your command line utilities186+work on Windows too.187+188+The second reason is that entry point scripts work with virtualenv on Unix without the virtualenv having to be189+activated. This is a very useful concept which allows you to bundle your scripts with all requirements into a190+virtualenv.191+192+Click is perfectly equipped to work with that and in fact the rest of the documentation will assume that you are writing193+applications as distributed packages.194+195+Look at the {doc}`entry-points` chapter before reading the rest as the examples assume that you will be using entry196+points.deleted:docs/quickstart.rst-206 removed
1-Quickstart2-==========3-4-.. currentmodule:: click5-6-Install7-----------------------8-Install from PyPI::9-10- pip install click11-12-Installing into a virtual environment is highly recommended. We suggest :ref:`virtualenv-heading`.13-14-Examples15------------------------16-17-Some standalone examples of Click applications are packaged with Click. They are available in the `examples folder <https://github.com/pallets/click/tree/main/examples>`_ of the repo.18-19-* `inout <https://github.com/pallets/click/tree/main/examples/inout>`_ : A very simple example of an application that can read from files and write to files and also accept input from stdin or write to stdout.20-* `validation <https://github.com/pallets/click/tree/main/examples/validation>`_ : A simple example of an application that performs custom validation of parameters in different ways.21-* `naval <https://github.com/pallets/click/tree/main/examples/naval>`_ : Port of the `docopt <http://docopt.org/>`_ naval example.22-* `colors <https://github.com/pallets/click/tree/main/examples/colors>`_ : A simple example that colorizes text. Uses colorama on Windows.23-* `aliases <https://github.com/pallets/click/tree/main/examples/aliases>`_ : An advanced example that implements :ref:`aliases`.24-* `imagepipe <https://github.com/pallets/click/tree/main/examples/imagepipe>`_ : A complex example that implements some :ref:`command-pipelines` . It chains together image processing instructions. Requires pillow.25-* `repo <https://github.com/pallets/click/tree/main/examples/repo>`_ : An advanced example that implements a Git-/Mercurial-like command line interface.26-* `complex <https://github.com/pallets/click/tree/main/examples/complex>`_ : A very advanced example that implements loading subcommands dynamically from a plugin folder.27-* `termui <https://github.com/pallets/click/tree/main/examples/termui>`_ : A simple example that showcases terminal UI helpers provided by click.28-29-Basic Concepts - Creating a Command30------------------------------------31-32-Click is based on declaring commands through decorators. Internally, there33-is a non-decorator interface for advanced use cases, but it's discouraged34-for high-level usage.35-36-A function becomes a Click command line tool by decorating it through37-:func:`click.command`. At its simplest, just decorating a function38-with this decorator will make it into a callable script:39-40-.. click:example::41-42- import click43-44- @click.command()45- def hello():46- click.echo('Hello World!')47-48-What's happening is that the decorator converts the function into a49-:class:`Command` which then can be invoked::50-51- if __name__ == '__main__':52- hello()53-54-And what it looks like:55-56-.. click:run::57-58- invoke(hello, args=[], prog_name='python hello.py')59-60-And the corresponding help page:61-62-.. click:run::63-64- invoke(hello, args=['--help'], prog_name='python hello.py')65-66-Echoing67--------68-69-Why does this example use :func:`echo` instead of the regular70-:func:`print` function? The answer to this question is that Click71-attempts to support different environments consistently and to be very72-robust even when the environment is misconfigured. Click wants to be73-functional at least on a basic level even if everything is completely74-broken.75-76-What this means is that the :func:`echo` function applies some error77-correction in case the terminal is misconfigured instead of dying with a78-:exc:`UnicodeError`.79-80-The echo function also supports color and other styles in output. It81-will automatically remove styles if the output stream is a file. On82-Windows, colorama is automatically installed and used. See83-:ref:`ansi-colors`.84-85-If you don't need this, you can also use the `print()` construct /86-function.87-88-Nesting Commands89-----------------90-91-Commands can be attached to other commands of type :class:`Group`. This92-allows arbitrary nesting of scripts. As an example here is a script that93-implements two commands for managing databases:94-95-.. click:example::96-97- @click.group()98- def cli():99- pass100-101- @click.command()102- def initdb():103- click.echo('Initialized the database')104-105- @click.command()106- def dropdb():107- click.echo('Dropped the database')108-109- cli.add_command(initdb)110- cli.add_command(dropdb)111-112-As you can see, the :func:`group` decorator works like the :func:`command`113-decorator, but creates a :class:`Group` object instead which can be given114-multiple subcommands that can be attached with :meth:`Group.add_command`.115-116-For simple scripts, it's also possible to automatically attach and create a117-command by using the :meth:`Group.command` decorator instead. The above118-script can instead be written like this:119-120-.. click:example::121-122- @click.group()123- def cli():124- pass125-126- @cli.command()127- def initdb():128- click.echo('Initialized the database')129-130- @cli.command()131- def dropdb():132- click.echo('Dropped the database')133-134-You would then invoke the :class:`Group` in your entry points or other invocations::135-136- if __name__ == '__main__':137- cli()138-139-140-Registering Commands Later141---------------------------142-143-Instead of using the ``@group.command()`` decorator, commands can be144-decorated with the plain ``@click.command()`` decorator and registered145-with a group later with ``group.add_command()``. This could be used to146-split commands into multiple Python modules.147-148-.. code-block:: python149-150- @click.command()151- def greet():152- click.echo("Hello, World!")153-154-.. code-block:: python155-156- @click.group()157- def group():158- pass159-160- group.add_command(greet)161-162-163-Adding Parameters164------------------165-166-To add parameters, use the :func:`option` and :func:`argument` decorators:167-168-.. click:example::169-170- @click.command()171- @click.option('--count', default=1, help='number of greetings')172- @click.argument('name')173- def hello(count, name):174- for x in range(count):175- click.echo(f"Hello {name}!")176-177-What it looks like:178-179-.. click:run::180-181- invoke(hello, args=['--help'], prog_name='python hello.py')182-183-Switching to Entry Points184--------------------------185-186-In the code you wrote so far there is a block at the end of the file which187-looks like this: ``if __name__ == '__main__':``. This is traditionally188-how a standalone Python file looks like. With Click you can continue189-doing that, but a better way is to package your app with an entry point.190-191-There are two main (and many more) reasons for this:192-193-The first one is that installers automatically generate executable194-wrappers for Windows so your command line utilities work on Windows too.195-196-The second reason is that entry point scripts work with virtualenv on Unix197-without the virtualenv having to be activated. This is a very useful198-concept which allows you to bundle your scripts with all requirements into199-a virtualenv.200-201-Click is perfectly equipped to work with that and in fact the rest of the202-documentation will assume that you are writing applications as distributed203-packages.204-205-Look at the :doc:`entry-points` chapter before reading the rest as the examples206-assume that you will be using entry points.added:docs/setuptools.md+7 added
1234567---orphan: true---
# Setuptools Integration
Moved to {doc}`entry-points`.deleted:docs/setuptools.rst-6 removed
1-:orphan:2-3-Setuptools Integration4-======================5-6-Moved to :doc:`entry-points`.added:docs/shell-completion.md+249 added
1+(shell-completion)=2+3+# Shell Completion4+5+```{currentmodule} click.shell_completion6+```7+8+Click provides tab completion support for Bash (version 4.4 and up), Zsh, and Fish. It is possible to add support for9+other shells too, and suggestions can be customized at multiple levels.10+11+Shell completion suggests command names, option names, and values for choice, file, and path parameter types. Options12+are only listed if at least a dash has been entered. Hidden commands and options are not shown.13+14+```console15+$ repo <TAB><TAB>16+clone commit copy delete setuser17+$ repo clone -<TAB><TAB>18+--deep --help --rev --shallow -r19+```20+21+## Enabling Completion22+23+Completion is only available if a script is installed and invoked through an entry point, not through the `python`24+command. See {doc}`entry-points`. Once the executable is installed, calling it with a special environment variable will25+put Click in completion mode.26+27+To enable shell completion, the user needs to register a special function with their shell. The exact script varies28+depending on the shell you are using. Click will output it when called with `_{FOO_BAR}_COMPLETE` set to29+`{shell}_source`. `{FOO_BAR}` is the executable name in uppercase with dashes replaced by underscores. It is30+conventional but not strictly required for environment variable names to be in upper case. This convention helps31+distinguish environment variables from regular shell variables and commands, making scripts and configuration files more32+readable and easier to maintain. The built-in shells are `bash`, `zsh`, and `fish`.33+34+Provide your users with the following instructions customized to your program name. This uses `foo-bar` as an example.35+36+```{eval-rst}37+.. tabs::38+39+ .. group-tab:: Bash40+41+ Add this to ``~/.bashrc``:42+43+ .. code-block:: bash44+45+ eval "$(_FOO_BAR_COMPLETE=bash_source foo-bar)"46+47+ .. group-tab:: Zsh48+49+ Add this to ``~/.zshrc``:50+51+ .. code-block:: zsh52+53+ eval "$(_FOO_BAR_COMPLETE=zsh_source foo-bar)"54+55+ .. group-tab:: Fish56+57+ Add this to ``~/.config/fish/completions/foo-bar.fish``:58+59+ .. code-block:: fish60+61+ _FOO_BAR_COMPLETE=fish_source foo-bar | source62+63+ This is the same file used for the activation script method64+ below. For Fish it's probably always easier to use that method.65+```66+67+Using `eval` means that the command is invoked and evaluated every time a shell is started, which can delay shell68+responsiveness. To speed it up, write the generated script to a file, then source that. You can generate the files ahead69+of time and distribute them with your program to save your users a step.70+71+```{eval-rst}72+.. tabs::73+74+ .. group-tab:: Bash75+76+ Save the script somewhere.77+78+ .. code-block:: bash79+80+ _FOO_BAR_COMPLETE=bash_source foo-bar > ~/.foo-bar-complete.bash81+82+ Source the file in ``~/.bashrc``.83+84+ .. code-block:: bash85+86+ . ~/.foo-bar-complete.bash87+88+ .. group-tab:: Zsh89+90+ Save the script somewhere.91+92+ .. code-block:: bash93+94+ _FOO_BAR_COMPLETE=zsh_source foo-bar > ~/.foo-bar-complete.zsh95+96+ Source the file in ``~/.zshrc``.97+98+ .. code-block:: bash99+100+ . ~/.foo-bar-complete.zsh101+102+ .. group-tab:: Fish103+104+ Save the script to ``~/.config/fish/completions/foo-bar.fish``:105+106+ .. code-block:: fish107+108+ _FOO_BAR_COMPLETE=fish_source foo-bar > ~/.config/fish/completions/foo-bar.fish109+```110+111+After modifying the shell config, you need to start a new shell in order for the changes to be loaded.112+113+## Custom Type Completion114+115+When creating a custom {class}`~click.ParamType`, override its {meth}`~click.ParamType.shell_complete` method to provide116+shell completion for parameters with the type. The method must return a list of {class}`~CompletionItem` objects.117+Besides the value, these objects hold metadata that shell support might use. The built-in implementations use `type` to118+indicate special handling for paths, and `help` for shells that support showing a help string next to a suggestion.119+120+In this example, the type will suggest environment variables that start with the incomplete value.121+122+```python123+class EnvVarType(ParamType):124+ name = "envvar"125+126+ def shell_complete(self, ctx, param, incomplete):127+ return [128+ CompletionItem(name)129+ for name in os.environ if name.startswith(incomplete)130+ ]131+132+@click.command()133+@click.option("--ev", type=EnvVarType())134+def cli(ev):135+ click.echo(os.environ[ev])136+```137+138+## Overriding Value Completion139+140+Value completions for a parameter can be customized without a custom type by providing a `shell_complete` function. The141+function is used instead of any completion provided by the type. It is passed 3 positional arguments:142+143+- `ctx` - The current command context.144+- `param` - The current parameter requesting completion.145+- `incomplete` - The partial word that is being completed. May be an empty string if no characters have been entered146+ yet.147+148+It must return a list of {class}`CompletionItem` objects, or as a shortcut it can return a list of strings.149+150+In this example, the command will suggest environment variables that start with the incomplete value.151+152+```python153+def complete_env_vars(ctx, param, incomplete):154+ return [k for k in os.environ if k.startswith(incomplete)]155+156+@click.command()157+@click.argument("name", shell_complete=complete_env_vars)158+def cli(name):159+ click.echo(f"Name: {name}")160+ click.echo(f"Value: {os.environ[name]}")161+```162+163+## Adding Support for a Shell164+165+Support can be added for shells that do not come built in. Be sure to check PyPI to see if there's already a package166+that adds support for your shell. This topic is very technical, you'll want to look at Click's source to study the167+built-in implementations.168+169+Shell support is provided by subclasses of {class}`ShellComplete` registered with {func}`add_completion_class`. When170+Click is invoked in completion mode, it calls {meth}`~ShellComplete.source` to output the completion script, or171+{meth}`~ShellComplete.complete` to output completions. The base class provides default implementations that require172+implementing some smaller parts.173+174+First, you'll need to figure out how your shell's completion system works and write a script to integrate it with Click.175+It must invoke your program with the environment variable `_{FOO_BAR}_COMPLETE` set to `{shell}_complete` and pass the176+complete args and incomplete value. How it passes those values, and the format of the completion response from Click is177+up to you.178+179+In your subclass, set {attr}`ShellComplete.source_template` to the completion script. The default implementation will180+perform `%` formatting with the following variables:181+182+- `complete_func` - A safe name for the completion function defined in the script.183+- `complete_var` - The environment variable name for passing the `{shell}_complete` instruction.184+- `foo_bar` - The name of the executable being completed.185+186+The example code is for a made up shell "My Shell" or "mysh" for short.187+188+```python189+from click.shell_completion import add_completion_class190+from click.shell_completion import ShellComplete191+192+_mysh_source = """\193+%(complete_func)s {194+ response=$(%(complete_var)s=mysh_complete %(foo_bar)s)195+ # parse response and set completions somehow196+}197+call-on-complete %(foo_bar)s %(complete_func)s198+"""199+200+@add_completion_class201+class MyshComplete(ShellComplete):202+ name = "mysh"203+ source_template = _mysh_source204+```205+206+Next, implement {meth}`~ShellComplete.get_completion_args`. This must get, parse, and return the complete args and207+incomplete value from the completion script. For example, for the Bash implementation the `COMP_WORDS` env var contains208+the command line args as a string, and the `COMP_CWORD` env var contains the index of the incomplete arg. The method209+must return a `(args, incomplete)` tuple.210+211+```python212+import os213+from click.parser import split_arg_string214+215+class MyshComplete(ShellComplete):216+ ...217+218+ def get_completion_args(self):219+ args = split_arg_string(os.environ["COMP_WORDS"])220+221+ if os.environ["COMP_PARTIAL"] == "1":222+ incomplete = args.pop()223+ return args, incomplete224+225+ return args, ""226+```227+228+Finally, implement {meth}`~ShellComplete.format_completion`. This is called to format each {class}`CompletionItem` into a string. For example, the Bash implementation returns `f"{item.type},{item.value}` (it doesn't support help strings), and the Zsh implementation returns each part separated by a newline, replacing empty help with a `_` placeholder. This format is entirely up to what you parse with your completion script.229+230+The `type` value is usually `plain`, but it can be another value that the completion script can switch on. For example,231+`file` or `dir` can tell the shell to handle path completion, since the shell is better at that than Click.232+233+```python234+class MyshComplete(ShellComplete):235+ ...236+237+ def format_completion(self, item):238+ return f"{item.type}\t{item.value}"239+```240+241+With those three things implemented, the new shell support is ready. In case those weren't sufficient, there are more242+parts that can be overridden, but that probably isn't necessary.243+244+The activation instructions will again depend on how your shell works. Use the following to generate the completion245+script, then load it into the shell somehow.246+247+```console248+_FOO_BAR_COMPLETE=mysh_source foo-bar249+```deleted:docs/shell-completion.rst-291 removed
1-.. currentmodule:: click.shell_completion2-3-Shell Completion4-================5-6-Click provides tab completion support for Bash (version 4.4 and up),7-Zsh, and Fish. It is possible to add support for other shells too, and8-suggestions can be customized at multiple levels.9-10-Shell completion suggests command names, option names, and values for11-choice, file, and path parameter types. Options are only listed if at12-least a dash has been entered. Hidden commands and options are not13-shown.14-15-.. code-block:: text16-17- $ repo <TAB><TAB>18- clone commit copy delete setuser19- $ repo clone -<TAB><TAB>20- --deep --help --rev --shallow -r21-22-23-Enabling Completion24--------------------25-26-Completion is only available if a script is installed and invoked27-through an entry point, not through the ``python`` command. See28-:doc:`entry-points`. Once the executable is installed, calling it with29-a special environment variable will put Click in completion mode.30-31-To enable shell completion, the user needs to register a special32-function with their shell. The exact script varies depending on the33-shell you are using. Click will output it when called with34-``_{FOO_BAR}_COMPLETE`` set to ``{shell}_source``. ``{FOO_BAR}`` is35-the executable name in uppercase with dashes replaced by underscores.36-It is conventional but not strictly required for environment variable37-names to be in upper case. This convention helps distinguish environment38-variables from regular shell variables and commands, making scripts39-and configuration files more readable and easier to maintain. The40-built-in shells are ``bash``, ``zsh``, and ``fish``.41-42-Provide your users with the following instructions customized to your43-program name. This uses ``foo-bar`` as an example.44-45-.. tabs::46-47- .. group-tab:: Bash48-49- Add this to ``~/.bashrc``:50-51- .. code-block:: bash52-53- eval "$(_FOO_BAR_COMPLETE=bash_source foo-bar)"54-55- .. group-tab:: Zsh56-57- Add this to ``~/.zshrc``:58-59- .. code-block:: zsh60-61- eval "$(_FOO_BAR_COMPLETE=zsh_source foo-bar)"62-63- .. group-tab:: Fish64-65- Add this to ``~/.config/fish/completions/foo-bar.fish``:66-67- .. code-block:: fish68-69- _FOO_BAR_COMPLETE=fish_source foo-bar | source70-71- This is the same file used for the activation script method72- below. For Fish it's probably always easier to use that method.73-74-Using ``eval`` means that the command is invoked and evaluated every75-time a shell is started, which can delay shell responsiveness. To speed76-it up, write the generated script to a file, then source that. You can77-generate the files ahead of time and distribute them with your program78-to save your users a step.79-80-.. tabs::81-82- .. group-tab:: Bash83-84- Save the script somewhere.85-86- .. code-block:: bash87-88- _FOO_BAR_COMPLETE=bash_source foo-bar > ~/.foo-bar-complete.bash89-90- Source the file in ``~/.bashrc``.91-92- .. code-block:: bash93-94- . ~/.foo-bar-complete.bash95-96- .. group-tab:: Zsh97-98- Save the script somewhere.99-100- .. code-block:: bash101-102- _FOO_BAR_COMPLETE=zsh_source foo-bar > ~/.foo-bar-complete.zsh103-104- Source the file in ``~/.zshrc``.105-106- .. code-block:: bash107-108- . ~/.foo-bar-complete.zsh109-110- .. group-tab:: Fish111-112- Save the script to ``~/.config/fish/completions/foo-bar.fish``:113-114- .. code-block:: fish115-116- _FOO_BAR_COMPLETE=fish_source foo-bar > ~/.config/fish/completions/foo-bar.fish117-118-After modifying the shell config, you need to start a new shell in order119-for the changes to be loaded.120-121-122-Custom Type Completion123-----------------------124-125-When creating a custom :class:`~click.ParamType`, override its126-:meth:`~click.ParamType.shell_complete` method to provide shell127-completion for parameters with the type. The method must return a list128-of :class:`~CompletionItem` objects. Besides the value, these objects129-hold metadata that shell support might use. The built-in implementations130-use ``type`` to indicate special handling for paths, and ``help`` for131-shells that support showing a help string next to a suggestion.132-133-In this example, the type will suggest environment variables that start134-with the incomplete value.135-136-.. code-block:: python137-138- class EnvVarType(ParamType):139- name = "envvar"140-141- def shell_complete(self, ctx, param, incomplete):142- return [143- CompletionItem(name)144- for name in os.environ if name.startswith(incomplete)145- ]146-147- @click.command()148- @click.option("--ev", type=EnvVarType())149- def cli(ev):150- click.echo(os.environ[ev])151-152-153-Overriding Value Completion154----------------------------155-156-Value completions for a parameter can be customized without a custom157-type by providing a ``shell_complete`` function. The function is used158-instead of any completion provided by the type. It is passed 3 keyword159-arguments:160-161-- ``ctx`` - The current command context.162-- ``param`` - The current parameter requesting completion.163-- ``incomplete`` - The partial word that is being completed. May164- be an empty string if no characters have been entered yet.165-166-It must return a list of :class:`CompletionItem` objects, or as a167-shortcut it can return a list of strings.168-169-In this example, the command will suggest environment variables that170-start with the incomplete value.171-172-.. code-block:: python173-174- def complete_env_vars(ctx, param, incomplete):175- return [k for k in os.environ if k.startswith(incomplete)]176-177- @click.command()178- @click.argument("name", shell_complete=complete_env_vars)179- def cli(name):180- click.echo(f"Name: {name}")181- click.echo(f"Value: {os.environ[name]}")182-183-184-Adding Support for a Shell185---------------------------186-187-Support can be added for shells that do not come built in. Be sure to188-check PyPI to see if there's already a package that adds support for189-your shell. This topic is very technical, you'll want to look at Click's190-source to study the built-in implementations.191-192-Shell support is provided by subclasses of :class:`ShellComplete`193-registered with :func:`add_completion_class`. When Click is invoked in194-completion mode, it calls :meth:`~ShellComplete.source` to output the195-completion script, or :meth:`~ShellComplete.complete` to output196-completions. The base class provides default implementations that197-require implementing some smaller parts.198-199-First, you'll need to figure out how your shell's completion system200-works and write a script to integrate it with Click. It must invoke your201-program with the environment variable ``_{FOO_BAR}_COMPLETE`` set to202-``{shell}_complete`` and pass the complete args and incomplete value.203-How it passes those values, and the format of the completion response204-from Click is up to you.205-206-In your subclass, set :attr:`~ShellComplete.source_template` to the207-completion script. The default implementation will perform ``%``208-formatting with the following variables:209-210-- ``complete_func`` - A safe name for the completion function defined211- in the script.212-- ``complete_var`` - The environment variable name for passing the213- ``{shell}_complete`` instruction.214-- ``foo_bar`` - The name of the executable being completed.215-216-The example code is for a made up shell "My Shell" or "mysh" for short.217-218-.. code-block:: python219-220- from click.shell_completion import add_completion_class221- from click.shell_completion import ShellComplete222-223- _mysh_source = """\224- %(complete_func)s {225- response=$(%(complete_var)s=mysh_complete %(foo_bar)s)226- # parse response and set completions somehow227- }228- call-on-complete %(foo_bar)s %(complete_func)s229- """230-231- @add_completion_class232- class MyshComplete(ShellComplete):233- name = "mysh"234- source_template = _mysh_source235-236-Next, implement :meth:`~ShellComplete.get_completion_args`. This must237-get, parse, and return the complete args and incomplete value from the238-completion script. For example, for the Bash implementation the239-``COMP_WORDS`` env var contains the command line args as a string, and240-the ``COMP_CWORD`` env var contains the index of the incomplete arg. The241-method must return a ``(args, incomplete)`` tuple.242-243-.. code-block:: python244-245- import os246- from click.parser import split_arg_string247-248- class MyshComplete(ShellComplete):249- ...250-251- def get_completion_args(self):252- args = split_arg_string(os.environ["COMP_WORDS"])253-254- if os.environ["COMP_PARTIAL"] == "1":255- incomplete = args.pop()256- return args, incomplete257-258- return args, ""259-260-Finally, implement :meth:`~ShellComplete.format_completion`. This is261-called to format each :class:`CompletionItem` into a string. For262-example, the Bash implementation returns ``f"{item.type},{item.value}``263-(it doesn't support help strings), and the Zsh implementation returns264-each part separated by a newline, replacing empty help with a ``_``265-placeholder. This format is entirely up to what you parse with your266-completion script.267-268-The ``type`` value is usually ``plain``, but it can be another value269-that the completion script can switch on. For example, ``file`` or270-``dir`` can tell the shell to handle path completion, since the shell is271-better at that than Click.272-273-.. code-block:: python274-275- class MyshComplete(ShellComplete):276- ...277-278- def format_completion(self, item):279- return f"{item.type}\t{item.value}"280-281-With those three things implemented, the new shell support is ready. In282-case those weren't sufficient, there are more parts that can be283-overridden, but that probably isn't necessary.284-285-The activation instructions will again depend on how your shell works.286-Use the following to generate the completion script, then load it into287-the shell somehow.288-289-.. code-block:: text290-291- _FOO_BAR_COMPLETE=mysh_source foo-barmodified:docs/utils.md+13 added-11 removed
87 unmodified lines88 writes to stdout and, if possible, through a pager.89 90 Example:91 92+```{eval-rst}92-```python93-@click.command()94-def less():95- click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))93+.. click:example::94+ @click.command()95+ def less():96+ click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))97 ```98 99 If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time,100 you can pass a generator (or generator function) instead of a string:101 102+```{eval-rst}101-```python102-def _generate_output():103- for idx in range(50000):104- yield f"Line {idx}\n"103+.. click:example::104+ def _generate_output():105+ for idx in range(50000):106+ yield f"Line {idx}\n"107 106-@click.command()107-def less():108- click.echo_via_pager(_generate_output())108+ @click.command()109+ def less():110+ click.echo_via_pager(_generate_output())111 ```112 113 ## Screen Clearing114 278 unmodified linesmodified:src/click/_termui_impl.py+13 added-5 removed
15 unmodified lines16 import typing as t17 from gettext import gettext as _18 from io import StringIO19 from pathlib import Path20-from shutil import which20 from types import TracebackType21 22 from ._compat import _default_text_stdout23 from ._compat import CYGWIN209 unmodified lines233 }234 ).rstrip()235 236 def render_progress(self) -> None:238- import shutil239-237 if self.hidden:238 return239 240 if not self._is_atty:5 unmodified lines246 247 buf = []248 # Update width in case the terminal has been resized249 if self.autowidth:250+ import shutil251+252 old_width = self.width253 self.width = 0254 clutter_length = term_len(self.format_progress_line())255 new_width = max(0, shutil.get_terminal_size().columns - clutter_length)163 unmodified lines419 """420 # Split the command into the invoked CLI and its parameters.421 if not cmd_parts:422 return False423+424+ import shutil425+426 cmd = cmd_parts[0]427 cmd_params = cmd_parts[1:]428 427- cmd_filepath = which(cmd)429+ cmd_filepath = shutil.which(cmd)430 if not cmd_filepath:431 return False432 # Resolves symlinks and produces a normalized absolute path string.433 cmd_path = Path(cmd_filepath).resolve()77 unmodified lines511 """512 # Split the command into the invoked CLI and its parameters.513 if not cmd_parts:514 return False515+516+ import shutil517+518 cmd = cmd_parts[0]519 515- cmd_filepath = which(cmd)520+ cmd_filepath = shutil.which(cmd)521 if not cmd_filepath:522 return False523 # Resolves symlinks and produces a normalized absolute path string.524 cmd_path = Path(cmd_filepath).resolve()52 unmodified lines577 if rv:578 return rv579 if WIN:580 return "notepad"581+582+ from shutil import which583+584 for editor in "sensible-editor", "vim", "nano":585 if which(editor) is not None:586 return editor587 return "vi"260 unmodified linesadded:src/click/_utils.py+36 added
1+from __future__ import annotations2+3+import enum4+import typing as t5+6+7+class Sentinel(enum.Enum):8+ """Enum used to define sentinel values.9+10+ .. seealso::11+12+ `PEP 661 - Sentinel Values <https://peps.python.org/pep-0661/>`_.13+ """14+15+ UNSET = object()16+ FLAG_NEEDS_VALUE = object()17+18+ def __repr__(self) -> str:19+ return f"{self.__class__.__name__}.{self.name}"20+21+22+UNSET = Sentinel.UNSET23+"""Sentinel used to indicate that a value is not set."""24+25+FLAG_NEEDS_VALUE = Sentinel.FLAG_NEEDS_VALUE26+"""Sentinel used to indicate an option was passed as a flag without a27+value but is not a flag option.28+29+``Option.consume_value`` uses this to prompt or use the ``flag_value``.30+"""31+32+T_UNSET = t.Literal[UNSET] # type: ignore[valid-type]33+"""Type hint for the :data:`UNSET` sentinel value."""34+35+T_FLAG_NEEDS_VALUE = t.Literal[FLAG_NEEDS_VALUE] # type: ignore[valid-type]36+"""Type hint for the :data:`FLAG_NEEDS_VALUE` sentinel value."""modified:src/click/core.py+344 added-175 removed
17 unmodified lines18 from itertools import repeat19 from types import TracebackType20 21 from . import types22+from ._utils import FLAG_NEEDS_VALUE23+from ._utils import UNSET24 from .exceptions import Abort25 from .exceptions import BadParameter26 from .exceptions import ClickException27 from .exceptions import Exit3 unmodified lines31 from .formatting import HelpFormatter32 from .formatting import join_options33 from .globals import pop_context34 from .globals import push_context33-from .parser import _flag_needs_value35 from .parser import _OptionParser36 from .parser import _split_opt37 from .termui import confirm38 from .termui import prompt443 unmodified lines482 self,483 exc_type: type[BaseException] | None,484 exc_value: BaseException | None,485 tb: TracebackType | None,485- ) -> None:486+ ) -> bool | None:487 self._depth -= 1488+ exit_result: bool | None = None489 if self._depth == 0:488- self.close()490+ exit_result = self._close_with_exception_info(exc_type, exc_value, tb)491 pop_context()492 493+ return exit_result494+495 @contextmanager496 def scope(self, cleanup: bool = True) -> cabc.Iterator[Context]:497 """This helper method can be used with the context object to promote498 it to the current thread local (see :func:`get_current_context`).118 unmodified lines617 """Invoke all close callbacks registered with618 :meth:`call_on_close`, and exit all context managers entered619 with :meth:`with_resource`.620 """617- self._exit_stack.close()621+ self._close_with_exception_info(None, None, None)622+623+ def _close_with_exception_info(624+ self,625+ exc_type: type[BaseException] | None,626+ exc_value: BaseException | None,627+ tb: TracebackType | None,628+ ) -> bool | None:629+ """Unwind the exit stack by calling its :meth:`__exit__` providing the exception630+ information to allow for exception handling by the various resources registered631+ using :meth;`with_resource`632+633+ :return: Whatever ``exit_stack.__exit__()`` returns.634+ """635+ exit_result = self._exit_stack.__exit__(exc_type, exc_value, tb)636 # In case the context is reused, create a new exit stack.637 self._exit_stack = ExitStack()638 639+ return exit_result640+641 @property642 def command_path(self) -> str:643 """The computed command path. This is used for the ``usage``644 information on the help page. It's automatically created by60 unmodified lines705 .. versionchanged:: 8.0706 Added the ``call`` parameter.707 """708 if self.default_map is not None:689- value = self.default_map.get(name)709+ value = self.default_map.get(name, UNSET)710 711 if call and callable(value):712 return value()713 714 return value715 696- return None716+ return UNSET717 718 def fail(self, message: str) -> t.NoReturn:719 """Aborts the execution of the program with a specific error720 message.492 unmodified lines1213 parser = self.make_parser(ctx)1214 opts, args, param_order = parser.parse_args(args=args)1215 1216 for param in iter_params_for_processing(param_order, self.get_params(ctx)):1197- value, args = param.handle_parse_result(ctx, opts, args)1217+ _, args = param.handle_parse_result(ctx, opts, args)1218 1219 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:1220 ctx.fail(1221 ngettext(812 unmodified lines2034 otherwise it's skipped.2035 :param is_eager: eager values are processed before non eager ones. This2036 should not be set for arguments or it will inverse the2037 order of processing.2018- :param envvar: a string or list of strings that are environment variables2019- that should be checked.2038+ :param envvar: environment variable(s) that are used to provide a default value for2039+ this parameter. This can be a string or a sequence of strings. If a sequence is2040+ given, only the first non-empty environment variable is used for the parameter.2041 :param shell_complete: A function that returns custom shell2042 completions. Used instead of the param's type completion if2043 given. Takes ``ctx, param, incomplete`` and must return a list2044 of :class:`~click.shell_completion.CompletionItem` or a list of53 unmodified lines2098 self,2099 param_decls: cabc.Sequence[str] | None = None,2100 type: types.ParamType | t.Any | None = None,2101 required: bool = False,2102+ # XXX The default historically embed two concepts:2103+ # - the declaration of a Parameter object carrying the default (handy to2104+ # arbitrage the default value of coupled Parameters sharing the same2105+ # self.name, like flag options),2106+ # - and the actual value of the default.2107+ # It is confusing and is the source of many issues discussed in:2108+ # https://github.com/pallets/click/pull/30302109+ # In the future, we might think of splitting it in two, not unlike2110+ # Option.is_flag and Option.flag_value: we could have something like2111+ # Parameter.is_default and Parameter.default_value.2081- default: t.Any | t.Callable[[], t.Any] | None = None,2112+ default: t.Any | t.Callable[[], t.Any] | None = UNSET,2113 callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None = None,2114 nargs: int | None = None,2115 multiple: bool = False,2116 metavar: str | None = None,40 unmodified lines2157 f"'nargs' must be {self.type.arity} (or None) for"2158 f" type {self.type!r}, but it was {nargs}."2159 )2160 2130- # Skip no default or callable default.2131- check_default = default if not callable(default) else None2132-2133- if check_default is not None:2134- if multiple:2135- try:2136- # Only check the first value against nargs.2137- check_default = next(_check_iter(check_default), None)2138- except TypeError:2139- raise ValueError(2140- "'default' must be a list when 'multiple' is true."2141- ) from None2142-2143- # Can be None for multiple with empty default.2144- if nargs != 1 and check_default is not None:2145- try:2146- _check_iter(check_default)2147- except TypeError:2148- if multiple:2149- message = (2150- "'default' must be a list of lists when 'multiple' is"2151- " true and 'nargs' != 1."2152- )2153- else:2154- message = "'default' must be a list when 'nargs' != 1."2155-2156- raise ValueError(message) from None2157-2158- if nargs > 1 and len(check_default) != nargs:2159- subject = "item length" if multiple else "length"2160- raise ValueError(2161- f"'default' {subject} must match nargs={nargs}."2162- )2163-2161 if required and deprecated:2162 raise ValueError(2163 f"The {self.param_type_name} '{self.human_readable_name}' "2164 "is deprecated and still required. A deprecated "6 unmodified lines2171 2172 Use :meth:`click.Context.to_info_dict` to traverse the entire2173 CLI structure.2174 2175+ .. versionchanged:: 8.3.02176+ Returns ``None`` for the :attr:`default` if it was not set.2177+2178 .. versionadded:: 8.02179 """2180 return {2181 "name": self.name,3 unmodified lines2185 "type": self.type.to_info_dict(),2186 "required": self.required,2187 "nargs": self.nargs,2188 "multiple": self.multiple,2189- "default": self.default,2189+ # We explicitly hide the :attr:`UNSET` value to the user, as we choose to2190+ # make it an implementation detail. And because ``to_info_dict`` has been2191+ # designed for documentation purposes, we return ``None`` instead.2192+ "default": self.default if self.default is not UNSET else None,2193 "envvar": self.envvar,2194 }2195 2196 def __repr__(self) -> str:59 unmodified lines2256 Added the ``call`` parameter.2257 """2258 value = ctx.lookup_default(self.name, call=False) # type: ignore2259 2257- if value is None:2260+ if value is UNSET:2261 value = self.default2262 2263 if call and callable(value):2264 value = value()5 unmodified lines2270 2271 def consume_value(2272 self, ctx: Context, opts: cabc.Mapping[str, t.Any]2273 ) -> tuple[t.Any, ParameterSource]:2271- value = opts.get(self.name) # type: ignore2272- source = ParameterSource.COMMANDLINE2274+ """Returns the parameter value produced by the parser.2275 2274- if value is None:2275- value = self.value_from_envvar(ctx)2276- source = ParameterSource.ENVIRONMENT2276+ If the parser did not produce a value from user input, the value is either2277+ sourced from the environment variable, the default map, or the parameter's2278+ default value. In that order of precedence.2279 2278- if value is None:2279- value = ctx.lookup_default(self.name) # type: ignore2280- source = ParameterSource.DEFAULT_MAP2280+ If no value is found, an internal sentinel value is returned.2281 2282- if value is None:2283- value = self.get_default(ctx)2284- source = ParameterSource.DEFAULT2282+ :meta private:2283+ """2284+ # Collect from the parse the value passed by the user to the CLI.2285+ value = opts.get(self.name, UNSET) # type: ignore2286+ # If the value is set, it means it was sourced from the command line by the2287+ # parser, otherwise it left unset by default.2288+ source = (2289+ ParameterSource.COMMANDLINE2290+ if value is not UNSET2291+ else ParameterSource.DEFAULT2292+ )2293 2294+ if value is UNSET:2295+ envvar_value = self.value_from_envvar(ctx)2296+ if envvar_value is not None:2297+ value = envvar_value2298+ source = ParameterSource.ENVIRONMENT2299+2300+ if value is UNSET:2301+ default_map_value = ctx.lookup_default(self.name) # type: ignore2302+ if default_map_value is not UNSET:2303+ value = default_map_value2304+ source = ParameterSource.DEFAULT_MAP2305+2306+ if value is UNSET:2307+ default_value = self.get_default(ctx)2308+ if default_value is not UNSET:2309+ value = default_value2310+ source = ParameterSource.DEFAULT2311+2312 return value, source2313 2314 def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:2289- """Convert and validate a value against the option's2315+ """Convert and validate a value against the parameter's2316 :attr:`type`, :attr:`multiple`, and :attr:`nargs`.2317 """2292- if value is None:2293- return () if self.multiple or self.nargs == -1 else None2318+ if value in (None, UNSET):2319+ if self.multiple or self.nargs == -1:2320+ return ()2321+ else:2322+ return value2323 2324 def check_iter(value: t.Any) -> cabc.Iterator[t.Any]:2325 try:2326 return _check_iter(value)4 unmodified lines2331 raise BadParameter(2332 _("Value must be an iterable."), ctx=ctx, param=self2333 ) from None2334 2335+ # Define the conversion function based on nargs and type.2336+2337 if self.nargs == 1 or self.type.is_composite:2338 2339 def convert(value: t.Any) -> t.Any:2340 return self.type(value, param=self, ctx=ctx)26 unmodified lines2367 2368 return convert(value)2369 2370 def value_is_missing(self, value: t.Any) -> bool:2371+ """A value is considered missing if:2372+2373+ - it is :attr:`UNSET`,2374+ - or if it is an empty sequence while the parameter is suppose to have2375+ non-single value (i.e. :attr:`nargs` is not ``1`` or :attr:`multiple` is2376+ set).2377+2378+ :meta private:2379+ """2340- if value is None:2380+ if value is UNSET:2381 return True2382 2383 if (self.nargs != 1 or self.multiple) and value == ():2384 return True2385 2386 return False2387 2388 def process_value(self, ctx: Context, value: t.Any) -> t.Any:2389+ """Process the value of this parameter:2390+2391+ 1. Type cast the value using :meth:`type_cast_value`.2392+ 2. Check if the value is missing (see: :meth:`value_is_missing`), and raise2393+ :exc:`MissingParameter` if it is required.2394+ 3. If a :attr:`callback` is set, call it to have the value replaced by the2395+ result of the callback. If the value was not set, the callback receive2396+ ``None``. This keep the legacy behavior as it was before the introduction of2397+ the :attr:`UNSET` sentinel.2398+2399+ :meta private:2400+ """2401 value = self.type_cast_value(ctx, value)2402 2403 if self.required and self.value_is_missing(value):2404 raise MissingParameter(ctx=ctx, param=self)2405 2406 if self.callback is not None:2407+ # Legacy case: UNSET is not exposed directly to the callback, but converted2408+ # to None.2409+ if value is UNSET:2410+ value = None2411 value = self.callback(ctx, self, value)2412 2413 return value2414 2415 def resolve_envvar_value(self, ctx: Context) -> str | None:2360- if self.envvar is None:2416+ """Returns the value found in the environment variable(s) attached to this2417+ parameter.2418+2419+ Environment variables values are `always returned as strings2420+ <https://docs.python.org/3/library/os.html#os.environ>`_.2421+2422+ This method returns ``None`` if:2423+2424+ - the :attr:`envvar` property is not set on the :class:`Parameter`,2425+ - the environment variable is not found in the environment,2426+ - the variable is found in the environment but its value is empty (i.e. the2427+ environment variable is present but has an empty string).2428+2429+ If :attr:`envvar` is setup with multiple environment variables,2430+ then only the first non-empty value is returned.2431+2432+ .. caution::2433+2434+ The raw value extracted from the environment is not normalized and is2435+ returned as-is. Any normalization or reconciliation is performed later by2436+ the :class:`Parameter`'s :attr:`type`.2437+2438+ :meta private:2439+ """2440+ if not self.envvar:2441 return None2442 2443 if isinstance(self.envvar, str):2444 rv = os.environ.get(self.envvar)3 unmodified lines2448 else:2449 for envvar in self.envvar:2450 rv = os.environ.get(envvar)2451 2452+ # Return the first non-empty value of the list of environment variables.2453 if rv:2454 return rv2455+ # Else, absence of value is interpreted as an environment variable that2456+ # is not set, so proceed to the next one.2457 2458 return None2459 2377- def value_from_envvar(self, ctx: Context) -> t.Any | None:2378- rv: t.Any | None = self.resolve_envvar_value(ctx)2460+ def value_from_envvar(self, ctx: Context) -> str | cabc.Sequence[str] | None:2461+ """Process the raw environment variable string for this parameter.2462 2463+ Returns the string as-is or splits it into a sequence of strings if the2464+ parameter is expecting multiple values (i.e. its :attr:`nargs` property is set2465+ to a value other than ``1``).2466+2467+ :meta private:2468+ """2469+ rv = self.resolve_envvar_value(ctx)2470+2471 if rv is not None and self.nargs != 1:2381- rv = self.type.split_envvar_value(rv)2472+ return self.type.split_envvar_value(rv)2473 2474 return rv2475 2476 def handle_parse_result(2477 self, ctx: Context, opts: cabc.Mapping[str, t.Any], args: list[str]2478 ) -> tuple[t.Any, list[str]]:2479+ """Process the value produced by the parser from user input.2480+2481+ Always process the value through the Parameter's :attr:`type`, wherever it2482+ comes from.2483+2484+ If the parameter is deprecated, this method warn the user about it. But only if2485+ the value has been explicitly set by the user (and as such, is not coming from2486+ a default).2487+2488+ :meta private:2489+ """2490 with augment_usage_errors(ctx, param=self):2491 value, source = self.consume_value(ctx, opts)2492 2493+ ctx.set_parameter_source(self.name, source) # type: ignore2494+2495+ # Display a deprecation warning if necessary.2496 if (2497 self.deprecated2393- and value is not None2394- and source2395- not in (2396- ParameterSource.DEFAULT,2397- ParameterSource.DEFAULT_MAP,2398- )2498+ and value is not UNSET2499+ and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)2500 ):2501 extra_message = (2502 f" {self.deprecated}" if isinstance(self.deprecated, str) else ""2503 )6 unmodified lines2510 extra_message=extra_message,2511 )2512 echo(style(message, fg="red"), err=True)2513 2413- ctx.set_parameter_source(self.name, source) # type: ignore2414-2514+ # Process the value through the parameter's type.2515 try:2516 value = self.process_value(ctx, value)2517 except Exception:2518 if not ctx.resilient_parsing:2519 raise2520+ # In resilient parsing mode, we do not want to fail the command if the2521+ # value is incompatible with the parameter type, so we reset the value2522+ # to UNSET, which will be interpreted as a missing value.2523+ value = UNSET2524 2421- value = None2525+ # Add parameter's value to the context.2526+ if (2527+ self.expose_value2528+ # We skip adding the value if it was previously set by another parameter2529+ # targeting the same variable name. This prevents parameters competing for2530+ # the same name to override each other.2531+ and self.name not in ctx.params2532+ ):2533+ # Click is logically enforcing that the name is None if the parameter is2534+ # not to be exposed. We still assert it here to please the type checker.2535+ assert self.name is not None, (2536+ f"{self!r} parameter's name should not be None when exposing value."2537+ )2538+ # Normalize UNSET values to None, as we're about to pass them to the2539+ # command function and move them to the pure-Python realm of user-written2540+ # code.2541+ ctx.params[self.name] = value if value is not UNSET else None2542 2423- if self.expose_value:2424- ctx.params[self.name] = value # type: ignore2425-2543 return value, args2544 2545 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:2546 pass108 unmodified lines2655 confirmation_prompt: bool | str = False,2656 prompt_required: bool = True,2657 hide_input: bool = False,2658 is_flag: bool | None = None,2542- flag_value: t.Any | None = None,2659+ flag_value: t.Any = UNSET,2660 multiple: bool = False,2661 count: bool = False,2662 allow_from_autoenv: bool = True,2663 type: types.ParamType | t.Any | None = None,34 unmodified lines2698 self.prompt_required = prompt_required2699 self.hide_input = hide_input2700 self.hidden = hidden2701 2585- # If prompt is enabled but not required, then the option can be2586- # used as a flag to indicate using prompt or flag_value.2702+ # The _flag_needs_value property tells the parser that this option is a flag2703+ # that cannot be used standalone and needs a value. With this information, the2704+ # parser can determine whether to consider the next user-provided argument in2705+ # the CLI as a value for this flag or as a new option.2706+ # If prompt is enabled but not required, then it opens the possibility for the2707+ # option to gets its value from the user.2708 self._flag_needs_value = self.prompt is not None and not self.prompt_required2709 2710+ # Auto-detect if this is a flag or not.2711 if is_flag is None:2712 # Implicitly a flag because flag_value was set.2591- if flag_value is not None:2713+ if flag_value is not UNSET:2714 is_flag = True2715 # Not a flag, but when used as a flag it shows a prompt.2716 elif self._flag_needs_value:2717 is_flag = False2596- # Implicitly a flag because flag options were given.2718+ # Implicitly a flag because secondary options names were given.2719 elif self.secondary_opts:2720 is_flag = True2721+ # The option is explicitly not a flag. But we do not know yet if it needs a2722+ # value or not. So we look at the default value to determine it.2723 elif is_flag is False and not self._flag_needs_value:2600- # Not a flag, and prompt is not enabled, can be used as a2601- # flag if flag_value is set.2602- self._flag_needs_value = flag_value is not None2724+ self._flag_needs_value = self.default is UNSET2725 2604- self.default: t.Any | t.Callable[[], t.Any]2605-2726 if is_flag:2727 # Set missing default for flags if not explicitly required or prompted.2608- if self.default is None and not self.required and not self.prompt:2728+ if self.default is UNSET and not self.required and not self.prompt:2729 if multiple:2730 self.default = ()2731+2732+ # Auto-detect the type of the flag based on the flag_value.2733+ if type is None:2734+ # A flag without a flag_value is a boolean flag.2735+ if flag_value is UNSET:2736+ self.type = types.BoolParamType()2737+ # If the flag value is a boolean, use BoolParamType.2738+ elif isinstance(flag_value, bool):2739+ self.type = types.BoolParamType()2740+ # Otherwise, guess the type from the flag value.2741 else:2612- self.default = False2742+ self.type = types.convert_type(None, flag_value)2743 2614- if flag_value is None:2615- # A boolean flag presence in the command line is enough to set2616- # the value: to the default if it is not blank, or to True2617- # otherwise.2618- flag_value = self.default if self.default else True2619-2620- self.type: types.ParamType2621- if is_flag and type is None:2622- # Re-guess the type from the flag value instead of the2623- # default.2624- self.type = types.convert_type(None, flag_value)2625-2744 self.is_flag: bool = bool(is_flag)2745 self.is_bool_flag: bool = bool(2746 is_flag and isinstance(self.type, types.BoolParamType)2747 )2748 self.flag_value: t.Any = flag_value2749 2750+ # Set boolean flag default to False if unset and not required.2751+ if self.is_bool_flag:2752+ if self.default is UNSET and not self.required:2753+ self.default = False2754+2755+ # Support the special case of aligning the default value with the flag_value2756+ # for flags whose default is explicitly set to True. Note that as long as we2757+ # have this condition, there is no way a flag can have a default set to True,2758+ # and a flag_value set to something else. Refs:2759+ # https://github.com/pallets/click/issues/3024#issuecomment-31461994612760+ # https://github.com/pallets/click/pull/3030/commits/06847da2761+ if self.default is True and self.flag_value is not UNSET:2762+ self.default = self.flag_value2763+2764+ # Set the default flag_value if it is not set.2765+ if self.flag_value is UNSET:2766+ if self.is_flag:2767+ self.flag_value = True2768+ else:2769+ self.flag_value = None2770+2632- # Counting2771+ # Counting.2772 self.count = count2773 if count:2774 if type is None:2775 self.type = types.IntRange(min=0)2637- if self.default is None:2776+ if self.default is UNSET:2777 self.default = 02778 2779 self.allow_from_autoenv = allow_from_autoenv2780 self.help = help7 unmodified lines2788 2789 if self.nargs == -1:2790 raise TypeError("nargs=-1 is not supported for options.")2791 2653- if self.prompt and self.is_flag and not self.is_bool_flag:2654- raise TypeError("'prompt' is not valid for non-boolean flag.")2655-2792 if not self.is_bool_flag and self.secondary_opts:2793 raise TypeError("Secondary flag is not valid for non-boolean flag.")2794 2795 if self.is_bool_flag and self.hide_input and self.prompt is not None:8 unmodified lines2804 if self.is_flag:2805 raise TypeError("'count' is not valid with 'is_flag'.")2806 2807 def to_info_dict(self) -> dict[str, t.Any]:2808+ """2809+ .. versionchanged:: 8.3.02810+ Returns ``None`` for the :attr:`flag_value` if it was not set.2811+ """2812 info_dict = super().to_info_dict()2813 info_dict.update(2814 help=self.help,2815 prompt=self.prompt,2816 is_flag=self.is_flag,2677- flag_value=self.flag_value,2817+ # We explicitly hide the :attr:`UNSET` value to the user, as we choose to2818+ # make it an implementation detail. And because ``to_info_dict`` has been2819+ # designed for documentation purposes, we return ``None`` instead.2820+ flag_value=self.flag_value if self.flag_value is not UNSET else None,2821 count=self.count,2822 hidden=self.hidden,2823 )2824 return info_dict2825 2826 def get_error_hint(self, ctx: Context) -> str:2827 result = super().get_error_hint(ctx)2685- if self.show_envvar:2828+ if self.show_envvar and self.envvar is not None:2829 result += f" (env var: '{self.envvar}')"2830 return result2831 2832 def _parse_decls(176 unmodified lines3009 show_default = self.show_default3010 elif ctx.show_default is not None:3011 show_default = ctx.show_default3012 2870- if show_default_is_str or (show_default and (default_value is not None)):3013+ if show_default_is_str or (3014+ show_default and (default_value not in (None, UNSET))3015+ ):3016 if show_default_is_str:3017 default_string = f"({self.show_default})"3018 elif isinstance(default_value, (list, tuple)):3019 default_string = ", ".join(str(d) for d in default_value)31 unmodified lines3051 extra["required"] = "required"3052 3053 return extra3054 2910- @t.overload2911- def get_default(2912- self, ctx: Context, call: t.Literal[True] = True2913- ) -> t.Any | None: ...2914-2915- @t.overload2916- def get_default(2917- self, ctx: Context, call: bool = ...2918- ) -> t.Any | t.Callable[[], t.Any] | None: ...2919-2920- def get_default(2921- self, ctx: Context, call: bool = True2922- ) -> t.Any | t.Callable[[], t.Any] | None:2923- # If we're a non boolean flag our default is more complex because2924- # we need to look at all flags in the same group to figure out2925- # if we're the default one in which case we return the flag2926- # value as default.2927- if self.is_flag and not self.is_bool_flag:2928- for param in ctx.command.params:2929- if param.name == self.name and param.default is not None:2930- return t.cast(Option, param).default2931-2932- return None2933-2934- return super().get_default(ctx, call=call)2935-3055 def prompt_for_value(self, ctx: Context) -> t.Any:3056 """This is an alternative flow that can be activated in the full3057 value processing if a value does not exist. It will prompt the3058 user until a valid value exists and then returns the processed3059 value as result.3060 """3061 assert self.prompt is not None3062 2944- # Calculate the default before prompting anything to be stable.3063+ # Calculate the default before prompting anything to lock in the value before3064+ # attempting any user interaction.3065 default = self.get_default(ctx)3066 2947- # If this is a prompt for a flag we need to handle this2948- # differently.3067+ # A boolean flag can use a simplified [y/n] confirmation prompt.3068 if self.is_bool_flag:3069+ # If we have no boolean default, we force the user to explicitly provide3070+ # one.3071+ if default in (UNSET, None):3072+ default = None3073+ # Nothing prevent you to declare an option that is simultaneously:3074+ # 1) auto-detected as a boolean flag,3075+ # 2) allowed to prompt, and3076+ # 3) still declare a non-boolean default.3077+ # This forced casting into a boolean is necessary to align any non-boolean3078+ # default to the prompt, which is going to be a [y/n]-style confirmation3079+ # because the option is still a boolean flag. That way, instead of [y/n],3080+ # we get [Y/n] or [y/N] depending on the truthy value of the default.3081+ # Refs: https://github.com/pallets/click/pull/3030#discussion_r22891802493082+ else:3083+ default = bool(default)3084 return confirm(self.prompt, default)3085 3086 # If show_default is set to True/False, provide this to `prompt` as well. For3087 # non-bool values of `show_default`, we use `prompt`'s default behavior2 unmodified lines3090 prompt_kwargs["show_default"] = self.show_default3091 3092 return prompt(3093 self.prompt,2960- default=default,3094+ # Use ``None`` to inform the prompt() function to reiterate until a valid3095+ # value is provided by the user if we have no default.3096+ default=None if default is UNSET else default,3097 type=self.type,3098 hide_input=self.hide_input,3099 show_choices=self.show_choices,3100 confirmation_prompt=self.confirmation_prompt,1 unmodified line3102 **prompt_kwargs,3103 )3104 3105 def resolve_envvar_value(self, ctx: Context) -> str | None:2970- """Find which environment variable to read for this option and return2971- its value.3106+ """:class:`Option` resolves its environment variable the same way as3107+ :func:`Parameter.resolve_envvar_value`, but it also supports3108+ :attr:`Context.auto_envvar_prefix`. If we could not find an environment from3109+ the :attr:`envvar` property, we fallback on :attr:`Context.auto_envvar_prefix`3110+ to build dynamiccaly the environment variable name using the3111+ :python:`{ctx.auto_envvar_prefix}_{self.name.upper()}` template.3112 2973- Returns the value of the environment variable if it exists, or ``None``2974- if it does not.2975-2976- .. caution::2977-2978- The raw value extracted from the environment is not normalized and2979- is returned as-is. Any normalization or reconciation with the2980- option's type should happen later.3113+ :meta private:3114 """3115 rv = super().resolve_envvar_value(ctx)3116 3117 if rv is not None:11 unmodified lines3129 return rv3130 3131 return None3132 3000- def value_from_envvar(self, ctx: Context) -> t.Any | None:3001- """Normalize the value from the environment variable, if it exists."""3002- rv: str | None = self.resolve_envvar_value(ctx)3133+ def value_from_envvar(self, ctx: Context) -> t.Any:3134+ """For :class:`Option`, this method processes the raw environment variable3135+ string the same way as :func:`Parameter.value_from_envvar` does.3136 3137+ But in the case of non-boolean flags, the value is analyzed to determine if the3138+ flag is activated or not, and returns a boolean of its activation, or the3139+ :attr:`flag_value` if the latter is set.3140+3141+ This method also takes care of repeated options (i.e. options with3142+ :attr:`multiple` set to ``True``).3143+3144+ :meta private:3145+ """3146+ rv = self.resolve_envvar_value(ctx)3147+3148+ # Absent environment variable or an empty string is interpreted as unset.3149 if rv is None:3150 return None3151 3152 # Non-boolean flags are more liberal in what they accept. But a flag being a3008- # flag, its envvar value still needs to analyzed to determine if the flag is3153+ # flag, its envvar value still needs to be analyzed to determine if the flag is3154 # activated or not.3155 if self.is_flag and not self.is_bool_flag:3156 # If the flag_value is set and match the envvar value, return it3157 # directly.3013- if self.flag_value is not None and rv == self.flag_value:3158+ if self.flag_value is not UNSET and rv == self.flag_value:3159 return self.flag_value3160 # Analyze the envvar value as a boolean to know if the flag is3161 # activated or not.3162 return types.BoolParamType.str_to_bool(rv)11 unmodified lines3174 3175 def consume_value(3176 self, ctx: Context, opts: cabc.Mapping[str, Parameter]3177 ) -> tuple[t.Any, ParameterSource]:3178+ """For :class:`Option`, the value can be collected from an interactive prompt3179+ if the option is a flag that needs a value (and the :attr:`prompt` property is3180+ set).3181+3182+ Additionally, this method handles flag option that are activated without a3183+ value, in which case the :attr:`flag_value` is returned.3184+3185+ :meta private:3186+ """3187 value, source = super().consume_value(ctx, opts)3188 3035- # The parser will emit a sentinel value if the option can be3036- # given as a flag without a value. This is different from None3037- # to distinguish from the flag not being given at all.3038- if value is _flag_needs_value:3189+ # The parser will emit a sentinel value if the option is allowed to as a flag3190+ # without a value.3191+ if value is FLAG_NEEDS_VALUE:3192+ # If the option allows for a prompt, we start an interaction with the user.3193 if self.prompt is not None and not ctx.resilient_parsing:3194 value = self.prompt_for_value(ctx)3195 source = ParameterSource.PROMPT3196+ # Else the flag takes its flag_value as value.3197 else:3198 value = self.flag_value3199 source = ParameterSource.COMMANDLINE3200 3046- # A flag which is activated and has a flag_value set, should returns3047- # the latter, unless the value comes from the explicitly sets default.3201+ # A flag which is activated always returns the flag value, unless the value3202+ # comes from the explicitly sets default.3203 elif (3204 self.is_flag3205 and value is True3206 and not self.is_bool_flag3052- and self.flag_value is not None3053- and source is not ParameterSource.DEFAULT3207+ and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)3208 ):3209 value = self.flag_value3210 3211+ # Re-interpret a multiple option which has been sent as-is by the parser.3212+ # Here we replace each occurrence of value-less flags (marked by the3213+ # FLAG_NEEDS_VALUE sentinel) with the flag_value.3214 elif (3215 self.multiple3059- and value is not None3060- and any(v is _flag_needs_value for v in value)3216+ and value is not UNSET3217+ and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)3218+ and any(v is FLAG_NEEDS_VALUE for v in value)3219 ):3062- value = [self.flag_value if v is _flag_needs_value else v for v in value]3220+ value = [self.flag_value if v is FLAG_NEEDS_VALUE else v for v in value]3221 source = ParameterSource.COMMANDLINE3222 3065- # The value wasn't set, or used the param's default, prompt if3066- # prompting is enabled.3223+ # The value wasn't set, or used the param's default, prompt for one to the user3224+ # if prompting is enabled.3225 elif (3068- source in {None, ParameterSource.DEFAULT}3226+ (3227+ value is UNSET3228+ or source in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)3229+ )3230 and self.prompt is not None3231 and (self.required or self.prompt_required)3232 and not ctx.resilient_parsing3233 ):1 unmodified line3235 source = ParameterSource.PROMPT3236 3237 return value, source3238 3239+ def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:3240+ if self.is_flag and not self.required:3241+ if value is UNSET:3242+ if self.is_bool_flag:3243+ # If the flag is a boolean flag, we return False if it is not set.3244+ value = False3245+ return super().type_cast_value(ctx, value)3246 3247+3248 class Argument(Parameter):3249 """Arguments are positional parameters to a command. They generally3250 provide fewer features than options but can have infinite ``nargs``3251 and are required by default.8 unmodified lines3260 param_decls: cabc.Sequence[str],3261 required: bool | None = None,3262 **attrs: t.Any,3263 ) -> None:3264+ # Auto-detect the requirement status of the argument if not explicitly set.3265 if required is None:3096- if attrs.get("default") is not None:3097- required = False3098- else:3266+ # The argument gets automatically required if it has no explicit default3267+ # value set and is setup to match at least one value.3268+ if attrs.get("default", UNSET) is UNSET:3269 required = attrs.get("nargs", 1) > 03270+ # If the argument has a default value, it is not required.3271+ else:3272+ required = False3273 3274 if "multiple" in attrs:3275 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.")3276 3277 super().__init__(param_decls, required=required, **attrs)3278 3106- if __debug__:3107- if self.default is not None and self.nargs == -1:3108- raise TypeError("'default' is not supported for nargs=-1.")3109-3279 @property3280 def human_readable_name(self) -> str:3281 if self.metavar is not None:3282 return self.metavar65 unmodified linesmodified:src/click/formatting.py+2 added-2 removed
117 unmodified lines118 indent_increment: int = 2,119 width: int | None = None,120 max_width: int | None = None,121 ) -> None:122- import shutil123-122 self.indent_increment = indent_increment123 if max_width is None:124 max_width = 80125 if width is None:126+ import shutil127+128 width = FORCED_WIDTH129 if width is None:130 width = max(min(shutil.get_terminal_size().columns, max_width) - 2, 50)131 self.width = width170 unmodified linesmodified:src/click/parser.py+24 added-24 removed
28 unmodified lines29 from collections import deque30 from gettext import gettext as _31 from gettext import ngettext32 33+from ._utils import FLAG_NEEDS_VALUE34+from ._utils import UNSET35 from .exceptions import BadArgumentUsage36 from .exceptions import BadOptionUsage37 from .exceptions import NoSuchOption38 from .exceptions import UsageError39 40 if t.TYPE_CHECKING:41+ from ._utils import T_FLAG_NEEDS_VALUE42+ from ._utils import T_UNSET43 from .core import Argument as CoreArgument44 from .core import Context45 from .core import Option as CoreOption46 from .core import Parameter as CoreParameter47 48 V = t.TypeVar("V")49 46-# Sentinel value that indicates an option was passed as a flag without a47-# value but is not a flag option. Option.consume_value uses this to48-# prompt or use the flag_value.49-_flag_needs_value = object()50 51-51 def _unpack_args(52 args: cabc.Sequence[str], nargs_spec: cabc.Sequence[int]53 ) -> tuple[cabc.Sequence[str | cabc.Sequence[str | None] | None], list[str]]:54 """Given an iterable of arguments and an iterable of nargs specifications,2 unmodified lines57 58 The nargs specification is the number of arguments that should be consumed59 or `-1` to indicate that this position should eat up all the remainders.60 62- Missing items are filled with `None`.61+ Missing items are filled with ``UNSET``.62 """63 args = deque(args)64 nargs_spec = deque(nargs_spec)66- rv: list[str | tuple[str | None, ...] | None] = []65+ rv: list[str | tuple[str | T_UNSET, ...] | T_UNSET] = []66 spos: int | None = None67 69- def _fetch(c: deque[V]) -> V | None:68+ def _fetch(c: deque[V]) -> V | T_UNSET:69 try:70 if spos is None:71 return c.popleft()72 else:73 return c.pop()74 except IndexError:76- return None75+ return UNSET76 77 while nargs_spec:78 nargs = _fetch(nargs_spec)79 80 if nargs is None:81 continue82 83 if nargs == 1:85- rv.append(_fetch(args))84+ rv.append(_fetch(args)) # type: ignore[arg-type]85 elif nargs > 1:86 x = [_fetch(args) for _ in range(nargs)]87 88 # If we're reversed, we're pulling in the arguments in reverse,6 unmodified lines95 if spos is not None:96 raise TypeError("Cannot have two nargs < 0")97 98 spos = len(rv)100- rv.append(None)99+ rv.append(UNSET)100 101 # spos is the position of the wildcard (star). If it's not `None`,102 # we fill it with the remainder.103 if spos is not None:81 unmodified lines185 self.obj = obj186 187 def process(188 self,190- value: str | cabc.Sequence[str | None] | None,189+ value: str | cabc.Sequence[str | None] | None | T_UNSET,190 state: _ParsingState,191 ) -> None:192 if self.nargs > 1:194- assert value is not None195- holes = sum(1 for x in value if x is None)193+ assert isinstance(value, cabc.Sequence)194+ holes = sum(1 for x in value if x is UNSET)195 if holes == len(value):197- value = None196+ value = UNSET197 elif holes != 0:198 raise BadArgumentUsage(199 _("Argument {name!r} takes {nargs} values.").format(200 name=self.dest, nargs=self.nargs201 )202 )203 205- if self.nargs == -1 and self.obj.envvar is not None and value == ():206- # Replace empty tuple with None so that a value from the207- # environment may be tried.208- value = None204+ # We failed to collect any argument value so we consider the argument as unset.205+ if value == ():206+ value = UNSET207 208 state.opts[self.dest] = value # type: ignore209 state.order.append(self.obj)210 170 unmodified lines381 opt, _("Option {name!r} does not take a value.").format(name=opt)382 )383 384 else:387- value = None385+ value = UNSET386 387 option.process(value, state)388 389 def _match_short_opt(self, arg: str, state: _ParsingState) -> None:21 unmodified lines411 412 value = self._get_value_from_state(opt, option, state)413 414 else:417- value = None415+ value = UNSET416 417 option.process(value, state)418 419 if stop:7 unmodified lines427 state.largs.append(f"{prefix}{''.join(unknown_options)}")428 429 def _get_value_from_state(430 self, option_name: str, option: _Option, state: _ParsingState433- ) -> t.Any:431+ ) -> str | cabc.Sequence[str] | T_FLAG_NEEDS_VALUE:432 nargs = option.nargs433 434+ value: str | cabc.Sequence[str] | T_FLAG_NEEDS_VALUE435+436 if len(state.rargs) < nargs:437 if option.obj._flag_needs_value:438 # Option allows omitting the value.439- value = _flag_needs_value439+ value = FLAG_NEEDS_VALUE440 else:441 raise BadOptionUsage(442 option_name,443 ngettext(12 unmodified lines456 and len(next_rarg) > 1457 ):458 # The next arg looks like the start of an option, don't459 # use it as the value if omitting the value is allowed.460- value = _flag_needs_value460+ value = FLAG_NEEDS_VALUE461 else:462 value = state.rargs.pop(0)463 else:464 value = tuple(state.rargs[:nargs])68 unmodified linesmodified:src/click/shell_completion.py+3 added
403 unmodified lines404 405 def get_completion_args(self) -> tuple[list[str], str]:406 cwords = split_arg_string(os.environ["COMP_WORDS"])407 incomplete = os.environ["COMP_CWORD"]408+ if incomplete:409+ incomplete = split_arg_string(incomplete)[0]410 args = cwords[1:]411 412 # Fish stores the partial word in both COMP_WORDS and413 # COMP_CWORD, remove it from complete args.139 unmodified lines553 break554 555 if _start_of_option(ctx, arg):556 last_option = arg557+ break558 559 return last_option is not None and last_option in param.opts560 561 106 unmodified linesmodified:src/click/testing.py+10 added-10 removed
3 unmodified lines4 import contextlib5 import io6 import os7 import shlex8-import shutil8 import sys9 import tempfile10 import typing as t11 from types import TracebackType114 unmodified lines126 @property127 def mode(self) -> str:128 return self._mode129 131- def __next__(self) -> str: # type: ignore132- try:133- line = super().__next__()134- except StopIteration as e:135- raise EOFError() from e136- return line130 138-131 def make_input_stream(132 input: str | bytes | t.IO[t.Any] | None, charset: str133 ) -> t.BinaryIO:134 # Is already an input stream.216 unmodified lines351 352 @_pause_echo(echo_input) # type: ignore353 def visible_input(prompt: str | None = None) -> str:354 sys.stdout.write(prompt or "")355+ try:363- val = next(text_input).rstrip("\r\n")356+ val = next(text_input).rstrip("\r\n")357+ except StopIteration as e:358+ raise EOFError() from e359 sys.stdout.write(f"{val}\n")360 sys.stdout.flush()361 return val362 363 @_pause_echo(echo_input) # type: ignore364 def hidden_input(prompt: str | None = None) -> str:365 sys.stdout.write(f"{prompt or ''}\n")366 sys.stdout.flush()367+ try:372- return next(text_input).rstrip("\r\n")368+ return next(text_input).rstrip("\r\n")369+ except StopIteration as e:370+ raise EOFError() from e371 372 @_pause_echo(echo_input) # type: ignore373 def _getchar(echo: bool) -> str:374 char = sys.stdin.read(1)193 unmodified lines568 finally:569 os.chdir(cwd)570 571 if temp_dir is None:572+ import shutil573+574 try:575 shutil.rmtree(dt)576 except OSError:577 passmodified:tests/test_arguments.py+150 added-30 removed
2 unmodified lines3 4 import pytest5 6 import click7+from click._utils import UNSET8 9 10 def test_nargs_star(runner):11 @click.command()7 unmodified lines19 assert not result.exception20 assert result.output.splitlines() == ["src=foo.txt|bar.txt", "dst=dir"]21 22 22-def test_argument_unbounded_nargs_cant_have_default(runner):23- with pytest.raises(TypeError, match="nargs=-1"):24-25- @click.command()26- @click.argument("src", nargs=-1, default=["42"])27- def copy(src):28- pass29-30-23 def test_nargs_tup(runner):24 @click.command()25 @click.argument("name", nargs=1)26 @click.argument("point", nargs=2, type=click.INT)27 unmodified lines54 assert result.exception is None55 assert result.output.splitlines() == ["name=peter id=1"]56 57 58+def test_nargs_mismatch_with_tuple_type():59+ with pytest.raises(ValueError, match="nargs.*must be 2.*but it was 3"):60+61+ @click.command()62+ @click.argument("test", type=(str, int), nargs=3)63+ def cli(_):64+ pass65+66+67 def test_nargs_err(runner):68 @click.command()69 @click.argument("x")70 def copy(x):94 unmodified lines165 166 result = runner.invoke(inout, [])167 assert not result.exception168 assert result.output == "Foo bar baz\n"169+ assert result.stdout == "Foo bar baz\n"170+ assert not result.stderr171 172 173 @pytest.mark.parametrize(174 ("nargs", "value", "expect"),69 unmodified lines244 assert result.exit_code == 2245 assert "Missing argument 'ARG'." in result.output246 247 245-def test_missing_argument_string_cast():248+@pytest.mark.parametrize(249+ ("value", "expect_missing", "processed_value"),250+ [251+ # Unspecified type of the argument fallback to string, so everything is252+ # processed the click.STRING type.253+ ("", False, ""),254+ (" ", False, " "),255+ ("foo", False, "foo"),256+ ("12", False, "12"),257+ (12, False, "12"),258+ (12.1, False, "12.1"),259+ (list(), False, "[]"),260+ (tuple(), False, "()"),261+ (set(), False, "set()"),262+ (frozenset(), False, "frozenset()"),263+ (dict(), False, "{}"),264+ # None is a value that is allowed to be processed by a required argument265+ # because at this stage, the process_value method happens after the default is266+ # applied.267+ (None, False, None),268+ # An UNSET required argument will raise MissingParameter.269+ (UNSET, True, None),270+ ],271+)272+def test_required_argument(value, expect_missing, processed_value):273+ """Test how a required argument is processing the provided values."""274 ctx = click.Context(click.Command(""))275+ argument = click.Argument(["a"], required=True)276 277+ if expect_missing:248- with pytest.raises(click.MissingParameter) as excinfo:249- click.Argument(["a"], required=True).process_value(ctx, None)278+ with pytest.raises(click.MissingParameter) as excinfo:279+ argument.process_value(ctx, value)280+ assert str(excinfo.value) == "Missing parameter: a"281 251- assert str(excinfo.value) == "Missing parameter: a"282+ else:283+ value = argument.process_value(ctx, value)284+ assert value == processed_value285 286 287 def test_implicit_non_required(runner):288 @click.command()85 unmodified lines374 result = runner.invoke(cmd, ["a", "b", "c", "d", "e", "f"])375 assert result.output.splitlines() == ["('a', 'b', 'c')", "d", "('e', 'f')"]376 377 345-def test_defaults_for_nargs(runner):378+@pytest.mark.parametrize(379+ ("argument_params", "args", "expected"),380+ [381+ # Any iterable with the same number of arguments as nargs is valid.382+ [{"nargs": 2, "default": (1, 2)}, [], (1, 2)],383+ [{"nargs": 2, "default": (1.1, 2.2)}, [], (1, 2)],384+ [{"nargs": 2, "default": ("1", "2")}, [], (1, 2)],385+ [{"nargs": 2, "default": (None, None)}, [], (None, None)],386+ [{"nargs": 2, "default": [1, 2]}, [], (1, 2)],387+ [{"nargs": 2, "default": {1, 2}}, [], (1, 2)],388+ [{"nargs": 2, "default": frozenset([1, 2])}, [], (1, 2)],389+ [{"nargs": 2, "default": {1: "a", 2: "b"}}, [], (1, 2)],390+ # Empty iterable is valid if default is None.391+ [{"nargs": 2, "default": None}, [], None],392+ # Arguments overrides the default.393+ [{"nargs": 2, "default": (1, 2)}, ["3", "4"], (3, 4)],394+ # Unbounded arguments are allowed to have a default.395+ # See: https://github.com/pallets/click/issues/2164396+ [{"nargs": -1, "default": [42]}, [], (42,)],397+ [{"nargs": -1, "default": None}, [], ()],398+ [{"nargs": -1, "default": {1, 2, 3, 4, 5}}, [], (1, 2, 3, 4, 5)],399+ ],400+)401+def test_good_defaults_for_nargs(runner, argument_params, args, expected):402 @click.command()347- @click.argument("a", nargs=2, type=int, default=(1, 2))403+ @click.argument("a", type=int, **argument_params)404 def cmd(a):349- x, y = a350- click.echo(x + y)405+ click.echo(repr(a), nl=False)406 352- result = runner.invoke(cmd, [])353- assert result.output.strip() == "3"407+ result = runner.invoke(cmd, args)408+ assert result.output == repr(expected)409 355- result = runner.invoke(cmd, ["3", "4"])356- assert result.output.strip() == "7"410 358- result = runner.invoke(cmd, ["3"])359- assert result.exception is not None360- assert "Argument 'a' takes 2 values." in result.output411+@pytest.mark.parametrize(412+ ("default", "message"),413+ [414+ # Non-iterables defaults.415+ ["Yo", "Error: Invalid value for '[A]...': Value must be an iterable."],416+ ["", "Error: Invalid value for '[A]...': Value must be an iterable."],417+ [True, "Error: Invalid value for '[A]...': Value must be an iterable."],418+ [False, "Error: Invalid value for '[A]...': Value must be an iterable."],419+ [12, "Error: Invalid value for '[A]...': Value must be an iterable."],420+ [7.9, "Error: Invalid value for '[A]...': Value must be an iterable."],421+ # Generator default.422+ [(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],423+ # Unset default.424+ [UNSET, "Error: Missing argument 'A...'."],425+ # Tuples defaults with wrong length.426+ [427+ tuple(),428+ "Error: Invalid value for '[A]...': Takes 2 values but 0 were given.",429+ ],430+ [(1,), "Error: Invalid value for '[A]...': Takes 2 values but 1 was given."],431+ [432+ (1, 2, 3),433+ "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",434+ ],435+ # Lists defaults with wrong length.436+ [list(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],437+ [[1], "Error: Invalid value for '[A]...': Takes 2 values but 1 was given."],438+ [439+ [1, 2, 3],440+ "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",441+ ],442+ # Sets defaults with wrong length.443+ [set(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],444+ [445+ set([1]),446+ "Error: Invalid value for '[A]...': Takes 2 values but 1 was given.",447+ ],448+ [449+ set([1, 2, 3]),450+ "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",451+ ],452+ # Frozensets defaults with wrong length.453+ [454+ frozenset(),455+ "Error: Invalid value for '[A]...': Takes 2 values but 0 were given.",456+ ],457+ [458+ frozenset([1]),459+ "Error: Invalid value for '[A]...': Takes 2 values but 1 was given.",460+ ],461+ [462+ frozenset([1, 2, 3]),463+ "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",464+ ],465+ # Dictionaries defaults with wrong length.466+ [dict(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],467+ [468+ {1: "a"},469+ "Error: Invalid value for '[A]...': Takes 2 values but 1 was given.",470+ ],471+ [472+ {1: "a", 2: "b", 3: "c"},473+ "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",474+ ],475+ ],476+)477+def test_bad_defaults_for_nargs(runner, default, message):478+ """Some defaults are not valid when nargs is set."""479 480+ @click.command()481+ @click.argument("a", nargs=2, type=int, default=default)482+ def cmd(a):483+ click.echo(repr(a))484 485+ result = runner.invoke(cmd, [])486+ assert message in result.stderr487+488+489 def test_multiple_param_decls_not_allowed(runner):490 with pytest.raises(TypeError):491 492 @click.command()6 unmodified lines499 with pytest.raises(TypeError, match="multiple"):500 click.Argument(["a"], multiple=True)501 502 377-@pytest.mark.parametrize("value", [(), ("a",), ("a", "b", "c")])378-def test_nargs_bad_default(runner, value):379- with pytest.raises(ValueError, match="nargs=2"):380- click.Argument(["a"], nargs=2, default=value)381-382-503 def test_subcommand_help(runner):504 @click.group()505 @click.argument("name")506 @click.argument("val")75 unmodified linesmodified:tests/test_basic.py+86 added-9 removed
5 unmodified lines6 7 import pytest8 9 import click10+from click._utils import UNSET11 12 13 def test_basic_functionality(runner):14 @click.command()190 unmodified lines205 else:206 assert result.exception is None207 208 208-@pytest.mark.parametrize("default", [True, False])209 @pytest.mark.parametrize(210- ("args", "expect"), [(["--on"], True), (["--off"], False), ([], None)]210+ ("args", "default", "expect"),211+ [212+ (["--on"], True, True),213+ (["--on"], False, True),214+ (["--on"], None, True),215+ (["--on"], UNSET, True),216+ (["--off"], True, False),217+ (["--off"], False, False),218+ (["--off"], None, False),219+ (["--off"], UNSET, False),220+ ([], True, True),221+ ([], False, False),222+ ([], None, None),223+ ([], UNSET, False),224+ ],225 )212-def test_boolean_switch(runner, default, args, expect):226+def test_boolean_switch(runner, args, default, expect):227 @click.command()228 @click.option("--on/--off", default=default)229 def cli(on):230 return on231 218- if expect is None:219- expect = default220-232 result = runner.invoke(cli, args, standalone_mode=False)233 assert result.return_value is expect234 235 3 unmodified lines239 (True, ["--f"], True),240 (True, [], True),241 (False, ["--f"], True),242 (False, [], False),243+ # Boolean flags have a 3-states logic.244+ # See: https://github.com/pallets/click/issues/3024#issue-3285556668245+ (None, ["--f"], True),246+ (None, [], None),247 ),248 )249 def test_boolean_flag(runner, default, args, expect):250 @click.command()24 unmodified lines275 result = runner.invoke(cli, ["--flag", value.title()])276 assert result.output == expect277 278 279+@pytest.mark.parametrize(280+ ("default", "args", "expected"),281+ # These test cases are similar to the ones in282+ # tests/test_options.py::test_default_dual_option_callback, so keep them in sync.283+ (284+ # Each option is returning its own flag_value, whatever the default is.285+ (True, ["--upper"], "upper"),286+ (True, ["--lower"], "lower"),287+ (False, ["--upper"], "upper"),288+ (False, ["--lower"], "lower"),289+ (None, ["--upper"], "upper"),290+ (None, ["--lower"], "lower"),291+ (UNSET, ["--upper"], "upper"),292+ (UNSET, ["--lower"], "lower"),293+ # Check that the last option wins when both are specified.294+ (True, ["--upper", "--lower"], "lower"),295+ (True, ["--lower", "--upper"], "upper"),296+ # Check that the default is returned as-is when no option is specified.297+ ("upper", [], "upper"),298+ ("lower", [], "lower"),299+ ("uPPer", [], "uPPer"),300+ ("lOwEr", [], "lOwEr"),301+ (" ᕕ( ᐛ )ᕗ ", [], " ᕕ( ᐛ )ᕗ "),302+ (None, [], None),303+ # Default is normalized to None if it is UNSET.304+ (UNSET, [], None),305+ # Special case: if default=True and flag_value is set, the value returned is the306+ # flag_value, not the True Python value itself.307+ (True, [], "upper"),308+ # Non-string defaults are process as strings by the default Parameter's type.309+ (False, [], "False"),310+ (42, [], "42"),311+ (12.3, [], "12.3"),312+ ),313+)314+def test_flag_value_dual_options(runner, default, args, expected):315+ """Check how default is processed when options compete for the same variable name.316+317+ Covers the regression reported in318+ https://github.com/pallets/click/issues/3024#issuecomment-3146199461319+ """320+321+ @click.command()322+ @click.option("--upper", "case", flag_value="upper", default=default)323+ @click.option("--lower", "case", flag_value="lower")324+ def cli(case):325+ click.echo(repr(case), nl=False)326+327+ result = runner.invoke(cli, args)328+ assert result.output == repr(expected)329+330+331 def test_file_option(runner):332 @click.command()333 @click.option("--file", type=click.File("w"))334 def input(file):206 unmodified lines541 "method", type=click.Choice(["not-none", None], case_sensitive=False)542 )543 def cli(method: str | None):544 assert isinstance(method, str) or method is None478- click.echo(method)545+ click.echo(repr(method), nl=False)546 547 result = runner.invoke(cli, ["not-none"])548 assert not result.exception482- assert result.output == "not-none\n"549+ assert result.output == repr("not-none")550 484- # None is not yet supported.551 result = runner.invoke(cli, ["none"])552+ assert not result.exception553+ assert result.output == repr(None)554+555+ result = runner.invoke(cli, [])556 assert result.exception557+ assert (558+ "Error: Missing argument '{not-none|none}'. "559+ "Choose from:\n\tnot-none,\n\tnone\n" in result.stderr560+ )561 562+ result = runner.invoke(cli, ["--help"])563+ assert result.output.startswith("Usage: cli [OPTIONS] {not-none|none}\n")564 565+566 def test_datetime_option_default(runner):567 @click.command()568 @click.option("--start_date", type=click.DateTime())569 def cli(start_date):166 unmodified linesmodified:tests/test_chain.py+2 added-2 removed
161 unmodified lines162 163 return processor164 165 result = runner.invoke(cli, args, input=input)166- # last two lines are '' and 'Aborted!'167- assert result.output.splitlines()[:-2] == expect166+ assert not result.exception167+ assert result.output.splitlines() == expect168 169 170 def test_args_and_chain(runner):171 @click.group(chain=True)74 unmodified linesmodified:tests/test_context.py+127 added
1 import logging2+from contextlib import AbstractContextManager3 from contextlib import contextmanager4+from types import TracebackType5 6 import pytest7 8 import click415 unmodified lines424 425 assert rv == [0]426 427 428+def test_with_resource_exception() -> None:429+ class TestContext(AbstractContextManager[list[int]]):430+ _handle_exception: bool431+ _base_val: int432+ val: list[int]433+434+ def __init__(self, base_val: int = 1, *, handle_exception: bool = True) -> None:435+ self._handle_exception = handle_exception436+ self._base_val = base_val437+438+ def __enter__(self) -> list[int]:439+ self.val = [self._base_val]440+ return self.val441+442+ def __exit__(443+ self,444+ exc_type: type[BaseException] | None,445+ exc_value: BaseException | None,446+ traceback: TracebackType | None,447+ ) -> bool | None:448+ if not exc_type:449+ self.val[0] = self._base_val - 1450+ return None451+452+ self.val[0] = self._base_val + 1453+ return self._handle_exception454+455+ class TestException(Exception):456+ pass457+458+ ctx = click.Context(click.Command("test"))459+460+ base_val = 1461+462+ with ctx.scope():463+ rv = ctx.with_resource(TestContext(base_val=base_val))464+ assert rv[0] == base_val465+466+ assert rv == [base_val - 1]467+468+ with ctx.scope():469+ rv = ctx.with_resource(TestContext(base_val=base_val))470+ raise TestException()471+472+ assert rv == [base_val + 1]473+474+ with pytest.raises(TestException):475+ with ctx.scope():476+ rv = ctx.with_resource(477+ TestContext(base_val=base_val, handle_exception=False)478+ )479+ raise TestException()480+481+482+def test_with_resource_nested_exception() -> None:483+ class TestContext(AbstractContextManager[list[int]]):484+ _handle_exception: bool485+ _base_val: int486+ val: list[int]487+488+ def __init__(self, base_val: int = 1, *, handle_exception: bool = True) -> None:489+ self._handle_exception = handle_exception490+ self._base_val = base_val491+492+ def __enter__(self) -> list[int]:493+ self.val = [self._base_val]494+ return self.val495+496+ def __exit__(497+ self,498+ exc_type: type[BaseException] | None,499+ exc_value: BaseException | None,500+ traceback: TracebackType | None,501+ ) -> bool | None:502+ if not exc_type:503+ self.val[0] = self._base_val - 1504+ return None505+506+ self.val[0] = self._base_val + 1507+ return self._handle_exception508+509+ class TestException(Exception):510+ pass511+512+ ctx = click.Context(click.Command("test"))513+ base_val = 1514+ base_val_nested = 11515+516+ with ctx.scope():517+ rv = ctx.with_resource(TestContext(base_val=base_val))518+ rv_nested = ctx.with_resource(TestContext(base_val=base_val_nested))519+ assert rv[0] == base_val520+ assert rv_nested[0] == base_val_nested521+522+ assert rv == [base_val - 1]523+ assert rv_nested == [base_val_nested - 1]524+525+ with ctx.scope():526+ rv = ctx.with_resource(TestContext(base_val=base_val))527+ rv_nested = ctx.with_resource(TestContext(base_val=base_val_nested))528+ raise TestException()529+530+ # If one of the context "eats" the exceptions they will not be forwarded to other531+ # parts. This is due to how ExitStack unwinding works532+ assert rv_nested == [base_val_nested + 1]533+ assert rv == [base_val - 1]534+535+ with ctx.scope():536+ rv = ctx.with_resource(TestContext(base_val=base_val))537+ rv_nested = ctx.with_resource(538+ TestContext(base_val=base_val_nested, handle_exception=False)539+ )540+ raise TestException()541+542+ assert rv_nested == [base_val_nested + 1]543+ assert rv == [base_val + 1]544+545+ with pytest.raises(TestException):546+ rv = ctx.with_resource(TestContext(base_val=base_val, handle_exception=False))547+ rv_nested = ctx.with_resource(548+ TestContext(base_val=base_val_nested, handle_exception=False)549+ )550+ raise TestException()551+552+553 def test_make_pass_decorator_args(runner):554 """555 Test to check that make_pass_decorator doesn't consume arguments based on556 invocation order.116 unmodified linesmodified:tests/test_imports.py-1 removed
41 unmodified lines42 "io",43 "itertools",44 "os",45 "re",46- "shutil",46 "stat",47 "struct",48 "sys",49 "threading",21 unmodified linesmodified:tests/test_options.py+1012 added-219 removed
1 import enum2 import os3 import re4 import sys5+import tempfile6+from contextlib import nullcontext7+from typing import Literal8 9 if sys.version_info < (3, 11):10 enum.StrEnum = enum.Enum # type: ignore[assignment]11 12 import pytest13 14 import click15 from click import Option16+from click import UNPROCESSED17+from click._utils import UNSET18 19 20 def test_prefixes(runner):21 @click.command()67 unmodified lines89 click.Option(["--a"], prompt=True, deprecated=True)90 91 92 def test_invalid_nargs(runner):88- with pytest.raises(TypeError, match="nargs=-1"):93+ with pytest.raises(TypeError, match="nargs=-1 is not supported for options."):94 95 @click.command()96 @click.option("--foo", nargs=-1)97 def cli(foo):76 unmodified lines174 assert "Error: Missing option '-m' / '--message'." in result.output175 176 177 @pytest.mark.parametrize(173- ("multiple", "nargs", "default"),178+ ("multiple", "nargs", "default", "expected"),179 [175- (True, 1, []),176- (True, 1, [1]),177- # (False, -1, []),178- # (False, -1, [1]),179- (False, 2, [1, 2]),180- # (True, -1, [[]]),181- # (True, -1, []),182- # (True, -1, [[1]]),183- (True, 2, []),184- (True, 2, [[1, 2]]),180+ # If multiple values are allowed, defaults should be iterable.181+ (True, 1, [], ()),182+ (True, 1, (), ()),183+ (True, 1, tuple(), ()),184+ (True, 1, set(), ()),185+ (True, 1, frozenset(), ()),186+ (True, 1, {}, ()),187+ # Special values.188+ (True, 1, None, ()),189+ (True, 1, UNSET, ()),190+ # Number of values are kept as-is in the default.191+ (True, 1, [1], (1,)),192+ (True, 1, [1, 2], (1, 2)),193+ (True, 1, [1, 2, 3], (1, 2, 3)),194+ (True, 1, [1.1, 2.2], (1.1, 2.2)),195+ (True, 1, ["1", "2"], ("1", "2")),196+ (True, 1, [None, None], (None, None)),197+ # Contrary to list or tuples, native Python types not supported by Click are198+ # not recognized and are converted to the default format: tuple of strings.199+ # Refs: https://github.com/pallets/click/issues/3036200+ (True, 1, {1, 2}, ("1", "2")),201+ (True, 1, frozenset([1, 2]), ("1", "2")),202+ (True, 1, {1: "a", 2: "b"}, ("1", "2")),203+ # Multiple values with nargs > 1.204+ (True, 2, [], ()),205+ (True, 2, (), ()),206+ (True, 2, tuple(), ()),207+ (True, 2, set(), ()),208+ (True, 2, frozenset(), ()),209+ (True, 2, {}, ()),210+ (True, 2, None, ()),211+ (True, 2, UNSET, ()),212+ (True, 2, [[1, 2]], ((1, 2),)),213+ (True, 2, [[1, 2], [3, 4]], ((1, 2), (3, 4))),214+ (True, 2, [[1, 2], [3, 4], [5, 6]], ((1, 2), (3, 4), (5, 6))),215+ (True, 2, [[1.1, 2.2], [3.3, 4.4]], ((1.1, 2.2), (3.3, 4.4))),216+ (True, 2, [["1", "2"], ["3", "4"]], (("1", "2"), ("3", "4"))),217+ (True, 2, [[None, None], [None, None]], ((None, None), (None, None))),218+ (True, 2, [[1, 2.2], ["3", None]], ((1, 2.2), (3, None))),219+ (True, 2, [[1, 2.2], None], ((1, 2.2), None)),220+ # Default of the right length works for non-multiples.221+ (False, 2, [1, 2], (1, 2)),222 ],223 )187-def test_init_good_default_list(runner, multiple, nargs, default):188- click.Option(["-a"], multiple=multiple, nargs=nargs, default=default)224+def test_good_defaults_for_multiple(runner, multiple, nargs, default, expected):225+ @click.command()226+ @click.option("-a", multiple=multiple, nargs=nargs, default=default)227+ def cmd(a):228+ click.echo(repr(a), nl=False)229 230+ result = runner.invoke(cmd)231+ assert result.output == repr(expected)232 233+234 @pytest.mark.parametrize(192- ("multiple", "nargs", "default"),235+ ("multiple", "nargs", "default", "exception", "message"),236 [194- (True, 1, 1),195- # (False, -1, 1),196- (False, 2, [1]),197- (True, 2, [[1]]),237+ # Non-iterables defaults.238+ (239+ True,240+ 1,241+ "Yo",242+ None,243+ "Error: Invalid value for '-a': Value must be an iterable.",244+ ),245+ (246+ True,247+ 1,248+ "",249+ None,250+ "Error: Invalid value for '-a': Value must be an iterable.",251+ ),252+ (253+ True,254+ 1,255+ True,256+ None,257+ "Error: Invalid value for '-a': Value must be an iterable.",258+ ),259+ (260+ True,261+ 1,262+ False,263+ None,264+ "Error: Invalid value for '-a': Value must be an iterable.",265+ ),266+ (267+ True,268+ 1,269+ 12,270+ None,271+ "Error: Invalid value for '-a': Value must be an iterable.",272+ ),273+ (274+ True,275+ 1,276+ 7.9,277+ None,278+ "Error: Invalid value for '-a': Value must be an iterable.",279+ ),280+ #281+ (282+ False,283+ 2,284+ 42,285+ None,286+ "Error: Invalid value for '-a': Value must be an iterable.",287+ ),288+ (289+ True,290+ 2,291+ ["test string which is not a list in the list"],292+ None,293+ "Error: Invalid value for '-a': Value must be an iterable.",294+ ),295+ # Multiple options, each with 2 args, but with wrong length.296+ (297+ True,298+ 2,299+ (1,),300+ None,301+ "Error: Invalid value for '-a': Value must be an iterable.",302+ ),303+ (304+ True,305+ 2,306+ (1, 2, 3),307+ None,308+ "Error: Invalid value for '-a': Value must be an iterable.",309+ ),310+ (311+ True,312+ 2,313+ [tuple()],314+ ValueError,315+ r"'nargs' must be 0 \(or None\) for type <click\.types\.Tuple object at "316+ r"0x[0-9A-Fa-f]+>, but it was 2\.",317+ ),318+ (319+ True,320+ 2,321+ [(1,)],322+ ValueError,323+ r"'nargs' must be 1 \(or None\) for type <click\.types\.Tuple object at "324+ r"0x[0-9A-Fa-f]+>, but it was 2\.",325+ ),326+ (327+ True,328+ 2,329+ [(1, 2, 3)],330+ ValueError,331+ r"'nargs' must be 3 \(or None\) for type <click\.types\.Tuple object at "332+ r"0x[0-9A-Fa-f]+>, but it was 2\.",333+ ),334+ # A mix of valid and invalid defaults.335+ (336+ True,337+ 2,338+ [[1, 2.2], []],339+ None,340+ "Error: Invalid value for '-a': 2 values are required, but 0 were given.",341+ ),342+ # Default values that are iterable but not of the right length.343+ (344+ False,345+ 2,346+ [1],347+ None,348+ "Error: Invalid value for '-a': Takes 2 values but 1 was given.",349+ ),350+ (351+ True,352+ 2,353+ [[1]],354+ ValueError,355+ r"'nargs' must be 1 \(or None\) for type <click\.types\.Tuple object at "356+ r"0x[0-9A-Fa-f]+>, but it was 2\.",357+ ),358 ],359 )200-def test_init_bad_default_list(runner, multiple, nargs, default):201- type = (str, str) if nargs == 2 else None360+def test_bad_defaults_for_multiple(361+ runner, multiple, nargs, default, exception, message362+):363+ if exception:364+ assert issubclass(exception, Exception)365+ else:366+ assert exception is None367 203- with pytest.raises(ValueError, match="default"):204- click.Option(["-a"], type=type, multiple=multiple, nargs=nargs, default=default)368+ with (369+ pytest.raises(exception, match=re.compile(message))370+ if exception371+ else nullcontext()372+ ):373 374+ @click.command()375+ @click.option("-a", multiple=multiple, nargs=nargs, default=default)376+ def cmd(a):377+ click.echo(repr(a))378 379+ result = runner.invoke(cmd)380+ assert message in result.stderr381+382+383 @pytest.mark.parametrize("env_key", ["MYPATH", "AUTO_MYPATH"])384 def test_empty_envvar(runner, env_key):385 @click.command()386 @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH")41 unmodified lines428 assert result.output == "foo|bar\n"429 430 431 @pytest.mark.parametrize(256- ("name", "value", "expected"),432+ ("envvar_name", "envvar_value", "expected"),433 (434 # Lower-cased variations of value.435 ("SHOUT", "true", True),436 ("SHOUT", "false", False),8 unmodified lines445 ("SHOUT", "truE", True),446 ("SHOUT", "FaLsE", False),447 ("SHOUT", "falsE", False),448 # Extra spaces around the value.273- ("SHOUT", "true ", True),274- ("SHOUT", " true", True),275- ("SHOUT", " true ", True),276- ("SHOUT", "false ", False),277- ("SHOUT", " false", False),278- ("SHOUT", " false ", False),449+ ("SHOUT", "true ", True),450+ ("SHOUT", " true ", True),451+ ("SHOUT", " true", True),452+ ("SHOUT", "false ", False),453+ ("SHOUT", " false ", False),454+ ("SHOUT", " false", False),455 # Integer variations.456 ("SHOUT", "1", True),457 ("SHOUT", "0", False),458 # Alternative states.459 ("SHOUT", "t", True),460+ ("SHOUT", "T", True),461+ ("SHOUT", " T ", True),462 ("SHOUT", "f", False),463 ("SHOUT", "y", True),464 ("SHOUT", "n", False),465 ("SHOUT", "yes", True),6 unmodified lines472 ("SHOUT", " ", False),473 ("SHOUT", " ", False),474 # Variable names are not stripped of spaces and so don't match the475 # flag, which then naturraly takes its default value.298- ("SHOUT ", "True", False),299- ("SHOUT ", "False", False),476+ ("SHOUT ", "True", False),477+ ("SHOUT ", "False", False),478 (" SHOUT ", "True", False),479 (" SHOUT ", "False", False),480+ (" SHOUT", "True", False),481+ (" SHOUT", "False", False),482+ ("SH OUT", "True", False),483+ ("SH OUT", "False", False),484 # Same for random and reverse environment variable names: they are not485 # recognized by the option.486 ("RANDOM", "True", False),487 ("NO_SHOUT", "True", False),488 ("NO_SHOUT", "False", False),489+ ("NOSHOUT", "True", False),490+ ("NOSHOUT", "False", False),491 ),492 )309-def test_boolean_envvar_normalization(runner, name, value, expected):493+def test_boolean_flag_envvar(runner, envvar_name, envvar_value, expected):494+ assert isinstance(envvar_name, str)495+ assert isinstance(envvar_value, str) or envvar_value is None496+497 @click.command()498 @click.option("--shout/--no-shout", envvar="SHOUT")499 def cli(shout):313- click.echo(f"shout: {shout!r}")500+ click.echo(repr(shout), nl=False)501 315- result = runner.invoke(cli, [], env={name: value})502+ result = runner.invoke(cli, [], env={envvar_name: envvar_value})503 assert result.exit_code == 0317- assert result.output == f"shout: {expected}\n"504+ assert result.output == repr(expected)505 506 507 @pytest.mark.parametrize(321- ("name", "value"),508+ "value",509 (323- ("SHOUT", "tr ue"),324- ("SHOUT", "10"),325- ("SHOUT", "01"),326- ("SHOUT", "00"),327- ("SHOUT", "11"),328- ("SHOUT", "randomstring"),329- ("SHOUT", "None"),510+ # Extra spaces inside the value.511+ "tr ue",512+ "fa lse",513+ # Numbers.514+ "10",515+ "01",516+ "00",517+ "11",518+ "0.0",519+ "1.1",520+ # Random strings.521+ "randomstring",522+ "None",523+ "'None'",524+ "A B",525+ " 1 2 ",526+ "9.3",527+ "a;n",528+ "x:y",529+ "i/o",530 ),531 )332-def test_boolean_envvar_bad_values(runner, name, value):532+def test_boolean_envvar_bad_values(runner, value):533 @click.command()534 @click.option("--shout/--no-shout", envvar="SHOUT")535 def cli(shout):336- click.echo(f"shout: {shout!r}")536+ click.echo(shout)537 338- result = runner.invoke(cli, [], env={name: value})538+ result = runner.invoke(cli, [], env={"SHOUT": value})539 assert result.exit_code == 2540 assert (541 f"Invalid value for '--shout': {value!r} is not a valid boolean."542 in result.output285 unmodified lines828 result = runner.invoke(cmd, ["-whatever=23"])829 assert result.output == "23\n"830 831 632-def test_missing_option_string_cast():832+@pytest.mark.parametrize(833+ ("value", "expect_missing", "processed_value"),834+ [835+ (UNSET, True, None),836+ (None, False, None),837+ # Default type of the argument is str, so everything is processed as strings.838+ ("", False, ""),839+ (" ", False, " "),840+ ("foo", False, "foo"),841+ ("12", False, "12"),842+ (12, False, "12"),843+ (12.1, False, "12.1"),844+ (list(), False, "[]"),845+ (tuple(), False, "()"),846+ (set(), False, "set()"),847+ (frozenset(), False, "frozenset()"),848+ (dict(), False, "{}"),849+ ],850+)851+def test_required_option(value, expect_missing, processed_value):852 ctx = click.Context(click.Command(""))853+ argument = click.Option(["-a"], required=True)854 855+ if expect_missing:635- with pytest.raises(click.MissingParameter) as excinfo:636- click.Option(["-a"], required=True).process_value(ctx, None)856+ with pytest.raises(click.MissingParameter) as excinfo:857+ argument.process_value(ctx, value)858+ assert str(excinfo.value) == "Missing parameter: a"859 638- assert str(excinfo.value) == "Missing parameter: a"860+ else:861+ value = argument.process_value(ctx, value)862+ assert value == processed_value863 864 865 def test_missing_required_flag(runner):866 cli = click.Command(33 unmodified lines900 result = runner.invoke(cli)901 assert result.exit_code == 2902 assert "Error: Missing option '--foo' (env var: 'bar')." in result.output903 904+ cli = click.Command(905+ "cli", params=[click.Option(["--foo"], show_envvar=True, required=True)]906+ )907+ result = runner.invoke(cli)908+ assert result.exit_code == 2909+ assert "Error: Missing option '--foo'." in result.output910 911+912 def test_case_insensitive_choice(runner):913 @click.command()914 @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))915 def cmd(foo):407 unmodified lines1323 assert param.type is click.INT1324 1325 1326 @pytest.mark.parametrize(1096- ("opt_params", "pass_flag", "expected"),1327+ ("opt_params", "args", "expected"),1328 [1098- # Effect of the presence/absence of flag depending on type1099- ({"type": bool}, False, False),1100- ({"type": bool}, True, True),1101- ({"type": click.BOOL}, False, False),1102- ({"type": click.BOOL}, True, True),1103- ({"type": str}, False, "False"),1104- ({"type": str}, True, "True"),1105- # Effects of default value1106- ({"type": bool, "default": True}, False, True),1107- ({"type": bool, "default": True}, True, True),1108- ({"type": bool, "default": False}, False, False),1109- ({"type": bool, "default": False}, True, True),1110- ({"type": bool, "default": None}, False, False),1111- ({"type": bool, "default": None}, True, True),1112- ({"type": click.BOOL, "default": True}, False, True),1113- ({"type": click.BOOL, "default": True}, True, True),1114- ({"type": click.BOOL, "default": False}, False, False),1115- ({"type": click.BOOL, "default": False}, True, True),1116- ({"type": click.BOOL, "default": None}, False, False),1117- ({"type": click.BOOL, "default": None}, True, True),1118- ({"type": str, "default": True}, False, "True"),1119- ({"type": str, "default": True}, True, "True"),1120- ({"type": str, "default": False}, False, "False"),1121- ({"type": str, "default": False}, True, "True"),1122- ({"type": str, "default": "foo"}, False, "foo"),1123- ({"type": str, "default": "foo"}, True, "foo"),1124- ({"type": str, "default": None}, False, "False"),1125- ({"type": str, "default": None}, True, "True"),1126- # Effects of flag_value1127- ({"type": bool, "flag_value": True}, False, False),1128- ({"type": bool, "flag_value": True}, True, True),1129- ({"type": bool, "flag_value": False}, False, False),1130- ({"type": bool, "flag_value": False}, True, False),1131- ({"type": bool, "flag_value": None}, False, False),1132- ({"type": bool, "flag_value": None}, True, True),1133- ({"type": click.BOOL, "flag_value": True}, False, False),1134- ({"type": click.BOOL, "flag_value": True}, True, True),1135- ({"type": click.BOOL, "flag_value": False}, False, False),1136- ({"type": click.BOOL, "flag_value": False}, True, False),1137- ({"type": click.BOOL, "flag_value": None}, False, False),1138- ({"type": click.BOOL, "flag_value": None}, True, True),1139- ({"type": str, "flag_value": True}, False, "False"),1140- ({"type": str, "flag_value": True}, True, "True"),1141- ({"type": str, "flag_value": False}, False, "False"),1142- ({"type": str, "flag_value": False}, True, "False"),1143- ({"type": str, "flag_value": "foo"}, False, "False"),1144- ({"type": str, "flag_value": "foo"}, True, "foo"),1145- ({"type": str, "flag_value": None}, False, "False"),1146- ({"type": str, "flag_value": None}, True, "True"),1147- # Not passing --foo returns the default value as-is1148- ({"type": bool, "default": True, "flag_value": True}, False, True),1149- ({"type": bool, "default": True, "flag_value": False}, False, True),1150- ({"type": bool, "default": False, "flag_value": True}, False, False),1151- ({"type": bool, "default": False, "flag_value": False}, False, False),1152- ({"type": bool, "default": None, "flag_value": True}, False, False),1153- ({"type": bool, "default": None, "flag_value": False}, False, False),1154- ({"type": str, "default": True, "flag_value": True}, False, "True"),1155- ({"type": str, "default": True, "flag_value": False}, False, "True"),1156- ({"type": str, "default": False, "flag_value": True}, False, "False"),1157- ({"type": str, "default": False, "flag_value": False}, False, "False"),1158- ({"type": str, "default": "foo", "flag_value": True}, False, "foo"),1159- ({"type": str, "default": "foo", "flag_value": False}, False, "foo"),1160- ({"type": str, "default": "foo", "flag_value": "bar"}, False, "foo"),1161- ({"type": str, "default": "foo", "flag_value": None}, False, "foo"),1162- ({"type": str, "default": None, "flag_value": True}, False, "False"),1163- ({"type": str, "default": None, "flag_value": False}, False, "False"),1164- # Passing --foo returns the explicitly set flag_value1165- ({"type": bool, "default": True, "flag_value": True}, True, True),1166- ({"type": bool, "default": True, "flag_value": False}, True, False),1167- ({"type": bool, "default": False, "flag_value": True}, True, True),1168- ({"type": bool, "default": False, "flag_value": False}, True, False),1169- ({"type": bool, "default": None, "flag_value": True}, True, True),1170- ({"type": bool, "default": None, "flag_value": False}, True, False),1171- ({"type": str, "default": True, "flag_value": True}, True, "True"),1172- ({"type": str, "default": True, "flag_value": False}, True, "False"),1173- ({"type": str, "default": False, "flag_value": True}, True, "True"),1174- ({"type": str, "default": False, "flag_value": False}, True, "False"),1175- ({"type": str, "default": "foo", "flag_value": True}, True, "True"),1176- ({"type": str, "default": "foo", "flag_value": False}, True, "False"),1177- ({"type": str, "default": "foo", "flag_value": "bar"}, True, "bar"),1178- ({"type": str, "default": "foo", "flag_value": None}, True, "foo"),1179- ({"type": str, "default": None, "flag_value": True}, True, "True"),1180- ({"type": str, "default": None, "flag_value": False}, True, "False"),1329+ # The type passed to the option is responsible to converting the value, whether1330+ # we pass the option flag or not.1331+ ({"type": bool}, [], False),1332+ ({"type": bool}, ["--foo"], True),1333+ ({"type": click.BOOL}, [], False),1334+ ({"type": click.BOOL}, ["--foo"], True),1335+ ({"type": str}, [], None),1336+ ({"type": str}, ["--foo"], "True"),1337+ # Default value is given as-is to the --foo option when it is not passed,1338+ # whatever the type. Now if --foo is passed, the value is always True, whatever1339+ # the type. In both case the type of the option is responsible for the1340+ # conversion of the value.1341+ ({"type": bool, "default": True}, [], True),1342+ ({"type": bool, "default": True}, ["--foo"], True),1343+ ({"type": bool, "default": False}, [], False),1344+ ({"type": bool, "default": False}, ["--foo"], True),1345+ # ({"type": bool, "default": "foo"}, [], "foo"),1346+ ({"type": bool, "default": "foo"}, ["--foo"], True),1347+ ({"type": bool, "default": None}, [], None),1348+ ({"type": bool, "default": None}, ["--foo"], True),1349+ ({"type": click.BOOL, "default": True}, [], True),1350+ ({"type": click.BOOL, "default": True}, ["--foo"], True),1351+ ({"type": click.BOOL, "default": False}, [], False),1352+ ({"type": click.BOOL, "default": False}, ["--foo"], True),1353+ # ({"type": click.BOOL, "default": "foo"}, [], "foo"),1354+ ({"type": click.BOOL, "default": "foo"}, ["--foo"], True),1355+ ({"type": click.BOOL, "default": None}, [], None),1356+ ({"type": click.BOOL, "default": None}, ["--foo"], True),1357+ ({"type": str, "default": True}, [], "True"),1358+ ({"type": str, "default": True}, ["--foo"], "True"),1359+ ({"type": str, "default": False}, [], "False"),1360+ ({"type": str, "default": False}, ["--foo"], "True"),1361+ ({"type": str, "default": "foo"}, [], "foo"),1362+ ({"type": str, "default": "foo"}, ["--foo"], "True"),1363+ ({"type": str, "default": None}, [], None),1364+ ({"type": str, "default": None}, ["--foo"], "True"),1365+ # Flag value is given as-is to the --foo option when it is passed, then1366+ # converted by the option type.1367+ ({"type": bool, "flag_value": True}, [], False),1368+ ({"type": bool, "flag_value": True}, ["--foo"], True),1369+ ({"type": bool, "flag_value": False}, [], False),1370+ ({"type": bool, "flag_value": False}, ["--foo"], False),1371+ ({"type": bool, "flag_value": None}, [], False),1372+ ({"type": bool, "flag_value": None}, ["--foo"], None),1373+ ({"type": click.BOOL, "flag_value": True}, [], False),1374+ ({"type": click.BOOL, "flag_value": True}, ["--foo"], True),1375+ ({"type": click.BOOL, "flag_value": False}, [], False),1376+ ({"type": click.BOOL, "flag_value": False}, ["--foo"], False),1377+ ({"type": click.BOOL, "flag_value": None}, [], False),1378+ ({"type": click.BOOL, "flag_value": None}, ["--foo"], None),1379+ ({"type": str, "flag_value": True}, [], None),1380+ ({"type": str, "flag_value": True}, ["--foo"], "True"),1381+ ({"type": str, "flag_value": False}, [], None),1382+ ({"type": str, "flag_value": False}, ["--foo"], "False"),1383+ ({"type": str, "flag_value": "foo"}, [], None),1384+ ({"type": str, "flag_value": "foo"}, ["--foo"], "foo"),1385+ ({"type": str, "flag_value": None}, [], None),1386+ ({"type": str, "flag_value": None}, ["--foo"], None),1387+ # Not passing --foo returns the default value as-is, in its Python type, then1388+ # converted by the option type.1389+ ({"type": bool, "default": True, "flag_value": True}, [], True),1390+ ({"type": bool, "default": True, "flag_value": False}, [], False),1391+ ({"type": bool, "default": False, "flag_value": True}, [], False),1392+ ({"type": bool, "default": False, "flag_value": False}, [], False),1393+ ({"type": bool, "default": None, "flag_value": True}, [], None),1394+ ({"type": bool, "default": None, "flag_value": False}, [], None),1395+ ({"type": str, "default": True, "flag_value": True}, [], "True"),1396+ ({"type": str, "default": True, "flag_value": False}, [], "False"),1397+ ({"type": str, "default": False, "flag_value": True}, [], "False"),1398+ ({"type": str, "default": False, "flag_value": False}, [], "False"),1399+ ({"type": str, "default": "foo", "flag_value": True}, [], "foo"),1400+ ({"type": str, "default": "foo", "flag_value": False}, [], "foo"),1401+ ({"type": str, "default": "foo", "flag_value": "bar"}, [], "foo"),1402+ ({"type": str, "default": "foo", "flag_value": None}, [], "foo"),1403+ ({"type": str, "default": None, "flag_value": True}, [], None),1404+ ({"type": str, "default": None, "flag_value": False}, [], None),1405+ # Passing --foo returns the flag_value that was explicitly set by the user,1406+ # with its Python type, but still converted by the option type.1407+ ({"type": bool, "default": True, "flag_value": True}, ["--foo"], True),1408+ ({"type": bool, "default": True, "flag_value": False}, ["--foo"], False),1409+ ({"type": bool, "default": False, "flag_value": True}, ["--foo"], True),1410+ ({"type": bool, "default": False, "flag_value": False}, ["--foo"], False),1411+ ({"type": bool, "default": None, "flag_value": True}, ["--foo"], True),1412+ ({"type": bool, "default": None, "flag_value": False}, ["--foo"], False),1413+ ({"type": str, "default": True, "flag_value": True}, ["--foo"], "True"),1414+ ({"type": str, "default": True, "flag_value": False}, ["--foo"], "False"),1415+ ({"type": str, "default": False, "flag_value": True}, ["--foo"], "True"),1416+ ({"type": str, "default": False, "flag_value": False}, ["--foo"], "False"),1417+ ({"type": str, "default": "foo", "flag_value": True}, ["--foo"], "True"),1418+ ({"type": str, "default": "foo", "flag_value": False}, ["--foo"], "False"),1419+ ({"type": str, "default": "foo", "flag_value": "bar"}, ["--foo"], "bar"),1420+ ({"type": str, "default": "foo", "flag_value": None}, ["--foo"], None),1421+ ({"type": str, "default": None, "flag_value": True}, ["--foo"], "True"),1422+ ({"type": str, "default": None, "flag_value": False}, ["--foo"], "False"),1423 ],1424 )1183-def test_flag_value_and_default(runner, opt_params, pass_flag, expected):1425+def test_flag_value_and_default(runner, opt_params, args, expected):1426 @click.command()1427 @click.option("--foo", is_flag=True, **opt_params)1428 def cmd(foo):1187- click.echo(repr(foo))1429+ click.echo(repr(foo), nl=False)1430 1189- result = runner.invoke(cmd, ["--foo"] if pass_flag else [])1190- assert result.output == f"{expected!r}\n"1431+ result = runner.invoke(cmd, args)1432+ assert result.output == repr(expected)1433 1434 1435 @pytest.mark.parametrize(1194- "opts",1436+ ("args", "opts"),1437 [1196- {"type": bool, "default": "foo"},1197- {"type": bool, "flag_value": "foo"},1198- {"type": click.BOOL, "default": "foo"},1199- {"type": click.BOOL, "flag_value": "foo"},1438+ ([], {"type": bool, "default": "foo"}),1439+ ([], {"type": click.BOOL, "default": "foo"}),1440+ (["--foo"], {"type": bool, "flag_value": "foo"}),1441+ (["--foo"], {"type": click.BOOL, "flag_value": "foo"}),1442 ],1443 )1202-def test_invalid_flag_definition(runner, opts):1444+def test_invalid_flag_definition(runner, args, opts):1445 @click.command()1446 @click.option("--foo", is_flag=True, **opts)1447 def cmd(foo):1448 click.echo(foo)1449 1208- result = runner.invoke(cmd, ["--foo"])1450+ result = runner.invoke(cmd, args)1451 assert (1452 "Error: Invalid value for '--foo': 'foo' is not a valid boolean"1453 in result.output1454 )1455 1456 1457 @pytest.mark.parametrize(1458+ ("default", "args", "expected"),1459+ # These test cases are similar to the ones in1460+ # tests/test_basic.py::test_flag_value_dual_options, so keep them in sync.1461+ (1462+ # Each option is returning its own flag_value, whatever the default is.1463+ (True, ["--js"], "js"),1464+ (True, ["--xml"], "xml"),1465+ (False, ["--js"], "js"),1466+ (False, ["--xml"], "xml"),1467+ (None, ["--js"], "js"),1468+ (None, ["--xml"], "xml"),1469+ (UNSET, ["--js"], "js"),1470+ (UNSET, ["--xml"], "xml"),1471+ # Check that the last option wins when both are specified.1472+ (True, ["--js", "--xml"], "xml"),1473+ (True, ["--xml", "--js"], "js"),1474+ # Check that the default is returned as-is when no option is specified.1475+ ("js", [], "js"),1476+ ("xml", [], "xml"),1477+ ("jS", [], "jS"),1478+ ("xMl", [], "xMl"),1479+ (" ᕕ( ᐛ )ᕗ ", [], " ᕕ( ᐛ )ᕗ "),1480+ (None, [], None),1481+ # Special case: UNSET is not provided as-is to the callback, but normalized to1482+ # None.1483+ (UNSET, [], None),1484+ # Special case: if default=True and flag_value is set, the value returned is the1485+ # flag_value, not the True Python value itself.1486+ (True, [], "js"),1487+ # Non-string defaults are process as strings by the default Parameter's type.1488+ (False, [], "False"),1489+ (42, [], "42"),1490+ (12.3, [], "12.3"),1491+ ),1492+)1493+def test_default_dual_option_callback(runner, default, args, expected):1494+ """Check how default is processed by the callback when options compete for the same1495+ variable name.1496+1497+ Reproduction of the issue reported in1498+ https://github.com/pallets/click/pull/3030#discussion_r22715718191499+ """1500+1501+ def _my_func(ctx, param, value):1502+ # Print the value received by the callback as-is, so we can check for it.1503+ return f"Callback value: {value!r}"1504+1505+ @click.command()1506+ @click.option("--js", "fmt", flag_value="js", callback=_my_func, default=default)1507+ @click.option("--xml", "fmt", flag_value="xml", callback=_my_func)1508+ def main(fmt):1509+ click.secho(fmt, nl=False)1510+1511+ result = runner.invoke(main, args)1512+ assert result.output == f"Callback value: {expected!r}"1513+ assert result.exit_code == 01514+1515+1516+@pytest.mark.parametrize(1517 ("flag_value", "envvar_value", "expected"),1518 [1218- # Envvar is set to false, so the flag default value is returned.1219- ("bar", "False", "False"),1220- # Same as above with alternative states and blank values.1221- ("bar", "0", "False"),1222- ("bar", "f", "False"),1223- ("bar", "", "False"),1224- # Envvar is set to true, so the flag_value is returned.1225- ("bar", "True", "bar"),1226- ("bar", "1", "bar"),1227- ("bar", "t", "bar"),1228- # So far we have the same cases as the test_flag_value_and_default1229- # test case. Now instead of passing a boolean-like value, let's use1230- # the flag_value as the envvar value.1519+ # The envvar match exactly the flag value and is case-sensitive.1520 ("bar", "bar", "bar"),1232- # flag_value is expected to be the exact same in the envvar for the flag to be1233- # activated.1234- ("bar", " bar ", "False"),1235- ("bar", "BAR", "False"),1236- ("bar", "random", "False"),1237- ("bar", "bar random", "False"),1238- ("bar", "random bar", "False"),1521 ("BAR", "BAR", "BAR"),1240- ("BAR", "bar", "False"),1522 (" bar ", " bar ", " bar "),1523+ ("42", "42", "42"),1524+ ("None", "None", "None"),1525+ ("True", "True", "True"),1526+ ("False", "False", "False"),1527+ ("true", "true", "true"),1528+ ("false", "false", "false"),1529+ ("A B", "A B", "A B"),1530+ (" 1 2 ", " 1 2 ", " 1 2 "),1531+ ("9.3", "9.3", "9.3"),1532+ ("a;n", "a;n", "a;n"),1533+ ("x:y", "x:y", "x:y"),1534+ ("i/o", "i/o", "i/o"),1535+ # Empty or absent envvar is consider unset, so the flag default value is1536+ # returned, which is None in this case.1537+ ("bar", "", None),1538+ ("bar", None, None),1539+ ("BAR", "", None),1540+ ("BAR", None, None),1541+ (" bar ", "", None),1542+ (" bar ", None, None),1543+ (42, "", None),1544+ (42, None, None),1545+ ("42", "", None),1546+ ("42", None, None),1547+ (None, "", None),1548+ (None, None, None),1549+ ("None", "", None),1550+ ("None", None, None),1551+ (True, "", None),1552+ (True, None, None),1553+ ("True", "", None),1554+ ("True", None, None),1555+ ("true", "", None),1556+ ("true", None, None),1557+ (False, "", None),1558+ (False, None, None),1559+ ("False", "", None),1560+ ("False", None, None),1561+ ("false", "", None),1562+ ("false", None, None),1563+ # Activate the flag with a value recognized as True by the envvar, which1564+ # returns the flag_value.1565+ ("bar", "True", "bar"),1566+ ("bar", "true", "bar"),1567+ ("bar", "trUe", "bar"),1568+ ("bar", " TRUE ", "bar"),1569+ ("bar", "1", "bar"),1570+ ("bar", "yes", "bar"),1571+ ("bar", "on", "bar"),1572+ ("bar", "t", "bar"),1573+ ("bar", "y", "bar"),1574+ # Deactivating the flag with a value recognized as False by the envvar, which1575+ # explicitly return the 'False' as the option is explicitly declared as a1576+ # string.1577+ ("bar", "False", "False"),1578+ ("bar", "false", "False"),1579+ ("bar", "faLse", "False"),1580+ ("bar", " FALSE ", "False"),1242- (" bar ", "bar", "False"),1243- (" bar ", "BAR", "False"),1581+ ("bar", "0", "False"),1582+ ("bar", "no", "False"),1583+ ("bar", "off", "False"),1584+ ("bar", "f", "False"),1585+ ("bar", "n", "False"),1586+ # Any other value than the flag_value, or a recogned True or False value, fails1587+ # to explicitly activate or deactivate the flag. So the flag default value is1588+ # returned, which is None in this case.1589+ ("bar", " bar ", None),1590+ ("bar", "BAR", None),1591+ ("bar", "random", None),1592+ ("bar", "bar random", None),1593+ ("bar", "random bar", None),1594+ ("BAR", "bar", None),1595+ (" bar ", "bar", None),1596+ (" bar ", "BAR", None),1597+ (42, "42", None),1598+ (42, "foo", None),1599+ (None, "foo", None),1600+ ("None", "foo", None),1601 ],1602 )1246-def test_envvar_flag_value(runner, flag_value, envvar_value, expected):1603+def test_envvar_string_flag_value(runner, flag_value, envvar_value, expected):1604 """Ensure that flag_value is recognized by the envvar."""1605 1606 @click.command()1250- @click.option(1251- "--upper", type=str, is_flag=True, flag_value=flag_value, envvar="UPPER"1252- )1607+ @click.option("--upper", type=str, flag_value=flag_value, envvar="UPPER")1608 def cmd(upper):1254- click.echo(repr(upper))1609+ click.echo(repr(upper), nl=False)1610 1611 result = runner.invoke(cmd, env={"UPPER": envvar_value})1612 assert result.exit_code == 01258- assert result.output == f"{expected!r}\n"1613+ assert result.output == repr(expected)1614 1615 1616 @pytest.mark.parametrize(1262- ("option", "expected"),1617+ ("opt_decls", "opt_params", "expect_is_flag", "expect_is_bool_flag"),1618 [1264- # Not boolean flags1265- pytest.param(Option(["-a"], type=int), False, id="int option"),1266- pytest.param(Option(["-a"], type=bool), False, id="bool non-flag [None]"),1267- pytest.param(Option(["-a"], default=True), False, id="bool non-flag [True]"),1268- pytest.param(Option(["-a"], default=False), False, id="bool non-flag [False]"),1269- pytest.param(Option(["-a"], flag_value=1), False, id="non-bool flag_value"),1270- # Boolean flags1271- pytest.param(Option(["-a"], is_flag=True), True, id="is_flag=True"),1272- pytest.param(Option(["-a/-A"]), True, id="secondary option [implicit flag]"),1273- pytest.param(Option(["-a"], flag_value=True), True, id="bool flag_value"),1619+ # Not boolean flags.1620+ ("-a", {"type": int}, False, False),1621+ ("-a", {"type": bool}, False, False),1622+ ("-a", {"default": True}, False, False),1623+ ("-a", {"default": False}, False, False),1624+ ("-a", {"flag_value": 1}, True, False),1625+ # Boolean flags.1626+ ("-a", {"is_flag": True}, True, True),1627+ ("-a/-A", {}, True, True),1628+ ("-a", {"flag_value": True}, True, True),1629+ # Non-flag with flag_value.1630+ ("-a", {"is_flag": False, "flag_value": 1}, False, False),1631 ],1632 )1276-def test_bool_flag_auto_detection(option, expected):1277- assert option.is_bool_flag is expected1633+def test_flag_auto_detection(1634+ opt_decls, opt_params, expect_is_flag, expect_is_bool_flag1635+):1636+ option = Option([opt_decls], **opt_params)1637+ assert option.is_flag is expect_is_flag1638+ assert option.is_bool_flag is expect_is_bool_flag1639 1640 1641 @pytest.mark.parametrize(1642 ("kwargs", "message"),23 unmodified lines1666 assert result.exit_code == 01667 1668 1669 class HashType(enum.Enum):1309- MD5 = enum.auto()1310- SHA1 = enum.auto()1670+ MD5 = "MD5"1671+ SHA1 = "SHA1"1672+ SHA256 = "SHA-256"1673 1674 1675 class Number(enum.IntEnum):1676 ONE = enum.auto()1677 TWO = enum.auto()1678 1679 1680 class Letter(enum.StrEnum):1319- A = enum.auto()1320- B = enum.auto()1681+ NAME_1 = "Value-1"1682+ NAME_2 = "Value_2"1683+ NAME_3 = "42_value"1684 1685 1686 class Color(enum.Flag):1687 RED = enum.auto()7 unmodified lines1695 BLUE = enum.auto()1696 1697 1698 @pytest.mark.parametrize(1336- ("choices", "metavars"),1699+ ("choices", "metavar"),1700 [1338- pytest.param(["foo", "bar"], "[TEXT]", id="text choices"),1339- pytest.param([1, 2], "[INTEGER]", id="int choices"),1340- pytest.param([1.0, 2.0], "[FLOAT]", id="float choices"),1341- pytest.param([True, False], "[BOOLEAN]", id="bool choices"),1342- pytest.param(["foo", 1], "[TEXT|INTEGER]", id="text/int choices"),1343- pytest.param(HashType, "[HASHTYPE]", id="enum choices"),1344- pytest.param(Number, "[NUMBER]", id="int enum choices"),1345- pytest.param(Letter, "[LETTER]", id="str enum choices"),1346- pytest.param(Color, "[COLOR]", id="flag enum choices"),1347- pytest.param(ColorInt, "[COLORINT]", id="int flag enum choices"),1701+ (["foo", "bar"], "[TEXT]"),1702+ ([1, 2], "[INTEGER]"),1703+ ([1.0, 2.0], "[FLOAT]"),1704+ ([True, False], "[BOOLEAN]"),1705+ (["foo", 1], "[TEXT|INTEGER]"),1706+ (HashType, "[HASHTYPE]"),1707+ (Number, "[NUMBER]"),1708+ (Letter, "[LETTER]"),1709+ (Color, "[COLOR]"),1710+ (ColorInt, "[COLORINT]"),1711 ],1712 )1350-def test_usage_show_choices(runner, choices, metavars):1351- """When show_choices=False is set, the --help output1352- should print choice metavars instead of values.1713+def test_choice_usage_rendering(runner, choices, metavar):1714+ """BY default ``--help`` prints choice's values in the usage message.1715+1716+ But ``show_choices=False`` makes ``--help`` prints choice's METAVAR instead of1717+ values.1718+1719+ Also check that usage error message always suggests the actual values.1720 """1721 1722 @click.command()1723 @click.option("-g", type=click.Choice(choices))1724 def cli_with_choices(g):1725 pass1726 1727 @click.command()1361- @click.option(1362- "-g",1363- type=click.Choice(choices),1364- show_choices=False,1365- )1728+ @click.option("-g", type=click.Choice(choices), show_choices=False)1729 def cli_without_choices(g):1730 pass1731 1369- result = runner.invoke(cli_with_choices, ["--help"])1370- assert (1371- f"[{'|'.join(i.name if isinstance(i, enum.Enum) else str(i) for i in choices)}]"1372- in result.output1732+ display_values = tuple(1733+ i.name if isinstance(i, enum.Enum) else str(i) for i in choices1734 )1735 1736+ # Check that the choices values are rendered as-is in the usage message.1737+ result = runner.invoke(cli_with_choices, ["--help"])1738+ assert f"[{'|'.join(display_values)}]" in result.stdout1739+ assert not result.stderr1740+ assert result.exit_code == 01741+1742+ # Check that the metavar is rendered instead of the choices values themselves.1743 result = runner.invoke(cli_without_choices, ["--help"])1376- assert metavars in result.output1744+ assert metavar in result.stdout1745+ assert not result.stderr1746+ assert result.exit_code == 01747 1748+ # Check the usage error message suggests the actual accepted values.1749+ for cli in (cli_with_choices, cli_without_choices):1750+ result = runner.invoke(cli, ["-g", "random"])1751+ assert (1752+ "\n\nError: Invalid value for '-g': 'random' is not one of "1753+ f"{', '.join(map(repr, display_values))}.\n" in result.stderr1754+ )1755+ assert not result.stdout1756+ assert result.exit_code == 21757 1758+1759 @pytest.mark.parametrize(1760 ("choices", "default", "default_string"),1761 [1762 (["foo", "bar"], "bar", "bar"),10 unmodified lines1773 ([True, False], True, "True"),1774 ([True, False], False, "False"),1775 (["foo", 1], "foo", "foo"),1776 (["foo", 1], 1, "1"),1397- # Enum choices are rendered as their names.1777+ # Enum choices are rendered as their names, not values.1778 # See: https://github.com/pallets/click/issues/29111779 (HashType, HashType.SHA1, "SHA1"),1780 # Enum choices allow defaults strings that are their names.1401- (HashType, "SHA1", "SHA1"),1781+ (HashType, HashType.SHA256, "SHA256"),1782+ (HashType, "SHA256", "SHA256"),1783 (Number, Number.TWO, "TWO"),1403- (Letter, Letter.B, "B"),1784+ (Number, "TWO", "TWO"),1785+ (Letter, Letter.NAME_1, "NAME_1"),1786+ (Letter, Letter.NAME_2, "NAME_2"),1787+ (Letter, Letter.NAME_3, "NAME_3"),1788+ (Letter, "NAME_1", "NAME_1"),1789+ (Letter, "NAME_2", "NAME_2"),1790+ (Letter, "NAME_3", "NAME_3"),1791 (Color, Color.GREEN, "GREEN"),1792+ (Color, "GREEN", "GREEN"),1793 (ColorInt, ColorInt.GREEN, "GREEN"),1794+ (ColorInt, "GREEN", "GREEN"),1795 ],1796 )1797 def test_choice_default_rendering(runner, choices, default, default_string):1798 @click.command()35 unmodified lines1834 pass1835 1836 with pytest.warns(UserWarning):1837 runner.invoke(cli, [])1838+1839+1840+OBJECT_SENTINEL = object()1841+"""An object-based sentinel value."""1842+1843+1844+class EnumSentinel(enum.Enum):1845+ FALSY_SENTINEL = object()1846+1847+ def __bool__(self) -> Literal[False]:1848+ """Force the sentinel to be falsy to make sure it is not caught by Click1849+ internal implementation.1850+1851+ Falsy sentinels have been discussed in:1852+ https://github.com/pallets/click/pull/3030#pullrequestreview-31066047951853+ https://github.com/pallets/click/pull/3030#pullrequestreview-31084715521854+ """1855+ return False1856+1857+1858+# Any kind of sentinel value is recognized by Click as a valid flag value.1859+@pytest.mark.parametrize("sentinel", (OBJECT_SENTINEL, EnumSentinel.FALSY_SENTINEL))1860+@pytest.mark.parametrize(1861+ ("args", "expected"),1862+ (1863+ # Option default to None.1864+ ([], None),1865+ # Config has no default value, and no flag value, so it requires an argument.1866+ (1867+ ["--config"],1868+ re.compile(re.escape("Error: Option '--config' requires an argument.\n")),1869+ ),1870+ (1871+ ["--no-config", "--config"],1872+ re.compile(re.escape("Error: Option '--config' requires an argument.\n")),1873+ ),1874+ # Passing --no-config defaults to the sentinel value because of the flag_value,1875+ # and then the custom type receives that sentinel and returns a message.1876+ (["--no-config"], "No configuration file provided."),1877+ # Passing --config with an argument returns the file path.1878+ (["--config", "foo.conf"], "foo.conf"),1879+ # An argument is not allowed for --no-config, so it raises an error.1880+ (1881+ ["--no-config", "foo.conf"],1882+ re.compile(1883+ r"Usage: main \[OPTIONS\]\n"1884+ r"Try 'main --help' for help.\n"1885+ r"\n"1886+ r"Error: Got unexpected extra argument (.+)\n"1887+ ),1888+ ),1889+ # Passing --config with an argument that does not exist raises an error.1890+ (1891+ ["--config", "random-file.conf"],1892+ re.compile(1893+ r"Usage: main \[OPTIONS\]\n"1894+ r"Try 'main --help' for help.\n"1895+ r"\n"1896+ r"Error: Invalid value for '-c' / '--config': "1897+ r"File 'random-file.conf' does not exist.\n"1898+ ),1899+ ),1900+ (1901+ ["--config", "--no-config"],1902+ re.compile(1903+ r"Usage: main \[OPTIONS\]\n"1904+ r"Try 'main --help' for help.\n"1905+ r"\n"1906+ r"Error: Invalid value for '-c' / '--config': "1907+ r"File '--no-config' does not exist.\n"1908+ ),1909+ ),1910+ (1911+ ["--config", "--no-config", "foo.conf"],1912+ re.compile(1913+ r"Usage: main \[OPTIONS\]\n"1914+ r"Try 'main --help' for help.\n"1915+ r"\n"1916+ r"Error: Invalid value for '-c' / '--config': "1917+ r"File '--no-config' does not exist.\n"1918+ ),1919+ ),1920+ # --config is passed last and overrides the --no-config option.1921+ (["--no-config", "--config", "foo.conf"], "foo.conf"),1922+ ),1923+)1924+def test_dual_options_custom_type_sentinel_flag_value(runner, sentinel, args, expected):1925+ """Check that an object-based sentinel, used as a flag value, is returned as-is1926+ to a custom type that is shared by two options, competing for the same variable1927+ name.1928+1929+ A reproduction of1930+ https://github.com/pallets/click/issues/3024#issuecomment-31465113561931+ """1932+1933+ class ConfigParamType(click.ParamType):1934+ """A custom type that accepts a file path or a sentinel value."""1935+1936+ def convert(self, value, param, ctx):1937+ if value is sentinel:1938+ return "No configuration file provided."1939+ else:1940+ return click.Path(exists=True, dir_okay=False).convert(1941+ value, param, ctx1942+ )1943+1944+ @click.command()1945+ @click.option("-c", "--config", type=ConfigParamType())1946+ @click.option("--no-config", "config", flag_value=sentinel, type=ConfigParamType())1947+ def main(config):1948+ click.echo(repr(config), nl=False)1949+1950+ with tempfile.NamedTemporaryFile(mode="w") as named_tempfile:1951+ if "foo.conf" in args:1952+ named_tempfile.write("Blah blah")1953+ named_tempfile.flush()1954+ args = [named_tempfile.name if a == "foo.conf" else a for a in args]1955+1956+ result = runner.invoke(main, args)1957+1958+ if isinstance(expected, re.Pattern):1959+ assert re.match(expected, result.output)1960+ else:1961+ assert result.output == repr(1962+ named_tempfile.name if expected == "foo.conf" else expected1963+ )1964+1965+1966+class EngineType(enum.Enum):1967+ OSS = enum.auto()1968+ PRO = enum.auto()1969+ MAX = enum.auto()1970+1971+1972+class Class1:1973+ pass1974+1975+1976+class Class2:1977+ pass1978+1979+1980+@pytest.mark.parametrize(1981+ ("opt_params", "args", "expected"),1982+ [1983+ # Check that the flag value is returned as-is when the option is passed, and1984+ # not normalized to a boolean, even if it is explicitly declared as a flag.1985+ ({"type": EngineType, "flag_value": None}, ["--pro"], None),1986+ (1987+ {"type": EngineType, "is_flag": True, "flag_value": None},1988+ ["--pro"],1989+ None,1990+ ),1991+ ({"type": EngineType, "flag_value": EngineType.OSS}, ["--pro"], EngineType.OSS),1992+ (1993+ {"type": EngineType, "is_flag": True, "flag_value": EngineType.OSS},1994+ ["--pro"],1995+ EngineType.OSS,1996+ ),1997+ (1998+ {"type": EngineType, "is_flag": True, "default": EngineType.OSS},1999+ ["--pro"],2000+ EngineType.OSS,2001+ ),2002+ # The default value is returned as-is when the option is not passed, whatever2003+ # the flag value.2004+ ({"type": EngineType, "flag_value": None}, [], None),2005+ ({"type": EngineType, "is_flag": True, "flag_value": None}, [], None),2006+ ({"type": EngineType, "flag_value": EngineType.OSS}, [], None),2007+ (2008+ {"type": EngineType, "is_flag": True, "flag_value": EngineType.OSS},2009+ [],2010+ None,2011+ ),2012+ (2013+ {"type": EngineType, "is_flag": True, "default": EngineType.OSS},2014+ [],2015+ EngineType.OSS,2016+ ),2017+ # The option has not enough parameters to be detected as flag-like, so it2018+ # requires an argument.2019+ (2020+ {"type": EngineType, "default": EngineType.OSS},2021+ ["--pro"],2022+ re.compile(re.escape("Error: Option '--pro' requires an argument.\n")),2023+ ),2024+ ({"type": EngineType, "default": EngineType.OSS}, [], EngineType.OSS),2025+ # If a flag value is set, it is returned instead of the default value.2026+ (2027+ {"type": EngineType, "flag_value": EngineType.OSS, "default": True},2028+ ["--pro"],2029+ EngineType.OSS,2030+ ),2031+ (2032+ {"type": EngineType, "flag_value": EngineType.OSS, "default": True},2033+ [],2034+ EngineType.OSS,2035+ ),2036+ # Type is not specified and default to string, so the default value is2037+ # returned as a string, even if it is a boolean. Also, defaults to the2038+ # flag_value instead of the default value to support legacy behavior.2039+ ({"flag_value": "1", "default": True}, [], "1"),2040+ ({"flag_value": "1", "default": 42}, [], "42"),2041+ ({"flag_value": EngineType.OSS, "default": True}, [], "EngineType.OSS"),2042+ ({"flag_value": EngineType.OSS, "default": 42}, [], "42"),2043+ # See: the result is the same if we force the type to be str.2044+ ({"type": str, "flag_value": 1, "default": True}, [], "1"),2045+ ({"type": str, "flag_value": 1, "default": 42}, [], "42"),2046+ ({"type": str, "flag_value": "1", "default": True}, [], "1"),2047+ ({"type": str, "flag_value": "1", "default": 42}, [], "42"),2048+ (2049+ {"type": str, "flag_value": EngineType.OSS, "default": True},2050+ [],2051+ "EngineType.OSS",2052+ ),2053+ ({"type": str, "flag_value": EngineType.OSS, "default": 42}, [], "42"),2054+ # But having the flag value set to integer is automaticcally recognized by2055+ # Click.2056+ ({"flag_value": 1, "default": True}, [], 1),2057+ ({"flag_value": 1, "default": 42}, [], 42),2058+ ({"type": int, "flag_value": 1, "default": True}, [], 1),2059+ ({"type": int, "flag_value": 1, "default": 42}, [], 42),2060+ ({"type": int, "flag_value": "1", "default": True}, [], 1),2061+ ({"type": int, "flag_value": "1", "default": 42}, [], 42),2062+ ],2063+)2064+def test_custom_type_flag_value_standalone_option(runner, opt_params, args, expected):2065+ """Test how the type and flag_value influence the returned value.2066+2067+ Cover cases reported in:2068+ https://github.com/pallets/click/issues/3024#issuecomment-31464807142069+ https://github.com/pallets/click/issues/2012#issuecomment-8924370602070+ """2071+2072+ @click.command()2073+ @click.option("--pro", **opt_params)2074+ def scan(pro):2075+ click.echo(repr(pro), nl=False)2076+2077+ result = runner.invoke(scan, args)2078+ if isinstance(expected, re.Pattern):2079+ assert re.match(expected, result.output)2080+ else:2081+ assert result.output == repr(expected)2082+2083+2084+@pytest.mark.parametrize(2085+ ("opt1_params", "opt2_params", "args", "expected"),2086+ [2087+ # Dual options sharing the same variable name, are not competitive, and the2088+ # flag value is returned as-is. Especially when the type is force to be2089+ # unprocessed.2090+ (2091+ {"flag_value": EngineType.OSS, "type": UNPROCESSED},2092+ {"flag_value": EngineType.PRO, "type": UNPROCESSED},2093+ [],2094+ None,2095+ ),2096+ (2097+ {"flag_value": EngineType.OSS, "type": UNPROCESSED},2098+ {"flag_value": EngineType.PRO, "type": UNPROCESSED},2099+ ["--opt1"],2100+ EngineType.OSS,2101+ ),2102+ (2103+ {"flag_value": EngineType.OSS, "type": UNPROCESSED},2104+ {"flag_value": EngineType.PRO, "type": UNPROCESSED},2105+ ["--opt2"],2106+ EngineType.PRO,2107+ ),2108+ # Check that passing exotic flag values like classes is supported, but are2109+ # rendered to strings when the type is not specified.2110+ (2111+ {"flag_value": Class1, "default": True},2112+ {"flag_value": Class2},2113+ [],2114+ re.compile(r"'<test_options.Class1 object at 0x[0-9A-Fa-f]+>'"),2115+ ),2116+ (2117+ {"flag_value": Class1, "default": True},2118+ {"flag_value": Class2},2119+ ["--opt1"],2120+ "<class 'test_options.Class1'>",2121+ ),2122+ (2123+ {"flag_value": Class1, "default": True},2124+ {"flag_value": Class2},2125+ ["--opt2"],2126+ "<class 'test_options.Class2'>",2127+ ),2128+ # Even the default is processed as a string.2129+ ({"flag_value": Class1, "default": "True"}, {"flag_value": Class2}, [], "True"),2130+ ({"flag_value": Class1, "default": None}, {"flag_value": Class2}, [], None),2131+ # To get the classes as-is, we need to specify the type as UNPROCESSED.2132+ (2133+ {"flag_value": Class1, "type": UNPROCESSED, "default": True},2134+ {"flag_value": Class2, "type": UNPROCESSED},2135+ [],2136+ re.compile(r"<test_options.Class1 object at 0x[0-9A-Fa-f]+>"),2137+ ),2138+ (2139+ {"flag_value": Class1, "type": UNPROCESSED, "default": True},2140+ {"flag_value": Class2, "type": UNPROCESSED},2141+ ["--opt1"],2142+ Class1,2143+ ),2144+ (2145+ {"flag_value": Class1, "type": UNPROCESSED, "default": True},2146+ {"flag_value": Class2, "type": UNPROCESSED},2147+ ["--opt2"],2148+ Class2,2149+ ),2150+ # Setting the default to a class, an instance of the class is returned instead2151+ # of the class itself, because the default is allowed to be callable (and2152+ # consummd). And this happens whatever the type is.2153+ (2154+ {"flag_value": Class1, "default": Class1},2155+ {"flag_value": Class2},2156+ [],2157+ re.compile(r"'<test_options.Class1 object at 0x[0-9A-Fa-f]+>'"),2158+ ),2159+ (2160+ {"flag_value": Class1, "default": Class2},2161+ {"flag_value": Class2},2162+ [],2163+ re.compile(r"'<test_options.Class2 object at 0x[0-9A-Fa-f]+>'"),2164+ ),2165+ (2166+ {"flag_value": Class1, "type": UNPROCESSED, "default": Class1},2167+ {"flag_value": Class2, "type": UNPROCESSED},2168+ [],2169+ re.compile(r"<test_options.Class1 object at 0x[0-9A-Fa-f]+>"),2170+ ),2171+ (2172+ {"flag_value": Class1, "type": UNPROCESSED, "default": Class2},2173+ {"flag_value": Class2, "type": UNPROCESSED},2174+ [],2175+ re.compile(r"<test_options.Class2 object at 0x[0-9A-Fa-f]+>"),2176+ ),2177+ # Having the flag value set to integer is automaticcally recognized by Click.2178+ (2179+ {"flag_value": 1, "default": True},2180+ {"flag_value": "1"},2181+ [],2182+ 1,2183+ ),2184+ (2185+ {"flag_value": 1, "type": int, "default": True},2186+ {"flag_value": "1", "type": int},2187+ [],2188+ 1,2189+ ),2190+ ],2191+)2192+def test_custom_type_flag_value_dual_options(2193+ runner, opt1_params, opt2_params, args, expected2194+):2195+ """Test how flag values are processed with dual options competing for the same2196+ variable name.2197+2198+ Reproduce issues reported in:2199+ https://github.com/pallets/click/issues/3024#issuecomment-31465085362200+ https://github.com/pallets/click/issues/2012#issue-9464710492201+ https://github.com/pallets/click/issues/2012#issuecomment-8924370602202+ """2203+2204+ @click.command()2205+ @click.option("--opt1", "dual_option", **opt1_params)2206+ @click.option("--opt2", "dual_option", **opt2_params)2207+ def cli(dual_option):2208+ click.echo(repr(dual_option), nl=False)2209+2210+ result = runner.invoke(cli, args)2211+ if isinstance(expected, re.Pattern):2212+ assert re.match(expected, result.output)2213+ else:2214+ assert result.output == repr(expected)2215+2216+2217+def test_custom_type_frozenset_flag_value(runner):2218+ """Check that frozenset is correctly handled as a type, a flag value and a default.2219+2220+ Reproduces https://github.com/pallets/click/issues/26102221+ """2222+2223+ @click.command()2224+ @click.option(2225+ "--without-scm-ignore-files",2226+ "scm_ignore_files",2227+ is_flag=True,2228+ type=frozenset,2229+ flag_value=frozenset(),2230+ default=frozenset(["git"]),2231+ )2232+ def rcli(scm_ignore_files):2233+ click.echo(repr(scm_ignore_files), nl=False)2234+2235+ result = runner.invoke(rcli)2236+ assert result.stdout == "frozenset({'git'})"2237+ assert result.exit_code == 02238+2239+ result = runner.invoke(rcli, ["--without-scm-ignore-files"])2240+ assert result.stdout == "frozenset()"2241+ assert result.exit_code == 0modified:tests/test_shell_completion.py+14 added
218 unmodified lines219 # flag option doesn't take value, use choice argument220 assert _get_words(cli, ["--on"], "a") == ["a1", "a2"]221 222 223+def test_flag_option_with_nargs_option():224+ cli = Command(225+ "cli",226+ add_help_option=False,227+ params=[228+ Argument(["a"], type=Choice(["a1", "a2", "b"])),229+ Option(["--flag"], is_flag=True),230+ Option(["-c"], type=Choice(["p", "q"]), nargs=2),231+ ],232+ )233+ assert _get_words(cli, ["a1", "--flag", "-c"], "") == ["p", "q"]234+235+236 def test_option_custom():237 def custom(ctx, param, incomplete):238 return [incomplete.upper()]239 118 unmodified lines358 ("zsh", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain\na\n_\nplain\nb\nbee\n"),359 ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"),360 ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"),361 ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"),362+ ("fish", {"COMP_WORDS": 'a "b', "COMP_CWORD": '"b'}, "plain,b\tbee\n"),363 ],364 )365 @pytest.mark.usefixtures("_patch_for_completion")366 def test_full_complete(runner, shell, env, expect):195 unmodified linesmodified:tests/test_termui.py+218 added
4 unmodified lines5 import pytest6 7 import click._termui_impl8 from click._compat import WIN9+from click.exceptions import BadParameter10+from click.exceptions import MissingParameter11 12 13 class FakeClock:14 def __init__(self):471 unmodified lines486 # Confirm that the default value is not included in the output when `show_default`487 # is False488 result = runner.invoke(cmd, input="my-input", standalone_mode=False)489 assert "my-default-value" not in result.output490+491+492+REPEAT = object()493+"""Sentinel value to indicate that the prompt is expected to be repeated.494+495+I.e. the value provided by the user is not satisfactory and need to be re-prompted.496+"""497+498+INVALID = object()499+"""Sentinel value to indicate that the prompt is expected to be invalid.500+501+On invalid input, Click will output an error message and re-prompt the user.502+"""503+504+BOOLEAN_FLAG_PROMPT_CASES = [505+ ###506+ ### Test cases with prompt=True explicitly enabled for the flag.507+ ###508+ # Prompt is allowed and the flag has no default, so it prompts.509+ ({"prompt": True}, [], "[y/N]", "y", True),510+ ({"prompt": True}, [], "[y/N]", "n", False),511+ # Empty input default to False.512+ ({"prompt": True}, [], "[y/N]", "", False),513+ # Changing the default to True, makes the prompt change to [Y/n].514+ ({"prompt": True, "default": True}, [], "[Y/n]", "", True),515+ ({"prompt": True, "default": True}, [], "[Y/n]", "y", True),516+ ({"prompt": True, "default": True}, [], "[Y/n]", "n", False),517+ # False is the default's default, so it prompts with [y/N].518+ ({"prompt": True, "default": False}, [], "[y/N]", "", False),519+ ({"prompt": True, "default": False}, [], "[y/N]", "y", True),520+ ({"prompt": True, "default": False}, [], "[y/N]", "n", False),521+ # Defaulting to None, prompts with [y/n], which makes the user explicitly choose522+ # between True or False.523+ ({"prompt": True, "default": None}, [], "[y/n]", "y", True),524+ ({"prompt": True, "default": None}, [], "[y/n]", "n", False),525+ # Random string default is treated as a truthy value, so it prompts with [Y/n].526+ ({"prompt": True, "default": "foo"}, [], "[Y/n]", "", True),527+ ({"prompt": True, "default": "foo"}, [], "[Y/n]", "y", True),528+ ({"prompt": True, "default": "foo"}, [], "[Y/n]", "n", False),529+ ###530+ ### Test cases with required=True explicitly enabled for the flag.531+ ###532+ # A required flag just raises an error unless a default is set.533+ ({"required": True}, [], None, None, MissingParameter),534+ ({"required": True, "default": True}, [], None, None, True),535+ ({"required": True, "default": False}, [], None, None, False),536+ ({"required": True, "default": None}, [], None, None, None),537+ ({"required": True, "default": "on"}, [], None, None, True),538+ ({"required": True, "default": "off"}, [], None, None, False),539+ ({"required": True, "default": "foo"}, [], None, None, BadParameter),540+ ###541+ ### Explicitly passing the flag to the CLI bypass any prompt, whatever the542+ ### configuration of the flag.543+ ###544+ # Flag allowing a prompt.545+ ({"prompt": True}, ["--flag"], None, None, True),546+ ({"prompt": True}, ["--no-flag"], None, None, False),547+ ({"prompt": True, "default": None}, ["--flag"], None, None, True),548+ ({"prompt": True, "default": None}, ["--no-flag"], None, None, False),549+ ({"prompt": True, "default": True}, ["--flag"], None, None, True),550+ ({"prompt": True, "default": True}, ["--no-flag"], None, None, False),551+ ({"prompt": True, "default": False}, ["--flag"], None, None, True),552+ ({"prompt": True, "default": False}, ["--no-flag"], None, None, False),553+ ({"prompt": True, "default": "foo"}, ["--flag"], None, None, True),554+ ({"prompt": True, "default": "foo"}, ["--no-flag"], None, None, False),555+ # Required flag.556+ ({"required": True}, ["--flag"], None, None, True),557+ ({"required": True}, ["--no-flag"], None, None, False),558+ ({"required": True, "default": None}, ["--flag"], None, None, True),559+ ({"required": True, "default": None}, ["--no-flag"], None, None, False),560+ ({"required": True, "default": True}, ["--flag"], None, None, True),561+ ({"required": True, "default": True}, ["--no-flag"], None, None, False),562+ ({"required": True, "default": False}, ["--flag"], None, None, True),563+ ({"required": True, "default": False}, ["--no-flag"], None, None, False),564+ ({"required": True, "default": "foo"}, ["--flag"], None, None, True),565+ ({"required": True, "default": "foo"}, ["--no-flag"], None, None, False),566+]567+568+FLAG_VALUE_PROMPT_CASES = [569+ ###570+ ### Test cases with prompt=True explicitly enabled for the flag.571+ ###572+ # Prompt is allowed and the flag has no default, so it prompts.573+ # But the flag_value is not set, so it defaults to a string.574+ ({"prompt": True}, [], "", "", REPEAT),575+ ({"prompt": True}, [], "", "y", "y"),576+ ({"prompt": True}, [], "", "n", "n"),577+ ({"prompt": True}, [], "", "foo", "foo"),578+ # This time we provide a boolean flag_value, which makes the flag behave like a579+ # boolean flag, and use the appropriate variation of [y/n].580+ ({"prompt": True, "flag_value": True}, [], "[y/N]", "", False),581+ ({"prompt": True, "flag_value": True}, [], "[y/N]", "y", True),582+ ({"prompt": True, "flag_value": True}, [], "[y/N]", "n", False),583+ ({"prompt": True, "flag_value": False}, [], "[y/N]", "", False),584+ ({"prompt": True, "flag_value": False}, [], "[y/N]", "y", True),585+ ({"prompt": True, "flag_value": False}, [], "[y/N]", "n", False),586+ # Other flag values changes the auto-detection of the flag type.587+ ({"prompt": True, "flag_value": None}, [], "", "", REPEAT),588+ ({"prompt": True, "flag_value": None}, [], "", "y", "y"),589+ ({"prompt": True, "flag_value": None}, [], "", "n", "n"),590+ ({"prompt": True, "flag_value": "foo"}, [], "", "", REPEAT),591+ ({"prompt": True, "flag_value": "foo"}, [], "", "y", "y"),592+ ({"prompt": True, "flag_value": "foo"}, [], "", "n", "n"),593+ ###594+ ### Test cases with a flag_value and a default.595+ ###596+ # default=True597+ ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "", True),598+ ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "y", True),599+ ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "n", False),600+ ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "", False),601+ ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "y", True),602+ ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "n", False),603+ # default=False604+ ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "", False),605+ ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "y", True),606+ ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "n", False),607+ ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "", False),608+ ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "y", True),609+ ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "n", False),610+ # default=None611+ (612+ {"prompt": True, "default": None, "flag_value": True},613+ [],614+ "[y/n]",615+ "",616+ INVALID,617+ ),618+ ({"prompt": True, "default": None, "flag_value": True}, [], "[y/n]", "y", True),619+ ({"prompt": True, "default": None, "flag_value": True}, [], "[y/n]", "n", False),620+ (621+ {"prompt": True, "default": None, "flag_value": False},622+ [],623+ "[y/n]",624+ "",625+ INVALID,626+ ),627+ ({"prompt": True, "default": None, "flag_value": False}, [], "[y/n]", "y", True),628+ ({"prompt": True, "default": None, "flag_value": False}, [], "[y/n]", "n", False),629+ # If the flag_value is None, the flag behave like a string flag, whatever the630+ # default is.631+ ({"prompt": True, "default": True, "flag_value": None}, [], "", "", REPEAT),632+ ({"prompt": True, "default": True, "flag_value": None}, [], "", "y", "y"),633+ ({"prompt": True, "default": True, "flag_value": None}, [], "", "n", "n"),634+ (635+ {"prompt": True, "default": False, "flag_value": None},636+ [],637+ "[False]",638+ "",639+ "False",640+ ),641+ ({"prompt": True, "default": False, "flag_value": None}, [], "[False]", "y", "y"),642+ ({"prompt": True, "default": False, "flag_value": None}, [], "[False]", "n", "n"),643+ ({"prompt": True, "default": None, "flag_value": None}, [], "", "", REPEAT),644+ ({"prompt": True, "default": None, "flag_value": None}, [], "", "y", "y"),645+ ({"prompt": True, "default": None, "flag_value": None}, [], "", "n", "n"),646+]647+648+649+@pytest.mark.parametrize(650+ ("opt_decls", "opt_params", "args", "prompt", "input", "expected"),651+ # Boolean flag prompt cases.652+ [("--flag/--no-flag", *case_params) for case_params in BOOLEAN_FLAG_PROMPT_CASES]653+ # Non-boolean flag prompt cases.654+ + [("--flag", *case_params) for case_params in FLAG_VALUE_PROMPT_CASES],655+)656+def test_flag_value_prompt(657+ runner, opt_decls, opt_params, args, prompt, input, expected658+):659+ """Check how flag value are prompted and handled by all combinations of660+ ``prompt``, ``default``, and ``flag_value`` parameters.661+662+ Covers concerns raised in issue https://github.com/pallets/click/issues/1992.663+ """664+665+ @click.command()666+ @click.option(opt_decls, **opt_params)667+ def cli(flag):668+ click.echo(repr(flag))669+670+ invoke_options = {"standalone_mode": False}671+ if input is not None:672+ assert isinstance(input, str)673+ invoke_options["input"] = f"{input}\n"674+675+ result = runner.invoke(cli, args, **invoke_options)676+677+ if expected in (MissingParameter, BadParameter):678+ assert isinstance(result.exception, expected)679+ assert not result.output680+ assert result.exit_code == 1681+682+ else:683+ expected_output = ""684+ if prompt is not None:685+ # Build the expected prompt.686+ assert isinstance(prompt, str)687+ expected_prompt = f"Flag {prompt}: " if prompt else "Flag: "688+689+ # Add the user input to the expected output.690+ assert isinstance(input, str)691+ expected_output += f"{expected_prompt}{input}\n"692+693+ if expected is INVALID:694+ expected_output += "Error: invalid input\n"695+696+ # The prompt is expected to be repeated.697+ if expected in (REPEAT, INVALID):698+ expected_output += expected_prompt699+700+ if expected not in (REPEAT, INVALID):701+ expected_output += f"{expected!r}\n"702+703+ assert result.output == expected_output704+ assert not result.stderr705+ assert result.exit_code == 0 if expected not in (REPEAT, INVALID) else 1modified:tests/test_utils.py+51 added
3 unmodified lines4 import subprocess5 import sys6 from collections import namedtuple7 from contextlib import nullcontext8+from decimal import Decimal9+from fractions import Fraction10 from functools import partial11 from io import StringIO12 from pathlib import Path13 from tempfile import tempdir3 unmodified lines17 18 import click._termui_impl19 import click.utils20 from click._compat import WIN21+from click._utils import UNSET22 23 24+def test_unset_sentinel():25+ value = UNSET26+27+ assert value28+ assert value is UNSET29+ assert value == UNSET30+ assert repr(value) == "Sentinel.UNSET"31+ assert str(value) == "Sentinel.UNSET"32+ assert bool(value) is True33+34+ # Try all native Python values that can be falsy or truthy.35+ # See: https://docs.python.org/3/library/stdtypes.html#truth-value-testing36+ real_values = (37+ None,38+ True,39+ False,40+ 0,41+ 1,42+ 0.0,43+ 1.0,44+ 0j,45+ 1j,46+ Decimal(0),47+ Decimal(1),48+ Fraction(0, 1),49+ Fraction(1, 1),50+ "",51+ "a",52+ "UNSET",53+ "Sentinel.UNSET",54+ [1],55+ (1),56+ {1: "a"},57+ set(),58+ set([1]),59+ frozenset(),60+ frozenset([1]),61+ range(0),62+ range(1),63+ )64+65+ for real_value in real_values:66+ assert value != real_value67+ assert value is not real_value68+69+ assert value not in real_values70+71+72 def test_echo(runner):73 with runner.isolation() as outstreams:74 click.echo("\N{SNOWMAN}")75 click.echo(b"\x44\x44")671 unmodified linesmodified:CHANGES.rst+33 added-5 removed
1 .. currentmodule:: click2 3+Version 8.3.04+--------------5+6+Released 2025-09-157+8+- **Improved flag option handling**: Reworked the relationship between ``flag_value``9+ and ``default`` parameters for better consistency:10+11+ * The ``default`` parameter value is now preserved as-is and passed directly12+ to CLI functions (no more unexpected transformations)13+ * Exception: flag options with ``default=True`` maintain backward compatibility14+ by defaulting to their ``flag_value``15+ * The ``default`` parameter can now be any type (``bool``, ``None``, etc.)16+ * Fixes inconsistencies reported in: :issue:`1992` :issue:`2514` :issue:`2610`17+ :issue:`3024` :pr:`3030`18+- Allow ``default`` to be set on ``Argument`` for ``nargs = -1``. :issue:`2164`19+ :pr:`3030`20+- Show correct auto complete value for ``nargs`` option in combination with flag21+ option :issue:`2813`22+- Show correct auto complete value for nargs option in combination with flag option :issue:`2813`23+- Fix handling of quoted and escaped parameters in Fish autocompletion. :issue:`2995` :pr:`3013`24+- Lazily import ``shutil``. :pr:`3023`25+- Properly forward exception information to resources registered with26+ ``click.core.Context.with_resource()``. :issue:`2447` :pr:`3058`27+- Fix regression related to EOF handling in CliRunner. :issue:`2939`:pr:`2940`28+29 Version 8.2.230 -------------31 6-Unreleased32+Released 2025-07-3133 8-- Fix reconciliation of `default`, `flag_value` and `type` parameters for34+- Fix reconciliation of ``default``, ``flag_value`` and ``type`` parameters for35 flag options, as well as parsing and normalization of environment variables.36 :issue:`2952` :pr:`2956`37 - Fix typing issue in ``BadParameter`` and ``MissingParameter`` exceptions for the38 parameter ``param_hint`` that did not allow for a sequence of string where the13- underlying functino ``_join_param_hints`` allows for it. :issue:`2777` :pr:`2990`39+ underlying function ``_join_param_hints`` allows for it. :issue:`2777` :pr:`2990`40 - Use the value of ``Enum`` choices to render their default value in help41 screen. Refs :issue:`2911` :pr:`3004`42 - Fix completion for the Z shell (``zsh``) for completion items containing43 colons. :issue:`2703` :pr:`2846`18-- Fix rendering when ``prompt`` and ``confirm`` parameter ``prompt_suffix`` is19- empty. :issue:`3019`44+- Don't include envvar in error hint when not configured. :issue:`2971` :pr:`2972`45+- Fix a rare race in ``click.testing.StreamMixer``'s finalization that manifested46+ as a ``ValueError`` on close in a multi-threaded test session.47+ :issue:`2993` :pr:`2991`48 49 Version 8.2.150 -------------51 1242 unmodified linesmodified:pyproject.toml+1 added-1 removed
1 [project]2 name = "click"3-version = "8.2.1"3+version = "8.3.0"4 description = "Composable command line interface toolkit"5 readme = "README.md"6 license = "BSD-3-Clause"7 license-files = ["LICENSE.txt"]201 unmodified linesmodified:uv.lock+1 added-1 removed
137 unmodified lines138 ]139 140 [[package]]141 name = "click"142-version = "8.2.1"142+version = "8.3.0"143 source = { editable = "." }144 dependencies = [145 { name = "colorama", marker = "sys_platform == 'win32'" },146 ]1076 unmodified lines