Skip to content
Myr

Merge branch 'main' into fix-path-byteswarning

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

authored by Kevin Deldycke · committed by GitHub · parents 6f85d26, 240603f · Browse files · 17 files+217 added−107 removed
This commit

State

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

Diff stats

17 files+217 added−107 removed

  • tests:+134 added−10 removed
  • other:+83 added−97 removed

17 files+217 added−107 removed

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+8 added-3 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.5657Primarily this means that:5859- 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.6263On Windows, Click uses colorama without calling `colorama.init()`. You can still call that in your code, but it's not64required for Click.63:::{admonition} Older Windows Support64:class: note6566Recent Windows 11 supports ANSI styling by default, in both Terminal and cmd.exe.67If you need to support color output on older versions of Windows, install68[colorama](https://pypi.org/project/colorama/) and call `colorama.init()`.69:::7071For styling a string, the {func}`style` function can be used:7273```python74import click
336 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/_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/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-11 removed
11 unmodified lines
12from gettext import gettext as _1314from ._compat import isatty15from ._compat import strip_ansi16from ._compat import WIN16from .exceptions import Abort17from .exceptions import UsageError18from .globals import resolve_color_default19from .types import Choice
62 unmodified lines
8283def _readline_prompt(func: t.Callable[[str], str], text: str, err: bool) -> str:84 """Call a prompt function, passing the full prompt on non-Windows so85 readline can 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*.86 """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:])87 if err:88 with redirect_stdout(sys.stderr):89 return func(text)90 return func(text)
844 unmodified lines
modified:src/click/utils.py+5 added-11 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
252 unmodified lines
272 :param color: Force showing or hiding colors and other styles. By273 default Click will remove color if the output does not look like274 an interactive terminal.275276 .. versionchanged:: 8.5277 Colorama is no longer used for color on Windows.278279 .. versionchanged:: 6.0280 Support Unicode output on the Windows console. Click does not281 modify ``sys.stdout``, so ``sys.stdout.write()`` and ``print()``282 will still not support Unicode.
49 unmodified lines
332 return333334 # ANSI style code support. For no message or bytes, nothing happens.335 # When outputting to a file instead of a terminal, strip codes.334 else:335 color = resolve_color_default(color)336 elif should_strip_ansi(file, resolve_color_default(color)):337 out = strip_ansi(out)338337 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)344339 file.write(out) # type: ignore340 file.flush()341342
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_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_utils.py+6 added-10 removed
539 unmodified lines
540 click.echo(styled_text, color=True)541 out, err = capfd.readouterr()542 assert out == f"{styled_text}\n"543544 isatty = True544 click.echo(styled_text)545 out, err = capfd.readouterr()546 assert out == f"{styled_text}\n"547548 isatty = False550 # Faking isatty() is not enough on Windows;551 # the implementation caches the colorama wrapped stream552 # so we have to use a new stream for each test553 stream = StringIO()554 click.echo(styled_text, file=stream)555 assert stream.getvalue() == f"{text}\n"549 click.echo(styled_text)550 out, err = capfd.readouterr()551 assert out == f"{text}\n"552557 stream = StringIO()558 click.echo(styled_text, file=stream, color=True)559 assert stream.getvalue() == f"{styled_text}\n"553 click.echo(styled_text, color=True)554 out, err = capfd.readouterr()555 assert out == f"{styled_text}\n"556557558def test_prompt_cast_default(capfd, monkeypatch):559 monkeypatch.setattr(sys, "stdin", StringIO("\n"))
298 unmodified lines
modified:CHANGES.md+9 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`910## Version 8.4.21112Released 2026-06-2413
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