-
Notifications
You must be signed in to change notification settings - Fork 2
/
jim-github.js
553 lines (454 loc) · 19.3 KB
/
jim-github.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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
/**
* GitHub JIRA Issue Helper Functions
*/
// externally defined modules
var GitHub = require("github");
var moment = require('moment');
var Promise = require("bluebird");
var randomColor = require("randomcolor");
var request = require('request-promise');
var retry = require('bluebird-retry');
// constants
var USER_AGENT = 'JIM: [email protected]';
var REQUEST_DELAY = 500; // half a second
/**
* Creates a GitHub Milestone.
*/
function createMilestone(github, username, repository, title) {
return new Promise(function (resolve, reject) {
github.issues.createMilestone({owner: username, repo: repository, title: title}, function (error, response) {
if (error) {
// when the milestone already exists we carry on
if (error.message.search("already_exists")) {
return resolve();
} else {
return reject(error);
}
} else {
return resolve();
}
});
});
}
/**
* Creates a GitHub Label.
*/
function createLabel(github, username, repository, name, color)
{
return new Promise(function (resolve, reject) {
// ensure we have a color
if (typeof color == "undefined")
{
color = randomColor();
}
// ensure the color doesn't have a leading #
if (color.charAt(0) == "#")
{
color = color.substr(1);
}
github.issues.createLabel({ owner:username, repo:repository, name: name, color:color}, function (error, response)
{
if (error) {
// when label already exists we carry on
if (error.message.search("already_exists")) {
return resolve();
} else {
return reject(error);
}
} else {
return resolve();
}
});
});
}
/**
* Creates a Collaborator in the repository.
*/
function createCollaborator(github, username, repository, collaborator)
{
return new Promise(function (resolve, reject) {
github.repos.addCollaborator({ owner:username, repo:repository, username:collaborator, permission:"pull"}, function (error, response)
{
if (error) {
// when label already exists we carry on
if (error.message.search("already_exists")) {
return resolve();
} else {
return reject(error);
}
} else {
return resolve();
}
});
});
}
function getIssue(github, username, repository, number) {
return new Promise(function (resolve, reject) {
github.issues.get({ owner:username, repo:repository, number:number}, function(error, response) {
if (error) {
return reject(error);
} else {
return resolve(response);
}
});
});
}
function createIssueIfAbsent(github, username, token, repository, issue, comments, milestones, collaborators, timeout, response, defaultusername) {
return getIssue(github, username, repository, issue.new_id)
.then(function(existing) {
var jiraProject = issue.project;
var jiraIssue = issue.old_id;
console.log("Skipping JIRA Issue: " + issue.old_id + " as a GitHub Issue already exists");
response.write("<p>Skipping the migration of JIRA " + jiraProject + "-" + jiraIssue + " as it already exists.</p>");
return Promise.resolve();
})
.catch(function(error) {
return createIssue(github, username, token, repository, issue, comments, milestones, collaborators, timeout, response, defaultusername)
});
}
/**
* Creates a GitHub Issue.
*/
function createIssue(github, username, token, repository, issue, comments, milestones, collaborators, timeout, response, defaultusername)
{
return new Promise(function (resolve, reject) {
var jiraProject = issue.project;
var jiraIssue = issue.old_id;
var githubIssue = issue.new_id;
console.log("Migrating JIRA Issue: " + jiraIssue + " to GitHub");
response.write("<p>Creating GitHub issue for JIRA " + jiraProject + "-" + jiraIssue + ". ");
// create milestone (when there's a fix version)
if (issue.fixVersion) {
// determine the GitHub milestone for the fix version.
var milestone = milestones[issue.fixVersion];
if (milestone) {
issue.milestone = milestone.number;
}
}
// ensure the assignee is a known collaborator
if (!(issue.assignee in collaborators)) {
// Add a comment storing the old assignee who is not a collaborator
if (issue.assignee) {
issue.labels.push("ERR: Assignee");
comments.push({
created_at: issue.created_at,
body: "Was assigned to " + issue.assignee
});
// assign the issue the default username
issue.assignee = defaultusername;
}
}
// add a comment indicating the issue was automatically imported
comments.push({
created_at: new Date(),
body: "This issue was imported from java.net JIRA " + issue.project + "-" + issue.old_id
});
// add a comment indicating the resolution
if (issue.closed && issue.resolution) {
comments.push({
created_at: issue.closed_at,
body: "Marked as **" + issue.resolution.toLowerCase() +
"** on " + moment(issue.closed_at).format("dddd, MMMM Do YYYY, h:mm:ss a")
});
}
// ensure the issue has a body
if (!issue.body || issue.body == "")
{
issue.body = issue.title;
}
// remove JIRA specific properties
delete issue.old_id;
delete issue.new_id;
delete issue.project;
delete issue.reporter;
delete issue.resolution;
delete issue.fixVersion;
if (!(issue.assignee)) {
delete issue.assignee;
}
// create the issue using the issue importer API
var postRequestOptions = {
method: 'POST',
uri: 'https://api.github.com/repos/' + username + '/' + repository + '/import/issues',
headers: {
'Authorization': "token " + token,
'Accept': "application/vnd.github.golden-comet-preview+json",
'User-Agent': USER_AGENT
},
json: true,
body: {
'issue': issue,
'comments': comments
}
};
var getRequestOptions = {
method: 'GET',
headers: {
'Authorization': "token " + token,
'Accept': "application/vnd.github.golden-comet-preview+json",
'User-Agent': USER_AGENT
},
json: true
};
console.log("Importing Issue: " + jiraIssue);
console.log(issue);
console.log(comments);
retry(function() {
return request(postRequestOptions)
.then(function (body) {
if (body.id) {
console.log("Migrating JIRA " + jiraProject + "-" + jiraIssue + ". Created GitHub Request: " + body.id + ". (" + body.status + ")");
response.write("Created GitHub Request " + body.id + ". ");
// wait until the issue is imported
// options for the status request
getRequestOptions.uri = body.url;
return retry(function() {
return request(getRequestOptions)
.then(function(body) {
switch(body.status) {
case "imported":
var githubIssue = body.issue_url.split("/").pop();
return Promise.resolve(githubIssue);
case "failed":
console.log("$$$$ ERROR $$$$");
console.log(postRequestOptions);
console.log(body);
if(body.errors) {
if(body.errors[0].resource == "Internal Error") {
throw new retry.StopError('internal_error');
}
else {
throw new retry.StopError('other_error');
}
}
else {
return Promise.reject(new Error(JSON.stringify(body)));
}
default:
return Promise.reject(new Error('JIRA Issue migration still pending. Last result:' + JSON.stringify(body)));
}
});
}, { timeout: timeout })
.then(function(githubIssue) {
return Promise.resolve(githubIssue);
})
.catch(function(error) {
if(error.message) {
if(error.message == "other_error") {
console.log("Request Failed due to some other error. Check logs");
throw new retry.StopError('other_error');
}
}
console.log("Request Failed. Will retry again");
return Promise.reject(new Error(error));
});
} else {
console.log("Failed to migrate JIRA Issue: " + jiraIssue + " because: " + body.message);
response.write("Failed to migrate JIRA Issue " + jiraIssue + " because: " + body.message + "</p>");
reject(body);
}
})
}, {max_tries: -1})
.then(function(githubIssue) {
console.log("Created GitHub Issue #" + githubIssue + " for JIRA Issue: " + jiraIssue)
response.write("Successfully created GitHub Issue # " + githubIssue + ".</p>");
resolve(githubIssue);
})
.catch(function (error) {
console.log("Failed to migrate JIRA Issue: " + issue + " due to " + error);
response.write("Failed to migrate JIRA Issue " + issue + " due to " + error + "</p>");
reject(error);
});
});
}
function getCollaborators(github, username, repository, collaborators)
{
return new Promise(function (resolve, reject) {
console.log("Obtaining Collaborators from GitHub");
github.repos.getCollaborators({owner: username, repo: repository, per_page: 100}, function (error, response) {
if (error) {
return reject(error);
} else {
// remember the collaborators
response.forEach(function(collaborator) {
collaborators[collaborator.login] = collaborator;
});
return resolve(collaborators);
}
});
});
}
/**
* Obtains an array of all the Milestones.
*/
function getMilestones(github, username, repository, milestones)
{
return new Promise(function (resolve, reject) {
console.log("Obtaining Milestones from GitHub");
github.issues.getMilestones({owner: username, repo: repository}, function (error, response) {
if (error) {
return reject(error);
} else {
// add all of the milestones to the local map so we can look them up
response.forEach(function(milestone) {
milestones[milestone.title] = milestone;
});
return resolve(milestones);
}
});
});
}
/**
* Imports the specified JIRA project into a GitHub Issue tracking system.
*
* @param project
*/
function importJIRAProject(project, response) {
// the github timeout (2 minutes)
var timeout = 120000;
// ----- connect and authenticate to github -----
response.write("<p>Connecting to Github Repository <b>" + project.repository +
"</b> on behalf of <b>" + project.username +
"</b> using token <b>" + project.token + "</b></p>");
var github = new GitHub({
// required
version: "3.0.0",
// optional
debug: false,
protocol: "https",
host: "api.github.com",
timeout: timeout,
headers: {
"user-agent": USER_AGENT
}
});
github.authenticate({
type: "token",
token: project.token
});
// acquire the repository
github.repos.get({ owner: project.username, repo: project.repository}, function (error, data)
{
if (error)
{
response.write("<p>Failed to perform migration. GitHub reported the following error: " + error + "</p>");
response.end();
}
else
{
response.write("<p>Connected to Github. Commencing Issue Creation.</p>");
// the milestones and collaborators known to github for the project
var milestones = {};
var collaborators = {};
// an array of initialization promises
// (these need to be complete before we can start creating issues)
var initialization = [];
// ----- create the versions as milestones -----
response.write("<p>Creating JIRA Versions as GitHub Milestones.</p>");
initialization.push(
Promise.each(project.versions, function(version) {
return Promise.delay(REQUEST_DELAY, createMilestone(github, project.username, project.repository, version));
}).then(function() {
response.write("<p>All Versions Created</p>");
}));
// ----- create the components as labels -----
response.write("<p>Creating JIRA Components as GitHub Labels</p>");
initialization.push(
Promise.each(project.components, function(component) {
return Promise.delay(REQUEST_DELAY, createLabel(github, project.username, project.repository, "Component: " + component));
}).then(function() {
response.write("<p>All Components Created</p>");
}));
// ----- create the types as labels -----
response.write("<p>Creating JIRA Issue Types as GitHub Labels</p>");
initialization.push(
Promise.each(project.types, function(type) {
return Promise.delay(REQUEST_DELAY, createLabel(github, project.username, project.repository, "Type: " + type));
}).then(function() {
response.write("<p>All Issue Types Created</p>");
}));
// ----- create the priorities as labels -----
response.write("<p>Creating JIRA Priorities as GitHub Labels</p>");
initialization.push(
Promise.each(project.priorities, function(priority) {
return Promise.delay(REQUEST_DELAY, createLabel(github, project.username, project.repository, "Priority: " + priority));
}).then(function() {
response.write("<p>All Priorities Created</p>");
}));
// acquire the known collaborators
initialization.push(getCollaborators(github, project.username, project.repository, collaborators));
Promise.all(initialization).then(function() {
return getMilestones(github, project.username, project.repository, milestones);
}).then(function() {
console.log("Creating GitHub Issues for JIRA Issues");
// create the issues
return Promise.each(project.issues, function(issue) {
return Promise.delay(REQUEST_DELAY, createIssueIfAbsent(github, project.username, project.token, project.repository, issue.issue, issue.comments, milestones, collaborators, timeout, response, project.defaultusername));
});
}).then(function () {
response.write("<p>Completed Issue Migration!</p>");
// we're now done
response.end();
});
}
});
}
/**
* Create collaborators for the project
*/
function importCollaborators(repository, username, token, collaborators, response) {
var timeout = 120000;
// ----- connect and authenticate to github -----
response.write("<p>Connecting to Github Repository <b>" + repository +
"</b> on behalf of <b>" + username +
"</b> using token <b>" + token + "</b></p>");
var github = new GitHub({
// required
version: "3.0.0",
// optional
debug: false,
protocol: "https",
host: "api.github.com",
timeout: timeout,
headers: {
"user-agent": USER_AGENT
}
});
github.authenticate({
type: "token",
token: token
});
// acquire the repository
github.repos.get({ owner: username, repo: repository}, function (error, data)
{
if (error)
{
response.write("<p>Failed to perform migration. GitHub reported the following error: " + error + "</p>");
response.end();
}
// an array of initialization promises
// (these need to be complete before we can start creating issues)
var initialization = [];
response.write("<p>Adding collaborators to the project</p>")
initialization.push(
Promise.each(collaborators, function(collaborator) {
return Promise.delay(REQUEST_DELAY, createCollaborator(github, username, repository, collaborator));
}).then(function() {
response.write("<p>All Collaborators Created</p>");
}));
Promise.all(initialization).then(function() {
response.write("<p>Completed Collaborators Migration!</p>");
response.end();
});
});
}
exports.createIssue = createIssue;
exports.createIssueIfAbsent = createIssueIfAbsent;
exports.createLabel = createLabel;
exports.createMilestone = createMilestone;
exports.getCollaborators = getCollaborators;
exports.getIssue = getIssue;
exports.getMilestones = getMilestones;
exports.importJIRAProject = importJIRAProject;
exports.importCollaborators = importCollaborators;
exports.USER_AGENT = USER_AGENT;