Skip to content

Commit 0c15b1b

Browse files
šŸ› Make second column of Rich help output reflect the type consistently, even when using metavar (#1410)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
1 parent b7cb8c7 commit 0c15b1b

4 files changed

Lines changed: 109 additions & 37 deletions

File tree

ā€Žtests/test_rich_utils.pyā€Ž

Lines changed: 49 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -108,31 +108,31 @@ def main(bar: str):
108108
@pytest.mark.parametrize("input_text", ["[ARGS]", "[ARGS]..."])
109109
def test_metavar_highlighter(input_text: str):
110110
"""
111-
Test that the MetavarHighlighter works correctly.
111+
Test that the TypesHighlighter (used to be the MetavarHighlighter) works correctly.
112112
cf PR 1508
113113
"""
114114
from typer.rich_utils import (
115-
STYLE_METAVAR_SEPARATOR,
115+
STYLE_TYPES_SEPARATOR,
116116
Text,
117117
_get_rich_console,
118-
metavar_highlighter,
118+
types_highlighter,
119119
)
120120

121121
console = _get_rich_console()
122122

123123
text = Text(input_text)
124-
highlighted = metavar_highlighter(text)
124+
highlighted = types_highlighter(text)
125125
console.print(highlighted)
126126

127127
# Get the style for each bracket
128128
opening_bracket_style = highlighted.get_style_at_offset(console, 0)
129129
closing_bracket_style = highlighted.get_style_at_offset(console, 5)
130130

131-
# The opening bracket should have metavar_sep style
132-
assert str(opening_bracket_style) == STYLE_METAVAR_SEPARATOR
131+
# The opening bracket should have types_sep style
132+
assert str(opening_bracket_style) == STYLE_TYPES_SEPARATOR
133133

134-
# The closing bracket should have metavar_sep style (fails before PR 1508 when there are 3 dots)
135-
assert str(closing_bracket_style) == STYLE_METAVAR_SEPARATOR
134+
# The closing bracket should have types_sep style (fails before PR 1508 when there are 3 dots)
135+
assert str(closing_bracket_style) == STYLE_TYPES_SEPARATOR
136136

137137

138138
def test_make_rich_text_with_ansi_escape_sequences():
@@ -222,3 +222,44 @@ def find_right_boundary_pos(line):
222222
assert pos_a == pos_b == pos_c, (
223223
f"Right boundaries not aligned: A={pos_a}, B={pos_b}, C={pos_c}"
224224
)
225+
226+
227+
def test_rich_help_metavar():
228+
app = typer.Typer(rich_markup_mode="rich")
229+
230+
@app.command()
231+
def main(
232+
*,
233+
arg1: int,
234+
arg2: int = 42,
235+
arg3: int = typer.Argument(...),
236+
arg4: int = typer.Argument(42),
237+
arg5: int = typer.Option(...),
238+
arg6: int = typer.Option(42),
239+
arg7: int = typer.Argument(42, metavar="meta7"),
240+
arg8: int = typer.Argument(metavar="ARG8"),
241+
arg9: int = typer.Argument(metavar="arg9"),
242+
):
243+
pass # pragma: no cover
244+
245+
result = runner.invoke(app, ["--help"])
246+
assert "Usage: main [OPTIONS] ARG1 ARG3 [ARG4] [meta7] ARG8 arg9" in result.stdout
247+
248+
out_nospace = result.stdout.replace(" ", "")
249+
250+
# arguments
251+
assert "arg1INTEGER" in out_nospace
252+
assert "arg3INTEGER" in out_nospace
253+
assert "[arg4]INTEGER" in out_nospace
254+
assert "[meta7]INTEGER" in out_nospace
255+
assert "ARG8INTEGER" in out_nospace
256+
assert "arg9INTEGER" in out_nospace
257+
258+
assert "arg7" not in result.stdout.lower()
259+
assert "arg8" not in result.stdout
260+
assert "ARG9" not in result.stdout
261+
262+
# options
263+
assert "arg2INTEGER" in out_nospace
264+
assert "arg5INTEGER" in out_nospace
265+
assert "arg6INTEGER" in out_nospace

ā€Žtests/test_tutorial/test_arguments/test_help/test_tutorial006.pyā€Ž

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from types import ModuleType
55

66
import pytest
7+
import typer
78
from typer.testing import CliRunner
89

910
runner = CliRunner()
@@ -22,16 +23,31 @@ def get_mod(request: pytest.FixtureRequest) -> ModuleType:
2223
return mod
2324

2425

25-
def test_help(mod: ModuleType):
26-
result = runner.invoke(mod.app, ["--help"])
26+
@pytest.fixture(
27+
name="app",
28+
params=[
29+
pytest.param(None),
30+
pytest.param("rich"),
31+
],
32+
)
33+
def get_app(mod: ModuleType, request: pytest.FixtureRequest) -> typer.Typer:
34+
rich_markup_mode = request.param
35+
app = typer.Typer(rich_markup_mode=rich_markup_mode)
36+
app.command()(mod.main)
37+
return app
38+
39+
40+
def test_help(app):
41+
result = runner.invoke(app, ["--help"])
2742
assert result.exit_code == 0
2843
assert "Usage: main [OPTIONS] [✨username✨]" in result.output
44+
assert "NAME" not in result.output
2945
assert "Arguments" in result.output
3046
assert "[default: World]" in result.output
3147

3248

33-
def test_call_arg(mod: ModuleType):
34-
result = runner.invoke(mod.app, ["Camila"])
49+
def test_call_arg(app):
50+
result = runner.invoke(app, ["Camila"])
3551
assert result.exit_code == 0
3652
assert "Hello Camila" in result.output
3753

ā€Žtests/test_tutorial/test_commands/test_help/test_tutorial007.pyā€Ž

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ def test_main_help(mod: ModuleType):
3636
def test_create_help(mod: ModuleType):
3737
result = runner.invoke(mod.app, ["create", "--help"])
3838
assert result.exit_code == 0
39+
assert "create [OPTIONS] USERNAME [LASTNAME]" in result.output
3940
assert "username" in result.output
4041
assert "The username to create" in result.output
4142
assert "Secondary Arguments" in result.output

ā€Žtyper/rich_utils.pyā€Ž

Lines changed: 39 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@
3333
STYLE_SWITCH = "bold green"
3434
STYLE_NEGATIVE_OPTION = "bold magenta"
3535
STYLE_NEGATIVE_SWITCH = "bold red"
36-
STYLE_METAVAR = "bold yellow"
37-
STYLE_METAVAR_SEPARATOR = "dim"
36+
STYLE_TYPES = "bold yellow"
37+
STYLE_TYPES_SEPARATOR = "dim"
3838
STYLE_USAGE = "yellow"
3939
STYLE_USAGE_COMMAND = "bold"
4040
STYLE_DEPRECATED = "red"
@@ -112,7 +112,7 @@ class OptionHighlighter(RegexHighlighter):
112112
highlights = [
113113
r"(^|\W)(?P<switch>\-\w+)(?![a-zA-Z0-9])",
114114
r"(^|\W)(?P<option>\-\-[\w\-]+)(?![a-zA-Z0-9])",
115-
r"(?P<metavar>\<[^\>]+\>)",
115+
r"(?P<types>\<[^\>]+\>)",
116116
r"(?P<usage>Usage: )",
117117
]
118118

@@ -125,17 +125,17 @@ class NegativeOptionHighlighter(RegexHighlighter):
125125

126126

127127
# Highlighter to make [ | ] and <> dim
128-
class MetavarHighlighter(RegexHighlighter):
128+
class TypesHighlighter(RegexHighlighter):
129129
highlights = [
130-
r"^(?P<metavar_sep>(\[|<))",
131-
r"(?P<metavar_sep>\|)",
132-
r"(?P<metavar_sep>(\]|>))(\.\.\.)?$",
130+
r"^(?P<types_sep>(\[|<))",
131+
r"(?P<types_sep>\|)",
132+
r"(?P<types_sep>(\]|>))(\.\.\.)?$",
133133
]
134134

135135

136136
highlighter = OptionHighlighter()
137137
negative_highlighter = NegativeOptionHighlighter()
138-
metavar_highlighter = MetavarHighlighter()
138+
types_highlighter = TypesHighlighter()
139139

140140

141141
def _has_ansi_character(text: str) -> bool:
@@ -150,8 +150,8 @@ def _get_rich_console(stderr: bool = False) -> Console:
150150
"switch": STYLE_SWITCH,
151151
"negative_option": STYLE_NEGATIVE_OPTION,
152152
"negative_switch": STYLE_NEGATIVE_SWITCH,
153-
"metavar": STYLE_METAVAR,
154-
"metavar_sep": STYLE_METAVAR_SEPARATOR,
153+
"types": STYLE_TYPES,
154+
"types_sep": STYLE_TYPES_SEPARATOR,
155155
"usage": STYLE_USAGE,
156156
},
157157
),
@@ -364,31 +364,45 @@ def _print_options_panel(
364364
opt_short_strs = []
365365
secondary_opt_long_strs = []
366366
secondary_opt_short_strs = []
367+
368+
# check whether argument has a metavar name or type set
369+
metavar_name = None
370+
metavar_type = None
371+
metavar_str = param.make_metavar(ctx=ctx)
372+
if isinstance(param, TyperArgument):
373+
# TODO: revise this legacy behaviour of keeping argument names lowercased for Rich formatting
374+
if param.metavar is None and param.name:
375+
metavar_name = metavar_str.replace(param.name.upper(), param.name)
376+
else:
377+
metavar_name = metavar_str
378+
if isinstance(param, TyperOption):
379+
metavar_type = metavar_str
380+
367381
for opt_str in param.opts:
368382
if "--" in opt_str:
369383
opt_long_strs.append(opt_str)
384+
elif metavar_name:
385+
opt_short_strs.append(metavar_name)
370386
else:
371387
opt_short_strs.append(opt_str)
372388
for opt_str in param.secondary_opts:
373389
if "--" in opt_str:
374390
secondary_opt_long_strs.append(opt_str)
391+
elif metavar_name: # pragma: no cover
392+
secondary_opt_short_strs.append(metavar_name)
375393
else:
376394
secondary_opt_short_strs.append(opt_str)
377395

378-
# Column for a metavar, if we have one
379-
metavar = Text(style=STYLE_METAVAR, overflow="fold")
380-
metavar_str = param.make_metavar(ctx=ctx)
381-
# Do it ourselves if this is a positional argument
382-
if (
383-
isinstance(param, TyperArgument)
384-
and param.name
385-
and metavar_str == param.name.upper()
386-
):
387-
metavar_str = param.type.name.upper()
396+
# Column for recording the type
397+
types_data = Text(style=STYLE_TYPES, overflow="fold")
388398

389-
# Skip booleans and choices (handled above)
390-
if metavar_str != "BOOLEAN":
391-
metavar.append(metavar_str)
399+
# Fetch type
400+
if metavar_type and metavar_type != "BOOLEAN":
401+
types_data.append(metavar_type)
402+
else:
403+
type_str = param.type.name.upper()
404+
if type_str != "BOOLEAN":
405+
types_data.append(type_str)
392406

393407
# Range - from
394408
# https://github.com/pallets/click/blob/c63c70dabd3f86ca68678b4f00951f78f52d0270/src/click/core.py#L2698-L2706 # noqa: E501
@@ -400,7 +414,7 @@ def _print_options_panel(
400414
):
401415
range_str = param.type._describe_range()
402416
if range_str:
403-
metavar.append(RANGE_STRING.format(range_str))
417+
types_data.append(RANGE_STRING.format(range_str))
404418

405419
# Required asterisk
406420
required: str | Text = ""
@@ -414,7 +428,7 @@ def _print_options_panel(
414428
highlighter(",".join(opt_short_strs)),
415429
negative_highlighter(",".join(secondary_opt_long_strs)),
416430
negative_highlighter(",".join(secondary_opt_short_strs)),
417-
metavar_highlighter(metavar),
431+
types_highlighter(types_data),
418432
_get_parameter_help(
419433
param=param,
420434
ctx=ctx,

0 commit comments

Comments
Ā (0)