🐛 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
Provenance
- Commit
4f04666- Tree
a320718- Author
goraje <45512761+goraje@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
85ca5b5
7 files changed+204 added−23 removed
added:tests/test_completion/example_rich_tags.py+31 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def create(username: str):8+ """9+ Create a [green]new[green/] user with USERNAME.10+ """11+ print(f"Creating user: {username}")12+13+14+@app.command()15+def delete(username: str):16+ """17+ Delete a user with [bold]USERNAME[/].18+ """19+ print(f"Deleting user: {username}")20+21+22+@app.command()23+def delete_all():24+ """25+ [red]Delete ALL users[/red] in the database.26+ """27+ print("Deleting all users")28+29+30+if __name__ == "__main__":31+ app()added:tests/test_completion/test_completion_complete_rich.py+113 added
1+import os2+import subprocess3+import sys4+5+from . import example_rich_tags as mod6+7+8+def 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.stdout16+17+ 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.stdout24+25+ 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.stdout32+33+34+def 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.stdout47+48+49+def 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.stdout64+65+66+def 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+ )82+83+84+def 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.stdout98+99+100+def 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.stdoutmodified:tests/test_completion/test_completion_complete.py+1 added-1 removed
77 unmodified lines78 "_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 )85 86 74 unmodified linesadded:tests/test_completion/test_sanitization.py+39 added
1+from importlib.machinery import ModuleSpec2+from typing import Union3+from unittest.mock import patch4+5+import pytest6+from typer._completion_classes import _sanitize_help_text7+8+9+@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+)34+def 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
1+import importlib.util2 import os3 import re4 import sys5 from typing import Any, Dict, List, Tuple15 unmodified lines21 except ImportError: # pragma: no cover22 shellingham = None23 24 25+def _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_utils30+31+ return rich_utils.rich_render_text(text)32+33+34 class BashComplete(click.shell_completion.BashComplete):35 name = Shells.bash.value36 source_template = COMPLETION_SCRIPT_BASH37 64 unmodified lines102 # 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)}"'109 110 def complete(self) -> str:37 unmodified lines148 149 # 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}"155 156 def complete(self) -> str:32 unmodified lines189 args = cwords[1:-1] if incomplete else cwords[1:]190 return args, incomplete191 192 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 ' '}"194 195 196 def completion_init() -> None:197 click.shell_completion.add_completion_class(BashComplete, Shells.bash.value)6 unmodified linesmodified:typer/completion.py+1 added-13 removed
13 unmodified lines14 import shellingham15 except ImportError: # pragma: no cover16 shellingham = None17 18-try:19- import rich18 21-except ImportError: # pragma: no cover22- rich = None # type: ignore23-24-19 _click_patched = False20 21 22 def get_completion_inspect_parameters() -> Tuple[ParamMeta, ParamMeta]:117 unmodified lines140 return 0141 142 # 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_utils154-155- rich_utils.print_with_rich(comp.complete())156-145 return 0146 # Typer override end147 148 click.echo(f'Completion instruction "{instruction}" not supported.', err=True)1 unmodified linemodified:typer/rich_utils.py+6 added-6 removed
710 unmodified lines711 console = _get_rich_console(stderr=True)712 console.print(ABORTED_TEXT, style=STYLE_ABORTED)713 714 715-def print_with_rich(text: str) -> None:716- """Print richly formatted message."""717- console = _get_rich_console()718- console.print(text)719-720-715 def rich_to_html(input_text: str) -> str:716 """Print the HTML version of a rich-formatted input string.717 718 This function does not provide a full HTML page, but can be used to insert3 unmodified lines722 723 console.print(input_text, overflow="ignore", crop=False)724 725 return console.export_html(inline_styles=True, code_format="{code}").strip()726+727+728+def 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")