-
Notifications
You must be signed in to change notification settings - Fork 431
/
ReleaseNotesFunctions.ts
2367 lines (2159 loc) · 128 KB
/
ReleaseNotesFunctions.ts
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
export interface SimpleArtifact {
artifactAlias: string;
buildDefinitionId: string;
buildNumber: string;
buildId: string;
artifactType: string;
isPrimary: boolean;
sourceId: string;
}
interface WorkItemInfo {
id: number;
url: string;
}
interface EnrichedGitPullRequest extends GitPullRequest {
associatedWorkitems: WorkItemInfo[];
associatedCommits: GitCommit[];
}
interface EnrichedTestRun extends TestRun {
TestResults: TestCaseResult[];
}
export class UnifiedArtifactDetails {
build: Build;
commits: Change[];
workitems: WorkItem[];
relatedworkitems: WorkItem[];
tests: TestCaseResult[];
manualtests: EnrichedTestRun[];
constructor ( build: Build, commits: Change[], workitems: WorkItem[], tests: TestCaseResult[], manualtests: EnrichedTestRun[], relatedworkitems: WorkItem[]) {
this.build = build;
if (commits) {
this.commits = commits;
} else {
this.commits = [];
}
if (workitems) {
this.workitems = workitems;
} else {
this.workitems = [];
}
if (relatedworkitems) {
this.relatedworkitems = relatedworkitems;
} else {
this.workitems = [];
}
if (tests) {
this.tests = tests;
} else {
this.tests = [];
}
if (manualtests) {
this.manualtests = manualtests;
} else {
this.manualtests = [];
}
}
}
import { ClientApiBase } from "azure-devops-node-api/ClientApiBases";
import * as vsom from "azure-devops-node-api/VsoClient";
import * as restm from "typed-rest-client/RestClient";
import path = require("path");
import { PersonalAccessTokenCredentialHandler, BasicCredentialHandler } from "typed-rest-client/Handlers";
import tl = require("azure-pipelines-task-lib/task");
import { ReleaseEnvironment, Artifact, Deployment, DeploymentStatus, Release } from "azure-devops-node-api/interfaces/ReleaseInterfaces";
import { IAgentSpecificApi, AgentSpecificApi } from "./agentSpecific";
import { IReleaseApi } from "azure-devops-node-api/ReleaseApi";
import { IRequestHandler } from "azure-devops-node-api/interfaces/common/VsoBaseInterfaces";
import * as webApi from "azure-devops-node-api/WebApi";
import fs = require("fs");
import { Build, Change, Timeline, TimelineRecord, BuildArtifact } from "azure-devops-node-api/interfaces/BuildInterfaces";
import { IGitApi, GitApi } from "azure-devops-node-api/GitApi";
import { ResourceRef } from "azure-devops-node-api/interfaces/common/VSSInterfaces";
import { GitCommit, GitPullRequest, GitPullRequestQueryType, GitPullRequestSearchCriteria, PullRequestStatus } from "azure-devops-node-api/interfaces/GitInterfaces";
import { WebApi } from "azure-devops-node-api";
import { TestApi } from "azure-devops-node-api/TestApi";
import { timeout, async } from "q";
import { ResultDetails, TestCaseResult, TestResolutionState, TestRun } from "azure-devops-node-api/interfaces/TestInterfaces";
import { IWorkItemTrackingApi } from "azure-devops-node-api/WorkItemTrackingApi";
import { WorkItemExpand, WorkItem, ArtifactUriQuery, Wiql, QueryExpand } from "azure-devops-node-api/interfaces/WorkItemTrackingInterfaces";
import { ITfvcApi } from "azure-devops-node-api/TfvcApi";
import * as issue349 from "./Issue349Workaround";
import { ITestApi } from "azure-devops-node-api/TestApi";
import { IBuildApi, BuildApi } from "azure-devops-node-api/BuildApi";
import * as vstsInterfaces from "azure-devops-node-api/interfaces/common/VsoBaseInterfaces";
import { Console, time } from "console";
import { InstalledExtensionQuery } from "azure-devops-node-api/interfaces/ExtensionManagementInterfaces";
import { SSL_OP_SSLEAY_080_CLIENT_DH_BUG } from "constants";
import { stringify } from "querystring";
import { Exception } from "handlebars";
import { IdentityDisplayFormat } from "azure-devops-node-api/interfaces/WorkInterfaces";
process.on("uncaughtException", (error) => {
console.error("Uncaught Exception:", error);
});
let agentApi = new AgentSpecificApi();
export function getDeploymentCount(environments: ReleaseEnvironment[], environmentName: string): number {
agentApi.logInfo(`Getting deployment count for stage`);
var attemptCount = 0;
for (let environment of environments) {
if (environment.name.toLowerCase() === environmentName) {
agentApi.logInfo(`Found the stage [${environmentName}]`);
var currentDeployment = environment.preDeployApprovals[environment.preDeployApprovals.length - 1];
if (currentDeployment) {
attemptCount = currentDeployment.attempt;
}
}
}
if (attemptCount === 0) {
agentApi.logInfo(`Cannot find any deployment to [${environmentName}]`);
} else {
agentApi.logInfo(`Identified [${environmentName}] as having deployment count of [${attemptCount}]`);
}
return attemptCount;
}
export function getReleaseDefinitionId(environments: ReleaseEnvironment[], environmentName: string): number {
agentApi.logInfo(`Getting the Environment Id`);
var environmentId: number = 0;
for (let environment of environments) {
if (environment.name.toLowerCase() === environmentName) {
environmentId = environment.definitionEnvironmentId;
}
}
if (environmentId === 0) {
throw `Failed to locate environment with name ${environmentName}`;
}
agentApi.logInfo(`Identified [${environmentName}] as having id [${environmentId}]`);
return environmentId;
}
export function getSimpleArtifactArray(artifacts: Artifact[]): SimpleArtifact[] {
var result: SimpleArtifact[] = [];
for (let artifact of artifacts) {
result.push(
{
"artifactAlias": artifact.alias,
"buildDefinitionId": artifact.definitionReference.definition.id,
"buildNumber": artifact.definitionReference.version.name,
"buildId": artifact.definitionReference.version.id,
"artifactType": artifact.type,
"isPrimary": artifact.isPrimary,
"sourceId": artifact.sourceId.split(":")[0]
}
);
}
return result;
}
export async function restoreAzurePipelineArtifactsBuildInfo(artifactsInRelease: SimpleArtifact[], webApi: WebApi): Promise<number> {
let existAzurePipelineArtifacts = false;
for (const artifactInRelease of artifactsInRelease) {
if (artifactInRelease.artifactType === "PackageManagement") {
agentApi.logInfo(`The artifact [${artifactInRelease.artifactAlias}] is an Azure Artifacts, expanding build details`);
existAzurePipelineArtifacts = true;
// FIXME #937: workaround for missing PackagingApi library. Should replace with `const packagingApi = await organisation.getPackagingApi();` when available
interface PackagingPackage { id: string; string; url: string; versions: {id: string; normalizedVersion: string}[]; }
interface PackagingVersionProvenance { TeamProjectId: string; provenance: {data: {"System.DefinitionId": string; "System.TeamProjectId": string; "Build.BuildId": string; "Build.BuildNumber": string}}; }
interface IPackagingApi {
getPackage(project: string, feedId: string, packageId: string, includeAllVersions?: boolean): Promise<PackagingPackage>;
getPackageVersionProvenance(project: string, feedId: string, packageId: string, packageVersionId: string): Promise<PackagingVersionProvenance>;
}
const PackagingApi = class extends ClientApiBase implements IPackagingApi {
constructor(...args) { super(args[0], args[1], "node-Packaging-api", args[2]); }
public static readonly RESOURCE_AREA_ID = "7ab4e64e-c4d8-4f50-ae73-5ef2e21642a5";
public async getPackage(project: string, feedId: string, packageId: string, includeAllVersions?: boolean): Promise<PackagingPackage> {
return new Promise<PackagingPackage>(async (resolve, reject) => {
let routeValues: any = {project: project, feedId: feedId, packageId: packageId};
let queryValues: any = {includeAllVersions: includeAllVersions};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData("6.1-preview.1", "Packaging", "7a20d846-c929-4acc-9ea2-0d5a7df1b197", routeValues, queryValues);
let res = await this.rest.get<PackagingPackage[]>(verData.requestUrl!, this.createRequestOptions("application/json", verData.apiVersion));
resolve(this.formatResponse(res.result, null, true));
} catch (err) {
reject(err);
}
});
}
public async getPackageVersionProvenance(project: string, feedId: string, packageId: string, packageVersionId: string): Promise<PackagingVersionProvenance> {
return new Promise<PackagingVersionProvenance>(async (resolve, reject) => {
let routeValues: any = {
project: project,
feedId: feedId,
packageId: packageId,
packageVersionId: packageVersionId
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData("6.1-preview.1", "Packaging", "0aaeabd4-85cd-4686-8a77-8d31c15690b8", routeValues);
let res = await this.rest.get<PackagingPackage[]>(verData.requestUrl!, this.createRequestOptions("application/json", verData.apiVersion));
resolve(this.formatResponse(res.result, null, true));
} catch (err) {
reject(err);
}
});
}
};
// const packagingApi = await organisation.getPackagingApi();
const packagingApi = await(async (serverUrl?: string, handlers?: IRequestHandler[]): Promise<IPackagingApi> => {
const this_ = webApi as any;
serverUrl = await this_._getResourceAreaUrl(serverUrl || this_.serverUrl, PackagingApi.RESOURCE_AREA_ID);
handlers = handlers || [this_.authHandler];
return new PackagingApi(serverUrl, handlers, this_.options);
})();
// END FIXME #937
const guids = artifactInRelease.sourceId.match(/([0-9a-f-]{36})\/([0-9a-f-]{36})/u);
if (guids !== null) {
const [projectId, feedId] = [guids[1], guids[2]];
const [packageId, packageVersion] = [artifactInRelease.buildDefinitionId, artifactInRelease.buildNumber];
const artifactPackageInfo = await packagingApi.getPackage(projectId, feedId, packageId, true);
const packageVersionId = (artifactPackageInfo.versions.find((version) => version.normalizedVersion === packageVersion) || {id: ""}).id;
const artifactBuildInfo = (await packagingApi.getPackageVersionProvenance(projectId, feedId, packageId, packageVersionId));
Object.assign(artifactInRelease, {
artifactType: "Build",
buildId: artifactBuildInfo.provenance.data["Build.BuildId"],
buildDefinitionId: artifactBuildInfo.provenance.data["System.DefinitionId"],
buildNumber: artifactBuildInfo.provenance.data["Build.BuildNumber"],
sourceId: artifactBuildInfo.TeamProjectId || artifactBuildInfo.provenance.data["System.TeamProjectId"]
} as SimpleArtifact);
}
}
}
return existAzurePipelineArtifacts ? parseInt(artifactsInRelease[0].buildId) : NaN;
}
export async function getPullRequests(
gitApi: GitApi,
projectName: string
): Promise<GitPullRequest[]> {
return new Promise<GitPullRequest[]>(async (resolve, reject) => {
let prList: GitPullRequest[] = [];
try {
var filter: GitPullRequestSearchCriteria = {
creatorId: "",
includeLinks: true,
repositoryId: "",
reviewerId: "",
sourceRefName: "",
sourceRepositoryId: "",
status: PullRequestStatus.Completed,
targetRefName: ""
};
var batchSize: number = 1000; // 1000 seems to be the API max
var skip: number = 0;
do {
agentApi.logDebug(`Get batch of PRs [${skip}] - [${skip + batchSize}]`);
var prListBatch = await (gitApi.getPullRequestsByProject( projectName, filter, 0 , skip, batchSize));
agentApi.logDebug(`Adding batch of ${prListBatch.length} PRs`);
prList.push(...prListBatch);
skip += batchSize;
} while (batchSize === prListBatch.length);
resolve(prList);
} catch (err) {
reject(err);
}
});
}
export async function getMostRecentSuccessfulDeployment(
releaseApi: IReleaseApi,
teamProject: string,
releaseDefinitionId: number,
environmentId: number,
overrideBuildReleaseId: string,
considerPartiallySuccessfulReleases: boolean): Promise<Deployment> {
return new Promise<Deployment>(async (resolve, reject) => {
let mostRecentDeployment: Deployment = null;
try {
// Gets the latest successful deployments - the api returns the deployments in the correct order
agentApi.logInfo (`Finding successful deployments`);
var successfulDeployments = await releaseApi.getDeployments(teamProject, releaseDefinitionId, environmentId, null, null, null, DeploymentStatus.Succeeded, null, true, null, null, null, null).catch((reason) => {
reject(reason);
return;
});
if (considerPartiallySuccessfulReleases === true) {
agentApi.logInfo (`Finding partially successful deployments`);
var partialSuccessfulDeployments = await releaseApi.getDeployments(teamProject, releaseDefinitionId, environmentId, null, null, null, DeploymentStatus.PartiallySucceeded, null, true, null, null, null, null).catch((reason) => {
reject(reason);
return;
});
// merge the arrays
if (successfulDeployments && successfulDeployments.length > 0) {
if (partialSuccessfulDeployments && partialSuccessfulDeployments.length > 0) {
agentApi.logInfo (`Merging and sorting successful and partially successful deployments`);
successfulDeployments.push(...partialSuccessfulDeployments);
successfulDeployments.sort((a, b) => { if (a && b) { return b.id - a.id; } return 0; });
} else {
agentApi.logInfo (`No partially successful deployments to consider only using successful deployments`);
}
} else {
agentApi.logInfo (`No successful deployments using partially successful deployments`);
successfulDeployments = partialSuccessfulDeployments;
}
}
if (successfulDeployments && successfulDeployments.length > 0) {
agentApi.logInfo (`Found ${successfulDeployments.length} releases to consider`);
successfulDeployments.forEach(deployment => {
agentApi.logDebug (`Found DeploymentId ${deployment.id} with ReleaseID ${deployment.release.id} with the Deployment Status ${deployment.deploymentStatus}`);
});
if (overrideBuildReleaseId && !isNaN(parseInt(overrideBuildReleaseId))) {
agentApi.logInfo (`Trying to find successful deployment with the override release ID of '${overrideBuildReleaseId}'`);
mostRecentDeployment = successfulDeployments.find (element => element.release.id === parseInt(overrideBuildReleaseId));
if (mostRecentDeployment) {
agentApi.logInfo (`Found matching override release ${mostRecentDeployment.release.name}`);
} else {
agentApi.logError (`Cannot find matching release`);
reject(-1);
return;
}
} else {
mostRecentDeployment = successfulDeployments[0];
agentApi.logInfo (`Finding the last successful release ${mostRecentDeployment.release.name}`);
}
} else {
// There have been no recent successful deployments
}
resolve(mostRecentDeployment);
} catch (err) {
reject(err);
}
});
}
export async function expandTruncatedCommitMessages(restClient: WebApi, globalCommits: Change[], gitHubPat: string, bitbucketUser: string, bitbucketSecret: string): Promise<Change[]> {
return new Promise<Change[]>(async (resolve, reject) => {
var expanded: number = 0;
agentApi.logInfo(`Expanding the truncated commit messages...`);
for (var change of globalCommits) {
if (change.messageTruncated) {
try {
agentApi.logDebug(`Expanding commit [${change.id}]`);
let res: restm.IRestResponse<GitCommit>;
if (change.location.startsWith("https://api.github.com/")) {
agentApi.logDebug(`Need to expand details from GitHub`);
// we build PAT auth object even if we have no token
// this will still allow access to public repos
// if we have a token it will allow access to private ones
let auth = new PersonalAccessTokenCredentialHandler(gitHubPat);
let rc = new restm.RestClient("rest-client", "", [auth], {});
let gitHubRes: any = await rc.get(change.location); // we have to use type any as there is a type mismatch
if (gitHubRes.statusCode === 200) {
change.message = gitHubRes.result.commit.message;
change.messageTruncated = false;
expanded++;
} else {
agentApi.logWarn(`Cannot access API ${gitHubRes.statusCode} accessing ${change.location}`);
agentApi.logWarn(`The most common reason for this failure is that the GitHub Repo is private and a Personal Access Token giving read access needs to be passed as a parameter to this task`);
}
} else if (change.location.startsWith("https://api.bitbucket.org/")) {
agentApi.logDebug(`Need to expand details from BitBucket`);
// we build PAT auth object even if we have no token
// this will still allow access to public repos
// if we have a token it will allow access to private ones
let rc = new restm.RestClient("rest-client");
if (bitbucketUser && bitbucketUser.length > 0 && bitbucketSecret && bitbucketSecret.length > 0 ) {
let auth = new BasicCredentialHandler(bitbucketUser, bitbucketSecret);
rc = new restm.RestClient("rest-client", "", [auth], {});
} else {
agentApi.logInfo(`No Bitbucket user and app secret passed so cannot access private Bitbucket repos`);
}
let bitbucketRes: any = await rc.get(change.location); // we have to use type any as there is a type mismatch
if (bitbucketRes.statusCode === 200) {
change.message = bitbucketRes.result.message;
change.messageTruncated = false;
expanded++;
} else {
agentApi.logWarn(`Cannot access API ${bitbucketRes.statusCode} accessing ${change.location}`);
agentApi.logWarn(`The most common reason for this failure is that the Bitbucket Repo is private and a Personal Access Token giving read access needs to be passed as a parameter to this task`);
}
} else {
agentApi.logDebug(`Need to expand details from Azure DevOps`);
// the REST client is already authorised with the agent token
let vstsRes = await restClient.rest.get<GitCommit>(change.location);
if (vstsRes.statusCode === 200) {
change.message = vstsRes.result.comment;
change.messageTruncated = false;
expanded++;
} else {
agentApi.logWarn(`Cannot access API ${vstsRes.statusCode} accessing ${change.location}`);
agentApi.logWarn(`The most common reason for this failure is that the account defined by the agent access token does not have rights to read the required repo`);
}
}
} catch (err) {
agentApi.logWarn(`Cannot expand message ${err}`);
agentApi.logWarn(`Using ${change.location}`);
}
}
}
agentApi.logInfo(`Expanded truncated commit messages ${expanded}`);
resolve(globalCommits);
});
}
export async function enrichPullRequest(
gitApi: IGitApi,
pullRequests: EnrichedGitPullRequest[]
): Promise<EnrichedGitPullRequest[]> {
return new Promise<EnrichedGitPullRequest[]>(async (resolve, reject) => {
try {
for (let prIndex = 0; prIndex < pullRequests.length; prIndex++) {
const prDetails = pullRequests[prIndex];
// issue1512 the API call that gets the batch of PRs does not return the whole description, so we need to get each one individually
const pr = await gitApi.getPullRequestById(prDetails.pullRequestId);
prDetails.description = pr.description;
// get any missing labels for all the known PRs we are interested in as getPullRequestById does not populate labels, so get those as well
if (!prDetails.labels || prDetails.labels.length === 0 ) {
agentApi.logDebug(`Checking for tags for ${prDetails.pullRequestId}`);
const prLabels = await (gitApi.getPullRequestLabels(prDetails.repository.id, prDetails.pullRequestId));
prDetails.labels = prLabels;
}
// and added the WI IDs
var wiRefs = await (gitApi.getPullRequestWorkItemRefs(prDetails.repository.id, prDetails.pullRequestId));
prDetails.associatedWorkitems = wiRefs.map(wi => {
return {
id: parseInt(wi.id),
url: wi.url
};
}) ;
agentApi.logDebug(`Added ${prDetails.associatedWorkitems.length} work items for ${prDetails.pullRequestId}`);
prDetails.associatedCommits = [];
var csRefs = await (gitApi.getPullRequestCommits(prDetails.repository.id, prDetails.pullRequestId));
for (let csIndex = 0; csIndex < csRefs.length; csIndex++) {
prDetails.associatedCommits.push ( await (gitApi.getCommit(csRefs[csIndex].commitId, prDetails.repository.id)));
}
agentApi.logDebug(`Added ${prDetails.associatedCommits.length} commits for ${prDetails.pullRequestId}, note this includes commits on the PR source branch not associated directly with the build`);
}
resolve(pullRequests);
} catch (err) {
reject(err);
}
});
}
export async function enrichChangesWithFileDetails(
gitApi: IGitApi,
tfvcApi: ITfvcApi,
changes: Change[],
gitHubPat: string
): Promise<Change[]> {
return new Promise<Change[]>(async (resolve, reject) => {
try {
var extraDetail = [];
if (changes && changes.length > 0) {
for (let index = 0; index < changes.length; index++) {
const change = changes[index];
try {
agentApi.logInfo (`Enriched change ${change.id} of type ${change.type}`);
if (change.type === "TfsGit") {
// we need the repository ID for the API call
// the alternative is to take the basic location value and build a rest call from that
// neither are that nice.
var url = require("url");
// split the url up, check it is the expected format and then get the ID
var urlParts = url.parse(change.location);
try {
var pathParts = urlParts.path.split("/");
var repoId = "";
for (let index = 0; index < pathParts.length; index++) {
if (pathParts[index] === "repositories") {
repoId = pathParts[index + 1];
break;
}
}
let gitDetails = await gitApi.getChanges(change.id, repoId);
agentApi.logInfo (`Enriched with details of ${gitDetails.changes.length} files`);
extraDetail = gitDetails.changes;
} catch (ex) {
agentApi.logInfo (`Cannot enriched ${ex}`);
}
} else if (change.type === "TfsVersionControl") {
var tfvcDetail = await tfvcApi.getChangesetChanges(parseInt(change.id.substring(1)));
agentApi.logInfo (`Enriched with details of ${tfvcDetail.length} files`);
extraDetail = tfvcDetail;
} else if (change.type === "GitHub") {
let res: restm.IRestResponse<GitCommit>;
// we build PAT auth object even if we have no token
// this will still allow access to public repos
// if we have a token it will allow access to private ones
let auth = new PersonalAccessTokenCredentialHandler(gitHubPat);
let rc = new restm.RestClient("rest-client", "", [auth], {});
let gitHubRes: any = await rc.get(change.location); // we have to use type any as there is a type mismatch
if (gitHubRes.statusCode === 200) {
var gitHubFiles = gitHubRes.result.files;
agentApi.logInfo (`Enriched with details of ${gitHubFiles.length} files`);
extraDetail = gitHubFiles;
} else {
agentApi.logWarn(`Cannot access API ${gitHubRes.statusCode} accessing ${change.location}`);
agentApi.logWarn(`The most common reason for this failure is that the GitHub Repo is private and a Personal Access Token giving read access needs to be passed as a parameter to this task`);
}
} else if (change.type === "Bitbucket") {
agentApi.logWarn(`This task does not currently support getting file details associated to a commit on Bitbucket`);
} else {
agentApi.logWarn(`Cannot preform enrichment as type ${change.type} is not supported for enrichment`);
}
change["changes"] = extraDetail;
} catch (err) {
agentApi.logWarn(`Error ${err} enriching ${change.location}`);
}
}
} else {
changes = [];
}
resolve(changes);
} catch (err) {
reject(err);
}
});
}
// Gets the credential handler. Supports both PAT and OAuth tokens
export function getCredentialHandler(pat: string, accessToken: string): IRequestHandler {
if ( !(!accessToken || accessToken.length === 0) || (!pat || pat.length === 0)) {
// no pat passed so we need the system token
agentApi.logDebug("Getting System.AccessToken");
if (!accessToken || accessToken.length === 0) {
accessToken = agentApi.getSystemAccessToken();
}
let credHandler: IRequestHandler;
if (!accessToken || accessToken.length === 0) {
throw "Unable to locate access token that will allow access to Azure DevOps API.";
} else {
agentApi.logInfo("Creating the credential handler from the OAUTH token");
// used for local debugging. Allows switching between PAT token and Bearer Token for debugging
credHandler = webApi.getHandlerFromToken(accessToken, true);
}
return credHandler;
} else {
agentApi.logInfo("Creating the credential handler using override PAT (suitable for local testing or if the OAUTH token cannot be used)");
return webApi.getPersonalAccessTokenHandler(pat, true);
}
}
export async function getTestsForBuild(
testAPI: TestApi,
teamProject: string,
buildId: number
): Promise<TestCaseResult[]> {
return new Promise<TestCaseResult[]>(async (resolve, reject) => {
let testList: TestCaseResult[] = [];
try {
let buildTestResults = await (testAPI.getTestResultsByBuild(teamProject, buildId));
tl.debug(`Found ${buildTestResults.length} automated test results associated with the build`);
if ( buildTestResults.length > 0 ) {
for (let index = 0; index < buildTestResults.length; index++) {
const test = buildTestResults[index];
if (testList.filter(e => e.testRun.id === `${test.runId}`).length === 0) {
var skip = 0;
var batchSize = 1000; // the API max is 1000
do {
agentApi.logDebug(`Get batch of automated tests [${skip}] - [${skip + batchSize}] for test run ${test.runId}`);
var runBatch = await (testAPI.getTestResults(teamProject, test.runId, null, skip, batchSize));
tl.debug(`Adding ${runBatch.length} tests`);
testList.push(...runBatch);
skip += batchSize;
} while (batchSize === runBatch.length);
} else {
tl.debug(`Skipping adding tests for test run ${test.runId} as already added`);
}
}
tl.debug(`Test results expanded to unique ${testList.length} test results`);
} else {
tl.debug(`No automated tests associated with build ${buildId}`);
}
resolve(testList);
} catch (err) {
reject(err);
}
});
}
export async function getManualTestsForBuild(
restClient: restm.RestClient,
testAPI: TestApi,
tpcUri: string,
teamProject: string,
buildid: number,
globalManualTestConfigurations
): Promise<EnrichedTestRun[]> {
return new Promise<EnrichedTestRun[]>(async (resolve, reject) => {
let testRunList: EnrichedTestRun[] = [];
try {
let buildTestRuns = [];
var runSkip = 0;
var batchSize = 1000; // the API max
let usedConfigurations = [];
do {
agentApi.logDebug(`Get batch of manual test runs [${runSkip}] - [${runSkip + batchSize}]`);
var runs = await (testAPI.getTestRuns(
teamProject,
`vstfs:///Build/Build/${buildid}`,
null, // owner
null, // tmpiRunId
null, // planId
true, // include details
false, // shows both manual and automated
runSkip,
batchSize));
// this returns both manual and automated we need to filter
runs = runs.filter(run => run.isAutomated === false);
buildTestRuns.push(...runs);
} while (batchSize === runs.length);
tl.debug(`Found ${buildTestRuns.length} manual test runs associated with the build`);
if ( buildTestRuns.length > 0 ) {
for (let index = 0; index < buildTestRuns.length; index++) {
const testRun = <EnrichedTestRun>buildTestRuns[index];
testRun.TestResults = [];
var resultSkip = 0;
do {
agentApi.logDebug(`Get batch of tests [${resultSkip}] - [${resultSkip + batchSize}] for test run ${testRun.id}`);
// get the test steps
var batch = await testAPI.getTestResults(teamProject, testRun.id, ResultDetails.Point, resultSkip, batchSize );
testRun.TestResults.push (...batch);
// get the list of unique configurations
var uniqueIDs = [...new Set(batch.map(item => item.configuration.id))];
uniqueIDs.forEach(id => {
if (!usedConfigurations.includes(id)) {
usedConfigurations.push(id);
}
});
} while (batchSize === batch.length);
testRunList.push(testRun);
tl.debug(`Manual Test Run ${testRun.id} enriched with ${testRun.TestResults.length} individual test results`);
}
// get the details of the test configurations. There is no SDK call for this, so making a base REST call
try {
// extract a URL to use with the client
for (let index = 0; index < usedConfigurations.length; index++) {
tl.debug(`Getting details of the test configuration ${usedConfigurations[index]}`);
let response = await restClient.get(`${tpcUri}/${teamProject}/_apis/test/configurations/${usedConfigurations[index]}?api-version=5.0-preview.2`);
globalManualTestConfigurations.push(response.result);
}
} catch (err) {
tl.warning(`Cannot get the details of the test configuration`);
}
} else {
tl.debug(`No manual test plans associated with build`);
}
resolve(testRunList);
} catch (err) {
reject(err);
}
});
}
export async function getConsumedArtifactsForBuild(
restClient: restm.RestClient,
tpcUri: string,
teamProject: string,
buildid: number
): Promise<[]> {
return new Promise<[]>(async (resolve, reject) => {
let consumedArtifacts: [] = [];
try {
var payload = {
"contributionIds": [
"ms.vss-build-web.run-consumed-artifacts-data-provider"
],
"dataProviderContext": {
"properties": {
"buildId": `${buildid}`,
"sourcePage": {
"url": `${tpcUri}/${teamProject}/_build/results?buildId=${buildid}&view=results`,
"routeId": "ms.vss-build-web.ci-results-hub-route",
"routeValues": {
"project": `${teamProject}`,
"viewname": "build-results",
"controller": "ContributedPage",
"action": "Execute"
}
}
}
}
};
let response = await restClient.create(
`${tpcUri}/_apis/Contribution/HierarchyQuery/project/${teamProject}?api-version=5.1-preview`,
payload);
var result = response.result;
resolve(response.result["dataProviders"]["ms.vss-build-web.run-consumed-artifacts-data-provider"].consumedSources);
} catch (err) {
tl.warning(`Cannot get the details of the consumed artifacts ${err}`);
resolve([]);
}
});
}
export function addUniqueTestToArray (
masterArray: TestCaseResult[],
newArray: TestCaseResult[]
) {
tl.debug(`The global test array contains ${masterArray.length} items`);
if (newArray.length > 0) {
newArray.forEach(test => {
if (masterArray.filter(e => e.testCaseReferenceId === test.testCaseReferenceId && e.testRun.id === test.testRun.id).length === 0) {
tl.debug(`Adding the test case ${test.testCaseReferenceId} for test run ${test.testRun.id} as not present in the master list`);
masterArray.push(test);
} else {
tl.debug(`Skipping the test case ${test.testCaseReferenceId} for test run ${test.testRun.id} as already present in the master list`);
}
});
}
tl.debug(`The updated global test array contains ${masterArray.length} items`);
return masterArray;
}
export async function getTestsForRelease(
testAPI: TestApi,
teamProject: string,
release: Release
): Promise<TestCaseResult[]> {
return new Promise<TestCaseResult[]>(async (resolve, reject) => {
let testList: TestCaseResult[] = [];
try {
for (let envIndex = 0; envIndex < release.environments.length; envIndex++) {
const env = release.environments[envIndex];
let envTestResults = await (testAPI.getTestResultDetailsForRelease(teamProject, release.id, env.id));
if (envTestResults.resultsForGroup.length > 0) {
for (let index = 0; index < envTestResults.resultsForGroup[0].results.length; index++) {
const test = envTestResults.resultsForGroup[0].results[index];
if (testList.filter(e => e.testRun.id === `${test.testRun.id}`).length === 0) {
tl.debug(`Adding tests for test run ${test.testRun.id}`);
let run = await (testAPI.getTestResults(teamProject, parseInt(test.testRun.id)));
testList.push(...run);
} else {
tl.debug(`Skipping adding tests for test run ${test.testRun.id} as already added`);
}
}
} else {
tl.debug(`No tests associated with release ${release.id} environment ${env.name}`);
}
}
resolve(testList);
} catch (err) {
reject(err);
}
});
}
export function getTemplate(
templateLocation: string,
templateFile: string ,
inlinetemplate: string
): Array<string> {
agentApi.logDebug(`Using template mode ${templateLocation}`);
var template;
const handlebarIndicator = "{{";
if (templateLocation === "File") {
if (fs.existsSync(templateFile)) {
agentApi.logInfo (`Loading template file ${templateFile}`);
template = fs.readFileSync(templateFile, "utf8").toString();
} else {
agentApi.logError (`Cannot find template file ${templateFile}`);
return template;
}
} else {
agentApi.logInfo ("Using in-line template");
template = inlinetemplate;
}
// we now only handle handlebar templates
if (template.includes(handlebarIndicator)) {
agentApi.logDebug("Loading handlebar template");
}
else {
agentApi.logError("The template is not on handlebars format, load template has been skipped");
template = "";
}
return template;
}
export async function getAllDirectRelatedWorkitems (
workItemTrackingApi: IWorkItemTrackingApi,
workItems: WorkItem[]
) {
var relatedWorkItems = [...workItems]; // a clone
for (let wiIndex = 0; wiIndex < workItems.length; wiIndex++) {
var wi = workItems[wiIndex];
agentApi.logInfo(`Looking for parents and children of WI [${wi.id}]`);
for (let relIndex = 0; relIndex < wi.relations.length; relIndex++) {
var relation = wi.relations[relIndex];
if ((relation.attributes.name === "Child") ||
(relation.attributes.name === "Parent")) {
var urlParts = relation.url.split("/");
var id = parseInt(urlParts[urlParts.length - 1]);
if (!relatedWorkItems.find(element => element.hasOwnProperty("id") && element.id === id)) {
agentApi.logInfo(`Add ${relation.attributes.name} WI ${id}`);
relatedWorkItems.push(await (workItemTrackingApi.getWorkItem(id, null, null, WorkItemExpand.All, null)));
} else {
agentApi.logInfo(`Skipping ${id} as already in the relations list`);
}
}
}
}
return relatedWorkItems;
}
export async function getAllDirectRelatedTestCases (
workItemTrackingApi: IWorkItemTrackingApi,
workItems: WorkItem[]
) {
var testedBy = [];
for (let wiIndex = 0; wiIndex < workItems.length; wiIndex++) {
var wi = workItems[wiIndex];
agentApi.logInfo(`Looking for Tests of WI [${wi.id}]`);
for (let relIndex = 0; relIndex < wi.relations.length; relIndex++) {
var relation = wi.relations[relIndex];
if (relation.attributes.name === "Tested By") {
var urlParts = relation.url.split("/");
var id = parseInt(urlParts[urlParts.length - 1]);
if (!testedBy.find(element => element.id === id)) {
agentApi.logInfo(`Add Test ${relation.attributes.name} WI ${id}`);
testedBy.push(await (workItemTrackingApi.getWorkItem(id, null, null, WorkItemExpand.All, null)));
} else {
agentApi.logInfo(`Skipping Test ${id} as already in the relations list`);
}
}
}
}
return testedBy;
}
export async function getAllParentWorkitems (
workItemTrackingApi: IWorkItemTrackingApi,
relatedWorkItems: WorkItem[]
) {
var allRelatedWorkItems = [...relatedWorkItems]; // a clone
var knownWI = allRelatedWorkItems.length;
var addedOnThisPass = 0;
do {
// reset the count
addedOnThisPass = 0;
// look for all the parent
for (let wiIndex = 0; wiIndex < allRelatedWorkItems.length; wiIndex++) {
var wi = allRelatedWorkItems[wiIndex];
agentApi.logInfo(`Looking for parents of WI [${wi.id}]`);
for (let relIndex = 0; relIndex < wi.relations.length; relIndex++) {
var relation = wi.relations[relIndex];
if (relation.attributes.name === "Parent") {
var urlParts = relation.url.split("/");
var id = parseInt(urlParts[urlParts.length - 1]);
if (!allRelatedWorkItems.find(element => element.id === id)) {
agentApi.logInfo(`Add ${relation.attributes.name} WI ${id}`);
allRelatedWorkItems.push(await (workItemTrackingApi.getWorkItem(id, null, null, WorkItemExpand.All, null)));
// if we add something add to the count
addedOnThisPass ++;
} else {
agentApi.logInfo(`Skipping ${id} as already in the found parent list`);
}
}
}
}
} while (addedOnThisPass !== 0); // exit if we added nothing in this pass
agentApi.logInfo(`Added ${allRelatedWorkItems.length - knownWI} parent WI to the list of direct relations`);
return allRelatedWorkItems;
}
export async function getFullWorkItemDetails (
workItemTrackingApi: IWorkItemTrackingApi,
workItemRefs: ResourceRef[]
) {
let fullWorkItems: WorkItem[] = [];
if (workItemRefs && workItemRefs.length > 0) {
var workItemIds = workItemRefs.map(wi => parseInt(wi.id));
agentApi.logInfo(`Get details of [${workItemIds.length}] WIs`);
if (workItemIds && workItemIds.length > 0) {
var indexStart = 0;
var indexEnd = (workItemIds.length > 200) ? 200 : workItemIds.length ;
while ((indexEnd <= workItemIds.length) && (indexStart !== indexEnd)) {
var subList = workItemIds.slice(indexStart, indexEnd);
agentApi.logInfo(`Getting full details of WI batch from index: [${indexStart}] to [${indexEnd}]`);
var subListDetails = await workItemTrackingApi.getWorkItems(subList, null, null, WorkItemExpand.All, null);
agentApi.logInfo(`Adding [${subListDetails.length}] items`);
fullWorkItems = fullWorkItems.concat(subListDetails);
indexStart = indexEnd;
indexEnd = ((workItemIds.length - indexEnd) > 200) ? indexEnd + 200 : workItemIds.length;
}
}
}
return fullWorkItems;
}
// The Argument compareReleaseDetails is used in the template processing. Renaming or removing will break the templates
export function processTemplate(
template,
workItems: WorkItem[],
commits: Change[],
buildDetails: Build,
releaseDetails: Release,
compareReleaseDetails: Release,
customHandlebarsExtensionCodeAsFile: string,
customHandlebarsExtensionCode: string,
customHandlebarsExtensionFile: string,
customHandlebarsExtensionFolder: string,
pullRequests: EnrichedGitPullRequest[],
globalBuilds: UnifiedArtifactDetails[],
globalTests: TestCaseResult[],
releaseTests: TestCaseResult[],
relatedWorkItems: WorkItem[],
compareBuildDetails: Build,
currentStage: TimelineRecord,
inDirectlyAssociatedPullRequests: EnrichedGitPullRequest[],
globalManualTests: EnrichedTestRun[],
globalManualTestConfigurations: [],
stopOnError: boolean,
globalConsumedArtifacts: any[],
queryWorkItems: WorkItem[],
testedByWorkItems: WorkItem[],
publishedArtifacts: BuildArtifact[]
): string {
var output = "";
if (template.length > 0) {
agentApi.logDebug("Processing template");
agentApi.logDebug(` WI: ${workItems.length}`);
agentApi.logDebug(` CS: ${commits.length}`);
agentApi.logDebug(` PR: ${pullRequests.length}`);
agentApi.logDebug(` Builds: ${globalBuilds.length}`);
agentApi.logDebug(` Manual Tests: ${globalManualTests.length}`);
agentApi.logDebug(` Manual TestConfigurations: ${globalManualTestConfigurations.length}`);
agentApi.logDebug(` Release Tests: ${releaseTests.length}`);
agentApi.logDebug(` Related WI: ${relatedWorkItems.length}`);
agentApi.logDebug(` Related Tests: ${testedByWorkItems.length}`);
agentApi.logDebug(` Indirect PR: ${inDirectlyAssociatedPullRequests.length}`);
agentApi.logDebug(` Consumed Artifacts: ${globalConsumedArtifacts.length}`);
agentApi.logDebug(` Published Artifacts: ${publishedArtifacts.length}`);
agentApi.logDebug(` Query WI: ${queryWorkItems.length}`);
// it is a handlebar template
agentApi.logDebug("Processing handlebar template");
const handlebars = require("handlebars");
// load the extension library so it can be accessed in templates
agentApi.logInfo("Loading handlebars-helpers extension");
const helpers = require("handlebars-helpers")({
handlebars: handlebars
});
// add a custom helper to expand json
handlebars.registerHelper("json", function(context) {
return JSON.stringify(context);
});
// add our helper to find children and parents
handlebars.registerHelper("lookup_a_work_item", function (array, url) {
var urlParts = url.split("/");
var wiId = parseInt(urlParts[urlParts.length - 1]);
return array.find(element => element?.id === wiId);
});
// add our helper to find test configuration
handlebars.registerHelper("lookup_a_test_configuration", function (array, id) {
return array.find(element => element.id === Number(id));
});
// add our helper to find PR
handlebars.registerHelper("lookup_a_pullrequest", function (array, url) {
var urlParts = url.split("%2F");
var prId = parseInt(urlParts[urlParts.length - 1]);
return array.find(element => element.pullRequestId === prId);
});
// add our helper to get first line of commit message
handlebars.registerHelper("get_only_message_firstline", function (msg) {
return msg.split(`\n`)[0];
});
// add our helper to find PR
handlebars.registerHelper("lookup_a_pullrequest_by_merge_commit", function (array, commitId) {
return array.find(element => element.lastMergeCommit.commitId === commitId);
});
// make sure we have valid file name for the custom extension