@artieeez/cf-plugin-github 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +144 -2
- package/dist/ci.d.ts +93 -0
- package/dist/ci.d.ts.map +1 -0
- package/dist/ci.js +141 -0
- package/dist/ci.js.map +1 -0
- package/dist/diff.d.ts +7 -0
- package/dist/diff.d.ts.map +1 -0
- package/dist/diff.js +39 -0
- package/dist/diff.js.map +1 -0
- package/dist/index.d.ts +539 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1021 -0
- package/dist/index.js.map +1 -0
- package/dist/setup.d.ts +40 -0
- package/dist/setup.d.ts.map +1 -0
- package/dist/setup.js +73 -0
- package/dist/setup.js.map +1 -0
- package/package.json +42 -3
- package/src/ci.ts +228 -0
- package/src/diff.ts +35 -0
- package/src/index.ts +1102 -0
- package/src/setup.ts +99 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1021 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { createAppAuth } from '@octokit/auth-app';
|
|
3
|
+
import { Octokit } from '@octokit/rest';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { AGENT_TEXT_MAX, commandOf, cut, textOf, wdProblems } from '@artieeez/cf-core';
|
|
6
|
+
import { setting } from '@artieeez/cf-sdk';
|
|
7
|
+
import { definePlugin, slot, } from '@artieeez/cf-sdk/plugin';
|
|
8
|
+
import { classifyCi, isCiResult } from "./ci.js";
|
|
9
|
+
import { commentableLines } from "./diff.js";
|
|
10
|
+
export * from "./ci.js";
|
|
11
|
+
export * from "./diff.js";
|
|
12
|
+
export { setting } from '@artieeez/cf-sdk';
|
|
13
|
+
// ---- instance config (github-plugin door 2) ----
|
|
14
|
+
const REPO_SLUG = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
|
|
15
|
+
const digits = z
|
|
16
|
+
.union([z.string(), z.number().int().nonnegative()])
|
|
17
|
+
.transform(String)
|
|
18
|
+
.pipe(z.string().regex(/^\d+$/, 'digits, e.g. 1001'));
|
|
19
|
+
const Config = z.strictObject({
|
|
20
|
+
appId: digits,
|
|
21
|
+
installationId: digits,
|
|
22
|
+
/** the App's slug: its bot is `<appSlug>[bot]`, whose deliveries `normalize` drops (door 3, AD-075) */
|
|
23
|
+
appSlug: z.string().regex(/^[a-z0-9][a-z0-9-]*$/, 'the App slug, e.g. cf-factory'),
|
|
24
|
+
/** from env (`GITHUB_REPOS`) a comma list: split, trimmed, empty items dropped */
|
|
25
|
+
repos: z.preprocess((v) => (typeof v === 'string' ? v.split(',').map((s) => s.trim()).filter((s) => s !== '') : v), z.array(z.string().regex(REPO_SLUG, 'owner/name, e.g. org/api')).min(1)),
|
|
26
|
+
});
|
|
27
|
+
export const GITHUB_API_URL = 'https://api.github.com';
|
|
28
|
+
export const GITHUB_GIT_URL = 'https://github.com';
|
|
29
|
+
const apiUrl = () => process.env['CF_GITHUB_API_URL'] || GITHUB_API_URL;
|
|
30
|
+
const gitUrl = () => process.env['CF_GITHUB_GIT_URL'] || GITHUB_GIT_URL;
|
|
31
|
+
// ---- events (door 1) ----
|
|
32
|
+
const login = z.strictObject({ login: z.string() });
|
|
33
|
+
const prFields = {
|
|
34
|
+
repo: z.string(),
|
|
35
|
+
number: z.number().int(),
|
|
36
|
+
url: z.string(),
|
|
37
|
+
title: z.string(),
|
|
38
|
+
draft: z.boolean(),
|
|
39
|
+
head: z.strictObject({ ref: z.string(), sha: z.string() }),
|
|
40
|
+
base: z.strictObject({ ref: z.string() }),
|
|
41
|
+
user: login.nullable(),
|
|
42
|
+
};
|
|
43
|
+
const prEvent = z.strictObject(prFields);
|
|
44
|
+
const prClosedEvent = z.strictObject({ ...prFields, merged: z.boolean() });
|
|
45
|
+
/** door 1 (github-pr-sync): new commits on the PR; `before` is the head sha before the push */
|
|
46
|
+
const prSynchronizedEvent = z.strictObject({ ...prFields, before: z.string() });
|
|
47
|
+
/** The reviewer or commenter: GitHub's `author_association` verbatim, and whether the account is a bot. */
|
|
48
|
+
const actor = z.strictObject({ login: z.string(), association: z.string(), bot: z.boolean() });
|
|
49
|
+
const text = z.string().max(AGENT_TEXT_MAX);
|
|
50
|
+
/** door 1: PR fields at the top level, `url` the PR's, as in `github.pr.*`, so `$.data.url` finds a run */
|
|
51
|
+
const reviewEvent = z.strictObject({
|
|
52
|
+
repo: z.string(),
|
|
53
|
+
number: z.number().int(),
|
|
54
|
+
url: z.string(),
|
|
55
|
+
headSha: z.string(),
|
|
56
|
+
author: login.nullable(),
|
|
57
|
+
review: z.strictObject({
|
|
58
|
+
id: z.number().int(),
|
|
59
|
+
state: z.enum(['approved', 'changes_requested', 'commented']),
|
|
60
|
+
body: text,
|
|
61
|
+
commitId: z.string(),
|
|
62
|
+
url: z.string(),
|
|
63
|
+
stale: z.boolean(),
|
|
64
|
+
}),
|
|
65
|
+
user: actor,
|
|
66
|
+
byAuthor: z.boolean(),
|
|
67
|
+
});
|
|
68
|
+
const commentEvent = z.strictObject({
|
|
69
|
+
repo: z.string(),
|
|
70
|
+
number: z.number().int(),
|
|
71
|
+
url: z.string(),
|
|
72
|
+
author: login.nullable(),
|
|
73
|
+
comment: z.strictObject({
|
|
74
|
+
id: z.number().int(),
|
|
75
|
+
kind: z.enum(['issue', 'review']),
|
|
76
|
+
body: text,
|
|
77
|
+
url: z.string(),
|
|
78
|
+
path: z.string().nullable(),
|
|
79
|
+
line: z.number().int().nullable(),
|
|
80
|
+
reviewId: z.number().int().nullable(),
|
|
81
|
+
inReplyTo: z.number().int().nullable(),
|
|
82
|
+
}),
|
|
83
|
+
user: actor,
|
|
84
|
+
byAuthor: z.boolean(),
|
|
85
|
+
command: z.string().nullable(),
|
|
86
|
+
text: text.nullable(),
|
|
87
|
+
});
|
|
88
|
+
export const EVENTS = {
|
|
89
|
+
'github.checks.completed': z.strictObject({
|
|
90
|
+
repo: z.string(),
|
|
91
|
+
sha: z.string(),
|
|
92
|
+
suiteId: z.number().int(),
|
|
93
|
+
app: z.strictObject({ id: z.number().int(), slug: z.string() }),
|
|
94
|
+
conclusion: z.string().nullable(),
|
|
95
|
+
headBranch: z.string().nullable(),
|
|
96
|
+
pullRequests: z.array(z.number().int()),
|
|
97
|
+
}),
|
|
98
|
+
'github.pr.opened': prEvent,
|
|
99
|
+
'github.pr.closed': prClosedEvent,
|
|
100
|
+
'github.pr.merged': prClosedEvent,
|
|
101
|
+
'github.pr.synchronized': prSynchronizedEvent,
|
|
102
|
+
'github.pr.reopened': prEvent,
|
|
103
|
+
'github.pr.ready': prEvent,
|
|
104
|
+
'github.pr.review.submitted': reviewEvent,
|
|
105
|
+
'github.pr.comment.created': commentEvent,
|
|
106
|
+
};
|
|
107
|
+
const isRecord = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
108
|
+
const rec = (v) => (isRecord(v) ? v : {});
|
|
109
|
+
const str = (v) => (typeof v === 'string' ? v : '');
|
|
110
|
+
const num = (v) => (typeof v === 'number' ? v : 0);
|
|
111
|
+
const strOrNull = (v) => (typeof v === 'string' ? v : null);
|
|
112
|
+
const intOrNull = (v) => (typeof v === 'number' && Number.isInteger(v) ? v : null);
|
|
113
|
+
/** The PR author's login, or null when GitHub sends no user (a deleted account). */
|
|
114
|
+
const authorOf = (p) => {
|
|
115
|
+
const l = rec(p['user'])['login'];
|
|
116
|
+
return typeof l === 'string' ? { login: l } : null;
|
|
117
|
+
};
|
|
118
|
+
const actorOf = (u, association) => ({
|
|
119
|
+
login: str(u['login']),
|
|
120
|
+
association: str(association),
|
|
121
|
+
bot: u['type'] === 'Bot',
|
|
122
|
+
});
|
|
123
|
+
const REVIEW_STATES = new Set(['approved', 'changes_requested', 'commented']);
|
|
124
|
+
function pr(repo, p) {
|
|
125
|
+
const user = rec(p['user']);
|
|
126
|
+
return {
|
|
127
|
+
repo,
|
|
128
|
+
number: num(p['number']),
|
|
129
|
+
url: str(p['html_url']),
|
|
130
|
+
title: str(p['title']),
|
|
131
|
+
draft: p['draft'] === true,
|
|
132
|
+
head: { ref: str(rec(p['head'])['ref']), sha: str(rec(p['head'])['sha']) },
|
|
133
|
+
base: { ref: str(rec(p['base'])['ref']) },
|
|
134
|
+
user: typeof user['login'] === 'string' ? { login: user['login'] } : null,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
/** Webhook -> door 1 events; another installation, a repo outside `repos` and other kinds give none. */
|
|
138
|
+
export function normalize(req, config) {
|
|
139
|
+
const body = req.body;
|
|
140
|
+
if (!isRecord(body))
|
|
141
|
+
return [];
|
|
142
|
+
if (String(rec(body['installation'])['id'] ?? '') !== config.installationId)
|
|
143
|
+
return [];
|
|
144
|
+
const repo = str(rec(body['repository'])['full_name']);
|
|
145
|
+
if (!config.repos.includes(repo))
|
|
146
|
+
return [];
|
|
147
|
+
const kind = req.headers['x-github-event'];
|
|
148
|
+
// the instance's own App caused it: a workflow never sees its own events (door 3, AD-075).
|
|
149
|
+
// Not a check suite: its sender is whoever pushed the sha, and the App pushes the factory's
|
|
150
|
+
// branches, so dropping it would hide the CI verdict of every push the factory makes.
|
|
151
|
+
if (kind !== 'check_suite' && str(rec(body['sender'])['login']) === `${config.appSlug}[bot]`)
|
|
152
|
+
return [];
|
|
153
|
+
if (kind === 'pull_request_review' && body['action'] === 'submitted') {
|
|
154
|
+
const p = rec(body['pull_request']);
|
|
155
|
+
const r = rec(body['review']);
|
|
156
|
+
const state = str(r['state']).toLowerCase();
|
|
157
|
+
if (!REVIEW_STATES.has(state))
|
|
158
|
+
return [];
|
|
159
|
+
const author = authorOf(p);
|
|
160
|
+
const user = actorOf(rec(r['user']), r['author_association']);
|
|
161
|
+
const headSha = str(rec(p['head'])['sha']);
|
|
162
|
+
const commitId = str(r['commit_id']);
|
|
163
|
+
return [
|
|
164
|
+
{
|
|
165
|
+
type: 'github.pr.review.submitted',
|
|
166
|
+
data: {
|
|
167
|
+
repo,
|
|
168
|
+
number: num(p['number']),
|
|
169
|
+
url: str(p['html_url']),
|
|
170
|
+
headSha,
|
|
171
|
+
author,
|
|
172
|
+
review: { id: num(r['id']), state, body: cut(str(r['body']), AGENT_TEXT_MAX), commitId, url: str(r['html_url']), stale: commitId !== headSha },
|
|
173
|
+
user,
|
|
174
|
+
byAuthor: author !== null && author.login === user.login,
|
|
175
|
+
},
|
|
176
|
+
},
|
|
177
|
+
];
|
|
178
|
+
}
|
|
179
|
+
if (kind === 'issue_comment' && body['action'] === 'created') {
|
|
180
|
+
const issue = rec(body['issue']);
|
|
181
|
+
if (!isRecord(issue['pull_request']))
|
|
182
|
+
return [];
|
|
183
|
+
const c = rec(body['comment']);
|
|
184
|
+
return [commentEventOf(repo, num(issue['number']), str(issue['html_url']), authorOf(issue), c, 'issue')];
|
|
185
|
+
}
|
|
186
|
+
if (kind === 'pull_request_review_comment' && body['action'] === 'created') {
|
|
187
|
+
const p = rec(body['pull_request']);
|
|
188
|
+
const c = rec(body['comment']);
|
|
189
|
+
return [commentEventOf(repo, num(p['number']), str(p['html_url']), authorOf(p), c, 'review')];
|
|
190
|
+
}
|
|
191
|
+
if (kind === 'check_suite' && body['action'] === 'completed') {
|
|
192
|
+
const suite = rec(body['check_suite']);
|
|
193
|
+
const app = rec(suite['app']);
|
|
194
|
+
const prs = Array.isArray(suite['pull_requests']) ? suite['pull_requests'] : [];
|
|
195
|
+
return [
|
|
196
|
+
{
|
|
197
|
+
type: 'github.checks.completed',
|
|
198
|
+
data: {
|
|
199
|
+
repo,
|
|
200
|
+
sha: str(suite['head_sha']),
|
|
201
|
+
suiteId: num(suite['id']),
|
|
202
|
+
app: { id: num(app['id']), slug: str(app['slug']) },
|
|
203
|
+
conclusion: strOrNull(suite['conclusion']),
|
|
204
|
+
headBranch: strOrNull(suite['head_branch']),
|
|
205
|
+
pullRequests: prs.map((p) => num(rec(p)['number'])),
|
|
206
|
+
},
|
|
207
|
+
},
|
|
208
|
+
];
|
|
209
|
+
}
|
|
210
|
+
if (kind === 'pull_request') {
|
|
211
|
+
const p = rec(body['pull_request']);
|
|
212
|
+
if (body['action'] === 'opened')
|
|
213
|
+
return [{ type: 'github.pr.opened', data: pr(repo, p) }];
|
|
214
|
+
if (body['action'] === 'closed') {
|
|
215
|
+
const data = { ...pr(repo, p), merged: p['merged'] === true };
|
|
216
|
+
const closed = { type: 'github.pr.closed', data };
|
|
217
|
+
return data.merged ? [closed, { type: 'github.pr.merged', data }] : [closed];
|
|
218
|
+
}
|
|
219
|
+
// github-pr-sync: new commits, a reopen and a draft marked ready (door 1)
|
|
220
|
+
if (body['action'] === 'synchronize')
|
|
221
|
+
return [{ type: 'github.pr.synchronized', data: { ...pr(repo, p), before: str(body['before']) } }];
|
|
222
|
+
if (body['action'] === 'reopened')
|
|
223
|
+
return [{ type: 'github.pr.reopened', data: pr(repo, p) }];
|
|
224
|
+
if (body['action'] === 'ready_for_review')
|
|
225
|
+
return [{ type: 'github.pr.ready', data: { ...pr(repo, p), draft: false } }];
|
|
226
|
+
}
|
|
227
|
+
return [];
|
|
228
|
+
}
|
|
229
|
+
function commentEventOf(repo, number, url, author, c, kind) {
|
|
230
|
+
const full = str(c['body']);
|
|
231
|
+
const user = actorOf(rec(c['user']), c['author_association']);
|
|
232
|
+
const rest = textOf(full);
|
|
233
|
+
return {
|
|
234
|
+
type: 'github.pr.comment.created',
|
|
235
|
+
data: {
|
|
236
|
+
repo,
|
|
237
|
+
number,
|
|
238
|
+
url,
|
|
239
|
+
author,
|
|
240
|
+
comment: {
|
|
241
|
+
id: num(c['id']),
|
|
242
|
+
kind,
|
|
243
|
+
body: cut(full, AGENT_TEXT_MAX),
|
|
244
|
+
url: str(c['html_url']),
|
|
245
|
+
path: kind === 'review' ? strOrNull(c['path']) : null,
|
|
246
|
+
line: kind === 'review' ? intOrNull(c['line']) : null,
|
|
247
|
+
reviewId: kind === 'review' ? intOrNull(c['pull_request_review_id']) : null,
|
|
248
|
+
inReplyTo: kind === 'review' ? intOrNull(c['in_reply_to_id']) : null,
|
|
249
|
+
},
|
|
250
|
+
user,
|
|
251
|
+
byAuthor: author !== null && author.login === user.login,
|
|
252
|
+
command: commandOf(full),
|
|
253
|
+
text: rest === null ? null : cut(rest, AGENT_TEXT_MAX),
|
|
254
|
+
},
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
/** `X-Hub-Signature-256`: `sha256=` and the hex HMAC-SHA256 of the raw body under the webhook secret. */
|
|
258
|
+
export function verify(rawBody, signature, secret) {
|
|
259
|
+
if (signature === undefined || secret === undefined || !/^sha256=[0-9a-f]{64}$/i.test(signature))
|
|
260
|
+
return false;
|
|
261
|
+
const expected = createHmac('sha256', secret).update(rawBody).digest();
|
|
262
|
+
const given = Buffer.from(signature.slice('sha256='.length), 'hex');
|
|
263
|
+
return given.length === expected.length && timingSafeEqual(given, expected);
|
|
264
|
+
}
|
|
265
|
+
// ---- the server's action (AD-049) ----
|
|
266
|
+
/** Pages of 100 workflow runs `github.ci.check` reads for a sha (door 6). */
|
|
267
|
+
export const WORKFLOW_RUN_PAGES = 10;
|
|
268
|
+
/**
|
|
269
|
+
* App-authenticated clients per instance, kept for each `fetch` (the server's is one for the
|
|
270
|
+
* process, a test's fake is its own): `@octokit/auth-app` then reuses its installation token.
|
|
271
|
+
*/
|
|
272
|
+
const clients = new WeakMap();
|
|
273
|
+
function appClient(ctx) {
|
|
274
|
+
let cache = clients.get(ctx.fetch);
|
|
275
|
+
if (cache === undefined)
|
|
276
|
+
clients.set(ctx.fetch, (cache = new Map()));
|
|
277
|
+
const privateKey = ctx.secrets['GITHUB_APP_PRIVATE_KEY'] ?? '';
|
|
278
|
+
const key = `${apiUrl()}|${ctx.config.appId}|${ctx.config.installationId}|${privateKey}`;
|
|
279
|
+
let client = cache.get(key);
|
|
280
|
+
if (client === undefined) {
|
|
281
|
+
client = new Octokit({
|
|
282
|
+
authStrategy: createAppAuth,
|
|
283
|
+
auth: { appId: ctx.config.appId, privateKey, installationId: ctx.config.installationId },
|
|
284
|
+
baseUrl: apiUrl(),
|
|
285
|
+
request: { fetch: ctx.fetch },
|
|
286
|
+
userAgent: 'code-factory',
|
|
287
|
+
});
|
|
288
|
+
cache.set(key, client);
|
|
289
|
+
}
|
|
290
|
+
return client;
|
|
291
|
+
}
|
|
292
|
+
/** A failed Octokit request as `GitHub <METHOD> <path> answered <status>: <message>`. */
|
|
293
|
+
function failure(method, path, err) {
|
|
294
|
+
const status = err.status;
|
|
295
|
+
if (status === undefined)
|
|
296
|
+
return err instanceof Error ? err : new Error(String(err));
|
|
297
|
+
return new Error(`GitHub ${method} ${path} answered ${status}: ${cut(err instanceof Error ? err.message : String(err), 300)}`);
|
|
298
|
+
}
|
|
299
|
+
/** The permissions a minted token may carry (door 2, AD-072), and its default. */
|
|
300
|
+
export const TOKEN_PERMISSIONS = ['contents', 'pull_requests', 'checks', 'actions', 'statuses', 'issues'];
|
|
301
|
+
const DEFAULT_PERMISSIONS = { contents: 'write', pull_requests: 'write' };
|
|
302
|
+
function actions(ctx) {
|
|
303
|
+
return {
|
|
304
|
+
/**
|
|
305
|
+
* An installation token for `repo` only, minted with the App key (door 2, AD-072): pushes and
|
|
306
|
+
* PRs made with it are the App's bot's. A repo outside `repos`, or a permission outside door 2,
|
|
307
|
+
* is refused before any request.
|
|
308
|
+
*/
|
|
309
|
+
async token(a) {
|
|
310
|
+
if (!ctx.config.repos.includes(a.repo))
|
|
311
|
+
throw new Error(`repo ${a.repo} is not in this instance's repos`);
|
|
312
|
+
const permissions = a.permissions ?? DEFAULT_PERMISSIONS;
|
|
313
|
+
if (!isRecord(permissions))
|
|
314
|
+
throw new Error('permissions must be an object');
|
|
315
|
+
// GitHub reads no permissions as every permission the App holds: a token always names its own
|
|
316
|
+
if (Object.keys(permissions).length === 0)
|
|
317
|
+
throw new Error(`permissions must name at least one of ${TOKEN_PERMISSIONS.join(', ')}`);
|
|
318
|
+
for (const [key, level] of Object.entries(permissions)) {
|
|
319
|
+
if (!TOKEN_PERMISSIONS.includes(key)) {
|
|
320
|
+
throw new Error(`permission "${key}" is not one of ${TOKEN_PERMISSIONS.join(', ')}`);
|
|
321
|
+
}
|
|
322
|
+
if (level !== 'read' && level !== 'write')
|
|
323
|
+
throw new Error(`permission ${key}: "${String(level)}" is not read or write`);
|
|
324
|
+
}
|
|
325
|
+
const name = a.repo.split('/')[1];
|
|
326
|
+
const path = `/app/installations/${ctx.config.installationId}/access_tokens`;
|
|
327
|
+
try {
|
|
328
|
+
const r = await appClient(ctx).request('POST /app/installations/{installation_id}/access_tokens', {
|
|
329
|
+
installation_id: Number(ctx.config.installationId),
|
|
330
|
+
repositories: [name],
|
|
331
|
+
permissions,
|
|
332
|
+
});
|
|
333
|
+
return { token: r.data.token, expiresAt: r.data.expires_at };
|
|
334
|
+
}
|
|
335
|
+
catch (err) {
|
|
336
|
+
throw failure('POST', path, err);
|
|
337
|
+
}
|
|
338
|
+
},
|
|
339
|
+
/** an issue comment on PR `number` of `repo`, as the instance's App; a repo outside `repos` is refused */
|
|
340
|
+
async comment(a) {
|
|
341
|
+
if (!ctx.config.repos.includes(a.repo))
|
|
342
|
+
throw new Error(`repo ${a.repo} is not in this instance's repos`);
|
|
343
|
+
const [owner, repo] = a.repo.split('/');
|
|
344
|
+
try {
|
|
345
|
+
const r = await appClient(ctx).rest.issues.createComment({ owner, repo, issue_number: a.number, body: a.body });
|
|
346
|
+
return { id: r.data.id, url: r.data.html_url };
|
|
347
|
+
}
|
|
348
|
+
catch (err) {
|
|
349
|
+
throw failure('POST', `/repos/${a.repo}/issues/${a.number}/comments`, err);
|
|
350
|
+
}
|
|
351
|
+
},
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
/** GitHub's status, when GitHub answered: Octokit reports a request that never got an answer as 500 with no response. */
|
|
355
|
+
const statusOf = (err) => {
|
|
356
|
+
const e = err;
|
|
357
|
+
return e.response === undefined ? undefined : e.status;
|
|
358
|
+
};
|
|
359
|
+
const messageOf = (err) => cut(err instanceof Error ? err.message : String(err), 300);
|
|
360
|
+
/**
|
|
361
|
+
* The server's App key works (health-ready AC 30): a fresh installation token is minted. `401` is
|
|
362
|
+
* a key GitHub rejects and `404` an installation it does not know, both fatal; anything else is not.
|
|
363
|
+
*/
|
|
364
|
+
async function checkApp(ctx) {
|
|
365
|
+
// the server aborts a check past its timeout: the request ends with it
|
|
366
|
+
const fetch = ((input, init) => ctx.fetch(input, { ...init, signal: ctx.signal }));
|
|
367
|
+
try {
|
|
368
|
+
const client = appClient({ ...ctx, fetch });
|
|
369
|
+
await client.auth({ type: 'installation', refresh: true });
|
|
370
|
+
const slug = (await client.request('GET /app')).data?.slug ?? '';
|
|
371
|
+
if (slug !== ctx.config.appSlug) {
|
|
372
|
+
return { ok: false, reason: `config.appSlug "${ctx.config.appSlug}" is not this App (GET /app says "${slug}")`, fatal: true };
|
|
373
|
+
}
|
|
374
|
+
return { ok: true };
|
|
375
|
+
}
|
|
376
|
+
catch (err) {
|
|
377
|
+
const status = statusOf(err);
|
|
378
|
+
if (status === 401)
|
|
379
|
+
return { ok: false, reason: 'GITHUB_APP_PRIVATE_KEY rejected by GitHub (401)', fatal: true };
|
|
380
|
+
if (status === 404)
|
|
381
|
+
return { ok: false, reason: `installation ${ctx.config.installationId} not found (404)`, fatal: true };
|
|
382
|
+
return { ok: false, reason: status !== undefined ? `GitHub answered ${status}` : `GitHub unreachable: ${messageOf(err)}` };
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* Validates `github.repo`, `github.branch`, and `github.label` settings against the bound GitHub
|
|
387
|
+
* App installation at worker register time (github-helpers door 3, AD-067).
|
|
388
|
+
*/
|
|
389
|
+
async function checkSettings(ctx, values) {
|
|
390
|
+
if (values.length === 0)
|
|
391
|
+
return [];
|
|
392
|
+
const problems = [];
|
|
393
|
+
const repoValues = values.filter((v) => v.type === 'github.repo');
|
|
394
|
+
const branchValues = values.filter((v) => v.type === 'github.branch');
|
|
395
|
+
const labelValues = values.filter((v) => v.type === 'github.label');
|
|
396
|
+
const checkedRepos = new Map();
|
|
397
|
+
const validRepos = [];
|
|
398
|
+
for (const v of repoValues) {
|
|
399
|
+
if (!ctx.config.repos.includes(v.value)) {
|
|
400
|
+
problems.push(`settings.${v.name}: repo "${v.value}" is not in this instance's repos`);
|
|
401
|
+
continue;
|
|
402
|
+
}
|
|
403
|
+
let ok = checkedRepos.get(v.value);
|
|
404
|
+
if (ok === undefined) {
|
|
405
|
+
const [owner, repo] = v.value.split('/');
|
|
406
|
+
try {
|
|
407
|
+
await appClient(ctx).rest.repos.get({ owner, repo });
|
|
408
|
+
ok = true;
|
|
409
|
+
}
|
|
410
|
+
catch (err) {
|
|
411
|
+
if (statusOf(err) === 404)
|
|
412
|
+
ok = false;
|
|
413
|
+
else
|
|
414
|
+
throw failure('GET', `/repos/${v.value}`, err);
|
|
415
|
+
}
|
|
416
|
+
checkedRepos.set(v.value, ok);
|
|
417
|
+
}
|
|
418
|
+
if (!ok) {
|
|
419
|
+
problems.push(`settings.${v.name}: repo "${v.value}" does not exist or is not accessible to installation ${ctx.config.installationId}`);
|
|
420
|
+
}
|
|
421
|
+
else {
|
|
422
|
+
validRepos.push(v.value);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
const targetRepos = repoValues.length > 0 ? [...new Set(validRepos)] : [...new Set(ctx.config.repos)];
|
|
426
|
+
if (targetRepos.length === 0)
|
|
427
|
+
return problems;
|
|
428
|
+
const checkedBranches = new Map();
|
|
429
|
+
for (const v of branchValues) {
|
|
430
|
+
if (v.value.trim() === '') {
|
|
431
|
+
for (const slug of targetRepos) {
|
|
432
|
+
problems.push(`settings.${v.name}: branch "${v.value}" does not exist in ${slug}`);
|
|
433
|
+
}
|
|
434
|
+
continue;
|
|
435
|
+
}
|
|
436
|
+
for (const slug of targetRepos) {
|
|
437
|
+
const key = `${slug}#${v.value}`;
|
|
438
|
+
let ok = checkedBranches.get(key);
|
|
439
|
+
if (ok === undefined) {
|
|
440
|
+
const [owner, repo] = slug.split('/');
|
|
441
|
+
try {
|
|
442
|
+
await appClient(ctx).rest.repos.getBranch({ owner, repo, branch: v.value });
|
|
443
|
+
ok = true;
|
|
444
|
+
}
|
|
445
|
+
catch (err) {
|
|
446
|
+
if (statusOf(err) === 404)
|
|
447
|
+
ok = false;
|
|
448
|
+
else
|
|
449
|
+
throw failure('GET', `/repos/${slug}/branches/${v.value}`, err);
|
|
450
|
+
}
|
|
451
|
+
checkedBranches.set(key, ok);
|
|
452
|
+
}
|
|
453
|
+
if (!ok)
|
|
454
|
+
problems.push(`settings.${v.name}: branch "${v.value}" does not exist in ${slug}`);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
const checkedLabels = new Map();
|
|
458
|
+
for (const v of labelValues) {
|
|
459
|
+
if (v.value.trim() === '') {
|
|
460
|
+
for (const slug of targetRepos) {
|
|
461
|
+
problems.push(`settings.${v.name}: label "${v.value}" does not exist in ${slug}`);
|
|
462
|
+
}
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
465
|
+
for (const slug of targetRepos) {
|
|
466
|
+
const key = `${slug}#${v.value}`;
|
|
467
|
+
let ok = checkedLabels.get(key);
|
|
468
|
+
if (ok === undefined) {
|
|
469
|
+
const [owner, repo] = slug.split('/');
|
|
470
|
+
try {
|
|
471
|
+
const r = await appClient(ctx).rest.issues.getLabel({ owner, repo, name: v.value });
|
|
472
|
+
ok = r.data.name === v.value;
|
|
473
|
+
}
|
|
474
|
+
catch (err) {
|
|
475
|
+
if (statusOf(err) === 404)
|
|
476
|
+
ok = false;
|
|
477
|
+
else
|
|
478
|
+
throw failure('GET', `/repos/${slug}/labels/${v.value}`, err);
|
|
479
|
+
}
|
|
480
|
+
checkedLabels.set(key, ok);
|
|
481
|
+
}
|
|
482
|
+
if (!ok)
|
|
483
|
+
problems.push(`settings.${v.name}: label "${v.value}" does not exist in ${slug}`);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
return problems;
|
|
487
|
+
}
|
|
488
|
+
/** AD-085: a `github.pr.*` event links its PR as `#<number>`; it names no run. */
|
|
489
|
+
function describeEvent(event) {
|
|
490
|
+
if (!event.type.startsWith('github.pr.'))
|
|
491
|
+
return undefined;
|
|
492
|
+
const { number, url } = event.data;
|
|
493
|
+
if (typeof number !== 'number' || typeof url !== 'string')
|
|
494
|
+
return undefined;
|
|
495
|
+
return { links: [{ label: `#${number}`, url }] };
|
|
496
|
+
}
|
|
497
|
+
/** The official `github` plugin (the `forge` slot). */
|
|
498
|
+
export const githubPlugin = definePlugin({
|
|
499
|
+
id: 'github',
|
|
500
|
+
version: '0.1.0',
|
|
501
|
+
config: Config,
|
|
502
|
+
configEnv: { appId: 'GITHUB_APP_ID', installationId: 'GITHUB_INSTALLATION_ID', appSlug: 'GITHUB_APP_SLUG', repos: 'GITHUB_REPOS' },
|
|
503
|
+
secrets: ['GITHUB_APP_PRIVATE_KEY', 'GITHUB_WEBHOOK_SECRET'],
|
|
504
|
+
events: EVENTS,
|
|
505
|
+
ingress: {
|
|
506
|
+
verify: (req, { secrets }) => verify(req.rawBody, req.headers['x-hub-signature-256'], secrets['GITHUB_WEBHOOK_SECRET']),
|
|
507
|
+
normalize: (req, { config }) => normalize(req, config),
|
|
508
|
+
dedupKey: (req) => req.headers['x-github-delivery'],
|
|
509
|
+
},
|
|
510
|
+
actions,
|
|
511
|
+
check: checkApp,
|
|
512
|
+
checkSettings,
|
|
513
|
+
describe: describeEvent,
|
|
514
|
+
});
|
|
515
|
+
/** The env `git` runs with: no system or global config, no prompt, no hooks, the token by a credential helper. */
|
|
516
|
+
export function gitEnv(token) {
|
|
517
|
+
return {
|
|
518
|
+
GIT_CONFIG_NOSYSTEM: '1',
|
|
519
|
+
GIT_CONFIG_GLOBAL: '/dev/null',
|
|
520
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
521
|
+
CF_GH_PUSH_TOKEN: token,
|
|
522
|
+
GIT_CONFIG_COUNT: '3',
|
|
523
|
+
GIT_CONFIG_KEY_0: 'credential.helper',
|
|
524
|
+
GIT_CONFIG_VALUE_0: '',
|
|
525
|
+
GIT_CONFIG_KEY_1: 'credential.helper',
|
|
526
|
+
GIT_CONFIG_VALUE_1: '!f() { test "$1" = get && echo username=x-access-token && echo "password=$CF_GH_PUSH_TOKEN"; }; f',
|
|
527
|
+
GIT_CONFIG_KEY_2: 'core.hooksPath',
|
|
528
|
+
GIT_CONFIG_VALUE_2: '/dev/null',
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
export const redact = (text, token) => (token === '' ? text : text.split(token).join('«token»'));
|
|
532
|
+
/**
|
|
533
|
+
* Pushes `sha` to `branch` of `repo` with the workflow's `token` (door 5): never forced, no push
|
|
534
|
+
* options, no hooks; the token reaches git only through the credential helper's env.
|
|
535
|
+
*/
|
|
536
|
+
async function push(ctx, a) {
|
|
537
|
+
const auth = { token: a.token };
|
|
538
|
+
const env = gitEnv(auth.token);
|
|
539
|
+
const remote = `${gitUrl()}/${a.repo}.git`;
|
|
540
|
+
const run = async (args) => {
|
|
541
|
+
const r = await ctx.exec('git', args, { cwd: a.dir, env, timeoutMs: 300_000 });
|
|
542
|
+
if (r.code !== 0) {
|
|
543
|
+
throw new Error(`git ${args[0]} to ${a.repo} failed: ${redact((r.stderr || r.stdout).trim(), auth.token)}`);
|
|
544
|
+
}
|
|
545
|
+
return r.stdout;
|
|
546
|
+
};
|
|
547
|
+
const sha = (await run(['rev-parse', '--verify', `${a.sha}^{commit}`])).trim();
|
|
548
|
+
await run(['push', '--no-verify', remote, `${sha}:refs/heads/${a.branch}`]);
|
|
549
|
+
const remoteSha = (await run(['ls-remote', remote, `refs/heads/${a.branch}`])).split(/\s/)[0] ?? '';
|
|
550
|
+
if (remoteSha !== sha)
|
|
551
|
+
throw new Error(`git push to ${a.repo}: ${a.branch} is ${remoteSha || 'missing'}, not ${sha}`);
|
|
552
|
+
return { pushed: true, remoteSha };
|
|
553
|
+
}
|
|
554
|
+
/**
|
|
555
|
+
* Clones `repo` into `dir` under `ctx.wd` with the workflow's `token` (github-helpers door 1,
|
|
556
|
+
* AD-067): no token in argv, URLs, `.git/config` or logs, no hooks, no global/system git config.
|
|
557
|
+
*/
|
|
558
|
+
async function clone(ctx, a) {
|
|
559
|
+
if (!REPO_SLUG.test(a.repo)) {
|
|
560
|
+
throw new Error(`git clone: "${a.repo}" is not a valid repo (owner/name)`);
|
|
561
|
+
}
|
|
562
|
+
const dirErrors = wdProblems(a.dir);
|
|
563
|
+
if (a.dir === '' || dirErrors.length > 0) {
|
|
564
|
+
throw new Error(`git clone: invalid dir "${a.dir}": ${dirErrors[0] ?? 'must not be empty'}`);
|
|
565
|
+
}
|
|
566
|
+
if (a.branch !== undefined && a.branch === '') {
|
|
567
|
+
throw new Error('git clone: branch must not be empty');
|
|
568
|
+
}
|
|
569
|
+
if (a.depth !== undefined && (!Number.isInteger(a.depth) || a.depth < 1)) {
|
|
570
|
+
throw new Error(`git clone: depth must be a positive integer, got ${String(a.depth)}`);
|
|
571
|
+
}
|
|
572
|
+
const auth = { token: a.token };
|
|
573
|
+
const env = gitEnv(auth.token);
|
|
574
|
+
const remote = `${gitUrl()}/${a.repo}.git`;
|
|
575
|
+
const run = async (args, cwd) => {
|
|
576
|
+
const r = await ctx.exec('git', args, { ...(cwd !== undefined ? { cwd } : {}), env, timeoutMs: 300_000 });
|
|
577
|
+
if (r.code !== 0) {
|
|
578
|
+
throw new Error(`git ${args[0]} of ${a.repo} failed: ${redact((r.stderr || r.stdout).trim(), auth.token)}`);
|
|
579
|
+
}
|
|
580
|
+
return r.stdout;
|
|
581
|
+
};
|
|
582
|
+
const cloneArgs = ['clone'];
|
|
583
|
+
if (a.branch !== undefined)
|
|
584
|
+
cloneArgs.push(`--branch=${a.branch}`);
|
|
585
|
+
if (a.depth !== undefined)
|
|
586
|
+
cloneArgs.push(`--depth=${a.depth}`);
|
|
587
|
+
cloneArgs.push('--', remote, a.dir);
|
|
588
|
+
await run(cloneArgs);
|
|
589
|
+
const sha = (await run(['rev-parse', 'HEAD'], a.dir)).trim();
|
|
590
|
+
const branch = (await run(['rev-parse', '--abbrev-ref', 'HEAD'], a.dir)).trim();
|
|
591
|
+
return { dir: a.dir, sha, branch };
|
|
592
|
+
}
|
|
593
|
+
/** The sha's latest check runs (every page) and its Actions workflow runs, through `octokit`. */
|
|
594
|
+
async function checksOf(octokit, slug, sha) {
|
|
595
|
+
const [owner, repo] = slug.split('/');
|
|
596
|
+
const get = async (path, params) => {
|
|
597
|
+
try {
|
|
598
|
+
return (await octokit.request(`GET ${path}`, { owner, repo, ...params })).data;
|
|
599
|
+
}
|
|
600
|
+
catch (err) {
|
|
601
|
+
throw failure('GET', path.replace('{owner}/{repo}', slug).replace('{ref}', sha).replace('{run_id}', String(params['run_id'])), err);
|
|
602
|
+
}
|
|
603
|
+
};
|
|
604
|
+
const checkRuns = [];
|
|
605
|
+
for (let page = 1;; page++) {
|
|
606
|
+
const r = await get('/repos/{owner}/{repo}/commits/{ref}/check-runs', {
|
|
607
|
+
ref: sha,
|
|
608
|
+
filter: 'latest',
|
|
609
|
+
per_page: 100,
|
|
610
|
+
page,
|
|
611
|
+
});
|
|
612
|
+
for (const c of r.check_runs) {
|
|
613
|
+
checkRuns.push({ id: c.id, name: c.name, status: c.status, conclusion: c.conclusion, app: c.app?.slug ?? '', suiteId: c.check_suite?.id ?? 0 });
|
|
614
|
+
}
|
|
615
|
+
if (r.check_runs.length === 0 || checkRuns.length >= r.total_count)
|
|
616
|
+
break;
|
|
617
|
+
}
|
|
618
|
+
const wfRuns = [];
|
|
619
|
+
for (let page = 1; page <= WORKFLOW_RUN_PAGES; page++) {
|
|
620
|
+
const r = await get('/repos/{owner}/{repo}/actions/runs', { head_sha: sha, per_page: 100, page });
|
|
621
|
+
wfRuns.push(...r.workflow_runs);
|
|
622
|
+
if (r.workflow_runs.length === 0 || wfRuns.length >= r.total_count)
|
|
623
|
+
break;
|
|
624
|
+
}
|
|
625
|
+
const workflowRuns = [];
|
|
626
|
+
for (const w of wfRuns) {
|
|
627
|
+
let jobs = null;
|
|
628
|
+
if (w.conclusion === 'failure' || w.conclusion === 'startup_failure') {
|
|
629
|
+
jobs = (await get('/repos/{owner}/{repo}/actions/runs/{run_id}/jobs', { run_id: w.id, per_page: 1 })).total_count;
|
|
630
|
+
}
|
|
631
|
+
workflowRuns.push({ id: w.id, name: w.name, path: w.path, status: w.status, conclusion: w.conclusion, suiteId: w.check_suite_id, url: w.html_url, jobs });
|
|
632
|
+
}
|
|
633
|
+
return { sha, checkRuns, workflowRuns };
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* One CI check of `sha` (door 4) through the workflow's `octokit`: reads the checks, classifies
|
|
637
|
+
* them with the step's previous result of the same sha, and for `retrying` re-runs the failed jobs
|
|
638
|
+
* of each workflow run of the new round.
|
|
639
|
+
*/
|
|
640
|
+
async function check(ctx, a) {
|
|
641
|
+
const snapshot = await checksOf(a.octokit, a.repo, a.sha);
|
|
642
|
+
const prev = ctx.outputs[ctx.step];
|
|
643
|
+
const previous = isCiResult(prev) && prev.sha === a.sha ? prev : undefined;
|
|
644
|
+
const result = classifyCi(snapshot, { ...(a.policy ? { policy: a.policy } : {}), previous, now: Date.now() });
|
|
645
|
+
if (result.status === 'retrying') {
|
|
646
|
+
const [owner, repo] = a.repo.split('/');
|
|
647
|
+
for (const r of result.retries.slice(previous?.retries.length ?? 0)) {
|
|
648
|
+
try {
|
|
649
|
+
await a.octokit.request('POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs', { owner, repo, run_id: r.workflowRunId });
|
|
650
|
+
}
|
|
651
|
+
catch (err) {
|
|
652
|
+
throw failure('POST', `/repos/${a.repo}/actions/runs/${r.workflowRunId}/rerun-failed-jobs`, err);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
return result;
|
|
657
|
+
}
|
|
658
|
+
/**
|
|
659
|
+
* Opens a PR from `head` to `base` of `repo` through the workflow's `octokit` (AD-062): the PR
|
|
660
|
+
* already open for `head` on `base` comes back with `created: false`, one open for `head` on
|
|
661
|
+
* another base is an error, and a create that loses a race (422) returns the PR that won it.
|
|
662
|
+
*/
|
|
663
|
+
async function open(_ctx, a) {
|
|
664
|
+
const [owner, repo] = a.repo.split('/');
|
|
665
|
+
const path = `/repos/${a.repo}/pulls`;
|
|
666
|
+
const openOnBase = async () => {
|
|
667
|
+
let pulls;
|
|
668
|
+
try {
|
|
669
|
+
pulls = await a.octokit.paginate(a.octokit.rest.pulls.list, { owner, repo, state: 'open', head: `${owner}:${a.head}`, per_page: 100 });
|
|
670
|
+
}
|
|
671
|
+
catch (err) {
|
|
672
|
+
throw failure('GET', path, err);
|
|
673
|
+
}
|
|
674
|
+
const mine = pulls.filter((p) => p.head.ref === a.head);
|
|
675
|
+
const same = mine.find((p) => p.base.ref === a.base);
|
|
676
|
+
if (same !== undefined)
|
|
677
|
+
return { number: same.number, url: same.html_url, created: false };
|
|
678
|
+
const other = mine[0];
|
|
679
|
+
if (other !== undefined) {
|
|
680
|
+
throw new Error(`PR #${other.number} is already open for ${a.head} in ${a.repo}, against ${other.base.ref}, not ${a.base}`);
|
|
681
|
+
}
|
|
682
|
+
return undefined;
|
|
683
|
+
};
|
|
684
|
+
const existing = await openOnBase();
|
|
685
|
+
if (existing !== undefined)
|
|
686
|
+
return existing;
|
|
687
|
+
try {
|
|
688
|
+
const r = await a.octokit.rest.pulls.create({ owner, repo, head: a.head, base: a.base, title: a.title, body: a.body, draft: a.draft === true });
|
|
689
|
+
return { number: r.data.number, url: r.data.html_url, created: true };
|
|
690
|
+
}
|
|
691
|
+
catch (err) {
|
|
692
|
+
if (statusOf(err) === 422) {
|
|
693
|
+
const won = await openOnBase();
|
|
694
|
+
if (won !== undefined)
|
|
695
|
+
return won;
|
|
696
|
+
}
|
|
697
|
+
throw failure('POST', path, err);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
/** Review `reviewId` of PR `number` and every inline comment of it, through `octokit` (door 5). */
|
|
701
|
+
async function feedback(_ctx, a) {
|
|
702
|
+
const [owner, repo] = a.repo.split('/');
|
|
703
|
+
const base = `/repos/${a.repo}/pulls/${a.number}/reviews/${a.reviewId}`;
|
|
704
|
+
let review;
|
|
705
|
+
try {
|
|
706
|
+
review = (await a.octokit.request('GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}', { owner, repo, pull_number: a.number, review_id: a.reviewId }))
|
|
707
|
+
.data;
|
|
708
|
+
}
|
|
709
|
+
catch (err) {
|
|
710
|
+
throw failure('GET', base, err);
|
|
711
|
+
}
|
|
712
|
+
const comments = [];
|
|
713
|
+
for (let page = 1;; page++) {
|
|
714
|
+
let batch;
|
|
715
|
+
try {
|
|
716
|
+
batch = (await a.octokit.request('GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments', {
|
|
717
|
+
owner,
|
|
718
|
+
repo,
|
|
719
|
+
pull_number: a.number,
|
|
720
|
+
review_id: a.reviewId,
|
|
721
|
+
per_page: 100,
|
|
722
|
+
page,
|
|
723
|
+
})).data;
|
|
724
|
+
}
|
|
725
|
+
catch (err) {
|
|
726
|
+
throw failure('GET', `${base}/comments`, err);
|
|
727
|
+
}
|
|
728
|
+
for (const c of batch) {
|
|
729
|
+
comments.push({
|
|
730
|
+
id: c.id,
|
|
731
|
+
path: c.path,
|
|
732
|
+
line: c.line ?? c.original_line ?? null,
|
|
733
|
+
body: c.body,
|
|
734
|
+
diffHunk: c.diff_hunk,
|
|
735
|
+
url: c.html_url,
|
|
736
|
+
inReplyTo: c.in_reply_to_id ?? null,
|
|
737
|
+
});
|
|
738
|
+
}
|
|
739
|
+
if (batch.length < 100)
|
|
740
|
+
break;
|
|
741
|
+
}
|
|
742
|
+
return {
|
|
743
|
+
review: { id: review.id, state: review.state.toLowerCase(), body: review.body ?? '', user: review.user === null ? null : { login: review.user.login } },
|
|
744
|
+
comments,
|
|
745
|
+
};
|
|
746
|
+
}
|
|
747
|
+
/** GitHub's limit on a review body. */
|
|
748
|
+
export const REVIEW_BODY_MAX = 65536;
|
|
749
|
+
/** Marks a review as one call's, so a retried step finds it (github-review-helper door 2). */
|
|
750
|
+
const reviewMarker = (key) => `<!-- code-factory-review:${key} -->`;
|
|
751
|
+
function reviewProblem(a, comments) {
|
|
752
|
+
if (typeof a.repo !== 'string' || !REPO_SLUG.test(a.repo))
|
|
753
|
+
return `repo "${String(a.repo)}" is not owner/name`;
|
|
754
|
+
if (!Number.isInteger(a.number) || a.number < 1)
|
|
755
|
+
return `number must be a positive integer, got ${String(a.number)}`;
|
|
756
|
+
if (typeof a.commitId !== 'string' || !/^[0-9a-fA-F]{40}$/.test(a.commitId))
|
|
757
|
+
return `commitId must be a 40-character hex sha, got "${String(a.commitId)}"`;
|
|
758
|
+
if (typeof a.body !== 'string' || a.body === '')
|
|
759
|
+
return 'body must not be empty';
|
|
760
|
+
if (a.key !== undefined) {
|
|
761
|
+
if (typeof a.key !== 'string' || a.key === '' || a.key.length > 200)
|
|
762
|
+
return 'key must be 1 to 200 characters';
|
|
763
|
+
if (/\s|>|--/.test(a.key))
|
|
764
|
+
return `key "${a.key}" must not hold whitespace, > or --`;
|
|
765
|
+
}
|
|
766
|
+
for (const [i, c] of comments.entries()) {
|
|
767
|
+
if (typeof c.path !== 'string' || c.path === '' || c.path.startsWith('/') || c.path.split('/').includes('..')) {
|
|
768
|
+
return `comments[${i}].path "${String(c.path)}" is not a repo-relative path`;
|
|
769
|
+
}
|
|
770
|
+
if (!Number.isInteger(c.line) || c.line < 1)
|
|
771
|
+
return `comments[${i}].line must be a positive integer, got ${String(c.line)}`;
|
|
772
|
+
if (typeof c.body !== 'string' || c.body === '')
|
|
773
|
+
return `comments[${i}].body must not be empty`;
|
|
774
|
+
}
|
|
775
|
+
return undefined;
|
|
776
|
+
}
|
|
777
|
+
/**
|
|
778
|
+
* Posts one `COMMENT` review on `commitId` of PR `number` through `octokit` (github-review-helper,
|
|
779
|
+
* AD-079): a comment on a head line the diff `<base>...<commitId>` shows goes inline, the rest go
|
|
780
|
+
* in the body under `### Outside the diff`; a `422` posts again with every comment in the body. The
|
|
781
|
+
* body's first line marks it with `key` (default `<runId>/<step>@<visit>`): a review already
|
|
782
|
+
* holding that marker is returned with `created: false` and nothing is posted.
|
|
783
|
+
*/
|
|
784
|
+
async function review(ctx, a) {
|
|
785
|
+
const comments = a.comments ?? [];
|
|
786
|
+
const problem = reviewProblem(a, comments);
|
|
787
|
+
if (problem !== undefined)
|
|
788
|
+
throw new Error(`github.pr.review: ${problem}`);
|
|
789
|
+
const marker = reviewMarker(a.key ?? `${ctx.runId}/${ctx.step}@${ctx.visit}`);
|
|
790
|
+
const compose = (outside) => [marker, a.body, ...(outside.length > 0 ? ['', '### Outside the diff', ...outside.flatMap((c) => ['', `#### \`${c.path}:${c.line}\``, '', c.body])] : [])].join('\n');
|
|
791
|
+
// the longest body this call may post is the 422 fallback's
|
|
792
|
+
const longest = compose(comments).length;
|
|
793
|
+
if (longest > REVIEW_BODY_MAX)
|
|
794
|
+
throw new Error(`github.pr.review: the review body would be ${longest} characters, over GitHub's ${REVIEW_BODY_MAX}`);
|
|
795
|
+
const [owner, repo] = a.repo.split('/');
|
|
796
|
+
const where = { owner, repo, pull_number: a.number };
|
|
797
|
+
const reviewsPath = `/repos/${a.repo}/pulls/${a.number}/reviews`;
|
|
798
|
+
const get = async (route, path, params) => {
|
|
799
|
+
try {
|
|
800
|
+
return (await a.octokit.request(`GET ${route}`, params)).data;
|
|
801
|
+
}
|
|
802
|
+
catch (err) {
|
|
803
|
+
throw failure('GET', path, err);
|
|
804
|
+
}
|
|
805
|
+
};
|
|
806
|
+
/** every page of a list GitHub pages 100 at a time */
|
|
807
|
+
const all = async (route, path, params) => {
|
|
808
|
+
const out = [];
|
|
809
|
+
for (let page = 1;; page++) {
|
|
810
|
+
const batch = await get(route, path, { ...params, per_page: 100, page });
|
|
811
|
+
out.push(...batch);
|
|
812
|
+
if (batch.length < 100)
|
|
813
|
+
return out;
|
|
814
|
+
}
|
|
815
|
+
};
|
|
816
|
+
const mine = (await all('/repos/{owner}/{repo}/pulls/{pull_number}/reviews', reviewsPath, where)).find((r) => r.body?.includes(marker) === true);
|
|
817
|
+
if (mine !== undefined) {
|
|
818
|
+
const inline = (await all('/repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments', `${reviewsPath}/${mine.id}/comments`, { ...where, review_id: mine.id })).length;
|
|
819
|
+
return { id: mine.id, url: mine.html_url, created: false, inline, inBody: Math.max(0, comments.length - inline) };
|
|
820
|
+
}
|
|
821
|
+
const pr = await get('/repos/{owner}/{repo}/pulls/{pull_number}', `/repos/${a.repo}/pulls/${a.number}`, where);
|
|
822
|
+
const basehead = `${pr.base.ref}...${a.commitId}`;
|
|
823
|
+
// GitHub lists the changed files on the first page only, at most 300: one request (AD-079)
|
|
824
|
+
const compare = await get('/repos/{owner}/{repo}/compare/{basehead}', `/repos/${a.repo}/compare/${basehead}`, {
|
|
825
|
+
owner,
|
|
826
|
+
repo,
|
|
827
|
+
basehead,
|
|
828
|
+
});
|
|
829
|
+
const shown = new Map();
|
|
830
|
+
for (const f of compare.files ?? []) {
|
|
831
|
+
if (f.patch === undefined)
|
|
832
|
+
continue;
|
|
833
|
+
for (const [path, lines] of commentableLines(`diff --git a/${f.filename} b/${f.filename}\n+++ b/${f.filename}\n${f.patch}`))
|
|
834
|
+
shown.set(path, lines);
|
|
835
|
+
}
|
|
836
|
+
const isInline = (c) => shown.get(c.path)?.has(c.line) === true;
|
|
837
|
+
const inline = comments.filter(isInline);
|
|
838
|
+
const post = (body, withInline) => a.octokit.request('POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews', {
|
|
839
|
+
...where,
|
|
840
|
+
commit_id: a.commitId,
|
|
841
|
+
event: 'COMMENT',
|
|
842
|
+
body,
|
|
843
|
+
...(withInline && inline.length > 0 ? { comments: inline.map((c) => ({ path: c.path, line: c.line, side: 'RIGHT', body: c.body })) } : {}),
|
|
844
|
+
});
|
|
845
|
+
let made;
|
|
846
|
+
let placedInline = inline.length;
|
|
847
|
+
try {
|
|
848
|
+
made = await post(compose(comments.filter((c) => !isInline(c))), true);
|
|
849
|
+
}
|
|
850
|
+
catch (err) {
|
|
851
|
+
// GitHub refused an inline position after all: every comment goes in the body
|
|
852
|
+
if (statusOf(err) !== 422 || inline.length === 0)
|
|
853
|
+
throw failure('POST', reviewsPath, err);
|
|
854
|
+
try {
|
|
855
|
+
made = await post(compose(comments), false);
|
|
856
|
+
}
|
|
857
|
+
catch (again) {
|
|
858
|
+
throw failure('POST', reviewsPath, again);
|
|
859
|
+
}
|
|
860
|
+
placedInline = 0;
|
|
861
|
+
}
|
|
862
|
+
return { id: Number(made.data.id), url: made.data.html_url, created: true, inline: placedInline, inBody: comments.length - placedInline };
|
|
863
|
+
}
|
|
864
|
+
/**
|
|
865
|
+
* Whether the workflow's own client can read each of `repos` (health-ready door 7), for its
|
|
866
|
+
* `workerReady`: `401` is a token GitHub rejects and `404` a repo it cannot see, both fatal; a
|
|
867
|
+
* network error or any other answer is not.
|
|
868
|
+
*/
|
|
869
|
+
async function checkAccess(octokit, a) {
|
|
870
|
+
for (const slug of a.repos) {
|
|
871
|
+
const [owner, repo] = slug.split('/');
|
|
872
|
+
try {
|
|
873
|
+
await octokit.rest.repos.get({ owner, repo });
|
|
874
|
+
}
|
|
875
|
+
catch (err) {
|
|
876
|
+
const status = statusOf(err);
|
|
877
|
+
if (status === 401)
|
|
878
|
+
return { ok: false, reason: 'the GitHub token was rejected (401)', fatal: true };
|
|
879
|
+
if (status === 404)
|
|
880
|
+
return { ok: false, reason: `repo ${slug} not found or not readable with this token (404)`, fatal: true };
|
|
881
|
+
return { ok: false, reason: status !== undefined ? `GitHub answered ${status} for ${slug}` : `GitHub unreachable: ${messageOf(err)}` };
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
return { ok: true };
|
|
885
|
+
}
|
|
886
|
+
/** The PR updates `github.on.prUpdated` binds, and their events (door 2). */
|
|
887
|
+
const PR_UPDATES = {
|
|
888
|
+
opened: 'github.pr.opened',
|
|
889
|
+
synchronized: 'github.pr.synchronized',
|
|
890
|
+
reopened: 'github.pr.reopened',
|
|
891
|
+
ready: 'github.pr.ready',
|
|
892
|
+
};
|
|
893
|
+
/** The associations that mean write access (AD-073). */
|
|
894
|
+
export const WRITE_ACCESS = ['OWNER', 'MEMBER', 'COLLABORATOR'];
|
|
895
|
+
/** Whose review or comment counts (AD-073): write access, or the `reviewers` given; never a bot or the PR's author. */
|
|
896
|
+
function counted(reviewers) {
|
|
897
|
+
return {
|
|
898
|
+
...(reviewers !== undefined ? { 'data.user.login': { in: reviewers } } : { 'data.user.association': { in: WRITE_ACCESS } }),
|
|
899
|
+
'data.user.bot': false,
|
|
900
|
+
'data.byAuthor': false,
|
|
901
|
+
};
|
|
902
|
+
}
|
|
903
|
+
/** The authoring helpers of door 5. */
|
|
904
|
+
export const github = {
|
|
905
|
+
slot: () => slot(githubPlugin),
|
|
906
|
+
repo: (opts = {}) => ({ type: 'github.repo', ...opts }),
|
|
907
|
+
branch: (opts = {}) => ({ type: 'github.branch', ...opts }),
|
|
908
|
+
label: (opts = {}) => ({ type: 'github.label', ...opts }),
|
|
909
|
+
setting,
|
|
910
|
+
match: {
|
|
911
|
+
/** a check suite of `sha` in `repo` completed */
|
|
912
|
+
checksCompleted(o) {
|
|
913
|
+
return { events: ['github.checks.completed'], slot: o.slot, filter: { 'data.repo': o.repo, 'data.sha': o.sha } };
|
|
914
|
+
},
|
|
915
|
+
/**
|
|
916
|
+
* A review of PR `number` of `repo` by someone who counts (AD-073); `states` narrows the state,
|
|
917
|
+
* `sha` the commit reviewed
|
|
918
|
+
*/
|
|
919
|
+
reviewSubmitted(o) {
|
|
920
|
+
return {
|
|
921
|
+
events: ['github.pr.review.submitted'],
|
|
922
|
+
slot: o.slot,
|
|
923
|
+
filter: {
|
|
924
|
+
'data.repo': o.repo,
|
|
925
|
+
'data.number': o.number,
|
|
926
|
+
...(o.states !== undefined ? { 'data.review.state': { in: o.states } } : {}),
|
|
927
|
+
...(o.sha !== undefined ? { 'data.review.commitId': o.sha } : {}),
|
|
928
|
+
...counted(o.reviewers),
|
|
929
|
+
},
|
|
930
|
+
};
|
|
931
|
+
},
|
|
932
|
+
/** A comment on PR `number` of `repo` by someone who counts (AD-073), starting with `command` when given */
|
|
933
|
+
commentCreated(o) {
|
|
934
|
+
return {
|
|
935
|
+
events: ['github.pr.comment.created'],
|
|
936
|
+
slot: o.slot,
|
|
937
|
+
filter: {
|
|
938
|
+
'data.repo': o.repo,
|
|
939
|
+
'data.number': o.number,
|
|
940
|
+
...(o.command !== undefined ? { 'data.command': o.command } : {}),
|
|
941
|
+
...counted(o.reviewers),
|
|
942
|
+
},
|
|
943
|
+
};
|
|
944
|
+
},
|
|
945
|
+
/** new commits pushed to PR `number` of `repo` (head `sha`, when given) */
|
|
946
|
+
prSynchronized(o) {
|
|
947
|
+
return {
|
|
948
|
+
events: ['github.pr.synchronized'],
|
|
949
|
+
slot: o.slot,
|
|
950
|
+
filter: { 'data.repo': o.repo, 'data.number': o.number, ...(o.sha !== undefined ? { 'data.head.sha': o.sha } : {}) },
|
|
951
|
+
};
|
|
952
|
+
},
|
|
953
|
+
/** PR `number` of `repo` closed, merged or not */
|
|
954
|
+
prClosed(o) {
|
|
955
|
+
return { events: ['github.pr.closed'], slot: o.slot, filter: { 'data.repo': o.repo, 'data.number': o.number } };
|
|
956
|
+
},
|
|
957
|
+
},
|
|
958
|
+
on: {
|
|
959
|
+
/**
|
|
960
|
+
* A non-draft PR became worth reviewing: opened, new commits, reopened or marked ready (`on`
|
|
961
|
+
* narrows it, all four by default); one trigger per update, keyed on the PR's URL
|
|
962
|
+
*/
|
|
963
|
+
prUpdated(o) {
|
|
964
|
+
const on = o.on ?? Object.keys(PR_UPDATES);
|
|
965
|
+
if (on.length === 0)
|
|
966
|
+
throw new Error('github.on.prUpdated: `on` is empty, so the workflow would have no trigger; leave it out for all four');
|
|
967
|
+
return Object.keys(PR_UPDATES)
|
|
968
|
+
.filter((u) => on.includes(u))
|
|
969
|
+
.map((u) => ({
|
|
970
|
+
events: [PR_UPDATES[u]],
|
|
971
|
+
slot: o.slot,
|
|
972
|
+
filter: {
|
|
973
|
+
'data.draft': false,
|
|
974
|
+
...(o.repo !== undefined ? { 'data.repo': o.repo } : {}),
|
|
975
|
+
...(o.base !== undefined ? { 'data.base.ref': o.base } : {}),
|
|
976
|
+
},
|
|
977
|
+
input: o.input,
|
|
978
|
+
key: o.key ?? '$.data.url',
|
|
979
|
+
}));
|
|
980
|
+
},
|
|
981
|
+
/** a PR merged (into `base`, when given) */
|
|
982
|
+
prMerged(o) {
|
|
983
|
+
return {
|
|
984
|
+
events: ['github.pr.merged'],
|
|
985
|
+
slot: o.slot,
|
|
986
|
+
...(o.base !== undefined ? { filter: { 'data.base.ref': o.base } } : {}),
|
|
987
|
+
input: o.input,
|
|
988
|
+
key: o.key ?? '$.data.url',
|
|
989
|
+
};
|
|
990
|
+
},
|
|
991
|
+
/**
|
|
992
|
+
* A review of the PR whose URL the run holds as a key (AD-074) answers its open `step`: one
|
|
993
|
+
* trigger per state in `outcomes`; stale reviews and those who do not count (AD-073) answer nothing
|
|
994
|
+
*/
|
|
995
|
+
reviewAnswers(o) {
|
|
996
|
+
return Object.entries(o.outcomes).map(([state, outcome]) => ({
|
|
997
|
+
events: ['github.pr.review.submitted'],
|
|
998
|
+
slot: o.slot,
|
|
999
|
+
filter: { 'data.review.state': state, 'data.review.stale': false, ...counted(o.reviewers) },
|
|
1000
|
+
key: '$.data.url',
|
|
1001
|
+
answer: { step: o.step, outcome: outcome, ...(o.data !== undefined ? { data: o.data } : {}) },
|
|
1002
|
+
}));
|
|
1003
|
+
},
|
|
1004
|
+
/** a PR comment whose first word is `command`, from someone who counts, answers the open `step` with `outcome` */
|
|
1005
|
+
commentCommand(o) {
|
|
1006
|
+
return {
|
|
1007
|
+
events: ['github.pr.comment.created'],
|
|
1008
|
+
slot: o.slot,
|
|
1009
|
+
filter: { 'data.command': o.command, ...counted(o.reviewers) },
|
|
1010
|
+
key: '$.data.url',
|
|
1011
|
+
answer: { step: o.step, outcome: o.outcome, ...(o.data !== undefined ? { data: o.data } : {}) },
|
|
1012
|
+
};
|
|
1013
|
+
},
|
|
1014
|
+
},
|
|
1015
|
+
git: { push, clone },
|
|
1016
|
+
ci: { check },
|
|
1017
|
+
pr: { open, feedback, review },
|
|
1018
|
+
checkAccess,
|
|
1019
|
+
};
|
|
1020
|
+
export * from "./setup.js";
|
|
1021
|
+
//# sourceMappingURL=index.js.map
|