diff --git a/install.sh b/install.sh index dbdde79..ee60ec0 100755 --- a/install.sh +++ b/install.sh @@ -76,10 +76,23 @@ echo "[2/4] Installing screen_locker into user site-packages (editable)..." # gatelock is a sibling in the utils monorepo and is developed in lockstep with # the four lockers, so the local clone must win. Ordering is the fix: install # it last. -if [[ -d "$GATELOCK_DIR" ]]; then +# +# But only while the clone is at least the pinned release. On 2026-11-27 the +# clone sat at 0.16.0 behind the 0.16.2 pin, and re-asserting it kept the +# stall-watch fix out of the running lock. A stale clone gets the pin instead +# (forced: pip keeps an editable install that merely shares the name). +readonly PIN_GATE=("$PROD_PYTHON" "$SCRIPT_DIR/scripts/gatelock_pin.py") +if [[ -d "$GATELOCK_DIR" ]] && + "${PIN_GATE[@]}" clone-ok "$REPO_DIR/pyproject.toml" "$GATELOCK_DIR"; then echo " re-asserting editable gatelock from $GATELOCK_DIR..." "$PROD_PYTHON" -m pip install --user --break-system-packages \ --no-deps -e "$GATELOCK_DIR" +elif [[ -d "$GATELOCK_DIR" ]]; then + gatelock_spec="$("${PIN_GATE[@]}" spec "$REPO_DIR/pyproject.toml")" + echo " WARNING: $GATELOCK_DIR is older than the pin; installing" >&2 + echo " $gatelock_spec" >&2 + "$PROD_PYTHON" -m pip install --user --break-system-packages \ + --no-deps --force-reinstall --quiet "$gatelock_spec" else echo " WARNING: $GATELOCK_DIR not found; leaving the pinned gatelock" >&2 echo " wheel in place. Local gatelock changes will NOT be" >&2 @@ -125,7 +138,14 @@ if ! (cd /tmp && "$PROD_PYTHON" -c "import gatelock" 2>/dev/null); then echo " backend). Install it editable from ~/src/utils/gatelock." >&2 exit 1 fi -if [[ -d "$GATELOCK_DIR" ]]; then +# Fail closed on an old gatelock wherever it came from: a deploy that reports +# healthy while the lock runs code older than the pin ships nothing. +if ! "${PIN_GATE[@]}" installed-ok "$REPO_DIR/pyproject.toml"; then + echo "ERROR: the gatelock $PROD_PYTHON imports is older than the pin." >&2 + exit 1 +fi +if [[ -d "$GATELOCK_DIR" ]] && + "${PIN_GATE[@]}" clone-ok "$REPO_DIR/pyproject.toml" "$GATELOCK_DIR" >/dev/null 2>&1; then gatelock_path="$(cd /tmp && "$PROD_PYTHON" -c \ "import gatelock; print(gatelock.__file__)")" if [[ "$gatelock_path" != "$GATELOCK_DIR"* ]]; then diff --git a/screen_locker/tests/test_gatelock_pin.py b/screen_locker/tests/test_gatelock_pin.py new file mode 100644 index 0000000..76e9fa1 --- /dev/null +++ b/screen_locker/tests/test_gatelock_pin.py @@ -0,0 +1,95 @@ +"""The gatelock version gate install.sh runs (scripts/gatelock_pin.py).""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import pytest + +from scripts import gatelock_pin as gp + +if TYPE_CHECKING: + from pathlib import Path + +PIN = "gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.2#subdirectory=gatelock" + + +def _repo(root: Path, dep: str = PIN) -> Path: + path = root / "pyproject.toml" + path.write_text(f'[project]\ndependencies = [\n "{dep}",\n]\n', encoding="utf-8") + return path + + +def _clone(root: Path, version: str) -> Path: + clone = root / "gatelock" + clone.mkdir() + (clone / "pyproject.toml").write_text( + f'[project]\nname = "gatelock"\nversion = "{version}"\n', encoding="utf-8" + ) + return clone + + +def test_pinned_version_reads_the_tag(tmp_path: Path) -> None: + """The pin's tag is the version.""" + assert gp.pinned_version(_repo(tmp_path)) == (0, 16, 2) + + +def test_pinned_version_without_a_gatelock_pin(tmp_path: Path) -> None: + """No gatelock dependency is an error, not a pass.""" + with pytest.raises(gp.PinError, match="no gatelock"): + gp.pinned_version(_repo(tmp_path, "requests==2.0.0")) + + +@pytest.mark.parametrize( + ("version", "code"), [("0.16.0", 1), ("0.16.2", 0), ("0.17.0", 0)] +) +def test_clone_ok_compares_against_the_pin( + tmp_path: Path, version: str, code: int, caplog: pytest.LogCaptureFixture +) -> None: + """A clone older than the pin must not be made editable.""" + # 2026-11-27: a stale ~/src/utils clone (0.16.0) was re-asserted over the + # 0.16.2 pin, and the fix never reached the lock. + repo, clone = _repo(tmp_path), _clone(tmp_path, version) + assert gp.main(["clone-ok", str(repo), str(clone)]) == code + if code: + assert "older than the pin" in caplog.text + + +def test_clone_ok_unreadable_clone(tmp_path: Path) -> None: + """A missing clone fails closed.""" + repo = _repo(tmp_path) + assert gp.main(["clone-ok", str(repo), str(tmp_path / "missing")]) == gp.EXIT_ERROR + + +def test_installed_ok(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + """The imported gatelock is checked against the pin.""" + repo = _repo(tmp_path) + monkeypatch.setattr(gp, "installed_version", lambda: (0, 16, 2)) + assert gp.main(["installed-ok", str(repo)]) == gp.EXIT_OK + monkeypatch.setattr(gp, "installed_version", lambda: (0, 16, 0)) + assert gp.main(["installed-ok", str(repo)]) == 1 + + +def test_installed_version_is_the_running_one() -> None: + """The real metadata lookup returns a version.""" + assert gp.installed_version() >= (0, 1, 0) + + +def test_spec_prints_the_pin( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + """Spec prints the exact pinned dependency for pip.""" + assert gp.main(["spec", str(_repo(tmp_path))]) == gp.EXIT_OK + assert capsys.readouterr().out.strip() == PIN + + +def test_bad_usage(tmp_path: Path) -> None: + """Unknown or short commands are usage errors.""" + assert gp.main(["nope"]) == gp.EXIT_ERROR + assert gp.main(["clone-ok", str(_repo(tmp_path))]) == gp.EXIT_ERROR + + +def test_bad_version_text(tmp_path: Path) -> None: + """A non-numeric version fails closed.""" + repo, clone = _repo(tmp_path), _clone(tmp_path, "abc") + assert gp.main(["clone-ok", str(repo), str(clone)]) == gp.EXIT_ERROR diff --git a/scripts/gatelock_pin.py b/scripts/gatelock_pin.py new file mode 100644 index 0000000..0093c14 --- /dev/null +++ b/scripts/gatelock_pin.py @@ -0,0 +1,123 @@ +"""Compare a gatelock against the version screen-locker pins (install.sh's gate). + +install.sh re-installs the ~/src/utils/gatelock clone editable so unreleased +gatelock work reaches the lock. That is only right while the clone is at least +the pinned release: on 2026-11-27 a stale clone (0.16.0) was re-asserted over +the 0.16.2 pin and the stall fix never reached the running lock. + +CLI (exit 0 ok, 1 older than the pin, 2 unreadable/usage): + gatelock_pin.py clone-ok PYPROJECT CLONE_DIR clone may be made editable + gatelock_pin.py installed-ok PYPROJECT imported gatelock is current + gatelock_pin.py spec PYPROJECT print the pinned pip spec +""" + +from __future__ import annotations + +from importlib import metadata +import logging +from pathlib import Path +import re +import sys +import tomllib + +_logger = logging.getLogger("gatelock_pin") + +EXIT_OK = 0 +EXIT_OLDER = 1 +EXIT_ERROR = 2 + +_PIN = re.compile(r"^gatelock\s*@.*@gatelock-v(?P[0-9][0-9.]*)#") + +Version = tuple[int, ...] + + +class PinError(ValueError): + """A version that cannot be read: the gate fails closed on it.""" + + +def _parse(text: str) -> Version: + try: + return tuple(int(part) for part in text.split(".")) + except ValueError as exc: + msg = f"not a release version: {text!r}" + raise PinError(msg) from exc + + +def _project(path: Path) -> dict[str, object]: + try: + data = tomllib.loads(path.read_text(encoding="utf-8")) + except (OSError, tomllib.TOMLDecodeError) as exc: + msg = f"cannot read {path}: {exc}" + raise PinError(msg) from exc + project = data.get("project", {}) + return project if isinstance(project, dict) else {} + + +def _pin(pyproject: Path) -> re.Match[str]: + for dep in _project(pyproject).get("dependencies", []): + match = _PIN.match(str(dep)) + if match: + return match + msg = f"no gatelock pin in {pyproject}" + raise PinError(msg) + + +def pinned_spec(pyproject: Path) -> str: + """Return the gatelock dependency string pinned in ``pyproject``.""" + return _pin(pyproject).string + + +def pinned_version(pyproject: Path) -> Version: + """Return the gatelock tag version pinned in ``pyproject``'s dependencies.""" + return _parse(_pin(pyproject)["v"].rstrip(".")) + + +def clone_version(clone: Path) -> Version: + """Return the version a gatelock source clone declares.""" + return _parse(str(_project(clone / "pyproject.toml").get("version", ""))) + + +def installed_version() -> Version: + """Return the version of the gatelock this interpreter imports.""" + return _parse(metadata.version("gatelock")) + + +def _show(version: Version) -> str: + return ".".join(map(str, version)) + + +def _check(what: str, have: Version, pin: Version) -> int: + if have < pin: + _logger.error( + "gatelock %s %s is older than the pin %s", what, _show(have), _show(pin) + ) + return EXIT_OLDER + _logger.warning("gatelock %s %s >= pin %s", what, _show(have), _show(pin)) + return EXIT_OK + + +def main(argv: list[str]) -> int: + """Run one check; see the module docstring for the exit codes.""" + try: + match argv: + case ["clone-ok", pyproject, clone]: + pin = pinned_version(Path(pyproject)) + return _check("clone", clone_version(Path(clone)), pin) + case ["installed-ok", pyproject]: + pin = pinned_version(Path(pyproject)) + return _check("installed", installed_version(), pin) + case ["spec", pyproject]: + sys.stdout.write(pinned_spec(Path(pyproject)) + "\n") + return EXIT_OK + case _: + _logger.error("usage:%s", __doc__) + return EXIT_ERROR + except PinError, metadata.PackageNotFoundError: + # Fail closed: install.sh treats any non-zero exit as untrusted. + _logger.exception("gatelock version gate failed") + return EXIT_ERROR + + +if __name__ == "__main__": + logging.basicConfig(format="%(message)s") + sys.exit(main(sys.argv[1:]))