forked from pascalgn/size-label-action
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·216 lines (182 loc) · 4.99 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
#!/usr/bin/env node
const fs = require("fs");
const process = require("process");
const { Octokit } = require("@octokit/rest");
const globrex = require("globrex");
const Diff = require("diff");
const core = require("@actions/core");
const defaultSizes = {
0: "XS",
10: "S",
30: "M",
100: "L",
500: "XL",
};
const actions = ["opened", "synchronize", "reopened"];
const globrexOptions = { extended: true, globstar: true };
async function main() {
debug("Running size-label-action...");
const GITHUB_TOKEN = core.getInput("token");
if (!GITHUB_TOKEN) {
throw new Error("Environment variable GITHUB_TOKEN not set!");
}
const GITHUB_EVENT_PATH = process.env.GITHUB_EVENT_PATH;
if (!GITHUB_EVENT_PATH) {
throw new Error("Environment variable GITHUB_EVENT_PATH not set!");
}
const eventDataStr = await readFile(GITHUB_EVENT_PATH);
const eventData = JSON.parse(eventDataStr);
if (!eventData || !eventData.pull_request || !eventData.pull_request.base) {
throw new Error(`Invalid GITHUB_EVENT_PATH contents: ${eventDataStr}`);
}
debug("Event payload:", eventDataStr);
if (!actions.includes(eventData.action)) {
console.log("Action will be ignored:", eventData.action);
return false;
}
const isIgnored = parseIgnored(core.getInput("ignored"));
const pullRequestHome = {
owner: eventData.pull_request.base.repo.owner.login,
repo: eventData.pull_request.base.repo.name
};
const pull_number = eventData.pull_request.number;
const octokit = new Octokit({
auth: `token ${GITHUB_TOKEN}`,
userAgent: "pascalgn/size-label-action"
});
const pullRequestDiff = await octokit.pulls.get({
...pullRequestHome,
pull_number,
headers: {
accept: "application/vnd.github.v3.diff"
}
});
const changedLines = getChangedLines(isIgnored, pullRequestDiff.data);
console.log("Changed lines:", changedLines);
const sizes = getInputAsObject("sizes");
const sizeLabel = getSizeLabel(changedLines, sizes);
console.log("Matching label:", sizeLabel);
const { add, remove } = getLabelChanges(
sizeLabel,
eventData.pull_request.labels
);
if (add.length === 0 && remove.length === 0) {
console.log("Correct label already assigned");
return false;
}
if (add.length > 0) {
debug("Adding labels:", add);
await octokit.issues.addLabels({
...pullRequestHome,
issue_number: pull_number,
labels: add
});
}
for (const label of remove) {
debug("Removing label:", label);
try {
await octokit.issues.removeLabel({
...pullRequestHome,
issue_number: pull_number,
name: label
});
} catch (error) {
debug("Ignoring removing label error:", error);
}
}
debug("Success!");
return true;
}
function debug(...str) {
if (process.env.DEBUG_ACTION) {
console.log.apply(console, str);
}
}
function parseIgnored(str = "") {
const ignored = str
.split(/\r|\n/)
.map(s => s.trim())
.filter(s => s.length > 0 && !s.startsWith("#"))
.map(s =>
s.length > 1 && s[0] === "!"
? { not: globrex(s.substr(1), globrexOptions) }
: globrex(s, globrexOptions)
);
function isIgnored(path) {
if (path == null || path === "/dev/null") {
return true;
}
const pathname = path.substr(2);
let ignore = false;
for (const entry of ignored) {
if (entry.not) {
if (pathname.match(entry.not.regex)) {
return false;
}
} else if (!ignore && pathname.match(entry.regex)) {
ignore = true;
}
}
return ignore;
}
return isIgnored;
}
async function readFile(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, { encoding: "utf8" }, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
function getChangedLines(isIgnored, diff) {
return Diff.parsePatch(diff)
.flatMap(file =>
isIgnored(file.oldFileName) && isIgnored(file.newFileName)
? []
: file.hunks
)
.flatMap(hunk => hunk.lines)
.filter(line => line[0] === "+" || line[0] === "-").length;
}
function getSizeLabel(changedLines, sizes = defaultSizes) {
let label = null;
for (const lines of Object.keys(sizes).sort((a, b) => a - b)) {
if (changedLines >= lines) {
label = `size:${sizes[lines]}`;
}
}
return label;
}
function getLabelChanges(newLabel, existingLabels) {
const add = [newLabel];
const remove = [];
for (const existingLabel of existingLabels) {
const { name } = existingLabel;
if (name.startsWith("size:")) {
if (name === newLabel) {
add.pop();
} else {
remove.push(name);
}
}
}
return { add, remove };
}
function getInputAsObject(name, options) {
let input = core.getInput(name, options);
return input ? JSON.parse(input) : undefined;
}
if (require.main === module) {
main().then(
() => (process.exitCode = 0),
e => {
process.exitCode = 1;
console.error(e);
}
);
}
module.exports = { main };