diff --git a/src/specify_cli/events/__init__.py b/src/specify_cli/events/__init__.py index 66bef8154c..026ce4683a 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -4,6 +4,7 @@ - ``resolve_events`` — layered event resolution (CLI flag → YAML override → extension-declared → built-in). - ``collect_extension_events`` — scan installed extension.yml files for ``events:``. - ``install_integration_events`` / ``remove_integration_events`` — entry points called from ``IntegrationBase.setup()`` / ``teardown()``. +- ``hook_interpreter_available`` — whether the interpreter a generated hook command would use resolves on this machine (#5619). The singular CLI namespace intentionally maps to the plural Python package. ``specify_cli.events`` is an established domain API and monkeypatch boundary, @@ -1202,6 +1203,70 @@ def _resolve_interpreter_for_target(target_os: str) -> str: return "python3" +def hook_interpreter_available(interpreter: str, project_root: Path) -> bool: + """Return True when *interpreter* resolves to a runnable Python (#5619). + + *interpreter* is the string a generated hook command would use, so it + is resolved the same way the hook command does: a bare name is looked + up on ``PATH`` (on Windows, a found name must also pass the Store + stub probe, matching ``resolve_python_interpreter``); a + project-relative path is resolved against *project_root*; an absolute + path must exist. An empty string is unavailable. + """ + if not interpreter: + return False + candidate = Path(interpreter) + if candidate.is_absolute(): + return candidate.exists() + if "/" in interpreter or "\\" in interpreter: + return (project_root / interpreter).exists() + found = shutil.which(interpreter) + if found is None: + return False + if sys.platform == "win32": + from ..integrations.base import IntegrationBase + + return IntegrationBase._interpreter_runs(found) + return True + + +def _warn_if_hook_interpreter_missing( + integration: IntegrationBase, project_root: Path +) -> None: + """Warn when the generated hook commands have no interpreter to run. + + The warning is advisory: install still succeeds, because the hooks + may run on another machine (e.g. a config generated here and used on + Windows). It names the interpreter and the remedy so the failure + does not stay silent until the agent's hook runner drops it. + """ + interpreter = _resolve_interpreter(project_root) + if hook_interpreter_available(interpreter, project_root): + # ``resolve_python_interpreter`` falls back to the running + # interpreter when no venv interpreter and no bare name is on + # PATH; the generated command then embeds an absolute path that + # may belong to an ephemeral environment (a one-time ``uvx`` + # run), so warn. An empty ``.venv`` directory does not change + # the selected interpreter, so it does not suppress the warning. + # Check the bare names with the helper, not ``shutil.which``: + # a Windows Store stub is found by ``which`` but fails the + # helper's run probe, and must not suppress the warning. + if not ( + Path(interpreter).is_absolute() + and not hook_interpreter_available("python3", project_root) + and not hook_interpreter_available("python", project_root) + ): + return + print( + f"⚠️ Hook interpreter {interpreter!r} could not be resolved on " + f"this machine, so the event hooks installed for " + f"{integration.key} may fail silently. Put a Python interpreter on " + f"PATH, or create a project .venv and rerun " + f"`specify integration upgrade {integration.key}`.", + file=sys.stderr, + ) + + def _native_timeout(integration: IntegrationBase, timeout_seconds: Any) -> int: """Return the timeout in the unit the integration's native config expects. @@ -1403,6 +1468,11 @@ def install_integration_events( created: list[Path] = [] + # #5619: warn when the hook commands written below would have no + # interpreter to run on this machine. Advisory only — install + # continues, since the hooks may run elsewhere. + _warn_if_hook_interpreter_missing(integration, project_root) + # 1. Generate events.py dispatcher script (#12: validate destination first) dispatcher_dir = project_root / EVENTS_DISPATCHER_DIR dispatcher_path = dispatcher_dir / EVENTS_DISPATCHER_FILENAME diff --git a/tests/specify_cli/events/test_events.py b/tests/specify_cli/events/test_events.py index f5f7183702..de70791e66 100644 --- a/tests/specify_cli/events/test_events.py +++ b/tests/specify_cli/events/test_events.py @@ -3749,3 +3749,138 @@ def test_refresh_failure_preserves_existing_config(self, tmp_path): # The pre-existing config was NOT destroyed before the failure # (install handles cleanup atomically; refresh no longer pre-strips). assert config_path.read_text() == original + +# -- Hook interpreter check (#5619) ------------------------------------------ + + +class TestHookInterpreterAvailable: + """Resolution tests for the hook interpreter check: PATH command, + project-relative venv path, and absolute path (issue acceptance + criteria).""" + + def test_bare_name_on_path_is_available(self, tmp_path, monkeypatch): + from specify_cli.events import hook_interpreter_available + import shutil as _shutil + + # Pin a POSIX platform so the Windows stub probe does not reject + # the fake PATH entry on Windows CI (see TestResolvePythonInterpreter). + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + monkeypatch.setattr(_shutil, "which", lambda name: "/usr/bin/python3") + assert hook_interpreter_available("python3", tmp_path) is True + + def test_bare_name_missing_from_path_is_unavailable(self, tmp_path, monkeypatch): + from specify_cli.events import hook_interpreter_available + import shutil as _shutil + + monkeypatch.setattr(_shutil, "which", lambda name: None) + assert hook_interpreter_available("python3", tmp_path) is False + + def test_project_venv_path_resolves_against_project_root(self, tmp_path): + from specify_cli.events import hook_interpreter_available + + venv_python = tmp_path / ".venv" / "bin" / "python" + venv_python.parent.mkdir(parents=True) + venv_python.write_text("#!/bin/sh\n", encoding="utf-8") + assert hook_interpreter_available(".venv/bin/python", tmp_path) is True + assert hook_interpreter_available(".venv/bin/python", tmp_path.parent) is False + + def test_absolute_path_must_exist(self, tmp_path): + from specify_cli.events import hook_interpreter_available + + existing = tmp_path / "python" + existing.write_text("#!/bin/sh\n", encoding="utf-8") + assert hook_interpreter_available(str(existing), tmp_path) is True + assert ( + hook_interpreter_available(str(tmp_path / "no-such-python"), tmp_path) + is False + ) + + def test_empty_interpreter_is_unavailable(self, tmp_path): + from specify_cli.events import hook_interpreter_available + + assert hook_interpreter_available("", tmp_path) is False + + +class TestInstallWarnsOnMissingHookInterpreter: + """Install warns (without failing) when the hook interpreter the + generated commands would use cannot be resolved on this machine.""" + + def _install(self, tmp_path): + integration = ClaudeIntegration() + manifest = MagicMock(spec=IntegrationManifest) + manifest.files = {} + manifest.record_file = MagicMock() + manifest.record_existing = MagicMock() + install_integration_events( + integration, + tmp_path, + manifest, + {"session_start": [{"command": "speckit.x.y"}]}, + ) + return tmp_path / ".claude/settings.json" + + def test_warns_when_no_interpreter_on_path(self, tmp_path, monkeypatch, capsys): + import shutil as _shutil + + monkeypatch.setattr(_shutil, "which", lambda name: None) + config_path = self._install(tmp_path) + # The install itself still succeeds; the warning is advisory. + assert config_path.is_file() + err = capsys.readouterr().err + assert "python" in err + assert "PATH" in err or ".venv" in err + + def test_no_warning_when_interpreter_resolves(self, tmp_path, monkeypatch, capsys): + import shutil as _shutil + + # Mock a successful PATH lookup so the test does not depend on the + # runner having a system Python (e.g. a uvx-only install warns). + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + monkeypatch.setattr(_shutil, "which", lambda name: "/usr/bin/python3") + self._install(tmp_path) + err = capsys.readouterr().err + assert "interpreter" not in err.lower() + + def test_warns_when_path_has_only_windows_store_stubs( + self, tmp_path, monkeypatch, capsys + ): + import shutil as _shutil + + from specify_cli.integrations.base import IntegrationBase + + monkeypatch.setattr("specify_cli.events.sys.platform", "win32") + monkeypatch.setattr( + _shutil, + "which", + lambda name: f"C:\\WindowsApps\\{name}.exe" + if name in ("python3", "python") + else None, + ) + monkeypatch.setattr( + IntegrationBase, "_interpreter_runs", staticmethod(lambda path: False) + ) + config_path = self._install(tmp_path) + assert config_path.is_file() + err = capsys.readouterr().err + assert "Hook interpreter" in err + + def test_warns_when_venv_directory_is_empty(self, tmp_path, monkeypatch, capsys): + import shutil as _shutil + + (tmp_path / ".venv").mkdir() + monkeypatch.setattr(_shutil, "which", lambda name: None) + config_path = self._install(tmp_path) + assert config_path.is_file() + err = capsys.readouterr().err + assert "Hook interpreter" in err + + def test_no_warning_when_project_venv_exists(self, tmp_path, monkeypatch, capsys): + import shutil as _shutil + + venv_python = tmp_path / ".venv" / "bin" / "python" + venv_python.parent.mkdir(parents=True) + venv_python.write_text("#!/bin/sh\n", encoding="utf-8") + monkeypatch.setattr(_shutil, "which", lambda name: None) + self._install(tmp_path) + err = capsys.readouterr().err + assert "interpreter" not in err.lower()