-
Notifications
You must be signed in to change notification settings - Fork 407
/
labeler.ts
392 lines (343 loc) · 10.9 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
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
import * as core from '@actions/core';
import * as github from '@actions/github';
import * as pluginRetry from '@octokit/plugin-retry';
import * as yaml from 'js-yaml';
import fs from 'fs';
import {Minimatch} from 'minimatch';
interface MatchConfig {
all?: string[];
any?: string[];
}
type StringOrMatchConfig = string | MatchConfig;
type LabelsConfig = Map<
string,
{stringOrMatch: StringOrMatchConfig[]; color?: string}
>;
type ClientType = ReturnType<typeof github.getOctokit>;
// GitHub Issues cannot have more than 100 labels
const GITHUB_MAX_LABELS = 100;
export async function run() {
try {
const token = core.getInput('repo-token');
const configPath = core.getInput('configuration-path', {required: true});
const syncLabels = !!core.getInput('sync-labels');
const dot = core.getBooleanInput('dot');
const prNumbers = getPrNumbers();
if (!prNumbers.length) {
core.warning('Could not get pull request number(s), exiting');
return;
}
const client: ClientType = github.getOctokit(token, {}, pluginRetry.retry);
for (const prNumber of prNumbers) {
core.debug(`looking for pr #${prNumber}`);
let pullRequest: any;
try {
const result = await client.rest.pulls.get({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
pull_number: prNumber
});
pullRequest = result.data;
} catch (error: any) {
core.warning(`Could not find pull request #${prNumber}, skipping`);
continue;
}
core.debug(`fetching changed files for pr #${prNumber}`);
const changedFiles: string[] = await getChangedFiles(client, prNumber);
if (!changedFiles.length) {
core.warning(
`Pull request #${prNumber} has no changed files, skipping`
);
continue;
}
const labelsConfig: LabelsConfig = await getLabelGlobs(
client,
configPath
);
const preexistingLabels = pullRequest.labels.map(l => l.name);
const allLabels: Set<string> = new Set<string>(preexistingLabels);
for (const [label, {stringOrMatch: globs}] of labelsConfig.entries()) {
core.debug(`processing ${label}`);
if (checkGlobs(changedFiles, globs, dot)) {
allLabels.add(label);
} else if (syncLabels) {
allLabels.delete(label);
}
}
const labelsToAdd = [...allLabels].slice(0, GITHUB_MAX_LABELS);
const excessLabels = [...allLabels].slice(GITHUB_MAX_LABELS);
try {
let newLabels: string[] = [];
if (!isListEqual(labelsToAdd, preexistingLabels)) {
await setLabels(
client,
prNumber,
labelsToAdd,
getLabelsColor(labelsConfig)
);
newLabels = labelsToAdd.filter(l => !preexistingLabels.includes(l));
}
core.setOutput('new-labels', newLabels.join(','));
core.setOutput('all-labels', labelsToAdd.join(','));
if (excessLabels.length) {
core.warning(
`Maximum of ${GITHUB_MAX_LABELS} labels allowed. Excess labels: ${excessLabels.join(
', '
)}`,
{title: 'Label limit for a PR exceeded'}
);
}
} catch (error: any) {
if (
error.name === 'HttpError' &&
error.message === 'Resource not accessible by integration'
) {
core.warning(
`The action requires write permission to add labels to pull requests. For more information please refer to the action documentation: https://github.com/actions/labeler#permissions`,
{
title: `${process.env['GITHUB_ACTION_REPOSITORY']} running under '${github.context.eventName}' is misconfigured`
}
);
core.setFailed(error.message);
} else {
throw error;
}
}
}
} catch (error: any) {
core.error(error);
core.setFailed(error.message);
}
}
function getPrNumbers(): number[] {
const pullRequestNumbers = core.getMultilineInput('pr-number');
if (pullRequestNumbers && pullRequestNumbers.length) {
const prNumbers: number[] = [];
for (const prNumber of pullRequestNumbers) {
const prNumberInt = parseInt(prNumber, 10);
if (isNaN(prNumberInt) || prNumberInt <= 0) {
core.warning(`'${prNumber}' is not a valid pull request number`);
} else {
prNumbers.push(prNumberInt);
}
}
return prNumbers;
}
const pullRequest = github.context.payload.pull_request;
if (!pullRequest) {
return [];
}
return [pullRequest.number];
}
async function getChangedFiles(
client: ClientType,
prNumber: number
): Promise<string[]> {
const listFilesOptions = client.rest.pulls.listFiles.endpoint.merge({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
pull_number: prNumber
});
const listFilesResponse = await client.paginate(listFilesOptions);
const changedFiles = listFilesResponse.map((f: any) => f.filename);
core.debug('found changed files:');
for (const file of changedFiles) {
core.debug(' ' + file);
}
return changedFiles;
}
async function getLabelGlobs(
client: ClientType,
configurationPath: string
): Promise<LabelsConfig> {
let configurationContent: string;
try {
if (!fs.existsSync(configurationPath)) {
core.info(
`The configuration file (path: ${configurationPath}) was not found locally, fetching via the api`
);
configurationContent = await fetchContent(client, configurationPath);
} else {
core.info(
`The configuration file (path: ${configurationPath}) was found locally, reading from the file`
);
configurationContent = fs.readFileSync(configurationPath, {
encoding: 'utf8'
});
}
} catch (e: any) {
if (e.name == 'HttpError' || e.name == 'NotFound') {
core.warning(
`The config file was not found at ${configurationPath}. Make sure it exists and that this action has the correct access rights.`
);
}
throw e;
}
// loads (hopefully) a `{[label:string]: string | StringOrMatchConfig[]}`, but is `any`:
const configObject: any = yaml.load(configurationContent);
// transform `any` => `Map<string,StringOrMatchConfig[]>` or throw if yaml is malformed:
return getLabelGlobMapFromObject(configObject);
}
function getLabelsColor(labelsConfig: LabelsConfig): Map<string, string> {
const labelsColor: Map<string, string> = new Map();
for (const [label, {color}] of labelsConfig.entries()) {
if (color) {
labelsColor.set(label, color);
}
}
return labelsColor;
}
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();
}
function getLabelGlobMapFromObject(configObject: any): LabelsConfig {
const labelGlobs: Map<
string,
{stringOrMatch: StringOrMatchConfig[]; color?: string}
> = new Map();
for (const label in configObject) {
if (typeof configObject[label] === 'string') {
labelGlobs.set(label, {stringOrMatch: [configObject[label]]});
} else if (configObject[label] instanceof Array) {
labelGlobs.set(label, {stringOrMatch: configObject[label]});
} else if (
typeof configObject[label] === 'object' &&
configObject[label]?.pattern
) {
labelGlobs.set(label, {
stringOrMatch: configObject[label].pattern,
color: configObject[label].color
});
} else {
throw Error(
`found unexpected type for label ${label} (should be string or array of globs)`
);
}
}
return labelGlobs;
}
function toMatchConfig(config: StringOrMatchConfig): MatchConfig {
if (typeof config === 'string') {
return {
any: [config]
};
}
return config;
}
function printPattern(matcher: Minimatch): string {
return (matcher.negate ? '!' : '') + matcher.pattern;
}
export function checkGlobs(
changedFiles: string[],
globs: StringOrMatchConfig[],
dot: boolean
): boolean {
for (const glob of globs) {
core.debug(` checking pattern ${JSON.stringify(glob)}`);
const matchConfig = toMatchConfig(glob);
if (checkMatch(changedFiles, matchConfig, dot)) {
return true;
}
}
return false;
}
function isMatch(changedFile: string, matchers: Minimatch[]): boolean {
core.debug(` matching patterns against file ${changedFile}`);
for (const matcher of matchers) {
core.debug(` - ${printPattern(matcher)}`);
if (!matcher.match(changedFile)) {
core.debug(` ${printPattern(matcher)} did not match`);
return false;
}
}
core.debug(` all patterns matched`);
return true;
}
// equivalent to "Array.some()" but expanded for debugging and clarity
function checkAny(
changedFiles: string[],
globs: string[],
dot: boolean
): boolean {
const matchers = globs.map(g => new Minimatch(g, {dot}));
core.debug(` checking "any" patterns`);
for (const changedFile of changedFiles) {
if (isMatch(changedFile, matchers)) {
core.debug(` "any" patterns matched against ${changedFile}`);
return true;
}
}
core.debug(` "any" patterns did not match any files`);
return false;
}
// equivalent to "Array.every()" but expanded for debugging and clarity
function checkAll(
changedFiles: string[],
globs: string[],
dot: boolean
): boolean {
const matchers = globs.map(g => new Minimatch(g, {dot}));
core.debug(` checking "all" patterns`);
for (const changedFile of changedFiles) {
if (!isMatch(changedFile, matchers)) {
core.debug(` "all" patterns did not match against ${changedFile}`);
return false;
}
}
core.debug(` "all" patterns matched all files`);
return true;
}
function checkMatch(
changedFiles: string[],
matchConfig: MatchConfig,
dot: boolean
): boolean {
if (matchConfig.all !== undefined) {
if (!checkAll(changedFiles, matchConfig.all, dot)) {
return false;
}
}
if (matchConfig.any !== undefined) {
if (!checkAny(changedFiles, matchConfig.any, dot)) {
return false;
}
}
return true;
}
function isListEqual(listA: string[], listB: string[]): boolean {
return listA.length === listB.length && listA.every(el => listB.includes(el));
}
async function setLabels(
client: ClientType,
prNumber: number,
labels: string[],
labelsColour: Map<string, string>
) {
// remove previous labels
await client.rest.issues.setLabels({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
issue_number: prNumber,
labels
});
for (const label of labels) {
const color = labelsColour.get(label);
if (color) {
await client.rest.issues.updateLabel({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
name: label,
color: color ?? '#EDEDED'
});
}
}
}