From 15b9aa5139a3d2b22b72a363595059382d542267 Mon Sep 17 00:00:00 2001 From: codeasier Date: Fri, 17 Apr 2026 22:05:24 +0800 Subject: [PATCH 1/2] fix: graceful handling of shell completion KeyError crash (#26) Click's shell completion raises KeyError when COMP_WORDS/COMP_LINE env vars are missing in non-standard terminal environments. Added a _safe_call() wrapper that catches these specific KeyErrors and displays a helpful message instead of crashing with a traceback. - Updated console script entry point to use _safe_call - Updated __main__ block to use _safe_call - Added tests for the wrapper (happy path, completion error, unrelated error) Closes #26 --- pyproject.toml | 2 +- src/pt_snap_cli/cli.py | 26 +++++++++++++++++++++++++- tests/test_cli.py | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 64 insertions(+), 2 deletions(-) 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..2cbc3b0 100644 --- a/src/pt_snap_cli/cli.py +++ b/src/pt_snap_cli/cli.py @@ -364,5 +364,29 @@ 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. + if str(e) in ("'COMP_WORDS'", "'COMP_LINE'", "'COMP_POINT'"): + typer.secho( + "Error: shell completion is not properly configured. " + "Run 'pt-snap --install-completion' and restart your shell.", + fg=typer.colors.RED, + ) + 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() From 427e78ee06252de831770a886ef20d13ef5d19f6 Mon Sep 17 00:00:00 2001 From: codeasier Date: Fri, 17 Apr 2026 22:10:59 +0800 Subject: [PATCH 2/2] fix: exit silently on completion KeyError instead of printing error The previous fix printed an error message to stdout, which zsh completion captured and tried to execute as a command, causing '(eval):1: command not found: Error:'. Exit silently instead. Closes #26 --- src/pt_snap_cli/cli.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/pt_snap_cli/cli.py b/src/pt_snap_cli/cli.py index 2cbc3b0..bc47763 100644 --- a/src/pt_snap_cli/cli.py +++ b/src/pt_snap_cli/cli.py @@ -376,12 +376,9 @@ def _safe_call() -> int: 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'"): - typer.secho( - "Error: shell completion is not properly configured. " - "Run 'pt-snap --install-completion' and restart your shell.", - fg=typer.colors.RED, - ) return 1 raise