Skip to content
Myr

Merge stable into main (#3876)

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

authored by Rowlando13 · committed by GitHub · parents 6aabf09, bb695aa · Browse files · 11 files+304 added−92 removed
This commit

State

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

Diff stats

11 files+304 added−92 removed

  • tests:+191 added−5 removed
  • other:+113 added−87 removed

11 files+304 added−92 removed

modified:docs/arguments.md+2 added-1 removed
modified:docs/documentation.md+4 added
116 unmodified lines
117the `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.120121The section shows up as soon as one argument of the command has a `help`. It122then lists every argument, so it always matches the usage line. Arguments with123no `help` are listed with an empty description.124125A brief example:126127```{eval-rst}128.. click:example::
219 unmodified lines
modified:src/click/core.py+45 added-40 removed
1308 unmodified lines
1309 with formatter.section(_("Options")):1310 formatter.write_dl(opts)13111312 def format_arguments(self, ctx: Context, formatter: HelpFormatter) -> None:1313 """Writes the arguments that have a help record into the formatter."""1314 args = []1315 for param in self.get_params(ctx):1316 rv = param.get_help_record(ctx)1317 if rv is not None and isinstance(param, Argument):1318 args.append(rv)1313 """Writes all arguments into the formatter, if at least one is documented.13141320 if args:1315 An argument with no help gets an empty description, the same way an option1316 with no help does. That keeps the section an exhaustive list of the1317 positional arguments, matching the usage line.1318 """1319 args = [param for param in self.get_params(ctx) if isinstance(param, Argument)]13201321 if any(arg.help is not None for arg in args):1322 with formatter.section(_("Positional arguments")):1322 formatter.write_dl(args)1323 formatter.write_dl([arg.get_help_record(ctx) for arg in args])13241325 def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None:1326 """Writes the epilog into the formatter if it exists."""1327 if self.epilog:
931 unmodified lines
2259 indicating that the argument is deprecated and highlights2260 its deprecation in --help. The message can be customized2261 by using a string as the value. A deprecated parameter2262 cannot be required, a ValueError will be raised otherwise.2263 :param help: the help string. It is dedented and get a deprecated label if2264 appropriate.22652266 .. versionchanged:: 8.5.12267 New ``help`` parameter to replace the one from :class:`Option` and2268 :class:`Argument`.22692270 .. versionchanged:: 8.2.02271 Introduction of ``deprecated``.22722273 .. versionchanged:: 8.2
55 unmodified lines
2329 _custom_shell_complete: (2330 t.Callable[[Context, Parameter, str], list[CompletionItem] | list[str]] | None2331 )2332 deprecated: bool | str2333 help: str | None23342335 def __init__(2336 self,2337 param_decls: cabc.Sequence[str] | None = None,
21 unmodified lines
2359 [Context, Parameter, str], list[CompletionItem] | list[str]2360 ]2361 | None = None,2362 deprecated: bool | str = False,2363 help: str | None = None,2364 ) -> None:2365 self.name, self.opts, self.secondary_opts = self._parse_decls(2366 param_decls or (), expose_value2367 )
24 unmodified lines
2392 self.envvar = envvar2393 self._custom_shell_complete = shell_complete2394 self.deprecated = deprecated23952396 if help:2397 help = inspect.cleandoc(help)23982399 if deprecated:2400 label = _format_deprecated_label(deprecated)2401 help = f"{help} {label}" if help else label24022403 self.help = help24042405 if __debug__:2406 if self.type.is_composite and nargs != self.type.arity:2407 raise ValueError(2408 f"'nargs' must be {self.type.arity} (or None) for"
37 unmodified lines
2446 "nargs": self.nargs,2447 "multiple": self.multiple,2448 "default": self._hide_unset(self.default),2449 "envvar": self.envvar,2450 "help": self.help,2451 }24522453 def __repr__(self) -> str:2454 return f"<{self.__class__.__name__} {self.name}>"
534 unmodified lines
2989 default: t.Any | t.Callable[[], t.Any] | None29902991 count: bool2992 allow_from_autoenv: bool2974 help: str | None2993 show_default: bool | str | None2994 show_choices: bool2995 show_envvar: bool2996
17 unmodified lines
3014 show_envvar: bool = False,3015 deprecated: bool | str = False,3016 **attrs: t.Any,3017 ) -> None:3000 if help:3001 help = inspect.cleandoc(help)30023018 super().__init__(3004 param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs3019 param_decls,3020 type=type,3021 multiple=multiple,3022 deprecated=deprecated,3023 help=help,3024 **attrs,3025 )30263027 # Phase 1: prompt-related attributes. ``_infer_flag_kind`` reads ``self.prompt``3028 # and ``self.prompt_required`` so this must run first.
6 unmodified lines
3035 prompt_text = None3036 else:3037 prompt_text = prompt30383019 if deprecated:3020 label = _format_deprecated_label(deprecated)3021 help = f"{help} {label}" if help else label30223039 self.prompt = prompt_text3040 self.confirmation_prompt = confirmation_prompt3041 self.prompt_required = prompt_required3042 self.hide_input = hide_input
21 unmodified lines
3064 if count and self.default is UNSET:3065 self.default = 030663067 self.allow_from_autoenv = allow_from_autoenv3052 self.help = help3068 self.show_default = show_default3069 self.show_choices = show_choices3070 self.show_envvar = show_envvar3071
153 unmodified lines
3225 """3226 info_dict = super().to_info_dict()3227 info_dict.update(3228 default=self._hide_unset(self._resolve_lazy_default(self.default)),3214 help=self.help,3229 prompt=self.prompt,3230 is_flag=self.is_flag,3231 flag_value=self.flag_activation_value,3232 count=self.count,
514 unmodified lines
37473748 if "multiple" in attrs:3749 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.")37503737 deprecated = attrs.get("deprecated", False)3751 super().__init__(param_decls, required=required, help=help, **attrs)37523739 if help:3740 help = inspect.cleandoc(help)37413742 if deprecated:3743 label = _format_deprecated_label(deprecated)3744 help = f"{help} {label}" if help else label37453746 self.help = help37473748 super().__init__(param_decls, required=required, **attrs)37493750 def to_info_dict(self) -> dict[str, t.Any]:3751 info_dict = super().to_info_dict()3752 info_dict.update(help=self.help)3753 return info_dict37543753 @property3754 def human_readable_name(self) -> str:3755 if self.metavar is not None:3756 return self.metavar
39 unmodified lines
37963797 def get_usage_pieces(self, ctx: Context) -> list[str]:3798 return [self.make_metavar(ctx)]37993802 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:3803 if self.help is None:3804 return None3800 def get_help_record(self, ctx: Context) -> tuple[str, str]:3801 """Returns the argument's help row: its metavar and its help text.38023806 return self.make_metavar(ctx), self.help3803 Unlike :meth:`Option.get_help_record`, this never returns ``None``. An3804 argument cannot be hidden, so an undocumented one still gets a row, with3805 an empty description.38063807 .. versionchanged:: 8.5.13808 Always returns a tuple. It used to return ``None`` when ``help`` was3809 not set.3810 """3811 return self.make_metavar(ctx), self.help or ""38123813 def get_error_hint(self, ctx: Context | None) -> str:3814 if ctx is not None:3815 return f"'{self.make_metavar(ctx)}'"3816 return f"'{self.human_readable_name}'"
27 unmodified lines
modified:src/click/types.py+29 added-14 removed
43 unmodified lines
4445_FloatValueT = t.TypeVar("_FloatValueT", bound=float)46_FloatValueT_co = t.TypeVar("_FloatValueT_co", bound=float, covariant=True)4748if t.TYPE_CHECKING:49 _PathT_co = te.TypeVar(50 "_PathT_co", covariant=True, default="str | bytes | os.PathLike[str]"51 )52elif sys.version_info >= (3, 13):53 _PathT_co = t.TypeVar(54 "_PathT_co", covariant=True, default=str | bytes | os.PathLike[str]55 )56else:57 _PathT_co = t.TypeVar("_PathT_co", covariant=True)585960class ParamTypeInfoDict(t.TypedDict):61 param_type: str62 name: str63
991 unmodified lines
1055 readable: bool1056 allow_dash: bool105710581048class Path(ParamType[str | bytes | os.PathLike[str]]):1059class Path(ParamType[_PathT_co, str | os.PathLike[str]], t.Generic[_PathT_co]):1060 """The ``Path`` type is similar to the :class:`File` type, but1061 returns the filename instead of an open file. Various checks can be1062 enabled to validate the type of file and permissions.1063
14 unmodified lines
1078 :param path_type: Convert the incoming path value to this type. If1079 ``None``, keep Python's default, which is ``str``. Useful to1080 convert to :class:`pathlib.Path`.10811082 .. versionchanged:: 8.5.11083 Reveal the actual type of the value as converted from raw input.10841085 .. versionchanged:: 8.11086 Added the ``executable`` parameter.10871088 .. versionchanged:: 8.0
23 unmodified lines
1112 writable: bool = False,1113 readable: bool = True,1114 resolve_path: bool = False,1115 allow_dash: bool = False,1102 path_type: type | None = None,1116 path_type: type[_PathT_co] | None = None,1117 executable: bool = False,1118 ) -> None:1119 self.exists = exists1120 self.file_okay = file_okay
2 unmodified lines
1123 self.writable = writable1124 self.executable = executable1125 self.resolve_path = resolve_path1126 self.allow_dash = allow_dash1113 self.type: type | None = path_type1127 self.type: type[_PathT_co] | None = path_type11281129 if self.file_okay and not self.dir_okay:1130 self.name = _("file")1131 elif self.dir_okay and not self.file_okay:
11 unmodified lines
1143 "allow_dash": self.allow_dash,1144 **super().to_info_dict(),1145 }11461133 def coerce_path_result(1134 self, value: str | os.PathLike[str]1135 ) -> str | bytes | os.PathLike[str]:1136 if self.type is not None and not isinstance(value, self.type):1137 if self.type is str:1138 return os.fsdecode(value)1139 elif self.type is bytes:1140 return os.fsencode(value)1147 def coerce_path_result(self, value: str | os.PathLike[str]) -> _PathT_co:1148 path_type: type[t.Any] | None = self.type1149 rv: t.Any = value11501151 if path_type is not None and not isinstance(value, path_type):1152 if path_type is str:1153 rv = os.fsdecode(value)1154 elif path_type is bytes:1155 rv = os.fsencode(value)1156 else:1142 return t.cast("os.PathLike[str]", self.type(value))1157 rv = path_type(value)11581144 return value1159 return t.cast("_PathT_co", rv)11601161 def convert(1162 self,1163 value: str | os.PathLike[str],1164 param: Parameter | None,1165 ctx: Context | None,1151 ) -> str | bytes | os.PathLike[str]:1166 ) -> _PathT_co:1167 rv = value11681169 dash = b"-" if isinstance(rv, bytes) else "-"1170 is_dash = self.file_okay and self.allow_dash and rv == dash
267 unmodified lines
modified:src/click/utils.py+20 added-32 removed
62 unmodified lines
63 """Returns a condensed version of help string.6465 :meta private:66 """67 # Consider only the first paragraph.68 paragraph_end = help.find("\n\n")67 # Consider only the first paragraph and collapse newlines, tabs and spaces.68 words = help.partition("\n\n")[0].split()6970 if paragraph_end != -1:71 help = help[:paragraph_end]70 # The first paragraph started with a "no rewrap" marker, ignore it.71 if words and words[0] == "\b":72 words = words[1:]7373 # Collapse newlines, tabs, and spaces.74 words = help.split()7574 if not words:75 return ""7679 # The first paragraph started with a "no rewrap" marker, ignore it.80 if words[0] == "\b":81 words = words[1:]8283 total_length = 077 last_index = len(words) - 17879 # A period ends a sentence when it closes the text, or when the next word80 # does not start in lowercase. A lowercase word continues the sentence, so81 # the period belongs to an abbreviation such as "vs.".82 for i, word in enumerate(words):87 total_length += len(word) + (i > 0)8889 if total_length > max_length: # too long, truncate83 if word.endswith(".") and (i == last_index or not words[i + 1][0].islower()):84 words = words[: i + 1]85 break8692 if word[-1] == ".": # sentence end, truncate without "..."93 return " ".join(words[: i + 1])87 text = " ".join(words)8895 if total_length == max_length and i != last_index:96 break # not at sentence end, truncate with "..."97 else:98 return " ".join(words) # no truncation needed89 if len(text) <= max_length:90 return text91100 # Account for the length of the suffix.101 total_length += len("...")92 # The suffix alone does not fit, and shorten() rejects such a width.93 if max_length < len("..."):94 return "..."95103 # remove words until the length is short enough104 while i > 0:105 total_length -= len(words[i]) + (i > 0)96 # Imported late to keep the import footprint small.97 import textwrap98107 if total_length <= max_length:108 break99 # Do not split hyphenated words.100 return textwrap.shorten(text, max_length, placeholder="...", break_on_hyphens=False)101110 i -= 1102112 return " ".join(words[:i]) + "..."113114103class _LazyFile:104 """A lazy file works like a regular file but it does not fully open105 the file but it does perform some basic checks early to see if the106 filename parameter does make sense. This is useful for safely opening
570 unmodified lines
modified:tests/test_types/test_Path.py+5 added
2 unmodified lines
3import platform4import subprocess5import sys6import tempfile7import typing as t89import pytest1011import click
171 unmodified lines
183 )184 result = runner.invoke(cli, ["a/b/c.txt"], standalone_mode=False)185 assert result.exception is None186 assert result.return_value == expect187188189def test_path_converted_type_parameter_at_runtime():190 assert t.get_args(click.Path[pathlib.Path]) == (pathlib.Path,)
modified:tests/test_utils/test_make_default_short_help.py+26 added-2 removed
6 unmodified lines
7 ("value", "max_length", "expect"),8 [9 pytest.param("", 10, "", id="empty"),10 pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),11 pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),11 pytest.param("123 567 9. Aaaa bbb", 10, "123 567 9.", id="sentence < max"),12 pytest.param("123 567 9.", 10, "123 567 9.", id="dot ends text"),13 pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),14 pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),15 pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),16 pytest.param(
1 unmodified line
18 20,19 "token in ~/.netrc...",20 id="ignore dot in word",21 ),22 pytest.param(23 "Weigh apples vs. pears.",24 30,25 "Weigh apples vs. pears.",26 id="abbreviation inside sentence",27 ),28 pytest.param(29 "Weigh apples vs. pears and plums.",30 20,31 "Weigh apples vs....",32 id="abbreviation inside truncated sentence",33 ),34 pytest.param("123 567 9. aaaa bbb", 10, "123 567...", id="lowercase after dot"),35 pytest.param(36 "Pick a fruit. 3 remain.", 20, "Pick a fruit.", id="digit after dot"37 ),38 pytest.param("well-behaved.", 8, "...", id="never split a hyphenated word"),39 pytest.param("supercalifragilistic", 10, "...", id="never split a long word"),40 pytest.param("ab cd", 3, "...", id="width fits the suffix only"),41 pytest.param("ab cd", 2, "...", id="width below the suffix"),42 pytest.param("ab", 2, "ab", id="text shorter than the suffix"),43 pytest.param("ab cd", -1, "...", id="negative width"),44 ],45)46@pytest.mark.parametrize(47 "alter",
4 unmodified lines
52 ),53 ],54)55def test_make_default_short_help(value, max_length, alter, expect):33 assert len(expect) <= max_length56 # A width too narrow for the suffix still returns the whole suffix.57 assert len(expect) <= max(max_length, len("..."))5859 if alter:60 value = alter(value)61
2 unmodified lines
added:tests/typing/typing_path.py+34 added
1import os2import pathlib34from typing_extensions import assert_type56import click78# Without ``path_type``, ``convert`` returns the value it was given.9assert_type(click.Path().convert("a/b.txt", None, None), str | bytes | os.PathLike[str])10assert_type(click.prompt("File", type=click.Path()), str | bytes | os.PathLike[str])1112# ``path_type`` narrows the converted value's type for ``convert`` and ``prompt``.13assert_type(click.Path(path_type=str).convert("a/b.txt", None, None), str)14assert_type(click.Path(path_type=bytes).convert("a/b.txt", None, None), bytes)15assert_type(16 click.Path(path_type=pathlib.Path).convert("a/b.txt", None, None), pathlib.Path17)18assert_type(click.prompt("File", type=click.Path(path_type=str)), str)19assert_type(click.prompt("File", type=click.Path(path_type=pathlib.Path)), pathlib.Path)2021assert_type(click.Path(path_type=pathlib.Path)("a/b.txt"), pathlib.Path)22assert_type(click.Path(path_type=pathlib.Path)(None), None)2324# The class can be parameterized explicitly.25param_type: click.Path[pathlib.Path] = click.Path(exists=True, path_type=pathlib.Path)26assert_type(param_type.convert("a/b.txt", None, None), pathlib.Path)27assert_type(param_type.coerce_path_result("a/b.txt"), pathlib.Path)2829general: click.ParamType[str | bytes | os.PathLike[str]] = click.Path()30specific: click.ParamType[pathlib.Path] = click.Path(path_type=pathlib.Path)3132assert_type(33 click.Path(path_type=pathlib.Path)(pathlib.PurePosixPath("a/b.txt")), pathlib.Path34)
modified:tests/test_arguments.py+93 added
322 unmodified lines
323 assert "Options:" in result.output324 assert "number of greetings" in result.output325326327def test_argument_help_lists_undocumented_arguments(runner):328 """One documented argument makes the section list all of them."""329330 @click.command()331 @click.argument("src", help="Source path")332 @click.argument("dst")333 @click.argument("extra", nargs=-1)334 def cli(src, dst, extra):335 pass336337 result = runner.invoke(cli, ["--help"])338 assert result.exit_code == 0, result.output339 lines = result.output.splitlines()340 start = lines.index("Positional arguments:")341 assert lines[start : start + 4] == [342 "Positional arguments:",343 " SRC Source path",344 " DST",345 " [EXTRA]...",346 ]347348349def test_argument_help_undocumented_arguments_only_no_section(runner):350 """Arguments alone produce no section: at least one needs a help."""351352 @click.command()353 @click.argument("src")354 @click.argument("dst")355 def cli(src, dst):356 pass357358 result = runner.invoke(cli, ["--help"])359 assert result.exit_code == 0, result.output360 assert "Positional arguments:" not in result.output361362363def test_argument_help_deprecated_without_help_lists_all(runner):364 """A deprecation label counts as help and brings every argument into view."""365366 @click.command()367 @click.argument("src", required=False, deprecated=True)368 @click.argument("dst")369 def cli(src, dst):370 pass371372 result = runner.invoke(cli, ["--help"])373 assert result.exit_code == 0, result.output374 lines = result.output.splitlines()375 start = lines.index("Positional arguments:")376 assert lines[start : start + 3] == [377 "Positional arguments:",378 " [SRC!] (DEPRECATED)",379 " DST",380 ]381382383def test_argument_help_empty_string_lists_all(runner):384 """An explicit empty help opens the section, the same way an empty option help385 keeps its option listed.386 """387388 @click.command()389 @click.argument("src", help="")390 @click.argument("dst")391 def cli(src, dst):392 pass393394 result = runner.invoke(cli, ["--help"])395 assert result.exit_code == 0, result.output396 lines = result.output.splitlines()397 start = lines.index("Positional arguments:")398 assert lines[start : start + 3] == [399 "Positional arguments:",400 " SRC",401 " DST",402 ]403404405@pytest.mark.parametrize(406 ("help_text", "expected"),407 [408 pytest.param(None, ("SRC", ""), id="None"),409 pytest.param("", ("SRC", ""), id="empty"),410 pytest.param("Source path", ("SRC", "Source path"), id="documented"),411 ],412)413def test_argument_get_help_record_never_none(help_text, expected):414 """Every argument gets a row, even an undocumented one."""415 arg = click.Argument(["src"], help=help_text)416 ctx = click.Context(click.Command("cli"))417 assert arg.get_help_record(ctx) == expected418419420def test_argument_help_optional_metavar(runner):421 @click.command()422 @click.argument("name", required=False, default="", help="The name to print")423 def cli(name):
410 unmodified lines
modified:tests/test_info_dict.py+33 added-3 removed
274 unmodified lines
275276 assert TestType().to_info_dict()["name"] == "TestType"277278279PARAM_KINDS = [280 pytest.param(lambda **kwargs: click.Option(["--name"], **kwargs), id="option"),281 pytest.param(lambda **kwargs: click.Argument(["name"], **kwargs), id="argument"),282]283"""Both concrete kinds of parameter, built from the same keyword arguments."""284285286@pytest.mark.parametrize("make_param", PARAM_KINDS)287@pytest.mark.parametrize(288 ("help_in", "help_out"),289 [290 pytest.param(None, None, id="None"),
5 unmodified lines
296 id="multi-line",297 ),298 ],299)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_out300def test_param_to_info_dict_help(make_param, help_in, help_out):301 """`Parameter` owns the help string, so every kind dedents it the same way."""302 assert make_param(help=help_in).to_info_dict()["help"] == help_out303304305@pytest.mark.parametrize("make_param", PARAM_KINDS)306@pytest.mark.parametrize(307 ("help_in", "deprecated", "help_out"),308 [309 pytest.param(None, True, "(DEPRECATED)", id="no-help"),310 pytest.param(311 "Pack the basket.", True, "Pack the basket. (DEPRECATED)", id="help"312 ),313 pytest.param(314 "Pack the basket.",315 "USE THE CRATE",316 "Pack the basket. (DEPRECATED: USE THE CRATE)",317 id="custom-label",318 ),319 ],320)321def test_param_to_info_dict_deprecated_help(make_param, help_in, deprecated, help_out):322 """A deprecated parameter of any kind gets the same label appended."""323 param = make_param(help=help_in, required=False, deprecated=deprecated)324 assert param.to_info_dict()["help"] == help_out325326327def test_argument_to_info_dict_nargs():328 arg = click.Argument(["files"], nargs=-1, help="files to process")329 info = arg.to_info_dict()330 assert info["nargs"] == -1
15 unmodified lines
modified:CHANGES.md+13 added
7 unmodified lines
8 exits with the intended code; only the message may be lost. {issue}`3802`9- Add {meth}`Option.get_help_spec`, which returns the option's left help10 column even when the option is hidden. {meth}`Option.get_help_record` still11 returns `None` for hidden options, so help screens are unchanged. {pr}`3821`12- The `Positional arguments` help section lists every argument of the command,13 not only the documented ones. An argument with no `help` gets an empty14 description, the same way an option with no `help` does. {pr}`3860`15- {meth}`Argument.get_help_record` always returns a tuple. It used to return16 `None` for an argument with no `help`. {pr}`3860`17- Document which types are inferred from `default`, and what an unrecognized18 `type` callable does to a command-line value. {issue}`3036` {pr}`3808`19- `path_type` narrows the converted value's type for `convert` and `prompt`.20 {issue}`3822` {pr}`3858`21- {class}`Parameter` accepts a new `help` argument and {class}`Option` and {class}`Argument`22 inherits it. {meth}`Parameter.to_info_dict` now reports `help` for every kind of parameter.23 {pr}`3861`24- A command's short help no longer stops at an abbreviation such as `vs.` or `e.g.`25 inside the first sentence. A period ends the sentence only when it closes the text26 or the next word does not start in lowercase. {pr}`3865`2728## Version 8.5.02930Released 2026-08-24
1655 unmodified lines