git_worktree_mode.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. #!/usr/bin/env python3
  2. """Detect live_git vs snapshot vs detached review modes.
  3. Compact packages do not ship raw ``.git``. Tests and replay entrypoints must
  4. distinguish:
  5. - ``live_git``: resolvable raw ``.git`` (strict commit-compare paths OK)
  6. - ``snapshot``: sanitized synthetic single-commit snapshot present (no raw ``.git``)
  7. - ``detached``: extracted package / copy without raw ``.git`` or snapshot
  8. Override with ``PRODU2_GIT_MODE`` when intentionally forcing a mode.
  9. """
  10. from __future__ import annotations
  11. import json
  12. import os
  13. import shutil
  14. import subprocess
  15. import sys
  16. from pathlib import Path
  17. from typing import Any
  18. LIVE_GIT = "live_git"
  19. SNAPSHOT = "snapshot"
  20. DETACHED = "detached"
  21. GIT_MODES = frozenset({LIVE_GIT, SNAPSHOT, DETACHED})
  22. ENV_GIT_MODE = "PRODU2_GIT_MODE"
  23. def _tools_dir() -> Path:
  24. return Path(__file__).resolve().parent
  25. def _load_handoff():
  26. tools = _tools_dir()
  27. if str(tools) not in sys.path:
  28. sys.path.insert(0, str(tools))
  29. import package_agent_handoff as handoff # noqa: WPS433
  30. return handoff
  31. def _read_json(path: Path) -> dict[str, Any] | None:
  32. if not path.is_file():
  33. return None
  34. try:
  35. payload = json.loads(path.read_text(encoding="utf-8"))
  36. except (OSError, UnicodeError, json.JSONDecodeError):
  37. return None
  38. return payload if isinstance(payload, dict) else None
  39. def find_meta_git_dir(root: Path) -> Path | None:
  40. """Locate ``meta/git`` under a repo root or extracted CPLD tree."""
  41. candidates = (
  42. root / "meta" / "git",
  43. root / "CPLD" / "meta" / "git",
  44. )
  45. for path in candidates:
  46. if path.is_dir():
  47. return path
  48. return None
  49. def snapshot_present(root: Path) -> bool:
  50. meta_git = find_meta_git_dir(root)
  51. if meta_git is None:
  52. return False
  53. bundle = meta_git / "sanitized-snapshot.bundle"
  54. status = _read_json(meta_git / "sanitized-snapshot-status.json")
  55. if bundle.is_file():
  56. return True
  57. if status and status.get("status") == "pass" and status.get("requested") is True:
  58. return True
  59. return False
  60. def raw_git_marker_present(root: Path) -> bool:
  61. """True when a raw ``.git`` file/directory marker exists (incl. linked worktrees)."""
  62. marker = root / ".git"
  63. try:
  64. return marker.exists()
  65. except OSError:
  66. return False
  67. def live_git_usable(root: Path) -> bool:
  68. """True when git treats ``root`` as an inside-work-tree checkout.
  69. Packager ``resolve_git_dir`` intentionally rejects linked-worktree gitdirs that
  70. point outside the tree (security). Mode detection still treats those as
  71. ``live_git`` so commit-compare tests stay strict on real checkouts.
  72. """
  73. if not raw_git_marker_present(root):
  74. return False
  75. git = shutil.which("git")
  76. if not git:
  77. # Marker present but tool missing: still classify as live_git for policy.
  78. return True
  79. try:
  80. completed = subprocess.run(
  81. [git, "-C", str(root), "rev-parse", "--is-inside-work-tree"],
  82. stdout=subprocess.PIPE,
  83. stderr=subprocess.DEVNULL,
  84. text=True,
  85. check=False,
  86. )
  87. except OSError:
  88. return True
  89. return completed.returncode == 0 and completed.stdout.strip() == "true"
  90. def detect_git_mode(root: Path | None = None) -> str:
  91. """Return ``live_git``, ``snapshot``, or ``detached`` for ``root``."""
  92. override = os.environ.get(ENV_GIT_MODE, "").strip().casefold()
  93. if override:
  94. if override not in GIT_MODES:
  95. raise ValueError(
  96. f"invalid {ENV_GIT_MODE}={override!r}; expected one of "
  97. f"{sorted(GIT_MODES)}"
  98. )
  99. return override
  100. base = (root or Path.cwd()).expanduser().resolve(strict=False)
  101. if live_git_usable(base):
  102. return LIVE_GIT
  103. if snapshot_present(base):
  104. return SNAPSHOT
  105. return DETACHED
  106. def require_live_git(root: Path, testcase: Any | None = None) -> str:
  107. """Assert or skip unless ``root`` is in ``live_git`` mode.
  108. When ``testcase`` is a unittest.TestCase, skips instead of raising so
  109. compact/detached replay hosts stay green. Live worktrees remain strict.
  110. """
  111. mode = detect_git_mode(root)
  112. if mode == LIVE_GIT:
  113. return mode
  114. message = (
  115. f"requires live_git (raw .git); current mode={mode} under {root}. "
  116. "Compact/detached packages are Git-optional by policy."
  117. )
  118. if testcase is not None and hasattr(testcase, "skipTest"):
  119. testcase.skipTest(message)
  120. raise RuntimeError(message)
  121. def git_optional_ok(root: Path | None = None) -> bool:
  122. """True when software checks may run without raw ``.git``."""
  123. return detect_git_mode(root) in {SNAPSHOT, DETACHED, LIVE_GIT}
  124. def describe_git_mode(root: Path | None = None) -> dict[str, Any]:
  125. base = (root or Path.cwd()).expanduser().resolve(strict=False)
  126. mode = detect_git_mode(base)
  127. handoff = _load_handoff()
  128. packager_git_dir = handoff.resolve_git_dir(base)
  129. meta_git = find_meta_git_dir(base)
  130. status = _read_json(meta_git / "sanitized-snapshot-status.json") if meta_git else None
  131. return {
  132. "schema": "cpld-git-worktree-mode-v1",
  133. "root": str(base),
  134. "mode": mode,
  135. "raw_git_marker_present": raw_git_marker_present(base),
  136. "packager_resolve_git_dir": str(packager_git_dir) if packager_git_dir else None,
  137. "packager_resolve_rejects_linked_worktree": (
  138. raw_git_marker_present(base) and packager_git_dir is None and mode == LIVE_GIT
  139. ),
  140. "meta_git_dir": str(meta_git) if meta_git is not None else None,
  141. "sanitized_snapshot_present": snapshot_present(base),
  142. "sanitized_snapshot_status": status,
  143. "env_override": os.environ.get(ENV_GIT_MODE) or None,
  144. }
  145. def main(argv: list[str] | None = None) -> int:
  146. import argparse
  147. parser = argparse.ArgumentParser(description=__doc__)
  148. parser.add_argument(
  149. "--root",
  150. type=Path,
  151. default=Path.cwd(),
  152. help="repository or extracted CPLD root",
  153. )
  154. args = parser.parse_args(argv)
  155. print(json.dumps(describe_git_mode(args.root), ensure_ascii=False, indent=2))
  156. return 0
  157. if __name__ == "__main__":
  158. raise SystemExit(main())