forked from botwillacceptanything/botwillacceptanything
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
96 lines (78 loc) · 2.33 KB
/
main.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
var POLL_INTERVAL = 5; // how often to check the open PRs (in seconds)
var config = require('./config.js');
var git = require('gift');
var Github = require('github');
var path = require('path');
var spawn = require('child_process').spawn;
var gh = new Github({
version: '3.0.0',
headers: {
'User-Agent': config.user+'/'+config.repo
}
});
gh.authenticate(config.githubAuth);
var voting = require('./voting.js')(config, gh);
// if we merge something, `git sync` the changes and start the new version
voting.on('merge', function(pr) {
sync(function(err) {
if(err) return console.error('error pulling from origin/master:', err);
// start the new version
restart();
});
});
// `git sync`
function sync(cb) {
var repo = git(__dirname);
repo.sync(cb);
}
// gets the hash of the HEAD commit
function head(cb) {
var repo = git(__dirname);
repo.branch(function(err, head) {
if(err) return cb(err);
cb(null, head.commit.id);
});
}
// starts ourself up in a new process, and kills the current one
function restart() {
var child = spawn('node', [__filename], {
detached: true,
stdio: 'inherit'
});
child.unref();
// TODO: ensure child is alive before terminating self
process.exit(0);
}
// gets and processes the currently open PRs
function checkPRs() {
gh.pullRequests.getAll({
user: config.user,
repo: config.repo,
per_page: 100
}, function(err, res) {
if(err || !res) return console.error('error in checkPRs:', err);
// handle all the voting/merging logic in the voting module
res.forEach(voting.handlePR);
})
}
function main() {
// find the hash of the current HEAD
head(function(err, initial) {
if(err) return console.error('error checking HEAD:', err);
// make sure we are in sync with the remote repo
sync(function(err) {
if(err) return console.error('error pulling from origin/master:', err);
head(function(err, current) {
if(err) return console.error('error checking HEAD:', err);
// if we just got a new version, relaunch
if(initial !== current) return restart();
console.log('Bot is initialized. HEAD:', current);
// check PRs every POLL_INTERVAL seconds
// TODO: use github hooks instead of polling
setInterval(checkPRs, POLL_INTERVAL * 1000);
checkPRs();
});
});
});
}
main();