forked from danhellem/github-actions-issue-to-work-item
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
634 lines (560 loc) · 16.7 KB
/
index.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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
const core = require(`@actions/core`);
const github = require(`@actions/github`);
const azdev = require(`azure-devops-node-api`);
const debug = false; // debug mode for testing...always set to false before doing a commit
const testPayload = []; // used for debugging, cut and paste payload
main();
async function main() {
try {
const context = github.context;
const env = process.env;
let vm = [];
if (debug) {
// manually set when debugging
env.ado_organization = "{organization}";
env.ado_token = "{azure devops personal access token}";
env.github_token = "{github token}";
env.ado_project = "{project name}";
env.ado_wit = "User Story";
env.ado_close_state = "Closed";
env.ado_new_state = "New";
console.log("Set values from test payload");
vm = getValuesFromPayload(testPayload, env);
} else {
console.log("Set values from payload & env");
vm = getValuesFromPayload(github.context.payload, env);
}
console.log("Context: " + vm);
// todo: validate we have all the right inputs
// go check to see if work item already exists in azure devops or not
// based on the title and tags
console.log("Check to see if work item already exists");
let workItem = await find(vm);
if (workItem === null) {
console.log("Could not find existing ADO workitem");
} else {
console.log("Found existing ADO workitem: " + workItem.id);
}
let issue = "";
// if workItem == -1 then we have an error during find
if (workItem === -1) {
core.setFailed();
return;
}
// if a work item was not found, go create one, unless we are only creating
// items when tagged.
if (!vm.env.createOnTagging) {
if (workItem === null) {
console.log("No work item found, creating work item from issue");
workItem = await create(vm, vm.env.wit);
// if workItem == -1 then we have an error during create
if (workItem === -1) {
core.setFailed();
return;
}
} else {
console.log(`Existing work item found: ${workItem.id}`);
}
}
// create right patch document depending on the action tied to the issue
// update the work item
console.log("Performing action for event: " + vm.action);
switch (vm.action) {
case "opened":
if (!vm.env.createOnTagging && workItem === null) {
workItem === null ? await create(vm, vm.env.wit) : "";
}
break;
case "edited":
workItem != null ? await update(vm, workItem) : "";
break;
case "created": // adding a comment to an issue
workItem != null ? await comment(vm, workItem) : "";
break;
case "closed":
if (vm.env.tagOnClose) {
workItem != null ? await tag(vm, workItem, vm.env.tagOnClose) : "";
} else {
workItem != null ? await close(vm, workItem) : "";
}
break;
case "reopened":
workItem != null ? await reopen(vm, workItem) : "";
break;
case "assigned":
console.log("assigned action is not yet implemented");
break;
case "labeled":
if (vm.env.createOnTagging && workItem === null) {
workItem = await createForLabel(vm);
} else if (vm.env.setLabelsAsTags) {
workItem != null ? await label(vm, workItem) : "";
}
break;
case "unlabeled":
if (vm.env.setLabelsAsTags) {
workItem != null ? await unlabel(vm, workItem) : "";
}
break;
case "deleted":
console.log("deleted action is not yet implemented");
break;
case "transferred":
console.log("transferred action is not yet implemented");
break;
default:
console.log(`Unhandled action: ${vm.action}`);
}
// set output message
if (workItem != null || workItem != undefined) {
console.log(`Work item successfully created or updated: ${workItem.id}`);
core.setOutput(`id`, `${workItem.id}`);
}
} catch (error) {
console.log("Error: " + error);
core.setFailed();
}
}
function formatTitle(vm) {
return "[GitHub #" + vm.number + "] " + vm.title;
}
// create Work Item via https://docs.microsoft.com/en-us/rest/api/azure/devops/
async function create(vm, wit) {
let botMessage = 'This item was auto-opened from GitHub <a href="' +
vm.url +
'" target="_new">issue #' +
vm.number +
'</a> created in the <a href="' +
vm.repo_url +
'" target="_new">' +
vm.repo_fullname +
"</a> project</br></br><b>Description from GitHub: </b></br>" +
vm.body;
let patchDocument = [
{
op: "add",
path: "/fields/System.Title",
value: formatTitle(vm),
},
{
op: "add",
path: "/fields/System.Description",
value: botMessage,
},
{
op: "add",
path: "/fields/Microsoft.VSTS.TCM.ReproSteps",
value: botMessage,
},
{
op: "add",
path: "/fields/System.Tags",
value: vm.env.tags + "; " + vm.repository,
},
{
op: "add",
path: "/fields/System.History",
value:
'GitHub <a href="' +
vm.url +
'" target="_new">issue #' +
vm.number +
'</a> created in <a href="' +
vm.repo_url +
'" target="_new">' +
vm.repo_fullname +
"</a>",
},
{
op: "add",
path: "/relations/-",
value: {
rel: "Hyperlink",
url: vm.url,
},
},
];
// if area path is not empty, set it
if (vm.env.areaPath != "") {
patchDocument.push({
op: "add",
path: "/fields/System.AreaPath",
value: vm.env.areaPath,
});
}
let authHandler = azdev.getPersonalAccessTokenHandler(vm.env.adoToken);
let connection = new azdev.WebApi(vm.env.orgUrl, authHandler);
let client = await connection.getWorkItemTrackingApi();
let workItemSaveResult = null;
try {
workItemSaveResult = await client.createWorkItem(
(customHeaders = []),
(document = patchDocument),
(project = vm.env.project),
(type = wit),
(validateOnly = false),
(bypassRules = vm.env.bypassRules)
);
// if result is null, save did not complete correctly
if (workItemSaveResult == null) {
workItemSaveResult = -1;
console.log("Error: creatWorkItem failed");
console.log(`WIT may not be correct: ${wit}`);
core.setFailed();
} else {
console.log("Work item successfully created");
}
} catch (error) {
workItemSaveResult = -1;
console.log("Error: creatWorkItem failed");
console.log(patchDocument);
console.log(error);
core.setFailed(error);
}
if (workItemSaveResult != -1) {
console.log(workItemSaveResult);
// link the issue to the work item via AB# syntax with AzureBoards+GitHub App
issue = vm.env.ghToken != "" ? await updateIssueBody(vm, workItemSaveResult) : "";
}
return workItemSaveResult;
}
// create a work item for the new label
async function createForLabel(vm) {
console.log("Creating for label=" + vm.label);
if (vm.env.createOnTagging) {
var wit = "";
switch (vm.label) {
case "bug":
wit = "Bug";
break;
case "feature request":
wit = "Scenario"
break;
default:
return null;
}
var workItem = await create(vm, wit);
console.log("Work item created for label=" + vm.label);
return workItem;
}
}
// update existing working item
async function update(vm, workItem) {
let patchDocument = [];
if (
workItem.fields["System.Title"] !=
`[GitHub #${vm.number}] ${vm.title}`
) {
patchDocument.push({
op: "add",
path: "/fields/System.Title",
value: formatTitle(vm),
});
}
if (workItem.fields["System.Description"] != vm.body) {
patchDocument.push({
op: "add",
path: "/fields/System.Description",
value: vm.body,
});
}
if (patchDocument.length > 0) {
return await updateWorkItem(patchDocument, workItem.id, vm.env);
} else {
return null;
}
}
// add comment to an existing work item
async function comment(vm, workItem) {
let patchDocument = [];
if (vm.comment_text != "") {
patchDocument.push({
op: "add",
path: "/fields/System.History",
value:
'<a href="' +
vm.comment_url +
'" target="_new">GitHub Comment Added</a></br></br>' +
vm.comment_text,
});
}
if (patchDocument.length > 0) {
return await updateWorkItem(patchDocument, workItem.id, vm.env);
} else {
return null;
}
}
async function tag(vm, workItem, newTag) {
if (!workItem.fields["System.Tags"].includes(newTag)) {
let patchDocument = [];
patchDocument.push({
op: "add",
path: "/fields/System.Tags",
value: workItem.fields["System.Tags"] + ", " + newTag,
});
console.log("Tagging item with: " + newTag);
return await updateWorkItem(patchDocument, workItem.id, vm.env);
} else {
return null;
}
}
// close work item
async function close(vm, workItem) {
let patchDocument = [];
var closedState = vm.env.closedState;
// TODO: Move into main.yml settings
// switch (workItem.workItemType) {
// case "Bug":
// closedState = "Closed";
// break;
// case "Task":
// case "Deliverable":
// case "Scenario":
// case "Epic":
// closedState = "Completed";
// break;
// }
patchDocument.push({
op: "add",
path: "/fields/System.State",
value: closedState,
});
if (vm.comment_text != "") {
patchDocument.push({
op: "add",
path: "/fields/System.History",
value:
'<a href="' +
vm.comment_url +
'" target="_new">GitHub Comment Added</a></br></br>' +
vm.comment_text,
});
}
if (vm.closed_at != "") {
patchDocument.push({
op: "add",
path: "/fields/System.History",
value:
'GitHub <a href="' +
vm.url +
'" target="_new">issue #' +
vm.number +
"</a> was closed on " +
vm.closed_at,
});
}
if (patchDocument.length > 0) {
return await updateWorkItem(patchDocument, workItem.id, vm.env);
} else {
return null;
}
}
// reopen existing work item
async function reopen(vm, workItem) {
let patchDocument = [];
patchDocument.push({
op: "add",
path: "/fields/System.State",
value: vm.env.newState,
});
patchDocument.push({
op: "add",
path: "/fields/System.History",
value: "Issue reopened",
});
if (patchDocument.length > 0) {
return await updateWorkItem(patchDocument, workItem.id, vm.env);
} else {
return null;
}
}
// add new label to existing work item
async function label(vm, workItem) {
let patchDocument = [];
if (!workItem.fields["System.Tags"].includes(vm.label)) {
patchDocument.push({
op: "add",
path: "/fields/System.Tags",
value: workItem.fields["System.Tags"] + ", " + vm.label,
});
}
if (patchDocument.length > 0) {
return await updateWorkItem(patchDocument, workItem.id, vm.env);
} else {
return null;
}
}
async function unlabel(vm, workItem) {
let patchDocument = [];
if (workItem.fields["System.Tags"].includes(vm.label)) {
var str = workItem.fields["System.Tags"];
var res = str.replace(vm.label + "; ", "");
patchDocument.push({
op: "add",
path: "/fields/System.Tags",
value: res,
});
}
if (patchDocument.length > 0) {
return await updateWorkItem(patchDocument, workItem.id, vm.env);
} else {
return null;
}
}
// find work item to see if it already exists
async function find(vm) {
let authHandler = azdev.getPersonalAccessTokenHandler(vm.env.adoToken);
let connection = new azdev.WebApi(vm.env.orgUrl, authHandler);
let client = null;
let workItem = null;
let queryResult = null;
console.log("Finding workitem");
try {
client = await connection.getWorkItemTrackingApi();
} catch (error) {
console.log(
"Error: Connecting to organization. Check the spelling of the organization name and ensure your token is scoped correctly."
);
core.setFailed(error);
return -1;
}
let teamContext = { project: vm.env.project };
let wiql = {
query:
"SELECT [System.Id], [System.WorkItemType], [System.Description], [System.Title], [System.AssignedTo], [System.State], [System.Tags] " +
"FROM workitems " +
"WHERE [System.TeamProject] = @project AND [System.Title] CONTAINS '[GitHub #"+vm.number+"]'",
};
console.log("ADO query: " + wiql.query);
try {
queryResult = await client.queryByWiql(wiql, teamContext);
// if query results = null then i think we have issue with the project name
if (queryResult == null) {
console.log("Error: Project name appears to be invalid");
core.setFailed("Error: Project name appears to be invalid");
return -1;
}
} catch (error) {
console.log("Error: queryByWiql failure");
console.log(error);
core.setFailed(error);
return -1;
}
console.log("Use the first item found");
workItem = queryResult.workItems.length > 0 ? queryResult.workItems[0] : null;
if (workItem != null) {
try {
var result = await client.getWorkItem(workItem.id, null, null, 4);
console.log("Workitem data retrieved: " + workItem.id);
return result;
} catch (error) {
console.log("Error: getWorkItem failure");
core.setFailed(error);
return -1;
}
} else {
return null;
}
}
// standard updateWorkItem call used for all updates
async function updateWorkItem(patchDocument, id, env) {
let authHandler = azdev.getPersonalAccessTokenHandler(env.adoToken);
let connection = new azdev.WebApi(env.orgUrl, authHandler);
let client = await connection.getWorkItemTrackingApi();
let workItemSaveResult = null;
try {
workItemSaveResult = await client.updateWorkItem(
(customHeaders = []),
(document = patchDocument),
(id = id),
(project = env.project),
(validateOnly = false),
(bypassRules = env.bypassRules)
);
return workItemSaveResult;
} catch (error) {
console.log("Error: updateWorkItem failed");
console.log(patchDocument);
core.setFailed(error);
}
}
// update the GH issue body to include the AB# so that we link the Work Item to the Issue
// this should only get called when the issue is created
async function updateIssueBody(vm, workItem) {
var hasLink = vm.body.includes("AB#" + workItem.id);
if (!hasLink) {
const octokit = new github.GitHub(vm.env.ghToken);
vm.body = vm.body + "\r\n\r\nAB#" + workItem.id;
console.log("Attempting update");
try {
console.log(vm);
var result = await octokit.issues.update({
owner: vm.owner,
repo: vm.repository,
issue_number: vm.number,
body: vm.body,
});
return result;
} catch (error) {
console.log("Error: failed to update issue");
core.setFailed(error);
}
}
return null;
}
// get object values from the payload that will be used for logic, updates, finds, and creates
function getValuesFromPayload(payload, env) {
// prettier-ignore
var vm = {
action: payload.action != undefined ? payload.action : "",
url: payload.issue.html_url != undefined ? payload.issue.html_url : "",
number: payload.issue.number != undefined ? payload.issue.number : -1,
title: payload.issue.title != undefined ? payload.issue.title : "",
state: payload.issue.state != undefined ? payload.issue.state : "",
user: payload.issue.user.login != undefined ? payload.issue.user.login : "",
body: payload.issue.body != undefined ? payload.issue.body : "",
repo_fullname: payload.repository.full_name != undefined ? payload.repository.full_name : "",
repo_name: payload.repository.name != undefined ? payload.repository.name : "",
repo_url: payload.repository.html_url != undefined ? payload.repository.html_url : "",
closed_at: payload.issue.closed_at != undefined ? payload.issue.closed_at : null,
owner: payload.repository.owner != undefined ? payload.repository.owner.login : "",
label: "",
comment_text: "",
comment_url: "",
organization: "",
repository: "",
env: {
organization: env.ado_organization != undefined ? env.ado_organization : "",
orgUrl: env.ado_organization != undefined ? "https://dev.azure.com/" + env.ado_organization : "",
adoToken: env.ado_token != undefined ? env.ado_token : "",
ghToken: env.github_token != undefined ? env.github_token : "",
project: env.ado_project != undefined ? env.ado_project : "",
areaPath: env.ado_area_path != undefined ? env.ado_area_path : "",
wit: env.ado_wit != undefined ? env.ado_wit : "Bug",
tags: env.ado_tags != undefined ? env.ado_tags : "",
setLabelsAsTags: env.ado_set_labels != undefined ? env.ado_set_labels : true,
closedState: env.ado_close_state != undefined ? env.ado_close_state : "Closed",
newState: env.ado_new_state != undefined ? env.ado_new_State : "Active",
bypassRules: env.ado_bypassrules != undefined ? env.ado_bypassrules : false,
createOnTagging: env.create_on_tagging != undefined ? env.create_on_tagging : false,
tagOnClose: env.ado_tag_on_close != undefined ? env.ado_tag_on_close : ""
}
};
// label is not always part of the payload
if (payload.label != undefined) {
vm.label = payload.label.name != undefined ? payload.label.name : "";
}
// comments are not always part of the payload
// prettier-ignore
if (payload.comment != undefined) {
vm.comment_text = payload.comment.body != undefined ? payload.comment.body : "";
vm.comment_url = payload.comment.html_url != undefined ? payload.comment.html_url : "";
}
// split repo full name to get the org and repository names
if (vm.repo_fullname != "") {
var split = payload.repository.full_name.split("/");
vm.organization = split[0] != undefined ? split[0] : "";
vm.repository = split[1] != undefined ? split[1] : "";
}
return vm;
}