This repository has been archived by the owner on Feb 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 33
/
RallyValidate.js
1081 lines (989 loc) · 34.2 KB
/
RallyValidate.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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint no-multi-spaces: ["error", { ignoreEOLComments: true }] */
// Set the config file info and requirements
const configFile = 'rally.yml'
const outdent = require('outdent')
const rally = require('rally')
const yaml = require('js-yaml')
const queryUtils = rally.util.query
class RallyValidate {
/**
* Initialize the Probot framework
*
* @constructor
* @param robot
*/
constructor (robot) {
this.robot = robot
}
/**
* Sleep for a given period
*
* @param ms
* @returns {Promise<unknown>}
*/
async sleep (ms) {
return new Promise(resolve => {
setTimeout(resolve, ms)
})
}
/**
* Initialize the Rally client
*
* @param config
* @returns {Promise<void>}
*/
async initializeRallyClient (config) {
let rallyServer = process.env.RALLY_SERVER
let rallyUsername = process.env.RALLY_USERNAME
let rallyPassword = process.env.RALLY_PASSWORD
let rallyAPIKey = process.env.RALLY_API_KEY
if (config.rally) {
if (config.rally.server) { // Specify the RallyDev URL
rallyServer = config.rally.server
}
if (config.rally.username) { // Rally Username (should be stored elsewhere)
rallyUsername = config.rally.username
}
if (config.rally.password) { // Rally Password, to override global defaults
rallyPassword = config.rally.password
}
if (config.rally.api_key) { // Rally API key, to override global default
rallyAPIKey = config.rally.api_key
}
if (!config.rally.projects || config.rally.projects.length < 1) {
config.rally.projects = ['Any']
}
}
const rallyClient = rally({
user: rallyUsername, // Required if no api key, defaults to process.env.RALLY_USERNAME
pass: rallyPassword, // Required if no api key, defaults to process.env.RALLY_PASSWORD
apiKey: rallyAPIKey, // Preferred, required if no user/pass, defaults to process.env.RALLY_API_KEY
apiVersion: 'v2.0', // This is the default and may be omitted
server: rallyServer, // This is the default and may be omitted
requestOptions: {
headers: {
'X-RallyIntegrationName': 'Rally + GitHub', // while optional, it is good practice to
'X-RallyIntegrationVendor': 'GitHub, Inc', // provide this header information
'X-RallyIntegrationVersion': '1.0'
}
// any additional request options (proxy options, timeouts, etc.)
}
})
return rallyClient
}
/**
* Get the default config from the org-level repo
*
* @param context
* @returns {Promise<{}>}
*/
async getDefaultConfig (context) {
const noFile = true
const orgConfigRepoName = process.env.ORG_CONFIG_REPO_NAME ? process.env.ORG_CONFIG_REPO_NAME : '.github'
let orgConfig
// Get config default from org-level repo .github/rally/<REPO_NAME>.yml
let orgConfigResponse = await context.github.repos.getContents({
owner: context.payload.repository.owner.login,
repo: orgConfigRepoName,
path: '.github/rally/' + context.payload.repository.name + '.yml'
})
.catch(() => ({ // Failed to find or open any default config file
noFile
}))
// Fall back to the default org-level config .github/rally.yml
if (orgConfigResponse.noFile) {
this.robot.log.info('NOTE: config file not found in: ' + orgConfigRepoName + '/.github/rally/' + context.payload.repository.name + '.yml.')
orgConfigResponse = await context.github.repos.getContents({
owner: context.payload.repository.owner.login,
repo: orgConfigRepoName,
path: '.github/' + configFile
})
.catch(() => ({ // Failed to find or open any default config file
noFile
}))
}
if (orgConfigResponse.noFile) {
this.robot.log.info('NOTE: config file not found in: ' + orgConfigRepoName + '/.github/' + configFile + '.')
orgConfig = {}
} else {
// Config file found, need to parse variables
const orgConfigString = Buffer.from(orgConfigResponse.data.content, 'base64').toString('ascii')
orgConfig = yaml.load(orgConfigString)
}
return orgConfig
}
/**
* Process the pull request
*
* @param context
* @returns {Promise<void>}
*/
async handlePullRequest (context) {
await this.handlePullRequestWithRally (context, this.initializeRallyClient)
}
/**
* Process the pull request with the given initializeRallyClient
*
* @param context
* @param _initializeRallyClient
* @returns {Promise<void>}
*/
async handlePullRequestWithRally(context, _initializeRallyClient) {
// Initialize Rally Artifacts
const rallyArtifacts = {}
this.robot.log.debug(context)
// Get our config file
const defaultConfig = await this.getDefaultConfig(context)
const config = await context.config(configFile, defaultConfig)
// Confirm that the config file exists
if (!config) {
// Check environment variable to see whether we need to enforce on this repository
if (process.env.ENFORCE_ALL_REPOS === 'true') {
await this.setStatusFail(context, this.createNoConfigMessage())
}
return
}
this.robot.log.debug('Final Config:', config)
// Set the status to in_progress
await this.setStatusPending(context, config)
try {
const rallyClient = await _initializeRallyClient(config)
// Get commit comments for validation
rallyArtifacts.commits = await this.checkCommitMessages(context, config, rallyClient)
// Get the PR title for validation
rallyArtifacts.titleList = await this.checkPRTitle(context, config, rallyClient)
// Get the PR body for validation
rallyArtifacts.bodyList = await this.checkPRBody(context, config, rallyClient)
await this.updateRallyConnections(rallyClient, rallyArtifacts, context.payload.pull_request, config)
} catch (e) {
await this.setStatusFail(context, config, 'Error occurred while validating Rally Artifacts: ' + e)
this.robot.log.error(e)
return
}
// Set the status message
const { statusMessage, isSuccess } = await this.processArtifacts(config, rallyArtifacts)
// Set the check status based on Rally artifact validation
if (isSuccess) {
await this.setStatusPass(context, config, statusMessage)
} else {
await this.setStatusFail(context, config, statusMessage)
}
if (config.commentOnPull) {
// Comment on the PR
await this.commentOnPull(context, statusMessage)
}
}
/**
* Process the closed pull request
*
* @param context
* @returns {Promise<void>}
*/
async handlePullRequestClosed (context) {
// Only close Rally Artifacts if PR is merged
if (context.payload.pull_request.merged === false) {
return
}
const defaultConfig = await this.getDefaultConfig(context)
const config = await context.config(configFile, defaultConfig)
if (!config) {
// Check environment variable to see whether we need to enforce on this repository
if (process.env.ENFORCE_ALL_REPOS === 'true') {
await this.setStatusFail(context, config, this.createNoConfigMessage())
}
return
}
const rallyClient = await this.initializeRallyClient(config)
this.closeArtifactsFromPRBody(context, config, rallyClient)
}
/**
* Create the status message for the checks
*
* @param checkPRBody
* @param checkPRTitle
* @param checkCommitMessages
* @param statuses
* @param projects
* @param bodyMessage
* @param titleMessage
* @param commitsMessage
* @returns {*|string}
*/
createStatusMessage ({ checkPRBody, checkPRTitle, checkCommitMessages, statuses, projects, bodyMessage, titleMessage, commitsMessage }) {
return outdent`This repository requires a valid Rally artifact to be present in the following portions of this pull before merge will be allowed:
${checkPRBody}
${checkPRTitle}
${checkCommitMessages}
_Valid artifact states for this repository_:
${statuses}
_Valid projects for this repository_
${projects}
${bodyMessage}
${titleMessage}
${commitsMessage}
`
}
/**
* Process the artifacts that have been found in the pull request
*
* @param config
* @param rallyArtifacts
* @returns {Promise<{statusMessage: (*|string), isSuccess: boolean}>}
*/
async processArtifacts (config, rallyArtifacts) {
const statuses = [...new Set(config.rally.states.map(status => `- [x] \`${status}\``))]
const projects = [...new Set(config.rally.projects.map(project => `- [x] \`${project}\``))]
const statusMessageOptions = {
checkPRBody: config.checkPRBody ? '- [x] Pull Request Body' : '- [ ] Pull Request Body',
checkPRTitle: config.checkPRTitle ? '- [x] Pull Request Title' : '- [ ] Pull Request Title',
checkCommitMessages: config.checkCommitMessages ? '- [x] Commit Messages' : '- [ ] Commit Messages',
statuses: statuses.join('\n'),
projects: projects.join('\n')
}
let bodyResult = {
message: '',
isSuccess: true
}
let titleResult = {
message: '',
isSuccess: true
}
let commitsResult = {
message: '',
isSuccess: true
}
if (config.checkPRBody) {
bodyResult = await this.formatBodyMessage(config, rallyArtifacts.bodyList)
}
if (config.checkPRTitle) {
titleResult = await this.formatTitleMessage(config, rallyArtifacts.titleList)
}
if (config.checkCommitMessages) {
commitsResult = await this.formatCommitsMessage(config, rallyArtifacts.commits.commitsWithArtifact, rallyArtifacts.commits.commitsWithoutArtifact)
}
const isSuccess = (bodyResult.isSuccess && titleResult.isSuccess && commitsResult.isSuccess)
Object.assign(statusMessageOptions, {
bodyMessage: bodyResult.message,
titleMessage: titleResult.message,
commitsMessage: commitsResult.message
})
const statusMessage = this.createStatusMessage(statusMessageOptions)
return { statusMessage, isSuccess }
}
/**
* Pull Request Body
*
* Format the check body and/or pull request comment body
* with the status of the PR body validation
*
* @param config
* @param bodyList
*/
async formatBodyMessage (config, bodyList) {
// Default isSuccess to true, then set to fail if matches fail
let isSuccess = true
// Set the content headers
let message = '\n### Pull Request body validation\n'
// Format the message for the PR body
if (bodyList && bodyList.length > 0) {
message += 'The following Rally artifacts have been found in the body of this pull request, with validation status below\n\n'
message += '| Artifact | Rally Status | Project | Validation |\n'
message += '| :------- | :----------- | :------ | ---------- | \n'
bodyList.forEach(artifact => {
if (!artifact.isValid) { isSuccess = false }
// Append the status to the PR comment
message += `| [${artifact.key}](${artifact.artifact._ref}) | \`${artifact.status}\` | \`${artifact.projectName}\` | ${artifact.statusIcon} \`${artifact.validState}\` |\n`
})
} else {
message += '\n:heavy_exclamation_mark: No valid artifacts were found in the pull request body'
isSuccess = false
}
return { message, isSuccess }
}
/**
* Pull Request Title
*
* Format the check body and/or pull request comment body
* with the status of the PR title validation
*
* @param config
* @param bodyList
*/
async formatTitleMessage (config, titleList) {
// Default isSuccess to true, then set to fail if matches fail
let isSuccess = true
// Set the content headers
let message = '\n### Pull Request title validation\n'
// Format the message for PR title
if (titleList && titleList.length > 0) {
message += 'The following Rally artifacts have been found in the title of this pull request, with validation status below\n\n'
message += '| Artifact | Rally Status | Project | Validation |\n'
message += '| :------- | :----------- | :------ | ---------- |\n'
titleList.forEach(artifact => {
if (!artifact.isValid) { isSuccess = false }
// Append the status to the PR comment
message += `| [${artifact.key}](${artifact.artifact._ref}) | \`${artifact.status}\` | \`${artifact.projectName}\` | ${artifact.statusIcon} \`${artifact.validState}\` |\n`
})
} else {
message += '\n:heavy_exclamation_mark: No valid artifacts were found in the pull request title'
isSuccess = false
}
return { message, isSuccess }
}
/**
* Pull Request Title
*
* Format the check body and/or pull request comment body
* with the status of the commit message validation
*
* @param config
* @param commitsWithArtifact
* @param commitsWithoutArtifact
*/
async formatCommitsMessage (config, commitsWithArtifact = [], commitsWithoutArtifact = []) {
// Default isSuccess to true, then set to fail if matches fail
let isSuccess = true
// Set the content headers
let message = '\n### Commit validation\n'
message += '| Artifact | Commit SHA | Rally Status | Project | Validation |\n'
message += '| :------- | :--------- | :----------- | :------ | ---------- |\n'
// Process commits with Rally artifacts in them
commitsWithArtifact.forEach(artifact => {
if (!artifact.rally.isValid) { isSuccess = false }
// Append the status to the PR comment
message += `| [${artifact.rally.key}](${artifact.rally.artifact._ref})) | [${artifact.sha_short}](${artifact.commit_url}) | \`${artifact.rally.status}\` | \`${artifact.rally.projectName}\` | ${artifact.rally.statusIcon} \`${artifact.rally.validState}\` |\n`
})
// Process commits without Rally artifacts
if (commitsWithoutArtifact && commitsWithoutArtifact.length > 0) {
let commitsColumn = ''
commitsWithoutArtifact.forEach(commit => {
commitsColumn += `[${commit.sha_short}](${commit.commit_url})<br>`
})
message += `| \`missing\` | ${commitsColumn} | \`missing\` | \`missing\` | :heavy_exclamation_mark: \`failed\` |\n`
message += '\n**Note:** You can [amend your commit message](https://help.github.com/en/github/committing-changes-to-your-project/changing-a-commit-message) if needed\n\n'
isSuccess = false
}
return { message, isSuccess }
}
/**
* Comment on the pull request with the same message we have in the checks tab
*
* @param context
* @param message
* @returns {Promise<void>}
*/
async commentOnPull (context, message) {
await context.github.issues.createComment({
owner: context.payload.repository.owner.login,
repo: context.payload.repository.name,
issue_number: context.payload.pull_request.number,
body: message
})
}
/**
* Check commit messages for Rally artifacts
*
* @param context
* @param config
* @param rallyClient
* @returns {Promise<{commitsWithoutArtifact: [], commitsWithArtifact: []}>}
*/
async checkCommitMessages (context, config, rallyClient) {
const commitsWithArtifact = []
const commitsWithoutArtifact = []
// Only check commit messages if specified in the config
if (config.checkCommitMessages) {
// Get the URL for the pull request
const commitsUrl = context.payload.pull_request.html_url
// Get all the commits in the pull request
const compare = await context.github.repos.compareCommits(context.repo({
base: context.payload.pull_request.base.sha,
head: context.payload.pull_request.head.sha
}))
// Check that every commit message has a Rally artifact in it
for (const data of compare.data.commits) {
const rallyArtifact = this.findArtifact(data.commit.message, config.rally.objects)
const commitStatus = {
sha: data.sha,
message: data.commit.message,
sha_short: data.sha.substr(0, 6),
commit_url: `${commitsUrl}/commits/${data.sha}`,
rally: await this.validateArtifact(rallyClient, rallyArtifact[0], 'commitMessages', context.payload.pull_request, config)
}
// Group commits with keys and those without
if (commitStatus.rally) {
commitsWithArtifact.push(commitStatus)
} else {
commitsWithoutArtifact.push(commitStatus)
}
}
}
return {
commitsWithArtifact: commitsWithArtifact,
commitsWithoutArtifact: commitsWithoutArtifact
}
}
/**
* Check the pull request title for Rally artifacts
*
* @param context
* @param config
* @param rallyClient
* @returns {Promise<*[]|({artifact: *, validState: *, isValid: *, property: *, statusIcon: *, projectName: *, key: *, status: *}|undefined)[]>}
*/
async checkPRTitle (context, config, rallyClient) {
if (config.checkPRTitle) {
// Look for artifact keys in the PR title
const artifactKeys = this.findArtifact(context.payload.pull_request.title, config.rally.objects)
if (artifactKeys) { // validate each key we find
return Promise.all(artifactKeys.map(artifactKey => {
return this.validateArtifact(rallyClient, artifactKey, 'prTitle', context.payload.pull_request, config)
}))
} else {
this.robot.log.debug('No artifact found in PR title')
}
}
return []
}
/**
* Check the pull request body for Rally artifacts
*
* @param context
* @param config
* @param rallyClient
* @returns {Promise<*[]|({artifact: *, validState: *, isValid: *, property: *, statusIcon: *, projectName: *, key: *, status: *}|undefined)[]>}
*/
async checkPRBody (context, config, rallyClient) {
if (config.checkPRBody) {
// Look for artifact keys in the PR body
const artifactKeys = this.findArtifact(context.payload.pull_request.body, config.rally.objects)
if (artifactKeys) { // validate each key we find
return Promise.all(artifactKeys.map(artifactKey => {
return this.validateArtifact(rallyClient, artifactKey, 'prBody', context.payload.pull_request, config)
}))
} else {
this.robot.log.debug('No artifact found in PR body')
}
}
return []
}
/**
* Respond to the `/completes` command in a pull request body
*
* @param context
* @param config
* @param rallyClient
* @returns {Promise<void[]>}
*/
async closeArtifactsFromPRBody (context, config, rallyClient) {
if (config.mergeOnPRBody) {
// Look for artifact keys in the PR body
const artifactKeys = this.findPromotionArtifact(context.payload.pull_request.body, config.rally.objects, ['completes'])
if (artifactKeys) { // close on each key we find
return Promise.all(artifactKeys.map(artifactKey => {
return this.promoteArtifact(rallyClient, artifactKey, config)
}))
} else {
this.robot.log.debug('No artifact found in PR body')
}
}
}
/**
* Set the checks status to 'Pending'
*
* @param context
* @param config
* @returns {Promise<*>}
*/
async setStatusPending (context, config) {
return context.github.checks.create(context.repo({
name: config.checksName,
head_branch: context.payload.pull_request.head.ref,
head_sha: context.payload.pull_request.head.sha,
status: 'in_progress',
started_at: new Date(),
output: {
title: 'Rally validation is in progress...',
summary: 'We\'re currently validating the status of any Rally artifacts associated with this pull request. Please stand by.'
}
}))
}
/**
* Override the failed check
*
* @param context
* @param config
* @returns {Promise<*>}
*/
async setOverridePass (context, config) {
const timeStart = new Date()
return context.github.checks.create(context.repo({
name: config.checksName,
head_branch: context.payload.check_run.check_suite.head_branch,
head_sha: context.payload.check_run.head_sha,
status: 'completed',
started_at: timeStart,
conclusion: 'success',
completed_at: new Date(),
output: {
title: 'Rally artifact validation manually overridden by @' + context.payload.sender.login,
summary: 'Commit sign-off was manually approved by @' + context.payload.sender.login
}
}))
}
/**
* Set the checks status to 'Passed'
*
* @param context
* @param config
* @param statusMessage
* @returns {Promise<*>}
*/
async setStatusPass (context, config, statusMessage = 'All Rally artifacts have been validated!') {
const timeStart = new Date()
return context.github.checks.create(context.repo({
name: config.checksName,
head_branch: context.payload.pull_request.head.ref,
head_sha: context.payload.pull_request.head.sha,
status: 'completed',
started_at: timeStart,
conclusion: 'success',
completed_at: new Date(),
output: {
title: 'Rally artifacts have been validated',
summary: statusMessage
}
}))
}
/**
* Set the checks status to 'Failed'
*
* @param context
* @param config
* @param statusMessage
* @returns {Promise<*>}
*/
async setStatusFail (context, config, statusMessage = 'Please provide a valid Rally artifact') {
const timeStart = new Date()
return context.github.checks.create(context.repo({
name: config.checksName,
head_branch: context.payload.pull_request.head.ref,
head_sha: context.payload.pull_request.head.sha,
status: 'completed',
started_at: timeStart,
conclusion: 'failure',
completed_at: new Date(),
output: {
title: 'Rally artifact validation failed',
summary: statusMessage
}
}))
}
/**
* Create the message that notifies users they are missing the config file
*
* @returns {string}
*/
createNoConfigMessage () {
let noConfigMessage = 'No config file exists in this repository. Please create a valid config file at `.github/rally.yml`\n\nExample config file:\n\n'
noConfigMessage += `---
# Name of the GitHub Check
checksName: integrations/rally
# Check PR Body for Rally artifact
checkPRBody: true
# Check PR Title for Rally artifact
checkPRTitle: true
# Check all commit messages for a Rally artifact
checkCommitMessages: true
# Comment on the PR in addition to the check message?
commentOnPull: false"
rally:
server: https://rally1.rallydev.com
## Leave these blank if you use an API key
##username: rallyUser
##password: rallyPass
## This is required if we don't use username/password
## NOTE: If you set this in your .env file then you can
## leave this commented out. It will override your .env
#api_key: _1234abc567...
# Which workspace OID this repo will link to
workspace: 12345
# Which projects this repo will link to.
# To have it connect to any project, leave this value blank
projects:
- Sample Project
- devops-engineering
# List of valid Rally objects to check
objects:
- defect
#- defectsuite
#- task
#- testcase
#- hierarchicalrequirement
- userstory
#- story
# List of Rally states that an issue must be in in order to pass
states:
- Defined
- In-Progress
`
return noConfigMessage
}
/**
* Get all unique artifact prefixes based on the requested artifactTypes
*
* @param text
* @param artifactTypes
* @returns {[]}
*/
findArtifact (text, artifactTypes) {
let artifacts = []
let prefixes = []
const prefixMapping = {
defect: ['D', 'DE'],
defectsuite: ['DS'],
task: ['TA'],
testcase: ['TC'],
hierarchicalrequirement: ['S', 'US'],
userstory: ['S', 'US'],
story: ['S', 'US']
}
artifactTypes.forEach((type) => {
const newPrefixes = prefixMapping[type]
prefixes = prefixes.concat(newPrefixes)
})
prefixes = [...new Set(prefixes)]
prefixes.forEach(prefix => {
const regexp = RegExp('\\b' + prefix + '[0-9]{1,10}\\b', 'gi')
const artifactMatches = text.match(regexp)
if (artifactMatches) {
artifacts = artifacts.concat(artifactMatches.map(
artifactMatch => artifactMatch.toUpperCase())
)
}
})
return artifacts
}
/**
* Discover Rally artifacts that will be transitioned with commands
*
* @param text
* @param artifactTypes
* @param promotionCommands
* @returns {[]}
*/
findPromotionArtifact (text, artifactTypes, promotionCommands) {
let artifacts = []
// Get all unique artifact prefixes based on the requested artifactTypes
let prefixes = []
const prefixMapping = {
defect: ['D', 'DE'],
defectsuite: ['DS'],
task: ['TA'],
testcase: 'TC',
hierarchicalrequirement: ['S', 'US'],
userstory: ['S', 'US'],
story: ['S', 'US']
}
artifactTypes.forEach((type) => {
const newPrefixes = prefixMapping[type]
prefixes = prefixes.concat(newPrefixes)
})
prefixes = [...new Set(prefixes)]
if (promotionCommands && promotionCommands.length > 0) {
promotionCommands.forEach(command => {
prefixes.forEach(prefix => {
const regexp = RegExp('/' + command + ' ' + prefix + '[0-9]{1,10}\\b', 'gi')
const matches = text.match(regexp)
if (matches) {
const artifactMatches = matches.map(match => {
const artifactMatch = {
command: command,
artifact: match.substr(command.length + 2).toUpperCase()
}
return artifactMatch
})
artifacts = artifacts.concat(artifactMatches)
}
})
})
}
return artifacts
}
/**
* Re-run a failed check
*
* @param context
* @param config
* @returns {Promise<void>}
*/
async rerunCheck (context) {
await this.rerunCheckWithRally (context, this.initializeRallyClient)
}
/**
* Process the pull request with the given initializeRallyClient
*
* @param context
* @param _initializeRallyClient
* @returns {Promise<void>}
*/
async rerunCheckWithRally(context, _initializeRallyClient) {
const prContext = context
const defaultConfig = await this.getDefaultConfig(context)
const config = await context.config(configFile, defaultConfig)
if (!config) {
await this.setStatusFail(context, this.createNoConfigMessage())
}
let prNumber
if (context.name === 'check_suite') {
prNumber = context.payload.check_suite.pull_requests[0].number
const appId = context.payload.check_suite.app.id
if (appId !== process.env.APP_ID) {
return
}
} else {
prNumber = context.payload.check_run.check_suite.pull_requests[0].number
const checkName = context.payload.check_run.name
if (checkName !== config.checksName) {
return
}
}
const prResponse = await context.github.pulls.get({
owner: context.payload.repository.owner.login,
repo: context.payload.repository.name,
pull_number: prNumber
})
prContext.payload.pull_request = prResponse.data
await this.handlePullRequestWithRally(prContext, _initializeRallyClient)
}
/**
* Parse the pull request to find Rally artifacts
*
* @param artifactName
* @returns {{}}
*/
parseArtifact (artifactName) {
const artifact = {}
const typeMapping = {
D: 'defect',
DE: 'defect',
DS: 'defectsuite',
TA: 'task',
TC: 'testcase',
S: 'hierarchicalrequirement',
US: 'hierarchicalrequirement'
}
artifact.prefix = artifactName.match(/([A-Z]{1,2})/i)[0]
artifact.number = artifactName.match(/[1-9].*/)[0]
artifact.rallyType = typeMapping[artifact.prefix]
return artifact
}
/**
* Validate that the discovered Rally object exists and is in the correct state.
*
* @param rallyClient
* @param key
* @param property
* @param pr
* @param config
* @returns {Promise<{artifact, validState: string, isValid: *, property: *, statusIcon, projectName: string, key: *, status: string}>}
*/
async validateArtifact (rallyClient, key, property, pr, config) {
try {
if (key !== null && key !== undefined) {
const githubArtifact = this.parseArtifact(key)
const queryResponse = await rallyClient.query({
type: githubArtifact.rallyType,
start: 1,
pageSize: 2,
limit: 20,
order: 'Rank',
scope: {
workspace: '/workspace/' + config.rally.workspace
},
fetch: ['FormattedID', 'Name', 'Description', 'ScheduleState', 'State', 'Project', 'Connections'],
query: queryUtils.where('FormattedID', '=', githubArtifact.number),
requestOptions: {}
})
let status
let projectName
let validProject
let validState
let statusIcon
let isValid
if (queryResponse.TotalResultCount === 0) {
status = 'Not Found'
projectName = 'Not Found'
validState = 'failed'
statusIcon = ':heavy_exclamation_mark:'
} else {
const artifact = queryResponse.Results[0]
status = artifact.ScheduleState ? artifact.ScheduleState : artifact.State
projectName = artifact.Project._refObjectName
validProject = (config.rally.projects.includes('Any') || config.rally.projects.includes(projectName))
isValid = (config.rally.states.includes(status) && validProject)
validState = isValid ? 'passed' : 'failed'
statusIcon = isValid ? ':heavy_check_mark:' : ':heavy_exclamation_mark:'
}
const artifactStatus = {
key: key,
property: property,
status: status,
projectName: projectName,
isValid: isValid,
validState: validState,
statusIcon: statusIcon,
artifact: queryResponse.Results[0]
}
return artifactStatus
}
} catch (e) {
this.robot.log.error(e)
throw e
}
}
/**
* Set the Rally object to a specific state when the Pull Request merges.
* Default: 'Completed'
*
* @param rallyClient
* @param artifact
* @param config
* @returns {Promise<void>}
*/
async promoteArtifact (rallyClient, artifact, config) {
try {
const key = artifact.artifact
if (key !== null && key !== undefined) {
const githubArtifact = this.parseArtifact(key)
const queryResponse = await rallyClient.query({
type: githubArtifact.rallyType,
start: 1,
pageSize: 2,
limit: 20,
order: 'Rank',
scope: {
workspace: '/workspace/' + config.rally.workspace
},
fetch: ['FormattedID', 'Name', 'Description', 'ScheduleState', 'Project'],
query: queryUtils.where('FormattedID', '=', githubArtifact.number),
requestOptions: {}
})
if (queryResponse.TotalResultCount !== 0) {
await this.setArtifactScheduleState(rallyClient, queryResponse.Results[0]._ref, 'Completed')
}
}
} catch (e) {
this.robot.log.error(e)
throw e
}
}
/**
* Update the Rally artifact to contain this pull request as a Connection
*
* @param rallyClient
* @param rallyArtifacts
* @param pr
* @param config
* @returns {Promise<void>}
*/
async updateRallyConnections (rallyClient, rallyArtifacts, pr, config) {
let commitList = []
if (rallyArtifacts.commits) {
if (rallyArtifacts.commits.commitsWithArtifact) {
if (Array.isArray(rallyArtifacts.commits.commitsWithArtifact)) {
commitList = rallyArtifacts.commits.commitsWithArtifact.map(commit => commit.rally)
}
}
}
const allArtifacts = [...commitList, ...rallyArtifacts.titleList, ...rallyArtifacts.bodyList]
const validArtifacts = allArtifacts.filter(artifact => artifact.isValid)
// get a set of Artifacts with unique key value
const uniqueArtifacts = []
const map = new Map()
for (const artifact of validArtifacts) {
if (!map.has(artifact.key)) {
map.set(artifact.key, true)
uniqueArtifacts.push(artifact)
}
}
// Get a list of all PRs for this artifact
await uniqueArtifacts.forEach(async artifact => {