Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 Fix shell completions for the fish shell #1069

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion tests/test_completion/test_completion_complete.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def test_completion_complete_subcommand_fish():
},
)
assert (
"delete Delete a user with USERNAME.\ndelete-all Delete ALL users in the database."
"delete\tDelete a user with USERNAME.\ndelete-all\tDelete ALL users in the database."
in result.stdout
)

Expand Down
87 changes: 87 additions & 0 deletions tests/test_completion/test_completion_complete_rich.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import os
import subprocess
import sys

from . import tutorial001_with_rich_tags as mod


def test_completion_complete_subcommand_bash():
result = subprocess.run(
[sys.executable, "-m", "coverage", "run", mod.__file__, " "],
capture_output=True,
encoding="utf-8",
env={
**os.environ,
"_TUTORIAL001_WITH_RICH_TAGS.PY_COMPLETE": "complete_bash",
"COMP_WORDS": "tutorial001_with_rich_tags.py del",
"COMP_CWORD": "1",
},
)
assert "delete\ndelete-all" in result.stdout


def test_completion_complete_subcommand_zsh():
result = subprocess.run(
[sys.executable, "-m", "coverage", "run", mod.__file__, " "],
capture_output=True,
encoding="utf-8",
env={
**os.environ,
"_TUTORIAL001_WITH_RICH_TAGS.PY_COMPLETE": "complete_zsh",
"_TYPER_COMPLETE_ARGS": "tutorial001_with_rich_tags.py del",
},
)
assert (
"""_arguments '*: :(("delete":"Delete a user with USERNAME."\n"""
"""\"delete-all":"Delete ALL users in the database."))'"""
) in result.stdout


def test_completion_complete_subcommand_fish():
result = subprocess.run(
[sys.executable, "-m", "coverage", "run", mod.__file__, " "],
capture_output=True,
encoding="utf-8",
env={
**os.environ,
"_TUTORIAL001_WITH_RICH_TAGS.PY_COMPLETE": "complete_fish",
"_TYPER_COMPLETE_ARGS": "tutorial001_with_rich_tags.py del",
"_TYPER_COMPLETE_FISH_ACTION": "get-args",
},
)
assert (
"delete\tDelete a user with USERNAME.\ndelete-all\tDelete ALL users in the database."
in result.stdout
)


def test_completion_complete_subcommand_powershell():
result = subprocess.run(
[sys.executable, "-m", "coverage", "run", mod.__file__, " "],
capture_output=True,
encoding="utf-8",
env={
**os.environ,
"_TUTORIAL001_WITH_RICH_TAGS.PY_COMPLETE": "complete_powershell",
"_TYPER_COMPLETE_ARGS": "tutorial001_with_rich_tags.py del",
},
)
assert (
"delete:::Delete a user with USERNAME.\ndelete-all:::Delete ALL users in the database."
) in result.stdout


def test_completion_complete_subcommand_pwsh():
result = subprocess.run(
[sys.executable, "-m", "coverage", "run", mod.__file__, " "],
capture_output=True,
encoding="utf-8",
env={
**os.environ,
"_TUTORIAL001_WITH_RICH_TAGS.PY_COMPLETE": "complete_pwsh",
"_TYPER_COMPLETE_ARGS": "tutorial001_with_rich_tags.py del",
},
)
assert (
"delete:::Delete a user with USERNAME.\ndelete-all:::Delete ALL users in the database."
) in result.stdout
39 changes: 39 additions & 0 deletions tests/test_completion/test_sanitization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
from importlib.machinery import ModuleSpec
from typing import Union
from unittest.mock import patch

import pytest
from typer._completion_classes import _sanitize_help_text


@pytest.mark.parametrize(
"find_spec, help_text, expected",
[
(
ModuleSpec("rich", loader=None),
"help text without rich tags",
"help text without rich tags",
),
(
None,
"help text without rich tags",
"help text without rich tags",
),
(
ModuleSpec("rich", loader=None),
"help [bold]with[/] rich tags",
"help with rich tags",
),
(
None,
"help [bold]with[/] rich tags",
"help [bold]with[/] rich tags",
),
],
)
def test_sanitize_help_text(
find_spec: Union[ModuleSpec, None], help_text: str, expected: str
):
with patch("importlib.util.find_spec", return_value=find_spec) as mock_find_spec:
assert _sanitize_help_text(help_text) == expected
mock_find_spec.assert_called_once_with("rich")
62 changes: 62 additions & 0 deletions tests/test_completion/tutorial001_with_rich_tags.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import typer

