Add `@custom_version_option`, freeze `@version_option`
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kevin Deldycke · committed by Kevin Deldycke · parent 16fc00e · Browse files · 5 files·+84 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Refs: https://github.com/pallets/click/discussions/3527
Diff stats
5 files+84 added−0 removed
- tests:+23 added−0 removed
- other:+61 added−0 removed
Provenance
- Commit
9f9b149- Tree
f201eaa- Author
Kevin Deldycke <kevin@deldycke.com>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
16fc00e
5 files changed+84 added−0 removed
modified:docs/api.md+4 added
40 unmodified lines41 .. autofunction:: version_option42 ```43 44 ```{eval-rst}45+.. autofunction:: custom_version_option46+```47+48+```{eval-rst}49 .. autofunction:: help_option50 ```51 52 ```{eval-rst}313 unmodified linesmodified:src/click/__init__.py+1 added
16 unmodified lines17 from .core import ParameterSource as ParameterSource18 from .decorators import argument as argument19 from .decorators import command as command20 from .decorators import confirmation_option as confirmation_option21+from .decorators import custom_version_option as custom_version_option22 from .decorators import group as group23 from .decorators import help_option as help_option24 from .decorators import make_pass_decorator as make_pass_decorator25 from .decorators import option as option102 unmodified linesmodified:src/click/decorators.py+52 added
438 unmodified lines439 (top-level module) name via440 :func:`importlib.metadata.packages_distributions`, so e.g. ``PIL``441 resolves to the ``Pillow`` distribution.442 443+ .. note::444+ The parameters and message variables accepted by this option are445+ frozen: no new slots will be added, to keep the common case simple446+ and predictable. If you need values it does not expose, such as a447+ file path, the Python version, or git metadata, use448+ :func:`custom_version_option` to render the output yourself.449+450+ Rationale: `discussion #3527451+ <https://github.com/pallets/click/discussions/3527>`_.452+453 :param version: The version number to show. If not provided, Click454 will try to detect it.455 :param param_decls: One or more option names. Defaults to the single456 value ``"--version"``.100 unmodified lines557 kwargs["callback"] = callback558 return option(*param_decls, **kwargs)559 560 561+def custom_version_option(562+ callback: t.Callable[[Context], str],563+ *param_decls: str,564+ **kwargs: t.Any,565+) -> t.Callable[[FC], FC]:566+ """Add a ``--version`` option whose output is produced by ``callback``.567+568+ This is the customizable companion to :func:`version_option`. Where569+ :func:`version_option` is intentionally limited to a fixed message and570+ a small set of values, this option calls ``callback`` to build the571+ whole string to print. Use it when you need values that572+ :func:`version_option` does not expose, such as a file path, the573+ Python version, or git metadata.574+575+ :param callback: Called with the current :class:`Context` when the576+ option is invoked. Its return value is printed, then the program577+ exits.578+ :param param_decls: One or more option names. Defaults to the single579+ value ``--version``.580+ :param kwargs: Extra arguments are passed to :func:`option`.581+582+ .. versionadded:: 8.5.0583+ """584+585+ def show_version(ctx: Context, param: Parameter, value: bool) -> None:586+ if not value or ctx.resilient_parsing:587+ return588+589+ echo(callback(ctx), color=ctx.color)590+ ctx.exit()591+592+ if not param_decls:593+ param_decls = ("--version",)594+595+ kwargs.setdefault("is_flag", True)596+ kwargs.setdefault("expose_value", False)597+ kwargs.setdefault("is_eager", True)598+ kwargs.setdefault("help", _("Show the version and exit."))599+ kwargs["callback"] = show_version600+ return option(*param_decls, **kwargs)601+602+603 def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:604 """Pre-configured ``--help`` option which immediately prints the help page605 and exits the program.606 21 unmodified linesmodified:tests/test_basic.py+23 added
855 unmodified lines856 857 result = runner.invoke(cli, ["--version"])858 assert result.exit_code != 0859 assert "not installed" in str(result.exception)860+861+862+@pytest.mark.parametrize("args", [["--version"], ["-V"]])863+def test_custom_version_option(runner, args):864+ @click.command()865+ @click.custom_version_option(lambda ctx: "custom 9.9.9", "-V", "--version")866+ def cli():867+ pass868+869+ result = runner.invoke(cli, args)870+ assert result.exit_code == 0871+ assert result.output == "custom 9.9.9\n"872+873+874+def test_custom_version_option_receives_context(runner):875+ @click.command()876+ @click.custom_version_option(lambda ctx: f"{ctx.info_name} 1.0")877+ def cli():878+ pass879+880+ result = runner.invoke(cli, ["--version"], prog_name="mytool")881+ assert result.exit_code == 0882+ assert result.output == "mytool 1.0\n"modified:CHANGES.md+4 added
9 unmodified lines10 prompt when the output stream does not support them, matching `echo()`.11 This stripping was lost in `8.4.0` when {pr}`2969` began writing the12 prompt with `input()` directly. {issue}`3572` {pr}`3653`13 - Fix test failures when using pytest >= 9.1. {pr}`3656`14+- Add {func}`custom_version_option`, a `--version` option whose output is15+ produced by a callback, covering cases {func}`version_option` intentionally16+ does not. The feature set of {func}`version_option` is now frozen; see17+ [discussion #3527](https://github.com/pallets/click/discussions/3527). {pr}`3581`18 19 ## Version 8.4.220 21 Released 2026-06-241561 unmodified lines