lib/checks/check-review-ready.py

90 lines · 2314 bytes

 1"""Decides whether a PR is ready for maintainer review.
 2
 3Conditions: 2+ approvals from external contributors AND all CI checks passing.
 4
 5Reads:
 6  pr-meta/reviews.json       — array of {user, state} from GitHub API
 7  pr-meta/check-runs.json    — array of {status, conclusion} from GitHub API
 8  pr-meta/already-notified.txt — "true" if notification comment already exists
 9
10Writes:
11  pr-meta/action.txt         — "notify" or "skip"
12"""
13
14import json
15import os
16
17WORK_DIR = "pr-meta"
18MAINTAINER = "Lissy93"
19REQUIRED_APPROVALS = 2
20PASSING_CONCLUSIONS = {"success", "skipped", "neutral"}
21
22
23def read_json(filename):
24    """Load a JSON file from the work directory, or empty list on error."""
25    try:
26        with open(os.path.join(WORK_DIR, filename)) as f:
27            return json.load(f)
28    except Exception:
29        return []
30
31
32def count_external_approvals(reviews):
33    """Count unique non-maintainer users who approved."""
34    approvers = {
35        r["user"]
36        for r in reviews
37        if r.get("state") == "APPROVED"
38        and r.get("user", "").lower() != MAINTAINER.lower()
39    }
40    return len(approvers)
41
42
43def all_checks_passing(check_runs):
44    """Return True if every check run completed successfully."""
45    if not check_runs:
46        return False
47    return all(
48        cr.get("status") == "completed"
49        and cr.get("conclusion") in PASSING_CONCLUSIONS
50        for cr in check_runs
51    )
52
53
54def already_notified():
55    """Return True if the notification comment already exists on the PR."""
56    try:
57        with open(os.path.join(WORK_DIR, "already-notified.txt")) as f:
58            return f.read().strip().lower() == "true"
59    except Exception:
60        return False
61
62
63def write_action(action):
64    os.makedirs(WORK_DIR, exist_ok=True)
65    with open(os.path.join(WORK_DIR, "action.txt"), "w") as f:
66        f.write(action)
67
68
69def main():
70    if already_notified():
71        write_action("skip")
72        return
73
74    reviews = read_json("reviews.json")
75    approvals = count_external_approvals(reviews)
76
77    if approvals < REQUIRED_APPROVALS:
78        write_action("skip")
79        return
80
81    check_runs = read_json("check-runs.json")
82    if not all_checks_passing(check_runs):
83        write_action("skip")
84        return
85
86    write_action("notify")
87
88
89if __name__ == "__main__":
90    main()