This repository has been archived by the owner on Mar 11, 2019. It is now read-only.
forked from dgmltn/EggTimer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheggtimer.js
326 lines (290 loc) · 9.6 KB
/
eggtimer.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
const fs = require('fs');
const http = require('http');
const githubWebhookHandler = require('github-webhook-handler');
const nodeGithub = require('github');
///////////////////////////////////////////////////////////////////////////////////////////////////
// Setup
///////////////////////////////////////////////////////////////////////////////////////////////////
const CONFIG = JSON.parse(fs.readFileSync('config.js'));
const HANDLER = githubWebhookHandler({ path: CONFIG.github_webhook_path, secret: CONFIG.github_webhook_secret });
const GITHUB = new nodeGithub({ version: "3.0.0" });
const GITHUB_AUTHENTICATION = { type: 'token', username: CONFIG.github_username, token: CONFIG.github_token };
///////////////////////////////////////////////////////////////////////////////////////////////////
// PR state representation
///////////////////////////////////////////////////////////////////////////////////////////////////
// PRs contains status about incomplete pr's:
// {
// 'https://api.github.com/repos/dgmltn/api-test/pulls/5': {
// head_sha: 'abcd1234...',
// ref: 'my-pull-request',
// checks: {
// 'context1': true|false,
// 'context2': true|false
// },
// reviews: {
// 'user1': true|false,
// 'user2': true|false
// },
// mergeable: true|false
// }
// }
var prs = {};
// commits references a pr url to a commit sha:
// {
// 'abcd1234...': 'https://github.com/dgmltn/api-test/pull/5',
// }
var commits = {};
///////////////////////////////////////////////////////////////////////////////////////////////////
// Webhook Handlers
///////////////////////////////////////////////////////////////////////////////////////////////////
http.createServer(function (req, res) {
HANDLER(req, res, function (err) {
res.statusCode = 404
res.end('no such location')
});
}).listen(CONFIG.port);
HANDLER.on('error', function (err) {
console.error('Error:', err.message);
});
// https://developer.github.com/v3/activity/events/types/#pullrequestreviewevent
HANDLER.on('pull_request_review', function(event) {
const url = event.payload.pull_request.url;
const head_sha = event.payload.pull_request.head.sha;
const ref = event.payload.pull_request.head.ref;
console.log(url + " -> pull_request_review");
ensurePr(url, head_sha);
prs[url].ref = ref;
populateMergeable(url);
populateReviews(url);
mergeIfReady(url);
});
// https://developer.github.com/v3/activity/events/types/#pullrequestevent
HANDLER.on('pull_request', function(event) {
const url = event.payload.pull_request.url;
const head_sha = event.payload.pull_request.head.sha;
const ref = event.payload.pull_request.head.ref;
console.log(url + " -> pull_request");
ensurePr(url, head_sha);
prs[url].ref = ref;
populateMergeable(url);
populateReviews(url);
mergeIfReady(url);
});
// https://developer.github.com/v3/activity/events/types/#statusevent
HANDLER.on('status', function(event) {
const sha = event.payload.sha;
const context = event.payload.context;
const state = event.payload.state;
var success = false;
switch (state) {
case 'success':
success = true;
break;
case 'pending':
case 'failure':
case 'error':
// success = false, still
break;
default:
console.error("Unknown check state '" + state + "'. success = false");
break;
}
const processUrl = function(err, url) {
if (err) {
console.error(err);
return;
}
console.log(url + " -> status");
ensurePr(url, sha);
prs[url].checks[context] = success;
populateMergeable(url);
populateReviews(url);
mergeIfReady(url);
};
if (sha in commits) {
processUrl(null, commits[sha]);
}
else {
const owner = event.payload.repository.owner.login;
const repo = event.payload.repository.name;
lookupPullRequest(owner, repo, sha, processUrl);
}
});
///////////////////////////////////////////////////////////////////////////////////////////////////
// Private helpers
///////////////////////////////////////////////////////////////////////////////////////////////////
// Initialize an empty pr
function ensurePr(url, head_sha) {
if (!(url in prs)) {
prs[url] = {};
}
if (!('head_sha' in prs[url]) || prs[url].head_sha != head_sha) {
prs[url].head_sha = head_sha;
prs[url].checks = {};
prs[url].reviews = {};
prs[url].mergeable = false;
}
commits[head_sha] = url;
}
// GET pull requests and check their mergeable status
function populateMergeable(url) {
setTimeout(function() {
const params = parsePullRequestUrl(url);
GITHUB.pullRequests.get(params,
function(err, pr) {
if (!(url in prs)) {
console.error(url + " not found in prs hash");
return;
}
prs[url].mergeable = !!pr.data.mergeable;
mergeIfReady(url);
}
)
}, 10000);
}
// GET pr reviews and check their approved status. Replace existing reviews.
function populateReviews(url) {
console.log("populateReviews(" + url + ")");
const params = parsePullRequestUrl(url);
GITHUB.pullRequests.getReviews(params,
function(err, res) {
if (!(url in prs)) {
console.error(url + " not found in prs hash");
return;
}
// A bug in 'github' node module?
if ('data' in res) { res = res.data; }
prs[url].reviews = {};
for (var i in res) {
console.log("i = " + i);
var review = res[i];
console.log("review = " + JSON.stringify(review, null, " "));
var user = review.user.login;
// Since reviews are returned in chronological order, the last
// one found is the most recent. We'll use that one.
var approved = review.state.toLowerCase() == 'approved';
prs[url].reviews[user] = approved;
}
mergeIfReady(url);
}
);
}
// Perform a merge on this PR if:
// 1. it's mergeable
// 2. >1 reviews exist and all are approved
// 3. >1 checks exist and all passed
function mergeIfReady(url) {
console.log(JSON.stringify(prs, null, 4));
if (url in prs
&& !prs[url].done
&& isMergeable(prs[url])
&& isApproved(prs[url])
&& checksPassed(prs[url])) {
// APPROVED!
prs[url].done = true;
console.log("APPROVED (" + url + ")!");
const deleteCallback = function(err, res) {
if (err) {
console.error("Error: could not delete ref: " + err);
return;
}
delete prs[url];
console.log("DELETED (" + url + ")!");
};
const mergeCallback = function(err, res) {
if (err) {
console.error("Error: could not merge: " + err);
delete prs[url].done;
return;
}
console.log("MERGED (" + url + ")!");
if (CONFIG.delete_after_merge) {
deleteReference(url, deleteCallback);
}
};
mergePullRequest(url, mergeCallback);
}
}
function mergePullRequest(url, callback) {
if (!(url in prs)) {
console.error(url + " not found in prs hash");
return;
}
const params = parsePullRequestUrl(url);
params.sha = prs[url].head_sha;
GITHUB.authenticate(GITHUB_AUTHENTICATION);
GITHUB.pullRequests.merge(params, callback);
}
function deleteReference(url, callback) {
if (!(url in prs)) {
console.error(url + " not found in prs hash");
return;
}
const params = parsePullRequestUrl(url);
params.ref = 'heads/' + prs[url].ref;
GITHUB.authenticate(GITHUB_AUTHENTICATION);
GITHUB.gitdata.deleteReference(params, callback);
}
// Finds the PR URL associated with the given head SHA
function lookupPullRequest(owner, repo, sha, callback) {
const params = {
owner: owner,
repo: repo
};
GITHUB.pullRequests.getAll(params, function(err, res) {
if (err) {
console.log("err with pr.get: " + err);
callback(err, null);
return;
}
for (var i in res.data) {
const pr = res.data[i];
if (pr.head.sha == sha) {
const url = pr.url;
callback(null, url);
return;
}
}
callback("PR not found: (" + owner + ", " + repo + ", " + sha + ")", null);
});
}
function parsePullRequestUrl(url) {
const re = /^https?:\/\/([^\/]+)\/repos\/([^\/]+)\/([^\/]+)\/pulls\/(\d+)$/;
const match = re.exec(url);
return {
owner: match[2],
repo: match[3],
number: match[4]
};
}
function isMergeable(obj) {
return 'mergeable' in obj && !!obj.mergeable;
}
function isApproved(obj) {
if (!('reviews' in obj)) {
return false;
}
else if (Object.keys(obj.reviews).length <= 0) {
return false;
}
for (var id in obj.reviews) {
if (!obj.reviews[id]) {
return false;
}
}
return true;
}
function checksPassed(obj) {
if (!('checks' in obj)) {
return false;
}
else if (Object.keys(obj.checks).length <= 0) {
return false;
}
for (var context in obj.checks) {
if (!obj.checks[context]) {
return false;
}
}
return true;
}