Always list all positional arguments (#3860)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents 7068985, 05f6fd0 · Browse files · 5 files·+124 added−13 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+124 added−13 removed
- tests:+93 added−0 removed
- other:+31 added−13 removed
Provenance
- Commit
bb695aa- Tree
b8c174f- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
7068985- Parent 2
05f6fd0
5 files changed+124 added−13 removed
modified:docs/arguments.md+2 added-1 removed
10 unmodified lines1112131415151617181920172 unmodified linesExpand all10 unmodified lines* Similar to a limited version of {ref}`options <options>` that can take an arbitrary number of inputs* 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>`. <documenting-arguments>`. One argument with a `help` makes the section list all the arguments of the command.
Useful and often used kwargs are:
* `help`: Help text for the argument.172 unmodified linesExpand allmodified:docs/documentation.md+4 added
116 unmodified lines117 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+The section shows up as soon as one argument of the command has a `help`. It122+then lists every argument, so it always matches the usage line. Arguments with123+no `help` are listed with an empty description.124+125 A brief example:126 127 ```{eval-rst}128 .. click:example::219 unmodified linesmodified:src/click/core.py+20 added-12 removed
1308 unmodified lines1309 with formatter.section(_("Options")):1310 formatter.write_dl(opts)1311 1312 def format_arguments(self, ctx: Context, formatter: HelpFormatter) -> None:1313- """Writes the arguments that have a help record into the formatter."""1314- args = []1315- for param in self.get_params(ctx):1316- rv = param.get_help_record(ctx)1317- if rv is not None and isinstance(param, Argument):1318- args.append(rv)1313+ """Writes all arguments into the formatter, if at least one is documented.1314 1320- if args:1315+ An argument with no help gets an empty description, the same way an option1316+ with no help does. That keeps the section an exhaustive list of the1317+ positional arguments, matching the usage line.1318+ """1319+ args = [param for param in self.get_params(ctx) if isinstance(param, Argument)]1320+1321+ if any(arg.help is not None for arg in args):1322 with formatter.section(_("Positional arguments")):1322- formatter.write_dl(args)1323+ formatter.write_dl([arg.get_help_record(ctx) for arg in args])1324 1325 def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None:1326 """Writes the epilog into the formatter if it exists."""1327 if self.epilog:2468 unmodified lines3796 3797 def get_usage_pieces(self, ctx: Context) -> list[str]:3798 return [self.make_metavar(ctx)]3799 3799- def get_help_record(self, ctx: Context) -> tuple[str, str] | None:3800- if self.help is None:3801- return None3800+ def get_help_record(self, ctx: Context) -> tuple[str, str]:3801+ """Returns the argument's help row: its metavar and its help text.3802 3803- return self.make_metavar(ctx), self.help3803+ Unlike :meth:`Option.get_help_record`, this never returns ``None``. An3804+ argument cannot be hidden, so an undocumented one still gets a row, with3805+ an empty description.3806 3807+ .. versionchanged:: 8.5.13808+ Always returns a tuple. It used to return ``None`` when ``help`` was3809+ not set.3810+ """3811+ return self.make_metavar(ctx), self.help or ""3812+3813 def get_error_hint(self, ctx: Context | None) -> str:3814 if ctx is not None:3815 return f"'{self.make_metavar(ctx)}'"3816 return f"'{self.human_readable_name}'"27 unmodified linesmodified:tests/test_arguments.py+93 added
322 unmodified lines323 assert "Options:" in result.output324 assert "number of greetings" in result.output325 326 327+def test_argument_help_lists_undocumented_arguments(runner):328+ """One documented argument makes the section list all of them."""329+330+ @click.command()331+ @click.argument("src", help="Source path")332+ @click.argument("dst")333+ @click.argument("extra", nargs=-1)334+ def cli(src, dst, extra):335+ pass336+337+ result = runner.invoke(cli, ["--help"])338+ assert result.exit_code == 0, result.output339+ lines = result.output.splitlines()340+ start = lines.index("Positional arguments:")341+ assert lines[start : start + 4] == [342+ "Positional arguments:",343+ " SRC Source path",344+ " DST",345+ " [EXTRA]...",346+ ]347+348+349+def test_argument_help_undocumented_arguments_only_no_section(runner):350+ """Arguments alone produce no section: at least one needs a help."""351+352+ @click.command()353+ @click.argument("src")354+ @click.argument("dst")355+ def cli(src, dst):356+ pass357+358+ result = runner.invoke(cli, ["--help"])359+ assert result.exit_code == 0, result.output360+ assert "Positional arguments:" not in result.output361+362+363+def test_argument_help_deprecated_without_help_lists_all(runner):364+ """A deprecation label counts as help and brings every argument into view."""365+366+ @click.command()367+ @click.argument("src", required=False, deprecated=True)368+ @click.argument("dst")369+ def cli(src, dst):370+ pass371+372+ result = runner.invoke(cli, ["--help"])373+ assert result.exit_code == 0, result.output374+ lines = result.output.splitlines()375+ start = lines.index("Positional arguments:")376+ assert lines[start : start + 3] == [377+ "Positional arguments:",378+ " [SRC!] (DEPRECATED)",379+ " DST",380+ ]381+382+383+def test_argument_help_empty_string_lists_all(runner):384+ """An explicit empty help opens the section, the same way an empty option help385+ keeps its option listed.386+ """387+388+ @click.command()389+ @click.argument("src", help="")390+ @click.argument("dst")391+ def cli(src, dst):392+ pass393+394+ result = runner.invoke(cli, ["--help"])395+ assert result.exit_code == 0, result.output396+ lines = result.output.splitlines()397+ start = lines.index("Positional arguments:")398+ assert lines[start : start + 3] == [399+ "Positional arguments:",400+ " SRC",401+ " DST",402+ ]403+404+405+@pytest.mark.parametrize(406+ ("help_text", "expected"),407+ [408+ pytest.param(None, ("SRC", ""), id="None"),409+ pytest.param("", ("SRC", ""), id="empty"),410+ pytest.param("Source path", ("SRC", "Source path"), id="documented"),411+ ],412+)413+def test_argument_get_help_record_never_none(help_text, expected):414+ """Every argument gets a row, even an undocumented one."""415+ arg = click.Argument(["src"], help=help_text)416+ ctx = click.Context(click.Command("cli"))417+ assert arg.get_help_record(ctx) == expected418+419+420 def test_argument_help_optional_metavar(runner):421 @click.command()422 @click.argument("name", required=False, default="", help="The name to print")423 def cli(name):410 unmodified linesmodified:CHANGES.md+5 added
7 unmodified lines8 exits with the intended code; only the message may be lost. {issue}`3802`9 - Add {meth}`Option.get_help_spec`, which returns the option's left help10 column even when the option is hidden. {meth}`Option.get_help_record` still11 returns `None` for hidden options, so help screens are unchanged. {pr}`3821`12+- The `Positional arguments` help section lists every argument of the command,13+ not only the documented ones. An argument with no `help` gets an empty14+ description, the same way an option with no `help` does. {pr}`3860`15+- {meth}`Argument.get_help_record` always returns a tuple. It used to return16+ `None` for an argument with no `help`. {pr}`3860`17 - Document which types are inferred from `default`, and what an unrecognized18 `type` callable does to a command-line value. {issue}`3036` {pr}`3808`19 - `path_type` narrows the converted value's type for `convert` and `prompt`.20 {issue}`3822` {pr}`3858`1665 unmodified lines