diff options
| author | MoonEyes <ducoinbenjamin@yahoo.fr> | 2026-11-30 23:33:36 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-11-30 23:33:36 +0100 |
| commit | 2878a3911c04bd182f1c04aa8ac347ffaadcc2b3 (patch) | |
| tree | 3a677bcb6079a09868dc4b4cc90a4ac5558ed7ba /scripts | |
| parent | 6494909b783b9af95905fd101706fcb566292f1c (diff) | |
| parent | 1f08a8abb1c74943f541df5274d06773e4424f91 (diff) | |
Merge pull request #2787 from TheGeogeo/test-red-green
scripts: red_green.py checks a pull request red and green locally (TEST-RED-GREEN-LOCAL)
Diffstat (limited to 'scripts')
| -rw-r--r-- | scripts/red_green.py | 487 |
1 files changed, 487 insertions, 0 deletions
diff --git a/scripts/red_green.py b/scripts/red_green.py new file mode 100644 index 000000000..1af2fd167 --- /dev/null +++ b/scripts/red_green.py | |||
| @@ -0,0 +1,487 @@ | |||
| 1 | #!/usr/bin/env python3 | ||
| 2 | """Checks a pull request red and green on this machine (docs/testing.md, "Red and green on your machine"). | ||
| 3 | |||
| 4 | python -I scripts/red_green.py <pull request number | git ref> [--base REF] [--remote NAME] [--no-fetch] | ||
| 5 | [--work-dir DIR] [--crate NAME ...] [--no-cargo] [--no-python] [--cargo PATH] [--json] | ||
| 6 | |||
| 7 | Green is the base (`<remote>/main` after a fetch, by default) with the pull request merged. Red is the base with | ||
| 8 | only the pull request's tests. A test that fails on red and passes on green shows that the change is what makes it | ||
| 9 | pass; a test that passes on both proves nothing about the change. | ||
| 10 | |||
| 11 | The red side comes from the pull request's diff against its merge base with the base: | ||
| 12 | - test files, whole: a file under a `tests` folder (`tests/**`, a crate's `tests/`, `src/tests/`), `*_tests.rs`, | ||
| 13 | `tests.rs`; | ||
| 14 | - in other Rust files, the hunks that change only `#[cfg(test)]` items (a `#[cfg(test)] mod x { ... }` block, a | ||
| 15 | `#[cfg(test)] mod x_tests;` line, a `#[cfg(test)]` function), blank lines and comments around them allowed. | ||
| 16 | That change is committed on the merge base, then cherry-picked onto the base. A conflict, or a pull request with no | ||
| 17 | test, is "red not constructible". | ||
| 18 | |||
| 19 | It runs `cargo test --no-fail-fast` for the D3D12 crates the pull request touches (from `d3d12/`, so the pinned | ||
| 20 | toolchain applies) and the changed `tests/**/test*.py` files with unittest, on both sides, in one worktree and one | ||
| 21 | cargo target dir under --work-dir (default `<git common dir>/red-green`), red first. It keeps both between runs: the | ||
| 22 | second run on the same crates builds only what changed. C++ `runtime/` tests are not run here (docs/testing.md has | ||
| 23 | the fork-CI way). | ||
| 24 | |||
| 25 | Exit 0: at least one test went from red to green and no test that passes on red fails on green. 1: any other | ||
| 26 | verdict. 2: a usage or git error. | ||
| 27 | """ | ||
| 28 | from __future__ import annotations | ||
| 29 | |||
| 30 | import argparse | ||
| 31 | import json | ||
| 32 | import os | ||
| 33 | import re | ||
| 34 | import subprocess | ||
| 35 | import sys | ||
| 36 | import tempfile | ||
| 37 | from pathlib import Path | ||
| 38 | |||
| 39 | IDENTITY = { | ||
| 40 | "GIT_AUTHOR_NAME": "red_green", "GIT_AUTHOR_EMAIL": "red_green@localhost", | ||
| 41 | "GIT_COMMITTER_NAME": "red_green", "GIT_COMMITTER_EMAIL": "red_green@localhost", | ||
| 42 | } | ||
| 43 | |||
| 44 | |||
| 45 | class Failure(Exception): | ||
| 46 | """A usage or git error: the command exits 2 with its message.""" | ||
| 47 | |||
| 48 | |||
| 49 | def run(args: list[str], cwd: Path, env: dict | None = None, data: bytes | None = None) -> subprocess.CompletedProcess: | ||
| 50 | return subprocess.run(args, cwd=cwd, env=env, input=data, capture_output=True) | ||
| 51 | |||
| 52 | |||
| 53 | def git(cwd: Path, *args: str, env: dict | None = None, data: bytes | None = None, check: bool = True) -> str: | ||
| 54 | r = run(["git", *args], cwd, env, data) | ||
| 55 | if check and r.returncode != 0: | ||
| 56 | why = (r.stderr or r.stdout).decode("utf-8", "replace").strip().splitlines() | ||
| 57 | raise Failure(f"git {' '.join(args)}: {why[-1] if why else 'exit ' + str(r.returncode)}") | ||
| 58 | return r.stdout.decode("utf-8", "replace").strip() | ||
| 59 | |||
| 60 | |||
| 61 | def blob(cwd: Path, rev: str, path: str) -> bytes | None: | ||
| 62 | r = run(["git", "cat-file", "blob", f"{rev}:{path}"], cwd) | ||
| 63 | return r.stdout if r.returncode == 0 else None | ||
| 64 | |||
| 65 | |||
| 66 | def lines_of(data: bytes) -> list[bytes]: | ||
| 67 | """Lines as git counts them (on \\n only), each with its end.""" | ||
| 68 | parts = data.split(b"\n") | ||
| 69 | out = [p + b"\n" for p in parts[:-1]] | ||
| 70 | if parts[-1]: | ||
| 71 | out.append(parts[-1]) | ||
| 72 | return out | ||
| 73 | |||
| 74 | |||
| 75 | # --- which files and hunks are tests --------------------------------------------------------------------------- | ||
| 76 | |||
| 77 | def is_test_file(path: str) -> bool: | ||
| 78 | parts = path.split("/") | ||
| 79 | return "tests" in parts[:-1] or parts[-1].endswith("_tests.rs") or parts[-1] == "tests.rs" | ||
| 80 | |||
| 81 | |||
| 82 | CFG = re.compile(r"^\s*#\[cfg\((.*)\)\]\s*$") | ||
| 83 | RAW_OPEN = re.compile(r'b?r(#*)"') | ||
| 84 | CHAR = re.compile(r"b?'(?:\\(?:x[0-9a-fA-F]{2}|u\{[0-9a-fA-F]+\}|.)|[^\\'])'") | ||
| 85 | |||
| 86 | |||
| 87 | def is_test_cfg(expr: str) -> bool: | ||
| 88 | expr = expr.replace(" ", "") | ||
| 89 | if "not(test" in expr: | ||
| 90 | return False | ||
| 91 | return expr == "test" or (expr.startswith("all(") and re.search(r"[(,]test[,)]", expr) is not None) | ||
| 92 | |||
| 93 | |||
| 94 | def item_end(lines: list[str], start: int) -> int | None: | ||
| 95 | """The last line of the Rust item that starts at `start`: its `;` before any brace, or its closing brace.""" | ||
| 96 | depth, opened, state = 0, False, None | ||
| 97 | for i in range(start, len(lines)): | ||
| 98 | s, k = lines[i], 0 | ||
| 99 | while k < len(s): | ||
| 100 | c = s[k] | ||
| 101 | if state == "str": | ||
| 102 | if c == "\\": | ||
| 103 | k += 2 | ||
| 104 | continue | ||
| 105 | if c == '"': | ||
| 106 | state = None | ||
| 107 | elif isinstance(state, int): # a raw string with `state` hashes | ||
| 108 | close = '"' + "#" * state | ||
| 109 | if s.startswith(close, k): | ||
| 110 | state, k = None, k + len(close) | ||
| 111 | continue | ||
| 112 | elif state == "comment": | ||
| 113 | if s.startswith("*/", k): | ||
| 114 | state, k = None, k + 2 | ||
| 115 | continue | ||
| 116 | else: | ||
| 117 | if s.startswith("//", k): | ||
| 118 | break | ||
| 119 | if s.startswith("/*", k): | ||
| 120 | state, k = "comment", k + 2 | ||
| 121 | continue | ||
| 122 | m = RAW_OPEN.match(s, k) | ||
| 123 | if m and (k == 0 or not (s[k - 1].isalnum() or s[k - 1] == "_")): | ||
| 124 | state, k = len(m.group(1)), m.end() | ||
| 125 | continue | ||
| 126 | m = CHAR.match(s, k) | ||
| 127 | if m and (k == 0 or not (s[k - 1].isalnum() or s[k - 1] == "_")): | ||
| 128 | k = m.end() | ||
| 129 | continue | ||
| 130 | if c == '"': | ||
| 131 | state = "str" | ||
| 132 | elif c == "{": | ||
| 133 | depth, opened = depth + 1, True | ||
| 134 | elif c == "}": | ||
| 135 | depth -= 1 | ||
| 136 | if opened and depth == 0: | ||
| 137 | return i | ||
| 138 | elif c == ";" and not opened and depth == 0: | ||
| 139 | return i | ||
| 140 | k += 1 | ||
| 141 | return None | ||
| 142 | |||
| 143 | |||
| 144 | def test_lines(data: bytes) -> set[int]: | ||
| 145 | """0-based indexes of the lines that belong to `#[cfg(test)]` items.""" | ||
| 146 | lines = [line.decode("utf-8", "replace") for line in lines_of(data)] | ||
| 147 | out: set[int] = set() | ||
| 148 | i = 0 | ||
| 149 | while i < len(lines): | ||
| 150 | m = CFG.match(lines[i]) | ||
| 151 | if m and is_test_cfg(m.group(1)): | ||
| 152 | j = i + 1 | ||
| 153 | while j < len(lines) and (not lines[j].strip() or lines[j].lstrip().startswith(("#[", "//"))): | ||
| 154 | j += 1 | ||
| 155 | end = item_end(lines, j) if j < len(lines) else None | ||
| 156 | if end is not None: | ||
| 157 | out.update(range(i, end + 1)) | ||
| 158 | i = end + 1 | ||
| 159 | continue | ||
| 160 | i += 1 | ||
| 161 | return out | ||
| 162 | |||
| 163 | |||
| 164 | def neutral(line: bytes) -> bool: | ||
| 165 | text = line.decode("utf-8", "replace").strip() | ||
| 166 | return not text or text.startswith("//") | ||
| 167 | |||
| 168 | |||
| 169 | HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") | ||
| 170 | |||
| 171 | |||
| 172 | def hunks(diff: str) -> list[tuple[int, int, int, int]]: | ||
| 173 | out = [] | ||
| 174 | for line in diff.splitlines(): | ||
| 175 | m = HUNK.match(line) | ||
| 176 | if m: | ||
| 177 | a, b, c, d = m.group(1), m.group(2), m.group(3), m.group(4) | ||
| 178 | out.append((int(a), 1 if b is None else int(b), int(c), 1 if d is None else int(d))) | ||
| 179 | return out | ||
| 180 | |||
| 181 | |||
| 182 | def test_hunks(old: bytes, new: bytes, diff: str) -> bytes | None: | ||
| 183 | """`old` with only the hunks of `diff` (made with -U0) that change test code; None when there is none.""" | ||
| 184 | old_lines, new_lines = lines_of(old), lines_of(new) | ||
| 185 | old_tests, new_tests = test_lines(old), test_lines(new) | ||
| 186 | keep = [] | ||
| 187 | for a, b, c, d in hunks(diff): | ||
| 188 | removed = range(a - 1, a - 1 + b) | ||
| 189 | added = range(c - 1, c - 1 + d) | ||
| 190 | lines = [(i in old_tests, old_lines[i]) for i in removed] + [(i in new_tests, new_lines[i]) for i in added] | ||
| 191 | if lines and all(t or neutral(line) for t, line in lines) and any(t for t, _ in lines): | ||
| 192 | keep.append((a, b, c, d)) | ||
| 193 | if not keep: | ||
| 194 | return None | ||
| 195 | out = list(old_lines) | ||
| 196 | for a, b, c, d in sorted(keep, reverse=True): | ||
| 197 | at = a if b == 0 else a - 1 | ||
| 198 | out[at:at + b] = new_lines[c - 1:c - 1 + d] | ||
| 199 | return b"".join(out) | ||
| 200 | |||
| 201 | |||
| 202 | # --- the two sides ------------------------------------------------------------------------------------------------ | ||
| 203 | |||
| 204 | def red_commit(repo: Path, merge_base: str, head: str) -> tuple[str | None, list[str]]: | ||
| 205 | """A commit on the merge base with only the pull request's tests, and the files it takes them from.""" | ||
| 206 | changed = git(repo, "diff", "--name-status", "--no-renames", "-z", merge_base, head).split("\0") | ||
| 207 | pairs = [(changed[i], changed[i + 1]) for i in range(0, len(changed) - 1, 2)] | ||
| 208 | plan: list[tuple[str, tuple[str, bytes] | None]] = [] | ||
| 209 | for status, path in pairs: | ||
| 210 | if is_test_file(path): | ||
| 211 | if status == "D": | ||
| 212 | plan.append((path, None)) | ||
| 213 | continue | ||
| 214 | mode = git(repo, "ls-tree", head, "--", path).split(" ", 1)[0] | ||
| 215 | plan.append((path, (mode, blob(repo, head, path) or b""))) | ||
| 216 | elif path.endswith(".rs") and status == "M": | ||
| 217 | diff = git(repo, "diff", "-U0", "--no-color", "--no-ext-diff", merge_base, head, "--", path) | ||
| 218 | merged = test_hunks(blob(repo, merge_base, path) or b"", blob(repo, head, path) or b"", diff) | ||
| 219 | if merged is not None: | ||
| 220 | mode = git(repo, "ls-tree", merge_base, "--", path).split(" ", 1)[0] | ||
| 221 | plan.append((path, (mode, merged))) | ||
| 222 | if not plan: | ||
| 223 | return None, [] | ||
| 224 | with tempfile.TemporaryDirectory(prefix="red-green-index-") as tmp: | ||
| 225 | env = dict(os.environ, GIT_INDEX_FILE=str(Path(tmp) / "index"), **IDENTITY) | ||
| 226 | git(repo, "read-tree", merge_base, env=env) | ||
| 227 | for path, change in plan: | ||
| 228 | if change is None: | ||
| 229 | git(repo, "update-index", "--force-remove", "--", path, env=env) | ||
| 230 | else: | ||
| 231 | mode, data = change | ||
| 232 | sha = git(repo, "hash-object", "-w", "--stdin", data=data) | ||
| 233 | git(repo, "update-index", "--add", "--cacheinfo", f"{mode},{sha},{path}", env=env) | ||
| 234 | tree = git(repo, "write-tree", env=env) | ||
| 235 | commit = git(repo, "commit-tree", tree, "-p", merge_base, "-m", f"red_green: the tests of {head[:12]} only", | ||
| 236 | env=env) | ||
| 237 | return commit, [path for path, _ in plan] | ||
| 238 | |||
| 239 | |||
| 240 | def checkout(repo: Path, tree: Path, base: str) -> None: | ||
| 241 | if not (tree / ".git").exists(): | ||
| 242 | git(repo, "worktree", "add", "--detach", "--force", str(tree), base) | ||
| 243 | return | ||
| 244 | git(tree, "cherry-pick", "--quit", check=False) | ||
| 245 | git(tree, "merge", "--quit", check=False) | ||
| 246 | git(tree, "reset", "--hard", "-q") | ||
| 247 | git(tree, "clean", "-fdq") | ||
| 248 | git(tree, "checkout", "--detach", "--force", "-q", base) | ||
| 249 | |||
| 250 | |||
| 251 | def conflicts(tree: Path) -> list[str]: | ||
| 252 | return [p for p in git(tree, "diff", "--name-only", "--diff-filter=U").splitlines() if p] | ||
| 253 | |||
| 254 | |||
| 255 | # --- running the tests -------------------------------------------------------------------------------------------- | ||
| 256 | |||
| 257 | UNIT = re.compile(r"^\s*(?:Running\s.*?([\w-]+?)-[0-9a-f]{16}(?:\.exe)?\)|Doc-tests\s+(\S+))\s*$") | ||
| 258 | CARGO_TEST = re.compile(r"^test (.+?) \.\.\. (ok|FAILED|ignored)\b") | ||
| 259 | CARGO_ERROR = re.compile(r"^error(?:\[E\d+\])?: ") | ||
| 260 | |||
| 261 | |||
| 262 | def crates_of(tree: Path, paths: list[str]) -> list[str]: | ||
| 263 | names = [] | ||
| 264 | for path in paths: | ||
| 265 | parts = path.split("/") | ||
| 266 | if len(parts) > 3 and parts[0] == "d3d12" and parts[1] in ("crates", "apps"): | ||
| 267 | manifest = tree / "d3d12" / parts[1] / parts[2] / "Cargo.toml" | ||
| 268 | if manifest.is_file(): | ||
| 269 | m = re.search(r'^\s*name\s*=\s*"([^"]+)"', manifest.read_text(encoding="utf-8"), re.M) | ||
| 270 | if m and m.group(1) not in names: | ||
| 271 | names.append(m.group(1)) | ||
| 272 | return names | ||
| 273 | |||
| 274 | |||
| 275 | def cargo_tests(tree: Path, crates: list[str], cargo: str, target: Path) -> dict: | ||
| 276 | cmd = [sys.executable, cargo] if cargo.endswith(".py") else [cargo] | ||
| 277 | cmd += ["test", "--locked", "--no-fail-fast"] + [a for c in crates for a in ("-p", c)] | ||
| 278 | env = dict(os.environ, CARGO_TARGET_DIR=str(target)) | ||
| 279 | r = subprocess.run(cmd, cwd=tree / "d3d12", env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) | ||
| 280 | out = r.stdout.decode("utf-8", "replace") | ||
| 281 | tests, unit, error = {}, "?", None | ||
| 282 | for line in out.splitlines(): | ||
| 283 | m = UNIT.match(line) | ||
| 284 | if m: | ||
| 285 | unit = m.group(1) or "doc:" + m.group(2) | ||
| 286 | continue | ||
| 287 | m = CARGO_TEST.match(line) | ||
| 288 | if m: | ||
| 289 | tests[f"{unit}::{m.group(1)}"] = {"ok": "ok", "FAILED": "failed", "ignored": "ignored"}[m.group(2)] | ||
| 290 | elif error is None and CARGO_ERROR.match(line): | ||
| 291 | error = line.strip() | ||
| 292 | no_build = r.returncode != 0 and not tests | ||
| 293 | return {"tests": tests, "no_build": (error or f"cargo exit {r.returncode}") if no_build else None} | ||
| 294 | |||
| 295 | |||
| 296 | PY_TEST = re.compile(r"^(\w+) \(([\w.]+)\)(?:\n[^\n]*?)? \.\.\. (ok|FAIL|ERROR|skipped|expected failure|unexpected success)", | ||
| 297 | re.M) | ||
| 298 | |||
| 299 | |||
| 300 | def python_tests(tree: Path, files: list[str]) -> dict: | ||
| 301 | tests, no_build = {}, [] | ||
| 302 | for f in files: | ||
| 303 | start = "tests/semantic" if f.startswith("tests/semantic/") else str(Path(f).parent) | ||
| 304 | r = subprocess.run([sys.executable, "-I", "-m", "unittest", "discover", "-s", start, "-p", Path(f).name, "-v"], | ||
| 305 | cwd=tree, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) | ||
| 306 | out = r.stdout.decode("utf-8", "replace") | ||
| 307 | found = 0 | ||
| 308 | for name, where, status in PY_TEST.findall(out): | ||
| 309 | if "_FailedTest" in where: | ||
| 310 | no_build.append(f"{f}: does not import") | ||
| 311 | continue | ||
| 312 | key = where if where.endswith("." + name) else f"{where}.{name}" | ||
| 313 | tests[f"{f}::{key}"] = {"ok": "ok", "skipped": "ignored", "expected failure": "ok"}.get(status, "failed") | ||
| 314 | found += 1 | ||
| 315 | if not found and r.returncode != 0 and f"{f}: does not import" not in no_build: | ||
| 316 | no_build.append(f"{f}: exit {r.returncode}") | ||
| 317 | return {"tests": tests, "no_build": "; ".join(no_build) or None} | ||
| 318 | |||
| 319 | |||
| 320 | def side(tree: Path, crates: list[str], py_files: list[str], cargo: str, target: Path) -> dict: | ||
| 321 | result = {"tests": {}, "no_build": []} | ||
| 322 | for part in ([cargo_tests(tree, crates, cargo, target)] if crates else []) + \ | ||
| 323 | ([python_tests(tree, py_files)] if py_files else []): | ||
| 324 | result["tests"].update(part["tests"]) | ||
| 325 | if part["no_build"]: | ||
| 326 | result["no_build"].append(part["no_build"]) | ||
| 327 | return result | ||
| 328 | |||
| 329 | |||
| 330 | # --- reading the two sides ---------------------------------------------------------------------------------------- | ||
| 331 | |||
| 332 | def compare(red: dict | None, green: dict | None) -> dict: | ||
| 333 | r = red["tests"] if red else {} | ||
| 334 | g = green["tests"] if green else {} | ||
| 335 | rows = {"red_to_green": [], "regressions": [], "fail_on_both": [], "only_on_green": [], "only_on_red": []} | ||
| 336 | both_ok = 0 | ||
| 337 | for key in sorted(set(r) | set(g)): | ||
| 338 | a, b = r.get(key), g.get(key) | ||
| 339 | if a == "failed" and b == "ok": | ||
| 340 | rows["red_to_green"].append(key) | ||
| 341 | elif a == "ok" and b == "failed": | ||
| 342 | rows["regressions"].append(key) | ||
| 343 | elif a == "failed" and b == "failed": | ||
| 344 | rows["fail_on_both"].append(key) | ||
| 345 | elif a is None and b is not None: | ||
| 346 | rows["only_on_green"].append(f"{key} ({b})") | ||
| 347 | elif b is None and a is not None: | ||
| 348 | rows["only_on_red"].append(f"{key} ({a})") | ||
| 349 | elif a == "ok" and b == "ok": | ||
| 350 | both_ok += 1 | ||
| 351 | rows["pass_on_both"] = both_ok | ||
| 352 | return rows | ||
| 353 | |||
| 354 | |||
| 355 | def verdict(red_why: str | None, green_why: str | None, red: dict | None, green: dict | None, rows: dict) -> str: | ||
| 356 | if green_why: | ||
| 357 | return "green not constructible" | ||
| 358 | green_failed = rows["regressions"] or any(r.endswith("(failed)") for r in rows["only_on_green"]) | ||
| 359 | if green and green["no_build"] or green_failed: | ||
| 360 | return "green fails" | ||
| 361 | if red_why: | ||
| 362 | return "red not constructible" | ||
| 363 | if not (red and red["tests"]) and not (green and green["tests"]): | ||
| 364 | return "no tests ran" | ||
| 365 | if rows["red_to_green"]: | ||
| 366 | return "red then green" | ||
| 367 | if red and red["no_build"] and rows["only_on_green"]: | ||
| 368 | return "red does not build" | ||
| 369 | return "no red" | ||
| 370 | |||
| 371 | |||
| 372 | def report(r: dict) -> str: | ||
| 373 | out = [f"base {r['base']} {r['base_commit'][:9]}, head {r['head']} {r['head_commit'][:9]}, " | ||
| 374 | f"merge base {r['merge_base'][:9]}"] | ||
| 375 | out.append("red: " + (r["red_why"] or "the base plus the tests of " + ", ".join(r["red_files"]))) | ||
| 376 | out.append("green: " + (r["green_why"] or "the base with the pull request merged")) | ||
| 377 | out.append("ran: " + ", ".join([f"cargo -p {c}" for c in r["crates"]] + r["python_files"] or ["nothing"])) | ||
| 378 | for name in ("red", "green"): | ||
| 379 | s = r[name] | ||
| 380 | if s and s["no_build"]: | ||
| 381 | out.append(f"{name} does not build: " + "; ".join(s["no_build"])) | ||
| 382 | rows = r["rows"] | ||
| 383 | labels = {"red_to_green": "red then green", "regressions": "pass on red, FAIL on green", | ||
| 384 | "fail_on_both": "fail on both (failing on the base too?)", "only_on_green": "only on green", | ||
| 385 | "only_on_red": "only on red"} | ||
| 386 | for key, label in labels.items(): | ||
| 387 | if rows[key]: | ||
| 388 | out.append(f"{label} ({len(rows[key])}):") | ||
| 389 | out += [f" {t}" for t in rows[key][:40]] | ||
| 390 | if len(rows[key]) > 40: | ||
| 391 | out.append(f" ... {len(rows[key]) - 40} more") | ||
| 392 | out.append(f"pass on both: {rows['pass_on_both']}") | ||
| 393 | out.append(f"verdict: {r['verdict']}") | ||
| 394 | return "\n".join(out) | ||
| 395 | |||
| 396 | |||
| 397 | def main(argv: list[str] | None = None) -> int: | ||
| 398 | p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) | ||
| 399 | p.add_argument("pr", help="a pull request number (fetched from --remote) or a git ref") | ||
| 400 | p.add_argument("--base", help="the base to test on (default <remote>/main, fetched)") | ||
| 401 | p.add_argument("--remote", default="origin", help="where main and pull requests are fetched from (origin)") | ||
| 402 | p.add_argument("--no-fetch", action="store_true", help="use the refs as they are") | ||
| 403 | p.add_argument("--work-dir", type=Path, help="the worktree and cargo target dir (<git common dir>/red-green)") | ||
| 404 | p.add_argument("--crate", action="append", default=[], help="a cargo package to test as well (repeatable)") | ||
| 405 | p.add_argument("--no-cargo", action="store_true", help="skip the cargo tests") | ||
| 406 | p.add_argument("--no-python", action="store_true", help="skip the Python tests") | ||
| 407 | p.add_argument("--cargo", default="cargo", help="the cargo to run (a .py file runs with this Python)") | ||
| 408 | p.add_argument("--json", action="store_true", help="print the result as JSON") | ||
| 409 | a = p.parse_args(argv) | ||
| 410 | try: | ||
| 411 | repo = Path(git(Path.cwd(), "rev-parse", "--show-toplevel")) | ||
| 412 | common = Path(git(repo, "rev-parse", "--path-format=absolute", "--git-common-dir")) | ||
| 413 | base = a.base or f"{a.remote}/main" | ||
| 414 | if not a.no_fetch: | ||
| 415 | if not a.base: | ||
| 416 | git(repo, "fetch", "-q", a.remote, "main") | ||
| 417 | if a.pr.isdigit(): | ||
| 418 | git(repo, "fetch", "-q", a.remote, f"pull/{a.pr}/head") | ||
| 419 | head = git(repo, "rev-parse", "FETCH_HEAD" if a.pr.isdigit() and not a.no_fetch else a.pr + "^{commit}") | ||
| 420 | base_commit = git(repo, "rev-parse", base + "^{commit}") | ||
| 421 | merge_base = git(repo, "merge-base", base_commit, head) | ||
| 422 | work = (a.work_dir or common / "red-green").resolve() | ||
| 423 | work.mkdir(parents=True, exist_ok=True) | ||
| 424 | lock = work / "lock" | ||
| 425 | try: | ||
| 426 | fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY) | ||
| 427 | except FileExistsError: | ||
| 428 | raise Failure(f"{lock} exists: another run is going, or delete it if none is") from None | ||
| 429 | os.write(fd, str(os.getpid()).encode()) | ||
| 430 | os.close(fd) | ||
| 431 | try: | ||
| 432 | result = check(repo, work, a, base, base_commit, head, merge_base) | ||
| 433 | finally: | ||
| 434 | lock.unlink(missing_ok=True) | ||
| 435 | except Failure as e: | ||
| 436 | print(f"red_green: {e}", file=sys.stderr) | ||
| 437 | return 2 | ||
| 438 | print(json.dumps(result, indent=1) if a.json else report(result)) | ||
| 439 | return 0 if result["verdict"] == "red then green" else 1 | ||
| 440 | |||
| 441 | |||
| 442 | def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, merge_base: str) -> dict: | ||
| 443 | tree, target = work / "tree", work / "target" | ||
| 444 | changed = [p for p in git(repo, "diff", "--name-only", "--no-renames", merge_base, head).splitlines() if p] | ||
| 445 | checkout(repo, tree, base_commit) | ||
| 446 | crates = [] if a.no_cargo else crates_of(tree, changed) + [c for c in a.crate if c not in crates_of(tree, changed)] | ||
| 447 | py_files = [] if a.no_python else [ | ||
| 448 | f for f in changed if f.startswith("tests/") and re.fullmatch(r"test\w*\.py", f.rsplit("/", 1)[-1])] | ||
| 449 | env = dict(os.environ, **IDENTITY) | ||
| 450 | |||
| 451 | red, red_why = None, None | ||
| 452 | commit, red_files = red_commit(repo, merge_base, head) | ||
| 453 | if commit is None: | ||
| 454 | red_why = "not constructible: the pull request changes no test" | ||
| 455 | else: | ||
| 456 | git(tree, "cherry-pick", "--no-commit", commit, env=env, check=False) | ||
| 457 | stuck = conflicts(tree) | ||
| 458 | if stuck: | ||
| 459 | red_why = "not constructible: the tests conflict with the base in " + ", ".join(stuck) | ||
| 460 | else: | ||
| 461 | print("red_green: red side...", file=sys.stderr) | ||
| 462 | red = side(tree, crates, [f for f in py_files if (tree / f).is_file()], a.cargo, target) | ||
| 463 | |||
| 464 | green, green_why = None, None | ||
| 465 | checkout(repo, tree, base_commit) | ||
| 466 | git(tree, "merge", "--no-commit", "--no-ff", head, env=env, check=False) | ||
| 467 | stuck = conflicts(tree) | ||
| 468 | if stuck: | ||
| 469 | green_why = "not constructible: the pull request conflicts with the base in " + ", ".join(stuck) | ||
| 470 | else: | ||
| 471 | print("red_green: green side...", file=sys.stderr) | ||
| 472 | green = side(tree, crates, [f for f in py_files if (tree / f).is_file()], a.cargo, target) | ||
| 473 | checkout(repo, tree, base_commit) | ||
| 474 | |||
| 475 | rows = compare(red, green) | ||
| 476 | return {"base": base, "base_commit": base_commit, "head": a.pr, "head_commit": head, "merge_base": merge_base, | ||
| 477 | "red_files": red_files, "red_why": red_why, "green_why": green_why, "crates": crates, | ||
| 478 | "python_files": py_files, "red": red, "green": green, "rows": rows, | ||
| 479 | "verdict": verdict(red_why, green_why, red, green, rows)} | ||
| 480 | |||
| 481 | |||
| 482 | if __name__ == "__main__": | ||
| 483 | try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode | ||
| 484 | sys.stdout.reconfigure(errors="replace") | ||
| 485 | except (AttributeError, ValueError, OSError): | ||
| 486 | pass | ||
| 487 | sys.exit(main()) | ||