#!/usr/bin/env python3 """Resolve component main branches and write the canonical release lock.""" from __future__ import annotations import argparse import hashlib import json import re import subprocess import sys from pathlib import Path from typing import Any SEMVER_RE = re.compile( r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$" ) PROJECT_RE = re.compile( r"\bproject\s*\(\s*Echoion\s+VERSION\s+" r"([0-9]+\.[0-9]+\.[0-9]+)\b", re.IGNORECASE | re.MULTILINE, ) class ReleaseError(RuntimeError): """Release preparation validation failed.""" def command(*args: str, cwd: Path | None = None) -> str: try: return subprocess.check_output( args, cwd=cwd, text=True, stderr=subprocess.STDOUT, ).strip() except (OSError, subprocess.CalledProcessError) as error: detail = getattr(error, "output", "") or str(error) raise ReleaseError( f"command failed: {' '.join(args)}: {detail.strip()}" ) from error def remote_tag_commit(tag_output: str, tag: str) -> str | None: if not tag_output: return None direct_ref = f"refs/tags/{tag}" peeled_ref = f"{direct_ref}^{{}}" revisions: dict[str, str] = {} for line in tag_output.splitlines(): fields = line.split() if len(fields) != 2: raise ReleaseError(f"invalid ls-remote output for tag {tag}") revision, reference = fields if reference in (direct_ref, peeled_ref): revisions[reference] = revision if peeled_ref in revisions: return revisions[peeled_ref] if direct_ref in revisions: return revisions[direct_ref] raise ReleaseError(f"ls-remote did not return the requested tag {tag}") def root_product_version(cmake_text: str) -> str: matches = PROJECT_RE.findall(cmake_text) if len(matches) != 1: raise ReleaseError( "root CMakeLists.txt must contain exactly one " "project(Echoion VERSION x.y.z)" ) version = matches[0] if not SEMVER_RE.fullmatch(version): raise ReleaseError(f"root product version is not stable SemVer: {version}") return version def canonical_json(value: Any) -> bytes: return ( json.dumps( value, ensure_ascii=False, separators=(",", ":"), sort_keys=True, ) + "\n" ).encode() def contract_hash(value: Any) -> str: return "sha256:" + hashlib.sha256(canonical_json(value)).hexdigest() def compatible_append(old: Any, new: Any) -> bool: if isinstance(old, dict) and isinstance(new, dict): return all( key in new and compatible_append(value, new[key]) for key, value in old.items() ) if isinstance(old, list) and isinstance(new, list): return len(new) >= len(old) and all( compatible_append(value, new[index]) for index, value in enumerate(old) ) return type(old) is type(new) and old == new def classify_contract(old: Any, new: Any) -> str: if canonical_json(old) == canonical_json(new): return "identical" if compatible_append(old, new): return "compatible" return "breaking" def bump_version(version: str, change: str) -> str: match = SEMVER_RE.fullmatch(version) if not match: raise ReleaseError(f"invalid prior component version: {version}") major, minor, patch = map(int, match.groups()) if change == "breaking": return f"{major + 1}.0.0" if change == "compatible": return f"{major}.{minor + 1}.0" if change == "implementation": return f"{major}.{minor}.{patch + 1}" raise ReleaseError(f"unsupported version change: {change}") def read_contract(repo: Path, revision: str, relative_path: str) -> Any: raw = command("git", "show", f"{revision}:{relative_path}", cwd=repo) try: return json.loads(raw) except json.JSONDecodeError as error: raise ReleaseError( f"{repo.name}:{relative_path} is not valid JSON at {revision}" ) from error def derive_component_version( previous: dict[str, Any] | None, revision: str, current_contract: Any | None, previous_contract: Any | None, ) -> str: if previous is None: return "2.0.0" previous_version = previous["componentVersion"] if previous["revision"] == revision: return previous_version if current_contract is None: return bump_version(previous_version, "implementation") classification = classify_contract(previous_contract, current_contract) if classification == "identical": classification = "implementation" return bump_version(previous_version, classification) def normalize_remote(url: str) -> str: return url.removesuffix("/").removesuffix(".git").lower() def resolve_component( component_id: str, definition: dict[str, Any], previous: dict[str, Any] | None, workspace: Path, product_version: str, initial_modular_release: bool, ) -> dict[str, Any]: repository = definition["repository"] url = definition["url"] branch = definition.get("branch", "main") repo = workspace / component_id if not (repo / ".git").is_dir(): raise ReleaseError( f"component repository is missing: {repo}; " "run scripts/sync-components.py first" ) if command("git", "status", "--porcelain", cwd=repo): raise ReleaseError(f"refusing dirty component repository: {repo}") origin = command("git", "remote", "get-url", "origin", cwd=repo) if normalize_remote(origin) != normalize_remote(url): raise ReleaseError( f"{component_id} origin mismatch: expected {url}, found {origin}" ) remote_line = command("git", "ls-remote", url, f"refs/heads/{branch}") fields = remote_line.split() if len(fields) != 2: raise ReleaseError( f"{component_id} has no accessible {branch} branch at {url}" ) revision = fields[0] command("git", "fetch", "--quiet", "origin", branch, cwd=repo) command("git", "cat-file", "-e", f"{revision}^{{commit}}", cwd=repo) head = command("git", "rev-parse", "HEAD", cwd=repo) if head != revision: merge_base = command("git", "merge-base", "HEAD", revision, cwd=repo) relation = "behind" if merge_base == head else "non-fast-forward" raise ReleaseError( f"{component_id} local HEAD is {relation}; " f"expected current {branch} {revision}, found {head}" ) tree = command("git", "rev-parse", f"{revision}^{{tree}}", cwd=repo) contract_path = definition.get("abiContract") current_contract = ( read_contract(repo, revision, contract_path) if contract_path is not None else None ) previous_contract = None if ( current_contract is not None and previous is not None and previous.get("revision") ): try: previous_contract = read_contract( repo, previous["revision"], contract_path ) except ReleaseError: previous_contract = {} version = ( "2.0.0" if initial_modular_release else derive_component_version( previous, revision, current_contract, previous_contract, ) ) expected_tag = f"v{version}" tag_output = command( "git", "ls-remote", "--tags", url, f"refs/tags/{expected_tag}", f"refs/tags/{expected_tag}^{{}}", ) tag_revision = remote_tag_commit(tag_output, expected_tag) if tag_revision is not None: if tag_revision != revision: raise ReleaseError( f"{component_id} tag {expected_tag} points at " f"{tag_revision}, not {revision}" ) abi_hash = ( contract_hash(current_contract) if current_contract is not None else None ) package_id = definition["packageId"] return { "repository": repository, "revision": revision, "componentVersion": version, "abiHash": abi_hash, "sourceTreeHash": f"git-sha1:{tree}", "artifactIdentity": ( f"{package_id}-{version}-linux-x86_64" ), } def prepare(root: Path, workspace: Path, check: bool) -> dict[str, Any]: version = root_product_version((root / "CMakeLists.txt").read_text()) registry_path = root / "components.json" lock_path = root / "components.lock.json" registry = json.loads(registry_path.read_text()) previous_lock = json.loads(lock_path.read_text()) if lock_path.exists() else {} if registry.get("schemaVersion") != 1: raise ReleaseError("unsupported components.json schema") if previous_lock and previous_lock.get("schemaVersion") != 2: raise ReleaseError("unsupported components.lock.json schema") previous_product_version = previous_lock.get("productVersion") if previous_product_version is None and version != "2.0.0": raise ReleaseError( "the first modular release must use root product version 2.0.0" ) initial_modular_release = ( version == "2.0.0" and previous_product_version in (None, "2.0.0") ) previous_components = previous_lock.get("components", {}) components = { component_id: resolve_component( component_id, definition, previous_components.get(component_id), workspace, version, initial_modular_release, ) for component_id, definition in registry["components"].items() } result = { "schemaVersion": 2, "productVersion": version, "components": components, } rendered = json.dumps(result, indent=2, ensure_ascii=False) + "\n" if check: if not lock_path.exists() or lock_path.read_text() != rendered: raise ReleaseError("components.lock.json is not canonical or current") else: temporary = lock_path.with_suffix(".json.tmp") temporary.write_text(rendered) temporary.replace(lock_path) return result def main() -> int: parser = argparse.ArgumentParser() parser.add_argument( "--workspace", type=Path, help="directory containing permanent component repositories", ) parser.add_argument( "--check", action="store_true", help="validate that components.lock.json is already current", ) args = parser.parse_args() root = Path(__file__).resolve().parents[1] workspace = (args.workspace or root.parent).resolve() try: result = prepare(root, workspace, args.check) except ReleaseError as error: print(f"prepare-release: {error}", file=sys.stderr) return 1 print( f"prepared Echoion {result['productVersion']} with " f"{len(result['components'])} locked components" ) return 0 if __name__ == "__main__": raise SystemExit(main())