Skip to content

🐛 Ensure that autocompletion works for Path arguments/options #1138

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

Merged
merged 8 commits into from
Mar 26, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
14 changes: 14 additions & 0 deletions tests/test_completion/path_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from pathlib import Path

import typer

app = typer.Typer()


@app.command()
def f(p: Path):
print(p)


if __name__ == "__main__":
app()
30 changes: 30 additions & 0 deletions tests/test_completion/test_completion_path.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import os
import subprocess
import sys

from . import path_example as mod


def test_script():
result = subprocess.run(
[sys.executable, "-m", "coverage", "run", mod.__file__, "path/to/deadpool"],
capture_output=True,
encoding="utf-8",
)
assert result.returncode == 0
assert "deadpool" in result.stdout


def test_completion_path_bash():
result = subprocess.run(
[sys.executable, "-m", "coverage", "run", mod.__file__, " "],
capture_output=True,
encoding="utf-8",
env={
**os.environ,
"_PATH_EXAMPLE.PY_COMPLETE": "complete_bash",
"COMP_WORDS": "path_example.py ",
"COMP_CWORD": "2",
},
)
assert result.returncode == 0
3 changes: 2 additions & 1 deletion typer/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
ParamMeta,
Required,
TyperInfo,
TyperPath,
)
from .utils import get_params_from_function

Expand Down Expand Up @@ -743,7 +744,7 @@ def get_click_type(
or parameter_info.path_type
or parameter_info.resolve_path
):
return click.Path(
return TyperPath(
exists=parameter_info.exists,
file_okay=parameter_info.file_okay,
dir_okay=parameter_info.dir_okay,
Expand Down
11 changes: 11 additions & 0 deletions typer/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -531,3 +531,14 @@ def __init__(
self.pretty_exceptions_enable = pretty_exceptions_enable
self.pretty_exceptions_show_locals = pretty_exceptions_show_locals
self.pretty_exceptions_short = pretty_exceptions_short


class TyperPath(click.Path):
# Overwrite Click's behaviour to be compatible with Typer's autocompletion system
def shell_complete(
self, ctx: click.Context, param: click.Parameter, incomplete: str
) -> List[click.shell_completion.CompletionItem]:
"""Return an empty list so that the autocompletion functionality
will work properly from the commandline.
"""
return []
Loading