|
| 1 | +"""Compare immutable Protobuf trees using a trusted Buf FILE policy.""" |
| 2 | + |
| 3 | +import argparse |
| 4 | +import json |
| 5 | +import os |
| 6 | +import pathlib |
| 7 | +import subprocess |
| 8 | +import tempfile |
| 9 | + |
| 10 | + |
| 11 | +def write_workspace(directory, sources): |
| 12 | + modules = [] |
| 13 | + has_primary_module = any(path.startswith("proto/") for path in sources) |
| 14 | + if has_primary_module: |
| 15 | + modules.append({"path": "proto"}) |
| 16 | + if not sources or any(not path.startswith("proto/") for path in sources): |
| 17 | + root_module = {"path": "."} |
| 18 | + if has_primary_module: |
| 19 | + root_module["excludes"] = ["proto"] |
| 20 | + modules.append(root_module) |
| 21 | + directory.mkdir() |
| 22 | + for path, data in sources.items(): |
| 23 | + relative = pathlib.PurePosixPath(path) |
| 24 | + if ( |
| 25 | + relative.is_absolute() |
| 26 | + or ".." in relative.parts |
| 27 | + or relative.as_posix() != path |
| 28 | + ): |
| 29 | + raise ValueError("Invalid Protobuf source path") |
| 30 | + target = directory / relative |
| 31 | + target.parent.mkdir(parents=True, exist_ok=True) |
| 32 | + target.write_bytes(data) |
| 33 | + (directory / "buf.yaml").write_text( |
| 34 | + json.dumps({"version": "v2", "modules": modules, "breaking": {"use": ["FILE"]}}) |
| 35 | + ) |
| 36 | + |
| 37 | + |
| 38 | +def breaking_changes(baseline, candidate): |
| 39 | + if not baseline: |
| 40 | + if not candidate: |
| 41 | + return [] |
| 42 | + # Compile the first schema even though it has no prior contracts. |
| 43 | + baseline = candidate |
| 44 | + if not candidate: |
| 45 | + # Buf needs a non-empty candidate. Choose a distinct path so it |
| 46 | + # reports every baseline schema as removed. |
| 47 | + marker = "_empty.proto" |
| 48 | + while marker in baseline or "proto/" + marker in baseline: |
| 49 | + marker = "_" + marker |
| 50 | + candidate = {marker: b'syntax = "proto3";\n'} |
| 51 | + with tempfile.TemporaryDirectory(prefix="protobuf-compatibility-") as work: |
| 52 | + root = pathlib.Path(work) |
| 53 | + write_workspace(root / "baseline", baseline) |
| 54 | + write_workspace(root / "candidate", candidate) |
| 55 | + result = subprocess.run( |
| 56 | + [ |
| 57 | + "buf", |
| 58 | + "breaking", |
| 59 | + "candidate", |
| 60 | + "--against", |
| 61 | + "baseline", |
| 62 | + "--disable-symlinks", |
| 63 | + "--error-format=json", |
| 64 | + ], |
| 65 | + cwd=root, |
| 66 | + env={**os.environ, "XDG_CACHE_HOME": str(root / "cache")}, |
| 67 | + capture_output=True, |
| 68 | + text=True, |
| 69 | + timeout=30, |
| 70 | + ) |
| 71 | + if result.returncode == 0: |
| 72 | + return [] |
| 73 | + try: |
| 74 | + violations = [ |
| 75 | + json.loads(line) |
| 76 | + for line in (*result.stdout.splitlines(), *result.stderr.splitlines()) |
| 77 | + ] |
| 78 | + if ( |
| 79 | + result.returncode == 100 |
| 80 | + and violations |
| 81 | + and all(row.get("type") and row.get("message") for row in violations) |
| 82 | + ): |
| 83 | + return sorted( |
| 84 | + ( |
| 85 | + row.get("path", "protobuf").split("/", 1)[-1], |
| 86 | + row["type"], |
| 87 | + row["message"], |
| 88 | + ) |
| 89 | + for row in violations |
| 90 | + ) |
| 91 | + except (ValueError, AttributeError): |
| 92 | + pass |
| 93 | + raise ValueError( |
| 94 | + "Buf could not complete the Protobuf check: " |
| 95 | + + ( |
| 96 | + result.stderr or result.stdout or f"exit status {result.returncode}" |
| 97 | + ).strip()[:4096] |
| 98 | + ) |
| 99 | + |
| 100 | + |
| 101 | +def git_schemas(revision): |
| 102 | + commit = subprocess.check_output( |
| 103 | + ["git", "rev-parse", "--verify", "--end-of-options", revision + "^{commit}"], |
| 104 | + text=True, |
| 105 | + ).strip() |
| 106 | + entries = subprocess.check_output( |
| 107 | + ["git", "ls-tree", "-rz", commit], text=True |
| 108 | + ).split("\0") |
| 109 | + sources = {} |
| 110 | + for entry in filter(None, entries): |
| 111 | + metadata, path = entry.split("\t", 1) |
| 112 | + if path.endswith(".proto"): |
| 113 | + mode, kind, blob = metadata.split() |
| 114 | + if mode not in ("100644", "100755") or kind != "blob": |
| 115 | + raise ValueError("Unsupported Protobuf source mode: " + path) |
| 116 | + sources[path] = subprocess.check_output(["git", "cat-file", "blob", blob]) |
| 117 | + return sources |
| 118 | + |
| 119 | + |
| 120 | +if __name__ == "__main__": |
| 121 | + parser = argparse.ArgumentParser(description=__doc__) |
| 122 | + parser.add_argument("baseline") |
| 123 | + parser.add_argument("candidate") |
| 124 | + args = parser.parse_args() |
| 125 | + violations = breaking_changes( |
| 126 | + git_schemas(args.baseline), git_schemas(args.candidate) |
| 127 | + ) |
| 128 | + for path, rule, message in violations: |
| 129 | + print(f"{path}: {rule}: {message}") |
| 130 | + raise SystemExit(bool(violations)) |
0 commit comments