Skip to content

Commit 322bc8d

Browse files
authored
🐛 Ensure that autocompletion works for Path arguments/options (#1138)
1 parent 3c9f2c0 commit 322bc8d

File tree

4 files changed

+57
-1
lines changed

4 files changed

+57
-1
lines changed

tests/test_completion/path_example.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from pathlib import Path
2+
3+
import typer
4+
5+
app = typer.Typer()
6+
7+
8+
@app.command()
9+
def f(p: Path):
10+
print(p)
11+
12+
13+
if __name__ == "__main__":
14+
app()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import os
2+
import subprocess
3+
import sys
4+
5+
from . import path_example as mod
6+
7+
8+
def test_script():
9+
result = subprocess.run(
10+
[sys.executable, "-m", "coverage", "run", mod.__file__, "path/to/deadpool"],
11+
capture_output=True,
12+
encoding="utf-8",
13+
)
14+
assert result.returncode == 0
15+
assert "deadpool" in result.stdout
16+
17+
18+
def test_completion_path_bash():
19+
result = subprocess.run(
20+
[sys.executable, "-m", "coverage", "run", mod.__file__, " "],
21+
capture_output=True,
22+
encoding="utf-8",
23+
env={
24+
**os.environ,
25+
"_PATH_EXAMPLE.PY_COMPLETE": "complete_bash",
26+
"COMP_WORDS": "path_example.py ",
27+
"COMP_CWORD": "2",
28+
},
29+
)
30+
assert result.returncode == 0

typer/main.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
ParamMeta,
4545
Required,
4646
TyperInfo,
47+
TyperPath,
4748
)
4849
from .utils import get_params_from_function
4950

@@ -743,7 +744,7 @@ def get_click_type(
743744
or parameter_info.path_type
744745
or parameter_info.resolve_path
745746
):
746-
return click.Path(
747+
return TyperPath(
747748
exists=parameter_info.exists,
748749
file_okay=parameter_info.file_okay,
749750
dir_okay=parameter_info.dir_okay,

typer/models.py

+11
Original file line numberDiff line numberDiff line change
@@ -531,3 +531,14 @@ def __init__(
531531
self.pretty_exceptions_enable = pretty_exceptions_enable
532532
self.pretty_exceptions_show_locals = pretty_exceptions_show_locals
533533
self.pretty_exceptions_short = pretty_exceptions_short
534+
535+
536+
class TyperPath(click.Path):
537+
# Overwrite Click's behaviour to be compatible with Typer's autocompletion system
538+
def shell_complete(
539+
self, ctx: click.Context, param: click.Parameter, incomplete: str
540+
) -> List[click.shell_completion.CompletionItem]:
541+
"""Return an empty list so that the autocompletion functionality
542+
will work properly from the commandline.
543+
"""
544+
return []

0 commit comments

Comments
 (0)