Allow customization of help option right from its decorator.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Removes `click.decorators.HelpOption` class. Closes #2832. # Conflicts: # CHANGES.rst
authored by Kevin Deldycke · committed by Kevin Deldycke · parent 0bf333e · Browse files · 5 files·+64 added−42 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+64 added−42 removed
- tests:+39 added−0 removed
- other:+25 added−42 removed
Provenance
- Commit
0b7a9ac- Tree
b744719- Author
Kevin Deldycke <kevin@deldycke.com>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
0bf333e
5 files changed+64 added−42 removed
modified:src/click/__init__.py-1 removed
17 unmodified lines18 from .decorators import command as command19 from .decorators import confirmation_option as confirmation_option20 from .decorators import group as group21 from .decorators import help_option as help_option22-from .decorators import HelpOption as HelpOption22 from .decorators import make_pass_decorator as make_pass_decorator23 from .decorators import option as option24 from .decorators import pass_context as pass_context25 from .decorators import pass_obj as pass_obj98 unmodified linesmodified:src/click/core.py+11 added-15 removed
1012 unmodified lines1013 all_names.difference_update(param.secondary_opts)1014 return list(all_names)1015 1016 def get_help_option(self, ctx: Context) -> Option | None:1017- """Returns the help option object."""1018- help_options = self.get_help_option_names(ctx)1017+ """Returns the help option object.1018 1019+ Skipped if :attr:`add_help_option` is ``False``.1020+ """1021+ help_option_names = self.get_help_option_names(ctx)1022+1020- if not help_options or not self.add_help_option:1023+ if not help_option_names or not self.add_help_option:1024 return None1025 1023- def show_help(ctx: Context, param: Parameter, value: str) -> None:1024- if value and not ctx.resilient_parsing:1025- echo(ctx.get_help(), color=ctx.color)1026- ctx.exit()1026+ # Avoid circular import.1027+ from .decorators import help_option1028 1028- return Option(1029- help_options,1030- is_flag=True,1031- is_eager=True,1032- expose_value=False,1033- callback=show_help,1034- help=_("Show this message and exit."),1035- )1029+ # apply help_option decorator and pop resulting option1030+ help_option(*help_option_names)(self)1031+ return self.params.pop() # type: ignore[return-value]1032 1033 def make_parser(self, ctx: Context) -> _OptionParser:1034 """Creates the underlying option parser for this command."""1035 parser = _OptionParser(ctx)2082 unmodified linesmodified:src/click/decorators.py+12 added-26 removed
1 from __future__ import annotations2 3 import inspect4 import typing as t5-from collections import abc5 from functools import update_wrapper6 from gettext import gettext as _7 8 from .core import Argument514 unmodified lines523 kwargs["callback"] = callback524 return option(*param_decls, **kwargs)525 526 528-class HelpOption(Option):527+def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:528 """Pre-configured ``--help`` option which immediately prints the help page529 and exits the program.530+531+ :param param_decls: One or more option names. Defaults to the single532+ value ``"--help"``.533+ :param kwargs: Extra arguments are passed to :func:`option`.534 """535 533- def __init__(534- self,535- param_decls: abc.Sequence[str] | None = None,536- **kwargs: t.Any,537- ) -> None:538- if not param_decls:539- param_decls = ("--help",)540-541- kwargs.setdefault("is_flag", True)542- kwargs.setdefault("expose_value", False)543- kwargs.setdefault("is_eager", True)544- kwargs.setdefault("help", _("Show this message and exit."))545- kwargs.setdefault("callback", self.show_help)546-547- super().__init__(param_decls, **kwargs)548-549- @staticmethod536 def show_help(ctx: Context, param: Parameter, value: bool) -> None:537 """Callback that print the help page on ``<stdout>`` and exits."""538 if value and not ctx.resilient_parsing:539 echo(ctx.get_help(), color=ctx.color)540 ctx.exit()541 542+ if not param_decls:543+ param_decls = ("--help",)544 557-def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:558- """Decorator for the pre-configured ``--help`` option defined above.545+ kwargs.setdefault("is_flag", True)546+ kwargs.setdefault("expose_value", False)547+ kwargs.setdefault("is_eager", True)548+ kwargs.setdefault("help", _("Show this message and exit."))549+ kwargs.setdefault("callback", show_help)550 560- :param param_decls: One or more option names. Defaults to the single561- value ``"--help"``.562- :param kwargs: Extra arguments are passed to :func:`option`.563- """564- kwargs.setdefault("cls", HelpOption)551 return option(*param_decls, **kwargs)modified:tests/test_options.py+39 added
722 unmodified lines723 assert "I am a help text" in result.output724 assert "you wont see me" not in result.output725 726 727+@pytest.mark.parametrize("custom_class", (True, False))728+@pytest.mark.parametrize(729+ ("name_specs", "expected"),730+ (731+ (732+ ("-h", "--help"),733+ " -h, --help Show this message and exit.\n",734+ ),735+ (736+ ("-h",),737+ " -h Show this message and exit.\n"738+ " --help Show this message and exit.\n",739+ ),740+ (741+ ("--help",),742+ " --help Show this message and exit.\n",743+ ),744+ ),745+)746+def test_help_option_custom_names_and_class(runner, custom_class, name_specs, expected):747+ class CustomHelpOption(click.Option):748+ pass749+750+ option_attrs = {}751+ if custom_class:752+ option_attrs["cls"] = CustomHelpOption753+754+ @click.command()755+ @click.help_option(*name_specs, **option_attrs)756+ def cmd():757+ pass758+759+ for arg in name_specs:760+ result = runner.invoke(cmd, [arg])761+ assert not result.exception762+ assert result.exit_code == 0763+ assert expected in result.output764+765+766 def test_bool_flag_with_type(runner):767 @click.command()768 @click.option("--shout/--no-shout", default=False, type=bool)769 def cmd(shout):333 unmodified linesmodified:CHANGES.rst+2 added
96 unmodified lines97 - Incorrect ``click.edit`` typing has been corrected. :pr:`2804`98 - ``Choice`` is now generic and supports any iterable value.99 This allows you to use enums and other non-``str`` values. :pr:`2796`100 :issue:`605`101+- Fix setup of help option's defaults when using a custom class on its102+ decorator. Removes ``HelpOption``. :issue:`2832` :pr:`2840`103 104 Version 8.1.8105 -------------106 1117 unmodified lines