|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import os |
| 4 | +import sys |
| 5 | +import json |
| 6 | +import shutil |
| 7 | +import tarfile |
| 8 | +import tempfile |
| 9 | +import subprocess |
| 10 | +from typing import Any |
| 11 | +from pathlib import Path |
| 12 | +from collections import Counter |
| 13 | + |
| 14 | +ROOT = Path(__file__).resolve().parents[1] |
| 15 | +CONFIG = ROOT / "scripts/pyrightconfig.breaking-changes.json" |
| 16 | + |
| 17 | + |
| 18 | +def snapshot_baseline(ref: str, destination: Path) -> None: |
| 19 | + commit = subprocess.check_output( |
| 20 | + ["git", "rev-parse", "--verify", "--end-of-options", f"{ref}^{{commit}}"], cwd=ROOT, text=True |
| 21 | + ).strip() |
| 22 | + with tempfile.TemporaryFile() as archive: |
| 23 | + subprocess.run(["git", "archive", commit, "src", "tests"], cwd=ROOT, stdout=archive, check=True) |
| 24 | + archive.seek(0) |
| 25 | + with tarfile.open(fileobj=archive) as contents: |
| 26 | + for member in contents: |
| 27 | + path = Path(member.name) |
| 28 | + if path.is_absolute() or ".." in path.parts or not (member.isfile() or member.isdir()): |
| 29 | + raise RuntimeError(f"Unsupported baseline archive entry: {member.name}") |
| 30 | + target = destination / path |
| 31 | + if member.isdir(): |
| 32 | + target.mkdir(parents=True, exist_ok=True) |
| 33 | + else: |
| 34 | + target.parent.mkdir(parents=True, exist_ok=True) |
| 35 | + source = contents.extractfile(member) |
| 36 | + assert source is not None |
| 37 | + with source, target.open("wb") as output: |
| 38 | + shutil.copyfileobj(source, output) |
| 39 | + |
| 40 | + |
| 41 | +def check(snapshot: Path) -> list[dict[str, Any]]: |
| 42 | + # Keep the current checker configuration and dependencies fixed. Only the |
| 43 | + # SDK source changes; all tests and their helpers come from the baseline. |
| 44 | + # Preserve relative include and import paths by keeping the config in scripts/. |
| 45 | + config_path = snapshot / "scripts" / CONFIG.name |
| 46 | + config_path.parent.mkdir(parents=True, exist_ok=True) |
| 47 | + shutil.copyfile(CONFIG, config_path) |
| 48 | + result = subprocess.run( |
| 49 | + [str(ROOT / "scripts/run-pyright"), "--outputjson", "--pythonpath", sys.executable], |
| 50 | + cwd=ROOT, |
| 51 | + env={**os.environ, "PYRIGHT_PROJECT": str(config_path)}, |
| 52 | + capture_output=True, |
| 53 | + text=True, |
| 54 | + ) |
| 55 | + if result.returncode not in (0, 1): |
| 56 | + raise RuntimeError(f"Pyright failed ({result.returncode}): {result.stderr}\n{result.stdout}") |
| 57 | + report = json.loads(result.stdout) |
| 58 | + errors = [diagnostic for diagnostic in report["generalDiagnostics"] if diagnostic["severity"] == "error"] |
| 59 | + if ( |
| 60 | + report["summary"]["filesAnalyzed"] == 0 |
| 61 | + or report["summary"]["errorCount"] != len(errors) |
| 62 | + or result.returncode != bool(errors) |
| 63 | + ): |
| 64 | + raise RuntimeError("Pyright returned an incomplete or inconsistent report") |
| 65 | + return errors |
| 66 | + |
| 67 | + |
| 68 | +def diagnostic_key(diagnostic: dict[str, Any], snapshot: Path) -> str: |
| 69 | + # Compare full messages and locations, not just counts or rule names: a |
| 70 | + # different error on an already failing line is still a regression. |
| 71 | + key = {field: diagnostic.get(field) for field in ("file", "range", "rule", "message", "severity")} |
| 72 | + return json.dumps(key, sort_keys=True).replace(str(snapshot), "<snapshot>") |
| 73 | + |
| 74 | + |
| 75 | +def new_errors(baseline: list[dict[str, Any]], candidate: list[dict[str, Any]], snapshot: Path) -> list[dict[str, Any]]: |
| 76 | + remaining = Counter(diagnostic_key(diagnostic, snapshot) for diagnostic in baseline) |
| 77 | + added = [] |
| 78 | + for diagnostic in candidate: |
| 79 | + key = diagnostic_key(diagnostic, snapshot) |
| 80 | + if remaining[key]: |
| 81 | + remaining[key] -= 1 |
| 82 | + else: |
| 83 | + added.append(diagnostic) |
| 84 | + return added |
| 85 | + |
| 86 | + |
| 87 | +def main(ref: str) -> int: |
| 88 | + with tempfile.TemporaryDirectory(prefix="openai-consumer-compatibility-") as directory: |
| 89 | + snapshot = Path(directory).resolve() |
| 90 | + snapshot_baseline(ref, snapshot) |
| 91 | + print("==> Checking previous callers against the baseline SDK", flush=True) |
| 92 | + baseline = check(snapshot) |
| 93 | + shutil.rmtree(snapshot / "src") |
| 94 | + shutil.copytree(ROOT / "src", snapshot / "src", ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) |
| 95 | + print("==> Checking the same callers against the candidate SDK", flush=True) |
| 96 | + candidate = check(snapshot) |
| 97 | + added = new_errors(baseline, candidate, snapshot) |
| 98 | + print(f"Baseline: {len(baseline)} errors; candidate: {len(candidate)} errors; new: {len(added)}") |
| 99 | + for diagnostic in added: |
| 100 | + path = Path(diagnostic["file"]).relative_to(snapshot) |
| 101 | + start = diagnostic["range"]["start"] |
| 102 | + print(f"{path}:{start['line'] + 1}:{start['character'] + 1}: {diagnostic['message']}") |
| 103 | + print(f" [{diagnostic.get('rule', 'unknown')}]") |
| 104 | + return 1 if added else 0 |
| 105 | + |
| 106 | + |
| 107 | +if __name__ == "__main__": |
| 108 | + if len(sys.argv) != 2: |
| 109 | + raise SystemExit("Usage: check-consumer-compatibility.py BASE_REF") |
| 110 | + raise SystemExit(main(sys.argv[1])) |
0 commit comments