-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathindex.ts
More file actions
303 lines (263 loc) · 11.8 KB
/
Copy pathindex.ts
File metadata and controls
303 lines (263 loc) · 11.8 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
import { Probot, ProbotOctokit } from "probot";
import { OctokitResponse, GetResponseTypeFromEndpointMethod } from "@octokit/types";
type Octokit = InstanceType<typeof ProbotOctokit>;
type PullsListFilesResponseData = GetResponseTypeFromEndpointMethod<Octokit["pulls"]["listFiles"]>["data"]
const NEW_PLUGIN = "plugin added";
const REMOVE_PLUGIN = "plugin removed";
const PLUGIN_CHANGE = "plugin change";
const NON_AUTHOR_PLUGIN_CHANGE = "non-author plugin change";
const NON_COMMIT_PLUGIN_CHANGE = "non-commit plugin change";
const PACKAGE_CHANGE = "package change";
const DEPENDENCY_CHANGE = "dependency change";
const READY_TO_MERGE = "ready to merge";
const WAITING_FOR_AUTHOR = "waiting for author";
const TEAM = {
org: "runelite",
team_slug: "plugin-approvers",
};
// If you run the app outside of an org it can't get to the org's teams
let globalTeamGithub : Octokit | undefined;
if (process.env.TEAM_TOKEN) {
globalTeamGithub = new ProbotOctokit({auth: {token: process.env.TEAM_TOKEN}});
}
type SizeBucket = {label: string, maxSize: number};
const SIZE_BUCKETS: SizeBucket[] = [ // not a dict to preserve ordering
{label: 'size-0', maxSize: 0},
{label: 'size-xs', maxSize: 25},
{label: 'size-s', maxSize: 250},
{label: 'size-m', maxSize: 1000},
{label: 'size-l', maxSize: 4000},
{label: 'size-xl', maxSize: 1e9},
];
export = (app: Probot) => {
app.on(['pull_request.opened', 'pull_request.synchronize', 'pull_request.reopened'], async context => {
const github = context.octokit;
let { data: labelList } = await github.issues.listLabelsOnIssue(context.issue());
let labels = new Set(labelList.map(l => l.name));
const setHasLabel = async (condition: boolean, label: string) => {
if (condition && !labels.has(label)) {
await github.issues.addLabels(context.issue({ labels: [label] }));
} else if (!condition && labels.has(label)) {
await github.issues.removeLabel(context.issue({ name: label }));
}
};
await setHasLabel(false, READY_TO_MERGE);
let pluginFiles: PullsListFilesResponseData = [];
let dependencyFiles: PullsListFilesResponseData = [];
let otherFiles: PullsListFilesResponseData = [];
(await github.pulls.listFiles(context.pullRequest()))
.data
.forEach(f => {
if (f.filename.startsWith("plugins/")) {
pluginFiles.push(f);
} else if (f.filename == "package/verification-template/build.gradle"
|| f.filename == "package/verification-template/gradle/verification-metadata.xml") {
dependencyFiles.push(f);
} else {
otherFiles.push(f);
}
});
await setHasLabel(dependencyFiles.length > 0, DEPENDENCY_CHANGE);
await setHasLabel(otherFiles.length > 0, PACKAGE_CHANGE);
await setHasLabel(pluginFiles.some(f => f.status == "added"), NEW_PLUGIN);
await setHasLabel(pluginFiles.some(f => f.status == "modified"), PLUGIN_CHANGE);
await setHasLabel(pluginFiles.some(f => f.status == "removed"), REMOVE_PLUGIN);
let diffLines: string[] = [];
let diffSizes: number[] = [];
const prAuthor = (await github.issues.get(context.issue())).data.user!.login.toLowerCase();
let nonAuthorChange = false;
let nonCommitChange = false;
await Promise.all(pluginFiles.map(async file => {
let pluginName = file.filename.replace("plugins/", "");
let readKV = (res: OctokitResponse<string>) => res.data.split("\n")
.map(i => /([^=]+)=(.*)/.exec(i))
.filter(i => i)
.reduce((acc: { [key: string]: string }, val) => {
acc[val![1]] = val![2];
return acc;
}, {});
let newPlugin = readKV(await github.request(file.raw_url));
let extractURL = (cloneURL: string) => {
let urlmatch = /https:\/\/github\.com\/([^/]+)\/([^.]+).git/.exec(cloneURL);
if (!urlmatch) {
throw `Plugin repository must be a github https clone url, not \`${cloneURL}\``;
}
let [, user, repo] = urlmatch;
return { user, repo };
};
let { user, repo } = extractURL(newPlugin.repository);
let changedPluginAuthors: Set<string> = new Set();
let sanitizeAuthor = (author: string) => author.trim().toLowerCase();
let addPluginAuthors = (authors?: string) => {
if (!authors) {
return;
}
authors.split(',')
.forEach(author => changedPluginAuthors.add(sanitizeAuthor(author)));
};
changedPluginAuthors.add(sanitizeAuthor(user));
if (file.status == "modified") {
let oldPlugin = readKV(await github.request(`https://github.com/${context.repo().owner}/${context.repo().repo}/raw/master/plugins/${pluginName}`));
let oldPluginURL = extractURL(oldPlugin.repository);
changedPluginAuthors.add(sanitizeAuthor(oldPluginURL.user));
addPluginAuthors(oldPlugin.authors);
if (Object.keys(oldPlugin).length !== Object.keys(newPlugin).length) {
nonCommitChange = true;
} else if (Object.keys(oldPlugin).some(k => k !== 'commit' && oldPlugin[k] !== newPlugin[k])) {
nonCommitChange = true;
}
diffLines.push(`\`${pluginName}\`: [${oldPlugin.commit}..${newPlugin.commit}](https://github.com/${oldPluginURL.user}/${oldPluginURL.repo}/compare/${oldPlugin.commit}..${user}:${newPlugin.commit})`);
diffSizes.push(await getDiffSize(github, user, repo, `${oldPluginURL.user}:${oldPlugin.commit}`, `${user}:${newPlugin.commit}`));
} else if (file.status == "added") {
diffLines.push(`New plugin \`${pluginName}\`: https://github.com/${user}/${repo}/tree/${newPlugin.commit}`);
diffSizes.push(NaN); // no way to fetch new plugin size yet, but also don't want to say "0"
} else if (file.status == "renamed") {
let oldPluginName = ((file as any).previous_filename as string).replace("plugins/", "");
let oldPlugin = readKV(await github.request(`https://github.com/${context.repo().owner}/${context.repo().repo}/raw/master/plugins/${oldPluginName}`));
let oldPluginURL = extractURL(oldPlugin.repository);
diffLines.push(`\`${oldPluginName}\` renamed to \`${pluginName}\`; this will cause all current installs to become uninstalled.
[${oldPlugin.commit}..${newPlugin.commit}](https://github.com/${oldPluginURL.user}/${oldPluginURL.repo}/compare/${oldPlugin.commit}..${user}:${newPlugin.commit})`);
} else if (file.status === "removed") {
diffLines.push(`Removed \`${pluginName}\`; instead of removing the plugin hub manifest file, add the disabled flag with a corresponding reason.
\`\`\`
repository=...
commit=...
disabled=<Reason for disabling>
\`\`\``);
} else {
diffLines.push(`What is a \`${file.status}\`?`);
}
nonAuthorChange ||= !changedPluginAuthors.has(prAuthor);
}));
let difftext = diffLines.join("\n\n");
const totalSize = diffSizes.reduce((a, b) => a + b, 0);
const matchedBucket = isNaN(totalSize) ? undefined :
SIZE_BUCKETS.reduceRight((chosenBucket, nextBucket) => totalSize <= nextBucket.maxSize ? nextBucket : chosenBucket);
for (let bucket of SIZE_BUCKETS) {
await setHasLabel(bucket === matchedBucket, bucket.label);
}
if (nonAuthorChange) {
difftext = "**Includes changes by non-author**\n\n" + difftext;
await setHasLabel(true, NON_AUTHOR_PLUGIN_CHANGE);
} else {
await setHasLabel(false, NON_AUTHOR_PLUGIN_CHANGE);
}
if (nonCommitChange) {
difftext = "**Includes non-commit plugin change**\n\n" + difftext;
await setHasLabel(true, NON_COMMIT_PLUGIN_CHANGE);
} else {
await setHasLabel(false, NON_COMMIT_PLUGIN_CHANGE);
}
if (dependencyFiles.length > 0 || otherFiles.length > 0) {
difftext = "**Includes non-plugin changes**\n\n" + difftext;
}
let marker = "<!-- rlphc -->";
let body = marker + "\n" + difftext;
let sticky = (await github.issues.listComments(context.issue()))
.data.find(c => c.body?.startsWith(marker));
if (sticky) {
await github.issues.updateComment(context.issue({ comment_id: sticky.id, body }));
} else if (difftext) {
await github.issues.createComment(context.issue({ body }));
}
});
app.on(["pull_request_review.submitted"], async context => {
const github = context.octokit;
const teamGithub = globalTeamGithub || github;
let { data: labelList } = await github.issues.listLabelsOnIssue(context.issue());
let labels = new Set(labelList.map(l => l.name));
if (!labels.has(PLUGIN_CHANGE)) return;
let { data: reviews } = await github.pulls.listReviews(context.pullRequest());
if (reviews.length <= 0) return;
let { data: memberList } = await teamGithub.teams.listMembersInOrg(TEAM);
let members = new Set(memberList.map(m => m.login));
let reviewStates: { [key: string]: boolean } = {};
reviews.filter(r => r.user && members.has(r.user.login))
.forEach(r => {
let approved = r.state == "APPROVED" || r.body == "lgtm";
if (approved || (!approved && r.state != "COMMENTED")) {
reviewStates[r.user!.login] = approved;
}
});
let unapproved = Object.keys(reviewStates).filter(k => !reviewStates[k]);
if (unapproved.length > 0) {
console.log(`Unapproved for #${context.issue().issue_number}: ${unapproved}`);
if (labels.has(READY_TO_MERGE)) {
await github.issues.removeLabel(context.issue({ name: READY_TO_MERGE }));
}
} else if (Object.keys(reviewStates).length != 0) {
if (!labels.has(READY_TO_MERGE)) {
await github.issues.addLabels(context.issue({ labels: [READY_TO_MERGE] }));
}
}
});
// auto-approve workflow runs for new contributors
app.on("workflow_run.requested", async context => {
const run = context.payload.workflow_run;
if (run.conclusion !== "action_required") {
return;
}
try {
await context.octokit.actions.approveWorkflowRun(context.repo({ run_id: run.id }));
} catch (e) {
console.log(`Error approving workflow run ${run.id}: ${e}`);
}
});
// if "waiting for author" is present, remove it when the author interacts
// reviewers still need to add the label manually themselves in the first place
app.on([
"pull_request.edited",
"pull_request.opened",
"pull_request.reopened",
"pull_request.synchronize",
"issue_comment.created"
], async context => {
const github = context.octokit;
const prAuthor = (await github.issues.get(context.issue())).data.user!.login.toLowerCase();
if (context.payload.sender.login.toLowerCase() !== prAuthor) {
return;
}
let { data: labelList } = await github.issues.listLabelsOnIssue(context.issue());
let labels = new Set(labelList.map(l => l.name));
if (labels.has(WAITING_FOR_AUTHOR)) {
await github.issues.removeLabel(context.issue({ name: WAITING_FOR_AUTHOR }));
}
});
}
async function getDiffSize(github: Octokit, owner: string, repo: string, ref1: string, ref2: string): Promise<number> {
// Note: GitHub's api only allows us to diff commits as if they're `...` (merge diff),
// despite the ui allowing comparisons via `..` (direct diff).
// Trying to use .. in the basehead returns 404.
// As far as I'm aware, it's impossible to get the equivalent of .. from the API endpoints.
let data;
try {
const response = await github.repos.compareCommitsWithBasehead({
owner: owner,
repo: repo,
basehead: `${ref1}...${ref2}`,
});
data = response.data;
} catch (e) {
// worth noting that this branch actually catches disparate histories for us,
// since github returns 404 when there is no merge base
return NaN;
}
if (data.status === 'identical') {
// this can happen if we're just renaming a repo or changing authors or something
return 0;
}
const expectedMergeBase = ref1.includes(':') ? ref1.substring(ref1.indexOf(':') + 1) : ref1;
if (data.merge_base_commit.sha !== expectedMergeBase || data.status !== 'ahead') {
// if the merge base is not ref1 then we have diverging history and can't determine size properly
return NaN;
}
if (!data.files) {
// unless this occurs when status === 'identical', it's probably just impossible to determine a proper diff
return NaN;
}
// Although the API paginates commits over a certain count,
// the diff tracked in data.files is a summary diff, i.e. it's not restricted to that page
// so we don't need to worry about traversing extra pages
return data.files.map(f => f.changes)
.reduce((a, b) => a + b, 0);
}