Introduce Parameter.deprecated + Command.deprecated message customization (#2271)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Peacock · committed by GitHub · parent fde47b4 · Browse files · 5 files·+198 added−14 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
5 files+198 added−14 removed
- tests:+97 added−5 removed
- other:+101 added−9 removed
Provenance
- Commit
5961d31- Tree
c7dbe66- Author
Peacock <me@p3ac0ck.net>- Committer
GitHub <noreply@github.com>- Parent
fde47b4
5 files changed+198 added−14 removed
modified:src/click/core.py+91 added-9 removed
854 unmodified lines855 provided. This option is disabled by default.856 If enabled this will add ``--help`` as argument857 if no arguments are passed858 :param hidden: hide this command from help outputs.859+ :param deprecated: If ``True`` or non-empty string, issues a message860+ indicating that the command is deprecated and highlights861+ its deprecation in --help. The message can be customized862+ by using a string as the value.863 860- :param deprecated: issues a message indicating that861- the command is deprecated.862-864 .. versionchanged:: 8.2865 This is the base class for all commands, not ``BaseCommand``.866+ ``deprecated`` can be set to a string as well to customize the867+ deprecation message.868 869 .. versionchanged:: 8.1870 ``help``, ``epilog``, and ``short_help`` are stored unprocessed,871 all formatting is done when outputting help text, not at init,35 unmodified lines907 options_metavar: str | None = "[OPTIONS]",908 add_help_option: bool = True,909 no_args_is_help: bool = False,910 hidden: bool = False,908- deprecated: bool = False,911+ deprecated: bool | str = False,912 ) -> None:913 #: the name the command thinks it has. Upon registering a command914 #: on a :class:`Group` the group will default the command name915 #: with this information. You should instead use the145 unmodified lines1061 else:1062 text = ""1063 1064 if self.deprecated:1062- text = _("(Deprecated) {text}").format(text=text)1065+ deprecated_message = (1066+ f"(DEPRECATED: {self.deprecated})"1067+ if isinstance(self.deprecated, str)1068+ else "(DEPRECATED)"1069+ )1070+ text = _("{text} {deprecated_message}").format(1071+ text=text, deprecated_message=deprecated_message1072+ )1073 1074 return text.strip()1075 1076 def format_help(self, ctx: Context, formatter: HelpFormatter) -> None:21 unmodified lines1098 else:1099 text = ""1100 1101 if self.deprecated:1092- text = _("(Deprecated) {text}").format(text=text)1102+ deprecated_message = (1103+ f"(DEPRECATED: {self.deprecated})"1104+ if isinstance(self.deprecated, str)1105+ else "(DEPRECATED)"1106+ )1107+ text = _("{text} {deprecated_message}").format(1108+ text=text, deprecated_message=deprecated_message1109+ )1110 1111 if text:1112 formatter.write_paragraph()1113 85 unmodified lines1199 """Given a context, this invokes the attached callback (if it exists)1200 in the right way.1201 """1202 if self.deprecated:1203+ extra_message = (1204+ f" {self.deprecated}" if isinstance(self.deprecated, str) else ""1205+ )1206 message = _(1207 "DeprecationWarning: The command {name!r} is deprecated."1188- ).format(name=self.name)1208+ "{extra_message}"1209+ ).format(name=self.name, extra_message=extra_message)1210 echo(style(message, fg="red"), err=True)1211 1212 if self.callback is not None:1213 return ctx.invoke(self.callback, **ctx.params)794 unmodified lines2008 completions. Used instead of the param's type completion if2009 given. Takes ``ctx, param, incomplete`` and must return a list2010 of :class:`~click.shell_completion.CompletionItem` or a list of2011 strings.2012+ :param deprecated: If ``True`` or non-empty string, issues a message2013+ indicating that the argument is deprecated and highlights2014+ its deprecation in --help. The message can be customized2015+ by using a string as the value. A deprecated parameter2016+ cannot be required, a ValueError will be raised otherwise.2017 2018+ .. versionchanged:: 8.2.02019+ Introduction of ``deprecated``.2020+2021 .. versionchanged:: 8.22022 Adding duplicate parameter names to a :class:`~click.core.Command` will2023 result in a ``UserWarning`` being shown.2024 2025+ .. versionchanged:: 8.22026+ Adding duplicate parameter names to a :class:`~click.core.Command` will2027+ result in a ``UserWarning`` being shown.2028+2029 .. versionchanged:: 8.02030 ``process_value`` validates required parameters and bounded2031 ``nargs``, and invokes the parameter callback before returning2032 the value. This allows the callback to validate prompts.43 unmodified lines2076 shell_complete: t.Callable[2077 [Context, Parameter, str], list[CompletionItem] | list[str]2078 ]2079 | None = None,2080+ deprecated: bool | str = False,2081 ) -> None:2082 self.name: str | None2083 self.opts: list[str]2084 self.secondary_opts: list[str]19 unmodified lines2104 self.is_eager = is_eager2105 self.metavar = metavar2106 self.envvar = envvar2107 self._custom_shell_complete = shell_complete2108+ self.deprecated = deprecated2109 2110 if __debug__:2111 if self.type.is_composite and nargs != self.type.arity:2112 raise ValueError(34 unmodified lines2147 raise ValueError(2148 f"'default' {subject} must match nargs={nargs}."2149 )2150 2151+ if required and deprecated:2152+ raise ValueError(2153+ f"The {self.param_type_name} '{self.human_readable_name}' "2154+ "is deprecated and still required. A deprecated "2155+ f"{self.param_type_name} cannot be required."2156+ )2157+2158 def to_info_dict(self) -> dict[str, t.Any]:2159 """Gather information that could be useful for a tool generating2160 user-facing documentation.2161 211 unmodified lines2373 self, ctx: Context, opts: cabc.Mapping[str, t.Any], args: list[str]2374 ) -> tuple[t.Any, list[str]]:2375 with augment_usage_errors(ctx, param=self):2376 value, source = self.consume_value(ctx, opts)2377+2378+ if (2379+ self.deprecated2380+ and value is not None2381+ and source2382+ not in (2383+ ParameterSource.DEFAULT,2384+ ParameterSource.DEFAULT_MAP,2385+ )2386+ ):2387+ extra_message = (2388+ f" {self.deprecated}" if isinstance(self.deprecated, str) else ""2389+ )2390+ message = _(2391+ "DeprecationWarning: The {param_type} {name!r} is deprecated."2392+ "{extra_message}"2393+ ).format(2394+ param_type=self.param_type_name,2395+ name=self.human_readable_name,2396+ extra_message=extra_message,2397+ )2398+ echo(style(message, fg="red"), err=True)2399+2400 ctx.set_parameter_source(self.name, source) # type: ignore2401 2402 try:2403 value = self.process_value(ctx, value)62 unmodified lines2466 shown on the help page and error messages.2467 Normally, environment variables are not shown.2468 :param prompt: If set to ``True`` or a non empty string then the2469 user will be prompted for input. If set to ``True`` the prompt2405- will be the option name capitalized.2470+ will be the option name capitalized. A deprecated option cannot be2471+ prompted.2472 :param confirmation_prompt: Prompt a second time to confirm the2473 value if it was prompted for. Can be set to a string instead of2474 ``True`` to customize the message.2475 :param prompt_required: If set to ``False``, the user will be58 unmodified lines2534 help: str | None = None,2535 hidden: bool = False,2536 show_choices: bool = True,2537 show_envvar: bool = False,2538+ deprecated: bool | str = False,2539 **attrs: t.Any,2540 ) -> None:2541 if help:2542 help = inspect.cleandoc(help)2543 2544 default_is_missing = "default" not in attrs2478- super().__init__(param_decls, type=type, multiple=multiple, **attrs)2545+ super().__init__(2546+ param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs2547+ )2548 2549 if prompt is True:2550 if self.name is None:2551 raise TypeError("'name' is required with 'prompt=True'.")3 unmodified lines2555 prompt_text = None2556 else:2557 prompt_text = prompt2558 2559+ if deprecated:2560+ deprecated_message = (2561+ f"(DEPRECATED: {deprecated})"2562+ if isinstance(deprecated, str)2563+ else "(DEPRECATED)"2564+ )2565+ help = help + deprecated_message if help is not None else deprecated_message2566+2567 self.prompt = prompt_text2568 self.confirmation_prompt = confirmation_prompt2569 self.prompt_required = prompt_required2570 self.hide_input = hide_input53 unmodified lines2624 self.show_choices = show_choices2625 self.show_envvar = show_envvar2626 2627 if __debug__:2628+ if deprecated and prompt:2629+ raise ValueError("`deprecated` options cannot use `prompt`.")2630+2631 if self.nargs == -1:2632 raise TypeError("nargs=-1 is not supported for options.")2633 2634 if self.prompt and self.is_flag and not self.is_bool_flag:427 unmodified lines3062 return self.metavar3063 var = self.type.get_metavar(self)3064 if not var:3065 var = self.name.upper() # type: ignore3066+ if self.deprecated:3067+ var += "!"3068 if not self.required:3069 var = f"[{var}]"3070 if self.nargs != 1:3071 var += "..."51 unmodified linesmodified:tests/test_arguments.py+38 added
273 unmodified lines274 assert result.exit_code == 0275 assert result.output == "test\n"276 277 278+def test_deprecated_usage(runner):279+ @click.command()280+ @click.argument("f", required=False, deprecated=True)281+ def cli(f):282+ click.echo(f)283+284+ result = runner.invoke(cli, ["--help"])285+ assert result.exit_code == 0, result.output286+ assert "[F!]" in result.output287+288+289+@pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])290+def test_deprecated_warning(runner, deprecated):291+ @click.command()292+ @click.argument(293+ "my-argument", required=False, deprecated=deprecated, default="default argument"294+ )295+ def cli(my_argument: str):296+ click.echo(f"{my_argument}")297+298+ # defaults should not give a deprecated warning299+ result = runner.invoke(cli, [])300+ assert result.exit_code == 0, result.output301+ assert "is deprecated" not in result.output302+303+ result = runner.invoke(cli, ["hello"])304+ assert result.exit_code == 0, result.output305+ assert "argument 'MY_ARGUMENT' is deprecated" in result.output306+307+ if isinstance(deprecated, str):308+ assert deprecated in result.output309+310+311+def test_deprecated_required(runner):312+ with pytest.raises(ValueError, match="is deprecated and still required"):313+ click.Argument(["a"], required=True, deprecated=True)314+315+316 def test_eat_options(runner):317 @click.command()318 @click.option("-f")319 @click.argument("files", nargs=-1)155 unmodified linesmodified:tests/test_commands.py+13 added-5 removed
316 unmodified lines317 ]318 319 320 @pytest.mark.parametrize("doc", ["CLI HELP", None])321+@pytest.mark.parametrize("deprecated", [True, "USE OTHER COMMAND INSTEAD"])321-def test_deprecated_in_help_messages(runner, doc):322- @click.command(deprecated=True, help=doc)322+def test_deprecated_in_help_messages(runner, doc, deprecated):323+ @click.command(deprecated=deprecated, help=doc)324 def cli():325 pass326 327 result = runner.invoke(cli, ["--help"])327- assert "(Deprecated)" in result.output328+ assert "(DEPRECATED" in result.output329 330+ if isinstance(deprecated, str):331+ assert deprecated in result.output332 333+334+@pytest.mark.parametrize("deprecated", [True, "USE OTHER COMMAND INSTEAD"])330-def test_deprecated_in_invocation(runner):331- @click.command(deprecated=True)335+def test_deprecated_in_invocation(runner, deprecated):336+ @click.command(deprecated=deprecated)337 def deprecated_cmd():338 pass339 340 result = runner.invoke(deprecated_cmd)341 assert "DeprecationWarning:" in result.output342 343+ if isinstance(deprecated, str):344+ assert deprecated in result.output345 346+347 def test_command_parse_args_collects_option_prefixes():348 @click.command()349 @click.option("+p", is_flag=True)350 @click.option("!e", is_flag=True)65 unmodified linesmodified:tests/test_options.py+46 added
31 unmodified lines32 assert "declare an argument" in message33 assert "'--foo'" in message34 35 36+@pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])37+def test_deprecated_usage(runner, deprecated):38+ @click.command()39+ @click.option("--foo", default="bar", deprecated=deprecated)40+ def cmd(foo):41+ click.echo(foo)42+43+ result = runner.invoke(cmd, ["--help"])44+ assert "(DEPRECATED" in result.output45+46+ if isinstance(deprecated, str):47+ assert deprecated in result.output48+49+50+@pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])51+def test_deprecated_warning(runner, deprecated):52+ @click.command()53+ @click.option(54+ "--my-option", required=False, deprecated=deprecated, default="default option"55+ )56+ def cli(my_option: str):57+ click.echo(f"{my_option}")58+59+ # defaults should not give a deprecated warning60+ result = runner.invoke(cli, [])61+ assert result.exit_code == 0, result.output62+ assert "is deprecated" not in result.output63+64+ result = runner.invoke(cli, ["--my-option", "hello"])65+ assert result.exit_code == 0, result.output66+ assert "option 'my_option' is deprecated" in result.output67+68+ if isinstance(deprecated, str):69+ assert deprecated in result.output70+71+72+def test_deprecated_required(runner):73+ with pytest.raises(ValueError, match="is deprecated and still required"):74+ click.Option(["--a"], required=True, deprecated=True)75+76+77+def test_deprecated_prompt(runner):78+ with pytest.raises(ValueError, match="`deprecated` options cannot use `prompt`"):79+ click.Option(["--a"], prompt=True, deprecated=True)80+81+82 def test_invalid_nargs(runner):83 with pytest.raises(TypeError, match="nargs=-1"):84 85 @click.command()978 unmodified linesmodified:CHANGES.rst+10 added
77 unmodified lines78 - ``echo_via_pager`` will not ignore ``KeyboardInterrupt`` anymore. This79 allows the user to search for future output of the generator when80 using less and then aborting the program using ctrl-c.81 82+- ``deprecated: bool | str`` can now be used on options and arguments. This83+ previously was only available for ``Command``. The message can now also be84+ customised by using a ``str`` instead of a ``bool``. :issue:`2263` :pr:`2271`85+86+ - ``Command.deprecated`` formatting in ``--help`` changed from87+ ``(Deprecated) help`` to ``help (DEPRECATED)``.88+ - Parameters cannot be required nor prompted or an error is raised.89+ - A warning will be printed when something deprecated is used.90+91+92 Version 8.1.893 -------------94 95 Unreleased1116 unmodified lines