Fix `package_name` resolution when module differs from distribution name (#3582)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents 916883a, bec5928 · Browse files · 3 files·+115 added−6 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+115 added−6 removed
- tests:+79 added−0 removed
- other:+36 added−6 removed
Provenance
- Commit
7a16b20- Tree
491b164- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
916883a- Parent 2
bec5928
3 files changed+115 added−6 removed
modified: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:tests/test_basic.py+79 added
777 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:CHANGES.md+6 added
18 unmodified lines19 `I/O operation on closed file` fix from {pr}`3482`. {issue}`3449`20 {pr}`3533`21 - Fix CLI usage symopsis for optional arguments producing double square brackets22 `[[a|b|c]]...` whose type already brackets their metavar. {pr}`3578`23+- {func}`version_option` resolves a `package_name` that does not match an24+ installed distribution as an import (top-level module) name via25+ {func}`importlib.metadata.packages_distributions`. Packages whose26+ top-level module name differs from their distribution name (`PIL` vs27+ `Pillow`, `jwt` vs `PyJWT`) no longer raise `RuntimeError` out of the28+ box. {issue}`2331` {issue}`1884` {issue}`3125` {pr}`3582`29 30 ## Version 8.4.131 32 Released 2026-05-211532 unmodified lines