|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Classify changes to the committed public API dumps. |
| 3 | +
|
| 4 | +The binary-compatibility-validator plugin writes one ``.api`` file per published |
| 5 | +module (``android-core/api/android-core.api`` and |
| 6 | +``android-kit-base/api/android-kit-base.api``). ``./gradlew apiCheck`` fails |
| 7 | +when the compiled surface differs from the committed dump, and ``apiDump`` |
| 8 | +regenerates it. That keeps every change to the public surface visible in the |
| 9 | +pull request diff, but it does not say whether a change is acceptable. |
| 10 | +
|
| 11 | +This script compares the dumps on the current tree with the dumps on a base |
| 12 | +revision and classifies every changed class: |
| 13 | +
|
| 14 | +* **frozen** -- a class outside ``com.mparticle.internal``, or an internal |
| 15 | + class listed in ``scripts/api-frozen-internals.txt``. These are the |
| 16 | + documented customer API and the contract kit authors compile against. |
| 17 | + Any change fails with exit code 2. |
| 18 | +* **reviewable** -- any other class inside ``com.mparticle.internal``. The |
| 19 | + change is reported and the script exits 0; the reviewer decides. |
| 20 | +
|
| 21 | +Usage:: |
| 22 | +
|
| 23 | + scripts/check_api_dump.py --base origin/main |
| 24 | +
|
| 25 | +Exit codes: 0 no frozen change, 2 frozen change, 1 usage or tooling error. |
| 26 | +""" |
| 27 | + |
| 28 | +from __future__ import annotations |
| 29 | + |
| 30 | +import argparse |
| 31 | +import fnmatch |
| 32 | +import os |
| 33 | +import re |
| 34 | +import subprocess |
| 35 | +import sys |
| 36 | +from dataclasses import dataclass, field |
| 37 | +from pathlib import Path |
| 38 | + |
| 39 | +REPO_ROOT = Path(__file__).resolve().parent.parent |
| 40 | +DUMPS = ( |
| 41 | + Path("android-core/api/android-core.api"), |
| 42 | + Path("android-kit-base/api/android-kit-base.api"), |
| 43 | +) |
| 44 | +FROZEN_LIST = REPO_ROOT / "scripts" / "api-frozen-internals.txt" |
| 45 | +INTERNAL_PREFIX = "com.mparticle.internal." |
| 46 | + |
| 47 | +_HEADER = re.compile(r"^(?P<modifiers>[^{]*?)\bclass (?P<name>\S+)(?P<rest>[^{]*)\{\s*$") |
| 48 | + |
| 49 | + |
| 50 | +@dataclass |
| 51 | +class ClassEntry: |
| 52 | + header: str |
| 53 | + members: set[str] = field(default_factory=set) |
| 54 | + |
| 55 | + |
| 56 | +def parse_dump(text: str) -> dict[str, ClassEntry]: |
| 57 | + """Parse a BCV dump into ``{jvm_class_name: ClassEntry}``.""" |
| 58 | + classes: dict[str, ClassEntry] = {} |
| 59 | + current: ClassEntry | None = None |
| 60 | + for raw in text.splitlines(): |
| 61 | + line = raw.rstrip() |
| 62 | + if not line: |
| 63 | + continue |
| 64 | + if line.startswith(("\t", " ")): |
| 65 | + if current is not None: |
| 66 | + current.members.add(line.strip()) |
| 67 | + continue |
| 68 | + if line == "}": |
| 69 | + current = None |
| 70 | + continue |
| 71 | + match = _HEADER.match(line) |
| 72 | + if match: |
| 73 | + current = ClassEntry(header=line.strip()) |
| 74 | + classes[match.group("name")] = current |
| 75 | + return classes |
| 76 | + |
| 77 | + |
| 78 | +def jvm_to_dotted(name: str) -> str: |
| 79 | + return name.replace("/", ".") |
| 80 | + |
| 81 | + |
| 82 | +def outer_class(dotted: str) -> str: |
| 83 | + return dotted.split("$", 1)[0] |
| 84 | + |
| 85 | + |
| 86 | +def load_frozen_patterns(path: Path) -> list[str]: |
| 87 | + patterns: list[str] = [] |
| 88 | + if not path.exists(): |
| 89 | + return patterns |
| 90 | + for raw in path.read_text(encoding="utf-8").splitlines(): |
| 91 | + entry = raw.split("#", 1)[0].strip() |
| 92 | + if entry: |
| 93 | + patterns.append(entry) |
| 94 | + return patterns |
| 95 | + |
| 96 | + |
| 97 | +def is_frozen(dotted: str, frozen_patterns: list[str]) -> bool: |
| 98 | + if not dotted.startswith(INTERNAL_PREFIX): |
| 99 | + return True |
| 100 | + outer = outer_class(dotted) |
| 101 | + for pattern in frozen_patterns: |
| 102 | + if fnmatch.fnmatchcase(dotted, pattern) or fnmatch.fnmatchcase(outer, pattern): |
| 103 | + return True |
| 104 | + return False |
| 105 | + |
| 106 | + |
| 107 | +def git_show(base: str, path: Path) -> str | None: |
| 108 | + try: |
| 109 | + return subprocess.run( |
| 110 | + ["git", "show", f"{base}:{path.as_posix()}"], |
| 111 | + cwd=REPO_ROOT, |
| 112 | + check=True, |
| 113 | + capture_output=True, |
| 114 | + text=True, |
| 115 | + ).stdout |
| 116 | + except subprocess.CalledProcessError: |
| 117 | + return None |
| 118 | + |
| 119 | + |
| 120 | +def describe_change(old: ClassEntry | None, new: ClassEntry | None) -> list[str]: |
| 121 | + lines: list[str] = [] |
| 122 | + if old is None and new is not None: |
| 123 | + lines.append(" + class added") |
| 124 | + return lines |
| 125 | + if new is None and old is not None: |
| 126 | + lines.append(" - class removed") |
| 127 | + return lines |
| 128 | + assert old is not None and new is not None |
| 129 | + if old.header != new.header: |
| 130 | + lines.append(f" ~ declaration: {old.header} -> {new.header}") |
| 131 | + for member in sorted(old.members - new.members): |
| 132 | + lines.append(f" - {member}") |
| 133 | + for member in sorted(new.members - old.members): |
| 134 | + lines.append(f" + {member}") |
| 135 | + return lines |
| 136 | + |
| 137 | + |
| 138 | +def main(argv: list[str]) -> int: |
| 139 | + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) |
| 140 | + parser.add_argument("--base", required=True, help="git revision holding the baseline dumps, e.g. origin/main") |
| 141 | + args = parser.parse_args(argv) |
| 142 | + |
| 143 | + frozen_patterns = load_frozen_patterns(FROZEN_LIST) |
| 144 | + frozen_hits: list[str] = [] |
| 145 | + reviewable_hits: list[str] = [] |
| 146 | + |
| 147 | + for dump in DUMPS: |
| 148 | + current_path = REPO_ROOT / dump |
| 149 | + if not current_path.exists(): |
| 150 | + print(f"error: {dump} is missing; run ./gradlew apiDump", file=sys.stderr) |
| 151 | + return 1 |
| 152 | + old_text = git_show(args.base, dump) |
| 153 | + if old_text is None: |
| 154 | + print(f"note: {dump} does not exist at {args.base}; nothing to compare against (baseline creation)") |
| 155 | + continue |
| 156 | + old = parse_dump(old_text) |
| 157 | + new = parse_dump(current_path.read_text(encoding="utf-8")) |
| 158 | + |
| 159 | + for jvm_name in sorted(set(old) | set(new)): |
| 160 | + before, after = old.get(jvm_name), new.get(jvm_name) |
| 161 | + if before is not None and after is not None and before.header == after.header and before.members == after.members: |
| 162 | + continue |
| 163 | + dotted = jvm_to_dotted(jvm_name) |
| 164 | + block = [f"{dump}: {dotted}"] + describe_change(before, after) |
| 165 | + (frozen_hits if is_frozen(dotted, frozen_patterns) else reviewable_hits).append("\n".join(block)) |
| 166 | + |
| 167 | + if not frozen_hits and not reviewable_hits: |
| 168 | + print(f"api dumps unchanged against {args.base}") |
| 169 | + return 0 |
| 170 | + |
| 171 | + if reviewable_hits: |
| 172 | + print("Internal implementation surface changed (reviewable; explain in the PR description):") |
| 173 | + print("\n".join(reviewable_hits)) |
| 174 | + print() |
| 175 | + if frozen_hits: |
| 176 | + print("FROZEN API CHANGED. These classes are customer or kit-author contracts.") |
| 177 | + print("Fix the change, or label the pull request 'api-change-approved' after API review.") |
| 178 | + print("\n".join(frozen_hits)) |
| 179 | + return 2 |
| 180 | + return 0 |
| 181 | + |
| 182 | + |
| 183 | +if __name__ == "__main__": |
| 184 | + os.chdir(REPO_ROOT) |
| 185 | + sys.exit(main(sys.argv[1:])) |
0 commit comments