🐛 Make second column of Rich help output reflect the type consistently, even when using `metavar` (#1410)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sofie Van Landeghem · committed by GitHub · parent b7cb8c7 · Browse files · 4 files·+109 added−37 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Diff stats
4 files+109 added−37 removed
- tests:+70 added−12 removed
- other:+39 added−25 removed
Provenance
- Commit
0c15b1b- Tree
b898597- Author
Sofie Van Landeghem <svlandeg@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
b7cb8c7
4 files changed+109 added−37 removed
modified:tests/test_tutorial/test_arguments/test_help/test_tutorial006.py+20 added-4 removed
2 unmodified lines3 import sys4 from types import ModuleType5 6 import pytest7+import typer8 from typer.testing import CliRunner9 10 runner = CliRunner()11 10 unmodified lines22 mod = importlib.import_module(module_name)23 return mod24 25 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.param35+ app = typer.Typer(rich_markup_mode=rich_markup_mode)36+ app.command()(mod.main)37+ return app38+39+25-def test_help(mod: ModuleType):26- result = runner.invoke(mod.app, ["--help"])40+def test_help(app):41+ result = runner.invoke(app, ["--help"])42 assert result.exit_code == 043 assert "Usage: main [OPTIONS] [✨username✨]" in result.output44+ assert "NAME" not in result.output45 assert "Arguments" in result.output46 assert "[default: World]" in result.output47 48 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"])51 assert result.exit_code == 052 assert "Hello Camila" in result.output53 54 7 unmodified linesmodified:tests/test_tutorial/test_commands/test_help/test_tutorial007.py+1 added
34 unmodified lines35 36 def test_create_help(mod: ModuleType):37 result = runner.invoke(mod.app, ["create", "--help"])38 assert result.exit_code == 039+ assert "create [OPTIONS] USERNAME [LASTNAME]" in result.output40 assert "username" in result.output41 assert "The username to create" in result.output42 assert "Secondary Arguments" in result.output43 assert "lastname" in result.output27 unmodified linesmodified:tests/test_rich_utils.py+49 added-8 removed
106 unmodified lines107 @needs_rich108 @pytest.mark.parametrize("input_text", ["[ARGS]", "[ARGS]..."])109 def test_metavar_highlighter(input_text: str):110 """111- Test that the MetavarHighlighter works correctly.111+ Test that the TypesHighlighter (used to be the MetavarHighlighter) works correctly.112 cf PR 1508113 """114 from typer.rich_utils import (115- STYLE_METAVAR_SEPARATOR,115+ STYLE_TYPES_SEPARATOR,116 Text,117 _get_rich_console,118- metavar_highlighter,118+ types_highlighter,119 )120 121 console = _get_rich_console()122 123 text = Text(input_text)124- highlighted = metavar_highlighter(text)124+ highlighted = types_highlighter(text)125 console.print(highlighted)126 127 # Get the style for each bracket128 opening_bracket_style = highlighted.get_style_at_offset(console, 0)129 closing_bracket_style = highlighted.get_style_at_offset(console, 5)130 131- # The opening bracket should have metavar_sep style132- assert str(opening_bracket_style) == STYLE_METAVAR_SEPARATOR131+ # The opening bracket should have types_sep style132+ assert str(opening_bracket_style) == STYLE_TYPES_SEPARATOR133 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_SEPARATOR134+ # 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_SEPARATOR136 137 138 def test_make_rich_text_with_ansi_escape_sequences():139 from typer.rich_utils import Text, _make_rich_text81 unmodified lines221 222 assert pos_a == pos_b == pos_c, (223 f"Right boundaries not aligned: A={pos_a}, B={pos_b}, C={pos_c}"224 )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 cover244+245+ result = runner.invoke(app, ["--help"])246+ assert "Usage: main [OPTIONS] ARG1 ARG3 [ARG4] [meta7] ARG8 arg9" in result.stdout247+248+ out_nospace = result.stdout.replace(" ", "")249+250+ # arguments251+ assert "arg1INTEGER" in out_nospace252+ assert "arg3INTEGER" in out_nospace253+ assert "[arg4]INTEGER" in out_nospace254+ assert "[meta7]INTEGER" in out_nospace255+ assert "ARG8INTEGER" in out_nospace256+ assert "arg9INTEGER" in out_nospace257+258+ assert "arg7" not in result.stdout.lower()259+ assert "arg8" not in result.stdout260+ assert "ARG9" not in result.stdout261+262+ # options263+ assert "arg2INTEGER" in out_nospace264+ assert "arg5INTEGER" in out_nospace265+ assert "arg6INTEGER" in out_nospacemodified:typer/rich_utils.py+39 added-25 removed
31 unmodified lines32 STYLE_OPTION = "bold cyan"33 STYLE_SWITCH = "bold green"34 STYLE_NEGATIVE_OPTION = "bold magenta"35 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"38 STYLE_USAGE = "yellow"39 STYLE_USAGE_COMMAND = "bold"40 STYLE_DEPRECATED = "red"41 STYLE_DEPRECATED_COMMAND = "dim"69 unmodified lines111 112 highlights = [113 r"(^|\W)(?P<switch>\-\w+)(?![a-zA-Z0-9])",114 r"(^|\W)(?P<option>\-\-[\w\-]+)(?![a-zA-Z0-9])",115- r"(?P<metavar>\<[^\>]+\>)",115+ r"(?P<types>\<[^\>]+\>)",116 r"(?P<usage>Usage: )",117 ]118 119 4 unmodified lines124 ]125 126 127 # Highlighter to make [ | ] and <> dim128-class MetavarHighlighter(RegexHighlighter):128+class TypesHighlighter(RegexHighlighter):129 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>(\]|>))(\.\.\.)?$",133 ]134 135 136 highlighter = OptionHighlighter()137 negative_highlighter = NegativeOptionHighlighter()138-metavar_highlighter = MetavarHighlighter()138+types_highlighter = TypesHighlighter()139 140 141 def _has_ansi_character(text: str) -> bool:142 return ANSI_PREFIX in text6 unmodified lines149 "option": STYLE_OPTION,150 "switch": STYLE_SWITCH,151 "negative_option": STYLE_NEGATIVE_OPTION,152 "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,155 "usage": STYLE_USAGE,156 },157 ),158 highlighter=highlighter,204 unmodified lines363 opt_long_strs = []364 opt_short_strs = []365 secondary_opt_long_strs = []366 secondary_opt_short_strs = []367+368+ # check whether argument has a metavar name or type set369+ metavar_name = None370+ metavar_type = None371+ 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 formatting374+ 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_str378+ if isinstance(param, TyperOption):379+ metavar_type = metavar_str380+381 for opt_str in param.opts:382 if "--" in opt_str:383 opt_long_strs.append(opt_str)384+ elif metavar_name:385+ opt_short_strs.append(metavar_name)386 else:387 opt_short_strs.append(opt_str)388 for opt_str in param.secondary_opts:389 if "--" in opt_str:390 secondary_opt_long_strs.append(opt_str)391+ elif metavar_name: # pragma: no cover392+ secondary_opt_short_strs.append(metavar_name)393 else:394 secondary_opt_short_strs.append(opt_str)395 378- # Column for a metavar, if we have one379- metavar = Text(style=STYLE_METAVAR, overflow="fold")380- metavar_str = param.make_metavar(ctx=ctx)381- # Do it ourselves if this is a positional argument382- if (383- isinstance(param, TyperArgument)384- and param.name385- and metavar_str == param.name.upper()386- ):387- metavar_str = param.type.name.upper()396+ # Column for recording the type397+ types_data = Text(style=STYLE_TYPES, overflow="fold")398 389- # Skip booleans and choices (handled above)390- if metavar_str != "BOOLEAN":391- metavar.append(metavar_str)399+ # Fetch type400+ 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)406 407 # Range - from408 # https://github.com/pallets/click/blob/c63c70dabd3f86ca68678b4f00951f78f52d0270/src/click/core.py#L2698-L2706 # noqa: E501409 # skip count with default range type3 unmodified lines413 and not (param.count and param.type.min == 0 and param.type.max is None)414 ):415 range_str = param.type._describe_range()416 if range_str:403- metavar.append(RANGE_STRING.format(range_str))417+ types_data.append(RANGE_STRING.format(range_str))418 419 # Required asterisk420 required: str | Text = ""421 if param.required:5 unmodified lines427 highlighter(",".join(opt_long_strs)),428 highlighter(",".join(opt_short_strs)),429 negative_highlighter(",".join(secondary_opt_long_strs)),430 negative_highlighter(",".join(secondary_opt_short_strs)),417- metavar_highlighter(metavar),431+ types_highlighter(types_data),432 _get_parameter_help(433 param=param,434 ctx=ctx,435 markup_mode=markup_mode,337 unmodified lines