Skip to content
Myr

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

5 files+109 added−47 removed

modified:requirements/dev.txt+2 added
17 unmodified lines
18filelock==3.0.12 # via tox, virtualenv19identify==1.4.16 # via pre-commit20idna==2.9 # via requests21imagesize==1.2.0 # via sphinx22importlib-metadata==1.6.1 # via -r requirements/tests.in23jinja2==2.11.2 # via sphinx24markupsafe==1.1.1 # via jinja225more-itertools==8.3.0 # via pytest26nodeenv==1.3.5 # via pre-commit
24 unmodified lines
51tox==3.15.2 # via -r requirements/dev.in52urllib3==1.25.9 # via requests53virtualenv==20.0.21 # via pre-commit, tox54wcwidth==0.1.9 # via pytest55zipp==3.1.0 # via importlib-metadata5657# The following packages are considered to be unsafe in a requirements file:58# pip59# setuptools
modified:requirements/tests.in+1 added
1pytest2colorama3importlib_metadata
modified:requirements/tests.txt+2 added
4 unmodified lines
5# pip-compile requirements/tests.in6#7attrs==19.3.0 # via pytest8colorama==0.4.3 # via -r requirements/tests.in9importlib-metadata==1.6.1 # via -r requirements/tests.in10more-itertools==8.3.0 # via pytest11packaging==20.4 # via pytest12pluggy==0.13.1 # via pytest13py==1.8.1 # via pytest14pyparsing==2.4.7 # via packaging15pytest==5.4.3 # via -r requirements/tests.in16six==1.15.0 # via packaging17wcwidth==0.1.9 # via pytest18zipp==3.1.0 # via importlib-metadata
modified:src/click/decorators.py+101 added-47 removed
1import inspect2import sys2from functools import update_wrapper34from .core import Argument5from .core import Command
240 unmodified lines
246247 return decorator248249251def 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.250def 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.260256 :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.265266 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.269270 :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.282283 .. versionchanged:: 8.0284 Add the ``package_name`` parameter, and the ``%(package)s``285 value for messages.286287 .. 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 frame296269 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__")299273 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__")302303 if package_name:304 package_name = package_name.partition(".")[0]305306 def callback(ctx, param, value):307 if not value or ctx.resilient_parsing:308 return309310 nonlocal prog_name311 nonlocal version312313 if prog_name is None:314 prog_name = ctx.find_root().info_name315316 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 = None325297 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 )330304 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 )338339 if version is None:340 raise RuntimeError(341 f"Could not determine the version for {package_name!r} automatically."342 )343344 echo(345 message % {"prog": prog_name, "package": package_name, "version": version},346 color=ctx.color,347 )348 ctx.exit()349350 if not param_decls:351 param_decls = ("--version",)352353 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)359360361def 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 lines
modified:CHANGES.rst+3 added
11 unmodified lines
12 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`192021Version 7.1.222-------------
635 unmodified lines