git_worktree_mode.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. NOT_APPLICABLE_BY_PACKAGE_POLICY = "not_applicable_by_package_policy"
  24. def _tools_dir() -> Path:
  25. return Path(__file__).resolve().parent
  26. def _load_handoff():
  27. tools = _tools_dir()
  28. if str(tools) not in sys.path:
  29. sys.path.insert(0, str(tools))
  30. import package_agent_handoff as handoff # noqa: WPS433
  31. return handoff
  32. def _read_json(path: Path) -> dict[str, Any] | None:
  33. if not path.is_file():
  34. return None
  35. try:
  36. payload = json.loads(path.read_text(encoding="utf-8"))
  37. except (OSError, UnicodeError, json.JSONDecodeError):
  38. return None
  39. return payload if isinstance(payload, dict) else None
  40. def find_meta_git_dir(root: Path) -> Path | None:
  41. """Locate ``meta/git`` under a repo root or extracted CPLD tree."""
  42. candidates = (
  43. root / "meta" / "git",
  44. root / "CPLD" / "meta" / "git",
  45. )
  46. for path in candidates:
  47. if path.is_dir():
  48. return path
  49. return None
  50. def snapshot_present(root: Path) -> bool:
  51. meta_git = find_meta_git_dir(root)
  52. if meta_git is None:
  53. return False
  54. bundle = meta_git / "sanitized-snapshot.bundle"
  55. status = _read_json(meta_git / "sanitized-snapshot-status.json")
  56. if bundle.is_file():
  57. return True
  58. if status and status.get("status") == "pass" and status.get("requested") is True:
  59. return True
  60. return False
  61. def raw_git_marker_present(root: Path) -> bool:
  62. """True when a raw ``.git`` file/directory marker exists (incl. linked worktrees)."""
  63. marker = root / ".git"
  64. try:
  65. return marker.exists()
  66. except OSError:
  67. return False
  68. def live_git_usable(root: Path) -> bool:
  69. """True when git treats ``root`` as an inside-work-tree checkout.
  70. Packager ``resolve_git_dir`` intentionally rejects linked-worktree gitdirs that
  71. point outside the tree (security). Mode detection still treats those as
  72. ``live_git`` so commit-compare tests stay strict on real checkouts.
  73. """
  74. if not raw_git_marker_present(root):
  75. return False
  76. git = shutil.which("git")
  77. if not git:
  78. # Marker present but tool missing: still classify as live_git for policy.
  79. return True
  80. try:
  81. completed = subprocess.run(
  82. [git, "-C", str(root), "rev-parse", "--is-inside-work-tree"],
  83. stdout=subprocess.PIPE,
  84. stderr=subprocess.DEVNULL,
  85. text=True,
  86. check=False,
  87. )
  88. except OSError:
  89. return True
  90. return completed.returncode == 0 and completed.stdout.strip() == "true"
  91. def detect_git_mode(root: Path | None = None) -> str:
  92. """Return ``live_git``, ``snapshot``, or ``detached`` for ``root``."""
  93. override = os.environ.get(ENV_GIT_MODE, "").strip().casefold()
  94. if override:
  95. if override not in GIT_MODES:
  96. raise ValueError(
  97. f"invalid {ENV_GIT_MODE}={override!r}; expected one of "
  98. f"{sorted(GIT_MODES)}"
  99. )
  100. return override
  101. base = (root or Path.cwd()).expanduser().resolve(strict=False)
  102. if live_git_usable(base):
  103. return LIVE_GIT
  104. if snapshot_present(base):
  105. return SNAPSHOT
  106. return DETACHED
  107. def require_live_git(root: Path, testcase: Any | None = None) -> str:
  108. """Assert live_git, or mark detached/snapshot as policy-not-applicable.
  109. Live repository lanes stay strict (commit-compare required). Detached
  110. review-compact lanes must not fake ``.git``; they report
  111. ``not_applicable_by_package_policy`` (exact token — not a vague skip).
  112. """
  113. mode = detect_git_mode(root)
  114. if mode == LIVE_GIT:
  115. return mode
  116. message = NOT_APPLICABLE_BY_PACKAGE_POLICY
  117. if testcase is not None and hasattr(testcase, "skipTest"):
  118. testcase.skipTest(message)
  119. raise RuntimeError(message)
  120. def live_only_status(root: Path | None = None) -> str:
  121. """Return ``pass`` when live_git, else ``not_applicable_by_package_policy``."""
  122. mode = detect_git_mode(root or Path.cwd())
  123. if mode == LIVE_GIT:
  124. return "pass"
  125. return NOT_APPLICABLE_BY_PACKAGE_POLICY
  126. def git_optional_ok(root: Path | None = None) -> bool:
  127. """True when software checks may run without raw ``.git``."""
  128. return detect_git_mode(root) in {SNAPSHOT, DETACHED, LIVE_GIT}
  129. def describe_git_mode(root: Path | None = None) -> dict[str, Any]:
  130. base = (root or Path.cwd()).expanduser().resolve(strict=False)
  131. mode = detect_git_mode(base)
  132. handoff = _load_handoff()
  133. packager_git_dir = handoff.resolve_git_dir(base)
  134. meta_git = find_meta_git_dir(base)
  135. status = _read_json(meta_git / "sanitized-snapshot-status.json") if meta_git else None
  136. return {
  137. "schema": "cpld-git-worktree-mode-v1",
  138. "root": str(base),
  139. "mode": mode,
  140. "raw_git_marker_present": raw_git_marker_present(base),
  141. "packager_resolve_git_dir": str(packager_git_dir) if packager_git_dir else None,
  142. "packager_resolve_rejects_linked_worktree": (
  143. raw_git_marker_present(base) and packager_git_dir is None and mode == LIVE_GIT
  144. ),
  145. "meta_git_dir": str(meta_git) if meta_git is not None else None,
  146. "sanitized_snapshot_present": snapshot_present(base),
  147. "sanitized_snapshot_status": status,
  148. "env_override": os.environ.get(ENV_GIT_MODE) or None,
  149. }
  150. def main(argv: list[str] | None = None) -> int:
  151. import argparse
  152. parser = argparse.ArgumentParser(description=__doc__)
  153. parser.add_argument(
  154. "--root",
  155. type=Path,
  156. default=Path.cwd(),
  157. help="repository or extracted CPLD root",
  158. )
  159. args = parser.parse_args(argv)
  160. print(json.dumps(describe_git_mode(args.root), ensure_ascii=False, indent=2))
  161. return 0
  162. if __name__ == "__main__":
  163. raise SystemExit(main())