Revert "Revert "Merge Stable into master""
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This reverts commit 8bc912710774c7b4c84f5d4effd0c764f3e2bbb9.
authored by Edward G · committed by Edward G · parent 8bc9127 · Browse files · 8 files·+209 added−9 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+209 added−9 removed
- tests:+164 added−5 removed
- other:+45 added−4 removed
Provenance
- Commit
e252437- Tree
77a5471- Author
Edward G <edward.g2013@gmail.com>- Committer
Edward G <edward.g2013@gmail.com>- Parent
8bc9127
8 files changed+209 added−9 removed
modified:src/click/core.py+2 added
2870 unmodified lines2871 if show_default_is_str:2872 default_string = f"({self.show_default})"2873 elif isinstance(default_value, (list, tuple)):2874 default_string = ", ".join(str(d) for d in default_value)2875+ elif isinstance(default_value, enum.Enum):2876+ default_string = default_value.name2877 elif inspect.isfunction(default_value):2878 default_string = _("(dynamic)")2879 elif self.is_bool_flag and self.secondary_opts:2880 # For boolean flags that have distinct True/False opts,298 unmodified linesmodified:src/click/exceptions.py+3 added-3 removed
113 unmodified lines114 self,115 message: str,116 ctx: Context | None = None,117 param: Parameter | None = None,118- param_hint: str | None = None,118+ param_hint: cabc.Sequence[str] | str | None = None,119 ) -> None:120 super().__init__(message, ctx)121 self.param = param122 self.param_hint = param_hint27 unmodified lines150 self,151 message: str | None = None,152 ctx: Context | None = None,153 param: Parameter | None = None,154- param_hint: str | None = None,154+ param_hint: cabc.Sequence[str] | str | None = None,155 param_type: str | None = None,156 ) -> None:157 super().__init__(message or "", ctx, param, param_hint)158 self.param_type = param_type159 160 def format_message(self) -> str:161 if self.param_hint is not None:162- param_hint: str | None = self.param_hint162+ param_hint: cabc.Sequence[str] | str | None = self.param_hint163 elif self.param is not None:164 param_hint = self.param.get_error_hint(self.ctx) # type: ignore165 else:166 param_hint = None142 unmodified linesmodified:src/click/shell_completion.py+21 added-1 removed
122 unmodified lines123 124 %(complete_func)s_setup;125 """126 127+# See ZshComplete.format_completion below, and issue #2703, before128+# changing this script.129+#130+# (TL;DR: _describe is picky about the format, but this Zsh script snippet131+# is already widely deployed. So freeze this script, and use clever-ish132+# handling of colons in ZshComplet.format_completion.)133 _SOURCE_ZSH = """\134 #compdef %(prog_name)s135 136 %(complete_func)s() {241 unmodified lines378 379 return args, incomplete380 381 def format_completion(self, item: CompletionItem) -> str:376- return f"{item.type}\n{item.value}\n{item.help if item.help else '_'}"382+ help_ = item.help or "_"383+ # The zsh completion script uses `_describe` on items with help384+ # texts (which splits the item help from the item value at the385+ # first unescaped colon) and `compadd` on items without help386+ # text (which uses the item value as-is and does not support387+ # colon escaping). So escape colons in the item value if and388+ # only if the item help is not the sentinel "_" value, as used389+ # by the completion script.390+ #391+ # (The zsh completion script is potentially widely deployed, and392+ # thus harder to fix than this method.)393+ #394+ # See issue #1812 and issue #2703 for further context.395+ value = item.value.replace(":", r"\:") if help_ != "_" else item.value396+ return f"{item.type}\n{value}\n{help_}"397 398 399 class FishComplete(ShellComplete):400 """Shell completion for Fish."""264 unmodified linesmodified:src/click/testing.py+12 added
97 unmodified lines98 self.output: io.BytesIO = io.BytesIO()99 self.stdout: io.BytesIO = BytesIOCopy(copy_to=self.output)100 self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output)101 102+ def __del__(self) -> None:103+ """104+ Guarantee that embedded file-like objects are closed in a105+ predictable order, protecting against races between106+ self.output being closed and other streams being flushed on close107 108+ .. versionadded:: 8.2.2109+ """110+ self.stderr.close()111+ self.stdout.close()112+ self.output.close()113+114+115 class _NamedTextIOWrapper(io.TextIOWrapper):116 def __init__(117 self, buffer: t.BinaryIO, name: str, mode: str, **kwargs: t.Any118 ) -> None:459 unmodified linesmodified:tests/test_options.py+87 added-1 removed
1+import enum2 import os3 import re4+import sys5 6+if sys.version_info < (3, 11):7+ enum.StrEnum = enum.Enum # type: ignore[assignment]8+9 import pytest10 11 import click12 from click import Option1291 unmodified lines1304 result = runner.invoke(cmd)1305 assert result.exit_code == 01306 1307 1308+class HashType(enum.Enum):1309+ MD5 = enum.auto()1310+ SHA1 = enum.auto()1311+1312+1313+class Number(enum.IntEnum):1314+ ONE = enum.auto()1315+ TWO = enum.auto()1316+1317+1318+class Letter(enum.StrEnum):1319+ A = enum.auto()1320+ B = enum.auto()1321+1322+1323+class Color(enum.Flag):1324+ RED = enum.auto()1325+ GREEN = enum.auto()1326+ BLUE = enum.auto()1327+1328+1329+class ColorInt(enum.IntFlag):1330+ RED = enum.auto()1331+ GREEN = enum.auto()1332+ BLUE = enum.auto()1333+1334+1335 @pytest.mark.parametrize(1336 ("choices", "metavars"),1337 [1338 pytest.param(["foo", "bar"], "[TEXT]", id="text choices"),1339 pytest.param([1, 2], "[INTEGER]", id="int choices"),1340 pytest.param([1.0, 2.0], "[FLOAT]", id="float choices"),1341 pytest.param([True, False], "[BOOLEAN]", id="bool choices"),1342 pytest.param(["foo", 1], "[TEXT|INTEGER]", id="text/int choices"),1343+ pytest.param(HashType, "[HASHTYPE]", id="enum choices"),1344+ pytest.param(Number, "[NUMBER]", id="int enum choices"),1345+ pytest.param(Letter, "[LETTER]", id="str enum choices"),1346+ pytest.param(Color, "[COLOR]", id="flag enum choices"),1347+ pytest.param(ColorInt, "[COLORINT]", id="int flag enum choices"),1348 ],1349 )1350 def test_usage_show_choices(runner, choices, metavars):1351 """When show_choices=False is set, the --help output14 unmodified lines1366 def cli_without_choices(g):1367 pass1368 1369 result = runner.invoke(cli_with_choices, ["--help"])1333- assert f"[{'|'.join([str(i) for i in choices])}]" in result.output1370+ assert (1371+ f"[{'|'.join(i.name if isinstance(i, enum.Enum) else str(i) for i in choices)}]"1372+ in result.output1373+ )1374 1375 result = runner.invoke(cli_without_choices, ["--help"])1376 assert metavars in result.output1377 1378 1379 @pytest.mark.parametrize(1380+ ("choices", "default", "default_string"),1381+ [1382+ (["foo", "bar"], "bar", "bar"),1383+ # The default value is not enforced to be in the choices.1384+ (["foo", "bar"], "random", "random"),1385+ # None cannot be a default value as-is: it left the default value as unset.1386+ (["foo", "bar"], None, None),1387+ ([0, 1], 0, "0"),1388+ # Values are not coerced to the type of the choice, even if equivalent.1389+ ([0, 1], 0.0, "0.0"),1390+ ([1, 2], 2, "2"),1391+ ([1.0, 2.0], 2, "2"),1392+ ([1.0, 2.0], 2.0, "2.0"),1393+ ([True, False], True, "True"),1394+ ([True, False], False, "False"),1395+ (["foo", 1], "foo", "foo"),1396+ (["foo", 1], 1, "1"),1397+ # Enum choices are rendered as their names.1398+ # See: https://github.com/pallets/click/issues/29111399+ (HashType, HashType.SHA1, "SHA1"),1400+ # Enum choices allow defaults strings that are their names.1401+ (HashType, "SHA1", "SHA1"),1402+ (Number, Number.TWO, "TWO"),1403+ (Letter, Letter.B, "B"),1404+ (Color, Color.GREEN, "GREEN"),1405+ (ColorInt, ColorInt.GREEN, "GREEN"),1406+ ],1407+)1408+def test_choice_default_rendering(runner, choices, default, default_string):1409+ @click.command()1410+ @click.option("-g", type=click.Choice(choices), default=default, show_default=True)1411+ def cli_with_choices(g):1412+ pass1413+1414+ # Check that the default value is kept normalized to the type of the choice.1415+ assert cli_with_choices.params[0].default == default1416+1417+ result = runner.invoke(cli_with_choices, ["--help"])1418+ extra_usage = f"[default: {default_string}]"1419+ if default_string is None:1420+ assert extra_usage not in result.output1421+ else:1422+ assert extra_usage in result.output1423+1424+1425+@pytest.mark.parametrize(1426 "opts_one,opts_two",1427 [1428 # No duplicate shortnames1429 (19 unmodified linesmodified:tests/test_shell_completion.py+75 added
1+import textwrap2 import warnings3+from collections.abc import Mapping4 5 import pytest6 7 import click.shell_completion347 unmodified lines355 result = runner.invoke(cli, env=env)356 assert result.output == expect357 358 359+@pytest.mark.parametrize(360+ ("env", "expect"),361+ [362+ (363+ {"COMP_WORDS": "", "COMP_CWORD": "0"},364+ textwrap.dedent(365+ """\366+ plain367+ a368+ _369+ plain370+ b371+ bee372+ plain373+ c\\:d374+ cee:dee375+ plain376+ c:e377+ _378+ """379+ ),380+ ),381+ (382+ {"COMP_WORDS": "a c", "COMP_CWORD": "1"},383+ textwrap.dedent(384+ """\385+ plain386+ c\\:d387+ cee:dee388+ plain389+ c:e390+ _391+ """392+ ),393+ ),394+ (395+ {"COMP_WORDS": "a c:", "COMP_CWORD": "1"},396+ textwrap.dedent(397+ """\398+ plain399+ c\\:d400+ cee:dee401+ plain402+ c:e403+ _404+ """405+ ),406+ ),407+ ],408+)409 @pytest.mark.usefixtures("_patch_for_completion")410+def test_zsh_full_complete_with_colons(411+ runner, env: Mapping[str, str], expect: str412+) -> None:413+ cli = Group(414+ "cli",415+ commands=[416+ Command("a"),417+ Command("b", help="bee"),418+ Command("c:d", help="cee:dee"),419+ Command("c:e"),420+ ],421+ )422+ result = runner.invoke(423+ cli,424+ env={425+ **env,426+ "_CLI_COMPLETE": "zsh_complete",427+ },428+ )429+ assert result.output == expect430+431+432+@pytest.mark.usefixtures("_patch_for_completion")433 def test_context_settings(runner):434 def complete(ctx, param, incomplete):435 return ctx.obj["choices"]436 111 unmodified linesmodified:tests/test_testing.py+2 added-4 removed
446 unmodified lines447 runner = CliRunner()448 449 with runner.isolation() as (_, err, _):450 click.echo("\udce2", err=True, nl=False)451+ assert err.getvalue() == b"\\udce2"452 452- assert err.getvalue() == b"\\udce2"453 454-454 def test_isolation_flushes_unflushed_stderr():455 """An un-flushed write to stderr, as with `print(..., file=sys.stderr)`, will end up456 flushed by the runner at end of invocation.457 """458 runner = CliRunner()459 460 with runner.isolation() as (_, err, _):461 click.echo("\udce2", err=True, nl=False)462+ assert err.getvalue() == b"\\udce2"463 464- assert err.getvalue() == b"\\udce2"465-464 @click.command()465 def cli():466 # set end="", flush=False so that it's totally clear that we won't get any467 # auto-flush behaviors4 unmodified linesmodified:CHANGES.rst+7 added
6 unmodified lines7 8 - Fix reconciliation of `default`, `flag_value` and `type` parameters for9 flag options, as well as parsing and normalization of environment variables.10 :issue:`2952` :pr:`2956`11+- Fix typing issue in ``BadParameter`` and ``MissingParameter`` exceptions for the12+ parameter ``param_hint`` that did not allow for a sequence of string where the13+ underlying functino ``_join_param_hints`` allows for it. :issue:`2777` :pr:`2990`14+- Use the value of ``Enum`` choices to render their default value in help15+ screen. Refs :issue:`2911` :pr:`3004`16+- Fix completion for the Z shell (``zsh``) for completion items containing17+ colons. :issue:`2703` :pr:`2846`18 19 Version 8.2.120 -------------21 1242 unmodified lines