@@ -440,6 +440,16 @@ def version_option(
440440 :func:`importlib.metadata.packages_distributions`, so e.g. ``PIL``
441441 resolves to the ``Pillow`` distribution.
442442
443+ .. note::
444+ The parameters and message variables accepted by this option are
445+ frozen: no new slots will be added, to keep the common case simple
446+ and predictable. If you need values it does not expose, such as a
447+ file path, the Python version, or git metadata, use
448+ :func:`custom_version_option` to render the output yourself.
449+
450+ Rationale: `discussion #3527
451+ <https://github.com/pallets/click/discussions/3527>`_.
452+
443453 :param version: The version number to show. If not provided, Click
444454 will try to detect it.
445455 :param param_decls: One or more option names. Defaults to the single
@@ -548,6 +558,48 @@ def callback(ctx: Context, param: Parameter, value: bool) -> None:
548558 return option (* param_decls , ** kwargs )
549559
550560
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`. Where
569+ :func:`version_option` is intentionally limited to a fixed message and
570+ a small set of values, this option calls ``callback`` to build the
571+ whole string to print. Use it when you need values that
572+ :func:`version_option` does not expose, such as a file path, the
573+ Python version, or git metadata.
574+
575+ :param callback: Called with the current :class:`Context` when the
576+ option is invoked. Its return value is printed, then the program
577+ exits.
578+ :param param_decls: One or more option names. Defaults to the single
579+ value ``--version``.
580+ :param kwargs: Extra arguments are passed to :func:`option`.
581+
582+ .. versionadded:: 8.5.0
583+ """
584+
585+ def show_version (ctx : Context , param : Parameter , value : bool ) -> None :
586+ if not value or ctx .resilient_parsing :
587+ return
588+
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_version
600+ return option (* param_decls , ** kwargs )
601+
602+
551603def help_option (* param_decls : str , ** kwargs : t .Any ) -> t .Callable [[FC ], FC ]:
552604 """Pre-configured ``--help`` option which immediately prints the help page
553605 and exits the program.
0 commit comments