Split generation of help extra items and rendering (#2517)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kevin Deldycke · committed by GitHub · parent a6e0d29 · Browse files · 4 files·+63 added−27 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Andreas Backx <andreas@backx.org>
Diff stats
4 files+63 added−27 removed
- tests:+23 added−12 removed
- other:+40 added−15 removed
Provenance
- Commit
948d7a7- Tree
11a374d- Author
Kevin Deldycke <kdeldycke@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
a6e0d29
4 files changed+63 added−27 removed
modified:src/click/core.py+30 added-15 removed
2666 unmodified lines2667 if self.secondary_opts:2668 rv.append(_write_opts(self.secondary_opts))2669 2670 help = self.help or ""2671- extra = []2671 2672+ extra = self.get_help_extra(ctx)2673+ extra_items = []2674+ if "envvars" in extra:2675+ extra_items.append(2676+ _("env var: {var}").format(var=", ".join(extra["envvars"]))2677+ )2678+ if "default" in extra:2679+ extra_items.append(_("default: {default}").format(default=extra["default"]))2680+ if "range" in extra:2681+ extra_items.append(extra["range"])2682+ if "required" in extra:2683+ extra_items.append(_(extra["required"]))2684+2685+ if extra_items:2686+ extra_str = "; ".join(extra_items)2687+ help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"2688+2689+ return ("; " if any_prefix_is_slash else " / ").join(rv), help2690+2691+ def get_help_extra(self, ctx: Context) -> types.OptionHelpExtra:2692+ extra: types.OptionHelpExtra = {}2693+2694 if self.show_envvar:2695 envvar = self.envvar2696 2697 if envvar is None:4 unmodified lines2702 ):2703 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"2704 2705 if envvar is not None:2685- var_str = (2686- envvar2687- if isinstance(envvar, str)2688- else ", ".join(str(d) for d in envvar)2689- )2690- extra.append(_("env var: {var}").format(var=var_str))2706+ if isinstance(envvar, str):2707+ extra["envvars"] = (envvar,)2708+ else:2709+ extra["envvars"] = tuple(str(d) for d in envvar)2710 2711 # Temporarily enable resilient parsing to avoid type casting2712 # failing for the default. Might be possible to extend this to2713 # help formatting in general.36 unmodified lines2750 else:2751 default_string = str(default_value)2752 2753 if default_string:2735- extra.append(_("default: {default}").format(default=default_string))2754+ extra["default"] = default_string2755 2756 if (2757 isinstance(self.type, types._NumberRangeBase)2758 # skip count with default range type1 unmodified line2760 ):2761 range_str = self.type._describe_range()2762 2763 if range_str:2745- extra.append(range_str)2764+ extra["range"] = range_str2765 2766 if self.required:2748- extra.append(_("required"))2767+ extra["required"] = "required"2768 2750- if extra:2751- extra_str = "; ".join(extra)2752- help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"2769+ return extra2770 2754- return ("; " if any_prefix_is_slash else " / ").join(rv), help2755-2771 @t.overload2772 def get_default(2773 self, ctx: Context, call: t.Literal[True] = True2774 ) -> t.Any | None: ...226 unmodified linesmodified:src/click/types.py+7 added
1093 unmodified lines1094 BOOL = BoolParamType()1095 1096 #: A UUID parameter.1097 UUID = UUIDParameterType()1098+1099+1100+class OptionHelpExtra(t.TypedDict, total=False):1101+ envvars: tuple[str, ...]1102+ default: str1103+ range: str1104+ required: strmodified:tests/test_options.py+23 added-12 removed
314 unmodified lines315 return "special value"316 317 opt = click.Option(["-a"], default=Value(), show_default=True)318 ctx = click.Context(click.Command("cli"))319+ assert opt.get_help_extra(ctx) == {"default": "special value"}320 assert "special value" in opt.get_help_record(ctx)[1]321 322 323 @pytest.mark.parametrize(7 unmodified lines331 )332 def test_intrange_default_help_text(type, expect):333 option = click.Option(["--num"], type=type, show_default=True, default=2)334 context = click.Context(click.Command("test"))335+ assert option.get_help_extra(context) == {"default": "2", "range": expect}336 result = option.get_help_record(context)[1]337 assert expect in result338 339 340 def test_count_default_type_help():341 """A count option with the default type should not show >=0 in help."""342 option = click.Option(["--count"], count=True, help="some words")343 context = click.Context(click.Command("test"))344+ assert option.get_help_extra(context) == {}345 result = option.get_help_record(context)[1]346 assert result == "some words"347 348 7 unmodified lines356 option = click.Option(357 ["--in"], type=click.File(), default=__file__, show_default=True358 )359 context = click.Context(click.Command("test"))360+ assert option.get_help_extra(context) == {"default": __file__}361 result = option.get_help_record(context)[1]362 assert __file__ in result363 364 379 unmodified lines744 show_default=True,745 help="Enable/Disable the cache.",746 )747 ctx = click.Context(click.Command("test"))748+ assert opt.get_help_extra(ctx) == {"default": expect}749 message = opt.get_help_record(ctx)[1]750 assert f"[default: {expect}]" in message751 752 8 unmodified lines761 default=True,762 help="Enable the cache.",763 )764 ctx = click.Context(click.Command("test"))765+ assert opt.get_help_extra(ctx) == {"default": "True"}766 message = opt.get_help_record(ctx)[1]767 assert "[default: True]" in message768 769 9 unmodified lines779 default=default,780 help="Enable the cache.",781 )782 ctx = click.Context(click.Command("test"))783+ assert opt.get_help_extra(ctx) == {}784 message = opt.get_help_record(ctx)[1]785 assert "[default: " not in message786 787 788 def test_show_default_string(runner):789 """When show_default is a string show that value as default."""790 opt = click.Option(["--limit"], show_default="unlimited")791 ctx = click.Context(click.Command("cli"))792+ assert opt.get_help_extra(ctx) == {"default": "(unlimited)"}793 message = opt.get_help_record(ctx)[1]794 assert "[default: (unlimited)]" in message795 796 8 unmodified lines805 def test_do_not_show_no_default(runner):806 """When show_default is True and no default is set do not show None."""807 opt = click.Option(["--limit"], show_default=True)808 ctx = click.Context(click.Command("cli"))809+ assert opt.get_help_extra(ctx) == {}810 message = opt.get_help_record(ctx)[1]811 assert "[default: None]" not in message812 813 2 unmodified lines816 print empty default value in --help output.817 """818 opt = click.Option(["-a"], multiple=True, help="values", show_default=True)819 ctx = click.Context(click.Command("cli"))820+ assert opt.get_help_extra(ctx) == {}821 message = opt.get_help_record(ctx)[1]822 assert message == "values"823 824 825 @pytest.mark.parametrize(816- ("ctx_value", "opt_value", "expect"),826+ ("ctx_value", "opt_value", "extra_value", "expect"),827 [818- (None, None, False),819- (None, False, False),820- (None, True, True),821- (False, None, False),822- (False, False, False),823- (False, True, True),824- (True, None, True),825- (True, False, False),826- (True, True, True),827- (False, "one", True),828+ (None, None, {}, False),829+ (None, False, {}, False),830+ (None, True, {"default": "1"}, True),831+ (False, None, {}, False),832+ (False, False, {}, False),833+ (False, True, {"default": "1"}, True),834+ (True, None, {"default": "1"}, True),835+ (True, False, {}, False),836+ (True, True, {"default": "1"}, True),837+ (False, "one", {"default": "(one)"}, True),838 ],839 )830-def test_show_default_precedence(ctx_value, opt_value, expect):840+def test_show_default_precedence(ctx_value, opt_value, extra_value, expect):841 ctx = click.Context(click.Command("test"), show_default=ctx_value)842 opt = click.Option("-a", default=1, help="value", show_default=opt_value)843+ assert opt.get_help_extra(ctx) == extra_value844 help = opt.get_help_record(ctx)[1]845 assert ("default:" in help) is expect846 847 128 unmodified linesmodified:CHANGES.rst+3 added
34 unmodified lines35 ``--help`` message if ``show_choices=False`` is specified.36 :issue:`2356`37 - Do not display default values in prompts when ``Option.show_default`` is38 ``False``. :pr:`2509`39+- Add ``get_help_extra`` method on ``Option`` to fetch the generated extra40+ items used in ``get_help_record`` to render help text. :issue:`2516`41+ :pr:`2517`42 43 44 Version 8.1.845 -------------1116 unmodified lines