Merge remote-tracking branch 'origin/main' into zhihua/powershell
Before adoption: this commit came in with the history the project adopted, so no landing records it.
# Conflicts: # src/click/shell_completion.py
authored by Zhihua Lai · committed by Zhihua Lai · parents 1ac08db, 240603f · Browse files · 6 files·+207 added−29 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+207 added−29 removed
- tests:+121 added−4 removed
- other:+86 added−25 removed
Provenance
- Commit
cbc6765- Tree
300a138- Author
Zhihua Lai <zhihualai@microsoft.com>- Committer
Zhihua Lai <zhihualai@microsoft.com>- Parent 1
1ac08db- Parent 2
240603f
6 files changed+207 added−29 removed
modified:src/click/core.py+6 added-1 removed
3605 unmodified lines3606 return self.metavar3607 var = self.type.get_metavar(param=self, ctx=ctx)3608 if not var:3609 var = self.name.upper()3610+ # Types like ``Choice`` and ``DateTime`` already surround their metavar3611+ # with square brackets to enumerate the allowed values. Reuse those3612+ # outer brackets as the optional-argument indicator instead of wrapping3613+ # the metavar in a second pair, which would produce ``[[a|b|c]]``.3614+ already_bracketed = var.startswith("[") and var.endswith("]")3615 if self.deprecated:3616 var += "!"3612- if not self.required:3617+ if not self.required and not already_bracketed:3618 var = f"[{var}]"3619 if self.nargs != 1:3620 var += "..."3621 return var60 unmodified linesmodified:src/click/decorators.py+30 added-6 removed
432 unmodified lines433 :func:`importlib.metadata.version` to get the version for the434 ``package_name``.435 436 If ``package_name`` is not provided, Click will try to detect it by437- inspecting the stack frames. This will be used to detect the438- version, so it must match the name of the installed package.437+ inspecting the stack frames. If the detected (or given) name does438+ not match an installed distribution, Click resolves it as an import439+ (top-level module) name via440+ :func:`importlib.metadata.packages_distributions`, so e.g. ``PIL``441+ resolves to the ``Pillow`` distribution.442 443 :param version: The version number to show. If not provided, Click444 will try to detect it.445 :param param_decls: One or more option names. Defaults to the single16 unmodified lines462 Use :mod:`importlib.metadata` instead of ``pkg_resources``. The463 version is detected based on the package name, not the entry464 point name. The Python package name must match the installed465 package name, or be passed with ``package_name=``.466+467+ .. versionchanged:: 8.4.2468+ When ``package_name`` does not match an installed distribution,469+ Click now resolves it as an import (top-level module).470 """471 if message is None:472 message = _("%(prog)s, version %(version)s")473 19 unmodified lines493 return494 495 nonlocal prog_name496 nonlocal version497+ nonlocal package_name498 499 if prog_name is None:500 prog_name = ctx.find_root().info_name501 2 unmodified lines504 505 try:506 version = importlib.metadata.version(package_name)507 except importlib.metadata.PackageNotFoundError:508+ # The given name didn't match an installed distribution.509+ # Try resolving it as an import (top-level module) name,510+ # e.g. ``PIL`` is provided by the ``Pillow`` distribution.511+ distributions = importlib.metadata.packages_distributions().get(512+ package_name, []513+ )514+ if len(distributions) == 1:515+ package_name = distributions[0]516+ version = importlib.metadata.version(package_name)517+ elif len(distributions) > 1:518+ raise RuntimeError(519+ f"{package_name!r} maps to multiple installed"520+ f" distributions ({', '.join(distributions)})."521+ " Pass 'package_name' to disambiguate."522+ ) from None523+ else:500- raise RuntimeError(501- f"{package_name!r} is not installed. Try passing"502- " 'package_name' instead."503- ) from None524+ raise RuntimeError(525+ f"{package_name!r} is not installed. Try passing"526+ " 'package_name' instead."527+ ) from None528 529 if version is None:530 raise RuntimeError(531 f"Could not determine the version for {package_name!r} automatically."44 unmodified linesmodified:src/click/shell_completion.py+41 added-17 removed
20 unmodified lines21 ctx_args: cabc.MutableMapping[str, t.Any],22 prog_name: str,23 complete_var: str,24 instruction: str,25-) -> int:25+) -> t.Literal[0, 1]:26 """Perform shell completion for the given CLI program.27 28 :param cli: Command being called.29 :param ctx_args: Extra arguments to pass to24 unmodified lines54 55 return 156 57 58-class CompletionItem:58+if t.TYPE_CHECKING:59+ from typing_extensions import TypeVar60+61+ # `Any` is used as default for backwards compatibility (instead of e.g. `str`)62+ _ValueT_co = TypeVar("_ValueT_co", covariant=True, default=t.Any)63+else:64+ _ValueT_co = t.TypeVar("_ValueT_co", covariant=True)65+66+67+class CompletionItem(t.Generic[_ValueT_co]):68 """Represents a completion value and metadata about the value. The69 default metadata is ``type`` to indicate special shell handling,70 and ``help`` if a shell supports showing a help string next to the71 value.14 unmodified lines86 __slots__ = ("value", "type", "help", "_info")87 88 def __init__(89 self,81- value: t.Any,90+ value: _ValueT_co,91 type: str = "plain",92 help: str | None = None,93 **kwargs: t.Any,94 ) -> None:86- self.value: t.Any = value95+ self.value: _ValueT_co = value96 self.type: str = type97 self.help: str | None = help98 self._info = kwargs99 168 unmodified lines268 }269 """270 271 272+class _SourceVarsDict(t.TypedDict):273+ complete_func: str274+ complete_var: str275+ prog_name: str276+277+278 class ShellComplete:279 """Base class for providing shell completion support. A subclass for280 a given shell will override attributes and methods to implement the281 completion instructions (``source`` and ``complete``).41 unmodified lines323 """324 safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), flags=re.ASCII)325 return f"_{safe_name}_completion"326 312- def source_vars(self) -> dict[str, t.Any]:327+ def source_vars(self) -> _SourceVarsDict:328 """Vars for formatting :attr:`source_template`.329 330 By default this provides ``complete_func``, ``complete_var``,331 and ``prog_name``.18 unmodified lines350 subclasses.351 """352 raise NotImplementedError353 339- def get_completions(self, args: list[str], incomplete: str) -> list[CompletionItem]:354+ def get_completions(355+ self, args: list[str], incomplete: str356+ ) -> list[CompletionItem[str]]:357 """Determine the context and last complete command or parameter358 from the complete args. Call that object's ``shell_complete``359 method to get the completions for the incomplete value.360 3 unmodified lines364 ctx = _resolve_context(self.cli, self.ctx_args, self.prog_name, args)365 obj, incomplete = _resolve_incomplete(ctx, args, incomplete)366 return obj.shell_complete(ctx, incomplete)367 351- def format_completion(self, item: CompletionItem) -> str:368+ def format_completion(self, item: CompletionItem[str]) -> str:369 """Format a completion item into the form recognized by the370 shell script. This must be implemented by subclasses.371 372 :param item: Completion item to format.67 unmodified lines440 incomplete = ""441 442 return args, incomplete443 427- def format_completion(self, item: CompletionItem) -> str:444+ def format_completion(self, item: CompletionItem[t.Any]) -> str:445 return f"{item.type},{item.value}"446 447 448 class ZshComplete(ShellComplete):13 unmodified lines462 incomplete = ""463 464 return args, incomplete465 449- def format_completion(self, item: CompletionItem) -> str:466+ def format_completion(self, item: CompletionItem[str]) -> str:467 help_ = item.help or "_"468 # The zsh completion script uses `_describe` on items with help469 # texts (which splits the item help from the item value at the470 # first unescaped colon) and `compadd` on items without help29 unmodified lines500 args.pop()501 502 return args, incomplete503 487- def format_completion(self, item: CompletionItem) -> str:504+ def format_completion(self, item: CompletionItem[str]) -> str:505 """506 .. versionchanged:: 8.4.2507 Escape newlines and replace tabs with spaces in the help text to508 fix completion errors with multi-line help strings.29 unmodified lines538 incomplete = ""539 540 return args, incomplete541 525- def format_completion(self, item: CompletionItem) -> str:542+ def format_completion(self, item: CompletionItem[str]) -> str:543 # PowerShell parses the response by splitting on newlines and544 # consuming three lines per completion (type, value, help).545 # Multi-line help text would break that framing, so collapse546 # newlines and carriage returns to spaces. The literal "_"4 unmodified lines551 help_ = "_"552 return f"{item.type}\n{item.value}\n{help_}"553 554 538-ShellCompleteType = t.TypeVar("ShellCompleteType", bound="type[ShellComplete]")539-540-541-_available_shells: dict[str, type[ShellComplete]] = {555+_available_shells: t.Final[dict[str, type[ShellComplete]]] = {556 "bash": BashComplete,557 "fish": FishComplete,558 "powershell": PowerShellComplete,559 "zsh": ZshComplete,560 }561 562+_ShellCompleteT = t.TypeVar("_ShellCompleteT", bound="ShellComplete")563 564+565 def add_completion_class(550- cls: ShellCompleteType, name: str | None = None551-) -> ShellCompleteType:566+ cls: type[_ShellCompleteT], name: str | None = None567+) -> type[_ShellCompleteT]:568 """Register a :class:`ShellComplete` subclass under the given name.569 The name will be provided by the completion instruction environment570 variable during completion.571 9 unmodified lines581 582 return cls583 584 585+@t.overload586+def get_completion_class(shell: t.Literal["bash"]) -> type[BashComplete]: ...587+@t.overload588+def get_completion_class(shell: t.Literal["fish"]) -> type[FishComplete]: ...589+@t.overload590+def get_completion_class(shell: t.Literal["zsh"]) -> type[ZshComplete]: ...591+@t.overload592+def get_completion_class(shell: str) -> type[ShellComplete] | None: ...593 def get_completion_class(shell: str) -> type[ShellComplete] | None:594 """Look up a registered :class:`ShellComplete` subclass by the name595 provided by the completion instruction environment variable. If the596 name isn't registered, returns ``None``.205 unmodified linesmodified:tests/test_basic.py+119 added
567 unmodified lines568 result = runner.invoke(cli, ["--help"])569 assert result.output.startswith("Usage: cli [OPTIONS] {not-none|none}\n")570 571 572+def test_choice_argument_optional_metavar(runner):573+ """Optional Choice arguments reuse the type's brackets instead of doubling.574+575+ Without this the usage line for a ``Choice`` argument with ``nargs=-1`` or576+ ``required=False`` rendered as ``[[a|b|c]]``: one pair from ``Choice`` to577+ enumerate values, a second pair from ``Argument`` to mark it optional.578+ """579+580+ @click.command()581+ @click.argument("method", type=click.Choice(["foo", "bar", "baz"]), nargs=-1)582+ def cli_variadic(method):583+ pass584+585+ @click.command()586+ @click.argument("method", type=click.Choice(["foo", "bar", "baz"]), required=False)587+ def cli_optional(method):588+ pass589+590+ variadic = runner.invoke(cli_variadic, ["--help"]).output591+ assert "Usage: cli-variadic [OPTIONS] [foo|bar|baz]...\n" in variadic592+ assert "[[foo|bar|baz]]" not in variadic593+594+ optional = runner.invoke(cli_optional, ["--help"]).output595+ assert "Usage: cli-optional [OPTIONS] [foo|bar|baz]\n" in optional596+ assert "[[foo|bar|baz]]" not in optional597+598+599+def test_datetime_argument_optional_metavar(runner):600+ """``DateTime`` arguments behave the same way as ``Choice``."""601+602+ @click.command()603+ @click.argument("when", type=click.DateTime(formats=["%Y-%m-%d"]), required=False)604+ def cli(when):605+ pass606+607+ result = runner.invoke(cli, ["--help"])608+ assert "Usage: cli [OPTIONS] [%Y-%m-%d]\n" in result.output609+ assert "[[%Y-%m-%d]]" not in result.output610+611+612 def test_datetime_option_default(runner):613 @click.command()614 @click.option("--start_date", type=click.DateTime())615 def cli(start_date):162 unmodified lines778 )779 result = runner.invoke(cli, ["--help"])780 assert result.exit_code == 0781 assert "default: not found" in result.output782+783+784+def test_version_option_resolves_import_name_to_distribution(runner, monkeypatch):785+ """When ``package_name`` (detected or passed) is an import name that786+ differs from its installed distribution name (``PIL`` vs ``Pillow``),787+ ``version_option`` resolves it via ``packages_distributions()`` instead788+ of raising ``RuntimeError``.789+ """790+ import importlib.metadata791+792+ def fake_version(name):793+ if name == "pillow":794+ return "10.4.0"795+ raise importlib.metadata.PackageNotFoundError(name)796+797+ monkeypatch.setattr(importlib.metadata, "version", fake_version)798+ monkeypatch.setattr(799+ importlib.metadata,800+ "packages_distributions",801+ lambda: {"PIL": ["pillow"]},802+ )803+804+ @click.command()805+ @click.version_option(package_name="PIL")806+ def cli():807+ pass808+809+ result = runner.invoke(cli, ["--version"], prog_name="imageapp")810+ assert result.exit_code == 0811+ assert "10.4.0" in result.output812+813+814+def test_version_option_ambiguous_import_name_errors(runner, monkeypatch):815+ """When an import name maps to multiple installed distributions, the816+ user must disambiguate. The error names the candidates.817+ """818+ import importlib.metadata819+820+ def fake_version(name):821+ raise importlib.metadata.PackageNotFoundError(name)822+823+ monkeypatch.setattr(importlib.metadata, "version", fake_version)824+ monkeypatch.setattr(825+ importlib.metadata,826+ "packages_distributions",827+ lambda: {"plug": ["foo-plug", "bar-plug"]},828+ )829+830+ @click.command()831+ @click.version_option(package_name="plug")832+ def cli():833+ pass834+835+ result = runner.invoke(cli, ["--version"])836+ assert result.exit_code != 0837+ msg = str(result.exception)838+ assert "multiple installed distributions" in msg839+ assert "foo-plug" in msg840+ assert "bar-plug" in msg841+842+843+def test_version_option_unknown_package_errors(runner, monkeypatch):844+ """When the name resolves to no distribution, keep the existing error."""845+ import importlib.metadata846+847+ def fake_version(name):848+ raise importlib.metadata.PackageNotFoundError(name)849+850+ monkeypatch.setattr(importlib.metadata, "version", fake_version)851+ monkeypatch.setattr(importlib.metadata, "packages_distributions", lambda: {})852+853+ @click.command()854+ @click.version_option(package_name="nonexistent")855+ def cli():856+ pass857+858+ result = runner.invoke(cli, ["--version"])859+ assert result.exit_code != 0860+ assert "not installed" in str(result.exception)modified:tests/test_options.py+2 added-4 removed
3318 unmodified lines3319 @click.option("--xyz", default="second")3320 def cli(xyz):3321 click.echo(repr(xyz), nl=False)3322 3323- result = runner.invoke(cli, [])3324- assert result.exit_code == 13325- assert isinstance(result.exception, UserWarning)3326- assert "used more than once" in str(result.exception)3323+ with pytest.warns(UserWarning, match="used more than once"):3324+ runner.invoke(cli, [])3325 3326 3327 @pytest.mark.parametrize(3328 ("args", "expected"),187 unmodified linesmodified:CHANGES.md+9 added-1 removed
11 unmodified lines12 a `Positional arguments` section when argument help is available. {issue}`2983` {pr}`3473`13 14 ## Version 8.4.215 16-Unreleased16+Released 2026-06-2417 18 - Fix Fish shell completion broken in `8.4.0` by {pr}`3126`. Newlines and19 tabs in option help text are now escaped, keeping the original completion20 format while still supporting multi-line help. {issue}`3502`9 unmodified lines30 - `echo_via_pager` and `get_pager_file` no longer close a borrowed stdout31 stream when no external pager runs, completing the partial32 `I/O operation on closed file` fix from {pr}`3482`. {issue}`3449`33 {pr}`3533`34+- Fix CLI usage symopsis for optional arguments producing double square brackets35+ `[[a|b|c]]...` whose type already brackets their metavar. {pr}`3578`36+- {func}`version_option` resolves a `package_name` that does not match an37+ installed distribution as an import (top-level module) name via38+ {func}`importlib.metadata.packages_distributions`. Packages whose39+ top-level module name differs from their distribution name (`PIL` vs40+ `Pillow`, `jwt` vs `PyJWT`) no longer raise `RuntimeError` out of the41+ box. {issue}`2331` {issue}`1884` {issue}`3125` {pr}`3582`42 43 ## Version 8.4.144 45 Released 2026-05-211532 unmodified lines