Skip to content
Myr

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

23 files+405 added−111 removed

modified:docs/api.md+4 added
40 unmodified lines
41.. autofunction:: version_option42```4344```{eval-rst}45.. autofunction:: custom_version_option46```4748```{eval-rst}49.. autofunction:: help_option50```5152```{eval-rst}
313 unmodified lines
modified:docs/arguments.md+4 added-1 removed
modified:docs/changes.md-1 removed
modified:docs/documentation.md+7 added-5 removed
13 unmodified lines
14```{eval-rst}15.. click:example::1617 @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 lines
112(documenting-arguments)=113114## Documenting Arguments115116{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 text117by name. This should then be done via the docstring.116{class}`click.argument` accepts an optional `help` parameter that is shown in117the ``Positional arguments`` section of the help page. You can still document118arguments in the command docstring, especially when you want to describe them119in the main help text by name.120121A brief example:122123```{eval-rst}124.. click:example::125126 @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)131132.. click:run::133 invoke(touch, args=['--help'])134```135134Or more explicitly:136Or more explicitly in the docstring:137138```{eval-rst}139.. click:example::140
203 unmodified lines
modified:docs/quickstart.md+2 added-3 removed
22 unmodified lines
23- [validation](https://github.com/pallets/click/tree/main/examples/validation) : A simple example of an application that24 performs custom validation of parameters in different ways.25- [naval](https://github.com/pallets/click/tree/main/examples/naval) : Port of the [docopt](http://docopt.org/) naval26 example.27- [colors](https://github.com/pallets/click/tree/main/examples/colors) : A simple example that colorizes text. Uses28 colorama on Windows.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 lines
79What this means is that the {func}`echo` function applies some error correction in case the terminal is misconfigured80instead of dying with a {exc}`UnicodeError`.8182The echo function also supports color and other styles in output. It will automatically remove styles if the output84stream is a file. On Windows, colorama is automatically installed and used. See {ref}`ansi-colors`.83stream is a file. See {ref}`ansi-colors`.8485If you don't need this, you can also use the `print()` construct / function.8687## Nesting Commands
108 unmodified lines
modified:docs/utils.md+17 added-9 removed
50 unmodified lines
5152```{versionadded} 2.053```5455The {func}`echo` function supports ANSI colors and styles. On Windows this uses [colorama](https://pypi.org/project/colorama/).55The {func}`echo` function supports ANSI colors and styles. It will56automatically strip ANSI color codes if the stream is not connected to a57terminal.5857Primarily this means that:59:::{admonition} Older Windows Support60:class: note6159- 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.62Recent Windows 11 supports ANSI styling by default, in both Terminal and cmd.exe.63If you need to support color output on older versions of Windows, install64[colorama](https://pypi.org/project/colorama/) and call `colorama.init()`.65:::6663On Windows, Click uses colorama without calling `colorama.init()`. You can still call that in your code, but it's not64required for Click.6567For styling a string, the {func}`style` function can be used:6869```python70import click
52 unmodified lines
123 for idx in range(50000):124 print(idx, file=pager)125```126127```{hint} Why print instead of echo?128The pager object deals with ANSI color and style codes itself: they are kept or129stripped depending on what the pager supports, exactly as {func}`echo` would do.130Any code that writes to a file, including plain {func}`print`, can therefore be131used with it.132```133134## Screen Clearing135136```{versionadded} 2.0137```
247 unmodified lines
385import time386387with 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```392393Another useful feature is to associate a label with the progress bar which will be shown preceding the progress bar:
20 unmodified lines
modified:examples/colors/README-2 removed
1 unmodified line
23 colors is a simple example that shows how you can4 colorize text.56 Uses colorama on Windows.76Usage:78 $ pip install --editable .9 $ colors
modified:src/click/__init__.py+1 added
16 unmodified lines
17from .core import ParameterSource as ParameterSource18from .decorators import argument as argument19from .decorators import command as command20from .decorators import confirmation_option as confirmation_option21from .decorators import custom_version_option as custom_version_option22from .decorators import group as group23from .decorators import help_option as help_option24from .decorators import make_pass_decorator as make_pass_decorator25from .decorators import option as option
102 unmodified lines
modified:src/click/_compat.py+1 added-41 removed
10 unmodified lines
11from weakref import WeakKeyDictionary1213CYGWIN = sys.platform.startswith("cygwin")14WIN = sys.platform.startswith("win")15auto_wrap_for_ansi: t.Callable[[t.TextIO], t.TextIO] | None = None15_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")161718def _make_text_stream(
489 unmodified lines
508 return not isatty(stream) and not _is_jupyter_kernel_output(stream)509 return not color510511513# 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 Linux513if sys.platform.startswith("win") and WIN:514 from ._winconsole import _get_windows_console_stream515516 def _get_argv_encoding() -> str:517 import locale518519 return locale.getpreferredencoding()520524 _ansi_stream_wrappers: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()525526 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 = None534535 if cached is not None:536 return cached537538 import colorama539540 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.write544545 def _safe_write(s: str) -> int:546 try:547 return _write(s)548 except BaseException:549 ansi_wrapper.reset_all()550 raise551552 rv.write = _safe_write # type: ignore[method-assign]553554 try:555 _ansi_stream_wrappers[stream] = rv556 except Exception:557 pass558559 return rv560521else:522523 def _get_argv_encoding() -> str:524 return getattr(sys.stdin, "encoding", None) or sys.getfilesystemencoding()
62 unmodified lines
modified:src/click/core.py+43 added-1 removed
1214 unmodified lines
1215 This calls the following methods:12161217 - :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)12281229 def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None:
18 unmodified lines
1248 """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)12541255 if opts:1256 with formatter.section(_("Options")):1257 formatter.write_dl(opts)12581259 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)12661267 if args:1268 with formatter.section(_("Positional arguments")):1269 formatter.write_dl(args)12701271 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 lines
3547 provide fewer features than options but can have infinite ``nargs``3548 and are required by default.35493550 All parameters are passed onwards to the constructor of :class:`Parameter`.35513552 :param help: the help string.35533554 .. versionchanged:: 8.53555 Added the ``help`` parameter.3556 """35573558 param_type_name = "argument"35593560 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 lines
35763577 if "multiple" in attrs:3578 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.")35793580 deprecated = attrs.get("deprecated", False)35813582 if help:3583 help = inspect.cleandoc(help)35843585 if deprecated:3586 label = _format_deprecated_label(deprecated)3587 help = f"{help} {label}" if help else label35883589 self.help = help35903591 super().__init__(param_decls, required=required, **attrs)35923593 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_dict35973598 @property3599 def human_readable_name(self) -> str:3600 if self.metavar is not None:3601 return self.metavar
39 unmodified lines
36413642 def get_usage_pieces(self, ctx: Context) -> list[str]:3643 return [self.make_metavar(ctx)]36443645 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:3646 if self.help is None:3647 return None36483649 return self.make_metavar(ctx), self.help36503651 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 lines
modified:src/click/decorators.py+52 added
438 unmodified lines
439 (top-level module) name via440 :func:`importlib.metadata.packages_distributions`, so e.g. ``PIL``441 resolves to the ``Pillow`` distribution.442443 .. 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.449450 Rationale: `discussion #3527451 <https://github.com/pallets/click/discussions/3527>`_.452453 :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 lines
557 kwargs["callback"] = callback558 return option(*param_decls, **kwargs)559560561def 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``.567568 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.574575 :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`.581582 .. versionadded:: 8.5.0583 """584585 def show_version(ctx: Context, param: Parameter, value: bool) -> None:586 if not value or ctx.resilient_parsing:587 return588589 echo(callback(ctx), color=ctx.color)590 ctx.exit()591592 if not param_decls:593 param_decls = ("--version",)594595 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)601602603def 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 lines
modified:src/click/shell_completion.py+2 added-3 removed
524 unmodified lines
525526 lex = shlex.shlex(string, posix=True)527 lex.whitespace_split = True528 lex.commenters = ""529 out = []529 out = [] # type: list[str]530531 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 lines
modified:src/click/termui.py+15 added-12 removed
9 unmodified lines
10from contextlib import AbstractContextManager11from contextlib import redirect_stdout12from gettext import gettext as _1314from . import _compat15from ._compat import isatty16from ._compat import strip_ansi16from ._compat import WIN17from .exceptions import Abort18from .exceptions import UsageError19from .globals import resolve_color_default20from .types import Choice
60 unmodified lines
81 return getpass.getpass(prompt)828384def _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.8788 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.stdout9596 # 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)100101 if err:102 with redirect_stdout(sys.stderr):103 return func(text)104 return func(text)
844 unmodified lines
modified:src/click/types.py+2 added-1 removed
1102 unmodified lines
1103 ctx: Context | None,1104 ) -> str | bytes | os.PathLike[str]:1105 rv = value11061107 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 == dash11091110 if not is_dash:1111 if self.resolve_path:1112 rv = os.path.realpath(rv)
263 unmodified lines
modified:src/click/utils.py+5 added-12 removed
11 unmodified lines
1213from ._compat import _default_text_stderr14from ._compat import _default_text_stdout15from ._compat import _find_binary_writer16from ._compat import auto_wrap_for_ansi16from ._compat import binary_streams17from ._compat import open_stream18from ._compat import should_strip_ansi19from ._compat import strip_ansi
238 unmodified lines
258 - 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 lines
271 :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.274275 .. versionchanged:: 8.5276 Colorama is no longer used for color on Windows.277278 .. 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 lines
331 return332333 # 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)337337 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)344338 file.write(out) # type: ignore339 file.flush()340341
305 unmodified lines
modified:tests/test_arguments.py+88 added
293 unmodified lines
294 assert result.exit_code == 0295 assert result.output == "test\n"296297298def 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 pass304305 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 )315316317def 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 pass322323 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.output328329330def 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 pass335336 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.output340341342def test_deprecated_usage(runner):343 @click.command()344 @click.argument("f", required=False, deprecated=True)345 def cli(f):
29 unmodified lines
375 assert result.exit_code == 0376 assert result.output.splitlines()[0] == f"Usage: cli [OPTIONS] {expected}"377378379@pytest.mark.parametrize(380 ("deprecated", "expected_label"),381 [(True, "(DEPRECATED)"), ("use g instead", "(DEPRECATED: use g instead)")],382)383def 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)388389 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.output394395396def 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)401402 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.output407408409@pytest.mark.parametrize(410 ("deprecated", "expected"),411 [(True, "(DEPRECATED)"), ("USE B INSTEAD", "(DEPRECATED: USE B INSTEAD)")],412)413@pytest.mark.parametrize("help_text", ["", None])414def 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] == expected421422423@pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])424def test_deprecated_warning(runner, deprecated):425 @click.command()426 @click.argument(
317 unmodified lines
modified:tests/test_basic.py+27 added-5 removed
1from __future__ import annotations23import enum4import os5from itertools import chain56import pytest78import click
247 unmodified lines
256257258@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)265def test_boolean_conversion(runner, value, expect):266 @click.command()267 @click.option("--flag", type=bool)
588 unmodified lines
856857 result = runner.invoke(cli, ["--version"])858 assert result.exit_code != 0859 assert "not installed" in str(result.exception)860861862@pytest.mark.parametrize("args", [["--version"], ["-V"]])863def 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 pass868869 result = runner.invoke(cli, args)870 assert result.exit_code == 0871 assert result.output == "custom 9.9.9\n"872873874def 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 pass879880 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 lines
39 "nargs": 1,40 "multiple": False,41 "default": None,42 "envvar": None,43 "help": None,44 },45)46NUMBER_OPTION = (47 click.Option(["-c", "--count", "number"], default=1),
225 unmodified lines
273 class TestType(click.ParamType):274 pass275276 assert TestType().to_info_dict()["name"] == "TestType"277278279@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)292def 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_out295296297def 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"302303304def 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 pass310311 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 lines
1021 if prompt == "Confirm Password":1022 assert "Confirm Password: " in result.output102310241025@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)1058def 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 """10661067 @click.command()1068 def cli():1069 call()10701071 result = runner.invoke(cli, input=user_input, color=color)1072 assert result.output == expect107310741075def 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 lines
modified:tests/test_types.py+25 added
1import os.path2import pathlib3import platform4import subprocess5import sys6import tempfile78import pytest9
116 unmodified lines
126 assert result.exception is None127 assert result.return_value == expect128129130def test_path_dash_no_byteswarning():131 """Detecting the ``-`` dash sentinel must not compare ``bytes`` against132 ``str``, which raises a ``BytesWarning`` under ``python -bb``.133134 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.stderr151152153def _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 lines
modified:CHANGES.md+18 added
1## Version 8.5.023Unreleased45- 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`1819## Version 8.4.22021Released 2026-06-2422
1560 unmodified lines
modified:pyproject.toml+1 added-10 removed
1[project]2name = "click"3version = "8.4.2"3version = "8.5.0.dev"4description = "Composable command line interface toolkit"5readme = "README.md"6license = "BSD-3-Clause"7license-files = ["LICENSE.txt"]
5 unmodified lines
13 "Programming Language :: Python",14 "Typing :: Typed",15]16requires-python = ">=3.10"17dependencies = [18 "colorama; platform_system == 'Windows'",19]1718[project.urls]19Donate = "https://palletsprojects.com/donate"20Documentation = "https://click.palletsprojects.com/"
89 unmodified lines
110show_error_codes = true111pretty = true112strict = true113117[[tool.mypy.overrides]]118module = [119 "colorama.*",120]121ignore_missing_imports = true122114[tool.pyright]115pythonVersion = "3.10"116include = ["src", "tests/typing"]117typeCheckingMode = "basic"
114 unmodified lines
modified:uv.lock+1 added-5 removed
171 unmodified lines
172]173174[[package]]175name = "click"176version = "8.4.2"176version = "8.5.0.dev0"177source = { editable = "." }178dependencies = [179 { name = "colorama", marker = "sys_platform == 'win32'" },180]178179[package.dev-dependencies]180dev = [181 { name = "ruff" },
35 unmodified lines
217 { name = "pytest" },218]219220[package.metadata]224requires-dist = [{ name = "colorama", marker = "sys_platform == 'win32'" }]221222[package.metadata.requires-dev]223dev = [224 { name = "ruff" },
1437 unmodified lines