1import * as core from '@actions/core';
2import * as github from '@actions/github';
3
4async function run() {
5 try {
6 const labels_to_add = core.getMultilineInput('add');
7 const labels_to_remove = core.getMultilineInput('remove');
8
9 const token = process.env.GITHUB_TOKEN;
10 if (!token) {
11 throw new Error('missing required environment variable: GITHUB_TOKEN');
12 }
13
14 const issue_number = github.context.issue.number;
15 if (!issue_number) {
16 throw new Error('no issue or pull request context found');
17 }
18
19 const event_name = github.context.eventName;
20 const event_action = github.context.payload.action;
21 console.log(`triggered by: ${event_name}.${event_action} for #${issue_number}`);
22
23 const { owner, repo } = github.context.repo;
24
25 const overlap = labels_to_add.filter(label => labels_to_remove.includes(label));
26 if (overlap.length > 0) {
27 const formatted = overlap.map(label => `- ${label}`).join('\n');
28 throw new Error(`detected conflicting labels:\n\n${formatted}`);
29 }
30
31 const octokit = github.getOctokit(token);
32
33 const { data: issue } = await octokit.rest.issues.get({
34 owner,
35 repo,
36 issue_number
37 });
38
39 const current_labels = issue.labels.map(label => label.name);
40
41 if (labels_to_add.length > 0) {
42 const labels = []
43
44 for (const label of labels_to_add) {
45 if (!current_labels.includes(label)) {
46 labels.push(label);
47 }
48 }
49
50 if (labels.length > 0) {
51 await octokit.rest.issues.addLabels({
52 owner,
53 repo,
54 issue_number,
55 labels
56 });
57 } else {
58 console.log(`no new labels to add`)
59 }
60 }
61
62 if (labels_to_remove.length > 0) {
63 for (const label of labels_to_remove) {
64 if (current_labels.includes(label)) {
65 console.log(`removing label: ${label}`);
66 await octokit.rest.issues.removeLabel({
67 owner,
68 repo,
69 issue_number,
70 name: label
71 });
72 }
73 }
74 }
75 } catch (error) {
76 core.setFailed(error.message);
77 }
78}
79
80run();