#!/usr/bin/env python3 """Detect live_git vs snapshot vs detached review modes. Compact packages do not ship raw ``.git``. Tests and replay entrypoints must distinguish: - ``live_git``: resolvable raw ``.git`` (strict commit-compare paths OK) - ``snapshot``: sanitized synthetic single-commit snapshot present (no raw ``.git``) - ``detached``: extracted package / copy without raw ``.git`` or snapshot Override with ``PRODU2_GIT_MODE`` when intentionally forcing a mode. """ from __future__ import annotations import json import os import shutil import subprocess import sys from pathlib import Path from typing import Any LIVE_GIT = "live_git" SNAPSHOT = "snapshot" DETACHED = "detached" GIT_MODES = frozenset({LIVE_GIT, SNAPSHOT, DETACHED}) ENV_GIT_MODE = "PRODU2_GIT_MODE" def _tools_dir() -> Path: return Path(__file__).resolve().parent def _load_handoff(): tools = _tools_dir() if str(tools) not in sys.path: sys.path.insert(0, str(tools)) import package_agent_handoff as handoff # noqa: WPS433 return handoff def _read_json(path: Path) -> dict[str, Any] | None: if not path.is_file(): return None try: payload = json.loads(path.read_text(encoding="utf-8")) except (OSError, UnicodeError, json.JSONDecodeError): return None return payload if isinstance(payload, dict) else None def find_meta_git_dir(root: Path) -> Path | None: """Locate ``meta/git`` under a repo root or extracted CPLD tree.""" candidates = ( root / "meta" / "git", root / "CPLD" / "meta" / "git", ) for path in candidates: if path.is_dir(): return path return None def snapshot_present(root: Path) -> bool: meta_git = find_meta_git_dir(root) if meta_git is None: return False bundle = meta_git / "sanitized-snapshot.bundle" status = _read_json(meta_git / "sanitized-snapshot-status.json") if bundle.is_file(): return True if status and status.get("status") == "pass" and status.get("requested") is True: return True return False def raw_git_marker_present(root: Path) -> bool: """True when a raw ``.git`` file/directory marker exists (incl. linked worktrees).""" marker = root / ".git" try: return marker.exists() except OSError: return False def live_git_usable(root: Path) -> bool: """True when git treats ``root`` as an inside-work-tree checkout. Packager ``resolve_git_dir`` intentionally rejects linked-worktree gitdirs that point outside the tree (security). Mode detection still treats those as ``live_git`` so commit-compare tests stay strict on real checkouts. """ if not raw_git_marker_present(root): return False git = shutil.which("git") if not git: # Marker present but tool missing: still classify as live_git for policy. return True try: completed = subprocess.run( [git, "-C", str(root), "rev-parse", "--is-inside-work-tree"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, check=False, ) except OSError: return True return completed.returncode == 0 and completed.stdout.strip() == "true" def detect_git_mode(root: Path | None = None) -> str: """Return ``live_git``, ``snapshot``, or ``detached`` for ``root``.""" override = os.environ.get(ENV_GIT_MODE, "").strip().casefold() if override: if override not in GIT_MODES: raise ValueError( f"invalid {ENV_GIT_MODE}={override!r}; expected one of " f"{sorted(GIT_MODES)}" ) return override base = (root or Path.cwd()).expanduser().resolve(strict=False) if live_git_usable(base): return LIVE_GIT if snapshot_present(base): return SNAPSHOT return DETACHED def require_live_git(root: Path, testcase: Any | None = None) -> str: """Assert or skip unless ``root`` is in ``live_git`` mode. When ``testcase`` is a unittest.TestCase, skips instead of raising so compact/detached replay hosts stay green. Live worktrees remain strict. """ mode = detect_git_mode(root) if mode == LIVE_GIT: return mode message = ( f"requires live_git (raw .git); current mode={mode} under {root}. " "Compact/detached packages are Git-optional by policy." ) if testcase is not None and hasattr(testcase, "skipTest"): testcase.skipTest(message) raise RuntimeError(message) def git_optional_ok(root: Path | None = None) -> bool: """True when software checks may run without raw ``.git``.""" return detect_git_mode(root) in {SNAPSHOT, DETACHED, LIVE_GIT} def describe_git_mode(root: Path | None = None) -> dict[str, Any]: base = (root or Path.cwd()).expanduser().resolve(strict=False) mode = detect_git_mode(base) handoff = _load_handoff() packager_git_dir = handoff.resolve_git_dir(base) meta_git = find_meta_git_dir(base) status = _read_json(meta_git / "sanitized-snapshot-status.json") if meta_git else None return { "schema": "cpld-git-worktree-mode-v1", "root": str(base), "mode": mode, "raw_git_marker_present": raw_git_marker_present(base), "packager_resolve_git_dir": str(packager_git_dir) if packager_git_dir else None, "packager_resolve_rejects_linked_worktree": ( raw_git_marker_present(base) and packager_git_dir is None and mode == LIVE_GIT ), "meta_git_dir": str(meta_git) if meta_git is not None else None, "sanitized_snapshot_present": snapshot_present(base), "sanitized_snapshot_status": status, "env_override": os.environ.get(ENV_GIT_MODE) or None, } def main(argv: list[str] | None = None) -> int: import argparse parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--root", type=Path, default=Path.cwd(), help="repository or extracted CPLD root", ) args = parser.parse_args(argv) print(json.dumps(describe_git_mode(args.root), ensure_ascii=False, indent=2)) return 0 if __name__ == "__main__": raise SystemExit(main())