From fc9ec210db231c72d3f278729b6d115314aa3da9 Mon Sep 17 00:00:00 2001 From: Andreas Eisenbarth Date: Wed, 3 Apr 2024 20:11:26 +0200 Subject: [PATCH] Interpret help for arguments Closes: #132 --- sphinx_click/ext.py | 6 +++++ tests/test_formatter.py | 51 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/sphinx_click/ext.py b/sphinx_click/ext.py index 7013269..4454bc8 100644 --- a/sphinx_click/ext.py +++ b/sphinx_click/ext.py @@ -210,6 +210,12 @@ def _format_argument(arg: click.Argument) -> ty.Generator[str, None, None]: 'Required' if arg.required else 'Optional', '(s)' if arg.nargs != 1 else '' ) ) + # Subclasses of click.Argument may add a `help` attribute (like typer.main.TyperArgument) + if hasattr(arg, 'help'): + yield '' + help_string = ANSI_ESC_SEQ_RE.sub('', getattr(arg, 'help')) + for line in _format_help(help_string): + yield _indent(line) @_process_lines("sphinx-click-process-arguments") diff --git a/tests/test_formatter.py b/tests/test_formatter.py index 5d9fbe2..9b302c4 100644 --- a/tests/test_formatter.py +++ b/tests/test_formatter.py @@ -170,6 +170,57 @@ def foobar(bar): '\n'.join(output), ) + def test_help_argument(self): + """Validate a help text for arguments. + + While click only provides the help attribute for options, but not for arguments, + it allows customization with subclasses. + """ + + class CustomArgument(click.Argument): + def __init__(self, *args, help=None, **kwargs): + super().__init__(*args, **kwargs) + self.help = help + + @click.command() + @click.option('--option', help='A sample option') + @click.argument('ARG', help='A sample argument', cls=CustomArgument) + def foobar(bar): + """A sample command.""" + pass + + ctx = click.Context(foobar, info_name='foobar') + output = list(ext._format_command(ctx, nested='short')) + + self.assertEqual( + textwrap.dedent( + """ + A sample command. + + .. program:: foobar + .. code-block:: shell + + foobar [OPTIONS] ARG + + .. rubric:: Options + + .. option:: --option