/
server.js
104 lines (82 loc) · 2.68 KB
/
server.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
/*jshint node:true, globalstrict:true, sub:true */
"use strict";
/**
* roughly based on code from: https://github.com/brianc/node-auto-deploy/blob/master/serve.js
*/
var log = require('nlogger').logger(module),
http = require('http'),
path = require('path'),
decodeForm = require('./www-forms').decodeForm,
exec = require('child_process').exec,
command = 'git pull origin master && npm install',
currentResponse,
reqBody = [],
options = {};
/**
* @param {bool} processedOk
*/
function sendResponse(processedOk, messageText) {
var responseCode = (processedOk === true) ? 200 : 500;
currentResponse.writeHead(responseCode,
{
"Content-Type": "text/plain"
}
);
currentResponse.write(messageText ? messageText : "");
currentResponse.end();
}
//execute a git pull within the deployPath
//and then execute an npm install
function deploy(projectName) {
log.info('doing pull and npm');
options.cwd = path.join(process.env.DEPLOY_PATH, projectName);
exec(command, options, function(error, stdout, stderr) {
if (error) {
return log.error(command, {
error: error,
stdout: stdout,
stderr: stderr
});
}
log.debug(command, {
stdout: stdout,
stderr: stderr
});
//restart upstart process with the same name
log.info('restarting upstart process', process.env.RESTART_CMD);
exec(process.env.RESTART_CMD, function(err, stdout, stderr) {
log.debug('restarted', {
error: err,
stdout: stdout,
stderr: stderr
});
});
sendResponse(true, 'deployed');
});
}
function requestHandler(request, response) {
currentResponse = response;
if (request.url.charAt(0) === "/" && request.method === "POST") {
log.info("got POST for /");
request.setEncoding('utf8');
request.on("data", function(chunk) {
reqBody.push(chunk);
});
} else {
sendResponse("GET Request not supported");
}
request.on("end", function() {
var reqBodyText = reqBody.join(''),
data;
data = decodeForm(reqBodyText);
data = JSON.parse(data.payload || '{}');
log.info('repo:'+data.repository.name);
log.info('ref:'+data.ref);
if (data && data.ref && (data.ref === 'refs/heads/master')) {
deploy(data.repository.name);
}
});
}
http.createServer(requestHandler).listen(process.env.PORT, function() {
log.warn("node-github-deployhook listening on port:"+process.env.PORT);
});