| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148 |
- #!/usr/bin/env python3
- """Lint, list, create, and verify Repo-style XML manifests."""
- from __future__ import annotations
- import argparse
- import os
- from pathlib import Path
- import re
- import subprocess
- import sys
- import xml.etree.ElementTree as ET
- ROOT = Path(__file__).resolve().parents[1]
- WORKSPACE = ROOT.parent
- FULL_SHA = re.compile(r"[0-9a-f]{40}")
- def git(path: Path, *args: str) -> str:
- return subprocess.run(
- ["git", "-C", str(path), *args],
- check=True,
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- ).stdout.strip()
- def load(path: Path, seen: set[Path] | None = None) -> tuple[ET.Element, list[ET.Element]]:
- path = path.resolve()
- seen = set() if seen is None else seen
- if path in seen:
- raise ValueError(f"include cycle: {path}")
- seen.add(path)
- root = ET.parse(path).getroot()
- if root.tag != "manifest":
- raise ValueError(f"root must be manifest: {path}")
- projects = list(root.findall("project"))
- for include in root.findall("include"):
- name = include.get("name")
- if not name:
- raise ValueError(f"include missing name: {path}")
- _, children = load((path.parent / name).resolve(), seen)
- projects.extend(children)
- return root, projects
- def lint(path: Path, snapshot: bool = False) -> list[ET.Element]:
- root, projects = load(path)
- names: set[str] = set()
- paths: set[str] = set()
- default = root.find("default")
- default_revision = default.get("revision") if default is not None else None
- for project in projects:
- name = project.get("name")
- repo_path = project.get("path")
- revision = project.get("revision") or default_revision
- if not name or not repo_path:
- raise ValueError("each project requires name and path")
- if name in names or repo_path in paths:
- raise ValueError(f"duplicate project name/path: {name} {repo_path}")
- names.add(name)
- paths.add(repo_path)
- if snapshot and (revision is None or FULL_SHA.fullmatch(revision) is None):
- raise ValueError(f"snapshot revision is not full SHA: {name}={revision}")
- if not projects:
- raise ValueError("manifest has no projects")
- return projects
- def create_snapshot(source: Path, output: Path) -> None:
- projects = lint(source)
- output = output.resolve()
- checkouts = [(project, (WORKSPACE / project.get("path", "")).resolve()) for project in projects]
- for project, checkout in checkouts:
- if output.is_relative_to(checkout):
- raise ValueError(
- "snapshot output must be outside every snapshotted repository: "
- f"{project.get('name')} contains {output}"
- )
- rows: list[tuple[str, str, str, str]] = []
- for project, checkout in checkouts:
- name = project.get("name", "")
- repo_path = project.get("path", "")
- if not (checkout / ".git").exists():
- raise ValueError(f"repository missing: {checkout}")
- if git(checkout, "status", "--porcelain"):
- raise ValueError(f"repository dirty: {checkout}")
- rows.append((name, repo_path, git(checkout, "rev-parse", "HEAD"), project.get("groups", "")))
- container_digest = os.environ.get("PRODU2_CONTAINER_DIGEST", "NOT_RECORDED")
- td_version = os.environ.get("PRODU2_TD_VERSION", "NOT_RECORDED")
- manifest = ET.Element("manifest")
- notice = ET.SubElement(manifest, "notice")
- notice.text = f"container_digest={container_digest}; td_version={td_version}"
- for name, repo_path, revision, groups in rows:
- attrs = {"name": name, "path": repo_path, "revision": revision}
- if groups:
- attrs["groups"] = groups
- ET.SubElement(manifest, "project", attrs)
- ET.indent(manifest, space=" ")
- output.parent.mkdir(parents=True, exist_ok=True)
- ET.ElementTree(manifest).write(output, encoding="utf-8", xml_declaration=True)
- def verify(path: Path) -> None:
- projects = lint(path, snapshot=True)
- for project in projects:
- checkout = WORKSPACE / project.get("path", "")
- expected = project.get("revision", "")
- actual = git(checkout, "rev-parse", "HEAD")
- if actual != expected:
- raise ValueError(f"commit mismatch {project.get('name')}: {actual} != {expected}")
- if git(checkout, "status", "--porcelain"):
- raise ValueError(f"repository dirty: {checkout}")
- def main() -> int:
- parser = argparse.ArgumentParser()
- sub = parser.add_subparsers(dest="command", required=True)
- for command in ("lint", "list", "verify"):
- item = sub.add_parser(command)
- item.add_argument("manifest", type=Path)
- create = sub.add_parser("create")
- create.add_argument("manifest", type=Path)
- create.add_argument("output", type=Path)
- args = parser.parse_args()
- if args.command == "lint":
- projects = lint(args.manifest)
- print(f"PASS: {len(projects)} unique projects")
- elif args.command == "list":
- for project in lint(args.manifest):
- print(f"{project.get('path')}\t{project.get('revision', '<default>')}")
- elif args.command == "create":
- create_snapshot(args.manifest, args.output)
- print(args.output)
- else:
- verify(args.manifest)
- print(f"PASS: {args.manifest}")
- return 0
- if __name__ == "__main__":
- try:
- sys.exit(main())
- except (OSError, ValueError, ET.ParseError, subprocess.CalledProcessError) as exc:
- print(f"ERROR: {exc}", file=sys.stderr)
- sys.exit(2)
|