manifest_cli.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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. rows: list[tuple[str, str, str, str]] = []
  63. for project in projects:
  64. name = project.get("name", "")
  65. repo_path = project.get("path", "")
  66. checkout = WORKSPACE / repo_path
  67. if not (checkout / ".git").exists():
  68. raise ValueError(f"repository missing: {checkout}")
  69. if git(checkout, "status", "--porcelain"):
  70. raise ValueError(f"repository dirty: {checkout}")
  71. rows.append((name, repo_path, git(checkout, "rev-parse", "HEAD"), project.get("groups", "")))
  72. container_digest = os.environ.get("PRODU2_CONTAINER_DIGEST", "NOT_RECORDED")
  73. td_version = os.environ.get("PRODU2_TD_VERSION", "NOT_RECORDED")
  74. manifest = ET.Element("manifest")
  75. notice = ET.SubElement(manifest, "notice")
  76. notice.text = f"container_digest={container_digest}; td_version={td_version}"
  77. for name, repo_path, revision, groups in rows:
  78. attrs = {"name": name, "path": repo_path, "revision": revision}
  79. if groups:
  80. attrs["groups"] = groups
  81. ET.SubElement(manifest, "project", attrs)
  82. ET.indent(manifest, space=" ")
  83. output.parent.mkdir(parents=True, exist_ok=True)
  84. ET.ElementTree(manifest).write(output, encoding="utf-8", xml_declaration=True)
  85. def verify(path: Path) -> None:
  86. projects = lint(path, snapshot=True)
  87. for project in projects:
  88. checkout = WORKSPACE / project.get("path", "")
  89. expected = project.get("revision", "")
  90. actual = git(checkout, "rev-parse", "HEAD")
  91. if actual != expected:
  92. raise ValueError(f"commit mismatch {project.get('name')}: {actual} != {expected}")
  93. if git(checkout, "status", "--porcelain"):
  94. raise ValueError(f"repository dirty: {checkout}")
  95. def main() -> int:
  96. parser = argparse.ArgumentParser()
  97. sub = parser.add_subparsers(dest="command", required=True)
  98. for command in ("lint", "list", "verify"):
  99. item = sub.add_parser(command)
  100. item.add_argument("manifest", type=Path)
  101. create = sub.add_parser("create")
  102. create.add_argument("manifest", type=Path)
  103. create.add_argument("output", type=Path)
  104. args = parser.parse_args()
  105. if args.command == "lint":
  106. projects = lint(args.manifest)
  107. print(f"PASS: {len(projects)} unique projects")
  108. elif args.command == "list":
  109. for project in lint(args.manifest):
  110. print(f"{project.get('path')}\t{project.get('revision', '<default>')}")
  111. elif args.command == "create":
  112. create_snapshot(args.manifest, args.output)
  113. print(args.output)
  114. else:
  115. verify(args.manifest)
  116. print(f"PASS: {args.manifest}")
  117. return 0
  118. if __name__ == "__main__":
  119. try:
  120. sys.exit(main())
  121. except (OSError, ValueError, ET.ParseError, subprocess.CalledProcessError) as exc:
  122. print(f"ERROR: {exc}", file=sys.stderr)
  123. sys.exit(2)