-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
executable file
·256 lines (214 loc) · 5.94 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
#!/usr/bin/env node
"use strict";
const prompt = require("prompt");
if (process.argv.length < 5) {
console.error("Usage:");
console.error(
'GITHUB_TOKEN=*** npx mass-merge <organization> <"commit message"> <author> [--ignore-checks]'
);
process.exit(1);
}
const token = process.env["GITHUB_TOKEN"];
if (!token) {
console.error("GITHUB_TOKEN environment variable required!");
console.error(
"Create a personal access token at https://github.com/settings/tokens/new?scopes=repo"
);
process.exit(1);
}
const { Octokit } = require("@octokit/core");
const octokit = new Octokit({ auth: token });
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function approve(owner, repo, pullNumber) {
await octokit.request(
"POST /repos/{owner}/{repo}/pulls/{pullNumber}/reviews",
{
owner,
repo,
pullNumber,
event: "APPROVE",
}
);
process.stdout.write("approved ");
}
async function merge(owner, repo, pullNumber) {
try {
await octokit.request(
"PUT /repos/{owner}/{repo}/pulls/{pullNumber}/merge",
{
owner,
repo,
pullNumber,
merge_method: "squash",
}
);
console.log("and merged");
} catch (error) {
console.error(`NOT MERGED ❗️ (${error.message})`);
}
}
function extractUrlParts(url) {
const match = url.match(/\/repos\/([^\/]+)\/([^\/]+)\/issues\/([^\/]+)/);
return {
owner: match[1],
repo: match[2],
id: match[3],
};
}
async function getCheckStatus(pr) {
const { owner, repo, id } = extractUrlParts(pr.url);
const detail = await octokit.request(
`GET /repos/${owner}/${repo}/pulls/${id}`
);
const sha = detail.data.head.sha;
const checks = await octokit.request(
`GET /repos/${owner}/${repo}/commits/${sha}/check-runs`
);
const runs = checks.data.check_runs;
if (runs.length < 1) {
return "missing";
} else if (
runs.every((r) => ["success", "neutral", "skipped"].includes(r.conclusion))
) {
return "success";
} else if (runs.some((r) => r.status === "queued")) {
return "queued";
} else if (runs.some((r) => r.status === "in_progress")) {
return "in_progress";
} else {
return "failed";
}
}
function constructQuery(owner, title, author, restrictToRepos) {
const parts = [
"is:open",
"is:pr",
"archived:false",
"draft:false",
"comments:0",
`author:${author}`,
"in:title",
`"${title}"`,
];
if (restrictToRepos.length === 0) {
parts.push(`org:${owner}`);
} else {
for (const repo of restrictToRepos) {
parts.push(`repo:${repo}`);
}
}
return parts.join(" ");
}
async function listAll(
owner,
title,
author,
restrictToRepos,
{ ignoreChecks = false } = {}
) {
if (author === "dependabot") {
author = "app/dependabot";
}
const query = constructQuery(owner, title, author, restrictToRepos);
const response = await octokit.request("GET /search/issues", {
q: query,
sort: "created",
order: "asc",
per_page: 100,
page: 0,
});
const toMerge = [];
const maxTitleLength = response.data.items.reduce((max, pr) => {
return Math.max(max, pr.title.length);
}, 0);
for (const pr of response.data.items) {
const { repo, id } = extractUrlParts(pr.url);
const humanURL = `https://github.com/${owner}/${repo}/pull/${id}`;
const status = await getCheckStatus(pr);
if (status === "success") {
console.log(`✅ ${pr.title.padEnd(maxTitleLength)} ${humanURL}`);
toMerge.push(pr);
} else if (["queued", "in_progress"].includes(status)) {
console.log(`❓ ${pr.title.padEnd(maxTitleLength)} ${humanURL}`);
} else if (status === "missing") {
console.log(`🤔 ${pr.title.padEnd(maxTitleLength)} ${humanURL}`);
} else {
console.log(`❌ ${pr.title.padEnd(maxTitleLength)} ${humanURL}`);
}
if (ignoreChecks && status !== "success") {
toMerge.push(pr);
}
}
console.log(
`Checked ${response.data.total_count} PRs - ${toMerge.length} ready to merge`
);
if (toMerge.length > 0) {
prompt.start();
console.log("\n");
const { confirm } = await prompt.get([
{
name: "confirm",
description: `Are you sure you want to proceed with the mass merge of ${toMerge.length} PRs? (Y/N)`,
},
]);
if (
!confirm ||
(confirm.toLowerCase() !== "n" && confirm.toLowerCase() !== "y")
) {
console.log("Please answer Y or N.");
process.exit(1);
}
if (confirm.toLowerCase() === "n") {
console.log("Exiting...");
process.exit(1);
}
}
let processed = 0;
const requiredUserLogin =
author === "app/dependabot" ? "dependabot[bot]" : author;
for (const pr of toMerge) {
const regex = new RegExp(`\/repos\/${owner}\/([^\/]+)\/`);
const repo = pr.url.match(regex)[1];
process.stdout.write(`${repo}#${pr.number} `);
// Safety checks
if (pr.user.login !== requiredUserLogin) {
console.log(
`invalid PR author: "${pr.user.login}" expected: "${requiredUserLogin}"`
);
continue;
}
if (!pr.title.toLowerCase().includes(title.toLowerCase())) {
console.log(`invalid PR title: "${pr.title}" expected: "${title}"`);
continue;
}
await sleep(2000);
await approve(owner, repo, pr.number);
await merge(owner, repo, pr.number);
processed++;
}
return {
processed,
total: response.data.items.length,
};
}
let ignoreChecks = false;
const i = process.argv.findIndex(
(arg) => arg === "--ignore-checks" || arg === "-f"
);
if (i >= 0) {
ignoreChecks = true;
process.argv.splice(i, 1);
}
let restrictToRepos = [];
if (process.argv.length > 5 && !process.argv[5].startsWith("-")) {
restrictToRepos = process.argv[5].split(",");
}
listAll(process.argv[2], process.argv[3], process.argv[4], restrictToRepos, {
ignoreChecks,
})
.then(({ processed, total }) => {
console.log(`\nDone (${processed}/${total})`);
})
.catch((e) => console.error(e));