forked from Azure/azure-rest-api-specs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsummarize-checks.js
More file actions
1040 lines (948 loc) · 32.2 KB
/
summarize-checks.js
File metadata and controls
1040 lines (948 loc) · 32.2 KB
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
// @ts-check
/*
This file is a github script. It will be called directly from a github-script action. This code is a simplified
amalgamation of logic that previously resided in the `PR Summary` check and various events within the `pipelinebot`.
Both from openapi-alps repo.
It will trigger on:
- label addition / removal to a PR
- when one of a set of required workflows configured in .github/workflows/summarize-checks.yaml completes
While handling the incoming trigger, it will:
- Apply or remove labels from the PR based on the status of the checks and other labels
- Create or update a comment that summarizes the user's "next steps to merge" on the PR.
This script is a replacement for the old pipelinebot infrastructure from open-api-alps repository.
*/
// #region imports/constants
import { extractInputs } from "../context.js";
// import { commentOrUpdate } from "../comment.js";
import { execFile } from "../../../shared/src/exec.js";
import { PER_PAGE_MAX } from "../../../shared/src/github.js";
import {
brChRevApproval,
getViolatedRequiredLabelsRules,
processImpactAssessment,
verRevApproval,
} from "./labelling.js";
import {
brchTsg,
checkAndDiagramTsg,
defaultTsg,
diagramTsg,
reqMetCheckTsg,
typeSpecRequirementArmTsg,
typeSpecRequirementDataPlaneTsg,
} from "./tsgs.js";
import fs from "fs/promises";
import os from "os";
import path from "path";
/**
* @typedef {Object} CheckMetadata
* @property {number} precedence
* @property {string} name
* @property {string[]} suppressionLabels
* @property {string} troubleshootingGuide
*/
/**
* @typedef {Object} CheckRunData
* @property {string} name
* @property {string} status
* @property {string} conclusion
* @property {CheckMetadata} checkInfo
*/
/**
* @typedef {Object} WorkflowRunArtifact
* @property {string} name
* @property {number} id
* @property {string} url
* @property {string} archive_download_url
*/
/**
* @typedef {Object} WorkflowRunInfo
* @property {string} name
* @property {number} id
* @property {number} databaseId
* @property {string} url
* @property {number} workflowId
* @property {string} status
* @property {string} conclusion
* @property {string} createdAt
* @property {string} updatedAt
*/
/**
* @typedef {Object} GraphQLCheckRun
* @property {string} name
* @property {string} status
* @property {string} conclusion
* @property {boolean} isRequired
*/
/**
* @typedef {Object} GraphQLCheckSuite
* @property {GraphQLCheckRun[]} nodes
*/
/**
* @typedef {Object} GraphQLCheckSuites
* @property {GraphQLCheckSuite[]} nodes
*/
/**
* @typedef {Object} GraphQLCommit
* @property {GraphQLCheckSuites} checkSuites
*/
/**
* @typedef {Object} GraphQLResource
* @property {GraphQLCheckSuites} checkSuites
*/
/**
* @typedef {Object} GraphQLResponse
* @property {GraphQLResource} resource
* @property {Object} rateLimit
* @property {number} rateLimit.limit
* @property {number} rateLimit.cost
* @property {number} rateLimit.used
* @property {number} rateLimit.remaining
* @property {string} rateLimit.resetAt
*/
/**
* @typedef {import("./labelling.js").RequiredLabelRule} RequiredLabelRule
*/
// Placing these configuration items here until we decide another way to pull them in.
const FYI_CHECK_NAMES = [
"Swagger LintDiff",
"SDK Validation Status",
"Swagger BreakingChange",
"Swagger PrettierCheck",
];
const AUTOMATED_CHECK_NAME = "Automated merging requirements met";
const NEXT_STEPS_COMMENT_ID = "NextStepsToMerge";
/** @type {CheckMetadata[]} */
const CHECK_METADATA = [
{
precedence: 0,
name: "TypeSpec Requirement (resource-manager)",
suppressionLabels: [],
troubleshootingGuide: typeSpecRequirementArmTsg,
},
{
precedence: 0,
name: "TypeSpec Requirement (data-plane)",
suppressionLabels: [],
troubleshootingGuide: typeSpecRequirementDataPlaneTsg,
},
{
precedence: 0,
name: "TypeSpec Validation",
suppressionLabels: [],
troubleshootingGuide: defaultTsg,
},
{
precedence: 0,
name: "license/cla",
suppressionLabels: [],
troubleshootingGuide: defaultTsg,
},
{
precedence: 1,
name: "Swagger Avocado",
suppressionLabels: [],
troubleshootingGuide: defaultTsg,
},
{
precedence: 1,
name: "Swagger SpellCheck",
suppressionLabels: [],
troubleshootingGuide: defaultTsg,
},
{
precedence: 1,
name: "Swagger PrettierCheck",
suppressionLabels: [],
troubleshootingGuide: defaultTsg,
},
{
precedence: 2,
name: "Swagger SemanticValidation",
suppressionLabels: [],
troubleshootingGuide: defaultTsg,
},
{
precedence: 3,
name: "Swagger ModelValidation",
suppressionLabels: [],
troubleshootingGuide: defaultTsg,
},
{
precedence: 4,
name: "Swagger BreakingChange",
suppressionLabels: [verRevApproval, brChRevApproval],
troubleshootingGuide: brchTsg,
},
{
precedence: 4,
name: "Breaking Change(Cross-Version)",
suppressionLabels: [verRevApproval, brChRevApproval],
troubleshootingGuide: brchTsg,
},
{
precedence: 5,
name: "Swagger LintDiff",
suppressionLabels: [],
troubleshootingGuide: defaultTsg,
},
{
precedence: 5,
name: "Swagger Lint(RPaaS)",
suppressionLabels: [],
troubleshootingGuide: defaultTsg,
},
{
precedence: 6,
name: "SDK azure-sdk-for-net",
suppressionLabels: [],
troubleshootingGuide: checkAndDiagramTsg(3),
},
{
precedence: 6,
name: "SDK azure-sdk-for-net-track2",
suppressionLabels: [],
troubleshootingGuide: checkAndDiagramTsg(3),
},
{
precedence: 6,
name: "SDK azure-sdk-for-go",
suppressionLabels: [],
troubleshootingGuide: checkAndDiagramTsg(3),
},
{
precedence: 6,
name: "SDK azure-sdk-for-java",
suppressionLabels: [],
troubleshootingGuide: checkAndDiagramTsg(3),
},
{
precedence: 6,
name: "SDK azure-sdk-for-js",
suppressionLabels: [],
troubleshootingGuide: checkAndDiagramTsg(3),
},
{
precedence: 6,
name: "SDK azure-sdk-for-python",
suppressionLabels: [],
troubleshootingGuide: checkAndDiagramTsg(3),
},
{
precedence: 6,
name: "SDK azure-sdk-for-python-track2",
suppressionLabels: [],
troubleshootingGuide: checkAndDiagramTsg(3),
},
{
precedence: 10,
name: AUTOMATED_CHECK_NAME,
suppressionLabels: [],
troubleshootingGuide: reqMetCheckTsg,
},
];
// during renderAutomatedMergingRequirementsMetCheck we resolve the result of
// automated merge requirements met by from the result of and(requiredChecks).
// if any are pending, automated merging requirements is pending. This is ripe for complete removal
// in favor of just honoring the `required` checks results directly.
/** @type {string[]} */
const EXCLUDED_CHECK_NAMES = [];
// #endregion
// #region core
/**
* @param {import('@actions/github-script').AsyncFunctionArguments} AsyncFunctionArguments
* @returns {Promise<void>}
*/
export default async function summarizeChecks({ github, context, core }) {
let { owner, repo, issue_number, head_sha } = await extractInputs(github, context, core);
if (!issue_number) {
core.warning(`No issue number found for this event. Exiting summarize-checks.js early.`);
return;
}
const targetBranch = context.payload.pull_request?.base?.ref;
core.info(`PR target branch: ${targetBranch}`);
await summarizeChecksImpl(
github,
context,
core,
owner,
repo,
issue_number,
head_sha,
context.eventName,
targetBranch,
);
}
/**
* @param {import('@actions/github-script').AsyncFunctionArguments['github']} github
* @param {import('@actions/github').context } context
* @param {typeof import("@actions/core")} core
* @param {string} owner
* @param {string} repo
* @param {number} issue_number
* @param {string} head_sha
* @param {string} event_name
* @param {string} targetBranch
* @returns {Promise<void>}
*/
export async function summarizeChecksImpl(
github,
context,
core,
owner,
repo,
issue_number,
head_sha,
event_name,
targetBranch,
) {
core.info(`Handling ${event_name} event for PR #${issue_number} in ${owner}/${repo}.`);
let labelNames = await getExistingLabels(github, owner, repo, issue_number);
/** @type {[CheckRunData[], CheckRunData[], import("./labelling.js").ImpactAssessment | undefined]} */
const [requiredCheckRuns, fyiCheckRuns, impactAssessment] = await getCheckRunTuple(
github,
core,
owner,
repo,
head_sha,
issue_number,
EXCLUDED_CHECK_NAMES,
);
let labelContext = await updateLabels(labelNames, impactAssessment);
core.info(
`Summarize checks label actions against ${owner}/${repo}#${issue_number}: \n` +
`The following labels were present: [${Array.from(labelContext.present).join(", ")}]` +
`Removing labels [${Array.from(labelContext.toRemove).join(", ")}] then \n` +
`Adding labels [${Array.from(labelContext.toAdd).join(", ")}]`,
);
// for (const label of labelContext.toRemove) {
// core.info(`Removing label: ${label} from ${owner}/${repo}#${issue_number}.`);
// await github.rest.issues.removeLabel({
// owner: owner,
// repo: repo,
// issue_number: issue_number,
// name: label,
// });
// }
// if (labelContext.toAdd.size > 0) {
// core.info(
// `Adding labels: ${Array.from(labelContext.toAdd).join(", ")} to ${owner}/${repo}#${issue_number}.`,
// );
// await github.rest.issues.addLabels({
// owner: owner,
// repo: repo,
// issue_number: issue_number,
// labels: Array.from(labelContext.toAdd),
// });
// }
// adjust labelNames based on labelsToAdd/labelsToRemove
labelNames = labelNames.filter((name) => !labelContext.toRemove.has(name));
for (const label of labelContext.toAdd) {
if (!labelNames.includes(label)) {
labelNames.push(label);
}
}
const [commentBody, automatedChecksMet] = await createNextStepsComment(
core,
repo,
labelNames,
targetBranch,
requiredCheckRuns,
fyiCheckRuns,
);
core.info(
`Updating comment '${NEXT_STEPS_COMMENT_ID}' on ${owner}/${repo}#${issue_number} with body: ${commentBody}`,
);
// this will remain commented until we're comfortable with the change.
// await commentOrUpdate(
// { github, context, core },
// owner,
// repo,
// issue_number,
// commentName,
// commentBody
// )
core.info(
`Summarize checks has identified that status of "Automated merging requirements met" check should be updated to: ${automatedChecksMet}.`,
);
}
/**
* @param {import('@actions/github-script').AsyncFunctionArguments['github']} github
* @param {string} owner
* @param {string} repo
* @param {number} issue_number
* @param {*} owner
* @param {*} repo
* @param {*} issue_number
* @return {Promise<string[]>}
*/
export async function getExistingLabels(github, owner, repo, issue_number) {
const labels = await github.paginate(github.rest.issues.listLabelsOnIssue, {
owner,
repo,
issue_number: issue_number,
per_page: PER_PAGE_MAX,
});
/** @type {string[]} */
return labels.map((/** @type {{ name: string; }} */ label) => label.name);
}
// #endregion
// #region label update
/**
* @param {Set<string>} labelsToAdd
* @param {Set<string>} labelsToRemove
*/
function warnIfLabelSetsIntersect(labelsToAdd, labelsToRemove) {
const intersection = Array.from(labelsToAdd).filter((label) => labelsToRemove.has(label));
if (intersection.length > 0) {
console.warn(
"ASSERTION VIOLATION! The intersection of labelsToRemove and labelsToAdd is non-empty! " +
`labelsToAdd: [${[...labelsToAdd].join(", ")}]. ` +
`labelsToRemove: [${[...labelsToRemove].join(", ")}]. ` +
`intersection: [${intersection.join(", ")}].`,
);
}
}
// * @param {string} eventName
// * @param {string | undefined } changedLabel
/**
* @param {string[]} existingLabels
* @param {import("./labelling.js").ImpactAssessment | undefined} impactAssessment
* @returns {import("./labelling.js").LabelContext}
*/
export function updateLabels(existingLabels, impactAssessment) {
// logic for this function originally present in:
// - private/openapi-kebab/src/bots/pipeline/pipelineBotOnPRLabelEvent.ts
// - public/rest-api-specs-scripts/src/prSummary.ts
// it has since been simplified and moved here to handle all label addition and subtraction given a PR context
/** @type {import("./labelling.js").LabelContext} */
const labelContext = {
present: new Set(existingLabels),
toAdd: new Set(),
toRemove: new Set(),
};
if (impactAssessment) {
console.log(`Downloaded impact assessment: ${JSON.stringify(impactAssessment)}`);
// will further update the label context if necessary
processImpactAssessment(labelContext, impactAssessment);
}
warnIfLabelSetsIntersect(labelContext.toAdd, labelContext.toRemove);
return labelContext;
}
// #endregion
// #region checks
/**
* A GraphQL query to GitHub API that returns all check runs for given commit, with "isRequired" field for given PR.
*
* If you want to see example response, copy the query body into this:
* https://docs.github.com/en/graphql/overview/explorer
* Example inputs:
* resourceUrl: "https://github.com/test-repo-billy/azure-rest-api-specs/commit/c2789c5bde1b3f4fa34f76a8eeaaed479df23c4d"
* prNumber: 2996
*
* Reference:
* https://docs.github.com/en/graphql/reference/queries#resource
* https://docs.github.com/en/graphql/guides/using-global-node-ids#3-do-a-direct-node-lookup-in-graphql
* https://docs.github.com/en/graphql/reference/objects#checkrun
* Rate limit:
* https://docs.github.com/en/graphql/overview/resource-limitations#rate-limit
* https://docs.github.com/en/graphql/reference/objects#ratelimit
*
* Note: here, for "checkRuns(first: ..)", maybe we should add a filter that filters to LATEST, per:
* https://docs.github.com/en/graphql/reference/input-objects#checkrunfilter
* https://docs.github.com/en/graphql/reference/enums#checkruntype
**/
/**
* Fetch all check suites for a commit with pagination
* @param {import('@actions/github-script').AsyncFunctionArguments['github']} github
* @param {typeof import("@actions/core")} core
* @param {string} owner
* @param {string} repo
* @param {string} sha
* @param {number} prNumber
* @returns {Promise<any>} Complete GraphQL response with all check suites
*/
async function getAllCheckSuites(github, core, owner, repo, sha, prNumber) {
const resourceUrl = `https://github.com/${owner}/${repo}/commit/${sha}`;
let allCheckSuites = [];
let hasNextPage = true;
let cursor = null;
let lastResponse = null;
while (hasNextPage) {
/** @type {string} */
const query = `
{
resource(url: "${resourceUrl}") {
... on Commit {
checkSuites(first: 100${cursor ? `, after: "${cursor}"` : ""}) {
pageInfo {
hasNextPage
endCursor
}
nodes {
workflowRun {
id
databaseId
workflow {
name
}
}
checkRuns(first: 100) {
nodes {
name
status
conclusion
isRequired(pullRequestNumber: ${prNumber})
}
}
}
}
}
}
rateLimit {
limit
cost
used
remaining
resetAt
}
}
`;
/** @type {any} */
const response = await github.graphql(query);
lastResponse = response;
core.info(`GraphQL Rate Limit Information: ${JSON.stringify(response.rateLimit)}`);
if (response.resource?.checkSuites?.nodes) {
allCheckSuites.push(...response.resource.checkSuites.nodes);
hasNextPage = response.resource.checkSuites.pageInfo.hasNextPage;
cursor = response.resource.checkSuites.pageInfo.endCursor;
} else {
hasNextPage = false;
}
}
// Return a response object that matches the original structure
return {
resource: {
checkSuites: {
nodes: allCheckSuites,
},
},
rateLimit: lastResponse?.rateLimit,
};
}
/**
* @param {import('@actions/github-script').AsyncFunctionArguments['github']} github
* @param {typeof import("@actions/core")} core
* @param {string} owner - The repository owner.
* @param {string} repo - The repository name.
* @param {string} head_sha - The commit SHA to check.
* @param {number} prNumber - The pull request number.
* @param {string[]} excludedCheckNames
* @returns {Promise<[CheckRunData[], CheckRunData[], import("./labelling.js").ImpactAssessment | undefined]>}
*/
export async function getCheckRunTuple(
github,
core,
owner,
repo,
head_sha,
prNumber,
excludedCheckNames,
) {
// This function was originally a version of getRequiredAndFyiAndAutomatedMergingRequirementsMetCheckRuns
// but has been simplified for clarity and purpose.
/** @type {CheckRunData[]} */
let reqCheckRuns = [];
/** @type {CheckRunData[]} */
let fyiCheckRuns = [];
/** @type {number | undefined} */
let impactAssessmentWorkflowRun = undefined;
/** @type { import("./labelling.js").ImpactAssessment | undefined } */
let impactAssessment = undefined;
const response = await getAllCheckSuites(github, core, owner, repo, head_sha, prNumber);
core.info(`GraphQL Rate Limit Information: ${JSON.stringify(response.rateLimit)}`);
[reqCheckRuns, fyiCheckRuns, impactAssessmentWorkflowRun] =
extractRunsFromGraphQLResponse(response);
if (impactAssessmentWorkflowRun) {
core.info(
`Impact Assessment Workflow Run ID is present: ${impactAssessmentWorkflowRun}. Downloading job summary artifact`,
);
impactAssessment = await getImpactAssessment(
github,
core,
owner,
repo,
impactAssessmentWorkflowRun,
);
}
core.info(
`RequiredCheckRuns: ${JSON.stringify(reqCheckRuns)}, ` +
`FyiCheckRuns: ${JSON.stringify(fyiCheckRuns)}, ` +
`ImpactAssessment: ${JSON.stringify(impactAssessment)}`,
);
const filteredReqCheckRuns = reqCheckRuns.filter(
/**
* @param {CheckRunData} checkRun
*/
(checkRun) => !excludedCheckNames.includes(checkRun.name),
);
const filteredFyiCheckRuns = fyiCheckRuns.filter(
/**
* @param {CheckRunData} checkRun
*/
(checkRun) => !excludedCheckNames.includes(checkRun.name),
);
return [filteredReqCheckRuns, filteredFyiCheckRuns, impactAssessment];
}
/**
* @param {CheckRunData} checkRun
* @returns {boolean | undefined}
*/
export function checkRunIsSuccessful(checkRun) {
// If the check is still queued or in progress, return undefined
const status = checkRun.status.toLowerCase();
if (status === "queued" || status === "in_progress") {
return undefined;
}
// At this point we expect a completed run, so conclusion should be defined
const conclusion = checkRun.conclusion?.toLowerCase();
if (conclusion == null) {
return undefined;
}
// Return true for success or neutral, false for any other conclusion
return conclusion === "success" || conclusion === "neutral";
}
/**
* @param {any} response - GraphQL response data
* @returns {[CheckRunData[], CheckRunData[], number | undefined]}
*/
function extractRunsFromGraphQLResponse(response) {
/** @type {CheckRunData[]} */
const reqCheckRuns = [];
/** @type {CheckRunData[]} */
const fyiCheckRuns = [];
/** @type {number | undefined} */
let impactAssessmentWorkflowRun = undefined;
// Define the automated merging requirements check name
if (response.resource?.checkSuites?.nodes) {
response.resource.checkSuites.nodes.forEach(
/** @param {{ workflowRun?: WorkflowRunInfo, checkRuns?: { nodes?: any[] } }} checkSuiteNode */
(checkSuiteNode) => {
if (checkSuiteNode.checkRuns?.nodes) {
checkSuiteNode.checkRuns.nodes.forEach((checkRunNode) => {
// We have some specific guidance for some of the required checks.
const checkInfo =
CHECK_METADATA.find((metadata) => metadata.name === checkRunNode.name) ||
/** @type {CheckMetadata} */ ({
precedence: 1000,
name: checkRunNode.name,
suppressionLabels: [],
troubleshootingGuide: defaultTsg,
});
if (checkRunNode.isRequired) {
reqCheckRuns.push({
name: checkRunNode.name,
status: checkRunNode.status,
conclusion: checkRunNode.conclusion,
checkInfo: checkInfo,
});
}
// Note the "else" here. It means that:
// A GH check will be bucketed into "failing FYI check run" if:
// - It is failing
// - AND it is is NOT marked as 'required' in GitHub branch policy
// - AND it is marked as 'FYI' in this file's FYI_CHECK_NAMES array
else if (FYI_CHECK_NAMES.includes(checkRunNode.name)) {
fyiCheckRuns.push({
name: checkRunNode.name,
status: checkRunNode.status,
conclusion: checkRunNode.conclusion,
checkInfo: checkInfo,
});
}
});
}
},
);
}
// extract the ImpactAssessment check run if it is completed and successful
if (response.resource?.checkSuites?.nodes) {
response.resource.checkSuites.nodes.forEach(
/** @param {{ workflowRun?: WorkflowRunInfo, checkRuns?: { nodes?: any[] } }} checkSuiteNode */
(checkSuiteNode) => {
if (checkSuiteNode.checkRuns?.nodes) {
checkSuiteNode.checkRuns.nodes.forEach((checkRunNode) => {
if (
checkRunNode.name === "[TEST-IGNORE] Summarize PR Impact" &&
checkRunNode.status?.toLowerCase() === "completed" &&
checkRunNode.conclusion?.toLowerCase() === "success"
) {
// Assign numeric databaseId, not the string node ID
impactAssessmentWorkflowRun = checkSuiteNode.workflowRun?.databaseId;
}
});
}
},
);
}
return [reqCheckRuns, fyiCheckRuns, impactAssessmentWorkflowRun];
}
// #endregion
// #region next steps
/**
*
* @param {typeof import("@actions/core")} core
* @param {string} repo
* @param {string[]} labels
* @param {string} targetBranch
* @param {CheckRunData[]} requiredRuns
* @param {CheckRunData[]} fyiRuns
* @returns {Promise<[string, string]>}
*/
export async function createNextStepsComment(
core,
repo,
labels,
targetBranch,
requiredRuns,
fyiRuns,
) {
// select just the metadata that we need about the runs.
const requiredCheckInfos = requiredRuns
.filter((run) => checkRunIsSuccessful(run) === false)
.map((run) => run.checkInfo);
// determine if required runs have any successful runs.
const requiredCheckInfosPresent = requiredRuns.some((run) => {
const status = run.status.toLowerCase();
return status !== "queued" && status !== "in_progress";
});
const fyiCheckInfos = fyiRuns
.filter((run) => checkRunIsSuccessful(run) === false)
.map((run) => run.checkInfo);
const [commentBody, automatedChecksMet] = await buildNextStepsToMergeCommentBody(
core,
labels,
`${repo}/${targetBranch}`,
requiredCheckInfosPresent,
requiredCheckInfos,
fyiCheckInfos,
);
return [commentBody, automatedChecksMet];
}
/**
* @param {import("@actions/core")} core
* @param {string[]} labels
* @param {string} targetBranch // this is in the format of "repo/branch"
* @param {boolean} requiredCheckInfosPresent
* @param {CheckMetadata[]} failingReqChecksInfo
* @param {CheckMetadata[]} failingFyiChecksInfo
* @returns {Promise<[string, string]>}
*/
async function buildNextStepsToMergeCommentBody(
core,
labels,
targetBranch,
requiredCheckInfosPresent,
failingReqChecksInfo,
failingFyiChecksInfo,
) {
// Build the comment header
const commentTitle = `<h2>Next Steps to Merge</h2>`;
const violatedReqLabelsRules = await getViolatedRequiredLabelsRules(core, labels, targetBranch);
// this is the first place of adjusted logic. I am treating `requirementsMet` as `no failed required checks`.
// I do this because the `automatedMergingRequirementsMetCheckRun` WILL NOT BE PRESENT in the new world.
// The new world we will simply pull all the required checks and if any are failing then we are blocked. If there are
// no failed checks we can't yet say that everything is met, because a check MIGHT run in the future. To prevent
// this "no checks run" accidentally evaluating as success, we need to ensure that we have at least one failing check
// in the required checks to consider the requirements met
const anyBlockerPresent = failingReqChecksInfo.length > 0 || violatedReqLabelsRules.length > 0;
const anyFyiPresent = failingFyiChecksInfo.length > 0;
const requirementsMet = !anyBlockerPresent && requiredCheckInfosPresent;
// Compose the body based on the current state
const [commentBody, automatedChecksMet] = getCommentBody(
requirementsMet,
anyBlockerPresent,
anyFyiPresent,
failingReqChecksInfo,
failingFyiChecksInfo,
violatedReqLabelsRules,
);
return [commentTitle + commentBody, automatedChecksMet];
}
/**
* Gets the proper body content based on requirements status
* @param {boolean} requirementsMet - Whether all requirements are met
* @param {boolean} anyBlockerPresent - Whether any blockers are present
* @param {boolean} anyFyiPresent - Whether any FYI issues are present
* @param {CheckMetadata[]} failingReqChecksInfo - Failing required checks info
* @param {CheckMetadata[]} failingFyiChecksInfo - Failing FYI checks info
* @param {RequiredLabelRule[]} violatedRequiredLabelsRules - Violated required label rules
* @returns {[string, string]} The body content HTML and the status that automated checks met should be set to.
*/
function getCommentBody(
requirementsMet,
anyBlockerPresent,
anyFyiPresent,
failingReqChecksInfo,
failingFyiChecksInfo,
violatedRequiredLabelsRules,
) {
let bodyProper = "";
let automatedChecksMet = "pending";
if (anyBlockerPresent || anyFyiPresent) {
if (anyBlockerPresent) {
bodyProper += getBlockerPresentBody(failingReqChecksInfo, violatedRequiredLabelsRules);
automatedChecksMet = "blocked";
}
if (anyBlockerPresent && anyFyiPresent) {
bodyProper += "<br/>";
}
if (anyFyiPresent) {
bodyProper += getFyiPresentBody(failingFyiChecksInfo);
if (!anyBlockerPresent) {
bodyProper += `If you still want to proceed merging this PR without addressing the above failures, ${diagramTsg(4, false)}.`;
}
}
} else if (requirementsMet) {
automatedChecksMet = "success";
bodyProper =
`✅ All automated merging requirements have been met! ` +
`To get your PR merged, see <a href="https://aka.ms/azsdk/specreview/merge">aka.ms/azsdk/specreview/merge</a>.`;
} else {
bodyProper =
"⌛ Please wait. Next steps to merge this PR are being evaluated by automation. ⌛";
}
return [bodyProper, automatedChecksMet];
}
/**
* Gets the body content when blockers are present
* @param {CheckMetadata[]} failingRequiredChecks - Failing required checks
* @param {RequiredLabelRule[]} violatedRequiredLabelsRules - Violated required label rules
* @returns {string} The blocker present body HTML
*/
function getBlockerPresentBody(failingRequiredChecks, violatedRequiredLabelsRules) {
const failingRequiredChecksNextStepsText = buildFailingChecksNextStepsText(
failingRequiredChecks,
"required",
);
const violatedReqLabelsRulesNextStepsText = buildViolatedLabelRulesNextStepsText(
violatedRequiredLabelsRules,
);
return (
"Next steps that must be taken to merge this PR: <br/>" +
"<ul>" +
violatedReqLabelsRulesNextStepsText +
failingRequiredChecksNextStepsText +
"</ul>"
);
}
/**
* Gets the body content when FYI issues are present
* @param {CheckMetadata[]} failingFyiChecksInfo - Failing FYI checks info
* @returns {string} The FYI present body HTML
*/
function getFyiPresentBody(failingFyiChecksInfo) {
return (
"Important checks have failed. As of today they are not blocking this PR, but in near future they may.<br/>" +
"Addressing the following failures is highly recommended:<br/>" +
"<ul>" +
buildFailingChecksNextStepsText(failingFyiChecksInfo, "FYI") +
"</ul>"
);
}
/**
* Builds next steps text for failing checks
* @param {CheckMetadata[]} failingChecks - Array of failing checks
* @param {"required" | "FYI"} checkKind - Kind of check (required or FYI)
* @returns {string} The failing checks next steps HTML
*/
function buildFailingChecksNextStepsText(failingChecks, checkKind) {
let failingChecksNextStepsText = "";
if (failingChecks.length > 0) {
const minPrecedence = Math.min(...failingChecks.map((check) => check.precedence));
const checksToDisplay = failingChecks.filter((check) => check.precedence === minPrecedence);
// assert: checksToDisplay.length > 0
failingChecksNextStepsText = checksToDisplay
.map((check) =>
checkKind === "required"
? `<li>❌ The required check named <code>${check.name}</code> has failed. ${check.troubleshootingGuide}</li>`
: `<li>⚠️ The check named <code>${check.name}</code> has failed. ${check.troubleshootingGuide}</li>`,
)
.join("");
}
return failingChecksNextStepsText;
}
/**
* Builds next steps text for violated required label rules
* @param {RequiredLabelRule[]} violatedRequiredLabelsRules - Array of violated required label rules
* @returns {string} The violated label rules next steps HTML
*/
function buildViolatedLabelRulesNextStepsText(violatedRequiredLabelsRules) {
let violatedReqLabelsNextStepsText = "";
if (violatedRequiredLabelsRules.length > 0) {
const minPrecedence = Math.min(...violatedRequiredLabelsRules.map((rule) => rule.precedence));
const rulesToDisplay = violatedRequiredLabelsRules.filter(
(rule) => rule.precedence == minPrecedence,
);
// assert: rulesToDisplay.length > 0
violatedReqLabelsNextStepsText = rulesToDisplay
.map((rule) => `<li>❌ ${rule.troubleshootingGuide}</li>`)
.join("");
}
return violatedReqLabelsNextStepsText;
}
// #endregion
// #region artifact downloading
/**
* Downloads the job-summary artifact for a given workflow run.
* @param {import('@actions/github-script').AsyncFunctionArguments['github']} github
* @param {typeof import("@actions/core")} core
* @param {string} owner
* @param {string} repo
* @param {number} runId - The workflow run databaseId
* @returns {Promise<import("./labelling.js").ImpactAssessment | undefined>} The parsed job summary data
*/
export async function getImpactAssessment(github, core, owner, repo, runId) {
try {
// List artifacts for provided workflow run
const artifacts = await github.rest.actions.listWorkflowRunArtifacts({
owner,
repo,
run_id: runId,
});
// Find the job-summary artifact