Repository navigation
232 lines (215 loc) Β· 12.1 KB
/
Copy pathreview-post.yml
File metadata and controls
232 lines (215 loc) Β· 12.1 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
# Posts automated PR reviews that are produced outside GitHub Actions and
# sent here as `repository_dispatch` events (type `metro-review`), so that they
# appear as github-actions[bot] rather than as the maintainer who runs the
# reviewer. Sending a dispatch needs write access to this repo.
#
# This workflow holds no model credentials and never checks out PR code. It
# validates the payload, drops reviews of a head that is no longer current,
# then edits a single summary comment in place and adds inline comments for
# findings not posted before. It never approves or requests changes. A
# payload can also add or remove labels from a fixed allowlist, e.g. marking a
# PR the bot skipped (a dependency bot PR or a mechanical tooling update) with
# no comment at all. It can delete the bot's own comments (a whole review, or
# single findings it has withdrawn), and reply in the threads of its own
# findings. It only ever deletes or replies to comments by github-actions[bot].
name: react/metro/review-post
on:
repository_dispatch:
types: [metro-review]
permissions:
contents: read
concurrency:
group: metro-review-post-${{ github.event.client_payload.pr }}
cancel-in-progress: false
jobs:
post:
if: github.repository == 'react/metro'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
issues: write
pull-requests: write
steps:
- uses: actions/github-script@v8
with:
script: |
const zlib = require('node:zlib');
const MARKER = '<!-- metro-review-bot -->';
const BOT = 'github-actions[bot]';
// The only labels a payload may add or remove.
const LABELS = {
'Auto review: Skipped': {
color: 'ededed',
description: 'The Metro review bot skipped this PR (a dependency bot PR or a mechanical tooling update)',
},
};
// #region Validate the payload
let p = context.payload.client_payload ?? {};
if (typeof p.gz === 'string') {
p = {...p, ...JSON.parse(zlib.gunzipSync(Buffer.from(p.gz, 'base64')).toString('utf8'))};
}
const fail = msg => {
core.setFailed(`rejected payload: ${msg}`);
return null;
};
if (p.v !== 1) return fail('unsupported version');
if (!Number.isInteger(p.pr) || p.pr < 1) return fail('bad pr');
if (!/^[0-9a-f]{40}$/.test(p.head_sha ?? '')) return fail('bad head_sha');
const addLabels = Array.isArray(p.labels?.add) ? p.labels.add : [];
const removeLabels = Array.isArray(p.labels?.remove) ? p.labels.remove : [];
if ([...addLabels, ...removeLabels].some(l => !Object.hasOwn(LABELS, l))) return fail('label not allowed');
const hasSummary = p.summary != null;
if (hasSummary && (typeof p.summary !== 'string' || !p.summary.startsWith(MARKER) || p.summary.length > 60000)) {
return fail('bad summary');
}
const comments = Array.isArray(p.comments) ? p.comments : [];
const deleteIds = Array.isArray(p.delete_ids) ? p.delete_ids : [];
const replies = Array.isArray(p.replies) ? p.replies : [];
const retract = p.retract === true;
if (!hasSummary && (comments.length || deleteIds.length || replies.length || (!retract && !addLabels.length && !removeLabels.length))) {
return fail('a payload without a summary may only change labels or retract');
}
if (retract && (hasSummary || comments.length)) return fail('retract can only be combined with labels');
if (comments.length > 15) return fail('too many comments');
if (deleteIds.length > 30 || deleteIds.some(id => !/^[0-9a-f]{8}$/.test(id))) return fail('bad delete_ids');
if (replies.length > 15 || replies.some(r => !/^[0-9a-f]{8}$/.test(r?.id ?? '') || typeof r.body !== 'string' || r.body.length > 3000)) {
return fail('bad replies');
}
for (const c of comments) {
const ok =
/^[0-9a-f]{8}$/.test(c.id ?? '') &&
typeof c.path === 'string' && c.path.length < 500 && !c.path.startsWith('/') &&
Number.isInteger(c.line) && c.line > 0 &&
c.side === 'RIGHT' &&
typeof c.body === 'string' && c.body.length <= 5000;
if (!ok) return fail(`bad comment ${JSON.stringify(c).slice(0, 200)}`);
}
// Keeps @-mentions from notifying anyone. Review text is written by a
// model that has read the PR, and PR text is untrusted: a description
// or code comment could steer the review into naming arbitrary users
// or teams, and a bot that pings people on demand is a spam vector.
// Even an honest review that names a maintainer or a team would notify
// them from a bot. A zero-width joiner after the @ keeps the text
// readable while GitHub no longer treats it as a mention.
//
// Left alone: an @ preceded by a word character (e.g. an email
// address), and code (fenced blocks and inline spans) and URLs.
// Mentions there don't notify, and an invisible character would break
// suggestions, copied code and links to paths such as packages/@scope/.
// The sender does the same before dispatching, but a payload isn't
// trusted to have come from it.
const CODE_OR_URL = /(```[\s\S]*?```|~~~[\s\S]*?~~~|`[^`\n]*`|https?:\/\/[^\s<>()\]]+)/;
const defuse = s =>
s
.split(CODE_OR_URL)
.map((part, i) => (i % 2 ? part : part.replace(/(^|\W)@([A-Za-z0-9][A-Za-z0-9-]*)/g, '$1@\u200d$2')))
.join('');
// #endregion
// #region Check the PR is still at the reviewed head
const {owner, repo} = context.repo;
const {data: pr} = await github.rest.pulls.get({owner, repo, pull_number: p.pr});
if (pr.state !== 'open') return core.notice(`#${p.pr} is ${pr.state}; nothing posted`);
if (pr.head.sha !== p.head_sha) {
return core.notice(`#${p.pr} moved to ${pr.head.sha.slice(0, 7)}; stale review of ${p.head_sha.slice(0, 7)} dropped`);
}
// #endregion
// #region Labels
for (const name of addLabels) {
try {
await github.rest.issues.getLabel({owner, repo, name});
} catch (e) {
if (e.status !== 404) throw e;
try {
await github.rest.issues.createLabel({owner, repo, name, ...LABELS[name]});
} catch (createError) {
// Another run created it first.
if (createError.status !== 422) throw createError;
}
}
}
if (addLabels.length) await github.rest.issues.addLabels({owner, repo, issue_number: p.pr, labels: addLabels});
for (const name of removeLabels) {
try {
await github.rest.issues.removeLabel({owner, repo, issue_number: p.pr, name});
} catch (e) {
if (e.status !== 404) throw e;
}
}
const labelNote = [addLabels.length ? `labels added: ${addLabels.join(', ')}` : null, removeLabels.length ? `labels removed: ${removeLabels.join(', ')}` : null].filter(Boolean).join('; ');
// #endregion
// #region Retract and delete
const issueComments = await github.paginate(github.rest.issues.listComments, {owner, repo, issue_number: p.pr, per_page: 100});
const ownSummaries = issueComments.filter(c => c.user.login === BOT && c.body.startsWith(MARKER));
const reviewComments = await github.paginate(github.rest.pulls.listReviewComments, {owner, repo, pull_number: p.pr, per_page: 100});
// A finding's inline comment ends with a footer carrying its id. The
// id is read only from there, since the body itself may mention
// other findings' ids.
const findingId = c => c.body.match(/ id `([0-9a-f]{8})`<\/sub>\s*$/)?.[1];
const findingComments = reviewComments.filter(c => c.user.login === BOT && findingId(c));
const findingCommentIds = new Set(findingComments.map(c => c.id));
// The bot's own comments: its findings, and its replies in their
// threads. Other workflows also post as github-actions[bot], and
// their comments are never touched.
const own = reviewComments.filter(
c => c.user.login === BOT && (findingCommentIds.has(c.id) || findingCommentIds.has(c.in_reply_to_id)),
);
const deleted = new Set();
for (const c of own) {
const id = findingId(c);
if (retract || (id && deleteIds.includes(id))) {
await github.rest.pulls.deleteReviewComment({owner, repo, comment_id: c.id});
deleted.add(c.id);
}
}
if (retract) {
for (const c of ownSummaries) await github.rest.issues.deleteComment({owner, repo, comment_id: c.id});
return core.notice(`#${p.pr}: review retracted (${ownSummaries.length} summary and ${deleted.size} inline comment(s) deleted)${labelNote ? `; ${labelNote}` : ''}`);
}
if (!hasSummary) return core.notice(`#${p.pr}: ${labelNote}`);
// #endregion
// #region Post
// Head-side lines a comment can anchor to, per file.
const anchors = new Map();
for (const f of await github.paginate(github.rest.pulls.listFiles, {owner, repo, pull_number: p.pr, per_page: 100})) {
const lines = new Set();
let n = 0;
for (const l of (f.patch ?? '').split('\n')) {
const m = l.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
if (m) n = Number(m[1]);
else if (n && (l.startsWith('+') || l.startsWith(' '))) lines.add(n++);
}
anchors.set(f.filename, lines);
}
const existing = ownSummaries[0];
const summary = defuse(p.summary);
if (existing) {
await github.rest.issues.updateComment({owner, repo, comment_id: existing.id, body: summary});
} else {
await github.rest.issues.createComment({owner, repo, issue_number: p.pr, body: summary});
}
const remaining = own.filter(c => !deleted.has(c.id));
const posted = new Set(remaining.map(findingId).filter(Boolean));
const fresh = comments.filter(c => !posted.has(c.id) && anchors.get(c.path)?.has(c.line));
const skipped = comments.length - fresh.length;
if (fresh.length) {
await github.rest.pulls.createReview({
owner,
repo,
pull_number: p.pr,
commit_id: p.head_sha,
event: 'COMMENT',
comments: fresh.map(c => ({path: c.path, line: c.line, side: 'RIGHT', body: defuse(c.body)})),
});
}
// Replies go in the thread of the bot's own finding with that id.
let replied = 0;
for (const r of replies) {
const target = remaining.find(c => findingId(c) === r.id && c.in_reply_to_id == null);
if (!target) continue;
await github.rest.pulls.createReplyForReviewComment({owner, repo, pull_number: p.pr, comment_id: target.id, body: defuse(r.body)});
replied++;
}
const extra = [deleted.size ? `${deleted.size} deleted` : null, replied ? `${replied} replied` : null, labelNote || null].filter(Boolean).join('; ');
core.notice(`#${p.pr}: summary ${existing ? 'updated' : 'created'}, ${fresh.length} inline comment(s) posted, ${skipped} already posted or unanchorable${extra ? `; ${extra}` : ''}`);
// #endregion