#!/usr/bin/env python3 import argparse import base64 import io import os import re import subprocess import sys import tarfile import tempfile from pathlib import Path GITLAB = "https://gitlab.sarex.io" PLATFORM_REPO = "infra/terraform-platform" MODULES_GROUP = "infra/terraform-modules" SHARED_FILES = (".gitea/workflows/contract.yml", "scripts/load_admin_creds.sh") class SliceError(Exception): pass def list_contours(repo: Path) -> list[str]: return sorted(p.parent.name for p in repo.glob("live-contract/*/env.hcl")) def code_ref(repo: Path, contour: str) -> str: text = (repo / "live-contract" / contour / "env.hcl").read_text() m = re.search(r'code_ref\s*=\s*"([^"]+)"', text) if not m: raise SliceError(f"no code_ref in live-contract/{contour}/env.hcl") return m.group(1) def module_versions(platform_dir: Path) -> dict[str, str]: text = (platform_dir / "versions.hcl").read_text() block = re.search(r"module_versions\s*=\s*\{(.*?)\n\s*\}", text, re.S) if not block: raise SliceError("no module_versions in terraform-platform versions.hcl") return dict(re.findall(r'^\s*([a-z0-9-]+)\s*=\s*"([^"]+)"', block.group(1), re.M)) def infrastructure_yaml(contour: str, env_block: str = "") -> str: body = "".join(f" {line}\n" if line else "\n" for line in env_block.splitlines()) if env_block.strip() else "" return f"current_environment: {contour}\nenvironments:\n {contour}:" + ("\n" + body if body else " {}\n") def git_env(token: str | None) -> dict: env = {**os.environ, "GIT_TERMINAL_PROMPT": "0"} if token: basic = base64.b64encode(f"gitlab-ci-token:{token}".encode()).decode() env.update({"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "http.extraHeader", "GIT_CONFIG_VALUE_0": f"Authorization: Basic {basic}"}) return env def fetch_tree(source: str, ref: str, dest: Path, token: str | None) -> dict[str, bytes]: r = subprocess.run(["git", "clone", "--quiet", "--depth", "1", "--branch", ref, source, str(dest)], capture_output=True, text=True, env=git_env(token)) if r.returncode != 0: raise SliceError(f"git clone {source.split('@')[-1]}@{ref}: {r.stderr.strip()}") files = subprocess.run(["git", "-C", str(dest), "ls-files", "-z"], capture_output=True, check=True).stdout.split(b"\0") return {f.decode(): (dest / f.decode()).read_bytes() for f in files if f} def tracked(repo: Path, paths: list[str]) -> dict[str, bytes]: out = subprocess.run(["git", "-C", str(repo), "ls-files", "-z", "--", *paths], capture_output=True, check=True).stdout.split(b"\0") return {f.decode(): (repo / f.decode()).read_bytes() for f in out if f} def collect(repo: Path, contour: str, source_base: str, token: str | None) -> tuple[dict[str, bytes], dict[str, str]]: files = tracked(repo, [f"live-contract/{contour}", f"environments/{contour}", *SHARED_FILES]) missing = [p for p in SHARED_FILES if p not in files] if missing: raise SliceError(f"missing {', '.join(missing)}") if not any(p.startswith(f"environments/{contour}/") for p in files): raise SliceError(f"no environments/{contour}") env_block = files.pop(f"environments/{contour}/infrastructure.yaml", b"").decode() files["infrastructure.yaml"] = infrastructure_yaml(contour, env_block).encode() ref = code_ref(repo, contour) pins = {"terraform-platform": ref} with tempfile.TemporaryDirectory() as tmp: platform = Path(tmp) / "platform" for path, data in fetch_tree(f"{source_base}/{PLATFORM_REPO}.git", ref, platform, token).items(): files[f"vendor/terraform-platform/{path}"] = data for name, version in sorted(module_versions(platform).items()): for path, data in fetch_tree(f"{source_base}/{MODULES_GROUP}/{name}.git", version, Path(tmp) / name, token).items(): if path.startswith("tests/"): continue files[f"vendor/modules/{name}/{path}"] = data pins[name] = version return files, pins def write_tar(files: dict[str, bytes], out: Path) -> None: buf = io.BytesIO() with tarfile.open(fileobj=buf, mode="w", format=tarfile.PAX_FORMAT) as tar: for name in sorted(files): info = tarfile.TarInfo(name) info.size = len(files[name]) info.mode = 0o755 if name.endswith(".sh") else 0o644 info.mtime = 0 info.uid = info.gid = 0 info.uname = info.gname = "" tar.addfile(info, io.BytesIO(files[name])) out.write_bytes(buf.getvalue()) def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("contour") ap.add_argument("--repo", default=".") ap.add_argument("--out", required=True) ap.add_argument("--source-base", default=GITLAB, help="base URL or local directory holding infra/terraform-platform and infra/terraform-modules") args = ap.parse_args() try: files, pins = collect(Path(args.repo).resolve(), args.contour, args.source_base, os.environ.get("CI_JOB_TOKEN")) write_tar(files, Path(args.out)) except SliceError as e: print(f"slice {args.contour}: {e}", file=sys.stderr) return 1 print(f"slice {args.contour}: {len(files)} files, " + ", ".join(f"{k} {v}" for k, v in pins.items())) return 0 if __name__ == "__main__": sys.exit(main())