Add help parameter to arguments (#3473)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kevin Deldycke · committed by GitHub · parents 1a994ad, 684b3f5 · Browse files · 6 files·+184 added−7 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+184 added−7 removed
- tests:+128 added−0 removed
- other:+56 added−7 removed
Provenance
- Commit
c480210- Tree
ee7e2c3- Author
Kevin Deldycke <kdeldycke@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
1a994ad- Parent 2
684b3f5
6 files changed+184 added−7 removed
modified:docs/arguments.md+4 added-1 removed
8 unmodified lines9101112131314151617181920212223166 unmodified linesExpand all8 unmodified lines
* Are positional in nature.* Similar to a limited version of {ref}`options <options>` that can take an arbitrary number of inputs* {ref}`Documented manually <documenting-arguments>`.* Can take an optional `help` string shown in the ``Positional arguments`` section of the help page, or be {ref}`documented in the command docstring <documenting-arguments>`.
Useful and often used kwargs are:
* `help`: Help text for the argument.* `default`: Passes a default.* `nargs`: Sets the number of arguments. Set to -1 to take an arbitrary number.
## Basic Arguments166 unmodified linesExpand allmodified:docs/documentation.md+7 added-5 removed
13 unmodified lines14 ```{eval-rst}15 .. click:example::16 17 @click.command()18- @click.argument('name')18+ @click.argument('name', help='The name to print')19 @click.option('--count', default=1, help='number of greetings')20 def hello(name: str, count: int):21 """This script prints hello and a name one or more times."""22 for x in range(count):89 unmodified lines112 (documenting-arguments)=113 114 ## Documenting Arguments115 116-{class}`click.argument` does not take a `help` parameter. This follows the Unix Command Line Tools convention of using arguments only for necessary things and documenting them in the command help text117-by name. This should then be done via the docstring.116+{class}`click.argument` accepts an optional `help` parameter that is shown in117+the ``Positional arguments`` section of the help page. You can still document118+arguments in the command docstring, especially when you want to describe them119+in the main help text by name.120 121 A brief example:122 123 ```{eval-rst}124 .. click:example::125 126 @click.command()125- @click.argument('filename')127+ @click.argument('filename', help='The file to print.')128 def touch(filename):129 """Print FILENAME."""130 click.echo(filename)131 132 .. click:run::133 invoke(touch, args=['--help'])134 ```135 134-Or more explicitly:136+Or more explicitly in the docstring:137 138 ```{eval-rst}139 .. click:example::140 203 unmodified linesmodified:src/click/core.py+43 added-1 removed
1170 unmodified lines1171 This calls the following methods:1172 1173 - :meth:`format_usage`1174 - :meth:`format_help_text`1175+ - :meth:`format_arguments`1176 - :meth:`format_options`1177 - :meth:`format_epilog`1178 """1179 self.format_usage(ctx, formatter)1180 self.format_help_text(ctx, formatter)1181+ self.format_arguments(ctx, formatter)1182 self.format_options(ctx, formatter)1183 self.format_epilog(ctx, formatter)1184 1185 def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None:18 unmodified lines1204 """Writes all the options into the formatter if they exist."""1205 opts = []1206 for param in self.get_params(ctx):1207 rv = param.get_help_record(ctx)1206- if rv is not None:1208+ if rv is not None and not isinstance(param, Argument):1209 opts.append(rv)1210 1211 if opts:1212 with formatter.section(_("Options")):1213 formatter.write_dl(opts)1214 1215+ def format_arguments(self, ctx: Context, formatter: HelpFormatter) -> None:1216+ """Writes the arguments that have a help record into the formatter."""1217+ args = []1218+ for param in self.get_params(ctx):1219+ rv = param.get_help_record(ctx)1220+ if rv is not None and isinstance(param, Argument):1221+ args.append(rv)1222+1223+ if args:1224+ with formatter.section(_("Positional arguments")):1225+ formatter.write_dl(args)1226+1227 def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None:1228 """Writes the epilog into the formatter if it exists."""1229 if self.epilog:1230 epilog = inspect.cleandoc(self.epilog)2232 unmodified lines3463 provide fewer features than options but can have infinite ``nargs``3464 and are required by default.3465 3466 All parameters are passed onwards to the constructor of :class:`Parameter`.3467+3468+ :param help: the help string.3469+3470+ .. versionchanged:: 8.53471+ Added the ``help`` parameter.3472 """3473 3474 param_type_name = "argument"3475 3476 def __init__(3477 self,3478 param_decls: cabc.Sequence[str],3479 required: bool | None = None,3480+ help: str | None = None,3481 **attrs: t.Any,3482 ) -> None:3483 # Auto-detect the requirement status of the argument if not explicitly set.3484 if required is None:7 unmodified lines3492 3493 if "multiple" in attrs:3494 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.")3495 3496+ deprecated = attrs.get("deprecated", False)3497+3498+ if help:3499+ help = inspect.cleandoc(help)3500+3501+ if deprecated:3502+ label = _format_deprecated_label(deprecated)3503+ help = f"{help} {label}" if help else label3504+3505+ self.help = help3506+3507 super().__init__(param_decls, required=required, **attrs)3508 3509+ def to_info_dict(self) -> dict[str, t.Any]:3510+ info_dict = super().to_info_dict()3511+ info_dict.update(help=self.help)3512+ return info_dict3513+3514 @property3515 def human_readable_name(self) -> str:3516 if self.metavar is not None:3517 return self.metavar34 unmodified lines3552 3553 def get_usage_pieces(self, ctx: Context) -> list[str]:3554 return [self.make_metavar(ctx)]3555 3556+ def get_help_record(self, ctx: Context) -> tuple[str, str] | None:3557+ if self.help is None:3558+ return None3559+3560+ return self.make_metavar(ctx), self.help3561+3562 def get_error_hint(self, ctx: Context | None) -> str:3563 if ctx is not None:3564 return f"'{self.make_metavar(ctx)}'"3565 return f"'{self.human_readable_name}'"27 unmodified linesmodified:tests/test_arguments.py+88 added
293 unmodified lines294 assert result.exit_code == 0295 assert result.output == "test\n"296 297 298+def test_argument_help(runner):299+ @click.command()300+ @click.argument("name", help="The name to print")301+ @click.option("--count", default=1, help="number of greetings")302+ def cli(name, count):303+ pass304+305+ result = runner.invoke(cli, ["--help"])306+ assert result.exit_code == 0, result.output307+ assert "Positional arguments:" in result.output308+ assert "NAME" in result.output309+ assert "The name to print" in result.output310+ assert "Options:" in result.output311+ assert "number of greetings" in result.output312+ assert result.output.index("Positional arguments:") < result.output.index(313+ "Options:"314+ )315+316+317+def test_argument_help_options_only_no_arguments_section(runner):318+ @click.command()319+ @click.option("--count", default=1, help="number of greetings")320+ def cli(count):321+ pass322+323+ result = runner.invoke(cli, ["--help"])324+ assert result.exit_code == 0, result.output325+ assert "Positional arguments:" not in result.output326+ assert "Options:" in result.output327+ assert "number of greetings" in result.output328+329+330+def test_argument_help_optional_metavar(runner):331+ @click.command()332+ @click.argument("name", required=False, default="", help="The name to print")333+ def cli(name):334+ pass335+336+ result = runner.invoke(cli, ["--help"])337+ assert result.exit_code == 0, result.output338+ assert "[NAME]" in result.output339+ assert "The name to print" in result.output340+341+342 def test_deprecated_usage(runner):343 @click.command()344 @click.argument("f", required=False, deprecated=True)345 def cli(f):29 unmodified lines375 assert result.exit_code == 0376 assert result.output.splitlines()[0] == f"Usage: cli [OPTIONS] {expected}"377 378 379+@pytest.mark.parametrize(380+ ("deprecated", "expected_label"),381+ [(True, "(DEPRECATED)"), ("use g instead", "(DEPRECATED: use g instead)")],382+)383+def test_deprecated_usage_help_record(runner, deprecated, expected_label):384+ @click.command()385+ @click.argument("f", required=False, deprecated=deprecated, help="path to the file")386+ def cli(f):387+ click.echo(f)388+389+ result = runner.invoke(cli, ["--help"])390+ assert result.exit_code == 0, result.output391+ assert "Positional arguments:" in result.output392+ assert "[F!]" in result.output393+ assert f"path to the file {expected_label}" in result.output394+395+396+def test_deprecated_usage_help_record_without_help(runner):397+ @click.command()398+ @click.argument("f", required=False, deprecated=True)399+ def cli(f):400+ click.echo(f)401+402+ result = runner.invoke(cli, ["--help"])403+ assert result.exit_code == 0, result.output404+ # Deprecation alone produces a help row with just the deprecation label.405+ assert "Positional arguments:" in result.output406+ assert "(DEPRECATED)" in result.output407+408+409+@pytest.mark.parametrize(410+ ("deprecated", "expected"),411+ [(True, "(DEPRECATED)"), ("USE B INSTEAD", "(DEPRECATED: USE B INSTEAD)")],412+)413+@pytest.mark.parametrize("help_text", ["", None])414+def test_deprecated_empty_help_no_leading_space(help_text, deprecated, expected):415+ """An argument with empty or missing help text must not gain a stray leading416+ space before the deprecation label.417+ """418+ arg = click.Argument(["foo"], required=False, help=help_text, deprecated=deprecated)419+ ctx = click.Context(click.Command("cli"))420+ assert arg.get_help_record(ctx)[1] == expected421+422+423 @pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])424 def test_deprecated_warning(runner, deprecated):425 @click.command()426 @click.argument(317 unmodified linesmodified:tests/test_info_dict.py+40 added
38 unmodified lines39 "nargs": 1,40 "multiple": False,41 "default": None,42 "envvar": None,43+ "help": None,44 },45 )46 NUMBER_OPTION = (47 click.Option(["-c", "--count", "number"], default=1),225 unmodified lines273 class TestType(click.ParamType):274 pass275 276 assert TestType().to_info_dict()["name"] == "TestType"277+278+279+@pytest.mark.parametrize(280+ ("help_in", "help_out"),281+ [282+ pytest.param(None, None, id="None"),283+ pytest.param("", "", id="empty"),284+ pytest.param("single line", "single line", id="single-line"),285+ pytest.param(286+ "\n first line\n second line\n ",287+ "first line\nsecond line",288+ id="multi-line",289+ ),290+ ],291+)292+def test_argument_to_info_dict_help(help_in, help_out):293+ arg = click.Argument(["name"], help=help_in)294+ assert arg.to_info_dict()["help"] == help_out295+296+297+def test_argument_to_info_dict_nargs():298+ arg = click.Argument(["files"], nargs=-1, help="files to process")299+ info = arg.to_info_dict()300+ assert info["nargs"] == -1301+ assert info["help"] == "files to process"302+303+304+def test_command_to_info_dict_multiple_arguments():305+ @click.command()306+ @click.argument("src", help="source path")307+ @click.argument("dst", help="destination path")308+ def cli(src, dst):309+ pass310+311+ ctx = click.Context(cli)312+ params = cli.to_info_dict(ctx)["params"]313+ args = [p for p in params if p["param_type_name"] == "argument"]314+ assert [p["name"] for p in args] == ["src", "dst"]315+ assert [p["help"] for p in args] == ["source path", "destination path"]modified:CHANGES.rst+2 added
5 unmodified lines6 Unreleased7 8 - Supported versions of Windows enable ANSI terminal styles by default.9 Colorama is no longer a dependency and is not used. :issue:`2986` :pr:`3505`10+- :class:`Argument` accepts a ``help`` parameter, and help output includes11+ a ``Positional arguments`` section when argument help is available. :issue:`2983` :pr:`3473`12 13 14 Version 8.4.215 -------------1491 unmodified lines