refactor version_option
Before adoption: this commit came in with the history the project adopted, so no landing records it.
option() returns a decorator, no need for inner decorator function optional package_name parameter to skip stack frame detection package_name is available in message format use nonlocal keyword for modifying args from callback only detect version if package name was detected show error if importlib_metadata needs to be installed show error if detected package name isn't an installed package name show detected package name in error when version wasn't detected rewrite docs
authored by David Lord · committed by David Lord · parent cb37854 · Browse files · 1 file·+91 added−39 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+91 added−39 removed
- other:+91 added−39 removed
Provenance
- Commit
81ff0ae- Tree
ba977f7- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
cb37854
1 file changed+91 added−39 removed
modified:src/click/decorators.py+91 added-39 removed
245 unmodified lines246 247 return decorator248 249 250-def version_option(version=None, *param_decls, **attrs):251- """Adds a ``--version`` option which immediately ends the program252- printing out the version number. This is implemented as an eager253- 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 255- :param version: the version number to show. If not provided Click256- attempts an auto discovery via setuptools.257- :param prog_name: the name of the program (defaults to autodetection)258- :param message: custom message to show instead of the default259- (``'%(prog)s, version %(version)s'``)260- :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 """290+ if version is None and package_name is None:291+ frame = inspect.currentframe()292 263- def decorator(f):264- prog_name = attrs.pop("prog_name", None)265- message = attrs.pop("message", "%(prog)s, version %(version)s")293+ if frame is not None:294+ package_name = frame.f_back.f_globals.get("__name__").partition(".")[0]295 267- def callback(ctx, param, value):268- if not value or ctx.resilient_parsing:269- return270- prog = prog_name271- if prog is None:272- prog = ctx.find_root().info_name273- ver = version274- if ver is None:296+ def callback(ctx, param, value):297+ if not value or ctx.resilient_parsing:298+ return299+300+ nonlocal prog_name301+ nonlocal version302+303+ if prog_name is None:304+ prog_name = ctx.find_root().info_name305+306+ if version is None and package_name is not None:307+ try:308+ from importlib import metadata309+ except ImportError:310+ # Python < 3.8311 try:276- from importlib.metadata import version as get_version312+ import importlib_metadata as metadata313 except ImportError:278- try:279- from importlib_metadata import version as get_version280- except ImportError:281- get_version = None282- if get_version is not None:283- ver = get_version(prog)284- if ver is None:285- raise RuntimeError("Could not determine version")286- echo(message % {"prog": prog, "version": ver}, color=ctx.color)287- ctx.exit()314+ metadata = None315 289- attrs.setdefault("is_flag", True)290- attrs.setdefault("expose_value", False)291- attrs.setdefault("is_eager", True)292- attrs.setdefault("help", "Show the version and exit.")293- attrs["callback"] = callback294- return option(*(param_decls or ("--version",)), **attrs)(f)316+ if metadata is None:317+ raise RuntimeError(318+ "Install 'importlib_metadata' to get the version on Python < 3.8."319+ )320 296- return decorator321+ try:322+ version = metadata.version(package_name)323+ except metadata.PackageNotFoundError:324+ raise RuntimeError(325+ f"{package_name!r} is not installed. Try passing"326+ " 'package_name' instead."327+ )328 329+ if version is None:330+ raise RuntimeError(331+ f"Could not determine the version for {package_name!r} automatically."332+ )333 334+ echo(335+ message % {"prog": prog_name, "package": package_name, "version": version},336+ color=ctx.color,337+ )338+ ctx.exit()339+340+ if not param_decls:341+ param_decls = ("--version",)342+343+ kwargs.setdefault("is_flag", True)344+ kwargs.setdefault("expose_value", False)345+ kwargs.setdefault("is_eager", True)346+ kwargs.setdefault("help", "Show the version and exit.")347+ kwargs["callback"] = callback348+ return option(*param_decls, **kwargs)349+350+351 def help_option(*param_decls, **attrs):352 """Adds a ``--help`` option which immediately ends the program353 printing out the help page. This is usually unnecessary to add as354 this is added by default to all commands unless suppressed.21 unmodified lines