Merge branch 'stable' into rstTomyst
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Jaron Rosenau · committed by GitHub · parents 06e12da, 701b313 · Browse files · 23 files·+1052 added−437 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
23 files+1052 added−437 removed
- tests:+493 added−57 removed
- other:+559 added−380 removed
Provenance
- Commit
6ce5591- Tree
5eafa41- Author
Jaron Rosenau <jaron@rosenau.info>- Committer
GitHub <noreply@github.com>- Parent 1
06e12da- Parent 2
701b313
23 files changed+1052 added−437 removed
added:docs/contrib.md+45 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445(contrib)=
# click-contrib
As the user number of Click grows, more and more major feature requests aremade. To users, it may seem reasonable to include those features with Click;however, many of them are experimental or aren't practical to supportgenerically. Maintainers have to choose what is reasonable to maintain in Clickcore.
The [click-contrib](https://github.com/click-contrib/) GitHub organization exists as a place to collect third-partypackages that extend Click's features. It is also meant to ease the effort ofsearching for such extensions.
Please note that the quality and stability of those packages may be differentfrom Click itself. While published under a common organization, they are stillseparate from Click and the Pallets maintainers.
## Third-party projects
Other projects that extend Click's features are available outside the[click-contrib](https://github.com/click-contrib/) organization.
Some of the most popular and actively maintained are listed below:
| Project | Description | Popularity | Activity ||---------------------------------------------------------|--------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------|| [Typer](https://github.com/fastapi/typer) | Use Python type hints to create CLI apps. |  |  || [rich-click](https://github.com/ewels/rich-click) | Format help output with Rich. |  |  || [click-app](https://github.com/simonw/click-app) | Cookiecutter template for creating new CLIs. |  |  || [Cloup](https://github.com/janluke/cloup) | Adds option groups, constraints, command aliases, help themes, suggestions and more. |  |  || [Click Extra](https://github.com/kdeldycke/click-extra) | Cloup + colorful `--help`, `--config`, `--show-params`, `--verbosity` options, etc. |  |  |
```{note}To make it into the list above, a project:
- must be actively maintained (at least one commit in the last year)- must have a reasonable number of stars (at least 20)
If you have a project that meets these criteria, please open a pull requestto add it to the list.
If a project is no longer maintained or does not meet the criteria above,please open a pull request to remove it from the list.```deleted:docs/contrib.rst-58 removed
1-.. _contrib:2-3-=============4-click-contrib5-=============6-7-As the number of users of Click grows, more and more major feature requests are8-made. To users it may seem reasonable to include those features with Click;9-however, many of them are experimental or aren't practical to support10-generically. Maintainers have to choose what is reasonable to maintain in Click11-core.12-13-The click-contrib_ GitHub organization exists as a place to collect third-party14-packages that extend Click's features. It is also meant to ease the effort of15-searching for such extensions.16-17-Please note that the quality and stability of those packages may be different18-than Click itself. While published under a common organization, they are still19-separate from Click and the Pallets maintainers.20-21-22-Third-party projects23---------------------24-25-Other projects that extend Click's features are available outside of the26-click-contrib_ organization.27-28-Some of the most popular and actively maintained are listed below:29-30-========================================================== =========================================================================================== ================================================================================================= ======================================================================================================31-Project Description Popularity Activity32-========================================================== =========================================================================================== ================================================================================================= ======================================================================================================33-`Typer <https://github.com/fastapi/typer>`_ Use Python type hints to create CLI apps. .. image:: https://img.shields.io/github/stars/fastapi/typer?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/fastapi/typer?label=%20&style=flat-square34- :alt: GitHub stars :alt: Last commit35-`rich-click <https://github.com/ewels/rich-click>`_ Format help outputwith Rich. .. image:: https://img.shields.io/github/stars/ewels/rich-click?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/ewels/rich-click?label=%20&style=flat-square36- :alt: GitHub stars :alt: Last commit37-`click-app <https://github.com/simonw/click-app>`_ Cookiecutter template for creating new CLIs. .. image:: https://img.shields.io/github/stars/simonw/click-app?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/simonw/click-app?label=%20&style=flat-square38- :alt: GitHub stars :alt: Last commit39-`Cloup <https://github.com/janluke/cloup>`_ Adds option groups, constraints, command aliases, help themes, suggestions and more. .. image:: https://img.shields.io/github/stars/janluke/cloup?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/janluke/cloup?label=%20&style=flat-square40- :alt: GitHub stars :alt: Last commit41-`Click Extra <https://github.com/kdeldycke/click-extra>`_ Cloup + colorful ``--help``, ``--config``, ``--show-params``, ``--verbosity`` options, etc. .. image:: https://img.shields.io/github/stars/kdeldycke/click-extra?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/kdeldycke/click-extra?label=%20&style=flat-square42- :alt: GitHub stars :alt: Last commit43-========================================================== =========================================================================================== ================================================================================================= ======================================================================================================44-45-.. note::46-47- To make it into the list above, a project:48-49- - must be actively maintained (at least one commit in the last year)50- - must have a reasonable number of stars (at least 20)51-52- If you have a project that meets these criteria, please open a pull request53- to add it to the list.54-55- If a project is no longer maintained or does not meet the criteria above,56- please open a pull request to remove it from the list.57-58-.. _click-contrib: https://github.com/click-contrib/added:docs/documentation.md+277 added
1+# Help Pages2+3+```{currentmodule} click4+```5+6+Click makes it very easy to document your command line tools. For most things Click automatically generates help pages for you. By design the text is customizable, but the layout is not.7+8+## Help Texts9+10+Commands and options accept help arguments. For commands, the docstring of the function is automatically used if provided.11+12+Simple example:13+14+```{eval-rst}15+.. click:example::16+17+ @click.command()18+ @click.argument('name')19+ @click.option('--count', default=1, help='number of greetings')20+ def hello(name: str, count: int):21+ """This script prints hello and a name one or more times."""22+ for x in range(count):23+ if name:24+ click.echo(f"Hello {name}!")25+ else:26+ click.echo("Hello!")27+28+.. click:run::29+ invoke(hello, args=['--help'])30+```31+32+## Command Short Help33+34+For subcommands, a short help snippet is generated. By default, it's the first sentence of the docstring. If too long, then it will ellipsize what cannot be fit on a single line with `...`. The short help snippet can also be overridden with `short_help`:35+36+```{eval-rst}37+.. click:example::38+39+ import click40+41+ @click.group()42+ def cli():43+ """A simple command line tool."""44+45+ @cli.command('init', short_help='init the repo')46+ def init():47+ """Initializes the repository."""48+49+.. click:run::50+ invoke(cli, args=['--help'])51+```52+53+## Command Epilog Help54+55+The help epilog is printed at the end of the help and is useful for showing example command usages or referencing additional help resources.56+57+```{eval-rst}58+.. click:example::59+60+ import click61+62+ @click.command(63+ epilog='See https://example.com for more details',64+ )65+ def init():66+ """Initializes the repository."""67+68+.. click:run::69+ invoke(init, args=['--help'])70+```71+72+(documenting-arguments)=73+74+## Documenting Arguments75+76+{class}`click.argument` does not take a `help` parameter. This follows the Unix Command Line Tools convention of using arguments only for necessary things and documenting them in the command help text77+by name. This should then be done via the docstring.78+79+A brief example:80+81+```{eval-rst}82+.. click:example::83+84+ @click.command()85+ @click.argument('filename')86+ def touch(filename):87+ """Print FILENAME."""88+ click.echo(filename)89+90+.. click:run::91+ invoke(touch, args=['--help'])92+```93+94+Or more explicitly:95+96+```{eval-rst}97+.. click:example::98+99+ @click.command()100+ @click.argument('filename')101+ def touch(filename):102+ """Print FILENAME.103+104+ FILENAME is the name of the file to check.105+ """106+ click.echo(filename)107+108+.. click:run::109+ invoke(touch, args=['--help'])110+```111+112+## Showing Defaults113+114+To control the appearance of defaults pass `show_default`.115+116+```{eval-rst}117+.. click:example::118+119+ @click.command()120+ @click.option('--n', default=1, show_default=False, help='number of dots')121+ def dots(n):122+ click.echo('.' * n)123+124+.. click:run::125+ invoke(dots, args=['--help'])126+```127+128+For single option boolean flags, the default remains hidden if the default value is False, even if show default is set to true.129+130+```{eval-rst}131+.. click:example::132+133+ @click.command()134+ @click.option('--n', default=1, show_default=True)135+ @click.option("--gr", is_flag=True, show_default=True, default=False, help="Greet the world.")136+ @click.option("--br", is_flag=True, show_default=True, default=True, help="Add a thematic break")137+ def dots(n, gr, br):138+ if gr:139+ click.echo('Hello world!')140+ click.echo('.' * n)141+ if br:142+ click.echo('-' * n)143+144+.. click:run::145+ invoke(dots, args=['--help'])146+```147+148+## Click's Wrapping Behavior149+150+Click's default wrapping ignores single new lines and rewraps the text based on the width of the terminal, to a maximum of 80 characters. In the example notice how the second grouping of three lines is rewrapped into a single paragraph.151+152+```{eval-rst}153+.. click:example::154+155+ import click156+157+ @click.command()158+ def cli():159+ """160+ This is a very long paragraph and as you161+ can see wrapped very early in the source text162+ but will be rewrapped to the terminal width in163+ the final output.164+165+ This is166+ a paragraph167+ that is compacted.168+ """169+170+.. click:run::171+ invoke(cli, args=['--help'])172+```173+174+## Escaping Click's Wrapping175+176+Sometimes Click's wrapping can be a problem, such as when showing code examples where new lines are significant. This behavior can be escaped on a per-paragraph basis by adding a line with only `\b` . The `\b` is removed from the rendered help text.177+178+Example:179+180+```{eval-rst}181+.. click:example::182+183+ import click184+185+ @click.command()186+ def cli():187+ """First paragraph.188+189+ \b190+ This is191+ a paragraph192+ without rewrapping.193+194+ And this is a paragraph195+ that will be rewrapped again.196+ """197+198+.. click:run::199+ invoke(cli, args=['--help'])200+```201+202+To change the rendering maximum width, pass `max_content_width` when calling the command.203+204+```bash205+cli(max_content_width=120)206+```207+208+## Truncating Help Texts209+210+Click gets {class}`Command` help text from the docstring. If you do not want to include part of the docstring, add the `\f` escape marker to have Click truncate the help text after the marker.211+212+Example:213+214+```{eval-rst}215+.. click:example::216+217+ import click218+219+ @click.command()220+ def cli():221+ """First paragraph.222+ \f223+224+ Words to not be included.225+ """226+227+.. click:run::228+ invoke(cli, args=['--help'])229+```230+231+(doc-meta-variables)=232+233+## Placeholder / Meta Variable234+235+The default placeholder variable ([meta variable](https://en.wikipedia.org/wiki/Metasyntactic_variable#IETF_Requests_for_Comments)) in the help pages is the parameter name in uppercase with underscores. This can be changed for Commands and Parameters with the `options_metavar` and `metavar` kwargs.236+237+```{eval-rst}238+.. click:example::239+240+ # This controls entry on the usage line.241+ @click.command(options_metavar='[[options]]')242+ @click.option('--count', default=1, help='number of greetings',243+ metavar='<int>')244+ @click.argument('name', metavar='<name>')245+ def hello(name: str, count: int) -> None:246+ """This script prints 'hello <name>' a total of <count> times."""247+ for x in range(count):248+ click.echo(f"Hello {name}!")249+250+# Example usage:251+252+.. click:run::253+ invoke(hello, args=['--help'])254+255+```256+257+## Help Parameter Customization258+259+Help parameters are automatically added by Click for any command. The default is `--help` but can be overridden by the context setting {attr}`~Context.help_option_names`. Click also performs automatic conflict resolution on the default help parameter, so if a command itself implements a parameter named `help` then the default help will not be run.260+261+This example changes the default parameters to `-h` and `--help`262+instead of just `--help`:263+264+```{eval-rst}265+.. click:example::266+267+ import click268+269+ CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])270+271+ @click.command(context_settings=CONTEXT_SETTINGS)272+ def cli():273+ pass274+275+.. click:run::276+ invoke(cli, ['-h'])277+```deleted:docs/documentation.rst-268 removed
1-Help Pages2-===================3-4-.. currentmodule:: click5-6-Click makes it very easy to document your command line tools. For most things Click automatically generates help pages for you. By design the text is customizable, but the layout is not.7-8-Help Texts9---------------10-11-Commands and options accept help arguments. For commands, the docstring of the function is automatically used if provided.12-13-Simple example:14-15-.. click:example::16-17- @click.command()18- @click.argument('name')19- @click.option('--count', default=1, help='number of greetings')20- def hello(name: str, count: int):21- """This script prints hello and a name one or more times."""22- for x in range(count):23- if name:24- click.echo(f"Hello {name}!")25- else:26- click.echo("Hello!")27-28-.. click:run::29-30- invoke(hello, args=['--help'])31-32-33-Command Short Help34-------------------35-36-For subcommands, a short help snippet is generated. By default, it's the first sentence of the docstring. If too long, then it will ellipsize what cannot be fit on a single line with ``...``. The short help snippet can also be overridden with ``short_help``:37-38-.. click:example::39-40- @click.group()41- def cli():42- """A simple command line tool."""43-44- @cli.command('init', short_help='init the repo')45- def init():46- """Initializes the repository."""47-48-49-.. click:run::50-51- invoke(cli, args=['--help'])52-53-Command Epilog Help54--------------------55-56-The help epilog is printed at the end of the help and is useful for showing example command usages or referencing additional help resources.57-58-.. click:example::59-60- @click.command(61- epilog='See https://example.com for more details',62- )63- def init():64- """Initializes the repository."""65-66-67-.. click:run::68-69- invoke(init, args=['--help'])70-71-.. _documenting-arguments:72-73-Documenting Arguments74-----------------------75-76-:class:`click.argument` does not take a ``help`` parameter. This follows the Unix Command Line Tools convention of using arguments only for necessary things and documenting them in the command help text77-by name. This should then be done via the docstring.78-79-A brief example:80-81-.. click:example::82-83- @click.command()84- @click.argument('filename')85- def touch(filename):86- """Print FILENAME."""87- click.echo(filename)88-89-90-.. click:run::91-92- invoke(touch, args=['--help'])93-94-Or more explicitly:95-96-.. click:example::97-98- @click.command()99- @click.argument('filename')100- def touch(filename):101- """Print FILENAME.102-103- FILENAME is the name of the file to check.104- """105- click.echo(filename)106-107-.. click:run::108-109- invoke(touch, args=['--help'])110-111-112-Showing Defaults113----------------------------114-To control the appearance of defaults pass ``show_default``.115-116-.. click:example::117-118- @click.command()119- @click.option('--n', default=1, show_default=False, help='number of dots')120- def dots(n):121- click.echo('.' * n)122-123-.. click:run::124-125- invoke(dots, args=['--help'])126-127-For single option boolean flags, the default remains hidden if the default value is False even if show default is true.128-129-.. click:example::130-131- @click.command()132- @click.option('--n', default=1, show_default=True)133- @click.option("--gr", is_flag=True, show_default=True, default=False, help="Greet the world.")134- @click.option("--br", is_flag=True, show_default=True, default=True, help="Add a thematic break")135- def dots(n, gr, br):136- if gr:137- click.echo('Hello world!')138- click.echo('.' * n)139- if br:140- click.echo('-' * n)141-142-.. click:run::143-144- invoke(dots, args=['--help'])145-146-147-Click's Wrapping Behavior148-----------------------------149-Click's default wrapping ignores single new lines and rewraps the text based on the width of the terminal, to a maximum of 80 characters. In the example notice how the second grouping of three lines is rewrapped into a single paragraph.150-151-.. click:example::152-153- @click.command()154- def cli():155- """156- This is a very long paragraph and as you157- can see wrapped very early in the source text158- but will be rewrapped to the terminal width in159- the final output.160-161- This is162- a paragraph163- that is compacted.164- """165-166-.. click:run::167-168- invoke(cli, args=['--help'])169-170-Escaping Click's Wrapping171----------------------------172-Sometimes Click's wrapping can be a problem, such as when showing code examples where newlines are significant. This behavior can be escaped on a per-paragraph basis by adding a line with only ``\b`` . The ``\b`` is removed from the rendered help text.173-174-Example:175-176-.. click:example::177-178- @click.command()179- def cli():180- """First paragraph.181-182- \b183- This is184- a paragraph185- without rewrapping.186-187- And this is a paragraph188- that will be rewrapped again.189- """190-191-192-.. click:run::193-194- invoke(cli, args=['--help'])195-196-To change the rendering maximum width, pass ``max_content_width`` when calling the command.197-198-.. code-block:: python199-200- cli(max_content_width=120)201-202-203-204-Truncating Help Texts205----------------------206-207-Click gets :class:`Command` help text from the docstring. If you do not want to include part of the docstring, add the ``\f`` escape marker to have Click truncate the help text after the marker.208-209-Example:210-211-.. click:example::212-213- @click.command()214- def cli():215- """First paragraph.216- \f217-218- Words to not be included.219- """220-221-.. click:run::222-223- invoke(cli, args=['--help'])224-225-.. _doc-meta-variables:226-227-Placeholder / Meta Variable228------------------------------229-230-The default placeholder variable (`meta variable <https://en.wikipedia.org/wiki/Metasyntactic_variable#IETF_Requests_for_Comments>`_) in the help pages is the parameter name in uppercase with underscores. This can be changed for Commands and Parameters with the ``options_metavar`` and ``metavar`` kwargs.231-232-.. click:example::233-234- # This controls entry on the usage line.235- @click.command(options_metavar='[[options]]')236- @click.option('--count', default=1, help='number of greetings',237- metavar='<int>')238- @click.argument('name', metavar='<name>')239- def hello(name: str, count: int) -> None:240- """This script prints 'hello <name>' a total of <count> times."""241- for x in range(count):242- click.echo(f"Hello {name}!")243-244-Example:245-246-.. click:run::247-248- invoke(hello, args=['--help'])249-250-Help Parameter Customization251-----------------------------252-Help parameters are automatically added by Click for any command. The default is ``--help`` but can be override by the context setting :attr:`~Context.help_option_names`. Click also performs automatic conflict resolution on the default help parameter so if a command itself implements a parameter named ``help`` then the default help will not be run.253-254-This example changes the default parameters to ``-h`` and ``--help``255-instead of just ``--help``:256-257-.. click:example::258-259- CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])260-261- @click.command(context_settings=CONTEXT_SETTINGS)262- def cli():263- pass264-265-266-.. click:run::267-268- invoke(cli, ['-h'])modified:docs/options.md+25 added
366 unmodified lines367 invoke(greet, env={'ALT_USERNAME': 'Bill', 'USERNAME': 'john'})368 369 ```370 371+Variable names are:372+ - [Case-insensitive on Windows but not on other platforms](https://github.com/python/cpython/blob/aa9eb5f757ceff461e6e996f12c89e5d9b583b01/Lib/os.py#L777-L789).373+ - Not stripped of whitespaces and should match the exact name provided to the `envvar` argument.374+375+For flag options, there is two concepts to consider: the activation of the flag driven by the environment variable, and the value of the flag if it is activated.376+377+The environment variable need to be interpreted, because values read from them are always strings. We need to transform these strings into boolean values that will determine if the flag is activated or not.378+379+Here are the rules used to parse environment variable values for flag options:380+ - `true`, `1`, `yes`, `on`, `t`, `y` are interpreted as activating the flag381+ - `false`, `0`, `no`, `off`, `f`, `n` are interpreted as deactivating the flag382+ - The presence of the environment variable without value is interpreted as deactivating the flag383+ - Empty strings are interpreted as deactivating the flag384+ - Values are case-insensitive, so the `True`, `TRUE`, `tRuE` strings are all activating the flag385+ - Values are stripped of leading and trailing whitespaces before being interpreted, so the `" True "` string is transformed to `"true"` and so activates the flag386+ - 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 above387+ - Any other value is interpreted as deactivating the flag388+389+.. caution::390+ For boolean flags with a pair of values, the only recognized environment variable is the one provided to the `envvar` argument.391+392+ So an option defined as `--flag\--no-flag`, with a `envvar="FLAG"` parameter, there is no magical `NO_FLAG=<anything>` variable that is recognized. Only the `FLAG=<anything>` environment variable is recognized.393+394+Once the status of the flag has been determine to be activated or not, the `flag_value` is used as the value of the flag if it is activated. If the flag is not activated, the value of the flag is set to `None` by default.395+396 ## Multiple Options from Environment Values397 398 As options can accept multiple values, pulling in such values from399 environment variables (which are strings) is a bit more complex. The way77 unmodified linesmodified:docs/shell-completion.md+1 added-1 removed
136 unmodified lines137 138 ## Overriding Value Completion139 140 Value completions for a parameter can be customized without a custom type by providing a `shell_complete` function. The141-function is used instead of any completion provided by the type. It is passed 3 keyword arguments:141+function is used instead of any completion provided by the type. It is passed 3 positional arguments:142 143 - `ctx` - The current command context.144 - `param` - The current parameter requesting completion.145 - `incomplete` - The partial word that is being completed. May be an empty string if no characters have been entered104 unmodified linesmodified:src/click/_termui_impl.py+13 added-5 removed
15 unmodified lines16 import typing as t17 from gettext import gettext as _18 from io import StringIO19 from pathlib import Path20-from shutil import which20 from types import TracebackType21 22 from ._compat import _default_text_stdout23 from ._compat import CYGWIN209 unmodified lines233 }234 ).rstrip()235 236 def render_progress(self) -> None:238- import shutil239-237 if self.hidden:238 return239 240 if not self._is_atty:5 unmodified lines246 247 buf = []248 # Update width in case the terminal has been resized249 if self.autowidth:250+ import shutil251+252 old_width = self.width253 self.width = 0254 clutter_length = term_len(self.format_progress_line())255 new_width = max(0, shutil.get_terminal_size().columns - clutter_length)163 unmodified lines419 """420 # Split the command into the invoked CLI and its parameters.421 if not cmd_parts:422 return False423+424+ import shutil425+426 cmd = cmd_parts[0]427 cmd_params = cmd_parts[1:]428 427- cmd_filepath = which(cmd)429+ cmd_filepath = shutil.which(cmd)430 if not cmd_filepath:431 return False432 # Resolves symlinks and produces a normalized absolute path string.433 cmd_path = Path(cmd_filepath).resolve()77 unmodified lines511 """512 # Split the command into the invoked CLI and its parameters.513 if not cmd_parts:514 return False515+516+ import shutil517+518 cmd = cmd_parts[0]519 515- cmd_filepath = which(cmd)520+ cmd_filepath = shutil.which(cmd)521 if not cmd_filepath:522 return False523 # Resolves symlinks and produces a normalized absolute path string.524 cmd_path = Path(cmd_filepath).resolve()52 unmodified lines577 if rv:578 return rv579 if WIN:580 return "notepad"581+582+ from shutil import which583+584 for editor in "sensible-editor", "vim", "nano":585 if which(editor) is not None:586 return editor587 return "vi"260 unmodified linesmodified:src/click/core.py+69 added-26 removed
2552 unmodified lines2553 ) -> None:2554 if help:2555 help = inspect.cleandoc(help)2556 2557- default_is_missing = "default" not in attrs2557 super().__init__(2558 param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs2559 )2560 25 unmodified lines2586 # used as a flag to indicate using prompt or flag_value.2587 self._flag_needs_value = self.prompt is not None and not self.prompt_required2588 2589 if is_flag is None:2590+ # Implicitly a flag because flag_value was set.2591 if flag_value is not None:2592- # Implicitly a flag because flag_value was set.2592 is_flag = True2593+ # Not a flag, but when used as a flag it shows a prompt.2594 elif self._flag_needs_value:2595- # Not a flag, but when used as a flag it shows a prompt.2595 is_flag = False2597- else:2598- # Implicitly a flag because flag options were given.2599- is_flag = bool(self.secondary_opts)2596+ # Implicitly a flag because flag options were given.2597+ elif self.secondary_opts:2598+ is_flag = True2599 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 None2603 2604 self.default: t.Any | t.Callable[[], t.Any]2605 2606+ if is_flag:2607+ # Set missing default for flags if not explicitly required or prompted.2607- if is_flag and default_is_missing and not self.required:2608- if multiple:2609- self.default = ()2610- else:2611- self.default = False2608+ if self.default is None and not self.required and not self.prompt:2609+ if multiple:2610+ self.default = ()2611+ else:2612+ self.default = False2613 2613- if is_flag and flag_value is None:2614- flag_value = not self.default2614+ if flag_value is None:2615+ # A boolean flag presence in the command line is enough to set2616+ # the value: to the default if it is not blank, or to True2617+ # otherwise.2618+ flag_value = self.default if self.default else True2619 2620 self.type: types.ParamType2621 if is_flag and type is None:2622 # Re-guess the type from the flag value instead of the2623 # default.2624 self.type = types.convert_type(None, flag_value)2625 2622- self.is_flag: bool = is_flag2623- self.is_bool_flag: bool = is_flag and isinstance(self.type, types.BoolParamType)2626+ self.is_flag: bool = bool(is_flag)2627+ self.is_bool_flag: bool = bool(2628+ is_flag and isinstance(self.type, types.BoolParamType)2629+ )2630 self.flag_value: t.Any = flag_value2631 2632 # Counting2633 self.count = count2634 if count:2635 if type is None:2636 self.type = types.IntRange(min=0)2631- if default_is_missing:2637+ if self.default is None:2638 self.default = 02639 2640 self.allow_from_autoenv = allow_from_autoenv2641 self.help = help39 unmodified lines2681 return info_dict2682 2683 def get_error_hint(self, ctx: Context) -> str:2684 result = super().get_error_hint(ctx)2679- if self.show_envvar:2685+ if self.show_envvar and self.envvar is not None:2686 result += f" (env var: '{self.envvar}')"2687 return result2688 2689 def _parse_decls(181 unmodified lines2871 if show_default_is_str:2872 default_string = f"({self.show_default})"2873 elif isinstance(default_value, (list, tuple)):2874 default_string = ", ".join(str(d) for d in default_value)2875+ elif isinstance(default_value, enum.Enum):2876+ default_string = default_value.name2877 elif inspect.isfunction(default_value):2878 default_string = _("(dynamic)")2879 elif self.is_bool_flag and self.secondary_opts:2880 # For boolean flags that have distinct True/False opts,44 unmodified lines2925 # 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:2921- if param.name == self.name and param.default:2922- return t.cast(Option, param).flag_value2929+ if param.name == self.name and param.default is not None:2930+ return t.cast(Option, param).default2931 2932 return None2933 2934 return super().get_default(ctx, call=call)31 unmodified lines2966 **prompt_kwargs,2967 )2968 2969 def resolve_envvar_value(self, ctx: Context) -> str | None:2970+ """Find which environment variable to read for this option and return2971+ its value.2972+2973+ Returns the value of the environment variable if it exists, or ``None``2974+ if it does not.2975+2976+ .. caution::2977+2978+ The raw value extracted from the environment is not normalized and2979+ is returned as-is. Any normalization or reconciation with the2980+ option's type should happen later.2981+ """2982 rv = super().resolve_envvar_value(ctx)2983 2984 if rv is not None:2965- if self.is_flag and self.flag_value:2966- return str(self.flag_value)2985 return rv2986 2987 if (2988 self.allow_from_autoenv8 unmodified lines2997 2998 return None2999 3000 def value_from_envvar(self, ctx: Context) -> t.Any | None:3001+ """Normalize the value from the environment variable, if it exists."""2983- rv: t.Any | None = self.resolve_envvar_value(ctx)3002+ rv: str | None = self.resolve_envvar_value(ctx)3003 3004 if rv is None:3005 return None3006 2988- value_depth = (self.nargs != 1) + bool(self.multiple)3007+ # 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 is3009+ # activated or not.3010+ if self.is_flag and not self.is_bool_flag:3011+ # If the flag_value is set and match the envvar value, return it3012+ # directly.3013+ if self.flag_value is not None and rv == self.flag_value:3014+ return self.flag_value3015+ # Analyze the envvar value as a boolean to know if the flag is3016+ # activated or not.3017+ return types.BoolParamType.str_to_bool(rv)3018 3019+ # Split the envvar value if it is allowed to be repeated.3020+ value_depth = (self.nargs != 1) + bool(self.multiple)3021 if value_depth > 0:2991- rv = self.type.split_envvar_value(rv)2992-3022+ multi_rv = self.type.split_envvar_value(rv)3023 if self.multiple and self.nargs != 1:2994- rv = batch(rv, self.nargs)3024+ multi_rv = batch(multi_rv, self.nargs) # type: ignore[assignment]3025 3026+ return multi_rv3027+3028 return rv3029 3030 def consume_value(3031 self, ctx: Context, opts: cabc.Mapping[str, Parameter]10 unmodified lines3042 else:3043 value = self.flag_value3044 source = ParameterSource.COMMANDLINE3045 3046+ # A flag which is activated and has a flag_value set, should returns3047+ # the latter, unless the value comes from the explicitly sets default.3048 elif (3049+ self.is_flag3050+ and value is True3051+ and not self.is_bool_flag3052+ and self.flag_value is not None3053+ and source is not ParameterSource.DEFAULT3054+ ):3055+ value = self.flag_value3056+3057+ elif (3058 self.multiple3059 and value is not None3060 and any(v is _flag_needs_value for v in value)3061 ):117 unmodified linesmodified:src/click/exceptions.py+3 added-3 removed
113 unmodified lines114 self,115 message: str,116 ctx: Context | None = None,117 param: Parameter | None = None,118- param_hint: str | None = None,118+ param_hint: cabc.Sequence[str] | str | None = None,119 ) -> None:120 super().__init__(message, ctx)121 self.param = param122 self.param_hint = param_hint27 unmodified lines150 self,151 message: str | None = None,152 ctx: Context | None = None,153 param: Parameter | None = None,154- param_hint: str | None = None,154+ param_hint: cabc.Sequence[str] | str | None = None,155 param_type: str | None = None,156 ) -> None:157 super().__init__(message or "", ctx, param, param_hint)158 self.param_type = param_type159 160 def format_message(self) -> str:161 if self.param_hint is not None:162- param_hint: str | None = self.param_hint162+ param_hint: cabc.Sequence[str] | str | None = self.param_hint163 elif self.param is not None:164 param_hint = self.param.get_error_hint(self.ctx) # type: ignore165 else:166 param_hint = None142 unmodified linesmodified:src/click/formatting.py+2 added-2 removed
117 unmodified lines118 indent_increment: int = 2,119 width: int | None = None,120 max_width: int | None = None,121 ) -> None:122- import shutil123-122 self.indent_increment = indent_increment123 if max_width is None:124 max_width = 80125 if width is None:126+ import shutil127+128 width = FORCED_WIDTH129 if width is None:130 width = max(min(shutil.get_terminal_size().columns, max_width) - 2, 50)131 self.width = width170 unmodified linesmodified:src/click/shell_completion.py+24 added-1 removed
122 unmodified lines123 124 %(complete_func)s_setup;125 """126 127+# See ZshComplete.format_completion below, and issue #2703, before128+# changing this script.129+#130+# (TL;DR: _describe is picky about the format, but this Zsh script snippet131+# is already widely deployed. So freeze this script, and use clever-ish132+# handling of colons in ZshComplet.format_completion.)133 _SOURCE_ZSH = """\134 #compdef %(prog_name)s135 136 %(complete_func)s() {241 unmodified lines378 379 return args, incomplete380 381 def format_completion(self, item: CompletionItem) -> str:376- return f"{item.type}\n{item.value}\n{item.help if item.help else '_'}"382+ help_ = item.help or "_"383+ # The zsh completion script uses `_describe` on items with help384+ # texts (which splits the item help from the item value at the385+ # first unescaped colon) and `compadd` on items without help386+ # text (which uses the item value as-is and does not support387+ # colon escaping). So escape colons in the item value if and388+ # only if the item help is not the sentinel "_" value, as used389+ # by the completion script.390+ #391+ # (The zsh completion script is potentially widely deployed, and392+ # thus harder to fix than this method.)393+ #394+ # See issue #1812 and issue #2703 for further context.395+ value = item.value.replace(":", r"\:") if help_ != "_" else item.value396+ return f"{item.type}\n{value}\n{help_}"397 398 399 class FishComplete(ShellComplete):400 """Shell completion for Fish."""3 unmodified lines404 405 def get_completion_args(self) -> tuple[list[str], str]:406 cwords = split_arg_string(os.environ["COMP_WORDS"])407 incomplete = os.environ["COMP_CWORD"]408+ if incomplete:409+ incomplete = split_arg_string(incomplete)[0]410 args = cwords[1:]411 412 # Fish stores the partial word in both COMP_WORDS and413 # COMP_CWORD, remove it from complete args.139 unmodified lines553 break554 555 if _start_of_option(ctx, arg):556 last_option = arg557+ break558 559 return last_option is not None and last_option in param.opts560 561 106 unmodified linesmodified:src/click/testing.py+14 added-1 removed
3 unmodified lines4 import contextlib5 import io6 import os7 import shlex8-import shutil8 import sys9 import tempfile10 import typing as t11 from types import TracebackType85 unmodified lines97 self.output: io.BytesIO = io.BytesIO()98 self.stdout: io.BytesIO = BytesIOCopy(copy_to=self.output)99 self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output)100 101+ def __del__(self) -> None:102+ """103+ Guarantee that embedded file-like objects are closed in a104+ predictable order, protecting against races between105+ self.output being closed and other streams being flushed on close106 107+ .. versionadded:: 8.2.2108+ """109+ self.stderr.close()110+ self.stdout.close()111+ self.output.close()112+113+114 class _NamedTextIOWrapper(io.TextIOWrapper):115 def __init__(116 self, buffer: t.BinaryIO, name: str, mode: str, **kwargs: t.Any117 ) -> None:451 unmodified lines569 finally:570 os.chdir(cwd)571 572 if temp_dir is None:573+ import shutil574+575 try:576 shutil.rmtree(dt)577 except OSError:578 passmodified:src/click/types.py+57 added-13 removed
659 unmodified lines660 661 class BoolParamType(ParamType):662 name = "boolean"663 664- def convert(665- self, value: t.Any, param: Parameter | None, ctx: Context | None666- ) -> t.Any:667- if value in {False, True}:668- return bool(value)664+ bool_states: dict[str, bool] = {665+ "1": True,666+ "0": False,667+ "yes": True,668+ "no": False,669+ "true": True,670+ "false": False,671+ "on": True,672+ "off": False,673+ "t": True,674+ "f": False,675+ "y": True,676+ "n": False,677+ # Absence of value is considered False.678+ "": False,679+ }680+ """A mapping of string values to boolean states.681 670- norm = value.strip().lower()682+ Mapping is inspired by :py:attr:`configparser.ConfigParser.BOOLEAN_STATES`683+ and extends it.684 672- if norm in {"1", "true", "t", "yes", "y", "on"}:673- return True685+ .. caution::686+ String values are lower-cased, as the ``str_to_bool`` comparison function687+ below is case-insensitive.688 675- if norm in {"0", "false", "f", "no", "n", "off"}:676- return False689+ .. warning::690+ The mapping is not exhaustive, and does not cover all possible boolean strings691+ representations. It will remains as it is to avoid endless bikeshedding.692 678- self.fail(679- _("{value!r} is not a valid boolean.").format(value=value), param, ctx680- )693+ Future work my be considered to make this mapping user-configurable from public694+ API.695+ """696 697+ @staticmethod698+ def str_to_bool(value: str | bool) -> bool | None:699+ """Convert a string to a boolean value.700+701+ If the value is already a boolean, it is returned as-is. If the value is a702+ string, it is stripped of whitespaces and lower-cased, then checked against703+ the known boolean states pre-defined in the `BoolParamType.bool_states` mapping704+ above.705+706+ Returns `None` if the value does not match any known boolean state.707+ """708+ if isinstance(value, bool):709+ return value710+ return BoolParamType.bool_states.get(value.strip().lower())711+712+ def convert(713+ self, value: t.Any, param: Parameter | None, ctx: Context | None714+ ) -> bool:715+ normalized = self.str_to_bool(value)716+ if normalized is None:717+ self.fail(718+ _(719+ "{value!r} is not a valid boolean. Recognized values: {states}"720+ ).format(value=value, states=", ".join(sorted(self.bool_states))),721+ param,722+ ctx,723+ )724+ return normalized725+726 def __repr__(self) -> str:727 return "BOOL"728 729 480 unmodified linesmodified:tests/test_arguments.py+9 added-13 removed
61 unmodified lines62 assert result.exception is None63 assert result.output.splitlines() == ["name=peter id=1"]64 65 66+def test_nargs_mismatch_with_tuple_type():67+ with pytest.raises(ValueError, match="nargs.*must be 2.*but it was 3"):68+69+ @click.command()70+ @click.argument("test", type=(str, int), nargs=3)71+ def cli(_):72+ pass73+74+75 def test_nargs_err(runner):76 @click.command()77 @click.argument("x")78 def copy(x):127 unmodified lines206 else:207 assert result.return_value == expect208 209 201-def test_envvar_flag_value(runner):202- @click.command()203- # is_flag is implicitly true204- @click.option("--upper", flag_value="upper", envvar="UPPER")205- def cmd(upper):206- click.echo(upper)207- return upper208-209- # For whatever value of the `env` variable, if it exists, the flag should be `upper`210- result = runner.invoke(cmd, env={"UPPER": "whatever"})211- assert result.output.strip() == "upper"212-213-210 def test_nargs_envvar_only_if_values_empty(runner):211 @click.command()212 @click.argument("arg", envvar="X", nargs=-1)213 def cli(arg):257 unmodified linesmodified:tests/test_basic.py+9 added-5 removed
220 unmodified lines221 result = runner.invoke(cli, args, standalone_mode=False)222 assert result.return_value is expect223 224 225-@pytest.mark.parametrize("default", [True, False])226-@pytest.mark.parametrize(("args", "expect"), [(["--f"], True), ([], False)])225+@pytest.mark.parametrize(226+ ("default", "args", "expect"),227+ (228+ (True, ["--f"], True),229+ (True, [], True),230+ (False, ["--f"], True),231+ (False, [], False),232+ ),233+)234 def test_boolean_flag(runner, default, args, expect):235 @click.command()236 @click.option("--f", is_flag=True, default=default)237 def cli(f):238 return f239 233- if default:234- expect = not expect235-240 result = runner.invoke(cli, args, standalone_mode=False)241 assert result.return_value is expect242 243 415 unmodified linesmodified:tests/test_imports.py+15 added-15 removed
25 unmodified lines26 """27 28 ALLOWED_IMPORTS = {29 "__future__",30- "weakref",31- "os",32- "struct",30+ "codecs",31 "collections",32 "collections.abc",35- "sys",33+ "configparser",34 "contextlib",35+ "datetime",36+ "enum",37+ "errno",38+ "fcntl",39 "functools",38- "stat",39- "re",40- "codecs",40+ "gettext",41 "inspect",42- "itertools",42 "io",43+ "itertools",44+ "os",45+ "re",46+ "stat",47+ "struct",48+ "sys",49 "threading",45- "errno",46- "fcntl",47- "datetime",48- "enum",49- "typing",50 "types",51- "gettext",52- "shutil",51+ "typing",52+ "weakref",53 }54 55 if WIN:56 ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time"])14 unmodified linesmodified:tests/test_options.py+363 added-19 removed
1+import enum2 import os3 import re4+import sys5 6+if sys.version_info < (3, 11):7+ enum.StrEnum = enum.Enum # type: ignore[assignment]8+9 import pytest10 11 import click12 from click import Option238 unmodified lines251 assert not result.exception252 assert result.output == "foo|bar\n"253 254 250-def test_trailing_blanks_boolean_envvar(runner):255+@pytest.mark.parametrize(256+ ("name", "value", "expected"),257+ (258+ # Lower-cased variations of value.259+ ("SHOUT", "true", True),260+ ("SHOUT", "false", False),261+ # Title-cased variations of value.262+ ("SHOUT", "True", True),263+ ("SHOUT", "False", False),264+ # Upper-cased variations of value.265+ ("SHOUT", "TRUE", True),266+ ("SHOUT", "FALSE", False),267+ # Random-cased variations of value.268+ ("SHOUT", "TruE", True),269+ ("SHOUT", "truE", True),270+ ("SHOUT", "FaLsE", False),271+ ("SHOUT", "falsE", False),272+ # 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),279+ # Integer variations.280+ ("SHOUT", "1", True),281+ ("SHOUT", "0", False),282+ # Alternative states.283+ ("SHOUT", "t", True),284+ ("SHOUT", "f", False),285+ ("SHOUT", "y", True),286+ ("SHOUT", "n", False),287+ ("SHOUT", "yes", True),288+ ("SHOUT", "no", False),289+ ("SHOUT", "on", True),290+ ("SHOUT", "off", False),291+ # Blank value variations.292+ ("SHOUT", None, False),293+ ("SHOUT", "", False),294+ ("SHOUT", " ", False),295+ ("SHOUT", " ", False),296+ # Variable names are not stripped of spaces and so don't match the297+ # flag, which then naturraly takes its default value.298+ ("SHOUT ", "True", False),299+ ("SHOUT ", "False", False),300+ (" SHOUT ", "True", False),301+ (" SHOUT ", "False", False),302+ # Same for random and reverse environment variable names: they are not303+ # recognized by the option.304+ ("RANDOM", "True", False),305+ ("NO_SHOUT", "True", False),306+ ("NO_SHOUT", "False", False),307+ ),308+)309+def test_boolean_envvar_normalization(runner, name, value, expected):310 @click.command()311 @click.option("--shout/--no-shout", envvar="SHOUT")312 def cli(shout):313 click.echo(f"shout: {shout!r}")314 256- result = runner.invoke(cli, [], env={"SHOUT": " true "})315+ result = runner.invoke(cli, [], env={name: value})316 assert result.exit_code == 0258- assert result.output == "shout: True\n"317+ assert result.output == f"shout: {expected}\n"318 319 320+@pytest.mark.parametrize(321+ ("name", "value"),322+ (323+ ("SHOUT", "tr ue"),324+ ("SHOUT", "10"),325+ ("SHOUT", "01"),326+ ("SHOUT", "00"),327+ ("SHOUT", "11"),328+ ("SHOUT", "randomstring"),329+ ("SHOUT", "None"),330+ ),331+)332+def test_boolean_envvar_bad_values(runner, name, value):333+ @click.command()334+ @click.option("--shout/--no-shout", envvar="SHOUT")335+ def cli(shout):336+ click.echo(f"shout: {shout!r}")337+338+ result = runner.invoke(cli, [], env={name: value})339+ assert result.exit_code == 2340+ assert (341+ f"Invalid value for '--shout': {value!r} is not a valid boolean."342+ in result.output343+ )344+345+346 def test_multiple_default_help(runner):347 @click.command()348 @click.option("--arg1", multiple=True, default=("foo", "bar"), show_default=True)349 @click.option("--arg2", multiple=True, default=(1, 2), type=int, show_default=True)326 unmodified lines676 result = runner.invoke(cli)677 assert result.exit_code == 2678 assert "Error: Missing option '--foo' (env var: 'bar')." in result.output679 680+ cli = click.Command(681+ "cli", params=[click.Option(["--foo"], show_envvar=True, required=True)]682+ )683+ result = runner.invoke(cli)684+ assert result.exit_code == 2685+ assert "Error: Missing option '--foo'." in result.output686 687+688 def test_case_insensitive_choice(runner):689 @click.command()690 @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))691 def cmd(foo):407 unmodified lines1099 assert param.type is click.INT1100 1101 1102 @pytest.mark.parametrize(1011- ("opts", "pass_flag", "expected"),1103+ ("opt_params", "pass_flag", "expected"),1104 [1013- pytest.param({"type": bool}, False, "False"),1014- pytest.param({"type": bool}, True, "True"),1015- pytest.param({"type": bool, "default": True}, False, "True"),1016- pytest.param({"type": bool, "default": True}, True, "False"),1017- pytest.param({"type": click.BOOL}, False, "False"),1018- pytest.param({"type": click.BOOL}, True, "True"),1019- pytest.param({"type": click.BOOL, "default": True}, False, "True"),1020- pytest.param({"type": click.BOOL, "default": True}, True, "False"),1021- pytest.param({"type": str}, False, ""),1022- pytest.param({"type": str}, True, "True"),1105+ # Effect of the presence/absence of flag depending on type1106+ ({"type": bool}, False, False),1107+ ({"type": bool}, True, True),1108+ ({"type": click.BOOL}, False, False),1109+ ({"type": click.BOOL}, True, True),1110+ ({"type": str}, False, "False"),1111+ ({"type": str}, True, "True"),1112+ # Effects of default value1113+ ({"type": bool, "default": True}, False, True),1114+ ({"type": bool, "default": True}, True, True),1115+ ({"type": bool, "default": False}, False, False),1116+ ({"type": bool, "default": False}, True, True),1117+ ({"type": bool, "default": None}, False, False),1118+ ({"type": bool, "default": None}, True, True),1119+ ({"type": click.BOOL, "default": True}, False, True),1120+ ({"type": click.BOOL, "default": True}, True, True),1121+ ({"type": click.BOOL, "default": False}, False, False),1122+ ({"type": click.BOOL, "default": False}, True, True),1123+ ({"type": click.BOOL, "default": None}, False, False),1124+ ({"type": click.BOOL, "default": None}, True, True),1125+ ({"type": str, "default": True}, False, "True"),1126+ ({"type": str, "default": True}, True, "True"),1127+ ({"type": str, "default": False}, False, "False"),1128+ ({"type": str, "default": False}, True, "True"),1129+ ({"type": str, "default": "foo"}, False, "foo"),1130+ ({"type": str, "default": "foo"}, True, "foo"),1131+ ({"type": str, "default": None}, False, "False"),1132+ ({"type": str, "default": None}, True, "True"),1133+ # Effects of flag_value1134+ ({"type": bool, "flag_value": True}, False, False),1135+ ({"type": bool, "flag_value": True}, True, True),1136+ ({"type": bool, "flag_value": False}, False, False),1137+ ({"type": bool, "flag_value": False}, True, False),1138+ ({"type": bool, "flag_value": None}, False, False),1139+ ({"type": bool, "flag_value": None}, True, True),1140+ ({"type": click.BOOL, "flag_value": True}, False, False),1141+ ({"type": click.BOOL, "flag_value": True}, True, True),1142+ ({"type": click.BOOL, "flag_value": False}, False, False),1143+ ({"type": click.BOOL, "flag_value": False}, True, False),1144+ ({"type": click.BOOL, "flag_value": None}, False, False),1145+ ({"type": click.BOOL, "flag_value": None}, True, True),1146+ ({"type": str, "flag_value": True}, False, "False"),1147+ ({"type": str, "flag_value": True}, True, "True"),1148+ ({"type": str, "flag_value": False}, False, "False"),1149+ ({"type": str, "flag_value": False}, True, "False"),1150+ ({"type": str, "flag_value": "foo"}, False, "False"),1151+ ({"type": str, "flag_value": "foo"}, True, "foo"),1152+ ({"type": str, "flag_value": None}, False, "False"),1153+ ({"type": str, "flag_value": None}, True, "True"),1154+ # Not passing --foo returns the default value as-is1155+ ({"type": bool, "default": True, "flag_value": True}, False, True),1156+ ({"type": bool, "default": True, "flag_value": False}, False, True),1157+ ({"type": bool, "default": False, "flag_value": True}, False, False),1158+ ({"type": bool, "default": False, "flag_value": False}, False, False),1159+ ({"type": bool, "default": None, "flag_value": True}, False, False),1160+ ({"type": bool, "default": None, "flag_value": False}, False, False),1161+ ({"type": str, "default": True, "flag_value": True}, False, "True"),1162+ ({"type": str, "default": True, "flag_value": False}, False, "True"),1163+ ({"type": str, "default": False, "flag_value": True}, False, "False"),1164+ ({"type": str, "default": False, "flag_value": False}, False, "False"),1165+ ({"type": str, "default": "foo", "flag_value": True}, False, "foo"),1166+ ({"type": str, "default": "foo", "flag_value": False}, False, "foo"),1167+ ({"type": str, "default": "foo", "flag_value": "bar"}, False, "foo"),1168+ ({"type": str, "default": "foo", "flag_value": None}, False, "foo"),1169+ ({"type": str, "default": None, "flag_value": True}, False, "False"),1170+ ({"type": str, "default": None, "flag_value": False}, False, "False"),1171+ # Passing --foo returns the explicitly set flag_value1172+ ({"type": bool, "default": True, "flag_value": True}, True, True),1173+ ({"type": bool, "default": True, "flag_value": False}, True, False),1174+ ({"type": bool, "default": False, "flag_value": True}, True, True),1175+ ({"type": bool, "default": False, "flag_value": False}, True, False),1176+ ({"type": bool, "default": None, "flag_value": True}, True, True),1177+ ({"type": bool, "default": None, "flag_value": False}, True, False),1178+ ({"type": str, "default": True, "flag_value": True}, True, "True"),1179+ ({"type": str, "default": True, "flag_value": False}, True, "False"),1180+ ({"type": str, "default": False, "flag_value": True}, True, "True"),1181+ ({"type": str, "default": False, "flag_value": False}, True, "False"),1182+ ({"type": str, "default": "foo", "flag_value": True}, True, "True"),1183+ ({"type": str, "default": "foo", "flag_value": False}, True, "False"),1184+ ({"type": str, "default": "foo", "flag_value": "bar"}, True, "bar"),1185+ ({"type": str, "default": "foo", "flag_value": None}, True, "foo"),1186+ ({"type": str, "default": None, "flag_value": True}, True, "True"),1187+ ({"type": str, "default": None, "flag_value": False}, True, "False"),1188 ],1189 )1025-def test_flag_value_is_correctly_set(runner, opts, pass_flag, expected):1190+def test_flag_value_and_default(runner, opt_params, pass_flag, expected):1191 @click.command()1192+ @click.option("--foo", is_flag=True, **opt_params)1193+ def cmd(foo):1194+ click.echo(repr(foo))1195+1196+ result = runner.invoke(cmd, ["--foo"] if pass_flag else [])1197+ assert result.output == f"{expected!r}\n"1198+1199+1200+@pytest.mark.parametrize(1201+ "opts",1202+ [1203+ {"type": bool, "default": "foo"},1204+ {"type": bool, "flag_value": "foo"},1205+ {"type": click.BOOL, "default": "foo"},1206+ {"type": click.BOOL, "flag_value": "foo"},1207+ ],1208+)1209+def test_invalid_flag_definition(runner, opts):1210+ @click.command()1211 @click.option("--foo", is_flag=True, **opts)1212 def cmd(foo):1213 click.echo(foo)1214 1031- result = runner.invoke(cmd, ["--foo"] if pass_flag else [])1032- assert result.output == f"{expected}\n"1215+ result = runner.invoke(cmd, ["--foo"])1216+ assert (1217+ "Error: Invalid value for '--foo': 'foo' is not a valid boolean"1218+ in result.output1219+ )1220 1221 1222 @pytest.mark.parametrize(1223+ ("flag_value", "envvar_value", "expected"),1224+ [1225+ # Envvar is set to false, so the flag default value is returned.1226+ ("bar", "False", "False"),1227+ # Same as above with alternative states and blank values.1228+ ("bar", "0", "False"),1229+ ("bar", "f", "False"),1230+ ("bar", "", "False"),1231+ # Envvar is set to true, so the flag_value is returned.1232+ ("bar", "True", "bar"),1233+ ("bar", "1", "bar"),1234+ ("bar", "t", "bar"),1235+ # So far we have the same cases as the test_flag_value_and_default1236+ # test case. Now instead of passing a boolean-like value, let's use1237+ # the flag_value as the envvar value.1238+ ("bar", "bar", "bar"),1239+ # flag_value is expected to be the exact same in the envvar for the flag to be1240+ # activated.1241+ ("bar", " bar ", "False"),1242+ ("bar", "BAR", "False"),1243+ ("bar", "random", "False"),1244+ ("bar", "bar random", "False"),1245+ ("bar", "random bar", "False"),1246+ ("BAR", "BAR", "BAR"),1247+ ("BAR", "bar", "False"),1248+ (" bar ", " bar ", " bar "),1249+ (" bar ", "bar", "False"),1250+ (" bar ", "BAR", "False"),1251+ ],1252+)1253+def test_envvar_flag_value(runner, flag_value, envvar_value, expected):1254+ """Ensure that flag_value is recognized by the envvar."""1255+1256+ @click.command()1257+ @click.option(1258+ "--upper", type=str, is_flag=True, flag_value=flag_value, envvar="UPPER"1259+ )1260+ def cmd(upper):1261+ click.echo(repr(upper))1262+1263+ result = runner.invoke(cmd, env={"UPPER": envvar_value})1264+ assert result.exit_code == 01265+ assert result.output == f"{expected!r}\n"1266+1267+1268+@pytest.mark.parametrize(1269 ("option", "expected"),1270 [1271 # Not boolean flags1272 pytest.param(Option(["-a"], type=int), False, id="int option"),6 unmodified lines1279 pytest.param(Option(["-a/-A"]), True, id="secondary option [implicit flag]"),1280 pytest.param(Option(["-a"], flag_value=True), True, id="bool flag_value"),1281 ],1282 )1050-def test_is_bool_flag_is_correctly_set(option, expected):1283+def test_bool_flag_auto_detection(option, expected):1284 assert option.is_bool_flag is expected1285 1286 1287 @pytest.mark.parametrize(23 unmodified lines1311 result = runner.invoke(cmd)1312 assert result.exit_code == 01313 1314 1315+class HashType(enum.Enum):1316+ MD5 = enum.auto()1317+ SHA1 = enum.auto()1318+1319+1320+class Number(enum.IntEnum):1321+ ONE = enum.auto()1322+ TWO = enum.auto()1323+1324+1325+class Letter(enum.StrEnum):1326+ A = enum.auto()1327+ B = enum.auto()1328+1329+1330+class Color(enum.Flag):1331+ RED = enum.auto()1332+ GREEN = enum.auto()1333+ BLUE = enum.auto()1334+1335+1336+class ColorInt(enum.IntFlag):1337+ RED = enum.auto()1338+ GREEN = enum.auto()1339+ BLUE = enum.auto()1340+1341+1342 @pytest.mark.parametrize(1343 ("choices", "metavars"),1344 [1345 pytest.param(["foo", "bar"], "[TEXT]", id="text choices"),1346 pytest.param([1, 2], "[INTEGER]", id="int choices"),1347 pytest.param([1.0, 2.0], "[FLOAT]", id="float choices"),1348 pytest.param([True, False], "[BOOLEAN]", id="bool choices"),1349 pytest.param(["foo", 1], "[TEXT|INTEGER]", id="text/int choices"),1350+ pytest.param(HashType, "[HASHTYPE]", id="enum choices"),1351+ pytest.param(Number, "[NUMBER]", id="int enum choices"),1352+ pytest.param(Letter, "[LETTER]", id="str enum choices"),1353+ pytest.param(Color, "[COLOR]", id="flag enum choices"),1354+ pytest.param(ColorInt, "[COLORINT]", id="int flag enum choices"),1355 ],1356 )1357 def test_usage_show_choices(runner, choices, metavars):1358 """When show_choices=False is set, the --help output14 unmodified lines1373 def cli_without_choices(g):1374 pass1375 1376 result = runner.invoke(cli_with_choices, ["--help"])1112- assert f"[{'|'.join([str(i) for i in choices])}]" in result.output1377+ assert (1378+ f"[{'|'.join(i.name if isinstance(i, enum.Enum) else str(i) for i in choices)}]"1379+ in result.output1380+ )1381 1382 result = runner.invoke(cli_without_choices, ["--help"])1383 assert metavars in result.output1384 1385 1386 @pytest.mark.parametrize(1387+ ("choices", "default", "default_string"),1388+ [1389+ (["foo", "bar"], "bar", "bar"),1390+ # The default value is not enforced to be in the choices.1391+ (["foo", "bar"], "random", "random"),1392+ # None cannot be a default value as-is: it left the default value as unset.1393+ (["foo", "bar"], None, None),1394+ ([0, 1], 0, "0"),1395+ # Values are not coerced to the type of the choice, even if equivalent.1396+ ([0, 1], 0.0, "0.0"),1397+ ([1, 2], 2, "2"),1398+ ([1.0, 2.0], 2, "2"),1399+ ([1.0, 2.0], 2.0, "2.0"),1400+ ([True, False], True, "True"),1401+ ([True, False], False, "False"),1402+ (["foo", 1], "foo", "foo"),1403+ (["foo", 1], 1, "1"),1404+ # Enum choices are rendered as their names.1405+ # See: https://github.com/pallets/click/issues/29111406+ (HashType, HashType.SHA1, "SHA1"),1407+ # Enum choices allow defaults strings that are their names.1408+ (HashType, "SHA1", "SHA1"),1409+ (Number, Number.TWO, "TWO"),1410+ (Letter, Letter.B, "B"),1411+ (Color, Color.GREEN, "GREEN"),1412+ (ColorInt, ColorInt.GREEN, "GREEN"),1413+ ],1414+)1415+def test_choice_default_rendering(runner, choices, default, default_string):1416+ @click.command()1417+ @click.option("-g", type=click.Choice(choices), default=default, show_default=True)1418+ def cli_with_choices(g):1419+ pass1420+1421+ # Check that the default value is kept normalized to the type of the choice.1422+ assert cli_with_choices.params[0].default == default1423+1424+ result = runner.invoke(cli_with_choices, ["--help"])1425+ extra_usage = f"[default: {default_string}]"1426+ if default_string is None:1427+ assert extra_usage not in result.output1428+ else:1429+ assert extra_usage in result.output1430+1431+1432+@pytest.mark.parametrize(1433 "opts_one,opts_two",1434 [1435 # No duplicate shortnames1436 (15 unmodified lines1452 pass1453 1454 with pytest.warns(UserWarning):1455 runner.invoke(cli, [])1456+1457+1458+@pytest.mark.parametrize(1459+ ("multiple", "nargs", "default", "expected_message"),1460+ [1461+ (1462+ False, # multiple1463+ 2, # nargs1464+ 42, # default (not a list)1465+ "'default' must be a list when 'nargs' != 1.",1466+ ),1467+ (1468+ True, # multiple1469+ 2, # nargs1470+ [1471+ "test string which is not a list in the list"1472+ ], # default (list of non-lists)1473+ "'default' must be a list of lists when 'multiple' is true"1474+ " and 'nargs' != 1.",1475+ ),1476+ ],1477+)1478+def test_default_type_error_raises(multiple, nargs, default, expected_message):1479+ with pytest.raises(ValueError, match=expected_message):1480+ click.Option(1481+ ["--test"],1482+ multiple=multiple,1483+ nargs=nargs,1484+ default=default,1485+ )modified:tests/test_shell_completion.py+89 added
1+import textwrap2 import warnings3+from collections.abc import Mapping4 5 import pytest6 7 import click.shell_completion211 unmodified lines219 # flag option doesn't take value, use choice argument220 assert _get_words(cli, ["--on"], "a") == ["a1", "a2"]221 222 223+def test_flag_option_with_nargs_option():224+ cli = Command(225+ "cli",226+ add_help_option=False,227+ params=[228+ Argument(["a"], type=Choice(["a1", "a2", "b"])),229+ Option(["--flag"], is_flag=True),230+ Option(["-c"], type=Choice(["p", "q"]), nargs=2),231+ ],232+ )233+ assert _get_words(cli, ["a1", "--flag", "-c"], "") == ["p", "q"]234+235+236 def test_option_custom():237 def custom(ctx, param, incomplete):238 return [incomplete.upper()]239 118 unmodified lines358 ("zsh", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain\na\n_\nplain\nb\nbee\n"),359 ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"),360 ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"),361 ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"),362+ ("fish", {"COMP_WORDS": 'a "b', "COMP_CWORD": '"b'}, "plain,b\tbee\n"),363 ],364 )365 @pytest.mark.usefixtures("_patch_for_completion")366 def test_full_complete(runner, shell, env, expect):2 unmodified lines369 result = runner.invoke(cli, env=env)370 assert result.output == expect371 372 373+@pytest.mark.parametrize(374+ ("env", "expect"),375+ [376+ (377+ {"COMP_WORDS": "", "COMP_CWORD": "0"},378+ textwrap.dedent(379+ """\380+ plain381+ a382+ _383+ plain384+ b385+ bee386+ plain387+ c\\:d388+ cee:dee389+ plain390+ c:e391+ _392+ """393+ ),394+ ),395+ (396+ {"COMP_WORDS": "a c", "COMP_CWORD": "1"},397+ textwrap.dedent(398+ """\399+ plain400+ c\\:d401+ cee:dee402+ plain403+ c:e404+ _405+ """406+ ),407+ ),408+ (409+ {"COMP_WORDS": "a c:", "COMP_CWORD": "1"},410+ textwrap.dedent(411+ """\412+ plain413+ c\\:d414+ cee:dee415+ plain416+ c:e417+ _418+ """419+ ),420+ ),421+ ],422+)423 @pytest.mark.usefixtures("_patch_for_completion")424+def test_zsh_full_complete_with_colons(425+ runner, env: Mapping[str, str], expect: str426+) -> None:427+ cli = Group(428+ "cli",429+ commands=[430+ Command("a"),431+ Command("b", help="bee"),432+ Command("c:d", help="cee:dee"),433+ Command("c:e"),434+ ],435+ )436+ result = runner.invoke(437+ cli,438+ env={439+ **env,440+ "_CLI_COMPLETE": "zsh_complete",441+ },442+ )443+ assert result.output == expect444+445+446+@pytest.mark.usefixtures("_patch_for_completion")447 def test_context_settings(runner):448 def complete(ctx, param, incomplete):449 return ctx.obj["choices"]450 111 unmodified linesmodified:tests/test_testing.py+2 added-4 removed
446 unmodified lines447 runner = CliRunner()448 449 with runner.isolation() as (_, err, _):450 click.echo("\udce2", err=True, nl=False)451+ assert err.getvalue() == b"\\udce2"452 452- assert err.getvalue() == b"\\udce2"453 454-454 def test_isolation_flushes_unflushed_stderr():455 """An un-flushed write to stderr, as with `print(..., file=sys.stderr)`, will end up456 flushed by the runner at end of invocation.457 """458 runner = CliRunner()459 460 with runner.isolation() as (_, err, _):461 click.echo("\udce2", err=True, nl=False)462+ assert err.getvalue() == b"\\udce2"463 464- assert err.getvalue() == b"\\udce2"465-464 @click.command()465 def cli():466 # set end="", flush=False so that it's totally clear that we won't get any467 # auto-flush behaviors4 unmodified linesmodified:tests/test_types.py+6 added-1 removed
224 unmodified lines225 )226 def test_file_surrogates(type, tmp_path):227 path = tmp_path / "\udcff"228 229+ # - common case: �': No such file or directory230+ # - special case: Illegal byte sequence231+ # The spacial case is seen with rootless Podman. The root cause is most232+ # likely that the path is handled by a user-space program (FUSE).233+ match = r"(�': No such file or directory|Illegal byte sequence)"229- with pytest.raises(click.BadParameter, match="�': No such file or directory"):234+ with pytest.raises(click.BadParameter, match=match):235 type.convert(path, None, None)236 237 238 def test_file_error_surrogates():19 unmodified linesmodified:CHANGES.rst+27 added
1 .. currentmodule:: click2 3+Version 8.2.x4+-------------5+6+Unreleased7+8+- show correct auto complete value for nargs option in combination with flag option :issue:`2813`9+10+Version 8.2.211+-------------12+13+Released 2025-07-3114+15+- Fix reconciliation of `default`, `flag_value` and `type` parameters for16+ flag options, as well as parsing and normalization of environment variables.17+ :issue:`2952` :pr:`2956`18+- Fix typing issue in ``BadParameter`` and ``MissingParameter`` exceptions for the19+ parameter ``param_hint`` that did not allow for a sequence of string where the20+ underlying functino ``_join_param_hints`` allows for it. :issue:`2777` :pr:`2990`21+- Use the value of ``Enum`` choices to render their default value in help22+ screen. Refs :issue:`2911` :pr:`3004`23+- Fix completion for the Z shell (``zsh``) for completion items containing24+ colons. :issue:`2703` :pr:`2846`25+- Don't include envvar in error hint when not configured. :issue:`2971` :pr:`2972`26+- Fix a rare race in ``click.testing.StreamMixer``'s finalization that manifested27+ as a ``ValueError`` on close in a multi-threaded test session.28+ :issue:`2993` :pr:`2991`29+30 Version 8.2.131 -------------32 33 Released 2025-05-201241 unmodified linesmodified:pyproject.toml+1 added-1 removed
1 [project]2 name = "click"3-version = "8.2.1"3+version = "8.2.2"4 description = "Composable command line interface toolkit"5 readme = "README.md"6 license = "BSD-3-Clause"7 license-files = ["LICENSE.txt"]201 unmodified linesmodified:uv.lock+1 added-1 removed
137 unmodified lines138 ]139 140 [[package]]141 name = "click"142-version = "8.2.1"142+version = "8.2.2"143 source = { editable = "." }144 dependencies = [145 { name = "colorama", marker = "sys_platform == 'win32'" },146 ]1076 unmodified lines