diff --git a/pyproject.toml b/pyproject.toml index 707aebd..2be4fb0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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"] diff --git a/src/pt_snap_cli/cli.py b/src/pt_snap_cli/cli.py index 2ad1b3a..bc47763 100644 --- a/src/pt_snap_cli/cli.py +++ b/src/pt_snap_cli/cli.py @@ -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()) diff --git a/tests/test_cli.py b/tests/test_cli.py index 6d1e429..dd8eb4d 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -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()