-
-
Notifications
You must be signed in to change notification settings - Fork 100
/
index.js
472 lines (419 loc) · 12.7 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
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
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 packageJSON = require('./package.json');
function getGithubCommentInput() {
const input = core.getInput('github-comment');
if (input === 'true') return true;
if (input === 'false') return false;
return input;
}
const { context } = github;
const githubToken = core.getInput('github-token');
const githubComment = getGithubCommentInput();
const workingDirectory = core.getInput('working-directory');
const prNumberRegExp = /{{\s*PR_NUMBER\s*}}/g;
const branchRegExp = /{{\s*BRANCH\s*}}/g;
function isPullRequestType(event) {
return event.startsWith('pull_request');
}
function slugify(str) {
const slug = str
.toString()
.trim()
.toLowerCase()
.replace(/[_\s]+/g, '-')
.replace(/[^\w-]+/g, '')
.replace(/--+/g, '-')
.replace(/^-+/, '')
.replace(/-+$/, '');
core.debug(`before slugify: "${str}"; after slugify: "${slug}"`);
return slug;
}
function retry(fn, retries) {
async function attempt(retry) {
try {
return await fn();
} catch (error) {
if (retry > retries) {
throw error;
} else {
core.info(`retrying: attempt ${retry + 1} / ${retries + 1}`);
await new Promise(resolve => setTimeout(resolve, 3000));
return attempt(retry + 1);
}
}
}
return attempt(1);
}
// Vercel
function getVercelBin() {
const input = core.getInput('vercel-version');
const fallback = packageJSON.dependencies.vercel;
return `vercel@${input || fallback}`;
}
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 vercelProjectName = core.getInput('vercel-project-name');
const vercelBin = getVercelBin();
const aliasDomains = core
.getInput('alias-domains')
.split('\n')
.filter(x => x !== '')
.map(s => {
let url = s;
let branch = slugify(context.ref.replace('refs/heads/', ''));
if (isPullRequestType(context.eventName)) {
const pr =
context.payload.pull_request || context.payload.pull_request_target;
branch = slugify(pr.head.ref.replace('refs/heads/', ''));
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);
}
}
function addVercelMetadata(key, value, providedArgs) {
// returns a list for the metadata commands if key was not supplied by user in action parameters
// returns an empty list if key was provided by user
const pattern = `^${key}=.+`;
const metadataRegex = new RegExp(pattern, 'g');
// eslint-disable-next-line no-restricted-syntax
for (const arg of providedArgs) {
if (arg.match(metadataRegex)) {
return [];
}
}
return ['-m', `${key}=${value}`];
}
/**
*
* The following regex is used to split the vercelArgs string into an array of arguments.
* It conserves strings wrapped in simple / double quotes, with nested different quotes, as a single argument.
*
* Example:
*
* parseArgs(`--env foo=bar "foo=bar baz" 'foo="bar baz"'`) => ['--env', 'foo=bar', 'foo=bar baz', 'foo="bar baz"']
*/
function parseArgs(s) {
const args = [];
for (const match of s.matchAll(/'([^']*)'|"([^"]*)"|[^\s]+/gm)) {
args.push(match[1] ?? match[2] ?? match[0]);
}
return args;
}
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 => {
// eslint-disable-next-line no-unused-vars
myError += data.toString();
core.info(data.toString());
},
};
if (workingDirectory) {
options.cwd = workingDirectory;
}
const providedArgs = parseArgs(vercelArgs);
const args = [
...providedArgs,
...['-t', vercelToken],
...addVercelMetadata('githubCommitSha', context.sha, providedArgs),
...addVercelMetadata('githubCommitAuthorName', context.actor, providedArgs),
...addVercelMetadata(
'githubCommitAuthorLogin',
context.actor,
providedArgs,
),
...addVercelMetadata('githubDeployment', 1, providedArgs),
...addVercelMetadata('githubOrg', context.repo.owner, providedArgs),
...addVercelMetadata('githubRepo', context.repo.repo, providedArgs),
...addVercelMetadata('githubCommitOrg', context.repo.owner, providedArgs),
...addVercelMetadata('githubCommitRepo', context.repo.repo, providedArgs),
...addVercelMetadata('githubCommitMessage', `"${commit}"`, providedArgs),
...addVercelMetadata(
'githubCommitRef',
ref.replace('refs/heads/', ''),
providedArgs,
),
];
if (vercelScope) {
core.info('using scope');
args.push('--scope', vercelScope);
}
await exec.exec('npx', [vercelBin, ...args], options);
return myOutput;
}
async function vercelInspect(deploymentUrl) {
// eslint-disable-next-line no-unused-vars
let myOutput = '';
let myError = '';
const options = {};
options.listeners = {
stdout: data => {
// eslint-disable-next-line no-unused-vars
myOutput += data.toString();
core.info(data.toString());
},
stderr: data => {
myError += data.toString();
core.info(data.toString());
},
};
if (workingDirectory) {
options.cwd = workingDirectory;
}
const args = [vercelBin, '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 (isPullRequestType(context.eventName)) {
core.debug(`event is "${context.eventName}", 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;
}
function joinDeploymentUrls(deploymentUrl, aliasDomains_) {
if (aliasDomains_.length) {
const aliasUrls = aliasDomains_.map(domain => `https://${domain}`);
return [deploymentUrl, ...aliasUrls].join('\n');
}
return deploymentUrl;
}
function buildCommentPrefix(deploymentName) {
return `Deploy preview for _${deploymentName}_ ready!`;
}
function buildCommentBody(deploymentCommit, deploymentUrl, deploymentName) {
if (!githubComment) {
return undefined;
}
const prefix = `${buildCommentPrefix(deploymentName)}\n\n`;
const rawGithubComment =
prefix +
(typeof githubComment === 'string' || githubComment instanceof String
? githubComment
: stripIndents`
✅ Preview
{{deploymentUrl}}
Built with commit {{deploymentCommit}}.
This pull request is being automatically deployed with [vercel-action](https://github.com/marketplace/actions/vercel-action)
`);
return rawGithubComment
.replace(/\{\{deploymentCommit\}\}/g, deploymentCommit)
.replace(/\{\{deploymentName\}\}/g, deploymentName)
.replace(
/\{\{deploymentUrl\}\}/g,
joinDeploymentUrls(deploymentUrl, aliasDomains),
);
}
async function createCommentOnCommit(
deploymentCommit,
deploymentUrl,
deploymentName,
) {
if (!octokit) {
return;
}
const commentId = await findPreviousComment(
buildCommentPrefix(deploymentName),
);
const commentBody = buildCommentBody(
deploymentCommit,
deploymentUrl,
deploymentName,
);
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!`,
);
const commentBody = buildCommentBody(
deploymentCommit,
deploymentUrl,
deploymentName,
);
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 args = ['-t', vercelToken];
if (vercelScope) {
core.info('using scope');
args.push('--scope', vercelScope);
}
const promises = aliasDomains.map(domain =>
retry(
() =>
exec.exec('npx', [vercelBin, ...args, 'alias', deploymentUrl, domain]),
2,
),
);
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 (isPullRequestType(github.context.eventName)) {
const pullRequestPayload = github.context.payload;
const pr =
pullRequestPayload.pull_request || pullRequestPayload.pull_request_target;
core.debug(`head : ${pr.head}`);
ref = pr.head.ref;
sha = pr.head.sha;
core.debug(`The head ref is: ${pr.head.ref}`);
core.debug(`The head sha is: ${pr.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');
if (aliasDomains && aliasDomains.length) {
core.info('set preview-url output as first alias');
core.setOutput('preview-url', `https://${aliasDomains[0]}`);
} else {
core.setOutput('preview-url', deploymentUrl);
}
} else {
core.warning('get preview-url error');
}
const deploymentName =
vercelProjectName || (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);
});