Skip to content
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
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ rag = [
]

[project.scripts]
pt-snap = "pt_snap_cli.cli:app"
pt-snap = "pt_snap_cli.cli:_safe_call"

[tool.setuptools.packages.find]
where = ["src"]
Expand Down
23 changes: 22 additions & 1 deletion src/pt_snap_cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,5 +364,26 @@ def show_config(
typer.echo(f" {key}: {value}")


def _safe_call() -> int:
"""Wrapper for the console script entry point to handle completion errors.

Returns:
Exit code (0 for success, 1 for errors).
"""
try:
app()
return 0
except KeyError as e:
# Click's shell completion can raise KeyError when COMP_WORDS or
# COMP_LINE is not set in non-standard terminal environments.
# Exit silently β€” printing to stdout causes the shell to try
# executing the error message as a command.
if str(e) in ("'COMP_WORDS'", "'COMP_LINE'", "'COMP_POINT'"):
return 1
raise


if __name__ == "__main__":
app()
import sys

sys.exit(_safe_call())
38 changes: 38 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -615,3 +615,41 @@ def test_query_list_invalid_category(self, sample_db: Path) -> None:
result = runner.invoke(app, ["query", str(sample_db), "--list", "--category", "invalid"])
assert result.exit_code != 0
assert "Invalid category" in result.stdout


class TestSafeCall:
"""Test _safe_call wrapper for console script entry point."""

def test_safe_call_runs_app(self, sample_db: Path) -> None:
"""Test that _safe_call successfully runs the CLI app."""
from unittest.mock import patch

from pt_snap_cli.cli import _safe_call

with patch("sys.argv", ["pt-snap", "--version"]):
with pytest.raises(SystemExit) as exc_info:
_safe_call()
assert exc_info.value.code == 0

def test_safe_call_catches_comp_keyerror(self) -> None:
"""Test _safe_call catches KeyError from broken shell completion."""
from unittest.mock import patch

from pt_snap_cli.cli import _safe_call

# Simulate Click trying completion with missing COMP_WORDS
with patch("sys.argv", ["pt-snap"]):
with patch("click.core.Command.parse_args", side_effect=KeyError("COMP_WORDS")):
exit_code = _safe_call()
assert exit_code == 1

def test_safe_call_reraises_unrelated_keyerror(self) -> None:
"""Test _safe_call re-raises KeyError not related to shell completion."""
from unittest.mock import patch

from pt_snap_cli.cli import _safe_call

with patch("sys.argv", ["pt-snap"]):
with patch("click.core.Command.parse_args", side_effect=KeyError("some_other_key")):
with pytest.raises(KeyError, match="some_other_key"):
_safe_call()
Loading