Skip to content

Commit 1cb89d5

Browse files
committed
Handle missing COMP_WORDS and COMP_CWORD in completion script
1 parent 2a0acb5 commit 1cb89d5

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

src/pip/_internal/cli/autocompletion.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@ def autocomplete() -> None:
1717
# Don't complete if user hasn't sourced bash_completion file.
1818
if "PIP_AUTO_COMPLETE" not in os.environ:
1919
return
20+
# Don't complete if autocompletion environment variables
21+
# are not present
22+
if not os.environ.get("COMP_WORDS") or not os.environ.get("COMP_CWORD"):
23+
return
2024
cwords = os.environ["COMP_WORDS"].split()[1:]
2125
cword = int(os.environ["COMP_CWORD"])
2226
try:

tests/functional/test_completion.py

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,11 @@ def autocomplete_script(
128128

129129
class DoAutocomplete(Protocol):
130130
def __call__(
131-
self, words: str, cword: str, cwd: Union[Path, str, None] = None
131+
self,
132+
words: str,
133+
cword: str,
134+
cwd: Union[Path, str, None] = None,
135+
include_env: bool = True,
132136
) -> Tuple[TestPipResult, PipTestEnvironment]:
133137
...
134138

@@ -141,10 +145,14 @@ def autocomplete(
141145
autocomplete_script.environ["PIP_AUTO_COMPLETE"] = "1"
142146

143147
def do_autocomplete(
144-
words: str, cword: str, cwd: Union[Path, str, None] = None
148+
words: str,
149+
cword: str,
150+
cwd: Union[Path, str, None] = None,
151+
include_env: bool = True,
145152
) -> Tuple[TestPipResult, PipTestEnvironment]:
146-
autocomplete_script.environ["COMP_WORDS"] = words
147-
autocomplete_script.environ["COMP_CWORD"] = cword
153+
if include_env:
154+
autocomplete_script.environ["COMP_WORDS"] = words
155+
autocomplete_script.environ["COMP_CWORD"] = cword
148156
result = autocomplete_script.run(
149157
"python",
150158
"-c",
@@ -409,3 +417,16 @@ def test_completion_uses_same_executable_name(
409417
expect_stderr=deprecated_python,
410418
)
411419
assert executable_name in result.stdout
420+
421+
422+
def test_completion_without_env_vars(autocomplete: DoAutocomplete) -> None:
423+
"""
424+
Test getting completion <path> after options in command
425+
given absolute path
426+
"""
427+
res, env = autocomplete(
428+
words="pip install ",
429+
cword="",
430+
include_env=False,
431+
)
432+
assert res.stdout == ""

0 commit comments

Comments
 (0)