|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Post (or update) a sticky PR comment summarising rivet verification results. |
| 3 | +
|
| 4 | +Reads the JSON written by `tools/run_verification.py` and calls the GitHub |
| 5 | +REST API directly to upsert a single marker-tagged comment on the PR. |
| 6 | +Re-running on the same PR replaces the prior body rather than appending |
| 7 | +another comment. Pure stdlib (urllib) — no `gh` CLI dependency. |
| 8 | +
|
| 9 | +Usage: |
| 10 | + tools/post_verification_comment.py <pr-number> [--results-json PATH] [--repo OWNER/NAME] |
| 11 | +
|
| 12 | +Required env: |
| 13 | + GH_TOKEN (or GITHUB_TOKEN) with `pull-requests: write`. |
| 14 | +""" |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import argparse |
| 19 | +import json |
| 20 | +import os |
| 21 | +import sys |
| 22 | +import urllib.error |
| 23 | +import urllib.request |
| 24 | +from pathlib import Path |
| 25 | + |
| 26 | +MARKER = "<!-- rivet-verification-gate -->" |
| 27 | +API = "https://api.github.com" |
| 28 | + |
| 29 | + |
| 30 | +def github_request( |
| 31 | + method: str, path: str, token: str, body: dict | None = None |
| 32 | +) -> tuple[int, bytes]: |
| 33 | + url = f"{API}{path}" |
| 34 | + data = json.dumps(body).encode("utf-8") if body is not None else None |
| 35 | + req = urllib.request.Request( |
| 36 | + url, |
| 37 | + data=data, |
| 38 | + method=method, |
| 39 | + headers={ |
| 40 | + "Accept": "application/vnd.github+json", |
| 41 | + "Authorization": f"Bearer {token}", |
| 42 | + "X-GitHub-Api-Version": "2022-11-28", |
| 43 | + "User-Agent": "spar-verification-gate", |
| 44 | + "Content-Type": "application/json" if data else "application/octet-stream", |
| 45 | + }, |
| 46 | + ) |
| 47 | + try: |
| 48 | + with urllib.request.urlopen(req) as resp: |
| 49 | + return resp.status, resp.read() |
| 50 | + except urllib.error.HTTPError as e: |
| 51 | + return e.code, e.read() |
| 52 | + |
| 53 | + |
| 54 | +def render_body(results: dict) -> str: |
| 55 | + passed = results["passed_count"] |
| 56 | + failed = results["failed_count"] |
| 57 | + skipped = results["skipped_count"] |
| 58 | + total = results["total"] |
| 59 | + failed_ids = results["failed"] |
| 60 | + flt = results["filter"] |
| 61 | + |
| 62 | + if failed == 0: |
| 63 | + status = f"✅ **{passed}/{total}** passed" |
| 64 | + else: |
| 65 | + status = f"❌ **{passed}/{total}** passed — **{failed}** failed" |
| 66 | + |
| 67 | + failed_section = ( |
| 68 | + "\n".join(f"- `{i}`" for i in failed_ids) if failed_ids else "_(none)_" |
| 69 | + ) |
| 70 | + |
| 71 | + return f"""{MARKER} |
| 72 | +## Rivet verification gate |
| 73 | +
|
| 74 | +{status} |
| 75 | +
|
| 76 | +| | count | |
| 77 | +|---|---:| |
| 78 | +| Passed | {passed} | |
| 79 | +| Failed | {failed} | |
| 80 | +| Skipped (no steps) | {skipped} | |
| 81 | +
|
| 82 | +**Filter:** `{flt}` |
| 83 | +
|
| 84 | +<details><summary>Failed artifacts</summary> |
| 85 | +
|
| 86 | +{failed_section} |
| 87 | +
|
| 88 | +</details> |
| 89 | +
|
| 90 | +<sub>Updated automatically by `tools/post_verification_comment.py`. Source of truth: `artifacts/verification.yaml`.</sub>""" |
| 91 | + |
| 92 | + |
| 93 | +def find_marker_comment(repo: str, pr: int, token: str) -> int | None: |
| 94 | + """Page through PR comments looking for the marker. Returns comment id or None.""" |
| 95 | + page = 1 |
| 96 | + while True: |
| 97 | + status, body = github_request( |
| 98 | + "GET", |
| 99 | + f"/repos/{repo}/issues/{pr}/comments?per_page=100&page={page}", |
| 100 | + token, |
| 101 | + ) |
| 102 | + if status != 200: |
| 103 | + print(f"GET comments failed: {status} {body[:200]}", file=sys.stderr) |
| 104 | + return None |
| 105 | + comments = json.loads(body) |
| 106 | + if not comments: |
| 107 | + return None |
| 108 | + for c in comments: |
| 109 | + if MARKER in (c.get("body") or ""): |
| 110 | + return c["id"] |
| 111 | + if len(comments) < 100: |
| 112 | + return None |
| 113 | + page += 1 |
| 114 | + |
| 115 | + |
| 116 | +def upsert_comment(repo: str, pr: int, body: str, token: str) -> None: |
| 117 | + existing = find_marker_comment(repo, pr, token) |
| 118 | + if existing is not None: |
| 119 | + print(f"updating comment {existing}", file=sys.stderr) |
| 120 | + status, resp = github_request( |
| 121 | + "PATCH", |
| 122 | + f"/repos/{repo}/issues/comments/{existing}", |
| 123 | + token, |
| 124 | + {"body": body}, |
| 125 | + ) |
| 126 | + else: |
| 127 | + print("creating new comment", file=sys.stderr) |
| 128 | + status, resp = github_request( |
| 129 | + "POST", |
| 130 | + f"/repos/{repo}/issues/{pr}/comments", |
| 131 | + token, |
| 132 | + {"body": body}, |
| 133 | + ) |
| 134 | + if status not in (200, 201): |
| 135 | + print(f"comment upsert failed: {status} {resp[:300]}", file=sys.stderr) |
| 136 | + sys.exit(2) |
| 137 | + |
| 138 | + |
| 139 | +def main() -> int: |
| 140 | + parser = argparse.ArgumentParser(description=__doc__) |
| 141 | + parser.add_argument("pr", type=int, help="pull-request number") |
| 142 | + parser.add_argument( |
| 143 | + "--results-json", |
| 144 | + default="verification-results.json", |
| 145 | + type=Path, |
| 146 | + help="path to the JSON summary (default: %(default)s)", |
| 147 | + ) |
| 148 | + parser.add_argument( |
| 149 | + "--repo", |
| 150 | + default=os.environ.get("GH_REPO", "pulseengine/spar"), |
| 151 | + help="OWNER/NAME (default: %(default)s)", |
| 152 | + ) |
| 153 | + args = parser.parse_args() |
| 154 | + |
| 155 | + token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN") |
| 156 | + if not token: |
| 157 | + print("GH_TOKEN or GITHUB_TOKEN required", file=sys.stderr) |
| 158 | + return 2 |
| 159 | + |
| 160 | + if not args.results_json.is_file(): |
| 161 | + print(f"no {args.results_json} found; nothing to post", file=sys.stderr) |
| 162 | + return 0 |
| 163 | + |
| 164 | + results = json.loads(args.results_json.read_text()) |
| 165 | + body = render_body(results) |
| 166 | + upsert_comment(args.repo, args.pr, body, token) |
| 167 | + return 0 |
| 168 | + |
| 169 | + |
| 170 | +if __name__ == "__main__": |
| 171 | + sys.exit(main()) |
0 commit comments