Skip to content
Myr

🐛 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

4 files+109 added−37 removed

modified:tests/test_tutorial/test_arguments/test_help/test_tutorial006.py+20 added-4 removed
2 unmodified lines
3import sys4from types import ModuleType56import pytest7import typer8from typer.testing import CliRunner910runner = CliRunner()11
10 unmodified lines
22 mod = importlib.import_module(module_name)23 return mod242526@pytest.fixture(27 name="app",28 params=[29 pytest.param(None),30 pytest.param("rich"),31 ],32)33def 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 app383925def test_help(mod: ModuleType):26 result = runner.invoke(mod.app, ["--help"])40def 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.output474833def test_call_arg(mod: ModuleType):34 result = runner.invoke(mod.app, ["Camila"])49def test_call_arg(app):50 result = runner.invoke(app, ["Camila"])51 assert result.exit_code == 052 assert "Hello Camila" in result.output5354
7 unmodified lines
modified:tests/test_tutorial/test_commands/test_help/test_tutorial007.py+1 added
34 unmodified lines
3536def 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.output
27 unmodified lines
modified:tests/test_rich_utils.py+49 added-8 removed
106 unmodified lines
107@needs_rich108@pytest.mark.parametrize("input_text", ["[ARGS]", "[ARGS]..."])109def 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 )120121 console = _get_rich_console()122123 text = Text(input_text)124 highlighted = metavar_highlighter(text)124 highlighted = types_highlighter(text)125 console.print(highlighted)126127 # 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)130131 # 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_SEPARATOR133134 # 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_SEPARATOR136137138def test_make_rich_text_with_ansi_escape_sequences():139 from typer.rich_utils import Text, _make_rich_text
81 unmodified lines
221222 assert pos_a == pos_b == pos_c, (223 f"Right boundaries not aligned: A={pos_a}, B={pos_b}, C={pos_c}"224 )225226227def test_rich_help_metavar():228 app = typer.Typer(rich_markup_mode="rich")229230 @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 cover244245 result = runner.invoke(app, ["--help"])246 assert "Usage: main [OPTIONS] ARG1 ARG3 [ARG4] [meta7] ARG8 arg9" in result.stdout247248 out_nospace = result.stdout.replace(" ", "")249250 # 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_nospace257258 assert "arg7" not in result.stdout.lower()259 assert "arg8" not in result.stdout260 assert "ARG9" not in result.stdout261262 # options263 assert "arg2INTEGER" in out_nospace264 assert "arg5INTEGER" in out_nospace265 assert "arg6INTEGER" in out_nospace
modified:typer/rich_utils.py+39 added-25 removed
31 unmodified lines
32STYLE_OPTION = "bold cyan"33STYLE_SWITCH = "bold green"34STYLE_NEGATIVE_OPTION = "bold magenta"35STYLE_NEGATIVE_SWITCH = "bold red"36STYLE_METAVAR = "bold yellow"37STYLE_METAVAR_SEPARATOR = "dim"36STYLE_TYPES = "bold yellow"37STYLE_TYPES_SEPARATOR = "dim"38STYLE_USAGE = "yellow"39STYLE_USAGE_COMMAND = "bold"40STYLE_DEPRECATED = "red"41STYLE_DEPRECATED_COMMAND = "dim"
69 unmodified lines
111112 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 ]118119
4 unmodified lines
124 ]125126127# Highlighter to make [ | ] and <> dim128class MetavarHighlighter(RegexHighlighter):128class 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 ]134135136highlighter = OptionHighlighter()137negative_highlighter = NegativeOptionHighlighter()138metavar_highlighter = MetavarHighlighter()138types_highlighter = TypesHighlighter()139140141def _has_ansi_character(text: str) -> bool:142 return ANSI_PREFIX in text
6 unmodified lines
149 "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 lines
363 opt_long_strs = []364 opt_short_strs = []365 secondary_opt_long_strs = []366 secondary_opt_short_strs = []367368 # 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_str380381 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)395378 # 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")398389 # 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)406407 # Range - from408 # https://github.com/pallets/click/blob/c63c70dabd3f86ca68678b4f00951f78f52d0270/src/click/core.py#L2698-L2706 # noqa: E501409 # skip count with default range type
3 unmodified lines
413 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))418419 # Required asterisk420 required: str | Text = ""421 if param.required:
5 unmodified lines
427 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