forked from global-121/121-platform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebhook.js
106 lines (93 loc) · 2.79 KB
/
webhook.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
const http = require("http");
const crypto = require("crypto");
const child_process = require("child_process");
const fs = require("fs");
// ----------------------------------------------------------------------------
// Functions/Methods/etc:
// ----------------------------------------------------------------------------
/**
* Run the deployment script
* @param {string} target (optional)
*/
function deploy(target) {
let command = `cd ${process.env.GLOBAL_121_REPO} && sudo ./tools/deploy.sh`;
if (target) {
command += ` "${target}"`;
}
child_process.exec(
command,
{
maxBuffer: 10 * 1024 * 1024,
},
function (error) {
if (error) {
console.error(error);
return;
}
}
);
}
/**
* Check whether to deploy/ignore a release
* @param {string} target
*/
function isPatchUpgrade(target) {
const currentVersion = fs.readFileSync(`${process.env.GLOBAL_121_WEB_ROOT}/VERSION.txt`, { encoding: 'utf-8' });
const currentMinorVersion = currentVersion.replace(/v(\d+)\.(\d+)\.([\S\s]*)/, 'v$1.$2.');
return target.includes(currentMinorVersion);
}
// ----------------------------------------------------------------------------
// Webhook Service:
// ----------------------------------------------------------------------------
http
.createServer(function(req, res) {
let body = [];
req.on("data", function(chunk) {
body.push(chunk);
});
req.on("end", function() {
let str = Buffer.concat(body).toString();
let sig =
"sha1=" +
crypto
.createHmac("sha1", process.env.GITHUB_WEBHOOK_SECRET)
.update(str)
.digest("hex");
let payload = JSON.parse(str);
if (req.headers["x-hub-signature"] !== sig) {
console.warn('Invalid GitHub signature!');
return
}
if (
payload.pull_request &&
payload.pull_request.merged &&
payload.pull_request.title.includes("[SKIP CD]")
) {
console.log('PR deployment skipped with [SKIP CD]');
return
}
if (
process.env.NODE_ENV === "test" &&
payload.action === "closed" &&
payload.pull_request.merged
) {
console.log('PR deployment for test-environment.');
deploy()
return
}
if (
process.env.NODE_ENV === "production" &&
payload.action === "released" &&
payload.release.draft === false &&
payload.release.target_commitish &&
isPatchUpgrade(payload.release.target_commitish)
) {
console.log(`Release (hotfix) deployment for: ${payload.release.target_commitish}`);
deploy(payload.release.target_commitish);
return
}
});
res.end();
})
.listen(process.env.NODE_PORT);
console.log(`Listening on port ${process.env.NODE_PORT}`);