Skip to content
Myr

🐛 Fix shell completions for the fish shell (#1069)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by goraje · committed by GitHub · parent 85ca5b5 · Browse files · 7 files+204 added−23 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: svlandeg <svlandeg@github.com>

Diff stats

7 files+204 added−23 removed

  • tests:+184 added−1 removed
  • other:+20 added−22 removed

7 files+204 added−23 removed

added:tests/test_completion/example_rich_tags.py+31 added
1import typer23app = typer.Typer()456@app.command()7def create(username: str):8 """9 Create a [green]new[green/] user with USERNAME.10 """11 print(f"Creating user: {username}")121314@app.command()15def delete(username: str):16 """17 Delete a user with [bold]USERNAME[/].18 """19 print(f"Deleting user: {username}")202122@app.command()23def delete_all():24 """25 [red]Delete ALL users[/red] in the database.26 """27 print("Deleting all users")282930if __name__ == "__main__":31 app()
added:tests/test_completion/test_completion_complete_rich.py+113 added
1import os2import subprocess3import sys45from . import example_rich_tags as mod678def test_script():9 result = subprocess.run(10 [sys.executable, "-m", "coverage", "run", mod.__file__, "create", "DeadPool"],11 capture_output=True,12 encoding="utf-8",13 )14 assert result.returncode == 015 assert "Creating user: DeadPool" in result.stdout1617 result = subprocess.run(18 [sys.executable, "-m", "coverage", "run", mod.__file__, "delete", "DeadPool"],19 capture_output=True,20 encoding="utf-8",21 )22 assert result.returncode == 023 assert "Deleting user: DeadPool" in result.stdout2425 result = subprocess.run(26 [sys.executable, "-m", "coverage", "run", mod.__file__, "delete-all"],27 capture_output=True,28 encoding="utf-8",29 )30 assert result.returncode == 031 assert "Deleting all users" in result.stdout323334def test_completion_complete_subcommand_bash():35 result = subprocess.run(36 [sys.executable, "-m", "coverage", "run", mod.__file__, " "],37 capture_output=True,38 encoding="utf-8",39 env={40 **os.environ,41 "_EXAMPLE_RICH_TAGS.PY_COMPLETE": "complete_bash",42 "COMP_WORDS": "example_rich_tags.py del",43 "COMP_CWORD": "1",44 },45 )46 assert "delete\ndelete-all" in result.stdout474849def test_completion_complete_subcommand_zsh():50 result = subprocess.run(51 [sys.executable, "-m", "coverage", "run", mod.__file__, " "],52 capture_output=True,53 encoding="utf-8",54 env={55 **os.environ,56 "_EXAMPLE_RICH_TAGS.PY_COMPLETE": "complete_zsh",57 "_TYPER_COMPLETE_ARGS": "example_rich_tags.py del",58 },59 )60 assert (61 """_arguments '*: :(("delete":"Delete a user with USERNAME."\n"""62 """\"delete-all":"Delete ALL users in the database."))'"""63 ) in result.stdout646566def test_completion_complete_subcommand_fish():67 result = subprocess.run(68 [sys.executable, "-m", "coverage", "run", mod.__file__, " "],69 capture_output=True,70 encoding="utf-8",71 env={72 **os.environ,73 "_EXAMPLE_RICH_TAGS.PY_COMPLETE": "complete_fish",74 "_TYPER_COMPLETE_ARGS": "example_rich_tags.py del",75 "_TYPER_COMPLETE_FISH_ACTION": "get-args",76 },77 )78 assert (79 "delete\tDelete a user with USERNAME.\ndelete-all\tDelete ALL users in the database."80 in result.stdout81 )828384def test_completion_complete_subcommand_powershell():85 result = subprocess.run(86 [sys.executable, "-m", "coverage", "run", mod.__file__, " "],87 capture_output=True,88 encoding="utf-8",89 env={90 **os.environ,91 "_EXAMPLE_RICH_TAGS.PY_COMPLETE": "complete_powershell",92 "_TYPER_COMPLETE_ARGS": "example_rich_tags.py del",93 },94 )95 assert (96 "delete:::Delete a user with USERNAME.\ndelete-all:::Delete ALL users in the database."97 ) in result.stdout9899100def test_completion_complete_subcommand_pwsh():101 result = subprocess.run(102 [sys.executable, "-m", "coverage", "run", mod.__file__, " "],103 capture_output=True,104 encoding="utf-8",105 env={106 **os.environ,107 "_EXAMPLE_RICH_TAGS.PY_COMPLETE": "complete_pwsh",108 "_TYPER_COMPLETE_ARGS": "example_rich_tags.py del",109 },110 )111 assert (112 "delete:::Delete a user with USERNAME.\ndelete-all:::Delete ALL users in the database."113 ) in result.stdout
modified:tests/test_completion/test_completion_complete.py+1 added-1 removed
77 unmodified lines
78 "_TYPER_COMPLETE_FISH_ACTION": "get-args",79 },80 )81 assert (82 "delete Delete a user with USERNAME.\ndelete-all Delete ALL users in the database."82 "delete\tDelete a user with USERNAME.\ndelete-all\tDelete ALL users in the database."83 in result.stdout84 )8586
74 unmodified lines
added:tests/test_completion/test_sanitization.py+39 added
1from importlib.machinery import ModuleSpec2from typing import Union3from unittest.mock import patch45import pytest6from typer._completion_classes import _sanitize_help_text789@pytest.mark.parametrize(10 "find_spec, help_text, expected",11 [12 (13 ModuleSpec("rich", loader=None),14 "help text without rich tags",15 "help text without rich tags",16 ),17 (18 None,19 "help text without rich tags",20 "help text without rich tags",21 ),22 (23 ModuleSpec("rich", loader=None),24 "help [bold]with[/] rich tags",25 "help with rich tags",26 ),27 (28 None,29 "help [bold]with[/] rich tags",30 "help [bold]with[/] rich tags",31 ),32 ],33)34def test_sanitize_help_text(35 find_spec: Union[ModuleSpec, None], help_text: str, expected: str36):37 with patch("importlib.util.find_spec", return_value=find_spec) as mock_find_spec:38 assert _sanitize_help_text(help_text) == expected39 mock_find_spec.assert_called_once_with("rich")
modified:typer/_completion_classes.py+13 added-3 removed
1import importlib.util2import os3import re4import sys5from typing import Any, Dict, List, Tuple
15 unmodified lines
21except ImportError: # pragma: no cover22 shellingham = None232425def _sanitize_help_text(text: str) -> str:26 """Sanitizes the help text by removing rich tags"""27 if not importlib.util.find_spec("rich"):28 return text29 from . import rich_utils3031 return rich_utils.rich_render_text(text)323334class BashComplete(click.shell_completion.BashComplete):35 name = Shells.bash.value36 source_template = COMPLETION_SCRIPT_BASH37
64 unmodified lines
102 # TODO: Explore replicating the new behavior from Click, pay attention to103 # the difference with and without escape104 # return f"{item.type}\n{item.value}\n{item.help if item.help else '_'}"105 if item.help:96 return f'"{escape(item.value)}":"{escape(item.help)}"'106 return f'"{escape(item.value)}":"{_sanitize_help_text(escape(item.help))}"'107 else:108 return f'"{escape(item.value)}"'109110 def complete(self) -> str:
37 unmodified lines
148149 # return f"{item.type},{item.value}150 if item.help:151 formatted_help = re.sub(r"\s", " ", item.help)142 return f"{item.value}\t{formatted_help}"152 return f"{item.value}\t{_sanitize_help_text(formatted_help)}"153 else:154 return f"{item.value}"155156 def complete(self) -> str:
32 unmodified lines
189 args = cwords[1:-1] if incomplete else cwords[1:]190 return args, incomplete191192 def format_completion(self, item: click.shell_completion.CompletionItem) -> str:183 return f"{item.value}:::{item.help or ' '}"193 return f"{item.value}:::{_sanitize_help_text(item.help) if item.help else ' '}"194195196def completion_init() -> None:197 click.shell_completion.add_completion_class(BashComplete, Shells.bash.value)
6 unmodified lines
modified:typer/completion.py+1 added-13 removed
13 unmodified lines
14 import shellingham15except ImportError: # pragma: no cover16 shellingham = None1718try:19 import rich1821except ImportError: # pragma: no cover22 rich = None # type: ignore232419_click_patched = False202122def get_completion_inspect_parameters() -> Tuple[ParamMeta, ParamMeta]:
117 unmodified lines
140 return 0141142 # Typer override to print the completion help msg with Rich143 if instruction == "complete":150 if not rich: # pragma: no cover151 click.echo(comp.complete())144 click.echo(comp.complete())152 else:153 from . import rich_utils154155 rich_utils.print_with_rich(comp.complete())156145 return 0146 # Typer override end147148 click.echo(f'Completion instruction "{instruction}" not supported.', err=True)
1 unmodified line
modified:typer/rich_utils.py+6 added-6 removed
710 unmodified lines
711 console = _get_rich_console(stderr=True)712 console.print(ABORTED_TEXT, style=STYLE_ABORTED)713714715def print_with_rich(text: str) -> None:716 """Print richly formatted message."""717 console = _get_rich_console()718 console.print(text)719720715def rich_to_html(input_text: str) -> str:716 """Print the HTML version of a rich-formatted input string.717718 This function does not provide a full HTML page, but can be used to insert
3 unmodified lines
722723 console.print(input_text, overflow="ignore", crop=False)724725 return console.export_html(inline_styles=True, code_format="{code}").strip()726727728def rich_render_text(text: str) -> str:729 """Remove rich tags and render a pure text representation"""730 console = _get_rich_console()731 return "".join(segment.text for segment in console.render(text)).rstrip("\n")