forked from aicadium-archive/comment-when-approved-action
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
98 lines (83 loc) · 2.92 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
const { promises: fs } = require("fs");
const Octokit = require("@octokit/rest");
function checkEnvVars() {
if (!process.env.GITHUB_TOKEN) {
throw new Error("Set the GITHUB_TOKEN env variable.");
}
if (!process.env.GITHUB_REPOSITORY) {
throw new Error("Set the GITHUB_REPOSITORY env variable.");
}
if (!process.env.GITHUB_EVENT_PATH) {
throw new Error("Set the GITHUB_EVENT_PATH env variable.");
}
if (!process.env.COMMENT) {
throw new Error("Set the COMMENT env variable.");
}
if (!process.env.REACTION) {
console.warn("Warning: REACTION not set; default to hooray.");
process.env.REACTION = "hooray";
}
}
async function checkLabels(octokit, number, owner, repo) {
const { data: { labels } } = await octokit.pulls.get({
owner,
repo,
pull_number: number
});
const triggerLabels = process.env.TRIGGER_LABELS ? process.env.TRIGGER_LABELS.split(",") : [];
if (triggerLabels.length === 0) {
return false;
}
for (let label of labels) {
if (triggerLabels.indexOf(label.name) !== -1) {
return true;
}
}
return false;
}
async function commentWhenApproved(octokit, number, owner, repo) {
// Check whether this PR has any of the desired labels
const hasTrigger = await checkLabels(octokit, number, owner, repo);
if (!hasTrigger) {
console.warn("Ignoring pull request without trigger labels");
process.exit();
}
// Get all reviews
const { data: reviews } = await octokit.pulls.listReviews({ owner, repo, pull_number: number });
const lastReview = reviews[reviews.length - 1];
if (lastReview.state === "APPROVED") {
// Create comment
const { data: { id: comment_id } } = await octokit.issues.createComment({
owner,
repo,
issue_number: number,
body: process.env.COMMENT
});
// React to that comment
await octokit.reactions.createForIssueComment({
owner,
repo,
comment_id,
content: process.env.REACTION
});
}
}
async function main() {
const eventDataStr = await fs.readFile(process.env.GITHUB_EVENT_PATH, { encoding: "utf8" });
const eventData = JSON.parse(eventDataStr);
const { action, review: { state }, pull_request: { number } } = eventData;
const [owner, repo] = process.env.GITHUB_REPOSITORY.split("/");
const octokit = Octokit({
auth: process.env.GITHUB_TOKEN,
// Need this preview for the reaction API
// https://developer.github.com/v3/reactions/#create-reaction-for-an-issue-comment
previews: ["squirrel-girl-preview"],
});
if (action === "submitted" && state === "approved") {
await commentWhenApproved(octokit, number, owner, repo);
} else {
console.warn(`Ignoring event ${action}/${state}`);
}
}
checkEnvVars();
main();