Merge stable into main. Resolve conflicts about test utils.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Edward G · committed by Edward G · parents 9ab346f, a44e9f0 · Browse files · 23 files·+405 added−111 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+405 added−111 removed
- tests:+230 added−5 removed
- other:+175 added−106 removed
Provenance
- Commit
ea811f9- Tree
a4abfeb- Author
Edward G <edward.g2013@gmail.com>- Committer
Edward G <edward.g2013@gmail.com>- Parent 1
9ab346f- Parent 2
a44e9f0
23 files changed+405 added−111 removed
modified:docs/api.md+4 added
40 unmodified lines41 .. autofunction:: version_option42 ```43 44 ```{eval-rst}45+.. autofunction:: custom_version_option46+```47+48+```{eval-rst}49 .. autofunction:: help_option50 ```51 52 ```{eval-rst}313 unmodified linesmodified:docs/arguments.md+4 added-1 removed
8 unmodified lines9101112131314151617181920212223166 unmodified linesExpand all8 unmodified lines
* Are positional in nature.* Similar to a limited version of {ref}`options <options>` that can take an arbitrary number of inputs* {ref}`Documented manually <documenting-arguments>`.* Can take an optional `help` string shown in the ``Positional arguments`` section of the help page, or be {ref}`documented in the command docstring <documenting-arguments>`.
Useful and often used kwargs are:
* `help`: Help text for the argument.* `default`: Passes a default.* `nargs`: Sets the number of arguments. Set to -1 to take an arbitrary number.
## Basic Arguments166 unmodified linesExpand allmodified:docs/changes.md-1 removed
12334# Changes
```{include} ../CHANGES.md```modified:docs/documentation.md+7 added-5 removed
13 unmodified lines14 ```{eval-rst}15 .. click:example::16 17 @click.command()18- @click.argument('name')18+ @click.argument('name', help='The name to print')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):89 unmodified lines112 (documenting-arguments)=113 114 ## Documenting Arguments115 116-{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 text117-by name. This should then be done via the docstring.116+{class}`click.argument` accepts an optional `help` parameter that is shown in117+the ``Positional arguments`` section of the help page. You can still document118+arguments in the command docstring, especially when you want to describe them119+in the main help text by name.120 121 A brief example:122 123 ```{eval-rst}124 .. click:example::125 126 @click.command()125- @click.argument('filename')127+ @click.argument('filename', help='The file to print.')128 def touch(filename):129 """Print FILENAME."""130 click.echo(filename)131 132 .. click:run::133 invoke(touch, args=['--help'])134 ```135 134-Or more explicitly:136+Or more explicitly in the docstring:137 138 ```{eval-rst}139 .. click:example::140 203 unmodified linesmodified:docs/quickstart.md+2 added-3 removed
22 unmodified lines23 - [validation](https://github.com/pallets/click/tree/main/examples/validation) : A simple example of an application that24 performs custom validation of parameters in different ways.25 - [naval](https://github.com/pallets/click/tree/main/examples/naval) : Port of the [docopt](http://docopt.org/) naval26 example.27-- [colors](https://github.com/pallets/click/tree/main/examples/colors) : A simple example that colorizes text. Uses28- colorama on Windows.27+- [colors](https://github.com/pallets/click/tree/main/examples/colors) : A simple example that colorizes text.28 - [aliases](https://github.com/pallets/click/tree/main/examples/aliases) : An advanced example that implements29 {ref}`aliases`.30 - [imagepipe](https://github.com/pallets/click/tree/main/examples/imagepipe) : A complex example that implements some31 {ref}`command-pipelines` . It chains together image processing instructions. Requires pillow.47 unmodified lines79 What this means is that the {func}`echo` function applies some error correction in case the terminal is misconfigured80 instead of dying with a {exc}`UnicodeError`.81 82 The echo function also supports color and other styles in output. It will automatically remove styles if the output84-stream is a file. On Windows, colorama is automatically installed and used. See {ref}`ansi-colors`.83+stream is a file. See {ref}`ansi-colors`.84 85 If you don't need this, you can also use the `print()` construct / function.86 87 ## Nesting Commands108 unmodified linesmodified:docs/utils.md+17 added-9 removed
50 unmodified lines51 52 ```{versionadded} 2.053 ```54 55-The {func}`echo` function supports ANSI colors and styles. On Windows this uses [colorama](https://pypi.org/project/colorama/).55+The {func}`echo` function supports ANSI colors and styles. It will56+automatically strip ANSI color codes if the stream is not connected to a57+terminal.58 57-Primarily this means that:59+:::{admonition} Older Windows Support60+:class: note61 59-- Click's {func}`echo` function will automatically strip ANSI color codes if the stream is not connected to a terminal.60-- the {func}`echo` function will transparently connect to the terminal on Windows and translate ANSI codes to terminal61- API calls. This means that colors will work on Windows the same way they do on other operating systems.62+Recent Windows 11 supports ANSI styling by default, in both Terminal and cmd.exe.63+If you need to support color output on older versions of Windows, install64+[colorama](https://pypi.org/project/colorama/) and call `colorama.init()`.65+:::66 63-On Windows, Click uses colorama without calling `colorama.init()`. You can still call that in your code, but it's not64-required for Click.65-67 For styling a string, the {func}`style` function can be used:68 69 ```python70 import click52 unmodified lines123 for idx in range(50000):124 print(idx, file=pager)125 ```126 127+```{hint} Why print instead of echo?128+The pager object deals with ANSI color and style codes itself: they are kept or129+stripped depending on what the pager supports, exactly as {func}`echo` would do.130+Any code that writes to a file, including plain {func}`print`, can therefore be131+used with it.132+```133+134 ## Screen Clearing135 136 ```{versionadded} 2.0137 ```247 unmodified lines385 import time386 387 with click.progressbar([1, 2, 3]) as bar:388 for x in bar:381- print(f"sleep({x})...")389+ click.echo(f"sleep({x})...")390 time.sleep(x)391 ```392 393 Another useful feature is to associate a label with the progress bar which will be shown preceding the progress bar:20 unmodified linesmodified:examples/colors/README-2 removed
1 unmodified line2 3 colors is a simple example that shows how you can4 colorize text.5 6- Uses colorama on Windows.7-6 Usage:7 8 $ pip install --editable .9 $ colorsmodified:src/click/__init__.py+1 added
16 unmodified lines17 from .core import ParameterSource as ParameterSource18 from .decorators import argument as argument19 from .decorators import command as command20 from .decorators import confirmation_option as confirmation_option21+from .decorators import custom_version_option as custom_version_option22 from .decorators import group as group23 from .decorators import help_option as help_option24 from .decorators import make_pass_decorator as make_pass_decorator25 from .decorators import option as option102 unmodified linesmodified:src/click/_compat.py+1 added-41 removed
10 unmodified lines11 from weakref import WeakKeyDictionary12 13 CYGWIN = sys.platform.startswith("cygwin")14 WIN = sys.platform.startswith("win")15-auto_wrap_for_ansi: t.Callable[[t.TextIO], t.TextIO] | None = None15 _ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")16 17 18 def _make_text_stream(489 unmodified lines508 return not isatty(stream) and not _is_jupyter_kernel_output(stream)509 return not color510 511 513-# On Windows, wrap the output streams with colorama to support ANSI514-# color codes.515-# NOTE: double check is needed so mypy does not analyze this on Linux512+# double check is needed so mypy does not analyze this on Linux513 if sys.platform.startswith("win") and WIN:514 from ._winconsole import _get_windows_console_stream515 516 def _get_argv_encoding() -> str:517 import locale518 519 return locale.getpreferredencoding()520 524- _ansi_stream_wrappers: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()525-526- def auto_wrap_for_ansi(stream: t.TextIO, color: bool | None = None) -> t.TextIO:527- """Support ANSI color and style codes on Windows by wrapping a528- stream with colorama.529- """530- try:531- cached = _ansi_stream_wrappers.get(stream)532- except Exception:533- cached = None534-535- if cached is not None:536- return cached537-538- import colorama539-540- strip = should_strip_ansi(stream, color)541- ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip)542- rv = t.cast(t.TextIO, ansi_wrapper.stream)543- _write = rv.write544-545- def _safe_write(s: str) -> int:546- try:547- return _write(s)548- except BaseException:549- ansi_wrapper.reset_all()550- raise551-552- rv.write = _safe_write # type: ignore[method-assign]553-554- try:555- _ansi_stream_wrappers[stream] = rv556- except Exception:557- pass558-559- return rv560-521 else:522 523 def _get_argv_encoding() -> str:524 return getattr(sys.stdin, "encoding", None) or sys.getfilesystemencoding()62 unmodified linesmodified:src/click/core.py+43 added-1 removed
1214 unmodified lines1215 This calls the following methods:1216 1217 - :meth:`format_usage`1218 - :meth:`format_help_text`1219+ - :meth:`format_arguments`1220 - :meth:`format_options`1221 - :meth:`format_epilog`1222 """1223 self.format_usage(ctx, formatter)1224 self.format_help_text(ctx, formatter)1225+ self.format_arguments(ctx, formatter)1226 self.format_options(ctx, formatter)1227 self.format_epilog(ctx, formatter)1228 1229 def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None:18 unmodified lines1248 """Writes all the options into the formatter if they exist."""1249 opts = []1250 for param in self.get_params(ctx):1251 rv = param.get_help_record(ctx)1250- if rv is not None:1252+ if rv is not None and not isinstance(param, Argument):1253 opts.append(rv)1254 1255 if opts:1256 with formatter.section(_("Options")):1257 formatter.write_dl(opts)1258 1259+ def format_arguments(self, ctx: Context, formatter: HelpFormatter) -> None:1260+ """Writes the arguments that have a help record into the formatter."""1261+ args = []1262+ for param in self.get_params(ctx):1263+ rv = param.get_help_record(ctx)1264+ if rv is not None and isinstance(param, Argument):1265+ args.append(rv)1266+1267+ if args:1268+ with formatter.section(_("Positional arguments")):1269+ formatter.write_dl(args)1270+1271 def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None:1272 """Writes the epilog into the formatter if it exists."""1273 if self.epilog:1274 epilog = inspect.cleandoc(self.epilog)2272 unmodified lines3547 provide fewer features than options but can have infinite ``nargs``3548 and are required by default.3549 3550 All parameters are passed onwards to the constructor of :class:`Parameter`.3551+3552+ :param help: the help string.3553+3554+ .. versionchanged:: 8.53555+ Added the ``help`` parameter.3556 """3557 3558 param_type_name = "argument"3559 3560 def __init__(3561 self,3562 param_decls: cabc.Sequence[str],3563 required: bool | None = None,3564+ help: str | None = None,3565 **attrs: t.Any,3566 ) -> None:3567 # Auto-detect the requirement status of the argument if not explicitly set.3568 if required is None:7 unmodified lines3576 3577 if "multiple" in attrs:3578 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.")3579 3580+ deprecated = attrs.get("deprecated", False)3581+3582+ if help:3583+ help = inspect.cleandoc(help)3584+3585+ if deprecated:3586+ label = _format_deprecated_label(deprecated)3587+ help = f"{help} {label}" if help else label3588+3589+ self.help = help3590+3591 super().__init__(param_decls, required=required, **attrs)3592 3593+ def to_info_dict(self) -> dict[str, t.Any]:3594+ info_dict = super().to_info_dict()3595+ info_dict.update(help=self.help)3596+ return info_dict3597+3598 @property3599 def human_readable_name(self) -> str:3600 if self.metavar is not None:3601 return self.metavar39 unmodified lines3641 3642 def get_usage_pieces(self, ctx: Context) -> list[str]:3643 return [self.make_metavar(ctx)]3644 3645+ def get_help_record(self, ctx: Context) -> tuple[str, str] | None:3646+ if self.help is None:3647+ return None3648+3649+ return self.make_metavar(ctx), self.help3650+3651 def get_error_hint(self, ctx: Context | None) -> str:3652 if ctx is not None:3653 return f"'{self.make_metavar(ctx)}'"3654 return f"'{self.human_readable_name}'"27 unmodified linesmodified:src/click/decorators.py+52 added
438 unmodified lines439 (top-level module) name via440 :func:`importlib.metadata.packages_distributions`, so e.g. ``PIL``441 resolves to the ``Pillow`` distribution.442 443+ .. note::444+ The parameters and message variables accepted by this option are445+ frozen: no new slots will be added, to keep the common case simple446+ and predictable. If you need values it does not expose, such as a447+ file path, the Python version, or git metadata, use448+ :func:`custom_version_option` to render the output yourself.449+450+ Rationale: `discussion #3527451+ <https://github.com/pallets/click/discussions/3527>`_.452+453 :param version: The version number to show. If not provided, Click454 will try to detect it.455 :param param_decls: One or more option names. Defaults to the single456 value ``"--version"``.100 unmodified lines557 kwargs["callback"] = callback558 return option(*param_decls, **kwargs)559 560 561+def custom_version_option(562+ callback: t.Callable[[Context], str],563+ *param_decls: str,564+ **kwargs: t.Any,565+) -> t.Callable[[FC], FC]:566+ """Add a ``--version`` option whose output is produced by ``callback``.567+568+ This is the customizable companion to :func:`version_option`. Where569+ :func:`version_option` is intentionally limited to a fixed message and570+ a small set of values, this option calls ``callback`` to build the571+ whole string to print. Use it when you need values that572+ :func:`version_option` does not expose, such as a file path, the573+ Python version, or git metadata.574+575+ :param callback: Called with the current :class:`Context` when the576+ option is invoked. Its return value is printed, then the program577+ exits.578+ :param param_decls: One or more option names. Defaults to the single579+ value ``--version``.580+ :param kwargs: Extra arguments are passed to :func:`option`.581+582+ .. versionadded:: 8.5.0583+ """584+585+ def show_version(ctx: Context, param: Parameter, value: bool) -> None:586+ if not value or ctx.resilient_parsing:587+ return588+589+ echo(callback(ctx), color=ctx.color)590+ ctx.exit()591+592+ if not param_decls:593+ param_decls = ("--version",)594+595+ kwargs.setdefault("is_flag", True)596+ kwargs.setdefault("expose_value", False)597+ kwargs.setdefault("is_eager", True)598+ kwargs.setdefault("help", _("Show the version and exit."))599+ kwargs["callback"] = show_version600+ return option(*param_decls, **kwargs)601+602+603 def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:604 """Pre-configured ``--help`` option which immediately prints the help page605 and exits the program.606 21 unmodified linesmodified:src/click/shell_completion.py+2 added-3 removed
524 unmodified lines525 526 lex = shlex.shlex(string, posix=True)527 lex.whitespace_split = True528 lex.commenters = ""529- out = []529+ out = [] # type: list[str]530 531 try:532- for token in lex:533- out.append(token)532+ out.extend(lex)533 except ValueError:534 # Raised when end-of-string is reached in an invalid state. Use535 # the partial token as-is. The quote or escape character is in536 # lex.state, not lex.token.168 unmodified linesmodified:src/click/termui.py+15 added-12 removed
9 unmodified lines10 from contextlib import AbstractContextManager11 from contextlib import redirect_stdout12 from gettext import gettext as _13 14+from . import _compat15 from ._compat import isatty16 from ._compat import strip_ansi16-from ._compat import WIN17 from .exceptions import Abort18 from .exceptions import UsageError19 from .globals import resolve_color_default20 from .types import Choice60 unmodified lines81 return getpass.getpass(prompt)82 83 84 def _readline_prompt(func: t.Callable[[str], str], text: str, err: bool) -> str:85- """Call a prompt function, passing the full prompt on non-Windows so86- readline can handle line editing and cursor positioning correctly.85+ """Call a prompt function, passing the full prompt so readline can86+ handle line editing and cursor positioning correctly.87 88- On Windows the prompt is written separately via :func:`echo` for89- colorama support, with only the last character passed to *func*.88+ The prompt is handed to *func* (such as :func:`input`) rather than89+ written through :func:`echo`, so it has to strip ANSI color and style90+ codes itself when the destination stream does not support them. Without91+ this the prompt would keep codes that :func:`echo` removes from the92+ rest of the output.93 """91- if WIN:92- # Write the prompt separately so that we get nice coloring93- # through colorama on Windows.94- echo(text[:-1], nl=False, err=err)95- # Echo the last character to stdout to work around an issue96- # where readline causes backspace to clear the whole line.97- return func(text[-1:])94+ stream = sys.stderr if err else sys.stdout95+96+ # Look up ``should_strip_ansi`` on the module so that ``CliRunner``,97+ # which patches it there during test isolation, is honored.98+ if _compat.should_strip_ansi(stream, resolve_color_default()):99+ text = strip_ansi(text)100+101 if err:102 with redirect_stdout(sys.stderr):103 return func(text)104 return func(text)844 unmodified linesmodified:src/click/types.py+2 added-1 removed
1102 unmodified lines1103 ctx: Context | None,1104 ) -> str | bytes | os.PathLike[str]:1105 rv = value1106 1107+ dash = b"-" if isinstance(rv, bytes) else "-"1107- is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")1108+ is_dash = self.file_okay and self.allow_dash and rv == dash1109 1110 if not is_dash:1111 if self.resolve_path:1112 rv = os.path.realpath(rv)263 unmodified linesmodified:src/click/utils.py+5 added-12 removed
11 unmodified lines12 13 from ._compat import _default_text_stderr14 from ._compat import _default_text_stdout15 from ._compat import _find_binary_writer16-from ._compat import auto_wrap_for_ansi16 from ._compat import binary_streams17 from ._compat import open_stream18 from ._compat import should_strip_ansi19 from ._compat import strip_ansi238 unmodified lines258 - Ensures that the output encoding is not misconfigured on Linux.259 - Supports Unicode in the Windows console.260 - Supports writing to binary outputs, and supports writing bytes261 to text outputs.263- - Supports colors and styles on Windows.262 - Removes ANSI color and style codes if the output does not look263 like an interactive terminal.264 - Always flushes the output.265 5 unmodified lines271 :param color: Force showing or hiding colors and other styles. By272 default Click will remove color if the output does not look like273 an interactive terminal.274 275+ .. versionchanged:: 8.5276+ Colorama is no longer used for color on Windows.277+278 .. versionchanged:: 6.0279 Support Unicode output on the Windows console. Click does not280 modify ``sys.stdout``, so ``sys.stdout.write()`` and ``print()``281 will still not support Unicode.49 unmodified lines331 return332 333 # ANSI style code support. For no message or bytes, nothing happens.334 # When outputting to a file instead of a terminal, strip codes.334- else:335- color = resolve_color_default(color)335+ elif should_strip_ansi(file, resolve_color_default(color)):336+ out = strip_ansi(out)337 337- if should_strip_ansi(file, color):338- out = strip_ansi(out)339- elif WIN:340- if auto_wrap_for_ansi is not None:341- file = auto_wrap_for_ansi(file, color) # type: ignore342- elif not color:343- out = strip_ansi(out)344-338 file.write(out) # type: ignore339 file.flush()340 341 305 unmodified linesmodified:tests/test_arguments.py+88 added
293 unmodified lines294 assert result.exit_code == 0295 assert result.output == "test\n"296 297 298+def test_argument_help(runner):299+ @click.command()300+ @click.argument("name", help="The name to print")301+ @click.option("--count", default=1, help="number of greetings")302+ def cli(name, count):303+ pass304+305+ result = runner.invoke(cli, ["--help"])306+ assert result.exit_code == 0, result.output307+ assert "Positional arguments:" in result.output308+ assert "NAME" in result.output309+ assert "The name to print" in result.output310+ assert "Options:" in result.output311+ assert "number of greetings" in result.output312+ assert result.output.index("Positional arguments:") < result.output.index(313+ "Options:"314+ )315+316+317+def test_argument_help_options_only_no_arguments_section(runner):318+ @click.command()319+ @click.option("--count", default=1, help="number of greetings")320+ def cli(count):321+ pass322+323+ result = runner.invoke(cli, ["--help"])324+ assert result.exit_code == 0, result.output325+ assert "Positional arguments:" not in result.output326+ assert "Options:" in result.output327+ assert "number of greetings" in result.output328+329+330+def test_argument_help_optional_metavar(runner):331+ @click.command()332+ @click.argument("name", required=False, default="", help="The name to print")333+ def cli(name):334+ pass335+336+ result = runner.invoke(cli, ["--help"])337+ assert result.exit_code == 0, result.output338+ assert "[NAME]" in result.output339+ assert "The name to print" in result.output340+341+342 def test_deprecated_usage(runner):343 @click.command()344 @click.argument("f", required=False, deprecated=True)345 def cli(f):29 unmodified lines375 assert result.exit_code == 0376 assert result.output.splitlines()[0] == f"Usage: cli [OPTIONS] {expected}"377 378 379+@pytest.mark.parametrize(380+ ("deprecated", "expected_label"),381+ [(True, "(DEPRECATED)"), ("use g instead", "(DEPRECATED: use g instead)")],382+)383+def test_deprecated_usage_help_record(runner, deprecated, expected_label):384+ @click.command()385+ @click.argument("f", required=False, deprecated=deprecated, help="path to the file")386+ def cli(f):387+ click.echo(f)388+389+ result = runner.invoke(cli, ["--help"])390+ assert result.exit_code == 0, result.output391+ assert "Positional arguments:" in result.output392+ assert "[F!]" in result.output393+ assert f"path to the file {expected_label}" in result.output394+395+396+def test_deprecated_usage_help_record_without_help(runner):397+ @click.command()398+ @click.argument("f", required=False, deprecated=True)399+ def cli(f):400+ click.echo(f)401+402+ result = runner.invoke(cli, ["--help"])403+ assert result.exit_code == 0, result.output404+ # Deprecation alone produces a help row with just the deprecation label.405+ assert "Positional arguments:" in result.output406+ assert "(DEPRECATED)" in result.output407+408+409+@pytest.mark.parametrize(410+ ("deprecated", "expected"),411+ [(True, "(DEPRECATED)"), ("USE B INSTEAD", "(DEPRECATED: USE B INSTEAD)")],412+)413+@pytest.mark.parametrize("help_text", ["", None])414+def test_deprecated_empty_help_no_leading_space(help_text, deprecated, expected):415+ """An argument with empty or missing help text must not gain a stray leading416+ space before the deprecation label.417+ """418+ arg = click.Argument(["foo"], required=False, help=help_text, deprecated=deprecated)419+ ctx = click.Context(click.Command("cli"))420+ assert arg.get_help_record(ctx)[1] == expected421+422+423 @pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])424 def test_deprecated_warning(runner, deprecated):425 @click.command()426 @click.argument(317 unmodified linesmodified:tests/test_basic.py+27 added-5 removed
1 from __future__ import annotations2 3 import enum4 import os5-from itertools import chain5 6 import pytest7 8 import click247 unmodified lines256 257 258 @pytest.mark.parametrize(259 ("value", "expect"),261- chain(262- ((x, "True") for x in ("1", "true", "t", "yes", "y", "on")),263- ((x, "False") for x in ("0", "false", "f", "no", "n", "off")),264- ),260+ [261+ *((x, "True") for x in ("1", "true", "t", "yes", "y", "on")),262+ *((x, "False") for x in ("0", "false", "f", "no", "n", "off")),263+ ],264 )265 def test_boolean_conversion(runner, value, expect):266 @click.command()267 @click.option("--flag", type=bool)588 unmodified lines856 857 result = runner.invoke(cli, ["--version"])858 assert result.exit_code != 0859 assert "not installed" in str(result.exception)860+861+862+@pytest.mark.parametrize("args", [["--version"], ["-V"]])863+def test_custom_version_option(runner, args):864+ @click.command()865+ @click.custom_version_option(lambda ctx: "custom 9.9.9", "-V", "--version")866+ def cli():867+ pass868+869+ result = runner.invoke(cli, args)870+ assert result.exit_code == 0871+ assert result.output == "custom 9.9.9\n"872+873+874+def test_custom_version_option_receives_context(runner):875+ @click.command()876+ @click.custom_version_option(lambda ctx: f"{ctx.info_name} 1.0")877+ def cli():878+ pass879+880+ result = runner.invoke(cli, ["--version"], prog_name="mytool")881+ assert result.exit_code == 0882+ assert result.output == "mytool 1.0\n"modified:tests/test_info_dict.py+40 added
38 unmodified lines39 "nargs": 1,40 "multiple": False,41 "default": None,42 "envvar": None,43+ "help": None,44 },45 )46 NUMBER_OPTION = (47 click.Option(["-c", "--count", "number"], default=1),225 unmodified lines273 class TestType(click.ParamType):274 pass275 276 assert TestType().to_info_dict()["name"] == "TestType"277+278+279+@pytest.mark.parametrize(280+ ("help_in", "help_out"),281+ [282+ pytest.param(None, None, id="None"),283+ pytest.param("", "", id="empty"),284+ pytest.param("single line", "single line", id="single-line"),285+ pytest.param(286+ "\n first line\n second line\n ",287+ "first line\nsecond line",288+ id="multi-line",289+ ),290+ ],291+)292+def test_argument_to_info_dict_help(help_in, help_out):293+ arg = click.Argument(["name"], help=help_in)294+ assert arg.to_info_dict()["help"] == help_out295+296+297+def test_argument_to_info_dict_nargs():298+ arg = click.Argument(["files"], nargs=-1, help="files to process")299+ info = arg.to_info_dict()300+ assert info["nargs"] == -1301+ assert info["help"] == "files to process"302+303+304+def test_command_to_info_dict_multiple_arguments():305+ @click.command()306+ @click.argument("src", help="source path")307+ @click.argument("dst", help="destination path")308+ def cli(src, dst):309+ pass310+311+ ctx = click.Context(cli)312+ params = cli.to_info_dict(ctx)["params"]313+ args = [p for p in params if p["param_type_name"] == "argument"]314+ assert [p["name"] for p in args] == ["src", "dst"]315+ assert [p["help"] for p in args] == ["source path", "destination path"]modified:tests/test_termui.py+50 added
1020 unmodified lines1021 if prompt == "Confirm Password":1022 assert "Confirm Password: " in result.output1023 1024 1025+@pytest.mark.parametrize(1026+ ("call", "user_input", "color", "expect"),1027+ [1028+ pytest.param(1029+ lambda: click.confirm(click.style("Hello World!", fg="green")),1030+ "y",1031+ False,1032+ "Hello World! [y/N]: y\n",1033+ id="confirm-no-color",1034+ ),1035+ pytest.param(1036+ lambda: click.confirm(click.style("Hello World!", fg="green")),1037+ "y",1038+ True,1039+ "\x1b[32mHello World!\x1b[0m [y/N]: y\n",1040+ id="confirm-color",1041+ ),1042+ pytest.param(1043+ lambda: click.prompt(click.style("Name", fg="green")),1044+ "Bob",1045+ False,1046+ "Name: Bob\n",1047+ id="prompt-no-color",1048+ ),1049+ pytest.param(1050+ lambda: click.prompt(click.style("Name", fg="green")),1051+ "Bob",1052+ True,1053+ "\x1b[32mName\x1b[0m: Bob\n",1054+ id="prompt-color",1055+ ),1056+ ],1057+)1058+def test_prompt_and_confirm_ansi_respects_color(1059+ runner, call, user_input, color, expect1060+):1061+ """``confirm`` and ``prompt`` strip ANSI color and style codes from the1062+ prompt when color is disabled and keep them when it is enabled, like1063+ ``echo``. The prompt is written by ``input`` rather than ``echo``, so it1064+ used to keep the codes regardless (issue 3572).1065+ """1066+1067+ @click.command()1068+ def cli():1069+ call()1070+1071+ result = runner.invoke(cli, input=user_input, color=color)1072+ assert result.output == expect1073+1074+1075 def test_false_show_default_cause_no_default_display_in_prompt(runner):1076 @click.command()1077 @click.option("--arg1", show_default=False, prompt=True, default="my-default-value")1078 def cmd(arg1):534 unmodified linesmodified:tests/test_types.py+25 added
1 import os.path2 import pathlib3 import platform4+import subprocess5+import sys6 import tempfile7 8 import pytest9 116 unmodified lines126 assert result.exception is None127 assert result.return_value == expect128 129 130+def test_path_dash_no_byteswarning():131+ """Detecting the ``-`` dash sentinel must not compare ``bytes`` against132+ ``str``, which raises a ``BytesWarning`` under ``python -bb``.133+134+ The warning is only emitted when the interpreter runs with ``-b``, so this135+ has to be checked in a subprocess. ``-bb`` turns the warning into an error,136+ so a clean exit means no mismatched comparison happened.137+ """138+ program = (139+ "import click\n"140+ "convert = click.Path(allow_dash=True).convert\n"141+ "for value in ('-', '', b'-', b''):\n"142+ " convert(value, None, None)\n"143+ )144+ result = subprocess.run(145+ [sys.executable, "-bb", "-c", program],146+ capture_output=True,147+ text=True,148+ )149+ assert result.returncode == 0, result.stderr150+ assert "BytesWarning" not in result.stderr151+152+153 def _symlinks_supported():154 with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:155 target = os.path.join(tempdir, "target")156 open(target, "w").close()154 unmodified linesmodified:CHANGES.md+18 added
1+## Version 8.5.02+3+Unreleased4+5+- Supported versions of Windows enable ANSI terminal styles by default.6+ Colorama is no longer a dependency and is not used. {issue}`2986` {pr}`3505`7+- {class}`Argument` accepts a `help` parameter, and help output includes8+ a `Positional arguments` section when argument help is available. {issue}`2983` {pr}`3473`9+- `confirm()` and `prompt()` strip ANSI color and style codes from the10+ prompt when the output stream does not support them, matching `echo()`.11+ This stripping was lost in `8.4.0` when {pr}`2969` began writing the12+ prompt with `input()` directly. {issue}`3572` {pr}`3653`13+- Fix test failures when using pytest >= 9.1. {pr}`3656`14+- Add {func}`custom_version_option`, a `--version` option whose output is15+ produced by a callback, covering cases {func}`version_option` intentionally16+ does not. The feature set of {func}`version_option` is now frozen; see17+ [discussion #3527](https://github.com/pallets/click/discussions/3527). {pr}`3581`18+19 ## Version 8.4.220 21 Released 2026-06-2422 1560 unmodified linesmodified:pyproject.toml+1 added-10 removed
1 [project]2 name = "click"3-version = "8.4.2"3+version = "8.5.0.dev"4 description = "Composable command line interface toolkit"5 readme = "README.md"6 license = "BSD-3-Clause"7 license-files = ["LICENSE.txt"]5 unmodified lines13 "Programming Language :: Python",14 "Typing :: Typed",15 ]16 requires-python = ">=3.10"17-dependencies = [18- "colorama; platform_system == 'Windows'",19-]17 18 [project.urls]19 Donate = "https://palletsprojects.com/donate"20 Documentation = "https://click.palletsprojects.com/"89 unmodified lines110 show_error_codes = true111 pretty = true112 strict = true113 117-[[tool.mypy.overrides]]118-module = [119- "colorama.*",120-]121-ignore_missing_imports = true122-114 [tool.pyright]115 pythonVersion = "3.10"116 include = ["src", "tests/typing"]117 typeCheckingMode = "basic"114 unmodified linesmodified:uv.lock+1 added-5 removed
171 unmodified lines172 ]173 174 [[package]]175 name = "click"176-version = "8.4.2"176+version = "8.5.0.dev0"177 source = { editable = "." }178-dependencies = [179- { name = "colorama", marker = "sys_platform == 'win32'" },180-]178 179 [package.dev-dependencies]180 dev = [181 { name = "ruff" },35 unmodified lines217 { name = "pytest" },218 ]219 220 [package.metadata]224-requires-dist = [{ name = "colorama", marker = "sys_platform == 'win32'" }]221 222 [package.metadata.requires-dev]223 dev = [224 { name = "ruff" },1437 unmodified lines