Skip to content
Myr

Add `@custom_version_option`, freeze `@version_option` (#3581)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Rowlando13 · committed by GitHub · parents 16fc00e, 4453103 · Browse files · 6 files+92 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+92 added−1 removed

  • tests:+23 added−0 removed
  • other:+69 added−1 removed

6 files+92 added−1 removed

modified:docs/api.md+4 added
40 unmodified lines
41.. autofunction:: version_option42```4344```{eval-rst}45.. autofunction:: custom_version_option46```4748```{eval-rst}49.. autofunction:: help_option50```5152```{eval-rst}
313 unmodified lines
modified:docs/utils.md+8 added-1 removed
126 unmodified lines
127 for idx in range(50000):128 print(idx, file=pager)129```130131```{hint} Why print instead of echo?132The pager object deals with ANSI color and style codes itself: they are kept or133stripped depending on what the pager supports, exactly as {func}`echo` would do.134Any code that writes to a file, including plain {func}`print`, can therefore be135used with it.136```137138## Screen Clearing139140```{versionadded} 2.0141```
247 unmodified lines
389import time390391with click.progressbar([1, 2, 3]) as bar:392 for x in bar:386 print(f"sleep({x})...")393 click.echo(f"sleep({x})...")394 time.sleep(x)395```396397Another useful feature is to associate a label with the progress bar which will be shown preceding the progress bar:
20 unmodified lines
modified:src/click/__init__.py+1 added
16 unmodified lines
17from .core import ParameterSource as ParameterSource18from .decorators import argument as argument19from .decorators import command as command20from .decorators import confirmation_option as confirmation_option21from .decorators import custom_version_option as custom_version_option22from .decorators import group as group23from .decorators import help_option as help_option24from .decorators import make_pass_decorator as make_pass_decorator25from .decorators import option as option
102 unmodified lines
modified:src/click/decorators.py+52 added
438 unmodified lines
439 (top-level module) name via440 :func:`importlib.metadata.packages_distributions`, so e.g. ``PIL``441 resolves to the ``Pillow`` distribution.442443 .. 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.449450 Rationale: `discussion #3527451 <https://github.com/pallets/click/discussions/3527>`_.452453 :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 lines
557 kwargs["callback"] = callback558 return option(*param_decls, **kwargs)559560561def 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``.567568 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.574575 :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`.581582 .. versionadded:: 8.5.0583 """584585 def show_version(ctx: Context, param: Parameter, value: bool) -> None:586 if not value or ctx.resilient_parsing:587 return588589 echo(callback(ctx), color=ctx.color)590 ctx.exit()591592 if not param_decls:593 param_decls = ("--version",)594595 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)601602603def 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 lines
modified:tests/test_basic.py+23 added
855 unmodified lines
856857 result = runner.invoke(cli, ["--version"])858 assert result.exit_code != 0859 assert "not installed" in str(result.exception)860861862@pytest.mark.parametrize("args", [["--version"], ["-V"]])863def 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 pass868869 result = runner.invoke(cli, args)870 assert result.exit_code == 0871 assert result.output == "custom 9.9.9\n"872873874def 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 pass879880 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 lines
10 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`1819## Version 8.4.22021Released 2026-06-24
1561 unmodified lines