app = typer.Typer(help="Awesome CLI user manager.")


@app.command()
def create(username: str):
"""
Create a [green]new[green/] user with USERNAME.
"""
print(f"Creating user: {username}")


@app.command()
def delete(
username: str,
force: bool = typer.Option(
...,
prompt="Are you sure you want to delete the user?",
help="Force deletion without confirmation.",
),
):
"""
Delete a user with [bold]USERNAME[/].

If --force is not used, will ask for confirmation.
"""
if force:
print(f"Deleting user: {username}")
else:
print("Operation cancelled")


@app.command()
def delete_all(
force: bool = typer.Option(
...,
prompt="Are you sure you want to delete ALL users?",
help="Force deletion without confirmation.",
),
):
"""
[red]Delete ALL users[/red] in the database.

If --force is not used, will ask for confirmation.
"""
if force:
print("Deleting all users")
else:
print("Operation cancelled")


@app.command()
def init():
"""
Initialize the users database.
"""
print("Initializing user database")


if __name__ == "__main__":
app()
16 changes: 13 additions & 3 deletions typer/_completion_classes.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import importlib.util
import os
import re
import sys
Expand All @@ -21,6 +22,15 @@
shellingham = None


def _sanitize_help_text(text: str) -> str:
"""Sanitizes the help text by removing rich tags"""
if not importlib.util.find_spec("rich"):
return text
from . import rich_utils

return rich_utils.rich_render_text(text)


class BashComplete(click.shell_completion.BashComplete):
name = Shells.bash.value
source_template = COMPLETION_SCRIPT_BASH
Expand Down Expand Up @@ -93,7 +103,7 @@ def escape(s: str) -> str:
# the difference with and without escape
# return f"{item.type}\n{item.value}\n{item.help if item.help else '_'}"
if item.help:
return f'"{escape(item.value)}":"{escape(item.help)}"'
return f'"{escape(item.value)}":"{_sanitize_help_text(escape(item.help))}"'
else:
return f'"{escape(item.value)}"'

Expand Down Expand Up @@ -139,7 +149,7 @@ def format_completion(self, item: click.shell_completion.CompletionItem) -> str:
# return f"{item.type},{item.value}
if item.help:
formatted_help = re.sub(r"\s", " ", item.help)
return f"{item.value}\t{formatted_help}"
return f"{item.value}\t{_sanitize_help_text(formatted_help)}"
else:
return f"{item.value}"

Expand Down Expand Up @@ -180,7 +190,7 @@ def get_completion_args(self) -> Tuple[List[str], str]:
return args, incomplete

def format_completion(self, item: click.shell_completion.CompletionItem) -> str:
return f"{item.value}:::{item.help or ' '}"
return f"{item.value}:::{_sanitize_help_text(item.help) if item.help else ' '}"


def completion_init() -> None:
Expand Down
14 changes: 1 addition & 13 deletions typer/completion.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,6 @@
except ImportError: # pragma: no cover
shellingham = None

try:
import rich

except ImportError: # pragma: no cover
rich = None # type: ignore


_click_patched = False

Expand Down Expand Up @@ -147,13 +141,7 @@ def shell_complete(

# Typer override to print the completion help msg with Rich
if instruction == "complete":
if not rich: # pragma: no cover
click.echo(comp.complete())
else:
from . import rich_utils

rich_utils.print_with_rich(comp.complete())

click.echo(comp.complete())
return 0
# Typer override end

Expand Down
12 changes: 6 additions & 6 deletions typer/rich_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -712,12 +712,6 @@ def rich_abort_error() -> None:
console.print(ABORTED_TEXT, style=STYLE_ABORTED)


def print_with_rich(text: str) -> None:
"""Print richly formatted message."""
console = _get_rich_console()
console.print(text)


def rich_to_html(input_text: str) -> str:
"""Print the HTML version of a rich-formatted input string.

Expand All @@ -729,3 +723,9 @@ def rich_to_html(input_text: str) -> str:
console.print(input_text, overflow="ignore", crop=False)

return console.export_html(inline_styles=True, code_format="{code}").strip()


def rich_render_text(text: str) -> str:
"""Remove rich tags and render a pure text representation"""
console = _get_rich_console()
return "".join(segment.text for segment in console.render(text)).rstrip("\n")
Loading