-
Notifications
You must be signed in to change notification settings - Fork 405
/
labeler.ts
331 lines (285 loc) · 8.61 KB
/
labeler.ts
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
import * as core from '@actions/core';
import * as github from '@actions/github';
import * as yaml from 'js-yaml';
import {
ChangedFilesMatchConfig,
getChangedFiles,
toChangedFilesMatchConfig,
checkAllChangedFiles,
checkAnyChangedFiles
} from './changedFiles';
import {
checkAnyBranch,
checkAllBranch,
toBranchMatchConfig,
BranchMatchConfig
} from './branch';
export type BaseMatchConfig = BranchMatchConfig & ChangedFilesMatchConfig;
export type MatchConfig = {
any?: BaseMatchConfig[];
all?: BaseMatchConfig[];
};
type ClientType = ReturnType<typeof github.getOctokit>;
const ALLOWED_CONFIG_KEYS = ['changed-files', 'head-branch', 'base-branch'];
export async function run() {
try {
const token = core.getInput('repo-token');
const configPath = core.getInput('configuration-path', {required: true});
const syncLabels = core.getBooleanInput('sync-labels');
const prNumber = getPrNumber();
if (!prNumber) {
core.info('Could not get pull request number from context, exiting');
return;
}
const client: ClientType = github.getOctokit(token);
const {data: pullRequest} = await client.rest.pulls.get({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
pull_number: prNumber
});
core.debug(`fetching changed files for pr #${prNumber}`);
const changedFiles: string[] = await getChangedFiles(client, prNumber);
const labelConfigs: Map<string, MatchConfig[]> = await getMatchConfigs(
client,
configPath
);
const labels: string[] = [];
const labelsToRemove: string[] = [];
for (const [label, configs] of labelConfigs.entries()) {
core.debug(`processing ${label}`);
if (checkMatchConfigs(changedFiles, configs)) {
labels.push(label);
} else if (pullRequest.labels.find(l => l.name === label)) {
labelsToRemove.push(label);
}
}
if (labels.length > 0) {
await addLabels(client, prNumber, labels);
}
if (syncLabels && labelsToRemove.length) {
await removeLabels(client, prNumber, labelsToRemove);
}
} catch (error: any) {
core.error(error);
core.setFailed(error.message);
}
}
function getPrNumber(): number | undefined {
const pullRequest = github.context.payload.pull_request;
if (!pullRequest) {
return undefined;
}
return pullRequest.number;
}
async function getMatchConfigs(
client: ClientType,
configurationPath: string
): Promise<Map<string, MatchConfig[]>> {
const configurationContent: string = await fetchContent(
client,
configurationPath
);
// loads (hopefully) a `{[label:string]: MatchConfig[]}`, but is `any`:
const configObject: any = yaml.load(configurationContent);
// transform `any` => `Map<string,MatchConfig[]>` or throw if yaml is malformed:
return getLabelConfigMapFromObject(configObject);
}
async function fetchContent(
client: ClientType,
repoPath: string
): Promise<string> {
const response: any = await client.rest.repos.getContent({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
path: repoPath,
ref: github.context.sha
});
return Buffer.from(response.data.content, response.data.encoding).toString();
}
export function getLabelConfigMapFromObject(
configObject: any
): Map<string, MatchConfig[]> {
const labelMap: Map<string, MatchConfig[]> = new Map();
for (const label in configObject) {
const configOptions = configObject[label];
if (
!Array.isArray(configOptions) ||
!configOptions.every(opts => typeof opts === 'object')
) {
throw Error(
`found unexpected type for label '${label}' (should be array of config options)`
);
}
const matchConfigs = configOptions.reduce<MatchConfig[]>(
(updatedConfig, configValue) => {
if (!configValue) {
return updatedConfig;
}
Object.entries(configValue).forEach(([key, value]) => {
// If the top level `any` or `all` keys are provided then set them, and convert their values to
// our config objects.
if (key === 'any' || key === 'all') {
if (Array.isArray(value)) {
const newConfigs = value.map(toMatchConfig);
updatedConfig.push({[key]: newConfigs});
}
} else if (ALLOWED_CONFIG_KEYS.includes(key)) {
const newMatchConfig = toMatchConfig({[key]: value});
// Find or set the `any` key so that we can add these properties to that rule,
// Or create a new `any` key and add that to our array of configs.
const indexOfAny = updatedConfig.findIndex(mc => !!mc['any']);
if (indexOfAny >= 0) {
updatedConfig[indexOfAny].any?.push(newMatchConfig);
} else {
updatedConfig.push({any: [newMatchConfig]});
}
} else {
// Log the key that we don't know what to do with.
core.info(`An unknown config option was under ${label}: ${key}`);
}
});
return updatedConfig;
},
[]
);
if (matchConfigs.length) {
labelMap.set(label, matchConfigs);
}
}
return labelMap;
}
export function toMatchConfig(config: any): BaseMatchConfig {
const changedFilesConfig = toChangedFilesMatchConfig(config);
const branchConfig = toBranchMatchConfig(config);
return {
...changedFilesConfig,
...branchConfig
};
}
export function checkMatchConfigs(
changedFiles: string[],
matchConfigs: MatchConfig[]
): boolean {
for (const config of matchConfigs) {
core.debug(` checking config ${JSON.stringify(config)}`);
if (!checkMatch(changedFiles, config)) {
return false;
}
}
return true;
}
function checkMatch(changedFiles: string[], matchConfig: MatchConfig): boolean {
if (!Object.keys(matchConfig).length) {
core.debug(` no "any" or "all" patterns to check`);
return false;
}
if (matchConfig.all) {
if (!checkAll(matchConfig.all, changedFiles)) {
return false;
}
}
if (matchConfig.any) {
if (!checkAny(matchConfig.any, changedFiles)) {
return false;
}
}
return true;
}
// equivalent to "Array.some()" but expanded for debugging and clarity
export function checkAny(
matchConfigs: BaseMatchConfig[],
changedFiles: string[]
): boolean {
core.debug(` checking "any" patterns`);
if (
!matchConfigs.length ||
!matchConfigs.some(configOption => Object.keys(configOption).length)
) {
core.debug(` no "any" patterns to check`);
return false;
}
for (const matchConfig of matchConfigs) {
if (matchConfig.baseBranch) {
if (checkAnyBranch(matchConfig.baseBranch, 'base')) {
return true;
}
}
if (matchConfig.changedFiles) {
if (checkAnyChangedFiles(changedFiles, matchConfig.changedFiles)) {
return true;
}
}
if (matchConfig.headBranch) {
if (checkAnyBranch(matchConfig.headBranch, 'head')) {
return true;
}
}
}
core.debug(` "any" patterns did not match any configs`);
return false;
}
// equivalent to "Array.every()" but expanded for debugging and clarity
export function checkAll(
matchConfigs: BaseMatchConfig[],
changedFiles: string[]
): boolean {
core.debug(` checking "all" patterns`);
if (
!matchConfigs.length ||
!matchConfigs.some(configOption => Object.keys(configOption).length)
) {
core.debug(` no "all" patterns to check`);
return false;
}
for (const matchConfig of matchConfigs) {
if (matchConfig.baseBranch) {
if (!checkAllBranch(matchConfig.baseBranch, 'base')) {
return false;
}
}
if (matchConfig.changedFiles) {
if (!changedFiles.length) {
core.debug(` no files to check "changed-files" patterns against`);
return false;
}
if (!checkAllChangedFiles(changedFiles, matchConfig.changedFiles)) {
return false;
}
}
if (matchConfig.headBranch) {
if (!checkAllBranch(matchConfig.headBranch, 'head')) {
return false;
}
}
}
core.debug(` "all" patterns matched all configs`);
return true;
}
async function addLabels(
client: ClientType,
prNumber: number,
labels: string[]
) {
await client.rest.issues.addLabels({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
issue_number: prNumber,
labels: labels
});
}
async function removeLabels(
client: ClientType,
prNumber: number,
labels: string[]
) {
await Promise.all(
labels.map(label =>
client.rest.issues.removeLabel({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
issue_number: prNumber,
name: label
})
)
);
}