-
Notifications
You must be signed in to change notification settings - Fork 31
/
issue-bot.js
492 lines (417 loc) · 14 KB
/
issue-bot.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
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
const core = require('@actions/core');
const { context, getOctokit } = require('@actions/github');
const handlebars = require('handlebars');
let octokit;
// {key1: '', key2: 'some string', key3: undefined} => {key2: 'some string'}
const removeEmptyProps = (obj) => {
for (const key in obj) {
if (obj[key] === '' || typeof obj[key] === 'undefined') {
delete obj[key];
}
}
return obj;
};
const needPreviousIssue = (...conditions) => {
return conditions.includes(true);
};
const issueExists = (previousIssueNumber) => {
return previousIssueNumber >= 0;
};
const checkInputs = (inputs) => {
core.info(`Checking inputs: ${JSON.stringify(inputs)}`);
let ok = true;
ok = !!inputs.title;
if (inputs.projectType) {
ok = ok && (inputs.projectType === 'user' ||
inputs.projectType === 'organization' ||
inputs.projectType === 'repository');
}
if (inputs.pinned) {
ok = ok && !!inputs.labels;
}
if (inputs.closePrevious) {
ok = ok && !!inputs.labels;
}
if (inputs.linkedComments) {
ok = ok && !!inputs.labels;
}
if (inputs.rotateAssignees) {
ok = ok && !!(inputs.labels && inputs.assignees);
}
return ok;
};
const getNextAssignee = (assignees, previousAssignee) => {
core.info(`Getting next assignee from ${JSON.stringify(assignees)} with previous assignee ${previousAssignee}}`);
const index = (assignees.indexOf(previousAssignee) + 1) % assignees.length;
core.info(`Next assignee: ${assignees[index]}`);
return [assignees[index]];
};
// Is issue with issueId already pinned to this repo?
const isPinned = async (issueId) => {
core.info(`Checking if issue ${issueId} is pinned.`);
const query = `{
resource(url: "${context.repo.owner}/${context.repo.repo}") {
... on Repository {
pinnedIssues(last: 3) {
nodes {
issue {
id
}
}
}
}
}
}`;
const data = await octokit.graphql({
query,
headers: {
accept: 'application/vnd.github.elektra-preview+json'
}
});
core.debug(`isPinned data: ${JSON.stringify(data)}`);
if (!data.resource) {
return false;
}
const pinnedIssues = data.resource.pinnedIssues.nodes || [];
return pinnedIssues.findIndex(pinnedIssue => pinnedIssue.issue.id === issueId) >= 0;
};
// Given a GraphQL issue id, unpin the issue
const unpin = async (issueId) => {
if (!(await isPinned(issueId))) {
return;
}
core.info(`Unpinning ${issueId}...`);
const mutation = `mutation {
unpinIssue(input: {issueId: "${issueId}"}) {
issue {
body
}
}
}`;
return octokit.graphql({
query: mutation,
headers: {
accept: 'application/vnd.github.elektra-preview+json'
}
});
};
// Given a GraphQL issue id, pin the issue
const pin = async (issueId) => {
core.info(`Pinning ${issueId}...`);
const mutation = `mutation {
pinIssue(input: {issueId: "${issueId}"}) {
issue {
body
}
}
}`;
// TODO check if 3 issues are already pinned
return octokit.graphql({
query: mutation,
headers: {
accept: 'application/vnd.github.elektra-preview+json'
}
});
};
const createNewIssue = async (options) => {
// Remove empty props in order to make valid API calls
options = removeEmptyProps(Object.assign({}, options));
core.info(`Creating new issue with options: ${JSON.stringify(options)} and body: ${options.body}`);
const { data: { number: newIssueNumber, id: newIssueId, node_id: newIssueNodeId } } = (await octokit.rest.issues.create({
...context.repo,
title: options.title,
labels: options.labels,
assignees: options.assignees,
body: options.body
})) || {};
core.debug(`New issue number: ${newIssueNumber}`);
core.debug(`New issue id: ${newIssueId}`);
core.debug(`New issue node ID: ${newIssueNodeId}`);
return {
newIssueNumber: Number(newIssueNumber),
newIssueId,
newIssueNodeId
};
};
const closeIssue = async (issueNumber) => {
core.info(`Closing issue number ${issueNumber}...`);
return await octokit.rest.issues.update({
...context.repo,
issue_number: issueNumber,
state: 'closed'
});
};
const makeLinkedComments = async (previousIssueNumber, previousIssueText, newIssueNumber, newIssueText) => {
core.info(`Making linked comments on new issue number ${newIssueNumber} and previous issue number ${previousIssueNumber}`);
// Create comment on the new that links to the previous
await octokit.rest.issues.createComment({
...context.repo,
issue_number: newIssueNumber,
body: newIssueText
});
// Create comment on the previous that links to the new
await octokit.rest.issues.createComment({
...context.repo,
issue_number: previousIssueNumber,
body: previousIssueText
});
};
// Return previous issue matching both labels
// @input labels: ['label1', 'label2']
const getPreviousIssue = async (labels) => {
core.info(`Finding previous issue with labels: ${JSON.stringify(labels)}...`);
let previousIssueNumber; let previousIssueNodeId; let previousAssignees = '';
const data = (await octokit.rest.issues.listForRepo({
...context.repo,
labels,
state: 'all'
})).data[0];
if (data) {
previousIssueNumber = data.number;
previousIssueNodeId = data.node_id;
previousAssignees = data.assignees;
core.debug(`Previous issue number: ${previousIssueNumber}`);
core.debug(`Previous issue node id: ${previousIssueNodeId}`);
core.debug(`Previous issue assignees: ${previousAssignees}`);
} else {
core.info(`Couldn't find previous issue with labels: ${JSON.stringify(labels)}.`);
}
return {
previousIssueNumber: previousIssueNumber ? Number(previousIssueNumber) : undefined,
previousIssueNodeId,
previousAssignees
};
};
const addIssueToProjectColumn = async (options) => {
core.info(`Adding issue id ${options.issueId} to project type ${options.projectType}, project number ${options.projectNumber}, column name ${options.columnName}`);
const projects = [];
if (options.projectType === 'user') {
for await (const response of octokit.paginate.iterator(
octokit.rest.projects.listForUser,
{
username: context.repo.owner
}
)) {
projects.push(...response.data);
}
} else if (options.projectType === 'organization') {
for await (const response of octokit.paginate.iterator(
octokit.rest.projects.listForOrg,
{
org: context.repo.owner
}
)) {
projects.push(...response.data);
}
} else if (options.projectType === 'repository') {
for await (const response of octokit.paginate.iterator(
octokit.rest.projects.listForRepo,
{
...context.repo
}
)) {
projects.push(...response.data);
}
}
core.debug(`Found projects: ${JSON.stringify(projects)}`);
const project = projects.find(project => project.number === Number(options.projectNumber));
if (!project) {
throw new Error(`Project with type ${options.projectType}, number ${options.projectNumber} could not be found.`);
}
const { data: columns } = await octokit.rest.projects.listColumns({
project_id: project.id
});
core.debug(`Found columns for project id ${project.id}: ${JSON.stringify(columns)}`);
const column = columns.find(column => column.name === options.columnName);
core.debug(`Found column matching column name ${options.columnName}: ${JSON.stringify(column)}`);
if (!column) {
throw new Error(`Column with name ${options.columnName} could not be found in project with type ${options.projectType}, id ${options.projectNumber}.`);
}
core.debug(`Column name ${options.columnName} maps to column id ${column.id}`);
await octokit.rest.projects.createCard({
column_id: column.id,
content_id: options.issueId,
content_type: 'Issue'
});
};
const addIssueToProjectV2 = async (options) => {
core.info(`Adding issue with node ID ${options.issueNodeId} to project V2 URL: ${options.url}`);
const projectNodeId = await getProjectV2NodeIdFromUrl(options.url);
core.info(`Adding issue with node ID ${options.issueNodeId} to project V2 with node ID: ${projectNodeId}`);
const mutation = `
mutation {
addProjectV2ItemById(
input: {
projectId: "${projectNodeId}"
contentId: "${options.issueNodeId}"
}
) {
item {
id
}
}
}
`;
return octokit.graphql({
query: mutation,
headers: {
accept: 'application/vnd.github.elektra-preview+json'
}
});
};
const getProjectV2NodeIdFromUrl = async (url) => {
const match = /^.*(?<type>orgs|users)\/(?<name>[^/]+)\/projects\/(?<number>[0-9]+).*$/gm
.exec(url.trim());
if (!match || !match.groups || !match.groups.type || !match.groups.name || !match.groups.number) {
throw new Error('Malformed projectV2 url');
}
const { type, name, number } = match.groups;
return type === 'orgs'
? await getOrgProjectV2NodeId({ name, number })
: await getUserProjectV2NodeId({ name, number });
};
const getUserProjectV2NodeId = async (options) => {
const { name, number } = options;
const query = `
query FindUserProjectNodeID {
user(login: "${name}") {
projectV2(number: ${number}) {
id
}
}
}
`;
const data = await octokit.graphql({
query,
headers: {
accept: 'application/vnd.github.elektra-preview+json'
}
});
return data.user.projectV2.id;
};
const getOrgProjectV2NodeId = async (options) => {
const { name, number } = options;
const query = `
query FindOrgProjectNodeID {
organization(login: "${name}") {
projectV2(number: ${number}) {
id
}
}
}
`;
const data = await octokit.graphql({
query,
headers: {
accept: 'application/vnd.github.elektra-preview+json'
}
});
return data.organization.projectV2.id;
};
const addIssueToMilestone = async (issueNumber, milestoneNumber) => {
core.info(`Adding issue number ${issueNumber} to milestone number ${milestoneNumber}`);
const { data: issue } = await octokit.rest.issues.update({
...context.repo,
issue_number: issueNumber,
milestone: milestoneNumber
});
if (!issue) {
throw new Error(`Couldn't add issue ${issueNumber} to milestone ${milestoneNumber}.`);
}
};
/**
* Takes provided inputs, acts on them, and produces a single output.
* See action.yml for input descriptions.
* @param {object} inputs
*/
const run = async (inputs) => {
try {
octokit = getOctokit(inputs.token);
delete inputs.token;
core.info(`Running with inputs: ${JSON.stringify(inputs)}`);
let previousAssignee; let previousIssueNumber = -1; let previousIssueNodeId; let previousAssignees;
let projectV2IssueItemId;
if (needPreviousIssue(inputs.pinned, inputs.closePrevious, inputs.rotateAssignees, inputs.linkedComments)) {
({ previousIssueNumber, previousIssueNodeId, previousAssignees } = await getPreviousIssue(inputs.labels));
}
// Rotate assignee to next in list
if (issueExists(previousIssueNumber) && inputs.rotateAssignees) {
previousAssignee = previousAssignees.length ? previousAssignees[0].login : undefined;
inputs.assignees = getNextAssignee(inputs.assignees, previousAssignee);
}
inputs.body = handlebars.compile(inputs.body)({ previousIssueNumber, assignees: inputs.assignees });
const { newIssueNumber, newIssueId, newIssueNodeId } = await createNewIssue(inputs);
if (inputs.project && inputs.column) {
await addIssueToProjectColumn({
issueId: newIssueId,
projectType: inputs.projectType,
projectNumber: inputs.project,
columnName: inputs.column
});
}
if (inputs.projectV2) {
const response = await addIssueToProjectV2({
issueNodeId: newIssueNodeId,
url: inputs.projectV2
});
projectV2IssueItemId = response.addProjectV2ItemById.item.id;
}
if (inputs.milestone) {
await addIssueToMilestone(newIssueNumber, inputs.milestone);
}
// Write comments linking the current and previous issue
if (issueExists(previousIssueNumber) && inputs.linkedComments) {
const previousIssueText = handlebars.compile(inputs.linkedCommentsPreviousIssueText)({
previousIssueNumber,
newIssueNumber,
assignees: inputs.assignees
});
const newIssueText = handlebars.compile(inputs.linkedCommentsNewIssueText)({
previousIssueNumber,
newIssueNumber,
assignees: inputs.assignees
});
await makeLinkedComments(previousIssueNumber, previousIssueText, newIssueNumber, newIssueText);
}
// If there is a previous issue, close it out and point to the new
if (issueExists(previousIssueNumber) && inputs.closePrevious) {
await closeIssue(previousIssueNumber);
}
// If the pinned input is true, pin the current, unpin the previous
if (inputs.pinned) {
if (issueExists(previousIssueNumber)) {
await unpin(previousIssueNodeId);
}
await pin(newIssueNodeId);
}
if (newIssueNumber) {
core.info(`New issue number: ${newIssueNumber}`);
core.setOutput('issue-number', String(newIssueNumber));
}
if (previousIssueNumber) {
core.info(`Previous issue number: ${previousIssueNumber}`);
core.setOutput('previous-issue-number', String(previousIssueNumber));
}
if (projectV2IssueItemId) {
core.info(`Project V2 Issue Item Id: ${projectV2IssueItemId}`);
core.setOutput('project-v2-issue-item-id', projectV2IssueItemId);
}
} catch (error) {
core.setFailed(`Error encountered: ${error}.`);
}
};
exports.needPreviousIssue = needPreviousIssue;
exports.issueExists = issueExists;
exports.checkInputs = checkInputs;
exports.getNextAssignee = getNextAssignee;
exports.isPinned = isPinned;
exports.unpin = unpin;
exports.pin = pin;
exports.createNewIssue = createNewIssue;
exports.closeIssue = closeIssue;
exports.makeLinkedComments = makeLinkedComments;
exports.getPreviousIssue = getPreviousIssue;
exports.addIssueToProjectColumn = addIssueToProjectColumn;
exports.addIssueToProjectV2 = addIssueToProjectV2;
exports.addIssueToMilestone = addIssueToMilestone;
exports.run = run;