Repository navigation
Expand file tree
/
Copy pathpr_review_side.py
More file actions
330 lines (271 loc) · 14.3 KB
/
Copy pathpr_review_side.py
File metadata and controls
330 lines (271 loc) · 14.3 KB
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
"""The review policy's side of the gate: CodeRabbit and Qodo requests, and the checks they wait on.
This is a library module and has no command line. It is apart from `pr_review.py` for a reason.
Copilot is requested through a review-request mutation. CodeRabbit and Qodo are asked by a
comment and answer in their own shapes. Keeping their reading and asking here keeps the gate's
Copilot loop the size it was. `pr_review.py` hands in the reads and the one write. So nothing here
reaches GitHub on its own, and every case can drive it with constructed payloads.
"""
from __future__ import annotations
import re
import urllib.parse
from argparse import Namespace
from collections.abc import Callable
from datetime import UTC, datetime
from subprocess import CompletedProcess
import pr_review_policy as review_policy
from pr_review_checks import (
age,
check_nodes,
check_shape,
checks_settling,
runs_open,
utc_instant,
)
from pr_review_hold import PUSHED_KEY, head_arrived, hosted_check, side_asks, side_command
from pr_review_payload import bot_entry, covering_bot
from pr_review_rounds import (
CODERABBIT_LOGIN,
QODO_LOGIN,
commit_oid,
page_flag,
qodo_comment,
reviewed_heads,
reviewer_nodes,
)
from pr_review_summary import clean_pass, rabbit_on_head
COMMENT_PATH = ("addComment", "commentEdge", "node")
SIDE_LOGINS = {"coderabbit": CODERABBIT_LOGIN, "qodo": QODO_LOGIN}
PUSHED_JQ = 'map(select(.after == "{}") | .timestamp) | max // empty'
def checks_hold(pr: dict, now: datetime, grace: float, stall: float) -> str:
"""What holds a review back on the head's checks, empty where nothing does.
FAILURE where a check finished without passing, and a stuck shape's own name where one sits
in a shape no wait clears. PENDING where one is settling, a run on the head is open, or none
posted inside the grace after the head arrived. The open run counts as `held_checks_open`
counts it, since a run's later jobs enter the rollup only as their `needs:` finish. A hosted
reviewer's own check is left out, since the review it stands for is the one being held. A
workflow run it posts from still counts while open, since a run names no reviewer it belongs to.
DIRTY where no check has posted on a conflicted head, which runs no `pull_request` workflow.
"""
nodes = [n for n in check_nodes(pr) if not hosted_check(n)]
if any(n.get("unreadable") for n in nodes):
return "UNREAD"
if not nodes and pr.get("mergeStateStatus") == "DIRTY":
return "DIRTY"
shapes = {check_shape(n, now, grace, stall) for n in nodes}
if "FAILED" in shapes:
return "FAILURE"
if stuck := sorted(shapes - {"", "RUNNING_LONG"}):
return stuck[0]
if runs_open(pr) or checks_settling(nodes, now, grace, stall):
return "PENDING"
since = age(head_arrived(pr), now) if head_arrived(pr) and not nodes else None
return "PENDING" if not nodes and (since is None or since <= grace) else ""
def pushed(pr: dict, rest: Callable[[str, str], CompletedProcess]) -> dict:
"""`pr` carrying when GitHub logged the push that left its head on its branch, empty if unread.
The log stamps a push on receipt, where a commit's date is its author's clock, which can run
behind or ahead. The newest entry ending at the head counts, so a force-push back to it does.
"""
head, branch = pr.get("headRefOid") or "", pr.get("headRefName") or ""
where = (pr.get("headRepository") or {}).get("nameWithOwner")
placed = where and branch and re.fullmatch(r"[0-9a-f]{40,64}", head)
query = urllib.parse.urlencode({"ref": f"refs/heads/{branch}", "per_page": 100})
proc = rest(f"repos/{where}/activity?{query}", PUSHED_JQ.format(head)) if placed else None
return {**pr, PUSHED_KEY: proc.stdout.strip() if proc and proc.returncode == 0 else ""}
def push_log(rest: Callable[[str, str], CompletedProcess]) -> Callable[[dict], dict]:
"""`pushed` keeping each head's stamp once read, for a poll that judges one head many times.
The stamp does not move while the head holds. A read that failed or found no entry is not
kept, so a later poll still asks. The log can record a push after the poll began.
"""
found: dict[tuple, str] = {}
def read(pr: dict) -> dict:
where = (pr.get("headRepository") or {}).get("nameWithOwner")
key = (where, pr.get("headRefName"), pr.get("headRefOid"))
if key in found:
return {**pr, PUSHED_KEY: found[key]}
stamped = pushed(pr, rest)
if stamped[PUSHED_KEY]:
found[key] = stamped[PUSHED_KEY]
return stamped
return read
def side_asked_on_head(pr: dict, body: str) -> bool:
"""Whether a request `body` was posted since the head was pushed, both stamps GitHub's own.
No commit date, backdated or ahead, moves it. An ask in the push's own second counts as on it.
"""
since = utc_instant(pr.get(PUSHED_KEY) or "")
asked = (utc_instant(n.get("createdAt") or "") for n in side_asks(pr, body))
return since is not None and any(at is not None and at >= since for at in asked)
def unasked(pr: dict, name: str, body: str, lines: list[str]) -> bool:
"""Whether `name` is still to be asked, never where an unread push hides an ask on the head."""
placed = utc_instant(pr.get(PUSHED_KEY) or "") is not None or not side_asks(pr, body)
if not placed and not side_answered(pr, name):
lines.append(f"note: the head's push could not be read, so {name} was not asked")
return placed and not side_answered(pr, name) and not side_asked_on_head(pr, body)
def side_rounds(pr: dict, name: str, body: str) -> int:
"""Rounds asked of or run by `name` on this pull request, whichever count is larger.
CodeRabbit's distinct reviewed heads count too, and a commit no review of its covers that
`clean_pass` reads. Qodo edits one standing comment, so it counts once that comment exists.
"""
asked = len(side_asks(pr, body))
if name != "coderabbit":
return max(asked, 1 if qodo_comment(pr) else 0)
seen = {commit_oid(n) for n in reviewer_nodes(pr, "reviews", CODERABBIT_LOGIN)} | {""}
return max(asked, reviewed_heads(pr, CODERABBIT_LOGIN) + (clean_pass(pr) not in seen))
def side_answered(pr: dict, name: str) -> bool:
"""Whether `name` has reviewed the current head, known for CodeRabbit alone.
CodeRabbit answers with a formal review on the head's commit or a clean pass `clean_pass` reads
on it. Qodo's one standing comment names no head, so a request is its only per-head record.
"""
return name == "coderabbit" and rabbit_on_head(pr)
def side_reviewers(pr: dict) -> list[tuple[str, review_policy.BotPolicy, str]]:
"""Each comment-triggered reviewer the payload's policy covers this base for, with its request.
Empty where no policy rides the payload, since a reviewer the gate never named stays unnamed.
"""
found = []
for name in SIDE_LOGINS:
bot = covering_bot(pr, name)
if bot is not None:
found.append((name, bot, side_command(name, bot.command)))
return found
def asks_any(pr: dict) -> bool:
"""Whether the policy on `pr` may ask any comment-triggered reviewer on this base."""
return any(bot.requests() for _, bot, _ in side_reviewers(pr))
def post_comment(
send: Callable[..., dict], dig: Callable[..., dict], body: str
) -> tuple[dict, bool]:
"""Post one conversation comment, returning the created node and whether it is confirmed.
`send` makes the mutation and `dig` reads the node off its response. Only a node carrying a URL
and exactly `body` confirms the write, and a caller treats any other as possibly landed.
"""
made = dig(send(body=body), *COMMENT_PATH)
return made, bool(made.get("url")) and (made.get("body") or "") == body
def request_side_reviews(
read: Callable[[], dict],
await_green: Callable[[], str],
post: Callable[[str], tuple[dict, bool]],
phase: str,
) -> list[str]:
"""Ask each comment-triggered reviewer the policy asks explicitly in `phase`, once per head.
`phase` is the `when` value this call serves, so an on-open ask never waits behind a check wait.
A reviewer that answered or was asked since the push is skipped before any wait, and judged
again on a fresh read after one. So a request that a concurrent session sent during the wait is
seen. Nothing is sent where its cap is spent, or where an ask is on record and the push unread.
Nor where a cap applies and the comment window is cut, since the rounds spent cannot then be
counted. The merge never waits on these reviewers, so a held ask is a note rather than an exit.
`post` sends one comment and returns `post_comment`'s answer, and an unconfirmed one ends the
run, since it may have landed. A pull request no longer open is asked nothing, since a peer can
merge or close it while `wait` polls.
"""
lines: list[str] = []
held: str | None = None
pr = read()
if pr.get("state", "OPEN") != "OPEN":
return lines
for name, bot, body in side_reviewers(pr):
if not bot.requests() or bot.when != phase:
continue
if not unasked(pr, name, body, lines):
continue
if not bot.rounds_left(side_rounds(pr, name, body)):
lines.append(
f"note: the review policy allows {name} no further round, so none was asked"
)
continue
if bot.capped() and page_flag(pr, "comments", "hasPreviousPage"):
lines.append(
f"note: {name}'s rounds are capped and the comments run past the window, so its "
"rounds cannot be counted and none was asked"
)
continue
if bot.waits_for_checks():
if held is None:
held, pr = await_green(), read()
if pr.get("state", "OPEN") != "OPEN":
return lines
if held:
lines.append(
f"note: {name} is asked only once the head's checks pass, and they read {held}"
)
continue
if not unasked(pr, name, body, lines):
continue
made, confirmed = post(body)
if not confirmed:
raise SystemExit(
f"the request to {name} returned no URL or a different body, so it is "
"unconfirmed: inspect the conversation before asking again, since it may have landed"
)
lines.append(f"auto-request: asked {name} for a round on the current head ({made['url']})")
return lines
def copilot_policy(pr: dict | None, requested: bool) -> review_policy.BotPolicy | None:
"""The policy's Copilot entry off `pr`, None where no policy rides it.
A request can already be pending where the policy says Copilot is only asked explicitly. That
draws a note, since unless a session or an earlier `wait` sent it, an automatic trigger is on.
"""
copilot = bot_entry(pr, "copilot")
if copilot is not None and copilot.trigger == "explicit" and requested:
print(
"note: a Copilot review was already requested when this wait started, while the "
"review policy says Copilot is requested explicitly. If neither a session nor an "
"earlier wait sent it, an automatic trigger is still on, in the account's Copilot "
"settings or a ruleset"
)
return copilot
def holds_for_checks(copilot: review_policy.BotPolicy | None, forced: bool) -> bool:
"""Whether the Copilot request waits for green checks, which `--request` skips."""
return copilot is not None and copilot.waits_for_checks() and not forced
def await_green(
read: Callable[[], dict], start: float, args: Namespace, backoff: Callable[..., dict]
) -> str:
"""Poll the head's checks with `backoff` until none is settling, and name what holds a review.
Empty once they pass. Otherwise what `checks_hold` reads, PENDING where `args.timeout` ran out
first. So a failed build is never reviewed before it is fixed.
"""
windows = (args.check_grace, args.check_stall)
def holding(p: dict) -> bool:
return checks_hold(p, datetime.now(UTC), *windows) == "PENDING"
polled = backoff(read(), read, holding, start, args.timeout)
return checks_hold(polled, datetime.now(UTC), *windows)
def ask(
read: Callable[[], dict],
args: Namespace,
send: Callable[..., dict],
dig: Callable[..., dict],
pr: dict | bool,
rest: Callable[[str, str], CompletedProcess],
phase: str,
poll: Callable[[], str] | None = None,
) -> bool:
"""Send and print the `phase` requests, where `pr` is a payload whose policy asks any.
Returns whether any request was sent, since a sent one moves the registration grace's anchor.
`poll` waits out the checks an after-checks ask waits on, as `await_green` does on the wait's
own clock. So a head whose checks outlast the Copilot poll is still asked once they pass, and
the timeout bounds the wait. Without one they are read once, for a wait that stops rather than
polls, so the ask holds no wait that stops without polling.
"""
if not isinstance(pr, dict) or not asks_any(pr):
return False
def post(body: str) -> tuple[dict, bool]:
return post_comment(send, dig, body)
def checks_now() -> str:
return checks_hold(read(), datetime.now(UTC), args.check_grace, args.check_stall)
lines = request_side_reviews(lambda: pushed(read(), rest), poll or checks_now, post, phase)
for line in lines:
print(line)
return any(line.startswith("auto-request:") for line in lines)
def checks_note(held: str) -> str:
return (
"note: the review policy requests Copilot only once the head's checks pass, and they "
f"read {held}, so this wait requested nothing and polls no review"
)
def checks_status(held: str) -> int:
"""Print the status line for a head whose checks held the Copilot request back, and its exit."""
then, code = {
"PENDING": ("wait again once they conclude", 30),
"FAILURE": ("fix the build and push", 40),
"DIRTY": ("resolve the conflict with the base, since a conflicted head runs no checks", 44),
}.get(held, ("read the checks, since that shape is one no wait clears", 44))
print(
f"status=CHECKS_BEFORE_REVIEW the head's checks read {held}, and the review policy "
f"holds the review request until they pass: {then}"
)
return code