diff --git a/ci/pr_attestation.py b/ci/pr_attestation.py index ebf977d5fe..6cdb591262 100644 --- a/ci/pr_attestation.py +++ b/ci/pr_attestation.py @@ -181,13 +181,14 @@ def show(self, rev, path): return self.run("show", f"{rev}:{path}") def commit(self, rev): - sha = self.run("rev-parse", "--verify", f"{rev}^{{commit}}").strip() - return Commit( - sha, - self.run("rev-parse", f"{sha}^{{tree}}").strip(), - tuple(self.run("log", "-1", "--format=%P", sha).split()), - self.run("log", "-1", "--format=%B", sha), - ) + fields = self.run( + "show", "--no-patch", "--format=%H%x00%T%x00%P%x00%B", f"{rev}^{{commit}}", "--" + ).split("\0", 3) + if len(fields) != 4: + raise GitError("commit lookup returned malformed metadata") + sha, tree, parents, message = fields + return Commit(sha, tree, tuple(parents.split()), message) + def prooft_api(request): diff --git a/ci/test_pr_attestation.py b/ci/test_pr_attestation.py index 4c01623159..f041e22546 100644 --- a/ci/test_pr_attestation.py +++ b/ci/test_pr_attestation.py @@ -14,6 +14,7 @@ from dataclasses import dataclass, replace import hashlib import re +import shutil import io import json from pathlib import Path @@ -22,6 +23,7 @@ import sys import tempfile import unittest +import zlib from unittest.mock import patch import pr_attestation as subject @@ -103,26 +105,153 @@ def to_trailer(self): )) +class ObjectFixture: + """Write real loose Git objects; fixture construction needs no Git processes. + + Only the test builder uses this. The verifier still reads the resulting + repository with real Git, including its real merge-base and shallow logic. + """ + + def __init__(self, root): + self.root = root + self.index = {} + self.trees = {} + self.commits = {} + + def object(self, kind, body): + raw = f"{kind} {len(body)}\0".encode() + body + sha = hashlib.sha1(raw).hexdigest() + path = self.root / ".git/objects" / sha[:2] / sha[2:] + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(zlib.compress(raw)) + return sha + + def tree(self, entries): + children = {} + for path, sha in entries.items(): + name, sep, rest = path.partition("/") + if sep: + children.setdefault(name, {})[rest] = sha + else: + children[name] = sha + body = bytearray() + for name, value in sorted(children.items(), key=lambda item: item[0] + ("/" if isinstance(item[1], dict) else "")): + mode, sha = ("40000", self.tree(value)) if isinstance(value, dict) else ("100644", value) + body.extend(f"{mode} {name}\0".encode() + bytes.fromhex(sha)) + sha = self.object("tree", body) + self.trees[sha] = dict(entries) + return sha + + def run(self, *args, input_text=None): + command, *values = args + if command == "add": + paths = sorted(p.relative_to(self.root).as_posix() for p in self.root.rglob("*") + if p.is_file() and ".git" not in p.relative_to(self.root).parts) if values == ["."] else values + for path in paths: + self.index[path] = self.object("blob", (self.root / path).read_bytes()) + elif command == "write-tree": + return self.tree(self.index) + elif command == "commit-tree": + tree, *parents = values + headers = [f"tree {tree}"] + [f"parent {parent}" for parent in parents[1::2]] + identity = "Local fixture 1794519000 +0000" + headers += [f"author {identity}", f"committer {identity}"] + message = input_text + ("" if input_text.endswith("\n") else "\n") + sha = self.object("commit", ("\n".join(headers) + "\n\n" + message).encode()) + self.commits[sha] = tree + return sha + elif command == "read-tree": + tree = self.commits.get(values[0], values[0]) + self.index = dict(self.trees[tree]) + elif command == "hash-object": + return self.object("blob", input_text.encode()) + elif command == "update-index": + if values[0] == "--force-remove": + self.index.pop(values[1], None) + else: + assert values[:3] == ["--add", "--cacheinfo", "100644"], values + self.index[values[4]] = values[3] + else: + raise AssertionError(f"unsupported fixture operation: {args}") + return "" + + +REAL_GIT = subject.Git + + +class FixtureGit(REAL_GIT): + """Reuse successful immutable reads across identical fixture copies. + + Keys contain the exact command and full object IDs. Shallow repositories + always go through Git: shallow boundaries change ancestry without changing + object IDs. Failures are never cached. All distinct queries execute real Git. + """ + + reads = {} + + def run(self, *args): + git_dir = self.root / ".git" + if (args[0] not in {"show", "diff"} + or any((git_dir / path).exists() for path in + ("shallow", "info/grafts", "refs/replace", "packed-refs", "objects/info/alternates"))): + return super().run(*args) + ids = re.findall(r"(?