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
Provenance
- Commit
dbfb10a- Tree
0ef5a6f- Author
Kevin Deldycke <kdeldycke@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
6f85d26- Parent 2
240603f
17 files changed+217 added−107 removed
modified: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+8 added-3 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.56 57 Primarily this means that:58 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 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.63+:::{admonition} Older Windows Support64+:class: note65 66+Recent Windows 11 supports ANSI styling by default, in both Terminal and cmd.exe.67+If you need to support color output on older versions of Windows, install68+[colorama](https://pypi.org/project/colorama/) and call `colorama.init()`.69+:::70+71 For styling a string, the {func}`style` function can be used:72 73 ```python74 import click336 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/_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/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-11 removed
11 unmodified lines12 from gettext import gettext as _13 14 from ._compat import isatty15 from ._compat import strip_ansi16-from ._compat import WIN16 from .exceptions import Abort17 from .exceptions import UsageError18 from .globals import resolve_color_default19 from .types import Choice62 unmodified lines82 83 def _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.87-88- 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 linesmodified:src/click/utils.py+5 added-11 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_ansi252 unmodified lines272 :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.275 276+ .. versionchanged:: 8.5277+ Colorama is no longer used for color on Windows.278+279 .. 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 lines332 return333 334 # 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)338 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-339 file.write(out) # type: ignore340 file.flush()341 342 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_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_utils.py+6 added-10 removed
539 unmodified lines540 click.echo(styled_text, color=True)541 out, err = capfd.readouterr()542 assert out == f"{styled_text}\n"543 544- isatty = True544 click.echo(styled_text)545 out, err = capfd.readouterr()546 assert out == f"{styled_text}\n"547 548 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"552 557- 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"556 557 558 def test_prompt_cast_default(capfd, monkeypatch):559 monkeypatch.setattr(sys, "stdin", StringIO("\n"))298 unmodified linesmodified:CHANGES.md+9 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+10 ## Version 8.4.211 12 Released 2026-06-2413 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