Merge pull request #1582 from teymour-aldridge/version-check
Before adoption: this commit came in with the history the project adopted, so no landing records it.
changed version_option default package from pkg_resources to importli…
authored by David Lord · committed by GitHub · parents 6bdbea0, b38cb0e · Browse files · 5 files·+109 added−47 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+109 added−47 removed
- other:+109 added−47 removed
Provenance
- Commit
77ca520- Tree
0fe932b- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
6bdbea0- Parent 2
b38cb0e
5 files changed+109 added−47 removed
modified:requirements/dev.txt+2 added
17 unmodified lines18 filelock==3.0.12 # via tox, virtualenv19 identify==1.4.16 # via pre-commit20 idna==2.9 # via requests21 imagesize==1.2.0 # via sphinx22+importlib-metadata==1.6.1 # via -r requirements/tests.in23 jinja2==2.11.2 # via sphinx24 markupsafe==1.1.1 # via jinja225 more-itertools==8.3.0 # via pytest26 nodeenv==1.3.5 # via pre-commit24 unmodified lines51 tox==3.15.2 # via -r requirements/dev.in52 urllib3==1.25.9 # via requests53 virtualenv==20.0.21 # via pre-commit, tox54 wcwidth==0.1.9 # via pytest55+zipp==3.1.0 # via importlib-metadata56 57 # The following packages are considered to be unsafe in a requirements file:58 # pip59 # setuptoolsmodified:requirements/tests.in+1 added
1 pytest2 colorama3+importlib_metadatamodified:requirements/tests.txt+2 added
4 unmodified lines5 # pip-compile requirements/tests.in6 #7 attrs==19.3.0 # via pytest8 colorama==0.4.3 # via -r requirements/tests.in9+importlib-metadata==1.6.1 # via -r requirements/tests.in10 more-itertools==8.3.0 # via pytest11 packaging==20.4 # via pytest12 pluggy==0.13.1 # via pytest13 py==1.8.1 # via pytest14 pyparsing==2.4.7 # via packaging15 pytest==5.4.3 # via -r requirements/tests.in16 six==1.15.0 # via packaging17 wcwidth==0.1.9 # via pytest18+zipp==3.1.0 # via importlib-metadatamodified:src/click/decorators.py+101 added-47 removed
1 import inspect2-import sys2 from functools import update_wrapper3 4 from .core import Argument5 from .core import Command240 unmodified lines246 247 return decorator248 249 251-def version_option(version=None, *param_decls, **attrs):252- """Adds a ``--version`` option which immediately ends the program253- printing out the version number. This is implemented as an eager254- option that prints the version and exits the program in the callback.250+def version_option(251+ version=None,252+ *param_decls,253+ package_name=None,254+ prog_name=None,255+ message="%(prog)s, version %(version)s",256+ **kwargs,257+):258+ """Add a ``--version`` option which immediately prints the version259+ number and exits the program.260 256- :param version: the version number to show. If not provided Click257- attempts an auto discovery via setuptools.258- :param prog_name: the name of the program (defaults to autodetection)259- :param message: custom message to show instead of the default260- (``'%(prog)s, version %(version)s'``)261- :param others: everything else is forwarded to :func:`option`.261+ If ``version`` is not provided, Click will try to detect it using262+ :func:`importlib.metadata.version` to get the version for the263+ ``package_name``. On Python < 3.8, the ``importlib_metadata``264+ backport must be installed.265+266+ If ``package_name`` is not provided, Click will try to detect it by267+ inspecting the stack frames. This will be used to detect the268+ version, so it must match the name of the installed package.269+270+ :param version: The version number to show. If not provided, Click271+ will try to detect it.272+ :param param_decls: One or more option names. Defaults to the single273+ value ``"--version"``.274+ :param package_name: The package name to detect the version from. If275+ not provided, Click will try to detect it.276+ :param prog_name: The name of the CLI to show in the message. If not277+ provided, it will be detected from the command.278+ :param message: The message to show. The values ``%(prog)s``,279+ ``%(package)s``, and ``%(version)s`` are available.280+ :param kwargs: Extra arguments are passed to :func:`option`.281+ :raise RuntimeError: ``version`` could not be detected.282+283+ .. versionchanged:: 8.0284+ Add the ``package_name`` parameter, and the ``%(package)s``285+ value for messages.286+287+ .. versionchanged:: 8.0288+ Use :mod:`importlib.metadata` instead of ``pkg_resources``.289 """263- if version is None:264- if hasattr(sys, "_getframe"):265- module = sys._getframe(1).f_globals.get("__name__")266- else:267- module = ""290+ if version is None and package_name is None:291+ frame = inspect.currentframe()292+ f_globals = frame.f_back.f_globals if frame is not None else None293+ # break reference cycle294+ # https://docs.python.org/3/library/inspect.html#the-interpreter-stack295+ del frame296 269- def decorator(f):270- prog_name = attrs.pop("prog_name", None)271- message = attrs.pop("message", "%(prog)s, version %(version)s")297+ if f_globals is not None:298+ package_name = f_globals.get("__name__")299 273- def callback(ctx, param, value):274- if not value or ctx.resilient_parsing:275- return276- prog = prog_name277- if prog is None:278- prog = ctx.find_root().info_name279- ver = version280- if ver is None:300+ if package_name == "__main__":301+ package_name = f_globals.get("__package__")302+303+ if package_name:304+ package_name = package_name.partition(".")[0]305+306+ def callback(ctx, param, value):307+ if not value or ctx.resilient_parsing:308+ return309+310+ nonlocal prog_name311+ nonlocal version312+313+ if prog_name is None:314+ prog_name = ctx.find_root().info_name315+316+ if version is None and package_name is not None:317+ try:318+ from importlib import metadata319+ except ImportError:320+ # Python < 3.8321 try:282- import pkg_resources322+ import importlib_metadata as metadata323 except ImportError:284- pass285- else:286- for dist in pkg_resources.working_set:287- scripts = dist.get_entry_map().get("console_scripts") or {}288- for entry_point in scripts.values():289- if entry_point.module_name == module:290- ver = dist.version291- break292- if ver is None:293- raise RuntimeError("Could not determine version")294- echo(message % {"prog": prog, "version": ver}, color=ctx.color)295- ctx.exit()324+ metadata = None325 297- attrs.setdefault("is_flag", True)298- attrs.setdefault("expose_value", False)299- attrs.setdefault("is_eager", True)300- attrs.setdefault("help", "Show the version and exit.")301- attrs["callback"] = callback302- return option(*(param_decls or ("--version",)), **attrs)(f)326+ if metadata is None:327+ raise RuntimeError(328+ "Install 'importlib_metadata' to get the version on Python < 3.8."329+ )330 304- return decorator331+ try:332+ version = metadata.version(package_name)333+ except metadata.PackageNotFoundError:334+ raise RuntimeError(335+ f"{package_name!r} is not installed. Try passing"336+ " 'package_name' instead."337+ )338 339+ if version is None:340+ raise RuntimeError(341+ f"Could not determine the version for {package_name!r} automatically."342+ )343 344+ echo(345+ message % {"prog": prog_name, "package": package_name, "version": version},346+ color=ctx.color,347+ )348+ ctx.exit()349+350+ if not param_decls:351+ param_decls = ("--version",)352+353+ kwargs.setdefault("is_flag", True)354+ kwargs.setdefault("expose_value", False)355+ kwargs.setdefault("is_eager", True)356+ kwargs.setdefault("help", "Show the version and exit.")357+ kwargs["callback"] = callback358+ return option(*param_decls, **kwargs)359+360+361 def help_option(*param_decls, **attrs):362 """Adds a ``--help`` option which immediately ends the program363 printing out the help page. This is usually unnecessary to add as364 this is added by default to all commands unless suppressed.21 unmodified linesmodified:CHANGES.rst+3 added
11 unmodified lines12 parameter. :issue:`1264`, :pr:`1329`13 - Add an optional parameter to ``ProgressBar.update`` to set the14 ``current_item``. :issue:`1226`, :pr:`1332`15 - Include ``--help`` option in completion. :pr:`1504`16+- ``version_option`` uses ``importlib.metadata`` (or the17+ ``importlib_metadata`` backport) instead of ``pkg_resources``.18+ :issue:`1582`19 20 21 Version 7.1.222 -------------635 unmodified lines