-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
87 lines (71 loc) · 2.35 KB
/
app.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
var express = require('express'),
bodyParser = require('body-parser'),
app = express(),
util = require('util'),
_ = require('underscore'),
path = require('path'),
exec = require('child_process').exec,
config = require('./config.json'),
deployHistory = [];
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/', function(req, res) {
res.json(deployHistory);
});
app.post('/', function(req, res) {
var branch = req.body.ref.split('/').slice(-1)[0],
reponame = req.body.repository.name,
repoConfigs = _.where(config.hooks, { reponame: reponame }),
username = req.body.user_name,
branchConfigs, branchConfig;
if (_.some(repoConfigs)) {
// Further refine list to only get branch config
branchConfigs = _.where(repoConfigs, { branch: branch });
if (_.some(branchConfigs)) {
branchConfig = _.first(branchConfigs);
addToHistory(reponame, branch, username, true);
executePostReceiveScript(branchConfig);
} else {
var noBranchMessage = util.format('No configs found for branch "%s" on repository "%s"', branch, reponame);
addToHistory(reponame, branch, username, noBranchMessage);
console.log(noBranchMessage);
return;
}
} else {
var noRepoConfiguredMsg = util.format('No configs found for repository %s', reponame);
addToHistory(reponame, branch, username, noRepoConfiguredMsg);
console.log(noRepoConfiguredMsg);
return;
}
res.status(200).end();
});
app.listen(config.port, function() {
console.log('Listening on port %s for deploy hooks', config.port);
});
function executePostReceiveScript(config, username) {
var branch = config.branch,
script = config.script,
reponame = config.reponame,
user = config.runas,
command = util.format('sudo -u %s sh -c "cd %s; bash %s"', user, path.dirname(script), script);
console.log(util.format('Executing %s as user %s.', user, script));
exec(command, function(error, stdout, stderr) {
console.log(stdout);
if (error) {
var errMsg = util.format('Error: ', error, stderr);
console.log(errMsg);
addToHistory(reponame, branch, username, errMsg);
} else {
addToHistory(reponame, branch, username, stdout);
}
});
}
function addToHistory(reponame, branchname, username, message) {
deployHistory.push({
datetime: new Date(),
reponame: reponame,
branchname: branchname,
username: username,
message: message
});
}