-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
71 lines (59 loc) · 2.56 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
// Approach based on Vercel docs and a lot of trial and error.
// See: https://vercel.com/docs/concepts/deployments/generated-urls#truncation
const {createHash} = require("crypto");
const core = require('@actions/core');
/**
* Generate the branch preview URL for a Vercel deployment.
* @param [teamId] {string}
* @param [projectName] {string}
* @param [branchName] {string}
*/
function generateBranchPreviewURL(teamId, projectName, branchName) {
teamId = teamId || core.getInput("vercel-team-id")
projectName = projectName || core.getInput("vercel-project-name")
branchName = branchName || core.getInput("git-branch-name")
console.log()
console.log(">>> log inputs...")
console.log("vercel-project-name: %s", projectName)
console.log("vercel-team-id: %s", projectName)
console.log("git-branch-name: %s", branchName)
console.log();
console.log(">>> building url...");
const safeBranchName = branchName
.replace(/\//, "-") // replace first "/" with "-"
.replace(/\//g, "") // remove all other "/"
.replace(/[^a-z0-9]/gi, "-"); // replace any other non-alphanumeric char with "-"
const url = `${projectName}-git-${safeBranchName}-${teamId}.vercel.app`;
const requiresTruncation = url.replace(".vercel.app", "").length > 63;
console.log("- project: %s", projectName);
console.log("- team: %s", teamId);
console.log("- branch: %s", branchName);
console.log("- safe branch: %s", safeBranchName);
console.log("- url: %s", url);
console.log("- length: %s", url.length);
console.log("- will truncate: %s", requiresTruncation ? "yes" : "no");
if (!requiresTruncation) {
core.setOutput("url", "https://" + url);
return
}
console.log();
console.log(">>> truncating url...");
const input = "git-" + branchName + projectName;
const sha = createHash("sha256").update(input).digest("hex");
const shaSlice = sha.slice(0, 6);
const prefix = `${projectName}-git-${safeBranchName}`
.slice(0, 44)
.replace(/-$/, ""); // remove trailing "-"
const truncatedUrl = `${prefix}-${shaSlice}-${teamId}.vercel.app`;
console.log("- sha input: %s", input);
console.log("- sha: %s", sha);
console.log("- truncated url: %s", truncatedUrl);
console.log("- length: %s", truncatedUrl.length);
core.setOutput("url", "https://" + truncatedUrl);
}
// eg. `node index.js $team $project $branch`
if (process.argv.length === 5) {
generateBranchPreviewURL(process.argv[2], process.argv[3], process.argv[4]);
} else {
generateBranchPreviewURL()
}