Skip to content
Myr

Merge branch 'rstTomyst' of https://github.com/denuoweb/click into rstTomyst

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

authored by denuoweb · committed by denuoweb · parents 1dc4e91, 6ce5591 · Browse files · 24 files+1053 added−438 removed
This commit

State

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

Diff stats

24 files+1053 added−438 removed

  • tests:+493 added−57 removed
  • other:+560 added−381 removed

24 files+1053 added−438 removed

added:docs/contrib.md+45 added
deleted:docs/contrib.rst-58 removed
1.. _contrib:23=============4click-contrib5=============67As the number of users of Click grows, more and more major feature requests are8made. To users it may seem reasonable to include those features with Click;9however, many of them are experimental or aren't practical to support10generically. Maintainers have to choose what is reasonable to maintain in Click11core.1213The click-contrib_ GitHub organization exists as a place to collect third-party14packages that extend Click's features. It is also meant to ease the effort of15searching for such extensions.1617Please note that the quality and stability of those packages may be different18than Click itself. While published under a common organization, they are still19separate from Click and the Pallets maintainers.202122Third-party projects23--------------------2425Other projects that extend Click's features are available outside of the26click-contrib_ organization.2728Some of the most popular and actively maintained are listed below:2930========================================================== =========================================================================================== ================================================================================================= ======================================================================================================31Project 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========================================================== =========================================================================================== ================================================================================================= ======================================================================================================4445.. note::4647 To make it into the list above, a project:4849 - must be actively maintained (at least one commit in the last year)50 - must have a reasonable number of stars (at least 20)5152 If you have a project that meets these criteria, please open a pull request53 to add it to the list.5455 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.5758.. _click-contrib: https://github.com/click-contrib/
added:docs/documentation.md+277 added
1# Help Pages23```{currentmodule} click4```56Click 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.78## Help Texts910Commands and options accept help arguments. For commands, the docstring of the function is automatically used if provided.1112Simple example:1314```{eval-rst}15.. click:example::1617 @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!")2728.. click:run::29 invoke(hello, args=['--help'])30```3132## Command Short Help3334For 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`:3536```{eval-rst}37.. click:example::3839 import click4041 @click.group()42 def cli():43 """A simple command line tool."""4445 @cli.command('init', short_help='init the repo')46 def init():47 """Initializes the repository."""4849.. click:run::50 invoke(cli, args=['--help'])51```5253## Command Epilog Help5455The help epilog is printed at the end of the help and is useful for showing example command usages or referencing additional help resources.5657```{eval-rst}58.. click:example::5960 import click6162 @click.command(63 epilog='See https://example.com for more details',64 )65 def init():66 """Initializes the repository."""6768.. click:run::69 invoke(init, args=['--help'])70```7172(documenting-arguments)=7374## Documenting Arguments7576{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 text77by name. This should then be done via the docstring.7879A brief example:8081```{eval-rst}82.. click:example::8384 @click.command()85 @click.argument('filename')86 def touch(filename):87 """Print FILENAME."""88 click.echo(filename)8990.. click:run::91 invoke(touch, args=['--help'])92```9394Or more explicitly:9596```{eval-rst}97.. click:example::9899 @click.command()100 @click.argument('filename')101 def touch(filename):102 """Print FILENAME.103104 FILENAME is the name of the file to check.105 """106 click.echo(filename)107108.. click:run::109 invoke(touch, args=['--help'])110```111112## Showing Defaults113114To control the appearance of defaults pass `show_default`.115116```{eval-rst}117.. click:example::118119 @click.command()120 @click.option('--n', default=1, show_default=False, help='number of dots')121 def dots(n):122 click.echo('.' * n)123124.. click:run::125 invoke(dots, args=['--help'])126```127128For single option boolean flags, the default remains hidden if the default value is False, even if show default is set to true.129130```{eval-rst}131.. click:example::132133 @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)143144.. click:run::145 invoke(dots, args=['--help'])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.151152```{eval-rst}153.. click:example::154155 import click156157 @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.164165 This is166 a paragraph167 that is compacted.168 """169170.. click:run::171 invoke(cli, args=['--help'])172```173174## Escaping Click's Wrapping175176Sometimes 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.177178Example:179180```{eval-rst}181.. click:example::182183 import click184185 @click.command()186 def cli():187 """First paragraph.188189 \b190 This is191 a paragraph192 without rewrapping.193194 And this is a paragraph195 that will be rewrapped again.196 """197198.. click:run::199 invoke(cli, args=['--help'])200```201202To change the rendering maximum width, pass `max_content_width` when calling the command.203204```bash205cli(max_content_width=120)206```207208## Truncating Help Texts209210Click 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.211212Example:213214```{eval-rst}215.. click:example::216217 import click218219 @click.command()220 def cli():221 """First paragraph.222 \f223224 Words to not be included.225 """226227.. click:run::228 invoke(cli, args=['--help'])229```230231(doc-meta-variables)=232233## Placeholder / Meta Variable234235The 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.236237```{eval-rst}238.. click:example::239240 # 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}!")249250# Example usage:251252.. click:run::253 invoke(hello, args=['--help'])254255```256257## Help Parameter Customization258259Help 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.260261This example changes the default parameters to `-h` and `--help`262instead of just `--help`:263264```{eval-rst}265.. click:example::266267 import click268269 CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])270271 @click.command(context_settings=CONTEXT_SETTINGS)272 def cli():273 pass274275.. click:run::276 invoke(cli, ['-h'])277```
deleted:docs/documentation.rst-268 removed
1Help Pages2===================34.. currentmodule:: click56Click 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.78Help Texts9--------------1011Commands and options accept help arguments. For commands, the docstring of the function is automatically used if provided.1213Simple example:1415.. click:example::1617 @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!")2728.. click:run::2930 invoke(hello, args=['--help'])313233Command Short Help34------------------3536For 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``:3738.. click:example::3940 @click.group()41 def cli():42 """A simple command line tool."""4344 @cli.command('init', short_help='init the repo')45 def init():46 """Initializes the repository."""474849.. click:run::5051 invoke(cli, args=['--help'])5253Command Epilog Help54-------------------5556The help epilog is printed at the end of the help and is useful for showing example command usages or referencing additional help resources.5758.. click:example::5960 @click.command(61 epilog='See https://example.com for more details',62 )63 def init():64 """Initializes the repository."""656667.. click:run::6869 invoke(init, args=['--help'])7071.. _documenting-arguments:7273Documenting Arguments74----------------------7576: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 text77by name. This should then be done via the docstring.7879A brief example:8081.. click:example::8283 @click.command()84 @click.argument('filename')85 def touch(filename):86 """Print FILENAME."""87 click.echo(filename)888990.. click:run::9192 invoke(touch, args=['--help'])9394Or more explicitly:9596.. click:example::9798 @click.command()99 @click.argument('filename')100 def touch(filename):101 """Print FILENAME.102103 FILENAME is the name of the file to check.104 """105 click.echo(filename)106107.. click:run::108109 invoke(touch, args=['--help'])110111112Showing Defaults113---------------------------114To control the appearance of defaults pass ``show_default``.115116.. click:example::117118 @click.command()119 @click.option('--n', default=1, show_default=False, help='number of dots')120 def dots(n):121 click.echo('.' * n)122123.. click:run::124125 invoke(dots, args=['--help'])126127For single option boolean flags, the default remains hidden if the default value is False even if show default is true.128129.. click:example::130131 @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)141142.. click:run::143144 invoke(dots, args=['--help'])145146147Click's Wrapping Behavior148----------------------------149Click'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.150151.. click:example::152153 @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.160161 This is162 a paragraph163 that is compacted.164 """165166.. click:run::167168 invoke(cli, args=['--help'])169170Escaping Click's Wrapping171---------------------------172Sometimes 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.173174Example:175176.. click:example::177178 @click.command()179 def cli():180 """First paragraph.181182 \b183 This is184 a paragraph185 without rewrapping.186187 And this is a paragraph188 that will be rewrapped again.189 """190191192.. click:run::193194 invoke(cli, args=['--help'])195196To change the rendering maximum width, pass ``max_content_width`` when calling the command.197198.. code-block:: python199200 cli(max_content_width=120)201202203204Truncating Help Texts205---------------------206207Click 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.208209Example:210211.. click:example::212213 @click.command()214 def cli():215 """First paragraph.216 \f217218 Words to not be included.219 """220221.. click:run::222223 invoke(cli, args=['--help'])224225.. _doc-meta-variables:226227Placeholder / Meta Variable228-----------------------------229230The 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.231232.. click:example::233234 # 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}!")243244Example:245246.. click:run::247248 invoke(hello, args=['--help'])249250Help Parameter Customization251----------------------------252Help 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.253254This example changes the default parameters to ``-h`` and ``--help``255instead of just ``--help``:256257.. click:example::258259 CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])260261 @click.command(context_settings=CONTEXT_SETTINGS)262 def cli():263 pass264265266.. click:run::267268 invoke(cli, ['-h'])
modified:docs/options.md+25 added
366 unmodified lines
367 invoke(greet, env={'ALT_USERNAME': 'Bill', 'USERNAME': 'john'})368369```370371Variable 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.374375For 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.376377The 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.378379Here 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 flag388389.. caution::390 For boolean flags with a pair of values, the only recognized environment variable is the one provided to the `envvar` argument.391392 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.393394Once 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.395396## Multiple Options from Environment Values397398As options can accept multiple values, pulling in such values from399environment variables (which are strings) is a bit more complex. The way
77 unmodified lines
modified:docs/prompts.md+1 added-1 removed
modified:docs/shell-completion.md+1 added-1 removed
136 unmodified lines
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 keyword arguments:141function 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 entered
104 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
modified:src/click/core.py+69 added-26 removed
2552 unmodified lines
2553 ) -> None:2554 if help:2555 help = inspect.cleandoc(help)25562557 default_is_missing = "default" not in attrs2557 super().__init__(2558 param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs2559 )2560
25 unmodified lines
2586 # 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_required25882589 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 None26032604 self.default: t.Any | t.Callable[[], t.Any]26052606 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 = False26132613 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 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)26252622 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_value26312632 # 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 = 026392640 self.allow_from_autoenv = allow_from_autoenv2641 self.help = help
39 unmodified lines
2681 return info_dict26822683 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 result26882689 def _parse_decls(
181 unmodified lines
2871 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 lines
2925 # 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).default29312932 return None29332934 return super().get_default(ctx, call=call)
31 unmodified lines
2966 **prompt_kwargs,2967 )29682969 def resolve_envvar_value(self, ctx: Context) -> str | None:2970 """Find which environment variable to read for this option and return2971 its value.29722973 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.2981 """2982 rv = super().resolve_envvar_value(ctx)29832984 if rv is not None:2965 if self.is_flag and self.flag_value:2966 return str(self.flag_value)2985 return rv29862987 if (2988 self.allow_from_autoenv
8 unmodified lines
29972998 return None29993000 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)30033004 if rv is None:3005 return None30062988 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)30183019 # 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)29923022 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]30253026 return multi_rv30273028 return rv30293030 def consume_value(3031 self, ctx: Context, opts: cabc.Mapping[str, Parameter]
10 unmodified lines
3042 else:3043 value = self.flag_value3044 source = ParameterSource.COMMANDLINE30453046 # 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_value30563057 elif (3058 self.multiple3059 and value is not None3060 and any(v is _flag_needs_value for v in value)3061 ):
117 unmodified lines
modified:src/click/exceptions.py+3 added-3 removed
113 unmodified lines
114 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_hint
27 unmodified lines
150 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_type159160 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 = None
142 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/shell_completion.py+24 added-1 removed
122 unmodified lines
123124%(complete_func)s_setup;125"""126127# 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)s135136%(complete_func)s() {
241 unmodified lines
378379 return args, incomplete380381 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_}"397398399class FishComplete(ShellComplete):400 """Shell completion for Fish."""
3 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+14 added-1 removed
3 unmodified lines
4import contextlib5import io6import os7import shlex8import shutil8import sys9import tempfile10import typing as t11from types import TracebackType
85 unmodified lines
97 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)100101 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 close106107 .. versionadded:: 8.2.2108 """109 self.stderr.close()110 self.stdout.close()111 self.output.close()112113114class _NamedTextIOWrapper(io.TextIOWrapper):115 def __init__(116 self, buffer: t.BinaryIO, name: str, mode: str, **kwargs: t.Any117 ) -> None:
451 unmodified lines
569 finally:570 os.chdir(cwd)571572 if temp_dir is None:573 import shutil574575 try:576 shutil.rmtree(dt)577 except OSError:578 pass
modified:src/click/types.py+57 added-13 removed
659 unmodified lines
660661class BoolParamType(ParamType):662 name = "boolean"663664 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.681670 norm = value.strip().lower()682 Mapping is inspired by :py:attr:`configparser.ConfigParser.BOOLEAN_STATES`683 and extends it.684672 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.688675 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.692678 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 """696697 @staticmethod698 def str_to_bool(value: str | bool) -> bool | None:699 """Convert a string to a boolean value.700701 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.705706 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())711712 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 normalized725726 def __repr__(self) -> str:727 return "BOOL"728729
480 unmodified lines
modified:tests/test_arguments.py+9 added-13 removed
61 unmodified lines
62 assert result.exception is None63 assert result.output.splitlines() == ["name=peter id=1"]646566def test_nargs_mismatch_with_tuple_type():67 with pytest.raises(ValueError, match="nargs.*must be 2.*but it was 3"):6869 @click.command()70 @click.argument("test", type=(str, int), nargs=3)71 def cli(_):72 pass737475def test_nargs_err(runner):76 @click.command()77 @click.argument("x")78 def copy(x):
127 unmodified lines
206 else:207 assert result.return_value == expect208209201def 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 upper208209 # 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"212213210def 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 lines
modified:tests/test_basic.py+9 added-5 removed
220 unmodified lines
221 result = runner.invoke(cli, args, standalone_mode=False)222 assert result.return_value is expect223224225@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)234def 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 f239233 if default:234 expect = not expect235240 result = runner.invoke(cli, args, standalone_mode=False)241 assert result.return_value is expect242243
415 unmodified lines
modified:tests/test_imports.py+15 added-15 removed
25 unmodified lines
26"""2728ALLOWED_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}5455if WIN:56 ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time"])
14 unmodified lines
modified:tests/test_options.py+363 added-19 removed
1import enum2import os3import re4import sys56if sys.version_info < (3, 11):7 enum.StrEnum = enum.Enum # type: ignore[assignment]89import pytest1011import click12from click import Option
238 unmodified lines
251 assert not result.exception252 assert result.output == "foo|bar\n"253254250def 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)309def 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}")314256 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"318319320@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)332def 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}")337338 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 )344345346def 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 lines
676 result = runner.invoke(cli)677 assert result.exit_code == 2678 assert "Error: Missing option '--foo' (env var: 'bar')." in result.output679680 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.output686687688def 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 lines
1099 assert param.type is click.INT110011011102@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)1025def test_flag_value_is_correctly_set(runner, opts, pass_flag, expected):1190def 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))11951196 result = runner.invoke(cmd, ["--foo"] if pass_flag else [])1197 assert result.output == f"{expected!r}\n"119811991200@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)1209def 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)12141031 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 )122012211222@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)1253def test_envvar_flag_value(runner, flag_value, envvar_value, expected):1254 """Ensure that flag_value is recognized by the envvar."""12551256 @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))12621263 result = runner.invoke(cmd, env={"UPPER": envvar_value})1264 assert result.exit_code == 01265 assert result.output == f"{expected!r}\n"126612671268@pytest.mark.parametrize(1269 ("option", "expected"),1270 [1271 # Not boolean flags1272 pytest.param(Option(["-a"], type=int), False, id="int option"),
6 unmodified lines
1279 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)1050def test_is_bool_flag_is_correctly_set(option, expected):1283def test_bool_flag_auto_detection(option, expected):1284 assert option.is_bool_flag is expected128512861287@pytest.mark.parametrize(
23 unmodified lines
1311 result = runner.invoke(cmd)1312 assert result.exit_code == 0131313141315class HashType(enum.Enum):1316 MD5 = enum.auto()1317 SHA1 = enum.auto()131813191320class Number(enum.IntEnum):1321 ONE = enum.auto()1322 TWO = enum.auto()132313241325class Letter(enum.StrEnum):1326 A = enum.auto()1327 B = enum.auto()132813291330class Color(enum.Flag):1331 RED = enum.auto()1332 GREEN = enum.auto()1333 BLUE = enum.auto()133413351336class ColorInt(enum.IntFlag):1337 RED = enum.auto()1338 GREEN = enum.auto()1339 BLUE = enum.auto()134013411342@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)1357def test_usage_show_choices(runner, choices, metavars):1358 """When show_choices=False is set, the --help output
14 unmodified lines
1373 def cli_without_choices(g):1374 pass13751376 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 )13811382 result = runner.invoke(cli_without_choices, ["--help"])1383 assert metavars in result.output138413851386@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)1415def 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 pass14201421 # Check that the default value is kept normalized to the type of the choice.1422 assert cli_with_choices.params[0].default == default14231424 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.output143014311432@pytest.mark.parametrize(1433 "opts_one,opts_two",1434 [1435 # No duplicate shortnames1436 (
15 unmodified lines
1452 pass14531454 with pytest.warns(UserWarning):1455 runner.invoke(cli, [])145614571458@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)1478def 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
1import textwrap2import warnings3from collections.abc import Mapping45import pytest67import click.shell_completion
211 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):
2 unmodified lines
369 result = runner.invoke(cli, env=env)370 assert result.output == expect371372373@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")424def 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 == expect444445446@pytest.mark.usefixtures("_patch_for_completion")447def test_context_settings(runner):448 def complete(ctx, param, incomplete):449 return ctx.obj["choices"]450
111 unmodified lines
modified:tests/test_testing.py+2 added-4 removed
446 unmodified lines
447 runner = CliRunner()448449 with runner.isolation() as (_, err, _):450 click.echo("\udce2", err=True, nl=False)451 assert err.getvalue() == b"\\udce2"452452 assert err.getvalue() == b"\\udce2"453454454def 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()459460 with runner.isolation() as (_, err, _):461 click.echo("\udce2", err=True, nl=False)462 assert err.getvalue() == b"\\udce2"463464 assert err.getvalue() == b"\\udce2"465464 @click.command()465 def cli():466 # set end="", flush=False so that it's totally clear that we won't get any467 # auto-flush behaviors
4 unmodified lines
modified:tests/test_types.py+6 added-1 removed
224 unmodified lines
225)226def test_file_surrogates(type, tmp_path):227 path = tmp_path / "\udcff"228229 # - 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)236237238def test_file_error_surrogates():
19 unmodified lines
modified:CHANGES.rst+27 added
1.. currentmodule:: click23Version 8.2.x4-------------56Unreleased78- show correct auto complete value for nargs option in combination with flag option :issue:`2813`910Version 8.2.211-------------1213Released 2025-07-311415- 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`2930Version 8.2.131-------------3233Released 2025-05-20
1241 unmodified lines
modified:pyproject.toml+1 added-1 removed
1[project]2name = "click"3version = "8.2.1"3version = "8.2.2"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.2.2"143source = { editable = "." }144dependencies = [145 { name = "colorama", marker = "sys_platform == 'win32'" },146]
1076 unmodified lines