manifest_cli.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. #!/usr/bin/env python3
  2. """Lint, list, create, and verify Repo-style XML manifests."""
  3. from __future__ import annotations
  4. import argparse
  5. import os
  6. from pathlib import Path
  7. import re
  8. import subprocess
  9. import sys
  10. import xml.etree.ElementTree as ET
  11. ROOT = Path(__file__).resolve().parents[1]
  12. WORKSPACE = ROOT.parent
  13. FULL_SHA = re.compile(r"[0-9a-f]{40}")
  14. def git(path: Path, *args: str) -> str:
  15. return subprocess.run(
  16. ["git", "-C", str(path), *args],
  17. check=True,
  18. text=True,
  19. stdout=subprocess.PIPE,
  20. stderr=subprocess.PIPE,
  21. ).stdout.strip()
  22. def load(path: Path, seen: set[Path] | None = None) -> tuple[ET.Element, list[ET.Element]]:
  23. path = path.resolve()
  24. seen = set() if seen is None else seen
  25. if path in seen:
  26. raise ValueError(f"include cycle: {path}")
  27. seen.add(path)
  28. root = ET.parse(path).getroot()
  29. if root.tag != "manifest":
  30. raise ValueError(f"root must be manifest: {path}")
  31. projects = list(root.findall("project"))
  32. for include in root.findall("include"):
  33. name = include.get("name")
  34. if not name:
  35. raise ValueError(f"include missing name: {path}")
  36. _, children = load((path.parent / name).resolve(), seen)
  37. projects.extend(children)
  38. return root, projects
  39. def lint(path: Path, snapshot: bool = False) -> list[ET.Element]:
  40. root, projects = load(path)
  41. names: set[str] = set()
  42. paths: set[str] = set()
  43. default = root.find("default")
  44. default_revision = default.get("revision") if default is not None else None
  45. for project in projects:
  46. name = project.get("name")
  47. repo_path = project.get("path")
  48. revision = project.get("revision") or default_revision
  49. if not name or not repo_path:
  50. raise ValueError("each project requires name and path")
  51. if name in names or repo_path in paths:
  52. raise ValueError(f"duplicate project name/path: {name} {repo_path}")
  53. names.add(name)
  54. paths.add(repo_path)
  55. if snapshot and (revision is None or FULL_SHA.fullmatch(revision) is None):
  56. raise ValueError(f"snapshot revision is not full SHA: {name}={revision}")
  57. if not projects:
  58. raise ValueError("manifest has no projects")
  59. return projects
  60. def create_snapshot(source: Path, output: Path) -> None:
  61. projects = lint(source)
  62. output = output.resolve()
  63. checkouts = [(project, (WORKSPACE / project.get("path", "")).resolve()) for project in projects]
  64. for project, checkout in checkouts:
  65. if output.is_relative_to(checkout):
  66. raise ValueError(
  67. "snapshot output must be outside every snapshotted repository: "
  68. f"{project.get('name')} contains {output}"
  69. )
  70. rows: list[tuple[str, str, str, str]] = []
  71. for project, checkout in checkouts:
  72. name = project.get("name", "")
  73. repo_path = project.get("path", "")
  74. if not (checkout / ".git").exists():
  75. raise ValueError(f"repository missing: {checkout}")
  76. if git(checkout, "status", "--porcelain"):
  77. raise ValueError(f"repository dirty: {checkout}")
  78. rows.append((name, repo_path, git(checkout, "rev-parse", "HEAD"), project.get("groups", "")))
  79. container_digest = os.environ.get("PRODU2_CONTAINER_DIGEST", "NOT_RECORDED")
  80. td_version = os.environ.get("PRODU2_TD_VERSION", "NOT_RECORDED")
  81. manifest = ET.Element("manifest")
  82. notice = ET.SubElement(manifest, "notice")
  83. notice.text = f"container_digest={container_digest}; td_version={td_version}"
  84. for name, repo_path, revision, groups in rows:
  85. attrs = {"name": name, "path": repo_path, "revision": revision}
  86. if groups:
  87. attrs["groups"] = groups
  88. ET.SubElement(manifest, "project", attrs)
  89. ET.indent(manifest, space=" ")
  90. output.parent.mkdir(parents=True, exist_ok=True)
  91. ET.ElementTree(manifest).write(output, encoding="utf-8", xml_declaration=True)
  92. def verify(path: Path) -> None:
  93. projects = lint(path, snapshot=True)
  94. for project in projects:
  95. checkout = WORKSPACE / project.get("path", "")
  96. expected = project.get("revision", "")
  97. actual = git(checkout, "rev-parse", "HEAD")
  98. if actual != expected:
  99. raise ValueError(f"commit mismatch {project.get('name')}: {actual} != {expected}")
  100. if git(checkout, "status", "--porcelain"):
  101. raise ValueError(f"repository dirty: {checkout}")
  102. def main() -> int:
  103. parser = argparse.ArgumentParser()
  104. sub = parser.add_subparsers(dest="command", required=True)
  105. for command in ("lint", "list", "verify"):
  106. item = sub.add_parser(command)
  107. item.add_argument("manifest", type=Path)
  108. create = sub.add_parser("create")
  109. create.add_argument("manifest", type=Path)
  110. create.add_argument("output", type=Path)
  111. args = parser.parse_args()
  112. if args.command == "lint":
  113. projects = lint(args.manifest)
  114. print(f"PASS: {len(projects)} unique projects")
  115. elif args.command == "list":
  116. for project in lint(args.manifest):
  117. print(f"{project.get('path')}\t{project.get('revision', '<default>')}")
  118. elif args.command == "create":
  119. create_snapshot(args.manifest, args.output)
  120. print(args.output)
  121. else:
  122. verify(args.manifest)
  123. print(f"PASS: {args.manifest}")
  124. return 0
  125. if __name__ == "__main__":
  126. try:
  127. sys.exit(main())
  128. except (OSError, ValueError, ET.ParseError, subprocess.CalledProcessError) as exc:
  129. print(f"ERROR: {exc}", file=sys.stderr)
  130. sys.exit(2)