forked from OSS-Docs-Tools/code-owner-self-merge
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
505 lines (447 loc) · 14.5 KB
/
index.js
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
// @ts-check
const { context, getOctokit } = require("@actions/github");
const core = require("@actions/core");
const Codeowners = require("codeowners");
const { readFileSync } = require("fs");
// Effectively the main function
async function run() {
core.info("Running version 1.6.5");
// Tell folks they can merge
if (context.eventName === "pull_request_target") {
commentOnMergablePRs();
}
// Merge if they say they have access
if (
context.eventName === "issue_comment" ||
context.eventName === "pull_request_review"
) {
const bodyLower = getPayloadBody().toLowerCase();
if (bodyLower.includes("lgtm") && !bodyLower.includes("lgtm but")) {
new Actor().mergeIfHasAccess();
} else if (bodyLower.includes("@github-actions close")) {
new Actor().closePROrIssueIfInCodeowners();
} else if (bodyLower.includes("@github-actions reopen")) {
new Actor().reopenPROrIssueIfInCodeowners();
} else {
console.log("Doing nothing because the body does not include a command");
}
}
}
async function commentOnMergablePRs() {
if (context.eventName !== "pull_request_target") {
throw new Error(
"This function can only run when the workflow specifies `pull_request_target` in the `on:`."
);
}
// Setup
const cwd = core.getInput("cwd") || process.cwd();
const githubToken = process.env.GITHUB_TOKEN;
if (!githubToken) {
throw new Error(
"GITHUB_TOKEN is not defined in the environment variables."
);
}
const octokit = getOctokit(githubToken);
const pr = context.payload.pull_request;
if (pr === undefined) {
console.log("Pull request payload is undefined");
process.exit(0);
}
const thisRepo = { owner: context.repo.owner, repo: context.repo.repo };
core.info(
`\nLooking at PR: '${pr.title}' to see if the changed files all fit inside one set of code-owners to make a comment`
);
const co = new Codeowners(cwd);
core.info(`Code-owners file found at: ${co.codeownersFilePath}`);
const changedFiles = await getPRChangedFiles(octokit, thisRepo, pr.number);
core.info(`Changed files: \n - ${changedFiles.join("\n - ")}`);
const codeowners = findCodeOwnersForChangedFiles(changedFiles, cwd);
core.info(`Code-owners: \n - ${codeowners.users.join("\n - ")}`);
core.info(`Labels: \n - ${codeowners.labels.join("\n - ")}`);
if (!codeowners.users.length) {
console.log("This PR does not have any code-owners");
process.exit(0);
}
// Determine who has access to merge every file in this PR
const ownersWhoHaveAccessToAllFilesInPR = [];
codeowners.users.forEach((owner) => {
const filesWhichArentOwned = getFilesNotOwnedByCodeOwner(
owner,
changedFiles,
cwd
);
if (filesWhichArentOwned.length === 0)
ownersWhoHaveAccessToAllFilesInPR.push(owner);
});
if (!ownersWhoHaveAccessToAllFilesInPR.length) {
console.log(
"This PR does not have any code-owners who own all of the files in the PR"
);
listFilesWithOwners(changedFiles, cwd);
const labelToAdd = core.getInput("if_no_maintainers_add_label");
if (labelToAdd) {
const labelConfig = {
name: labelToAdd,
color: Math.random().toString(16).slice(2, 8),
};
await createOrAddLabel(
octokit,
{ ...thisRepo, id: pr.number },
labelConfig
);
}
const assignees = core.getInput("if_no_maintainers_assign");
if (assignees) {
const usernames = assignees
.split(" ")
.map((u) => u.replace("@", "").trim());
await octokit.rest.issues.addAssignees({
...thisRepo,
issue_number: pr.number,
assignees: usernames,
});
}
process.exit(0);
}
const ourSignature = "<!-- Message About Merging -->";
const comments = await octokit.rest.issues.listComments({
...thisRepo,
issue_number: pr.number,
});
const existingComment = comments.data.find((c) =>
c.body?.includes(ourSignature)
);
if (existingComment) {
console.log("There is an existing comment");
process.exit(0);
}
const owners = ownersWhoHaveAccessToAllFilesInPR.join(", ");
const message = `Thanks for the PR!
This section of the codebase is owned by ${owners} - if they write a comment saying "LGTM" then it will be merged.
${ourSignature}`;
const skipOutput = core.getInput("quiet");
if (!skipOutput) {
await octokit.rest.issues.createComment({
...thisRepo,
issue_number: pr.number,
body: message,
});
}
// Add labels
for (const label of codeowners.labels) {
const labelConfig = {
name: label,
color: Math.random().toString(16).slice(2, 8),
};
await createOrAddLabel(
octokit,
{ ...thisRepo, id: pr.number },
labelConfig
);
}
}
/**
* @param {string[]} files
*/
function pathListToMarkdown(files) {
return files
.map(
(i) =>
`* [\`${i}\`](https://github.com/${context.repo.owner}/${
context.repo.repo
}/tree/HEAD${encodeURIComponent(i)})`
)
.join("\n");
}
function getPayloadBody() {
const body = context.payload.comment
? context.payload.comment.body
: context.payload.review.body;
if (body == null) {
throw new Error(`No body found, ${JSON.stringify(context)}`);
}
return body;
}
class Actor {
constructor() {
this.cwd = core.getInput("cwd") || process.cwd();
const githubToken = process.env.GITHUB_TOKEN;
if (!githubToken) {
throw new Error(
"GITHUB_TOKEN is not defined in the environment variables"
);
}
this.octokit = getOctokit(githubToken);
this.thisRepo = { owner: context.repo.owner, repo: context.repo.repo };
this.issue = context.payload.issue || context.payload.pull_request;
/** @type {string} - GitHub login */
this.sender = context.payload.sender ? context.payload.sender.login : null;
}
async getTargetPRIfHasAccess() {
const { octokit, thisRepo, sender, issue, cwd } = this;
core.info(
`\n\nLooking at the ${context.eventName} from ${sender} in '${issue.title}' to see if we can proceed`
);
const changedFiles = await getPRChangedFiles(
octokit,
thisRepo,
issue.number
);
core.info(`Changed files: \n - ${changedFiles.join("\n - ")}`);
const filesWhichArentOwned = getFilesNotOwnedByCodeOwner(
"@" + sender,
changedFiles,
cwd
);
if (filesWhichArentOwned.length !== 0) {
console.log(
`@${sender} does not have access to \n - ${filesWhichArentOwned.join(
"\n - "
)}\n`
);
listFilesWithOwners(changedFiles, cwd);
await octokit.rest.issues.createComment({
...thisRepo,
issue_number: issue.number,
body: `Sorry @${sender}, you don't have access to these files:\n\n${pathListToMarkdown(
filesWhichArentOwned
)}.`,
});
return;
}
const prInfo = await octokit.rest.pulls.get({
...thisRepo,
pull_number: issue.number,
});
if (prInfo.data.state.toLowerCase() !== "open") {
await octokit.rest.issues.createComment({
...thisRepo,
issue_number: issue.number,
body: `Sorry @${sender}, this PR isn't open.`,
});
return;
}
return prInfo;
}
async mergeIfHasAccess() {
const prInfo = await this.getTargetPRIfHasAccess();
if (!prInfo) {
return;
}
const { octokit, thisRepo, issue, sender } = this;
// Don't try merge unmergable stuff
if (!prInfo.data.mergeable) {
await octokit.rest.issues.createComment({
...thisRepo,
issue_number: issue.number,
body: `Sorry @${sender}, this PR has merge conflicts. They'll need to be fixed before this can be merged.`,
});
return;
}
// Don't merge red PRs
const statusInfo = await octokit.rest.repos.listCommitStatusesForRef({
...thisRepo,
ref: prInfo.data.head.sha,
});
const failedStatus = statusInfo.data
// Check only the most recent for a set of duplicated statuses
.filter(
(thing, index, self) =>
index === self.findIndex((t) => t.target_url === thing.target_url)
)
.find((s) => s.state !== "success");
if (failedStatus) {
await octokit.rest.issues.createComment({
...thisRepo,
issue_number: issue.number,
body: `Sorry @${sender}, this PR could not be merged because it wasn't green. Blocked by [${failedStatus.context}](${failedStatus.target_url}): '${failedStatus.description}'.`,
});
return;
}
core.info(`Creating comments and merging`);
try {
const coauthor = `Co-authored-by: ${sender} <${sender}@users.noreply.github.com>`;
// @ts-ignore
await octokit.rest.pulls.merge({
...thisRepo,
pull_number: issue.number,
merge_method: core.getInput("merge_method") || "squash",
commit_message: coauthor,
});
await octokit.rest.issues.createComment({
...thisRepo,
issue_number: issue.number,
body: `Merging because @${sender} is a code-owner of all the changes - thanks!`,
});
} catch (error) {
core.info(`Merging (or commenting) failed:`);
core.error(error);
core.setFailed("Failed to merge");
const linkToCI = `https://github.com/${thisRepo.owner}/${thisRepo.repo}/actions/runs/${process.env.GITHUB_RUN_ID}?check_suite_focus=true`;
await octokit.rest.issues.createComment({
...thisRepo,
issue_number: issue.number,
body: `There was an issue merging, maybe try again ${sender}. <a href="${linkToCI}">Details</a>`,
});
}
}
async closePROrIssueIfInCodeowners() {
// Because closing a PR/issue does not mutate the repo, we can use a weaker
// authentication method: basically is the person in the codeowners? Then they can close
// an issue or PR.
if (!githubLoginIsInCodeowners(this.sender, this.cwd)) return;
const { octokit, thisRepo, issue, sender } = this;
core.info(`Creating comments and closing`);
await octokit.rest.issues.update({
...thisRepo,
issue_number: issue.number,
state: "closed",
});
await octokit.rest.issues.createComment({
...thisRepo,
issue_number: issue.number,
body: `Closing because @${sender} is one of the code-owners of this repository.`,
});
}
async reopenPROrIssueIfInCodeowners() {
if (!githubLoginIsInCodeowners(this.sender, this.cwd)) return;
const { octokit, thisRepo, issue, sender } = this;
core.info(`Creating comments and reopening`);
await octokit.rest.issues.update({
...thisRepo,
issue_number: issue.number,
state: "open",
});
await octokit.rest.issues.createComment({
...thisRepo,
issue_number: issue.number,
body: `Reopening because @${sender} is one of the code-owners of this repository.`,
});
}
}
/**
*
* @param {string} owner
* @param {string[]} files
* @param {string} cwd
*/
function getFilesNotOwnedByCodeOwner(owner, files, cwd) {
const filesWhichArentOwned = [];
const codeowners = new Codeowners(cwd);
for (const file of files) {
const relative = file.startsWith("/") ? file.slice(1) : file;
let owners = codeowners.getOwner(relative);
if (!owners.includes(owner)) {
filesWhichArentOwned.push(file);
}
}
return filesWhichArentOwned;
}
/**
* This is a reasonable security measure for proving an account is specified in the codeowners
* but _SHOULD NOT_ be used for authentication for something which mutates the repo,
*
* @param {string} login
* @param {string} cwd
*/
function githubLoginIsInCodeowners(login, cwd) {
const codeowners = new Codeowners(cwd);
const contents = readFileSync(
codeowners.codeownersFilePath,
"utf8"
).toLowerCase();
return (
contents.includes("@" + login.toLowerCase() + " ") ||
contents.includes("@" + login.toLowerCase() + "\n")
);
}
/**
*
* @param {string[]} files
* @param {string} cwd
*/
function listFilesWithOwners(files, cwd) {
const codeowners = new Codeowners(cwd);
console.log("\nKnown code-owners for changed files:");
for (const file of files) {
const relative = file.startsWith("/") ? file.slice(1) : file;
let owners = codeowners.getOwner(relative);
console.log(`- ${file} (${owners.join(", ")})`);
}
console.log("\n> CODEOWNERS file:");
console.log(readFileSync(codeowners.codeownersFilePath, "utf8"));
}
function findCodeOwnersForChangedFiles(changedFiles, cwd) {
const owners = new Set();
const labels = new Set();
const codeowners = new Codeowners(cwd);
for (const file of changedFiles) {
const relative = file.startsWith("/") ? file.slice(1) : file;
const filesOwners = codeowners.getOwner(relative);
filesOwners.forEach((o) => {
if (o.startsWith("@")) owners.add(o);
if (o.startsWith("[")) labels.add(o.slice(1, o.length - 1));
});
}
return {
users: Array.from(owners),
labels: Array.from(labels),
};
}
async function getPRChangedFiles(octokit, repoDeets, prNumber) {
// https://developer.github.com/v3/pulls/#list-pull-requests-files
const options = octokit.rest.pulls.listFiles.endpoint.merge({
...repoDeets,
pull_number: prNumber,
});
/** @type { import("@octokit/types").PullsListFilesResponseData} */
const files = await octokit.paginate(options);
const fileStrings = files.map((f) => `/${f.filename}`);
return fileStrings;
}
async function createOrAddLabel(octokit, repoDeets, labelConfig) {
let label = null;
const existingLabels = await octokit.paginate(
"GET /repos/:owner/:repo/labels",
{ owner: repoDeets.owner, repo: repoDeets.repo }
);
label = existingLabels.find((l) => l.name == labelConfig.name);
// Create the label if it doesn't exist yet
if (!label) {
await octokit.rest.issues.createLabel({
owner: repoDeets.owner,
repo: repoDeets.repo,
name: labelConfig.name,
color: labelConfig.color,
description: labelConfig.description,
});
}
await octokit.rest.issues.addLabels({
owner: repoDeets.owner,
repo: repoDeets.repo,
issue_number: repoDeets.id,
labels: [labelConfig.name],
});
}
// For tests
module.exports = {
getFilesNotOwnedByCodeOwner,
findCodeOwnersForChangedFiles,
githubLoginIsInCodeowners,
};
// @ts-ignore
if (!module.parent) {
try {
run();
} catch (error) {
core.setFailed(error.message);
throw error;
}
}
// Bail correctly
process.on("uncaughtException", function (err) {
core.setFailed(err.message);
console.error(new Date().toUTCString() + " uncaughtException:", err.message);
console.error(err.stack);
process.exit(1);
});