|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Wait until a GitHub PR's checks have all finished, then print them. |
| 3 | +
|
| 4 | + wait_pr_checks.py REPO PR [--min-checks N] [--interval S] [--timeout S] |
| 5 | +
|
| 6 | +Exit 0 if every check passed (or was skipped), 1 if any failed or was |
| 7 | +cancelled, 2 on timeout. Waits for at least --min-checks checks to exist |
| 8 | +first, since checks for a just-pushed commit appear with a delay (and a PR |
| 9 | +with no checks yet would otherwise look "all green"). |
| 10 | +""" |
| 11 | + |
| 12 | +import argparse |
| 13 | +import json |
| 14 | +import subprocess |
| 15 | +import sys |
| 16 | +import time |
| 17 | + |
| 18 | + |
| 19 | +def checks(repo, pr): |
| 20 | + r = subprocess.run(["gh", "pr", "checks", str(pr), "-R", repo, "--json", "name,bucket,link"], |
| 21 | + capture_output=True, text=True) |
| 22 | + if r.returncode not in (0, 1, 8): # gh exits 1 when checks failed, 8 while pending |
| 23 | + return None |
| 24 | + try: |
| 25 | + return json.loads(r.stdout or "[]") |
| 26 | + except json.JSONDecodeError: |
| 27 | + return None |
| 28 | + |
| 29 | + |
| 30 | +def main(): |
| 31 | + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) |
| 32 | + p.add_argument("repo") |
| 33 | + p.add_argument("pr", type=int) |
| 34 | + p.add_argument("--min-checks", type=int, default=1) |
| 35 | + p.add_argument("--interval", type=int, default=30) |
| 36 | + p.add_argument("--timeout", type=int, default=3600) |
| 37 | + args = p.parse_args() |
| 38 | + |
| 39 | + deadline = time.time() + args.timeout |
| 40 | + while time.time() < deadline: |
| 41 | + cs = checks(args.repo, args.pr) |
| 42 | + if cs is not None and len(cs) >= args.min_checks and all(c["bucket"] != "pending" for c in cs): |
| 43 | + bad = [c for c in cs if c["bucket"] in ("fail", "cancel")] |
| 44 | + for c in cs: |
| 45 | + print("%-30s %s" % (c["name"], c["bucket"])) |
| 46 | + print("ALL PASSED" if not bad else "FAILED: %d check(s)" % len(bad)) |
| 47 | + sys.exit(1 if bad else 0) |
| 48 | + time.sleep(args.interval) |
| 49 | + print("TIMEOUT waiting for checks on %s#%d" % (args.repo, args.pr)) |
| 50 | + sys.exit(2) |
| 51 | + |
| 52 | + |
| 53 | +if __name__ == "__main__": |
| 54 | + main() |
0 commit comments