"""Reconstruct declared source bases and verify exact Git identities.""" import hashlib import json import os from pathlib import Path, PurePosixPath import re import subprocess import tempfile from common import ROOT, contained, sha256 def object_id(kind, content): return hashlib.sha1(kind.encode() + b" " + str(len(content)).encode() + b"\0" + content).hexdigest() def relative_path(value): path = PurePosixPath(value) if path.is_absolute() or not path.parts or ".." in path.parts or ".git" in path.parts: raise ValueError(f"Unsafe source transformation path: {value}") return str(path) def construct(repo, cache, recipe_path): recipe = json.loads(Path(recipe_path).read_text()) if recipe["schema_version"] != 1 or recipe["kind"] != "git-tree-transform-v1": raise ValueError("Unsupported source construction recipe") if recipe["expected_commit"] != repo["base_commit"]: raise ValueError("Construction recipe changes the task source identity") revision = recipe["upstream_base_commit"] if not re.fullmatch(r"[0-9a-f]{40}", revision): raise ValueError("Invalid upstream construction revision") task_root = Path(recipe_path).resolve().parents[2] ref = recipe["commit_object"] commit_path = contained(task_root, ref["path"]) if sha256(commit_path) != ref["sha256"]: raise ValueError("Synthetic commit metadata changed") commit = commit_path.read_bytes() if object_id("commit", commit) != repo["base_commit"]: raise ValueError("Synthetic commit object does not match the declared base") header = commit.split(b"\n\n", 1)[0].splitlines() parents = [line[7:].decode() for line in header if line.startswith(b"parent ")] declared_parents = recipe.get("parents", []) if declared_parents not in ([], [revision]) or parents != declared_parents: raise ValueError("Construction commit parents must exactly match the declared upstream base or empty root") if [line for line in header if line.startswith(b"tree ")] != [b"tree " + recipe["expected_tree"].encode()]: raise ValueError("Construction commit does not declare its exact expected tree") exists = subprocess.run(["git", "-C", str(cache), "cat-file", "-e", revision + "^{commit}"], stderr=subprocess.DEVNULL).returncode == 0 if not exists: subprocess.run(["git", "-C", str(cache), "fetch", "--depth=1", "--no-tags", repo["url"], revision], check=True) with tempfile.TemporaryDirectory(prefix="crossswe-source-index-") as temporary: environment = dict(os.environ, GIT_INDEX_FILE=str(Path(temporary) / "index"), GIT_WORK_TREE=temporary) def git(*args, content=None): return subprocess.check_output(["git", "-C", str(cache), *args], env=environment, input=content) git("read-tree", revision + "^{tree}") for operation in recipe["operations"]: if operation["kind"] in ("remove_tree", "add_symlink", "set_mode"): name = relative_path(operation["path"]) if operation["kind"] == "remove_tree": names = git("ls-files", "-z").split(b"\0") prefix = os.fsencode(name) remove = [item for item in names if item == prefix or item.startswith(prefix + b"/")] if not remove: raise ValueError(f"Source removal did not match upstream files: {name}") git("update-index", "--force-remove", "-z", "--stdin", content=b"\0".join(remove) + b"\0") elif operation["kind"] == "add_symlink": target = operation["target"].encode() oid = git("hash-object", "-w", "--stdin", content=target).decode().strip() if oid != operation["expected_blob"]: raise ValueError("Declared source symlink object changed") git("update-index", "--add", "--cacheinfo", "120000", oid, name) elif operation["kind"] == "set_mode": if operation["from_mode"] not in ("100644", "100755") or operation["to_mode"] not in ("100644", "100755"): raise ValueError("Source mode normalization requires regular file modes") entries = git("ls-files", "--stage", "-z", "--", name).split(b"\0") expected = (operation["from_mode"] + " " + operation["expected_blob"] + " 0\t" + name).encode() if entries != [expected, b""]: raise ValueError("Source mode normalization differs from its declared file") git("update-index", "--cacheinfo", operation["to_mode"], operation["expected_blob"], name) elif operation["kind"] == "reverse_patch": patch = contained(task_root, operation["patch"]["path"]) if sha256(patch) != operation["patch"]["sha256"]: raise ValueError("Source construction patch changed") git("apply", "--cached", "--reverse", "--check", str(patch)) git("apply", "--cached", "--reverse", str(patch)) else: raise ValueError("Unknown source tree operation") tree = git("write-tree").decode().strip() if tree != recipe["expected_tree"]: raise ValueError(f"Constructed source tree differs: {tree}") actual = git("hash-object", "-t", "commit", "-w", "--stdin", content=commit).decode().strip() if actual != repo["base_commit"]: raise ValueError("Constructed source commit differs") git("update-ref", "refs/crossswe/base/" + actual, actual) return actual