Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix metavar for Choice options when show_choices=False #2365

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
3 changes: 3 additions & 0 deletions CHANGES.rst
Expand Up @@ -5,6 +5,9 @@ Version 8.2.0

Unreleased

- Show the ``types.ParamType.name`` for ``types.Choice`` options within
``--help`` message if ``show_choices=False`` is specified.
:issue:`2356`
- Drop support for Python 3.7. :pr:`2588`
- Use modern packaging metadata with ``pyproject.toml`` instead of ``setup.cfg``.
:pr:`326`
Expand Down
8 changes: 7 additions & 1 deletion src/click/types.py
Expand Up @@ -258,7 +258,13 @@ def to_info_dict(self) -> dict[str, t.Any]:
return info_dict

def get_metavar(self, param: Parameter) -> str:
choices_str = "|".join(self.choices)
if param.param_type_name == "option" and not param.show_choices: # type: ignore
choice_metavars = [
convert_type(type(choice)).name.upper() for choice in self.choices
]
choices_str = "|".join([*dict.fromkeys(choice_metavars)])
else:
choices_str = "|".join([str(i) for i in self.choices])

# Use curly braces to indicate a required argument.
if param.required and param.param_type_name == "argument":
Expand Down
36 changes: 36 additions & 0 deletions tests/test_options.py
Expand Up @@ -918,3 +918,39 @@ def test_invalid_flag_combinations(runner, kwargs, message):
click.Option(["-a"], **kwargs)

assert message in str(e.value)


@pytest.mark.parametrize(
("choices", "metavars"),
[
pytest.param(["foo", "bar"], "[TEXT]", id="text choices"),
pytest.param([1, 2], "[INTEGER]", id="int choices"),
pytest.param([1.0, 2.0], "[FLOAT]", id="float choices"),
pytest.param([True, False], "[BOOLEAN]", id="bool choices"),
pytest.param(["foo", 1], "[TEXT|INTEGER]", id="text/int choices"),
],
)
def test_usage_show_choices(runner, choices, metavars):
"""When show_choices=False is set, the --help output
should print choice metavars instead of values.
"""

@click.command()
@click.option("-g", type=click.Choice(choices))
def cli_with_choices(g):
pass

@click.command()
@click.option(
"-g",
type=click.Choice(choices),
show_choices=False,
)
def cli_without_choices(g):
pass

result = runner.invoke(cli_with_choices, ["--help"])
assert f"[{'|'.join([str(i) for i in choices])}]" in result.output

result = runner.invoke(cli_without_choices, ["--help"])
assert metavars in result.output