-
Notifications
You must be signed in to change notification settings - Fork 50
/
main.ts
242 lines (208 loc) · 6.98 KB
/
main.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
import { getInput, setFailed, debug } from "@actions/core";
import { context, getOctokit } from "@actions/github";
import { load as loadYaml } from "js-yaml";
type GitHubClient = ReturnType<typeof getOctokit>["rest"];
let configPath;
async function run() {
// Configuration parameters
configPath = getInput("configuration-path", { required: true });
const token = getInput("repo-token", { required: true });
const enableVersionedRegex = parseInt(
getInput("enable-versioned-regex", { required: true })
);
const versionedRegex = new RegExp(
getInput("versioned-regex", { required: false })
);
const notBefore = Date.parse(getInput("not-before", { required: false }));
const bodyMissingRegexLabel = getInput("body-missing-regex-label", {
required: false,
});
const includeTitle = parseInt(getInput("include-title", { required: false }));
const syncLabels = parseInt(getInput("sync-labels", { required: false }));
const issue_number = getIssueOrPRNumber();
if (issue_number === undefined) {
console.log("Could not get issue or PR number from context, exiting");
return;
}
const issue_body = getIssueOrPRBody();
if (issue_body === undefined) {
console.log("Could not get issue or PR body from context, exiting");
return;
}
const issue_title = getIssueOrPRTitle();
if (!issue_title) {
console.log("Could not get issue or PR title from context, exiting");
return;
}
// A client to load data from GitHub
const { rest: client } = getOctokit(token);
/** List of labels to add */
const toAdd: string[] = [];
/** List of labels to remove */
const toRemove: string[] = [];
if (enableVersionedRegex === 1) {
const regexVersion = versionedRegex.exec(issue_body);
if (!regexVersion || !regexVersion[1]) {
if (bodyMissingRegexLabel) {
await addLabels(client, issue_number, [bodyMissingRegexLabel]);
}
console.log(
`Issue #${issue_number} does not contain regex version in the body of the issue, exiting.`
);
return;
} else if (bodyMissingRegexLabel) {
toRemove.push(bodyMissingRegexLabel);
}
configPath = regexifyConfigPath(configPath, regexVersion[1]);
}
// If the notBefore parameter has been set to a valid timestamp, exit if the current issue was created before notBefore
if (notBefore) {
const issue = await client.issues.get({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number,
});
const issueCreatedAt = Date.parse(issue.data.created_at);
if (issueCreatedAt < notBefore) {
console.log(
"Issue is before `notBefore` configuration parameter. Exiting..."
);
return;
}
}
// Load our regex rules from the configuration path
const labelRegexes = await loadConfig(client, configPath);
let issueContent = "";
if (includeTitle === 1) issueContent += `${issue_title}\n\n`;
issueContent += issue_body;
for (const [label, globs] of labelRegexes.entries()) {
if (checkRegexes(issueContent, globs)) {
toAdd.push(label);
} else if (syncLabels === 1) {
toRemove.push(label);
}
}
let promises = [];
if (toAdd.length) {
promises.push(addLabels(client, issue_number, toAdd));
}
promises = promises.concat(toRemove.map(removeLabel(client, issue_number)));
const rejected = (await Promise.allSettled(promises))
.map((p) => p.status === "rejected" && p.reason)
.filter(Boolean);
if (rejected.length) {
throw new AggregateError(rejected)
}
}
function getIssueOrPRNumber() {
const { issue, pull_request } = context.payload;
return issue?.number ?? pull_request?.number;
}
function getIssueOrPRBody() {
const { issue, pull_request } = context.payload;
if (issue?.body === null || pull_request?.body === null) {
return '';
}
return issue?.body ?? pull_request?.body;
}
function getIssueOrPRTitle(): string | undefined {
const { issue, pull_request } = context.payload;
return issue?.title ?? pull_request?.title;
}
function regexifyConfigPath(configPath: string, version: string) {
const lastIndex = configPath.lastIndexOf(".");
return `${configPath.substring(0, lastIndex)}-v${version}.yml`;
}
/** Load the configuration file */
async function loadConfig(client: GitHubClient, configPath: string) {
try {
const { data } = await client.repos.getContent({
owner: context.repo.owner,
repo: context.repo.repo,
ref: context.sha,
path: configPath,
});
if (!("content" in data)) {
throw new TypeError(
"The configuration path provided is not a valid file. Exiting"
);
}
const configContent = Buffer.from(data.content, "base64").toString("utf8");
// loads (hopefully) a `{[label:string]: string | string[]}`, but is `any`:
const configObject = loadYaml(configContent);
// transform `any` => `Map<string,string[]>` or throw if yaml is malformed:
return getLabelRegexesMapFromObject(configObject);
} catch (error) {
console.log("Error loading configuration file: " + error);
throw error;
}
}
function getLabelRegexesMapFromObject(configObject: any) {
const labelRegexes = new Map<string, string[]>();
for (const label in configObject) {
if (typeof configObject[label] === "string") {
labelRegexes.set(label, [configObject[label]]);
} else if (Array.isArray(configObject[label])) {
labelRegexes.set(label, configObject[label]);
} else {
throw Error(
`found unexpected type for label ${label} (should be string or array of regex)`
);
}
}
return labelRegexes;
}
function checkRegexes(issue_body: string, regexes: string[]) {
let found;
// If several regex entries are provided we require all of them to match for the label to be applied.
for (const regEx of regexes) {
const isRegEx = regEx.match(/^\/(.+)\/(.*)$/);
if (isRegEx) {
found = issue_body.match(new RegExp(isRegEx[1], isRegEx[2]));
} else {
found = issue_body.match(regEx);
}
if (!found) {
return false;
}
}
return true;
}
async function addLabels(
client: GitHubClient,
issue_number: number,
labels: string[]
) {
try {
const formatted = labels.map((l) => `"${l}"`).join(", ");
debug(`Adding label(s) (${formatted}) to issue #${issue_number}`);
return await client.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number,
labels,
});
} catch (error) {
console.log(`Could not add label(s) ${labels} to issue #${issue_number}`);
throw error;
}
}
function removeLabel(client: GitHubClient, issue_number: number) {
return async function (name: string) {
try {
debug(`Removing label ${name} from issue #${issue_number}`);
return await client.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number,
name,
});
} catch (error) {
console.log(
`Could not remove label "${name}" from issue #${issue_number}`
);
throw error;
}
};
}
run().catch(setFailed);