#!/usr/bin/env python3 """Checks a pull request red and green on this machine (docs/testing.md, "Red and green on your machine"). python -I scripts/red_green.py [--base REF] [--remote NAME] [--no-fetch] [--work-dir DIR] [--crate NAME ...] [--no-cargo] [--no-python] [--cargo PATH] [--json] Green is the base (`/main` after a fetch, by default) with the pull request merged. Red is the base with only the pull request's tests. A test that fails on red and passes on green shows that the change is what makes it pass; a test that passes on both proves nothing about the change. The red side comes from the pull request's diff against its merge base with the base: - test files, whole: a file under a `tests` folder (`tests/**`, a crate's `tests/`, `src/tests/`), `*_tests.rs`, `tests.rs`; - in other Rust files, the hunks that change only `#[cfg(test)]` items (a `#[cfg(test)] mod x { ... }` block, a `#[cfg(test)] mod x_tests;` line, a `#[cfg(test)]` function), blank lines and comments around them allowed. That change is committed on the merge base, then cherry-picked onto the base. A conflict, or a pull request with no test, is "red not constructible". It runs `cargo test --no-fail-fast` for the D3D12 crates the pull request touches (from `d3d12/`, so the pinned toolchain applies) and the changed `tests/**/test*.py` files with unittest, on both sides, in one worktree and one cargo target dir under --work-dir (default `/red-green`), red first. It keeps both between runs: the second run on the same crates builds only what changed. C++ `runtime/` tests are not run here (docs/testing.md has the fork-CI way). A side whose compiler crashed (a Windows crash status of rustc or a build script, an internal compiler error, a failed allocation) builds again once; a second crash is the verdict `compiler crashed`. Exit 0: at least one test went from red to green and no test that passes on red fails on green. 1: any other verdict. 2: a usage or git error. """ from __future__ import annotations import argparse import json import os import re import subprocess import sys import tempfile from pathlib import Path IDENTITY = { "GIT_AUTHOR_NAME": "red_green", "GIT_AUTHOR_EMAIL": "red_green@localhost", "GIT_COMMITTER_NAME": "red_green", "GIT_COMMITTER_EMAIL": "red_green@localhost", } class Failure(Exception): """A usage or git error: the command exits 2 with its message.""" def run(args: list[str], cwd: Path, env: dict | None = None, data: bytes | None = None) -> subprocess.CompletedProcess: return subprocess.run(args, cwd=cwd, env=env, input=data, capture_output=True) def git(cwd: Path, *args: str, env: dict | None = None, data: bytes | None = None, check: bool = True) -> str: r = run(["git", *args], cwd, env, data) if check and r.returncode != 0: why = (r.stderr or r.stdout).decode("utf-8", "replace").strip().splitlines() raise Failure(f"git {' '.join(args)}: {why[-1] if why else 'exit ' + str(r.returncode)}") return r.stdout.decode("utf-8", "replace").strip() def blob(cwd: Path, rev: str, path: str) -> bytes | None: r = run(["git", "cat-file", "blob", f"{rev}:{path}"], cwd) return r.stdout if r.returncode == 0 else None def lines_of(data: bytes) -> list[bytes]: """Lines as git counts them (on \\n only), each with its end.""" parts = data.split(b"\n") out = [p + b"\n" for p in parts[:-1]] if parts[-1]: out.append(parts[-1]) return out # --- which files and hunks are tests --------------------------------------------------------------------------- def is_test_file(path: str) -> bool: parts = path.split("/") return "tests" in parts[:-1] or parts[-1].endswith("_tests.rs") or parts[-1] == "tests.rs" CFG = re.compile(r"^\s*#\[cfg\((.*)\)\]\s*$") RAW_OPEN = re.compile(r'b?r(#*)"') CHAR = re.compile(r"b?'(?:\\(?:x[0-9a-fA-F]{2}|u\{[0-9a-fA-F]+\}|.)|[^\\'])'") def is_test_cfg(expr: str) -> bool: expr = expr.replace(" ", "") if "not(test" in expr: return False return expr == "test" or (expr.startswith("all(") and re.search(r"[(,]test[,)]", expr) is not None) def item_end(lines: list[str], start: int) -> int | None: """The last line of the Rust item that starts at `start`: its `;` before any brace, or its closing brace.""" depth, opened, state = 0, False, None for i in range(start, len(lines)): s, k = lines[i], 0 while k < len(s): c = s[k] if state == "str": if c == "\\": k += 2 continue if c == '"': state = None elif isinstance(state, int): # a raw string with `state` hashes close = '"' + "#" * state if s.startswith(close, k): state, k = None, k + len(close) continue elif state == "comment": if s.startswith("*/", k): state, k = None, k + 2 continue else: if s.startswith("//", k): break if s.startswith("/*", k): state, k = "comment", k + 2 continue m = RAW_OPEN.match(s, k) if m and (k == 0 or not (s[k - 1].isalnum() or s[k - 1] == "_")): state, k = len(m.group(1)), m.end() continue m = CHAR.match(s, k) if m and (k == 0 or not (s[k - 1].isalnum() or s[k - 1] == "_")): k = m.end() continue if c == '"': state = "str" elif c == "{": depth, opened = depth + 1, True elif c == "}": depth -= 1 if opened and depth == 0: return i elif c == ";" and not opened and depth == 0: return i k += 1 return None def test_lines(data: bytes) -> set[int]: """0-based indexes of the lines that belong to `#[cfg(test)]` items.""" lines = [line.decode("utf-8", "replace") for line in lines_of(data)] out: set[int] = set() i = 0 while i < len(lines): m = CFG.match(lines[i]) if m and is_test_cfg(m.group(1)): j = i + 1 while j < len(lines) and (not lines[j].strip() or lines[j].lstrip().startswith(("#[", "//"))): j += 1 end = item_end(lines, j) if j < len(lines) else None if end is not None: out.update(range(i, end + 1)) i = end + 1 continue i += 1 return out def neutral(line: bytes) -> bool: text = line.decode("utf-8", "replace").strip() return not text or text.startswith("//") HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") def hunks(diff: str) -> list[tuple[int, int, int, int]]: out = [] for line in diff.splitlines(): m = HUNK.match(line) if m: a, b, c, d = m.group(1), m.group(2), m.group(3), m.group(4) out.append((int(a), 1 if b is None else int(b), int(c), 1 if d is None else int(d))) return out def test_hunks(old: bytes, new: bytes, diff: str) -> bytes | None: """`old` with only the hunks of `diff` (made with -U0) that change test code; None when there is none.""" old_lines, new_lines = lines_of(old), lines_of(new) old_tests, new_tests = test_lines(old), test_lines(new) keep = [] for a, b, c, d in hunks(diff): removed = range(a - 1, a - 1 + b) added = range(c - 1, c - 1 + d) lines = [(i in old_tests, old_lines[i]) for i in removed] + [(i in new_tests, new_lines[i]) for i in added] if lines and all(t or neutral(line) for t, line in lines) and any(t for t, _ in lines): keep.append((a, b, c, d)) if not keep: return None out = list(old_lines) for a, b, c, d in sorted(keep, reverse=True): at = a if b == 0 else a - 1 out[at:at + b] = new_lines[c - 1:c - 1 + d] return b"".join(out) # --- the two sides ------------------------------------------------------------------------------------------------ def red_commit(repo: Path, merge_base: str, head: str) -> tuple[str | None, list[str]]: """A commit on the merge base with only the pull request's tests, and the files it takes them from.""" changed = git(repo, "diff", "--name-status", "--no-renames", "-z", merge_base, head).split("\0") pairs = [(changed[i], changed[i + 1]) for i in range(0, len(changed) - 1, 2)] plan: list[tuple[str, tuple[str, bytes] | None]] = [] for status, path in pairs: if is_test_file(path): if status == "D": plan.append((path, None)) continue mode = git(repo, "ls-tree", head, "--", path).split(" ", 1)[0] plan.append((path, (mode, blob(repo, head, path) or b""))) elif path.endswith(".rs") and status == "M": diff = git(repo, "diff", "-U0", "--no-color", "--no-ext-diff", merge_base, head, "--", path) merged = test_hunks(blob(repo, merge_base, path) or b"", blob(repo, head, path) or b"", diff) if merged is not None: mode = git(repo, "ls-tree", merge_base, "--", path).split(" ", 1)[0] plan.append((path, (mode, merged))) if not plan: return None, [] with tempfile.TemporaryDirectory(prefix="red-green-index-") as tmp: env = dict(os.environ, GIT_INDEX_FILE=str(Path(tmp) / "index"), **IDENTITY) git(repo, "read-tree", merge_base, env=env) for path, change in plan: if change is None: git(repo, "update-index", "--force-remove", "--", path, env=env) else: mode, data = change sha = git(repo, "hash-object", "-w", "--stdin", data=data) git(repo, "update-index", "--add", "--cacheinfo", f"{mode},{sha},{path}", env=env) tree = git(repo, "write-tree", env=env) commit = git(repo, "commit-tree", tree, "-p", merge_base, "-m", f"red_green: the tests of {head[:12]} only", env=env) return commit, [path for path, _ in plan] def checkout(repo: Path, tree: Path, base: str) -> None: if not (tree / ".git").exists(): git(repo, "worktree", "add", "--detach", "--force", str(tree), base) return git(tree, "cherry-pick", "--quit", check=False) git(tree, "merge", "--quit", check=False) git(tree, "reset", "--hard", "-q") git(tree, "clean", "-fdq") git(tree, "checkout", "--detach", "--force", "-q", base) def conflicts(tree: Path) -> list[str]: return [p for p in git(tree, "diff", "--name-only", "--diff-filter=U").splitlines() if p] # --- running the tests -------------------------------------------------------------------------------------------- UNIT = re.compile(r"^\s*(?:Running\s.*?([\w-]+?)-[0-9a-f]{16}(?:\.exe)?\)|Doc-tests\s+(\S+))\s*$") CARGO_TEST = re.compile(r"^test (.+?) \.\.\. (ok|FAILED|ignored)\b") CARGO_ERROR = re.compile(r"^error(?:\[E\d+\])?: ") def crates_of(tree: Path, paths: list[str]) -> list[str]: names = [] for path in paths: parts = path.split("/") if len(parts) > 3 and parts[0] == "d3d12" and parts[1] in ("crates", "apps"): manifest = tree / "d3d12" / parts[1] / parts[2] / "Cargo.toml" if manifest.is_file(): m = re.search(r'^\s*name\s*=\s*"([^"]+)"', manifest.read_text(encoding="utf-8"), re.M) if m and m.group(1) not in names: names.append(m.group(1)) return names # A crashed compiler, not an error in the code: rustc or a build script ending with a Windows crash status # (0xC0000005 access violation, 0xC00000FD stack overflow, 0xC0000409 abort, ...), an internal compiler error, or a # failed allocation. Such a side runs again once (a crash of a test binary stays a test result). COMPILER_CRASH = re.compile( r"process didn't exit successfully: `[^`]*(?:rustc|build-script-\w+)[^`]*` \(exit (?:code|status): " r"(0x[cC][0-9a-fA-F]{7}(?:, \w+)?)\)" r"|(internal compiler error)|(the compiler unexpectedly panicked)|(memory allocation of \d+ bytes failed)") def cargo_once(tree: Path, crates: list[str], cargo: str, target: Path) -> dict: cmd = [sys.executable, cargo] if cargo.endswith(".py") else [cargo] cmd += ["test", "--locked", "--no-fail-fast"] + [a for c in crates for a in ("-p", c)] env = dict(os.environ, CARGO_TARGET_DIR=str(target)) r = subprocess.run(cmd, cwd=tree / "d3d12", env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out = r.stdout.decode("utf-8", "replace") tests, unit, error = {}, "?", None for line in out.splitlines(): m = UNIT.match(line) if m: unit = m.group(1) or "doc:" + m.group(2) continue m = CARGO_TEST.match(line) if m: tests[f"{unit}::{m.group(1)}"] = {"ok": "ok", "FAILED": "failed", "ignored": "ignored"}[m.group(2)] elif error is None and CARGO_ERROR.match(line): error = line.strip() no_build = r.returncode != 0 and not tests crash = COMPILER_CRASH.search(out) if no_build else None return {"tests": tests, "no_build": (error or f"cargo exit {r.returncode}") if no_build and not crash else None, "crash": next(g for g in crash.groups() if g) if crash else None} def cargo_tests(tree: Path, crates: list[str], cargo: str, target: Path) -> dict: first = cargo_once(tree, crates, cargo, target) if not first["crash"]: return {"tests": first["tests"], "no_build": first["no_build"]} print(f"red_green: the compiler crashed ({first['crash']}), running again", file=sys.stderr) again = cargo_once(tree, crates, cargo, target) result = {"tests": again["tests"], "no_build": again["no_build"], "rerun_after": first["crash"]} if again["crash"]: result["compiler_crashed"] = again["crash"] return result PY_TEST = re.compile(r"^(\w+) \(([\w.]+)\)(?:\n[^\n]*?)? \.\.\. (ok|FAIL|ERROR|skipped|expected failure|unexpected success)", re.M) def python_tests(tree: Path, files: list[str]) -> dict: tests, no_build = {}, [] for f in files: start = "tests/semantic" if f.startswith("tests/semantic/") else str(Path(f).parent) r = subprocess.run([sys.executable, "-I", "-m", "unittest", "discover", "-s", start, "-p", Path(f).name, "-v"], cwd=tree, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out = r.stdout.decode("utf-8", "replace") found = 0 for name, where, status in PY_TEST.findall(out): if "_FailedTest" in where: no_build.append(f"{f}: does not import") continue key = where if where.endswith("." + name) else f"{where}.{name}" tests[f"{f}::{key}"] = {"ok": "ok", "skipped": "ignored", "expected failure": "ok"}.get(status, "failed") found += 1 if not found and r.returncode != 0 and f"{f}: does not import" not in no_build: no_build.append(f"{f}: exit {r.returncode}") return {"tests": tests, "no_build": "; ".join(no_build) or None} def side(tree: Path, crates: list[str], py_files: list[str], cargo: str, target: Path) -> dict: result = {"tests": {}, "no_build": [], "compiler_crashed": None, "rerun_after": None} for part in ([cargo_tests(tree, crates, cargo, target)] if crates else []) + \ ([python_tests(tree, py_files)] if py_files else []): result["tests"].update(part["tests"]) if part["no_build"]: result["no_build"].append(part["no_build"]) for key in ("compiler_crashed", "rerun_after"): result[key] = result[key] or part.get(key) return result # --- reading the two sides ---------------------------------------------------------------------------------------- def compare(red: dict | None, green: dict | None) -> dict: r = red["tests"] if red else {} g = green["tests"] if green else {} rows = {"red_to_green": [], "regressions": [], "fail_on_both": [], "only_on_green": [], "only_on_red": []} both_ok = 0 for key in sorted(set(r) | set(g)): a, b = r.get(key), g.get(key) if a == "failed" and b == "ok": rows["red_to_green"].append(key) elif a == "ok" and b == "failed": rows["regressions"].append(key) elif a == "failed" and b == "failed": rows["fail_on_both"].append(key) elif a is None and b is not None: rows["only_on_green"].append(f"{key} ({b})") elif b is None and a is not None: rows["only_on_red"].append(f"{key} ({a})") elif a == "ok" and b == "ok": both_ok += 1 rows["pass_on_both"] = both_ok return rows def verdict(red_why: str | None, green_why: str | None, red: dict | None, green: dict | None, rows: dict) -> str: if green_why: return "green not constructible" # Twice in a row on a side: the build cannot tell anything; not a code error, run it again later. if any(s and s.get("compiler_crashed") for s in (red, green)): return "compiler crashed" green_failed = rows["regressions"] or any(r.endswith("(failed)") for r in rows["only_on_green"]) if green and green["no_build"] or green_failed: return "green fails" if red_why: return "red not constructible" if not (red and red["tests"]) and not (green and green["tests"]): return "no tests ran" if rows["red_to_green"]: return "red then green" if red and red["no_build"] and rows["only_on_green"]: return "red does not build" return "no red" def report(r: dict) -> str: out = [f"base {r['base']} {r['base_commit'][:9]}, head {r['head']} {r['head_commit'][:9]}, " f"merge base {r['merge_base'][:9]}"] out.append("red: " + (r["red_why"] or "the base plus the tests of " + ", ".join(r["red_files"]))) out.append("green: " + (r["green_why"] or "the base with the pull request merged")) out.append("ran: " + ", ".join([f"cargo -p {c}" for c in r["crates"]] + r["python_files"] or ["nothing"])) for name in ("red", "green"): s = r[name] if s and s["no_build"]: out.append(f"{name} does not build: " + "; ".join(s["no_build"])) if s and s.get("compiler_crashed"): out.append(f"{name}: the compiler crashed twice ({s['compiler_crashed']})") elif s and s.get("rerun_after"): out.append(f"{name}: the compiler crashed once ({s['rerun_after']}), the second build is the one shown") rows = r["rows"] labels = {"red_to_green": "red then green", "regressions": "pass on red, FAIL on green", "fail_on_both": "fail on both (failing on the base too?)", "only_on_green": "only on green", "only_on_red": "only on red"} for key, label in labels.items(): if rows[key]: out.append(f"{label} ({len(rows[key])}):") out += [f" {t}" for t in rows[key][:40]] if len(rows[key]) > 40: out.append(f" ... {len(rows[key]) - 40} more") out.append(f"pass on both: {rows['pass_on_both']}") out.append(f"verdict: {r['verdict']}") return "\n".join(out) def main(argv: list[str] | None = None) -> int: p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) p.add_argument("pr", help="a pull request number (fetched from --remote) or a git ref") p.add_argument("--base", help="the base to test on (default /main, fetched)") p.add_argument("--remote", default="origin", help="where main and pull requests are fetched from (origin)") p.add_argument("--no-fetch", action="store_true", help="use the refs as they are") p.add_argument("--work-dir", type=Path, help="the worktree and cargo target dir (/red-green)") p.add_argument("--crate", action="append", default=[], help="a cargo package to test as well (repeatable)") p.add_argument("--no-cargo", action="store_true", help="skip the cargo tests") p.add_argument("--no-python", action="store_true", help="skip the Python tests") p.add_argument("--cargo", default="cargo", help="the cargo to run (a .py file runs with this Python)") p.add_argument("--json", action="store_true", help="print the result as JSON") a = p.parse_args(argv) try: repo = Path(git(Path.cwd(), "rev-parse", "--show-toplevel")) common = Path(git(repo, "rev-parse", "--path-format=absolute", "--git-common-dir")) base = a.base or f"{a.remote}/main" if not a.no_fetch: if not a.base: git(repo, "fetch", "-q", a.remote, "main") if a.pr.isdigit(): git(repo, "fetch", "-q", a.remote, f"pull/{a.pr}/head") head = git(repo, "rev-parse", "FETCH_HEAD" if a.pr.isdigit() and not a.no_fetch else a.pr + "^{commit}") base_commit = git(repo, "rev-parse", base + "^{commit}") merge_base = git(repo, "merge-base", base_commit, head) work = (a.work_dir or common / "red-green").resolve() work.mkdir(parents=True, exist_ok=True) lock = work / "lock" try: fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY) except FileExistsError: raise Failure(f"{lock} exists: another run is going, or delete it if none is") from None os.write(fd, str(os.getpid()).encode()) os.close(fd) try: result = check(repo, work, a, base, base_commit, head, merge_base) finally: lock.unlink(missing_ok=True) except Failure as e: print(f"red_green: {e}", file=sys.stderr) return 2 print(json.dumps(result, indent=1) if a.json else report(result)) return 0 if result["verdict"] == "red then green" else 1 def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, merge_base: str) -> dict: tree, target = work / "tree", work / "target" changed = [p for p in git(repo, "diff", "--name-only", "--no-renames", merge_base, head).splitlines() if p] checkout(repo, tree, base_commit) crates = [] if a.no_cargo else crates_of(tree, changed) + [c for c in a.crate if c not in crates_of(tree, changed)] py_files = [] if a.no_python else [ f for f in changed if f.startswith("tests/") and re.fullmatch(r"test\w*\.py", f.rsplit("/", 1)[-1])] env = dict(os.environ, **IDENTITY) red, red_why = None, None commit, red_files = red_commit(repo, merge_base, head) if commit is None: red_why = "not constructible: the pull request changes no test" else: git(tree, "cherry-pick", "--no-commit", commit, env=env, check=False) stuck = conflicts(tree) if stuck: red_why = "not constructible: the tests conflict with the base in " + ", ".join(stuck) else: print("red_green: red side...", file=sys.stderr) red = side(tree, crates, [f for f in py_files if (tree / f).is_file()], a.cargo, target) green, green_why = None, None checkout(repo, tree, base_commit) git(tree, "merge", "--no-commit", "--no-ff", head, env=env, check=False) stuck = conflicts(tree) if stuck: green_why = "not constructible: the pull request conflicts with the base in " + ", ".join(stuck) else: print("red_green: green side...", file=sys.stderr) green = side(tree, crates, [f for f in py_files if (tree / f).is_file()], a.cargo, target) checkout(repo, tree, base_commit) rows = compare(red, green) return {"base": base, "base_commit": base_commit, "head": a.pr, "head_commit": head, "merge_base": merge_base, "red_files": red_files, "red_why": red_why, "green_why": green_why, "crates": crates, "python_files": py_files, "red": red, "green": green, "rows": rows, "verdict": verdict(red_why, green_why, red, green, rows)} if __name__ == "__main__": try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode sys.stdout.reconfigure(errors="replace") except (AttributeError, ValueError, OSError): pass sys.exit(main())