Repository navigation
Expand file tree
/
Copy pathpull-request.js
More file actions
482 lines (427 loc) · 18.6 KB
/
Copy pathpull-request.js
File metadata and controls
482 lines (427 loc) · 18.6 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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
import '../../lib/load-env-file.js';
import path from 'path';
import { fileURLToPath } from 'url';
import { styleText } from 'util';
import { Octokit } from '@octokit/rest';
const requiredEnvironmentVariables = [
'GITHUB_USER_TOKEN',
'GITHUB_REPOSITORY',
'GITHUB_PR_NUMBER',
'GITHUB_PR_HEAD_REF',
'GITHUB_PR_BASE_REF',
];
const GITHUB_BODY_MAX_BYTES = 262_144; // = max 65_536 4-byte Unicode characters
const RESERVED_COMMENT_BYTES = 2144; // reserve space for comment/issue body header
/** @type {Octokit} */
let githubClient;
let repositoryOwner;
let repositoryName;
let prData;
/**
* @typedef {object} ReviewComment
* @property {string} path - File path (relative to the repo root) the comment is anchored to.
* @property {number} line - 1-indexed line number in the new version of the file.
* @property {'LEFT' | 'RIGHT'} [side] - Diff side. Defaults to 'RIGHT' if omitted.
* @property {string} body - The comment body. May contain a `suggestion` code block.
* @property {boolean} isIncludedInDiffHunk - Whether the comment's line is in a diff hunk.
*/
/**
* Checks if the environment variables for GitHub operations are correct.
* @returns {Promise} Rejects an error message if the environment is not correct.
*/
export async function checkEnv() {
for (const environmentVariable of requiredEnvironmentVariables) {
if (!(environmentVariable in process.env)) {
throw `Environment variable ${environmentVariable} is required for this script. Please define it in your system or in the .env file.`;
}
}
}
/**
* Fetch data about the current pull request from the GitHub API.
* @returns {Promise} A Promise that resolves to the returned pull request data.
*/
export async function init() {
await checkEnv();
repositoryOwner = process.env.GITHUB_REPOSITORY.split('/', 1)[0];
repositoryName = process.env.GITHUB_REPOSITORY.split('/', 2)[1];
githubClient = new Octokit({
auth: `token ${process.env.GITHUB_USER_TOKEN}`,
});
const pr = await githubClient.rest.pulls.get({
owner: repositoryOwner,
repo: repositoryName,
// eslint-disable-next-line camelcase -- required by GitHub API
pull_number: process.env.GITHUB_PR_NUMBER,
});
// save PR for later use
prData = pr.data;
return pr.data;
}
/**
* @returns {Promise} A Promise that resolves to an object which describes the OFL components changed in this pull request.
*/
export async function fetchChangedComponents() {
// fetch all changed files
const files = await githubClient.paginate(githubClient.rest.pulls.listFiles, {
owner: repositoryOwner,
repo: repositoryName,
// eslint-disable-next-line camelcase -- required by GitHub API
pull_number: process.env.GITHUB_PR_NUMBER,
// eslint-disable-next-line camelcase -- required by GitHub API
per_page: 100,
});
// check which model components, plugins and fixtures have been changed in the PR
const changedComponents = {
added: {
schema: false,
model: false,
imports: [], // array of plugin keys
exports: [], // array of plugin keys
exportTests: [], // array of [plugin key, test key]
fixtures: [], // array of [man key, fix key]
},
modified: {
schema: false,
model: false,
imports: [], // array of plugin keys
exports: [], // array of plugin keys
exportTests: [], // array of [plugin key, test key]
fixtures: [], // array of [man key, fix key]
},
removed: {
schema: false,
model: false,
imports: [], // array of plugin keys
exports: [], // array of plugin keys
exportTests: [], // array of [plugin key, test key]
fixtures: [], // array of [man key, fix key]
},
};
for (const file of files) {
handleFileData(file);
}
return changedComponents;
/**
* Forwards the file's status and path to handleFile(...) with the specialty of splitting renamed files into added/removed.
* @param {object} fileData - The file object from GitHub.
*/
function handleFileData(fileData) {
if (fileData.status === 'renamed') {
// Handling renamed files would be a bit tricky, as we also had to store the previous filename.
// That's why we simply treat the old file name as removed and the new one as added.
handleFile('added', fileData.filename);
handleFile('removed', fileData.previous_filename);
}
else {
handleFile(fileData.status, fileData.filename);
}
}
/**
* Parse the file type by its path and update the change summary of the file's status accordingly.
* @param {'added' | 'removed' | 'modified'} fileStatus - What happened with the file in this pull request.
* @param {string} filePath - The file name, relative to the repository's root.
*/
function handleFile(fileStatus, filePath) {
const changeSummary = changedComponents[fileStatus];
const segments = filePath.split('/');
if (segments[0] === 'lib' && segments[1] === 'model') {
changeSummary.model = true;
return;
}
if (segments[0] === 'plugins' && segments[2] === 'import.js') {
changeSummary.imports.push(segments[1]); // plugin key
return;
}
if (segments[0] === 'plugins' && segments[2] === 'export.js') {
changeSummary.exports.push(segments[1]); // plugin key
return;
}
if (segments[0] === 'plugins' && segments[2] === 'exportTests') {
changeSummary.exportTests.push([
segments[1], // plugin key
segments[3].split('.', 1)[0], // test key
]);
return;
}
if (segments[0] === 'schemas') {
changeSummary.schema = true;
return;
}
if (segments[0] === 'fixtures' && segments.length === 3) {
changeSummary.fixtures.push([
segments[1], // man key
segments[2].split('.', 1)[0], // fix key
]);
}
}
}
/**
* Creates a new comment in the PR if test.lines is not empty and if there is not already an exactly equal comment.
* Deletes old comments from the same test (determined by test.fileUrl).
* @param {object} test - Information about the test script that wants to update the comment.
* @param {URL} test.fileUrl - URL of the test file.
* @param {string} test.name - Heading to be used in the comment
* @param {string[]} test.lines - The comment's lines of text
* @returns {Promise} A Promise that is fulfilled as soon as all GitHub operations have finished
*/
export async function updateComment(test) {
if (prData.head.repo.full_name !== prData.base.repo.full_name) {
console.warn(styleText('yellow', 'Warning:'), 'This PR is created from a forked repository, so there is no write permission for the repo.');
return undefined;
}
const oflRootPath = fileURLToPath(new URL('../../', import.meta.url));
const relativeFilePath = path.relative(oflRootPath, fileURLToPath(test.fileUrl));
const lines = [
`<!-- GITHUB-TEST: ${relativeFilePath} -->`,
`# ${test.name}`,
`(Output of test script \`${relativeFilePath}\`.)`,
'',
...test.lines,
];
const message = lines.join('\n');
const comments = await githubClient.paginate(githubClient.rest.issues.listComments, {
owner: repositoryOwner,
repo: repositoryName,
// eslint-disable-next-line camelcase -- required by GitHub API
issue_number: process.env.GITHUB_PR_NUMBER,
// eslint-disable-next-line camelcase -- required by GitHub API
per_page: 100,
});
let isEqualFound = false;
const promises = comments.flatMap((comment) => {
// get rid of \r linebreaks
comment.body = comment.body.replaceAll('\r', '');
if (lines[0] !== comment.body.split('\n', 1)[0]) {
// the comment was not created by this test script
return [];
}
if (!isEqualFound && message === comment.body && test.lines.length > 0) {
isEqualFound = true;
console.log(`Test comment with same content already exists at ${process.env.GITHUB_REPOSITORY}#${process.env.GITHUB_PR_NUMBER}.`);
return [];
}
console.log(`Deleting old test comment at ${process.env.GITHUB_REPOSITORY}#${process.env.GITHUB_PR_NUMBER}.`);
return githubClient.rest.issues.deleteComment({
owner: repositoryOwner,
repo: repositoryName,
// eslint-disable-next-line camelcase -- required by GitHub API
comment_id: comment.id,
});
});
if (!isEqualFound && test.lines.length > 0) {
console.log(`Creating test comment at ${process.env.GITHUB_REPOSITORY}#${process.env.GITHUB_PR_NUMBER}.`);
promises.push(githubClient.rest.issues.createComment({
owner: repositoryOwner,
repo: repositoryName,
// eslint-disable-next-line camelcase -- required by GitHub API
issue_number: process.env.GITHUB_PR_NUMBER,
body: message,
}));
}
return Promise.all(promises);
}
/**
* Tries to append `newLines` to `lines`. If adding `newLines` plus `tooLongMessage`
* (plus any `trailingLines`) would exceed the byte limit, appends `tooLongMessage`
* instead and returns `true`. Otherwise appends `newLines` and returns `false`.
*
* @param {string[]} lines - Accumulated lines so far (mutated in place).
* @param {readonly string[]} newLines - Lines to append.
* @param {string} tooLongMessage - Line to append when truncation is needed.
* @param {readonly string[]} trailingLines - Lines always appended after the loop (not yet in `lines`), used in the byte check.
* @returns {boolean} `true` if truncation occurred, `false` otherwise.
*/
export function appendOrTruncate(lines, newLines, tooLongMessage, trailingLines = []) { // eslint-disable-line unicorn/consistent-boolean-name -- returning a boolean is not the primary purpose
const testContent = [...lines, ...newLines, tooLongMessage, ...trailingLines].join('\r\n');
if (Buffer.byteLength(testContent, 'utf-8') > GITHUB_BODY_MAX_BYTES - RESERVED_COMMENT_BYTES) {
lines.push(tooLongMessage);
return true;
}
lines.push(...newLines);
return false;
}
/**
* @returns {string} The SHA of the head commit of the current pull request.
* @throws {Error} If `init()` has not been called.
*/
export function getHeadSha() {
if (!prData) {
throw new Error('init() must be called before getHeadSha().');
}
return prData.head.sha;
}
/**
* Posts (or updates) a pull request review with a summary body and an array of inline
* review comments. Each inline comment may contain a `suggestion` code block, which
* only renders GitHub's "Apply suggestion" button when posted via the review API
* (not via `updateComment` / `issues.createComment`).
*
* The review is always posted with `event: 'REQUEST_CHANGES'`. This is intentional:
* it lets the cleanup step dismiss prior reviews (GitHub's API only allows dismissing
* APPROVED or CHANGES_REQUESTED reviews, not COMMENTED ones). The review is informational
* (not blocking merge by itself) — the inline suggestions can be applied with one click.
*
* Cleanup: any prior review whose body starts with the marker (derived from
* `test.fileUrl`) AND has state `CHANGES_REQUESTED` is dismissed. The inline review
* comments that belong to any marked review (regardless of state) are deleted. The
* marker check ensures we only touch our own reviews, never human ones. The state
* check handles the cases GitHub won't let us dismiss (COMMENTED, DISMISSED) and
* is a no-op for already-dismissed reviews.
*
* If both `test.body` and `test.comments` are empty, the function only performs cleanup
* (dismiss prior reviews, delete orphan comments) and skips creating a new review. This
* is useful for "nothing to remind about" cases where a prior review should be cleared
* without leaving a stub.
*
* @param {object} test - Information about the test script that wants to update the review.
* @param {URL} test.fileUrl - URL of the test file. Used to derive the marker.
* @param {string} test.body - The review summary body (shown once, above the inline comments).
* @param {ReviewComment[]} test.comments - The inline review comments to attach. Each is anchored to a specific line in a file.
* @returns {Promise} A promise that is fulfilled once all GitHub operations have completed.
*/
export async function updateReview(test) {
if (prData.head.repo.full_name !== prData.base.repo.full_name) {
console.warn(styleText('yellow', 'Warning:'), 'This PR is created from a forked repository, so there is no write permission for the repo.');
return undefined;
}
const oflRootPath = fileURLToPath(new URL('../../', import.meta.url));
const relativeFilePath = path.relative(oflRootPath, fileURLToPath(test.fileUrl));
const marker = `<!-- GITHUB-TEST-REVIEW: ${relativeFilePath} -->`;
await cleanupPriorReviews(marker);
// Post the new review, unless the caller only wanted cleanup.
if (test.body === '' && test.comments.length === 0) {
console.log(`Skipping review creation at ${process.env.GITHUB_REPOSITORY}#${process.env.GITHUB_PR_NUMBER} (no body, no comments — cleanup-only mode).`);
return undefined;
}
console.log(`Creating review at ${process.env.GITHUB_REPOSITORY}#${process.env.GITHUB_PR_NUMBER} with ${test.comments.length} inline comment(s).`);
return githubClient.rest.pulls.createReview({
owner: repositoryOwner,
repo: repositoryName,
// eslint-disable-next-line camelcase -- required by GitHub API
pull_number: process.env.GITHUB_PR_NUMBER,
// eslint-disable-next-line camelcase -- required by GitHub API
commit_id: getHeadSha(),
body: `${marker}\n${test.body}`,
event: 'REQUEST_CHANGES',
comments: test.comments.map((comment) => ({
path: comment.path,
line: comment.line,
side: comment.side || 'RIGHT',
body: comment.body,
})),
});
}
/**
* Paginate `pulls.listReviews` and return the flat array of review objects.
* @returns {Promise<object[]>} All reviews on the current PR.
*/
async function fetchExistingReviews() {
return githubClient.paginate(githubClient.rest.pulls.listReviews, {
owner: repositoryOwner,
repo: repositoryName,
// eslint-disable-next-line camelcase -- required by GitHub API
pull_number: process.env.GITHUB_PR_NUMBER,
// eslint-disable-next-line camelcase -- required by GitHub API
per_page: 100,
});
}
/**
* Paginate `pulls.listReviewComments` and return the flat array of review comment objects.
* @returns {Promise<object[]>} All inline review comments on the current PR.
*/
async function fetchExistingReviewComments() {
return githubClient.paginate(githubClient.rest.pulls.listReviewComments, {
owner: repositoryOwner,
repo: repositoryName,
// eslint-disable-next-line camelcase -- required by GitHub API
pull_number: process.env.GITHUB_PR_NUMBER,
// eslint-disable-next-line camelcase -- required by GitHub API
per_page: 100,
});
}
/**
* Dismiss prior reviews posted by this test and delete their inline review comments.
*
* Reviews and comments are matched to this test by a hidden marker (derived from
* `test.fileUrl`). The state filter (`CHANGES_REQUESTED`) means we never try to
* dismiss reviews we couldn't have posted (APPROVED/COMMENTED/DISMISSED) and
* never touch human reviews (which lack the marker). Inline comments are
* matched by their parent review's `pull_request_review_id` because the marker
* only appears in the review body, not in the comment body.
*
* `Promise.allSettled` is used so a single failure does not abort the remaining
* cleanup; all cleanup is best-effort.
*
* @param {string} marker - The hidden HTML marker identifying reviews from this test.
* @returns {Promise<void>} Resolves when all cleanup operations have completed (success or failure).
*/
async function cleanupPriorReviews(marker) {
const existingReviews = await fetchExistingReviews();
// Identify reviews posted by this test (matched by the hidden marker in their body).
// These IDs are used both to filter the dismissal candidates and to identify
// which inline review comments belong to our reviews for deletion.
const markedReviews = existingReviews.filter((review) => review.body && review.body.startsWith(marker));
const markedReviewIds = new Set(markedReviews.map((review) => review.id));
const dismissPromises = markedReviews
.filter((review) => review.state === 'CHANGES_REQUESTED')
.map((review) => {
console.log(`Dismissing old review ${review.id} at ${process.env.GITHUB_REPOSITORY}#${process.env.GITHUB_PR_NUMBER}.`);
return githubClient.rest.pulls.dismissReview({
owner: repositoryOwner,
repo: repositoryName,
// eslint-disable-next-line camelcase -- required by GitHub API
pull_number: process.env.GITHUB_PR_NUMBER,
// eslint-disable-next-line camelcase -- required by GitHub API
review_id: review.id,
message: 'Superseded by a new run of the metadata-update-reminder test.',
});
});
const existingComments = await fetchExistingReviewComments();
const deletePromises = existingComments
.filter((comment) => markedReviewIds.has(comment.pull_request_review_id))
.map((comment) => {
console.log(`Deleting old review comment ${comment.id} (from marked review) at ${process.env.GITHUB_REPOSITORY}#${process.env.GITHUB_PR_NUMBER}.`);
return githubClient.rest.pulls.deleteReviewComment({
owner: repositoryOwner,
repo: repositoryName,
// eslint-disable-next-line camelcase -- required by GitHub API
comment_id: comment.id,
});
});
await Promise.allSettled([...dismissPromises, ...deletePromises]);
}
/**
* Fetch the UTF-8 text content of a file at a specific ref.
* @param {string} filePath - Path of the file relative to the repo root.
* @param {string} ref - The git ref (branch name, tag, or commit SHA) to fetch from.
* @returns {Promise<string>} The file content as a UTF-8 string.
*/
export async function getFileContent(filePath, ref) {
const { data } = await githubClient.rest.repos.getContent({
owner: repositoryOwner,
repo: repositoryName,
path: filePath,
ref,
});
if (Array.isArray(data) || data.type !== 'file') {
throw new Error(`${filePath} at ${ref} is not a regular file.`);
}
return Buffer.from(data.content, 'base64').toString('utf-8');
}
/**
* Fetch the unified diff patch for a file in the PR. Returns undefined if the patch is not
* available (e.g., file too large, binary file, or no diff).
* @param {string} filePath - Path of the file relative to the repo root.
* @returns {Promise<string | undefined>} The unified diff patch, or undefined if not available.
*/
export async function getFilePatch(filePath) {
const files = await githubClient.paginate(githubClient.rest.pulls.listFiles, {
owner: repositoryOwner,
repo: repositoryName,
// eslint-disable-next-line camelcase -- required by GitHub API
pull_number: process.env.GITHUB_PR_NUMBER,
// eslint-disable-next-line camelcase -- required by GitHub API
per_page: 100,
});
return files.find((file) => file.filename === filePath)?.patch;
}