Skip to content
Myr

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

32 files+2972 added−1346 removed

modified:docs/documentation.md+1 added-1 removed
145 unmodified lines
146```147148## Click's Wrapping Behavior149150Click'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.150Click'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.151152```{eval-rst}153.. click:example::154
123 unmodified lines
modified:docs/options.md+25 added-4 removed
312 unmodified lines
313```314315## Flag Value316317To 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:317To 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:318319```{eval-rst}320.. click:example::321
12 unmodified lines
334 invoke(info, args=['--lower'])335 invoke(info)336```337338````{note}339The `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.340341But 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`.342343Which means, in example above, this option:344345```python346@click.option('--upper', 'transformation', flag_value='upper', default=True)347```348349is equivalent to:350351```python352@click.option('--upper', 'transformation', flag_value='upper', default='upper')353```354355Because 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````357358## Values from Environment Variables359360To pass in a value in from a specific environment variable use `envvar`.361
43 unmodified lines
405 - 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 flag408389.. 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}410For boolean flags with a pair of values, the only recognized environment variable is the one provided to the `envvar` argument.411392 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.412So 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```414415Once 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.416417## Multiple Options from Environment Values
80 unmodified lines
added:docs/parameter-types.md+186 added
1(parameter-types)=23# Parameter Types45```{currentmodule} click6```78When the parameter type is set using `type`, Click will leverage the type to make your life easier, for example adding9data to your help pages. Most examples are done with options, but types are available to options and arguments.1011```{contents}12---13depth: 214local: true15---16```1718## Built-in Types Examples1920(choice-opts)=2122### Choice2324Sometimes, you want to have a parameter be a choice of a list of values. In that case you can use {class}`Choice` type.25It can be instantiated with a list of valid values. The originally passed choice will be returned, not the str passed on26the command line. Token normalization functions and `case_sensitive=False` can cause the two to be different but still27match. {meth}`Choice.normalize_choice` for more info.282930Example:3132```{eval-rst}33.. click:example::3435 import enum3637 class HashType(enum.Enum):38 MD5 = enum.auto()39 SHA1 = enum.auto()4041 @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)4647What it looks like:4849.. click:run::5051 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```5960Any iterable may be passed to {class}`Choice`. If an `Enum` is passed, the names of the enum members will be used as61valid choices.6263Choices work with options that have `multiple=True`. If a `default` value is given with `multiple=True`, it should be a64list or tuple of valid choices.6566Choices should be unique after normalization, see {meth}`Choice.normalize_choice` for more info.6768```{versionchanged} 7.169The resulting value from an option will always be one of the originally passed choices70regardless of `case_sensitive`.71```7273(ranges)=7475### Int and Float Ranges7677The {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`.7980If `min` or `max` is omitted, that side is *unbounded*. Any value in that direction is accepted. By default, both bounds81are *closed*, which means the boundary value is included in the accepted range. `min_open` and `max_open` can be used to82exclude that boundary from the range.8384If `clamp` mode is enabled, a value that is outside the range is set to the boundary instead of failing. For example,85the range `0, 5` would return `5` for the value `10`, or `0` for the value `-1`. When using {class}`FloatRange`, `clamp`86can only be enabled if both bounds are *closed* (the default).8788```{eval-rst}89.. click:example::9091 @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)9697.. click:run::9899 invoke(repeat, args=['--count=100', '--digit=5'])100 invoke(repeat, args=['--count=6', '--digit=12'])101```102103## Built-in Types Listing104105The supported parameter {ref}`click-api-types` are106107- `str` / {data}`click.STRING`: The default parameter type which indicates unicode strings.108109- `int` / {data}`click.INT`: A parameter that only accepts integers.110111- `float` / {data}`click.FLOAT`: A parameter that only accepts floating point values.112113- `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`.116117- {data}`click.UUID`: A parameter that accepts UUID values. This is not automatically guessed but represented as118 {class}`uuid.UUID`.119120```{eval-rst}121* .. autoclass:: Choice122 :noindex:123```124125```{eval-rst}126* .. autoclass:: DateTime127 :noindex:128```129130```{eval-rst}131* .. autoclass:: File132 :noindex:133```134135```{eval-rst}136* .. autoclass:: FloatRange137 :noindex:138```139140```{eval-rst}141* .. autoclass:: IntRange142 :noindex:143```144145```{eval-rst}146* .. autoclass:: Path147 :noindex:148```149150## How to Implement Custom Types151152To implement a custom type, you need to subclass the {class}`ParamType` class. For simple cases, passing a Python153function that fails with a `ValueError` is also supported, though discouraged. Override the {meth}`~ParamType.convert`154method to convert the value from a string to the correct type.155156The following code implements an integer type that accepts hex and octal numbers in addition to normal integers, and157converts them into regular integers.158159```python160import click161162class BasedIntParamType(click.ParamType):163 name = "integer"164165 def convert(self, value, param, ctx):166 if isinstance(value, int):167 return value168169 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)177178BASED_INT = BasedIntParamType()179```180181The {attr}`~ParamType.name` attribute is optional and is used for documentation. Call {meth}`~ParamType.fail` if182conversion fails. The `param` and `ctx` arguments may be `None` in some cases such as prompts.183184Values from user input or the command line will be strings, but default values and Python arguments may already be the185correct type. The custom type should check at the top if the value is already valid and pass it through to support those186cases.
deleted:docs/parameter-types.rst-181 removed
1.. _parameter-types:23Parameter Types4==================56.. currentmodule:: click78When 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.910.. contents::11 :depth: 212 :local:1314Built-in Types Examples15------------------------1617.. _choice-opts:1819Choice20^^^^^^^^^^^^^^^^^^^^^^2122Sometimes, you want to have a parameter be a choice of a list of values.23In that case you can use :class:`Choice` type. It can be instantiated24with a list of valid values. The originally passed choice will be returned,25not 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.2829Example:3031.. click:example::3233 import enum3435 class HashType(enum.Enum):36 MD5 = enum.auto()37 SHA1 = enum.auto()3839 @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)4445What it looks like:4647.. click:run::4849 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'])5657Any iterable may be passed to :class:`Choice`. If an ``Enum`` is passed, the58names of the enum members will be used as valid choices.5960Choices work with options that have ``multiple=True``. If a ``default``61value is given with ``multiple=True``, it should be a list or tuple of62valid choices.6364Choices should be unique after normalization, see65:meth:`Choice.normalize_choice` for more info.6667.. versionchanged:: 7.168 The resulting value from an option will always be one of the69 originally passed choices regardless of ``case_sensitive``.7071.. _ranges:7273Int and Float Ranges74^^^^^^^^^^^^^^^^^^^^^^^7576The :class:`IntRange` type extends the :data:`INT` type to ensure the77value is contained in the given range. The :class:`FloatRange` type does78the same for :data:`FLOAT`.7980If ``min`` or ``max`` is omitted, that side is *unbounded*. Any value in81that direction is accepted. By default, both bounds are *closed*, which82means the boundary value is included in the accepted range. ``min_open``83and ``max_open`` can be used to exclude that boundary from the range.8485If ``clamp`` mode is enabled, a value that is outside the range is set86to the boundary instead of failing. For example, the range ``0, 5``87would return ``5`` for the value ``10``, or ``0`` for the value ``-1``.88When using :class:`FloatRange`, ``clamp`` can only be enabled if both89bounds are *closed* (the default).9091.. click:example::9293 @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)9899.. click:run::100101 invoke(repeat, args=['--count=100', '--digit=5'])102 invoke(repeat, args=['--count=6', '--digit=12'])103104105Built-in Types Listing106-----------------------107The supported parameter :ref:`click-api-types` are:108109* ``str`` / :data:`click.STRING`: The default parameter type which indicates unicode strings.110111* ``int`` / :data:`click.INT`: A parameter that only accepts integers.112113* ``float`` / :data:`click.FLOAT`: A parameter that only accepts floating point values.114115* ``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``.119120* :data:`click.UUID`:121 A parameter that accepts UUID values. This is not automatically122 guessed but represented as :class:`uuid.UUID`.123124* .. autoclass:: Choice125 :noindex:126127* .. autoclass:: DateTime128 :noindex:129130* .. autoclass:: File131 :noindex:132133* .. autoclass:: FloatRange134 :noindex:135136* .. autoclass:: IntRange137 :noindex:138139* .. autoclass:: Path140 :noindex:141142How to Implement Custom Types143-------------------------------144145To 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.146147The following code implements an integer type that accepts hex and octal148numbers in addition to normal integers, and converts them into regular149integers.150151.. code-block:: python152153 import click154155 class BasedIntParamType(click.ParamType):156 name = "integer"157158 def convert(self, value, param, ctx):159 if isinstance(value, int):160 return value161162 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)170171 BASED_INT = BasedIntParamType()172173The :attr:`~ParamType.name` attribute is optional and is used for174documentation. Call :meth:`~ParamType.fail` if conversion fails. The175``param`` and ``ctx`` arguments may be ``None`` in some cases such as176prompts.177178Values from user input or the command line will be strings, but default179values and Python arguments may already be the correct type. The custom180type should check at the top if the value is already valid and pass it181through to support those cases.
added:docs/prompts.md+168 added
1# User Input Prompts23```{currentmodule} click4```56Click supports prompts in two different places. The first is automated prompts when the parameter handling happens, and7the second is to ask for prompts at a later point independently.89This 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).1112```{contents}13---14depth: 215local: true16---17```1819(option-prompting)=2021## Option Prompts2223Option prompts are integrated into the option interface. Internally, it automatically calls either {func}`prompt` or24{func}`confirm` as necessary.2526In some cases, you want parameters that can be provided from the command line, but if not provided, ask for user input27instead. This can be implemented with Click by defining a prompt string.2829Example:3031```{eval-rst}32.. click:example::3334 @click.command()35 @click.option('--name', prompt=True)36 def hello(name):37 click.echo(f"Hello {name}!")3839And what it looks like:4041.. click:run::4243 invoke(hello, args=['--name=John'])44 invoke(hello, input=['John'])45```4647If you are not happy with the default prompt string, you can ask for48a different one:4950```{eval-rst}51.. click:example::5253 @click.command()54 @click.option('--name', prompt='Your name please')55 def hello(name):56 click.echo(f"Hello {name}!")5758What it looks like:5960.. click:run::6162 invoke(hello, input=['John'])63```6465It is advised that prompt not be used in conjunction with the multiple flag set to True. Instead, prompt in the function66interactively.6768By default, the user will be prompted for an input if one was not passed through the command line. To turn this behavior69off, see {ref}`optional-value`.7071## Input Prompts7273To manually ask for user input, you can use the {func}`prompt` function. By default, it accepts any Unicode string, but74you can ask for any other type. For instance, you can ask for a valid integer:7576```python77value = click.prompt('Please enter a valid integer', type=int)78```7980Additionally, the type will be determined automatically if a default value is provided. For instance, the following will81only accept floats:8283```python84value = click.prompt('Please enter a number', default=42.0)85```8687## Optional Prompts8889If the option has `prompt` enabled, then setting `prompt_required=False` tells Click to only show the prompt if the90option's flag is given, instead of if the option is not provided at all.9192```{eval-rst}93.. click:example::9495 @click.command()96 @click.option('--name', prompt=True, prompt_required=False, default="Default")97 def hello(name):98 click.echo(f"Hello {name}!")99100.. click:run::101102 invoke(hello)103 invoke(hello, args=["--name", "Value"])104 invoke(hello, args=["--name"], input="Prompt")105```106107If `required=True`, then the option will still prompt if it is not given, but it will also prompt if only the flag is108given.109110## Confirmation Prompts111112To ask if a user wants to continue with an action, the {func}`confirm` function comes in handy. By default, it returns113the result of the prompt as a boolean value:114115```python116if click.confirm('Do you want to continue?'):117 click.echo('Well done!')118```119120There is also the option to make the function automatically abort the execution of the program if it does not return121`True`:122123```python124click.confirm('Do you want to continue?', abort=True)125```126127## Dynamic Defaults for Prompts128129The `auto_envvar_prefix` and `default_map` options for the context allow the program to read option values from the130environment or a configuration file. However, this overrides the prompting mechanism, so that the user does not get the131option to change the value interactively.132133If you want to let the user configure the default value, but still be prompted if the option isn't specified on the134command line, you can do so by supplying a callable as the default value. For example, to get a default from the135environment:136137```python138import os139140@click.command()141@click.option(142 "--username", prompt=True,143 default=lambda: os.environ.get("USER", "")144)145def hello(username):146 click.echo(f"Hello, {username}!")147```148149To describe what the default value will be, set it in ``show_default``.150151```{eval-rst}152.. click:example::153154 import os155156 @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}!")164165.. click:run::166167 invoke(hello, args=["--help"])168```
deleted:docs/prompts.rst-162 removed
1User Input Prompts2==================34.. currentmodule:: click56Click supports prompts in two different places. The first is automated7prompts when the parameter handling happens, and the second is to ask for8prompts at a later point independently.910This can be accomplished with the :func:`prompt` function, which asks for11valid input according to a type, or the :func:`confirm` function, which asks12for confirmation (yes/no).1314.. contents::15 :depth: 216 :local:1718.. _option-prompting:1920Option Prompts21--------------2223Option prompts are integrated into the option interface. Internally, it24automatically calls either :func:`prompt` or :func:`confirm` as necessary.2526In some cases, you want parameters that can be provided from the command line,27but if not provided, ask for user input instead. This can be implemented with28Click by defining a prompt string.2930Example:3132.. click:example::3334 @click.command()35 @click.option('--name', prompt=True)36 def hello(name):37 click.echo(f"Hello {name}!")3839And what it looks like:4041.. click:run::4243 invoke(hello, args=['--name=John'])44 invoke(hello, input=['John'])4546If you are not happy with the default prompt string, you can ask for47a different one:4849.. click:example::5051 @click.command()52 @click.option('--name', prompt='Your name please')53 def hello(name):54 click.echo(f"Hello {name}!")5556What it looks like:5758.. click:run::5960 invoke(hello, input=['John'])6162It is advised that prompt not be used in conjunction with the multiple63flag set to True. Instead, prompt in the function interactively.6465By default, the user will be prompted for an input if one was not passed66through the command line. To turn this behavior off, see67:ref:`optional-value`.6869Input Prompts70-------------7172To manually ask for user input, you can use the :func:`prompt` function.73By default, it accepts any Unicode string, but you can ask for any other74type. For instance, you can ask for a valid integer::7576 value = click.prompt('Please enter a valid integer', type=int)7778Additionally, the type will be determined automatically if a default value is79provided. For instance, the following will only accept floats::8081 value = click.prompt('Please enter a number', default=42.0)8283Optional Prompts84------------------85If the option has ``prompt`` enabled, then setting86``prompt_required=False`` tells Click to only show the prompt if the87option's flag is given, instead of if the option is not provided at all.8889.. click:example::9091 @click.command()92 @click.option('--name', prompt=True, prompt_required=False, default="Default")93 def hello(name):94 click.echo(f"Hello {name}!")9596.. click:run::9798 invoke(hello)99 invoke(hello, args=["--name", "Value"])100 invoke(hello, args=["--name"], input="Prompt")101102If ``required=True``, then the option will still prompt if it is not103given, but it will also prompt if only the flag is given.104105Confirmation Prompts106--------------------107108To ask if a user wants to continue with an action, the :func:`confirm`109function comes in handy. By default, it returns the result of the prompt110as a boolean value::111112 if click.confirm('Do you want to continue?'):113 click.echo('Well done!')114115There is also the option to make the function automatically abort the116execution of the program if it does not return ``True``::117118 click.confirm('Do you want to continue?', abort=True)119120Dynamic Defaults for Prompts121----------------------------122123The ``auto_envvar_prefix`` and ``default_map`` options for the context124allow the program to read option values from the environment or a125configuration file. However, this overrides the prompting mechanism, so126that the user does not get the option to change the value interactively.127128If you want to let the user configure the default value, but still be129prompted if the option isn't specified on the command line, you can do so130by supplying a callable as the default value. For example, to get a default131from the environment:132133.. code-block:: python134135 import os136137 @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}!")144145To describe what the default value will be, set it in ``show_default``.146147.. click:example::148149 import os150151 @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}!")159160.. click:run::161162 invoke(hello, args=["--help"])
added:docs/quickstart.md+196 added
1# Quickstart23```{currentmodule} click4```56## Install78Install from PyPI:910```console11pip install click12```1314Installing into a virtual environment is highly recommended. We suggest {ref}`virtualenv-heading`.1516## Examples1718Some 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.2021- [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.3940## Basic Concepts - Creating a Command4142Click is based on declaring commands through decorators. Internally, there is a non-decorator interface for advanced use43cases, but it's discouraged for high-level usage.4445A function becomes a Click command line tool by decorating it through {func}`command`. At its simplest, just46decorating a function with this decorator will make it into a callable script:474849```{eval-rst}50.. click:example::51 import click5253 @click.command()54 def hello():55 click.echo('Hello World!')5657What's happening is that the decorator converts the function into a :class:`Command` which then can be invoked:5859.. click:example::60 if __name__ == '__main__':61 hello()6263And what it looks like:6465.. click:run::66 invoke(hello, args=[], prog_name='python hello.py')6768And the corresponding help page:6970.. click:run::71 invoke(hello, args=['--help'], prog_name='python hello.py')72```7374## Echoing7576Why does this example use {func}`echo` instead of the regular {func}`print` function? The answer to this question is77that Click attempts to support different environments consistently and to be very robust even when the environment is78misconfigured. Click wants to be functional at least on a basic level even if everything is completely broken.7980What this means is that the {func}`echo` function applies some error correction in case the terminal is misconfigured81instead of dying with a {exc}`UnicodeError`.8283The echo function also supports color and other styles in output. It will automatically remove styles if the output84stream is a file. On Windows, colorama is automatically installed and used. See {ref}`ansi-colors`.8586If you don't need this, you can also use the `print()` construct / function.8788## Nesting Commands8990Commands can be attached to other commands of type {class}`Group`. This allows arbitrary nesting of scripts. As an91example here is a script that implements two commands for managing databases:9293```{eval-rst}94.. click:example::95 @click.group()96 def cli():97 pass9899 @click.command()100 def initdb():101 click.echo('Initialized the database')102103 @click.command()104 def dropdb():105 click.echo('Dropped the database')106107 cli.add_command(initdb)108 cli.add_command(dropdb)109```110111As you can see, the {func}`group` decorator works like the {func}`command` decorator, but creates a {class}`Group`112object instead which can be given multiple subcommands that can be attached with {meth}`Group.add_command`.113114For simple scripts, it's also possible to automatically attach and create a command by using the {meth}`Group.command`115decorator instead. The above script can instead be written like this:116117```{eval-rst}118.. click:example::119 @click.group()120 def cli():121 pass122123 @cli.command()124 def initdb():125 click.echo('Initialized the database')126127 @cli.command()128 def dropdb():129 click.echo('Dropped the database')130131You would then invoke the :class:`Group` in your entry points or other invocations:132133.. click:example::134 if __name__ == '__main__':135 cli()136```137138## Registering Commands Later139140Instead of using the `@group.command()` decorator, commands can be decorated with the plain `@command()` decorator141and registered with a group later with `group.add_command()`. This could be used to split commands into multiple Python142modules.143144```{code-block} python145 @click.command()146 def greet():147 click.echo("Hello, World!")148```149150```{code-block} python151 @click.group()152 def group():153 pass154155 group.add_command(greet)156```157158## Adding Parameters159160To add parameters, use the {func}`option` and {func}`argument` decorators:161162```{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}!")170171What it looks like:172173.. click:run::174 invoke(hello, args=['--help'], prog_name='python hello.py')175```176177## Switching to Entry Points178179In 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 continue181doing that, but a better way is to package your app with an entry point.182183There are two main (and many more) reasons for this:184185The first one is that installers automatically generate executable wrappers for Windows so your command line utilities186work on Windows too.187188The second reason is that entry point scripts work with virtualenv on Unix without the virtualenv having to be189activated. This is a very useful concept which allows you to bundle your scripts with all requirements into a190virtualenv.191192Click is perfectly equipped to work with that and in fact the rest of the documentation will assume that you are writing193applications as distributed packages.194195Look at the {doc}`entry-points` chapter before reading the rest as the examples assume that you will be using entry196points.
deleted:docs/quickstart.rst-206 removed
1Quickstart2==========34.. currentmodule:: click56Install7----------------------8Install from PyPI::910 pip install click1112Installing into a virtual environment is highly recommended. We suggest :ref:`virtualenv-heading`.1314Examples15-----------------------1617Some 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.1819* `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.2829Basic Concepts - Creating a Command30-----------------------------------3132Click is based on declaring commands through decorators. Internally, there33is a non-decorator interface for advanced use cases, but it's discouraged34for high-level usage.3536A function becomes a Click command line tool by decorating it through37:func:`click.command`. At its simplest, just decorating a function38with this decorator will make it into a callable script:3940.. click:example::4142 import click4344 @click.command()45 def hello():46 click.echo('Hello World!')4748What's happening is that the decorator converts the function into a49:class:`Command` which then can be invoked::5051 if __name__ == '__main__':52 hello()5354And what it looks like:5556.. click:run::5758 invoke(hello, args=[], prog_name='python hello.py')5960And the corresponding help page:6162.. click:run::6364 invoke(hello, args=['--help'], prog_name='python hello.py')6566Echoing67-------6869Why does this example use :func:`echo` instead of the regular70:func:`print` function? The answer to this question is that Click71attempts to support different environments consistently and to be very72robust even when the environment is misconfigured. Click wants to be73functional at least on a basic level even if everything is completely74broken.7576What this means is that the :func:`echo` function applies some error77correction in case the terminal is misconfigured instead of dying with a78:exc:`UnicodeError`.7980The echo function also supports color and other styles in output. It81will automatically remove styles if the output stream is a file. On82Windows, colorama is automatically installed and used. See83:ref:`ansi-colors`.8485If you don't need this, you can also use the `print()` construct /86function.8788Nesting Commands89----------------9091Commands can be attached to other commands of type :class:`Group`. This92allows arbitrary nesting of scripts. As an example here is a script that93implements two commands for managing databases:9495.. click:example::9697 @click.group()98 def cli():99 pass100101 @click.command()102 def initdb():103 click.echo('Initialized the database')104105 @click.command()106 def dropdb():107 click.echo('Dropped the database')108109 cli.add_command(initdb)110 cli.add_command(dropdb)111112As you can see, the :func:`group` decorator works like the :func:`command`113decorator, but creates a :class:`Group` object instead which can be given114multiple subcommands that can be attached with :meth:`Group.add_command`.115116For simple scripts, it's also possible to automatically attach and create a117command by using the :meth:`Group.command` decorator instead. The above118script can instead be written like this:119120.. click:example::121122 @click.group()123 def cli():124 pass125126 @cli.command()127 def initdb():128 click.echo('Initialized the database')129130 @cli.command()131 def dropdb():132 click.echo('Dropped the database')133134You would then invoke the :class:`Group` in your entry points or other invocations::135136 if __name__ == '__main__':137 cli()138139140Registering Commands Later141--------------------------142143Instead of using the ``@group.command()`` decorator, commands can be144decorated with the plain ``@click.command()`` decorator and registered145with a group later with ``group.add_command()``. This could be used to146split commands into multiple Python modules.147148.. code-block:: python149150 @click.command()151 def greet():152 click.echo("Hello, World!")153154.. code-block:: python155156 @click.group()157 def group():158 pass159160 group.add_command(greet)161162163Adding Parameters164-----------------165166To add parameters, use the :func:`option` and :func:`argument` decorators:167168.. click:example::169170 @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}!")176177What it looks like:178179.. click:run::180181 invoke(hello, args=['--help'], prog_name='python hello.py')182183Switching to Entry Points184-------------------------185186In the code you wrote so far there is a block at the end of the file which187looks like this: ``if __name__ == '__main__':``. This is traditionally188how a standalone Python file looks like. With Click you can continue189doing that, but a better way is to package your app with an entry point.190191There are two main (and many more) reasons for this:192193The first one is that installers automatically generate executable194wrappers for Windows so your command line utilities work on Windows too.195196The second reason is that entry point scripts work with virtualenv on Unix197without the virtualenv having to be activated. This is a very useful198concept which allows you to bundle your scripts with all requirements into199a virtualenv.200201Click is perfectly equipped to work with that and in fact the rest of the202documentation will assume that you are writing applications as distributed203packages.204205Look at the :doc:`entry-points` chapter before reading the rest as the examples206assume that you will be using entry points.
added:docs/setuptools.md+7 added
deleted:docs/setuptools.rst-6 removed
1:orphan:23Setuptools Integration4======================56Moved to :doc:`entry-points`.
added:docs/shell-completion.md+249 added
1(shell-completion)=23# Shell Completion45```{currentmodule} click.shell_completion6```78Click provides tab completion support for Bash (version 4.4 and up), Zsh, and Fish. It is possible to add support for9other shells too, and suggestions can be customized at multiple levels.1011Shell completion suggests command names, option names, and values for choice, file, and path parameter types. Options12are only listed if at least a dash has been entered. Hidden commands and options are not shown.1314```console15$ repo <TAB><TAB>16clone commit copy delete setuser17$ repo clone -<TAB><TAB>18--deep --help --rev --shallow -r19```2021## Enabling Completion2223Completion is only available if a script is installed and invoked through an entry point, not through the `python`24command. See {doc}`entry-points`. Once the executable is installed, calling it with a special environment variable will25put Click in completion mode.2627To enable shell completion, the user needs to register a special function with their shell. The exact script varies28depending 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 is30conventional but not strictly required for environment variable names to be in upper case. This convention helps31distinguish environment variables from regular shell variables and commands, making scripts and configuration files more32readable and easier to maintain. The built-in shells are `bash`, `zsh`, and `fish`.3334Provide your users with the following instructions customized to your program name. This uses `foo-bar` as an example.3536```{eval-rst}37.. tabs::3839 .. group-tab:: Bash4041 Add this to ``~/.bashrc``:4243 .. code-block:: bash4445 eval "$(_FOO_BAR_COMPLETE=bash_source foo-bar)"4647 .. group-tab:: Zsh4849 Add this to ``~/.zshrc``:5051 .. code-block:: zsh5253 eval "$(_FOO_BAR_COMPLETE=zsh_source foo-bar)"5455 .. group-tab:: Fish5657 Add this to ``~/.config/fish/completions/foo-bar.fish``:5859 .. code-block:: fish6061 _FOO_BAR_COMPLETE=fish_source foo-bar | source6263 This is the same file used for the activation script method64 below. For Fish it's probably always easier to use that method.65```6667Using `eval` means that the command is invoked and evaluated every time a shell is started, which can delay shell68responsiveness. To speed it up, write the generated script to a file, then source that. You can generate the files ahead69of time and distribute them with your program to save your users a step.7071```{eval-rst}72.. tabs::7374 .. group-tab:: Bash7576 Save the script somewhere.7778 .. code-block:: bash7980 _FOO_BAR_COMPLETE=bash_source foo-bar > ~/.foo-bar-complete.bash8182 Source the file in ``~/.bashrc``.8384 .. code-block:: bash8586 . ~/.foo-bar-complete.bash8788 .. group-tab:: Zsh8990 Save the script somewhere.9192 .. code-block:: bash9394 _FOO_BAR_COMPLETE=zsh_source foo-bar > ~/.foo-bar-complete.zsh9596 Source the file in ``~/.zshrc``.9798 .. code-block:: bash99100 . ~/.foo-bar-complete.zsh101102 .. group-tab:: Fish103104 Save the script to ``~/.config/fish/completions/foo-bar.fish``:105106 .. code-block:: fish107108 _FOO_BAR_COMPLETE=fish_source foo-bar > ~/.config/fish/completions/foo-bar.fish109```110111After modifying the shell config, you need to start a new shell in order for the changes to be loaded.112113## Custom Type Completion114115When creating a custom {class}`~click.ParamType`, override its {meth}`~click.ParamType.shell_complete` method to provide116shell completion for parameters with the type. The method must return a list of {class}`~CompletionItem` objects.117Besides the value, these objects hold metadata that shell support might use. The built-in implementations use `type` to118indicate special handling for paths, and `help` for shells that support showing a help string next to a suggestion.119120In this example, the type will suggest environment variables that start with the incomplete value.121122```python123class EnvVarType(ParamType):124 name = "envvar"125126 def shell_complete(self, ctx, param, incomplete):127 return [128 CompletionItem(name)129 for name in os.environ if name.startswith(incomplete)130 ]131132@click.command()133@click.option("--ev", type=EnvVarType())134def cli(ev):135 click.echo(os.environ[ev])136```137138## Overriding Value Completion139140Value completions for a parameter can be customized without a custom type by providing a `shell_complete` function. The141function is used instead of any completion provided by the type. It is passed 3 positional arguments:142143- `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.147148It must return a list of {class}`CompletionItem` objects, or as a shortcut it can return a list of strings.149150In this example, the command will suggest environment variables that start with the incomplete value.151152```python153def complete_env_vars(ctx, param, incomplete):154 return [k for k in os.environ if k.startswith(incomplete)]155156@click.command()157@click.argument("name", shell_complete=complete_env_vars)158def cli(name):159 click.echo(f"Name: {name}")160 click.echo(f"Value: {os.environ[name]}")161```162163## Adding Support for a Shell164165Support can be added for shells that do not come built in. Be sure to check PyPI to see if there's already a package166that adds support for your shell. This topic is very technical, you'll want to look at Click's source to study the167built-in implementations.168169Shell support is provided by subclasses of {class}`ShellComplete` registered with {func}`add_completion_class`. When170Click 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 require172implementing some smaller parts.173174First, you'll need to figure out how your shell's completion system works and write a script to integrate it with Click.175It must invoke your program with the environment variable `_{FOO_BAR}_COMPLETE` set to `{shell}_complete` and pass the176complete args and incomplete value. How it passes those values, and the format of the completion response from Click is177up to you.178179In your subclass, set {attr}`ShellComplete.source_template` to the completion script. The default implementation will180perform `%` formatting with the following variables:181182- `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.185186The example code is for a made up shell "My Shell" or "mysh" for short.187188```python189from click.shell_completion import add_completion_class190from click.shell_completion import ShellComplete191192_mysh_source = """\193%(complete_func)s {194 response=$(%(complete_var)s=mysh_complete %(foo_bar)s)195 # parse response and set completions somehow196}197call-on-complete %(foo_bar)s %(complete_func)s198"""199200@add_completion_class201class MyshComplete(ShellComplete):202 name = "mysh"203 source_template = _mysh_source204```205206Next, implement {meth}`~ShellComplete.get_completion_args`. This must get, parse, and return the complete args and207incomplete value from the completion script. For example, for the Bash implementation the `COMP_WORDS` env var contains208the command line args as a string, and the `COMP_CWORD` env var contains the index of the incomplete arg. The method209must return a `(args, incomplete)` tuple.210211```python212import os213from click.parser import split_arg_string214215class MyshComplete(ShellComplete):216 ...217218 def get_completion_args(self):219 args = split_arg_string(os.environ["COMP_WORDS"])220221 if os.environ["COMP_PARTIAL"] == "1":222 incomplete = args.pop()223 return args, incomplete224225 return args, ""226```227228Finally, 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.229230The `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.232233```python234class MyshComplete(ShellComplete):235 ...236237 def format_completion(self, item):238 return f"{item.type}\t{item.value}"239```240241With those three things implemented, the new shell support is ready. In case those weren't sufficient, there are more242parts that can be overridden, but that probably isn't necessary.243244The activation instructions will again depend on how your shell works. Use the following to generate the completion245script, then load it into the shell somehow.246247```console248_FOO_BAR_COMPLETE=mysh_source foo-bar249```
deleted:docs/shell-completion.rst-291 removed
1.. currentmodule:: click.shell_completion23Shell Completion4================56Click provides tab completion support for Bash (version 4.4 and up),7Zsh, and Fish. It is possible to add support for other shells too, and8suggestions can be customized at multiple levels.910Shell completion suggests command names, option names, and values for11choice, file, and path parameter types. Options are only listed if at12least a dash has been entered. Hidden commands and options are not13shown.1415.. code-block:: text1617 $ repo <TAB><TAB>18 clone commit copy delete setuser19 $ repo clone -<TAB><TAB>20 --deep --help --rev --shallow -r212223Enabling Completion24-------------------2526Completion is only available if a script is installed and invoked27through an entry point, not through the ``python`` command. See28:doc:`entry-points`. Once the executable is installed, calling it with29a special environment variable will put Click in completion mode.3031To enable shell completion, the user needs to register a special32function with their shell. The exact script varies depending on the33shell you are using. Click will output it when called with34``_{FOO_BAR}_COMPLETE`` set to ``{shell}_source``. ``{FOO_BAR}`` is35the executable name in uppercase with dashes replaced by underscores.36It is conventional but not strictly required for environment variable37names to be in upper case. This convention helps distinguish environment38variables from regular shell variables and commands, making scripts39and configuration files more readable and easier to maintain. The40built-in shells are ``bash``, ``zsh``, and ``fish``.4142Provide your users with the following instructions customized to your43program name. This uses ``foo-bar`` as an example.4445.. tabs::4647 .. group-tab:: Bash4849 Add this to ``~/.bashrc``:5051 .. code-block:: bash5253 eval "$(_FOO_BAR_COMPLETE=bash_source foo-bar)"5455 .. group-tab:: Zsh5657 Add this to ``~/.zshrc``:5859 .. code-block:: zsh6061 eval "$(_FOO_BAR_COMPLETE=zsh_source foo-bar)"6263 .. group-tab:: Fish6465 Add this to ``~/.config/fish/completions/foo-bar.fish``:6667 .. code-block:: fish6869 _FOO_BAR_COMPLETE=fish_source foo-bar | source7071 This is the same file used for the activation script method72 below. For Fish it's probably always easier to use that method.7374Using ``eval`` means that the command is invoked and evaluated every75time a shell is started, which can delay shell responsiveness. To speed76it up, write the generated script to a file, then source that. You can77generate the files ahead of time and distribute them with your program78to save your users a step.7980.. tabs::8182 .. group-tab:: Bash8384 Save the script somewhere.8586 .. code-block:: bash8788 _FOO_BAR_COMPLETE=bash_source foo-bar > ~/.foo-bar-complete.bash8990 Source the file in ``~/.bashrc``.9192 .. code-block:: bash9394 . ~/.foo-bar-complete.bash9596 .. group-tab:: Zsh9798 Save the script somewhere.99100 .. code-block:: bash101102 _FOO_BAR_COMPLETE=zsh_source foo-bar > ~/.foo-bar-complete.zsh103104 Source the file in ``~/.zshrc``.105106 .. code-block:: bash107108 . ~/.foo-bar-complete.zsh109110 .. group-tab:: Fish111112 Save the script to ``~/.config/fish/completions/foo-bar.fish``:113114 .. code-block:: fish115116 _FOO_BAR_COMPLETE=fish_source foo-bar > ~/.config/fish/completions/foo-bar.fish117118After modifying the shell config, you need to start a new shell in order119for the changes to be loaded.120121122Custom Type Completion123----------------------124125When creating a custom :class:`~click.ParamType`, override its126:meth:`~click.ParamType.shell_complete` method to provide shell127completion for parameters with the type. The method must return a list128of :class:`~CompletionItem` objects. Besides the value, these objects129hold metadata that shell support might use. The built-in implementations130use ``type`` to indicate special handling for paths, and ``help`` for131shells that support showing a help string next to a suggestion.132133In this example, the type will suggest environment variables that start134with the incomplete value.135136.. code-block:: python137138 class EnvVarType(ParamType):139 name = "envvar"140141 def shell_complete(self, ctx, param, incomplete):142 return [143 CompletionItem(name)144 for name in os.environ if name.startswith(incomplete)145 ]146147 @click.command()148 @click.option("--ev", type=EnvVarType())149 def cli(ev):150 click.echo(os.environ[ev])151152153Overriding Value Completion154---------------------------155156Value completions for a parameter can be customized without a custom157type by providing a ``shell_complete`` function. The function is used158instead of any completion provided by the type. It is passed 3 keyword159arguments:160161- ``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.165166It must return a list of :class:`CompletionItem` objects, or as a167shortcut it can return a list of strings.168169In this example, the command will suggest environment variables that170start with the incomplete value.171172.. code-block:: python173174 def complete_env_vars(ctx, param, incomplete):175 return [k for k in os.environ if k.startswith(incomplete)]176177 @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]}")182183184Adding Support for a Shell185--------------------------186187Support can be added for shells that do not come built in. Be sure to188check PyPI to see if there's already a package that adds support for189your shell. This topic is very technical, you'll want to look at Click's190source to study the built-in implementations.191192Shell support is provided by subclasses of :class:`ShellComplete`193registered with :func:`add_completion_class`. When Click is invoked in194completion mode, it calls :meth:`~ShellComplete.source` to output the195completion script, or :meth:`~ShellComplete.complete` to output196completions. The base class provides default implementations that197require implementing some smaller parts.198199First, you'll need to figure out how your shell's completion system200works and write a script to integrate it with Click. It must invoke your201program with the environment variable ``_{FOO_BAR}_COMPLETE`` set to202``{shell}_complete`` and pass the complete args and incomplete value.203How it passes those values, and the format of the completion response204from Click is up to you.205206In your subclass, set :attr:`~ShellComplete.source_template` to the207completion script. The default implementation will perform ``%``208formatting with the following variables:209210- ``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.215216The example code is for a made up shell "My Shell" or "mysh" for short.217218.. code-block:: python219220 from click.shell_completion import add_completion_class221 from click.shell_completion import ShellComplete222223 _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 """230231 @add_completion_class232 class MyshComplete(ShellComplete):233 name = "mysh"234 source_template = _mysh_source235236Next, implement :meth:`~ShellComplete.get_completion_args`. This must237get, parse, and return the complete args and incomplete value from the238completion script. For example, for the Bash implementation the239``COMP_WORDS`` env var contains the command line args as a string, and240the ``COMP_CWORD`` env var contains the index of the incomplete arg. The241method must return a ``(args, incomplete)`` tuple.242243.. code-block:: python244245 import os246 from click.parser import split_arg_string247248 class MyshComplete(ShellComplete):249 ...250251 def get_completion_args(self):252 args = split_arg_string(os.environ["COMP_WORDS"])253254 if os.environ["COMP_PARTIAL"] == "1":255 incomplete = args.pop()256 return args, incomplete257258 return args, ""259260Finally, implement :meth:`~ShellComplete.format_completion`. This is261called to format each :class:`CompletionItem` into a string. For262example, the Bash implementation returns ``f"{item.type},{item.value}``263(it doesn't support help strings), and the Zsh implementation returns264each part separated by a newline, replacing empty help with a ``_``265placeholder. This format is entirely up to what you parse with your266completion script.267268The ``type`` value is usually ``plain``, but it can be another value269that the completion script can switch on. For example, ``file`` or270``dir`` can tell the shell to handle path completion, since the shell is271better at that than Click.272273.. code-block:: python274275 class MyshComplete(ShellComplete):276 ...277278 def format_completion(self, item):279 return f"{item.type}\t{item.value}"280281With those three things implemented, the new shell support is ready. In282case those weren't sufficient, there are more parts that can be283overridden, but that probably isn't necessary.284285The activation instructions will again depend on how your shell works.286Use the following to generate the completion script, then load it into287the shell somehow.288289.. code-block:: text290291 _FOO_BAR_COMPLETE=mysh_source foo-bar
modified:docs/utils.md+13 added-11 removed
87 unmodified lines
88writes to stdout and, if possible, through a pager.8990Example:9192```{eval-rst}92```python93@click.command()94def 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```9899If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time,100you can pass a generator (or generator function) instead of a string:101102```{eval-rst}101```python102def _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"107106@click.command()107def less():108 click.echo_via_pager(_generate_output())108 @click.command()109 def less():110 click.echo_via_pager(_generate_output())111```112113## Screen Clearing114
278 unmodified lines
modified:src/click/_termui_impl.py+13 added-5 removed
15 unmodified lines
16import typing as t17from gettext import gettext as _18from io import StringIO19from pathlib import Path20from shutil import which20from types import TracebackType2122from ._compat import _default_text_stdout23from ._compat import CYGWIN
209 unmodified lines
233 }234 ).rstrip()235236 def render_progress(self) -> None:238 import shutil239237 if self.hidden:238 return239240 if not self._is_atty:
5 unmodified lines
246247 buf = []248 # Update width in case the terminal has been resized249 if self.autowidth:250 import shutil251252 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 lines
419 """420 # Split the command into the invoked CLI and its parameters.421 if not cmd_parts:422 return False423424 import shutil425426 cmd = cmd_parts[0]427 cmd_params = cmd_parts[1:]428427 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 lines
511 """512 # Split the command into the invoked CLI and its parameters.513 if not cmd_parts:514 return False515516 import shutil517518 cmd = cmd_parts[0]519515 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 lines
577 if rv:578 return rv579 if WIN:580 return "notepad"581582 from shutil import which583584 for editor in "sensible-editor", "vim", "nano":585 if which(editor) is not None:586 return editor587 return "vi"
260 unmodified lines
added:src/click/_utils.py+36 added
1from __future__ import annotations23import enum4import typing as t567class Sentinel(enum.Enum):8 """Enum used to define sentinel values.910 .. seealso::1112 `PEP 661 - Sentinel Values <https://peps.python.org/pep-0661/>`_.13 """1415 UNSET = object()16 FLAG_NEEDS_VALUE = object()1718 def __repr__(self) -> str:19 return f"{self.__class__.__name__}.{self.name}"202122UNSET = Sentinel.UNSET23"""Sentinel used to indicate that a value is not set."""2425FLAG_NEEDS_VALUE = Sentinel.FLAG_NEEDS_VALUE26"""Sentinel used to indicate an option was passed as a flag without a27value but is not a flag option.2829``Option.consume_value`` uses this to prompt or use the ``flag_value``.30"""3132T_UNSET = t.Literal[UNSET] # type: ignore[valid-type]33"""Type hint for the :data:`UNSET` sentinel value."""3435T_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 lines
18from itertools import repeat19from types import TracebackType2021from . import types22from ._utils import FLAG_NEEDS_VALUE23from ._utils import UNSET24from .exceptions import Abort25from .exceptions import BadParameter26from .exceptions import ClickException27from .exceptions import Exit
3 unmodified lines
31from .formatting import HelpFormatter32from .formatting import join_options33from .globals import pop_context34from .globals import push_context33from .parser import _flag_needs_value35from .parser import _OptionParser36from .parser import _split_opt37from .termui import confirm38from .termui import prompt
443 unmodified lines
482 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()492493 return exit_result494495 @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 lines
617 """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)622623 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`632633 :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()638639 return exit_result640641 @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 by
60 unmodified lines
705 .. 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)710711 if call and callable(value):712 return value()713714 return value715696 return None716 return UNSET717718 def fail(self, message: str) -> t.NoReturn:719 """Aborts the execution of the program with a specific error720 message.
492 unmodified lines
1213 parser = self.make_parser(ctx)1214 opts, args, param_order = parser.parse_args(args=args)12151216 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)12181219 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:1220 ctx.fail(1221 ngettext(
812 unmodified lines
2034 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 of
53 unmodified lines
2098 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 lines
2157 f"'nargs' must be {self.type.arity} (or None) for"2158 f" type {self.type!r}, but it was {nargs}."2159 )21602130 # Skip no default or callable default.2131 check_default = default if not callable(default) else None21322133 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 None21422143 # 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."21552156 raise ValueError(message) from None21572158 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 )21632161 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 lines
21712172 Use :meth:`click.Context.to_info_dict` to traverse the entire2173 CLI structure.21742175 .. versionchanged:: 8.3.02176 Returns ``None`` for the :attr:`default` if it was not set.21772178 .. versionadded:: 8.02179 """2180 return {2181 "name": self.name,
3 unmodified lines
2185 "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 }21952196 def __repr__(self) -> str:
59 unmodified lines
2256 Added the ``call`` parameter.2257 """2258 value = ctx.lookup_default(self.name, call=False) # type: ignore22592257 if value is None:2260 if value is UNSET:2261 value = self.default22622263 if call and callable(value):2264 value = value()
5 unmodified lines
22702271 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.22752274 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.22792278 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.22812282 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 )22932294 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.ENVIRONMENT22992300 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_MAP23052306 if value is UNSET:2307 default_value = self.get_default(ctx)2308 if default_value is not UNSET:2309 value = default_value2310 source = ParameterSource.DEFAULT23112312 return value, source23132314 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 value23232324 def check_iter(value: t.Any) -> cabc.Iterator[t.Any]:2325 try:2326 return _check_iter(value)
4 unmodified lines
2331 raise BadParameter(2332 _("Value must be an iterable."), ctx=ctx, param=self2333 ) from None23342335 # Define the conversion function based on nargs and type.23362337 if self.nargs == 1 or self.type.is_composite:23382339 def convert(value: t.Any) -> t.Any:2340 return self.type(value, param=self, ctx=ctx)
26 unmodified lines
23672368 return convert(value)23692370 def value_is_missing(self, value: t.Any) -> bool:2371 """A value is considered missing if:23722373 - 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).23772378 :meta private:2379 """2340 if value is None:2380 if value is UNSET:2381 return True23822383 if (self.nargs != 1 or self.multiple) and value == ():2384 return True23852386 return False23872388 def process_value(self, ctx: Context, value: t.Any) -> t.Any:2389 """Process the value of this parameter:23902391 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.23982399 :meta private:2400 """2401 value = self.type_cast_value(ctx, value)24022403 if self.required and self.value_is_missing(value):2404 raise MissingParameter(ctx=ctx, param=self)24052406 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)24122413 return value24142415 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.24182419 Environment variables values are `always returned as strings2420 <https://docs.python.org/3/library/os.html#os.environ>`_.24212422 This method returns ``None`` if:24232424 - 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).24282429 If :attr:`envvar` is setup with multiple environment variables,2430 then only the first non-empty value is returned.24312432 .. caution::24332434 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`.24372438 :meta private:2439 """2440 if not self.envvar:2441 return None24422443 if isinstance(self.envvar, str):2444 rv = os.environ.get(self.envvar)
3 unmodified lines
2448 else:2449 for envvar in self.envvar:2450 rv = os.environ.get(envvar)24512452 # 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.24572458 return None24592377 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.24622463 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``).24662467 :meta private:2468 """2469 rv = self.resolve_envvar_value(ctx)24702471 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)24732474 return rv24752476 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.24802481 Always process the value through the Parameter's :attr:`type`, wherever it2482 comes from.24832484 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).24872488 :meta private:2489 """2490 with augment_usage_errors(ctx, param=self):2491 value, source = self.consume_value(ctx, opts)24922493 ctx.set_parameter_source(self.name, source) # type: ignore24942495 # 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 lines
2510 extra_message=extra_message,2511 )2512 echo(style(message, fg="red"), err=True)25132413 ctx.set_parameter_source(self.name, source) # type: ignore24142514 # 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 = UNSET25242421 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 None25422423 if self.expose_value:2424 ctx.params[self.name] = value # type: ignore24252543 return value, args25442545 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:2546 pass
108 unmodified lines
2655 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 lines
2698 self.prompt_required = prompt_required2699 self.hide_input = hide_input2700 self.hidden = hidden27012585 # 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_required27092710 # 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 UNSET27252604 self.default: t.Any | t.Callable[[], t.Any]26052726 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 = ()27312732 # 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)27432614 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 True26192620 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)26252744 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_value27492750 # 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 = False27542755 # 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_value27632764 # 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 = None27702632 # 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 = 027782779 self.allow_from_autoenv = allow_from_autoenv2780 self.help = help
7 unmodified lines
27882789 if self.nargs == -1:2790 raise TypeError("nargs=-1 is not supported for options.")27912653 if self.prompt and self.is_flag and not self.is_bool_flag:2654 raise TypeError("'prompt' is not valid for non-boolean flag.")26552792 if not self.is_bool_flag and self.secondary_opts:2793 raise TypeError("Secondary flag is not valid for non-boolean flag.")27942795 if self.is_bool_flag and self.hide_input and self.prompt is not None:
8 unmodified lines
2804 if self.is_flag:2805 raise TypeError("'count' is not valid with 'is_flag'.")28062807 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_dict28252826 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 result28312832 def _parse_decls(
176 unmodified lines
3009 show_default = self.show_default3010 elif ctx.show_default is not None:3011 show_default = ctx.show_default30122870 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 lines
3051 extra["required"] = "required"30523053 return extra30542910 @t.overload2911 def get_default(2912 self, ctx: Context, call: t.Literal[True] = True2913 ) -> t.Any | None: ...29142915 @t.overload2916 def get_default(2917 self, ctx: Context, call: bool = ...2918 ) -> t.Any | t.Callable[[], t.Any] | None: ...29192920 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).default29312932 return None29332934 return super().get_default(ctx, call=call)29353055 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 None30622944 # 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)30662947 # 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)30853086 # 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 behavior
2 unmodified lines
3090 prompt_kwargs["show_default"] = self.show_default30913092 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 line
3102 **prompt_kwargs,3103 )31043105 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.31122973 Returns the value of the environment variable if it exists, or ``None``2974 if it does not.29752976 .. caution::29772978 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)31163117 if rv is not None:
11 unmodified lines
3129 return rv31303131 return None31323000 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.31363137 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.31403141 This method also takes care of repeated options (i.e. options with3142 :attr:`multiple` set to ``True``).31433144 :meta private:3145 """3146 rv = self.resolve_envvar_value(ctx)31473148 # Absent environment variable or an empty string is interpreted as unset.3149 if rv is None:3150 return None31513152 # 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 lines
31743175 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).31813182 Additionally, this method handles flag option that are activated without a3183 value, in which case the :attr:`flag_value` is returned.31843185 :meta private:3186 """3187 value, source = super().consume_value(ctx, opts)31883035 # 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.COMMANDLINE32003046 # 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_value32103211 # 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.COMMANDLINE32223065 # 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 line
3235 source = ParameterSource.PROMPT32363237 return value, source32383239 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)324632473248class 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 lines
3260 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 = False32733274 if "multiple" in attrs:3275 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.")32763277 super().__init__(param_decls, required=required, **attrs)32783106 if __debug__:3107 if self.default is not None and self.nargs == -1:3108 raise TypeError("'default' is not supported for nargs=-1.")31093279 @property3280 def human_readable_name(self) -> str:3281 if self.metavar is not None:3282 return self.metavar
65 unmodified lines
modified:src/click/formatting.py+2 added-2 removed
117 unmodified lines
118 indent_increment: int = 2,119 width: int | None = None,120 max_width: int | None = None,121 ) -> None:122 import shutil123122 self.indent_increment = indent_increment123 if max_width is None:124 max_width = 80125 if width is None:126 import shutil127128 width = FORCED_WIDTH129 if width is None:130 width = max(min(shutil.get_terminal_size().columns, max_width) - 2, 50)131 self.width = width
170 unmodified lines
modified:src/click/parser.py+24 added-24 removed
28 unmodified lines
29from collections import deque30from gettext import gettext as _31from gettext import ngettext3233from ._utils import FLAG_NEEDS_VALUE34from ._utils import UNSET35from .exceptions import BadArgumentUsage36from .exceptions import BadOptionUsage37from .exceptions import NoSuchOption38from .exceptions import UsageError3940if 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 CoreParameter4748V = t.TypeVar("V")4946# 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()505151def _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 lines
5758 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.6062 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 = None6769 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 UNSET7677 while nargs_spec:78 nargs = _fetch(nargs_spec)7980 if nargs is None:81 continue8283 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)]8788 # If we're reversed, we're pulling in the arguments in reverse,
6 unmodified lines
95 if spos is not None:96 raise TypeError("Cannot have two nargs < 0")9798 spos = len(rv)100 rv.append(None)99 rv.append(UNSET)100101 # 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 lines
185 self.obj = obj186187 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 )203205 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 = UNSET207208 state.opts[self.dest] = value # type: ignore209 state.order.append(self.obj)210
170 unmodified lines
381 opt, _("Option {name!r} does not take a value.").format(name=opt)382 )383384 else:387 value = None385 value = UNSET386387 option.process(value, state)388389 def _match_short_opt(self, arg: str, state: _ParsingState) -> None:
21 unmodified lines
411412 value = self._get_value_from_state(opt, option, state)413414 else:417 value = None415 value = UNSET416417 option.process(value, state)418419 if stop:
7 unmodified lines
427 state.largs.append(f"{prefix}{''.join(unknown_options)}")428429 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.nargs433434 value: str | cabc.Sequence[str] | T_FLAG_NEEDS_VALUE435436 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 lines
456 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 lines
modified:src/click/shell_completion.py+3 added
403 unmodified lines
404405 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:]411412 # Fish stores the partial word in both COMP_WORDS and413 # COMP_CWORD, remove it from complete args.
139 unmodified lines
553 break554555 if _start_of_option(ctx, arg):556 last_option = arg557 break558559 return last_option is not None and last_option in param.opts560561
106 unmodified lines
modified:src/click/testing.py+10 added-10 removed
3 unmodified lines
4import contextlib5import io6import os7import shlex8import shutil8import sys9import tempfile10import typing as t11from types import TracebackType
114 unmodified lines
126 @property127 def mode(self) -> str:128 return self._mode129131 def __next__(self) -> str: # type: ignore132 try:133 line = super().__next__()134 except StopIteration as e:135 raise EOFError() from e136 return line130138131def make_input_stream(132 input: str | bytes | t.IO[t.Any] | None, charset: str133) -> t.BinaryIO:134 # Is already an input stream.
216 unmodified lines
351352 @_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 val362363 @_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 e371372 @_pause_echo(echo_input) # type: ignore373 def _getchar(echo: bool) -> str:374 char = sys.stdin.read(1)
193 unmodified lines
568 finally:569 os.chdir(cwd)570571 if temp_dir is None:572 import shutil573574 try:575 shutil.rmtree(dt)576 except OSError:577 pass
modified:tests/test_arguments.py+150 added-30 removed
2 unmodified lines
34import pytest56import click7from click._utils import UNSET8910def test_nargs_star(runner):11 @click.command()
7 unmodified lines
19 assert not result.exception20 assert result.output.splitlines() == ["src=foo.txt|bar.txt", "dst=dir"]212222def test_argument_unbounded_nargs_cant_have_default(runner):23 with pytest.raises(TypeError, match="nargs=-1"):2425 @click.command()26 @click.argument("src", nargs=-1, default=["42"])27 def copy(src):28 pass293023def test_nargs_tup(runner):24 @click.command()25 @click.argument("name", nargs=1)26 @click.argument("point", nargs=2, type=click.INT)
27 unmodified lines
54 assert result.exception is None55 assert result.output.splitlines() == ["name=peter id=1"]565758def test_nargs_mismatch_with_tuple_type():59 with pytest.raises(ValueError, match="nargs.*must be 2.*but it was 3"):6061 @click.command()62 @click.argument("test", type=(str, int), nargs=3)63 def cli(_):64 pass656667def test_nargs_err(runner):68 @click.command()69 @click.argument("x")70 def copy(x):
94 unmodified lines
165166 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.stderr171172173@pytest.mark.parametrize(174 ("nargs", "value", "expect"),
69 unmodified lines
244 assert result.exit_code == 2245 assert "Missing argument 'ARG'." in result.output246247245def 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)272def 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)276277 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"281251 assert str(excinfo.value) == "Missing parameter: a"282 else:283 value = argument.process_value(ctx, value)284 assert value == processed_value285286287def test_implicit_non_required(runner):288 @click.command()
85 unmodified lines
374 result = runner.invoke(cmd, ["a", "b", "c", "d", "e", "f"])375 assert result.output.splitlines() == ["('a', 'b', 'c')", "d", "('e', 'f')"]376377345def 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)401def 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)406352 result = runner.invoke(cmd, [])353 assert result.output.strip() == "3"407 result = runner.invoke(cmd, args)408 assert result.output == repr(expected)409355 result = runner.invoke(cmd, ["3", "4"])356 assert result.output.strip() == "7"410358 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)477def test_bad_defaults_for_nargs(runner, default, message):478 """Some defaults are not valid when nargs is set."""479480 @click.command()481 @click.argument("a", nargs=2, type=int, default=default)482 def cmd(a):483 click.echo(repr(a))484485 result = runner.invoke(cmd, [])486 assert message in result.stderr487488489def test_multiple_param_decls_not_allowed(runner):490 with pytest.raises(TypeError):491492 @click.command()
6 unmodified lines
499 with pytest.raises(TypeError, match="multiple"):500 click.Argument(["a"], multiple=True)501502377@pytest.mark.parametrize("value", [(), ("a",), ("a", "b", "c")])378def test_nargs_bad_default(runner, value):379 with pytest.raises(ValueError, match="nargs=2"):380 click.Argument(["a"], nargs=2, default=value)381382503def test_subcommand_help(runner):504 @click.group()505 @click.argument("name")506 @click.argument("val")
75 unmodified lines
modified:tests/test_basic.py+86 added-9 removed
5 unmodified lines
67import pytest89import click10from click._utils import UNSET111213def test_basic_functionality(runner):14 @click.command()
190 unmodified lines
205 else:206 assert result.exception is None207208208@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)212def test_boolean_switch(runner, default, args, expect):226def test_boolean_switch(runner, args, default, expect):227 @click.command()228 @click.option("--on/--off", default=default)229 def cli(on):230 return on231218 if expect is None:219 expect = default220232 result = runner.invoke(cli, args, standalone_mode=False)233 assert result.return_value is expect234235
3 unmodified lines
239 (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)249def test_boolean_flag(runner, default, args, expect):250 @click.command()
24 unmodified lines
275 result = runner.invoke(cli, ["--flag", value.title()])276 assert result.output == expect277278279@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)314def test_flag_value_dual_options(runner, default, args, expected):315 """Check how default is processed when options compete for the same variable name.316317 Covers the regression reported in318 https://github.com/pallets/click/issues/3024#issuecomment-3146199461319 """320321 @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)326327 result = runner.invoke(cli, args)328 assert result.output == repr(expected)329330331def test_file_option(runner):332 @click.command()333 @click.option("--file", type=click.File("w"))334 def input(file):
206 unmodified lines
541 "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)546547 result = runner.invoke(cli, ["not-none"])548 assert not result.exception482 assert result.output == "not-none\n"549 assert result.output == repr("not-none")550484 # None is not yet supported.551 result = runner.invoke(cli, ["none"])552 assert not result.exception553 assert result.output == repr(None)554555 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 )561562 result = runner.invoke(cli, ["--help"])563 assert result.output.startswith("Usage: cli [OPTIONS] {not-none|none}\n")564565566def test_datetime_option_default(runner):567 @click.command()568 @click.option("--start_date", type=click.DateTime())569 def cli(start_date):
166 unmodified lines
modified:tests/test_chain.py+2 added-2 removed
161 unmodified lines
162163 return processor164165 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() == expect168169170def test_args_and_chain(runner):171 @click.group(chain=True)
74 unmodified lines
modified:tests/test_context.py+127 added
1import logging2from contextlib import AbstractContextManager3from contextlib import contextmanager4from types import TracebackType56import pytest78import click
415 unmodified lines
424425 assert rv == [0]426427428def test_with_resource_exception() -> None:429 class TestContext(AbstractContextManager[list[int]]):430 _handle_exception: bool431 _base_val: int432 val: list[int]433434 def __init__(self, base_val: int = 1, *, handle_exception: bool = True) -> None:435 self._handle_exception = handle_exception436 self._base_val = base_val437438 def __enter__(self) -> list[int]:439 self.val = [self._base_val]440 return self.val441442 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 None451452 self.val[0] = self._base_val + 1453 return self._handle_exception454455 class TestException(Exception):456 pass457458 ctx = click.Context(click.Command("test"))459460 base_val = 1461462 with ctx.scope():463 rv = ctx.with_resource(TestContext(base_val=base_val))464 assert rv[0] == base_val465466 assert rv == [base_val - 1]467468 with ctx.scope():469 rv = ctx.with_resource(TestContext(base_val=base_val))470 raise TestException()471472 assert rv == [base_val + 1]473474 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()480481482def test_with_resource_nested_exception() -> None:483 class TestContext(AbstractContextManager[list[int]]):484 _handle_exception: bool485 _base_val: int486 val: list[int]487488 def __init__(self, base_val: int = 1, *, handle_exception: bool = True) -> None:489 self._handle_exception = handle_exception490 self._base_val = base_val491492 def __enter__(self) -> list[int]:493 self.val = [self._base_val]494 return self.val495496 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 None505506 self.val[0] = self._base_val + 1507 return self._handle_exception508509 class TestException(Exception):510 pass511512 ctx = click.Context(click.Command("test"))513 base_val = 1514 base_val_nested = 11515516 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_nested521522 assert rv == [base_val - 1]523 assert rv_nested == [base_val_nested - 1]524525 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()529530 # 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]534535 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()541542 assert rv_nested == [base_val_nested + 1]543 assert rv == [base_val + 1]544545 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()551552553def 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 lines
modified:tests/test_imports.py-1 removed
41 unmodified lines
42 "io",43 "itertools",44 "os",45 "re",46 "shutil",46 "stat",47 "struct",48 "sys",49 "threading",
21 unmodified lines
modified:tests/test_options.py+1012 added-219 removed
1import enum2import os3import re4import sys5import tempfile6from contextlib import nullcontext7from typing import Literal89if sys.version_info < (3, 11):10 enum.StrEnum = enum.Enum # type: ignore[assignment]1112import pytest1314import click15from click import Option16from click import UNPROCESSED17from click._utils import UNSET181920def test_prefixes(runner):21 @click.command()
67 unmodified lines
89 click.Option(["--a"], prompt=True, deprecated=True)909192def 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."):9495 @click.command()96 @click.option("--foo", nargs=-1)97 def cli(foo):
76 unmodified lines
174 assert "Error: Missing option '-m' / '--message'." in result.output175176177@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)187def test_init_good_default_list(runner, multiple, nargs, default):188 click.Option(["-a"], multiple=multiple, nargs=nargs, default=default)224def 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)229230 result = runner.invoke(cmd)231 assert result.output == repr(expected)232233234@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)200def test_init_bad_default_list(runner, multiple, nargs, default):201 type = (str, str) if nargs == 2 else None360def 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 None367203 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 ):373374 @click.command()375 @click.option("-a", multiple=multiple, nargs=nargs, default=default)376 def cmd(a):377 click.echo(repr(a))378379 result = runner.invoke(cmd)380 assert message in result.stderr381382383@pytest.mark.parametrize("env_key", ["MYPATH", "AUTO_MYPATH"])384def test_empty_envvar(runner, env_key):385 @click.command()386 @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH")
41 unmodified lines
428 assert result.output == "foo|bar\n"429430431@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 lines
445 ("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 lines
472 ("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)309def test_boolean_envvar_normalization(runner, name, value, expected):493def 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 None496497 @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)501315 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)505506507@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)332def test_boolean_envvar_bad_values(runner, name, value):532def 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)537338 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.output
285 unmodified lines
828 result = runner.invoke(cmd, ["-whatever=23"])829 assert result.output == "23\n"830831632def 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)851def test_required_option(value, expect_missing, processed_value):852 ctx = click.Context(click.Command(""))853 argument = click.Option(["-a"], required=True)854855 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"859638 assert str(excinfo.value) == "Missing parameter: a"860 else:861 value = argument.process_value(ctx, value)862 assert value == processed_value863864865def test_missing_required_flag(runner):866 cli = click.Command(
33 unmodified lines
900 result = runner.invoke(cli)901 assert result.exit_code == 2902 assert "Error: Missing option '--foo' (env var: 'bar')." in result.output903904 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.output910911912def 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 lines
1323 assert param.type is click.INT132413251326@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)1183def test_flag_value_and_default(runner, opt_params, pass_flag, expected):1425def 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)14301189 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)143314341435@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)1202def test_invalid_flag_definition(runner, opts):1444def 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)14491208 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 )145514561457@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)1493def 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.14961497 Reproduction of the issue reported in1498 https://github.com/pallets/click/pull/3030#discussion_r22715718191499 """15001501 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}"15041505 @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)15101511 result = runner.invoke(main, args)1512 assert result.output == f"Callback value: {expected!r}"1513 assert result.exit_code == 0151415151516@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)1246def test_envvar_flag_value(runner, flag_value, envvar_value, expected):1603def test_envvar_string_flag_value(runner, flag_value, envvar_value, expected):1604 """Ensure that flag_value is recognized by the envvar."""16051606 @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)16101611 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)161416151616@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)1276def test_bool_flag_auto_detection(option, expected):1277 assert option.is_bool_flag is expected1633def 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_flag163916401641@pytest.mark.parametrize(1642 ("kwargs", "message"),
23 unmodified lines
1666 assert result.exit_code == 0166716681669class HashType(enum.Enum):1309 MD5 = enum.auto()1310 SHA1 = enum.auto()1670 MD5 = "MD5"1671 SHA1 = "SHA1"1672 SHA256 = "SHA-256"167316741675class Number(enum.IntEnum):1676 ONE = enum.auto()1677 TWO = enum.auto()167816791680class 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"168416851686class Color(enum.Flag):1687 RED = enum.auto()
7 unmodified lines
1695 BLUE = enum.auto()169616971698@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)1350def test_usage_show_choices(runner, choices, metavars):1351 """When show_choices=False is set, the --help output1352 should print choice metavars instead of values.1713def test_choice_usage_rendering(runner, choices, metavar):1714 """BY default ``--help`` prints choice's values in the usage message.17151716 But ``show_choices=False`` makes ``--help`` prints choice's METAVAR instead of1717 values.17181719 Also check that usage error message always suggests the actual values.1720 """17211722 @click.command()1723 @click.option("-g", type=click.Choice(choices))1724 def cli_with_choices(g):1725 pass17261727 @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 pass17311369 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 )17351736 # 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 == 017411742 # 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 == 017471748 # 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 == 2175717581759@pytest.mark.parametrize(1760 ("choices", "default", "default_string"),1761 [1762 (["foo", "bar"], "bar", "bar"),
10 unmodified lines
1773 ([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)1797def test_choice_default_rendering(runner, choices, default, default_string):1798 @click.command()
35 unmodified lines
1834 pass18351836 with pytest.warns(UserWarning):1837 runner.invoke(cli, [])183818391840OBJECT_SENTINEL = object()1841"""An object-based sentinel value."""184218431844class EnumSentinel(enum.Enum):1845 FALSY_SENTINEL = object()18461847 def __bool__(self) -> Literal[False]:1848 """Force the sentinel to be falsy to make sure it is not caught by Click1849 internal implementation.18501851 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 False185618571858# 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)1924def 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.19281929 A reproduction of1930 https://github.com/pallets/click/issues/3024#issuecomment-31465113561931 """19321933 class ConfigParamType(click.ParamType):1934 """A custom type that accepts a file path or a sentinel value."""19351936 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 )19431944 @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)19491950 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]19551956 result = runner.invoke(main, args)19571958 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 )196419651966class EngineType(enum.Enum):1967 OSS = enum.auto()1968 PRO = enum.auto()1969 MAX = enum.auto()197019711972class Class1:1973 pass197419751976class Class2:1977 pass197819791980@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)2064def test_custom_type_flag_value_standalone_option(runner, opt_params, args, expected):2065 """Test how the type and flag_value influence the returned value.20662067 Cover cases reported in:2068 https://github.com/pallets/click/issues/3024#issuecomment-31464807142069 https://github.com/pallets/click/issues/2012#issuecomment-8924370602070 """20712072 @click.command()2073 @click.option("--pro", **opt_params)2074 def scan(pro):2075 click.echo(repr(pro), nl=False)20762077 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)208220832084@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)2192def 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.21972198 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 """22032204 @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)22092210 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)221522162217def test_custom_type_frozenset_flag_value(runner):2218 """Check that frozenset is correctly handled as a type, a flag value and a default.22192220 Reproduces https://github.com/pallets/click/issues/26102221 """22222223 @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)22342235 result = runner.invoke(rcli)2236 assert result.stdout == "frozenset({'git'})"2237 assert result.exit_code == 022382239 result = runner.invoke(rcli, ["--without-scm-ignore-files"])2240 assert result.stdout == "frozenset()"2241 assert result.exit_code == 0
modified:tests/test_shell_completion.py+14 added
218 unmodified lines
219 # flag option doesn't take value, use choice argument220 assert _get_words(cli, ["--on"], "a") == ["a1", "a2"]221222223def 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"]234235236def test_option_custom():237 def custom(ctx, param, incomplete):238 return [incomplete.upper()]239
118 unmodified lines
358 ("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")366def test_full_complete(runner, shell, env, expect):
195 unmodified lines
modified:tests/test_termui.py+218 added
4 unmodified lines
5import pytest67import click._termui_impl8from click._compat import WIN9from click.exceptions import BadParameter10from click.exceptions import MissingParameter111213class FakeClock:14 def __init__(self):
471 unmodified lines
486 # 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.output490491492REPEAT = object()493"""Sentinel value to indicate that the prompt is expected to be repeated.494495I.e. the value provided by the user is not satisfactory and need to be re-prompted.496"""497498INVALID = object()499"""Sentinel value to indicate that the prompt is expected to be invalid.500501On invalid input, Click will output an error message and re-prompt the user.502"""503504BOOLEAN_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]567568FLAG_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]647648649@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)656def 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.661662 Covers concerns raised in issue https://github.com/pallets/click/issues/1992.663 """664665 @click.command()666 @click.option(opt_decls, **opt_params)667 def cli(flag):668 click.echo(repr(flag))669670 invoke_options = {"standalone_mode": False}671 if input is not None:672 assert isinstance(input, str)673 invoke_options["input"] = f"{input}\n"674675 result = runner.invoke(cli, args, **invoke_options)676677 if expected in (MissingParameter, BadParameter):678 assert isinstance(result.exception, expected)679 assert not result.output680 assert result.exit_code == 1681682 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: "688689 # Add the user input to the expected output.690 assert isinstance(input, str)691 expected_output += f"{expected_prompt}{input}\n"692693 if expected is INVALID:694 expected_output += "Error: invalid input\n"695696 # The prompt is expected to be repeated.697 if expected in (REPEAT, INVALID):698 expected_output += expected_prompt699700 if expected not in (REPEAT, INVALID):701 expected_output += f"{expected!r}\n"702703 assert result.output == expected_output704 assert not result.stderr705 assert result.exit_code == 0 if expected not in (REPEAT, INVALID) else 1
modified:tests/test_utils.py+51 added
3 unmodified lines
4import subprocess5import sys6from collections import namedtuple7from contextlib import nullcontext8from decimal import Decimal9from fractions import Fraction10from functools import partial11from io import StringIO12from pathlib import Path13from tempfile import tempdir
3 unmodified lines
1718import click._termui_impl19import click.utils20from click._compat import WIN21from click._utils import UNSET222324def test_unset_sentinel():25 value = UNSET2627 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 True3334 # 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 )6465 for real_value in real_values:66 assert value != real_value67 assert value is not real_value6869 assert value not in real_values707172def test_echo(runner):73 with runner.isolation() as outstreams:74 click.echo("\N{SNOWMAN}")75 click.echo(b"\x44\x44")
671 unmodified lines
modified:CHANGES.rst+33 added-5 removed
1.. currentmodule:: click23Version 8.3.04--------------56Released 2025-09-1578- **Improved flag option handling**: Reworked the relationship between ``flag_value``9 and ``default`` parameters for better consistency:1011 * 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`2829Version 8.2.230-------------316Unreleased32Released 2025-07-31338- 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`4849Version 8.2.150-------------51
1242 unmodified lines
modified:pyproject.toml+1 added-1 removed
1[project]2name = "click"3version = "8.2.1"3version = "8.3.0"4description = "Composable command line interface toolkit"5readme = "README.md"6license = "BSD-3-Clause"7license-files = ["LICENSE.txt"]
201 unmodified lines
modified:uv.lock+1 added-1 removed
137 unmodified lines
138]139140[[package]]141name = "click"142version = "8.2.1"142version = "8.3.0"143source = { editable = "." }144dependencies = [145 { name = "colorama", marker = "sys_platform == 'win32'" },146]
1076 unmodified lines