-
-
Notifications
You must be signed in to change notification settings - Fork 97
/
index.js
355 lines (317 loc) · 9.19 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
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
const { stripIndents } = require('common-tags');
const core = require('@actions/core');
const github = require('@actions/github');
const { execSync } = require('child_process');
const exec = require('@actions/exec');
const { context } = github;
const githubToken = core.getInput('github-token');
const githubComment = core.getInput('github-comment') === 'true';
const workingDirectory = core.getInput('working-directory');
const prNumberRegExp = /{{\s*PR_NUMBER\s*}}/g;
const branchRegExp = /{{\s*BRANCH\s*}}/g;
// Vercel
const vercelToken = core.getInput('vercel-token', { required: true });
const vercelArgs = core.getInput('vercel-args');
const vercelOrgId = core.getInput('vercel-org-id');
const vercelProjectId = core.getInput('vercel-project-id');
const vercelScope = core.getInput('scope');
const aliasDomains = core
.getInput('alias-domains')
.split('\n')
.filter(x => x !== '')
.map(s => {
let url = s;
let branch = context.ref.replace('refs/heads/', '').replace(/\//g, '-');
if (context.eventName === 'pull_request') {
branch = context.payload.pull_request.head.ref
.replace('refs/heads/', '')
.replace(/\//g, '-');
url = url.replace(prNumberRegExp, context.issue.number.toString());
}
url = url.replace(branchRegExp, branch);
return url;
});
let octokit;
if (githubToken) {
octokit = new github.GitHub(githubToken);
}
async function setEnv() {
core.info('set environment for vercel cli');
if (vercelOrgId) {
core.info('set env variable : VERCEL_ORG_ID');
core.exportVariable('VERCEL_ORG_ID', vercelOrgId);
}
if (vercelProjectId) {
core.info('set env variable : VERCEL_PROJECT_ID');
core.exportVariable('VERCEL_PROJECT_ID', vercelProjectId);
}
}
async function vercelDeploy(ref, commit) {
let myOutput = '';
// eslint-disable-next-line no-unused-vars
let myError = '';
const options = {};
options.listeners = {
stdout: data => {
myOutput += data.toString();
core.info(data.toString());
},
stderr: data => {
myError += data.toString();
core.info(data.toString());
},
};
if (workingDirectory) {
options.cwd = workingDirectory;
}
await exec.exec(
'npx',
[
'vercel',
...vercelArgs.split(/ +/),
'-t',
vercelToken,
'-m',
`githubCommitSha=${context.sha}`,
'-m',
`githubCommitAuthorName=${context.actor}`,
'-m',
`githubCommitAuthorLogin=${context.actor}`,
'-m',
'githubDeployment=1',
'-m',
`githubOrg=${context.repo.owner}`,
'-m',
`githubRepo=${context.repo.repo}`,
'-m',
`githubCommitOrg=${context.repo.owner}`,
'-m',
`githubCommitRepo=${context.repo.repo}`,
'-m',
`githubCommitMessage=${commit}`,
'-m',
`githubCommitRef=${ref}`,
],
options,
);
return myOutput;
}
async function vercelInspect(deploymentUrl) {
// eslint-disable-next-line no-unused-vars
let myOutput = '';
let myError = '';
const options = {};
options.listeners = {
stdout: data => {
myOutput += data.toString();
core.info(data.toString());
},
stderr: data => {
myError += data.toString();
core.info(data.toString());
},
};
if (workingDirectory) {
options.cwd = workingDirectory;
}
const args = ['vercel', 'inspect', deploymentUrl, '-t', vercelToken];
if (vercelScope) {
core.info('using scope');
args.push('--scope', vercelScope);
}
await exec.exec('npx', args, options);
const match = myError.match(/^\s+name\s+(.+)$/m);
return match && match.length ? match[1] : null;
}
async function findCommentsForEvent() {
core.debug('find comments for event');
if (context.eventName === 'push') {
core.debug('event is "commit", use "listCommentsForCommit"');
return octokit.repos.listCommentsForCommit({
...context.repo,
commit_sha: context.sha,
});
}
if (context.eventName === 'pull_request') {
core.debug('event is "pull_request", use "listComments"');
return octokit.issues.listComments({
...context.repo,
issue_number: context.issue.number,
});
}
core.error('not supported event_type');
return [];
}
async function findPreviousComment(text) {
if (!octokit) {
return null;
}
core.info('find comment');
const { data: comments } = await findCommentsForEvent();
const vercelPreviewURLComment = comments.find(comment =>
comment.body.startsWith(text),
);
if (vercelPreviewURLComment) {
core.info('previous comment found');
return vercelPreviewURLComment.id;
}
core.info('previous comment not found');
return null;
}
async function createCommentOnCommit(
deploymentCommit,
deploymentUrl,
deploymentName,
) {
if (!octokit) {
return;
}
const commentId = await findPreviousComment(
`Deploy preview for _${deploymentName}_ ready!`,
);
let previewUrl = deploymentUrl;
if (aliasDomains.length) {
aliasDomains.forEach(domain => {
previewUrl += `\nhttps://${domain}`;
});
}
const commentBody = stripIndents`
Deploy preview for _${deploymentName}_ ready!
✅ Preview
${previewUrl}
Built with commit ${deploymentCommit}.
This pull request is being automatically deployed with [vercel-action](https://github.com/marketplace/actions/vercel-action)
`;
if (commentId) {
await octokit.repos.updateCommitComment({
...context.repo,
comment_id: commentId,
body: commentBody,
});
} else {
await octokit.repos.createCommitComment({
...context.repo,
commit_sha: context.sha,
body: commentBody,
});
}
}
async function createCommentOnPullRequest(
deploymentCommit,
deploymentUrl,
deploymentName,
) {
if (!octokit) {
return;
}
const commentId = await findPreviousComment(
`Deploy preview for _${deploymentName}_ ready!`,
);
let previewUrl = deploymentUrl;
if (aliasDomains.length) {
aliasDomains.forEach(domain => {
previewUrl += `\nhttps://${domain}`;
});
}
const commentBody = stripIndents`
Deploy preview for _${deploymentName}_ ready!
✅ Preview
${previewUrl}
Built with commit ${deploymentCommit}.
This pull request is being automatically deployed with [vercel-action](https://github.com/marketplace/actions/vercel-action)
`;
if (commentId) {
await octokit.issues.updateComment({
...context.repo,
comment_id: commentId,
body: commentBody,
});
} else {
await octokit.issues.createComment({
...context.repo,
issue_number: context.issue.number,
body: commentBody,
});
}
}
async function aliasDomainsToDeployment(deploymentUrl) {
if (!deploymentUrl) {
core.error('deployment url is null');
}
const promises = aliasDomains.map(domain => {
return exec.exec('npx', [
'vercel',
'alias',
'-t',
vercelToken,
deploymentUrl,
domain,
]);
});
await Promise.all(promises);
}
async function run() {
core.debug(`action : ${context.action}`);
core.debug(`ref : ${context.ref}`);
core.debug(`eventName : ${context.eventName}`);
core.debug(`actor : ${context.actor}`);
core.debug(`sha : ${context.sha}`);
core.debug(`workflow : ${context.workflow}`);
let { ref } = context;
let { sha } = context;
await setEnv();
let commit = execSync('git log -1 --pretty=format:%B')
.toString()
.trim();
if (github.context.eventName === 'push') {
const pushPayload = github.context.payload;
core.debug(`The head commit is: ${pushPayload.head_commit}`);
} else if (github.context.eventName === 'pull_request') {
const pullRequestPayload = github.context.payload;
core.debug(`head : ${pullRequestPayload.pull_request.head}`);
ref = pullRequestPayload.pull_request.head.ref;
sha = pullRequestPayload.pull_request.head.sha;
core.debug(`The head ref is: ${pullRequestPayload.pull_request.head.ref}`);
core.debug(`The head sha is: ${pullRequestPayload.pull_request.head.sha}`);
if (octokit) {
const { data: commitData } = await octokit.git.getCommit({
...context.repo,
commit_sha: sha,
});
commit = commitData.message;
core.debug(`The head commit is: ${commit}`);
}
}
const deploymentUrl = await vercelDeploy(ref, commit);
if (deploymentUrl) {
core.info('set preview-url output');
core.setOutput('preview-url', deploymentUrl);
} else {
core.warning('get preview-url error');
}
const deploymentName = await vercelInspect(deploymentUrl);
if (deploymentName) {
core.info('set preview-name output');
core.setOutput('preview-name', deploymentName);
} else {
core.warning('get preview-name error');
}
if (aliasDomains.length) {
core.info('alias domains to this deployment');
await aliasDomainsToDeployment(deploymentUrl);
}
if (githubComment && githubToken) {
if (context.issue.number) {
core.info('this is related issue or pull_request ');
await createCommentOnPullRequest(sha, deploymentUrl, deploymentName);
} else if (context.eventName === 'push') {
core.info('this is push event');
await createCommentOnCommit(sha, deploymentUrl, deploymentName);
}
} else {
core.info('comment : disabled');
}
}
run().catch(error => {
core.setFailed(error.message);
});