1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
|
#!/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 <pull request number | git ref> [--base REF] [--remote NAME] [--no-fetch]
[--work-dir DIR] [--crate NAME ...] [--no-cargo] [--no-python] [--cargo PATH] [--json]
Green is the base (`<remote>/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 `<git common dir>/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 <remote>/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 (<git common 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())
|