forked from thollander/actions-comment-pull-request
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.ts
219 lines (190 loc) · 6.75 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
import fs from 'fs';
import * as github from '@actions/github';
import * as core from '@actions/core';
import { GetResponseDataTypeFromEndpointMethod } from '@octokit/types';
// See https://docs.github.com/en/rest/reactions#reaction-types
const REACTIONS = ['+1', '-1', 'laugh', 'confused', 'heart', 'hooray', 'rocket', 'eyes'] as const;
type Reaction = (typeof REACTIONS)[number];
const COMMENT_MAX_LENGTH = 64000; // max is 65536, but we keep a padding just in case :)
const CUT_DELIMITER = '<!-- cut-delimiter -->';
const WARNING_MESSAGE_LENGTH_TOO_LONG = '\n\n<b>Warning:</b> Output length greater than max comment size. Continued in next comment.';
async function run() {
try {
const message: string = core.getInput('message');
const filePath: string = core.getInput('filePath');
const cutDelimiter: string = core.getInput('cutDelimiter') || CUT_DELIMITER;
const cutMessage: string = core.getInput('cutMessage') || WARNING_MESSAGE_LENGTH_TOO_LONG;
const github_token: string = core.getInput('GITHUB_TOKEN');
const pr_number: string = core.getInput('pr_number');
const comment_tag: string = core.getInput('comment_tag');
const reactions: string = core.getInput('reactions');
const mode: string = core.getInput('mode');
const create_if_not_exists: boolean = core.getInput('create_if_not_exists') === 'true';
if (!message && !filePath) {
core.setFailed('Either "filePath" or "message" should be provided as input');
return;
}
let content: string = message;
if (!message && filePath) {
content = fs.readFileSync(filePath, 'utf8');
}
const context = github.context;
const issue_number = parseInt(pr_number) || context.payload.pull_request?.number || context.payload.issue?.number;
const octokit = github.getOctokit(github_token);
if (!issue_number) {
core.setFailed('No issue/pull request in input neither in current context.');
return;
}
async function addReactions(comment_id: number, reactions: string) {
const validReactions = <Reaction[]>reactions
.replace(/\s/g, '')
.split(',')
.filter((reaction) => REACTIONS.includes(<Reaction>reaction));
await Promise.allSettled(
validReactions.map(async (content) => {
await octokit.rest.reactions.createForIssueComment({
...context.repo,
comment_id,
content,
});
}),
);
}
async function createComment({
owner,
repo,
issue_number,
body,
}: {
owner: string;
repo: string;
issue_number: number;
body: string;
}) {
const chunks = [];
let message = body;
while (message.length > COMMENT_MAX_LENGTH) {
const chunk = message.substring(0, COMMENT_MAX_LENGTH);
const lastIndexOfCutDelimiter = chunk.lastIndexOf(cutDelimiter);
if (lastIndexOfCutDelimiter !== -1) {
chunks.push(chunk.substring(0, lastIndexOfCutDelimiter + cutDelimiter.length));
message = message.substring(lastIndexOfCutDelimiter + cutDelimiter.length);
} else {
// No cut delimiter found in this chunk, so just truncate
chunks.push(chunk);
message = message.substring(COMMENT_MAX_LENGTH);
}
}
// Add the remaining message as the last chunk
chunks.push(message);
let firstComment
for (const [index, chunk] of chunks.entries()) {
const { data: comment } = await octokit.rest.issues.createComment({
owner,
repo,
issue_number,
body: index == chunks.length -1 ? chunk : `${chunk}${cutMessage}`,
});
if (!firstComment) {
firstComment = comment
core.setOutput('id', firstComment.id);
core.setOutput('body', firstComment.body);
core.setOutput('html_url', firstComment.html_url);
await addReactions(firstComment.id, reactions);
}
}
return firstComment;
}
async function updateComment({
owner,
repo,
comment_id,
body,
}: {
owner: string;
repo: string;
comment_id: number;
body: string;
}) {
const { data: comment } = await octokit.rest.issues.updateComment({
owner,
repo,
comment_id,
body,
});
core.setOutput('id', comment.id);
core.setOutput('body', comment.body);
core.setOutput('html_url', comment.html_url);
await addReactions(comment.id, reactions);
return comment;
}
async function deleteComment({ owner, repo, comment_id }: { owner: string; repo: string; comment_id: number }) {
const { data: comment } = await octokit.rest.issues.deleteComment({
owner,
repo,
comment_id,
});
return comment;
}
const comment_tag_pattern = comment_tag
? `<!-- thollander/actions-comment-pull-request "${comment_tag}" -->`
: null;
const body = comment_tag_pattern ? `${content}\n${comment_tag_pattern}` : content;
if (comment_tag_pattern) {
type ListCommentsResponseDataType = GetResponseDataTypeFromEndpointMethod<
typeof octokit.rest.issues.listComments
>;
let comment: ListCommentsResponseDataType[0] | undefined;
for await (const { data: comments } of octokit.paginate.iterator(octokit.rest.issues.listComments, {
...context.repo,
issue_number,
})) {
comment = comments.find((comment) => comment?.body?.includes(comment_tag_pattern));
if (comment) break;
}
if (comment) {
if (mode === 'upsert') {
await updateComment({
...context.repo,
comment_id: comment.id,
body,
});
return;
} else if (mode === 'recreate') {
await deleteComment({
...context.repo,
comment_id: comment.id,
});
await createComment({
...context.repo,
issue_number,
body,
});
return;
} else if (mode === 'delete') {
core.debug('Registering this comment to be deleted.');
} else {
core.setFailed(`Mode ${mode} is unknown. Please use 'upsert', 'recreate' or 'delete'.`);
return;
}
} else if (create_if_not_exists) {
core.info('No comment has been found with asked pattern. Creating a new comment.');
} else {
core.info(
'Not creating comment as the pattern has not been found. Use `create_if_not_exists: true` to create a new comment anyway.',
);
return;
}
}
await createComment({
...context.repo,
issue_number,
body,
});
} catch (error) {
if (error instanceof Error) {
core.setFailed(error.message);
}
}
}
run();