-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.ts
901 lines (827 loc) · 23.8 KB
/
index.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
import is from '@sindresorhus/is';
import {
GitPullRequest,
GitPullRequestCommentThread,
GitPullRequestMergeStrategy,
GitStatus,
GitStatusState,
GitVersionDescriptor,
PullRequestStatus,
} from 'azure-devops-node-api/interfaces/GitInterfaces.js';
import delay from 'delay';
import JSON5 from 'json5';
import {
REPOSITORY_ARCHIVED,
REPOSITORY_EMPTY,
REPOSITORY_NOT_FOUND,
} from '../../../constants/error-messages';
import { logger } from '../../../logger';
import { BranchStatus, VulnerabilityAlert } from '../../../types';
import * as git from '../../../util/git';
import * as hostRules from '../../../util/host-rules';
import { regEx } from '../../../util/regex';
import { sanitize } from '../../../util/sanitize';
import { streamToString } from '../../../util/streams';
import { ensureTrailingSlash } from '../../../util/url';
import type {
BranchStatusConfig,
CreatePRConfig,
EnsureCommentConfig,
EnsureCommentRemovalConfig,
EnsureIssueResult,
FindPRConfig,
Issue,
MergePRConfig,
PlatformParams,
PlatformResult,
Pr,
RepoParams,
RepoResult,
UpdatePrConfig,
} from '../types';
import { getNewBranchName, repoFingerprint } from '../util';
import { smartTruncate } from '../utils/pr-body';
import * as azureApi from './azure-got-wrapper';
import * as azureHelper from './azure-helper';
import { AzurePr, AzurePrVote } from './types';
import {
getBranchNameWithoutRefsheadsPrefix,
getGitStatusContextCombinedName,
getGitStatusContextFromCombinedName,
getProjectAndRepo,
getRenovatePRFormat,
getRepoByName,
getStorageExtraCloneOpts,
max4000Chars,
} from './util';
interface Config {
repoForceRebase: boolean;
defaultMergeMethod: GitPullRequestMergeStrategy;
mergeMethods: Record<string, GitPullRequestMergeStrategy>;
owner: string;
repoId: string;
project: string;
prList: AzurePr[];
fileList: null;
repository: string;
defaultBranch: string;
}
interface User {
id: string;
name: string;
isRequired: boolean;
}
let config: Config = {} as any;
const defaults: {
endpoint?: string;
hostType: string;
} = {
hostType: 'azure',
};
export function initPlatform({
endpoint,
token,
username,
password,
}: PlatformParams): Promise<PlatformResult> {
if (!endpoint) {
throw new Error('Init: You must configure an Azure DevOps endpoint');
}
if (!token && !(username && password)) {
throw new Error(
'Init: You must configure an Azure DevOps token, or a username and password'
);
}
// TODO: Add a connection check that endpoint/token combination are valid (#9593)
const res = {
endpoint: ensureTrailingSlash(endpoint),
};
defaults.endpoint = res.endpoint;
azureApi.setEndpoint(res.endpoint);
const platformConfig: PlatformResult = {
endpoint: defaults.endpoint,
};
return Promise.resolve(platformConfig);
}
export async function getRepos(): Promise<string[]> {
logger.debug('Autodiscovering Azure DevOps repositories');
const azureApiGit = await azureApi.gitApi();
const repos = await azureApiGit.getRepositories();
// TODO: types (#7154)
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
return repos.map((repo) => `${repo.project?.name}/${repo.name}`);
}
export async function getRawFile(
fileName: string,
repoName?: string,
branchOrTag?: string
): Promise<string | null> {
const azureApiGit = await azureApi.gitApi();
let repoId: string | undefined;
if (repoName) {
const repos = await azureApiGit.getRepositories();
const repo = getRepoByName(repoName, repos);
repoId = repo?.id;
} else {
repoId = config.repoId;
}
if (!repoId) {
logger.debug('No repoId so cannot getRawFile');
return null;
}
const versionDescriptor: GitVersionDescriptor = {
version: branchOrTag,
} as GitVersionDescriptor;
const buf = await azureApiGit.getItemContent(
repoId,
fileName,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
branchOrTag ? versionDescriptor : undefined
);
const str = await streamToString(buf);
return str;
}
export async function getJsonFile(
fileName: string,
repoName?: string,
branchOrTag?: string
): Promise<any | null> {
const raw = await getRawFile(fileName, repoName, branchOrTag);
return raw ? JSON5.parse(raw) : null;
}
export async function initRepo({
repository,
cloneSubmodules,
}: RepoParams): Promise<RepoResult> {
logger.debug(`initRepo("${repository}")`);
config = { repository } as Config;
const azureApiGit = await azureApi.gitApi();
const repos = await azureApiGit.getRepositories();
const repo = getRepoByName(repository, repos);
if (!repo) {
logger.error({ repos, repo }, 'Could not find repo in repo list');
throw new Error(REPOSITORY_NOT_FOUND);
}
logger.debug({ repositoryDetails: repo }, 'Repository details');
if (repo.isDisabled) {
logger.debug('Repository is disabled- throwing error to abort renovation');
throw new Error(REPOSITORY_ARCHIVED);
}
// istanbul ignore if
if (!repo.defaultBranch) {
logger.debug('Repo is empty');
throw new Error(REPOSITORY_EMPTY);
}
// TODO #7154
config.repoId = repo.id!;
config.project = repo.project!.name!;
config.owner = '?owner?';
logger.debug(`${repository} owner = ${config.owner}`);
const defaultBranch = repo.defaultBranch.replace('refs/heads/', '');
config.defaultBranch = defaultBranch;
logger.debug(`${repository} default branch = ${defaultBranch}`);
const names = getProjectAndRepo(repository);
config.defaultMergeMethod = await azureHelper.getMergeMethod(
// TODO #7154
repo.id!,
names.project,
null,
defaultBranch
);
config.mergeMethods = {};
config.repoForceRebase = false;
const [projectName, repoName] = repository.split('/');
const opts = hostRules.find({
hostType: defaults.hostType,
url: defaults.endpoint,
});
// TODO: types (#7154)
const manualUrl = `${defaults.endpoint!}${encodeURIComponent(
projectName
)}/_git/${encodeURIComponent(repoName)}`;
const url = repo.remoteUrl ?? manualUrl;
await git.initRepo({
...config,
url,
extraCloneOpts: getStorageExtraCloneOpts(opts),
cloneSubmodules,
});
const repoConfig: RepoResult = {
defaultBranch,
isFork: false,
repoFingerprint: repoFingerprint(repo.id!, defaults.endpoint),
};
return repoConfig;
}
export function getRepoForceRebase(): Promise<boolean> {
return Promise.resolve(config.repoForceRebase === true);
}
export async function getPrList(): Promise<AzurePr[]> {
logger.debug('getPrList()');
if (!config.prList) {
const azureApiGit = await azureApi.gitApi();
let prs: GitPullRequest[] = [];
let fetchedPrs: GitPullRequest[];
let skip = 0;
do {
fetchedPrs = await azureApiGit.getPullRequests(
config.repoId,
{ status: 4 },
config.project,
0,
skip,
100
);
prs = prs.concat(fetchedPrs);
skip += 100;
} while (fetchedPrs.length > 0);
config.prList = prs.map(getRenovatePRFormat);
logger.debug(`Retrieved Pull Requests count: ${config.prList.length}`);
}
return config.prList;
}
export async function getPr(pullRequestId: number): Promise<Pr | null> {
logger.debug(`getPr(${pullRequestId})`);
if (!pullRequestId) {
return null;
}
const azurePr = (await getPrList()).find(
(item) => item.number === pullRequestId
);
if (!azurePr) {
return null;
}
const azureApiGit = await azureApi.gitApi();
const labels = await azureApiGit.getPullRequestLabels(
config.repoId,
pullRequestId
);
azurePr.labels = labels
.filter((label) => label.active)
.map((label) => label.name)
.filter(is.string);
azurePr.hasReviewers = is.nonEmptyArray(azurePr.reviewers);
return azurePr;
}
export async function findPr({
branchName,
prTitle,
state = 'all',
}: FindPRConfig): Promise<Pr | null> {
let prsFiltered: Pr[] = [];
try {
const prs = await getPrList();
prsFiltered = prs.filter(
(item) => item.sourceRefName === getNewBranchName(branchName)
);
if (prTitle) {
prsFiltered = prsFiltered.filter((item) => item.title === prTitle);
}
switch (state) {
case 'all':
// no more filter needed, we can go further...
break;
case '!open':
prsFiltered = prsFiltered.filter((item) => item.state !== 'open');
break;
default:
prsFiltered = prsFiltered.filter((item) => item.state === state);
break;
}
} catch (err) {
logger.error({ err }, 'findPr error');
}
if (prsFiltered.length === 0) {
return null;
}
return prsFiltered[0];
}
export async function getBranchPr(branchName: string): Promise<Pr | null> {
logger.debug(`getBranchPr(${branchName})`);
const existingPr = await findPr({
branchName,
state: 'open',
});
return existingPr ? getPr(existingPr.number) : null;
}
async function getStatusCheck(branchName: string): Promise<GitStatus[]> {
const azureApiGit = await azureApi.gitApi();
const branch = await azureApiGit.getBranch(
config.repoId,
// TODO: fix undefined (#7154)
getBranchNameWithoutRefsheadsPrefix(branchName)!
);
// only grab the latest statuses, it will group any by context
return azureApiGit.getStatuses(
// TODO #7154
branch.commit!.commitId!,
config.repoId,
undefined,
undefined,
undefined,
true
);
}
const azureToRenovateStatusMapping: Record<GitStatusState, BranchStatus> = {
[GitStatusState.Succeeded]: BranchStatus.green,
[GitStatusState.NotApplicable]: BranchStatus.green,
[GitStatusState.NotSet]: BranchStatus.yellow,
[GitStatusState.Pending]: BranchStatus.yellow,
[GitStatusState.Error]: BranchStatus.red,
[GitStatusState.Failed]: BranchStatus.red,
};
export async function getBranchStatusCheck(
branchName: string,
context: string
): Promise<BranchStatus | null> {
const res = await getStatusCheck(branchName);
for (const check of res) {
if (getGitStatusContextCombinedName(check.context) === context) {
// TODO #7154
return azureToRenovateStatusMapping[check.state!] ?? BranchStatus.yellow;
}
}
return null;
}
export async function getBranchStatus(
branchName: string
): Promise<BranchStatus> {
logger.debug(`getBranchStatus(${branchName})`);
const statuses = await getStatusCheck(branchName);
logger.debug({ branch: branchName, statuses }, 'branch status check result');
if (!statuses.length) {
logger.debug('empty branch status check result = returning "pending"');
return BranchStatus.yellow;
}
const noOfFailures = statuses.filter(
(status: GitStatus) =>
status.state === GitStatusState.Error ||
status.state === GitStatusState.Failed
).length;
if (noOfFailures) {
return BranchStatus.red;
}
const noOfPending = statuses.filter(
(status: GitStatus) =>
status.state === GitStatusState.NotSet ||
status.state === GitStatusState.Pending
).length;
if (noOfPending) {
return BranchStatus.yellow;
}
return BranchStatus.green;
}
export async function createPr({
sourceBranch,
targetBranch,
prTitle: title,
prBody: body,
labels,
draftPR = false,
platformOptions,
}: CreatePRConfig): Promise<Pr> {
const sourceRefName = getNewBranchName(sourceBranch);
const targetRefName = getNewBranchName(targetBranch);
const description = max4000Chars(sanitize(body));
const azureApiGit = await azureApi.gitApi();
const workItemRefs = [
{
id: platformOptions?.azureWorkItemId?.toString(),
},
];
let pr: GitPullRequest = await azureApiGit.createPullRequest(
{
sourceRefName,
targetRefName,
title,
description,
workItemRefs,
isDraft: draftPR,
},
config.repoId
);
if (platformOptions?.usePlatformAutomerge) {
pr = await azureApiGit.updatePullRequest(
{
autoCompleteSetBy: {
// TODO #7154
id: pr.createdBy!.id,
},
completionOptions: {
mergeStrategy: config.defaultMergeMethod,
deleteSourceBranch: true,
mergeCommitMessage: title,
},
},
config.repoId,
// TODO #7154
pr.pullRequestId!
);
}
if (platformOptions?.azureAutoApprove) {
await azureApiGit.createPullRequestReviewer(
{
reviewerUrl: pr.createdBy!.url,
vote: AzurePrVote.Approved,
isFlagged: false,
isRequired: false,
},
config.repoId,
// TODO #7154
pr.pullRequestId!,
pr.createdBy!.id!
);
}
await Promise.all(
labels!.map((label) =>
azureApiGit.createPullRequestLabel(
{
name: label,
},
config.repoId,
// TODO #7154
pr.pullRequestId!
)
)
);
return getRenovatePRFormat(pr);
}
export async function updatePr({
number: prNo,
prTitle: title,
prBody: body,
state,
}: UpdatePrConfig): Promise<void> {
logger.debug(`updatePr(${prNo}, ${title}, body)`);
const azureApiGit = await azureApi.gitApi();
const objToUpdate: GitPullRequest = {
title,
};
if (body) {
objToUpdate.description = max4000Chars(sanitize(body));
}
if (state === 'open') {
await azureApiGit.updatePullRequest(
{ status: PullRequestStatus.Active },
config.repoId,
prNo
);
} else if (state === 'closed') {
objToUpdate.status = PullRequestStatus.Abandoned;
}
await azureApiGit.updatePullRequest(objToUpdate, config.repoId, prNo);
}
export async function ensureComment({
number,
topic,
content,
}: EnsureCommentConfig): Promise<boolean> {
logger.debug(`ensureComment(${number}, ${topic!}, content)`);
const header = topic ? `### ${topic}\n\n` : '';
const body = `${header}${sanitize(content)}`;
const azureApiGit = await azureApi.gitApi();
const threads = await azureApiGit.getThreads(config.repoId, number);
let threadIdFound: number | undefined;
let commentIdFound: number | undefined;
let commentNeedsUpdating = false;
threads.forEach((thread) => {
const firstCommentContent = thread.comments?.[0].content;
if (
(topic && firstCommentContent?.startsWith(header)) ||
(!topic && firstCommentContent === body)
) {
threadIdFound = thread.id;
commentIdFound = thread.comments?.[0].id;
commentNeedsUpdating = firstCommentContent !== body;
}
});
if (!threadIdFound) {
await azureApiGit.createThread(
{
comments: [{ content: body, commentType: 1, parentCommentId: 0 }],
status: 1,
},
config.repoId,
number
);
logger.info(
{ repository: config.repository, issueNo: number, topic },
'Comment added'
);
} else if (commentNeedsUpdating) {
await azureApiGit.updateComment(
{
content: body,
},
config.repoId,
number,
threadIdFound,
// TODO #7154
commentIdFound!
);
logger.debug(
{ repository: config.repository, issueNo: number, topic },
'Comment updated'
);
} else {
logger.debug(
{ repository: config.repository, issueNo: number, topic },
'Comment is already update-to-date'
);
}
return true;
}
export async function ensureCommentRemoval(
removeConfig: EnsureCommentRemovalConfig
): Promise<void> {
const { number: issueNo } = removeConfig;
const key =
removeConfig.type === 'by-topic'
? removeConfig.topic
: removeConfig.content;
logger.debug(`Ensuring comment "${key}" in #${issueNo} is removed`);
const azureApiGit = await azureApi.gitApi();
const threads = await azureApiGit.getThreads(config.repoId, issueNo);
let threadIdFound: number | null | undefined = null;
if (removeConfig.type === 'by-topic') {
const thread = threads.find(
(thread: GitPullRequestCommentThread): boolean =>
!!thread.comments?.[0].content?.startsWith(
`### ${removeConfig.topic}\n\n`
)
);
threadIdFound = thread?.id;
} else {
const thread = threads.find(
(thread: GitPullRequestCommentThread): boolean =>
thread.comments?.[0].content?.trim() === removeConfig.content
);
threadIdFound = thread?.id;
}
if (threadIdFound) {
await azureApiGit.updateThread(
{
status: 4, // close
},
config.repoId,
issueNo,
threadIdFound
);
}
}
const renovateToAzureStatusMapping: Record<BranchStatus, GitStatusState> = {
[BranchStatus.green]: [GitStatusState.Succeeded],
[BranchStatus.green]: GitStatusState.Succeeded,
[BranchStatus.yellow]: GitStatusState.Pending,
[BranchStatus.red]: GitStatusState.Failed,
};
export async function setBranchStatus({
branchName,
context,
description,
state,
url: targetUrl,
}: BranchStatusConfig): Promise<void> {
logger.debug(
`setBranchStatus(${branchName}, ${context}, ${description}, ${state}, ${targetUrl!})`
);
const azureApiGit = await azureApi.gitApi();
const branch = await azureApiGit.getBranch(
config.repoId,
getBranchNameWithoutRefsheadsPrefix(branchName)!
);
const statusToCreate: GitStatus = {
description,
context: getGitStatusContextFromCombinedName(context),
state: renovateToAzureStatusMapping[state],
targetUrl,
};
await azureApiGit.createCommitStatus(
statusToCreate,
// TODO #7154
branch.commit!.commitId!,
config.repoId
);
logger.trace(`Created commit status of ${state} on branch ${branchName}`);
}
export async function mergePr({
branchName,
id: pullRequestId,
}: MergePRConfig): Promise<boolean> {
logger.debug(`mergePr(${pullRequestId}, ${branchName!})`);
const azureApiGit = await azureApi.gitApi();
let pr = await azureApiGit.getPullRequestById(pullRequestId, config.project);
// TODO #7154
const mergeMethod =
config.mergeMethods[pr.targetRefName!] ??
(config.mergeMethods[pr.targetRefName!] = await azureHelper.getMergeMethod(
config.repoId,
config.project,
pr.targetRefName,
config.defaultBranch
));
const objToUpdate: GitPullRequest = {
status: PullRequestStatus.Completed,
lastMergeSourceCommit: pr.lastMergeSourceCommit,
completionOptions: {
mergeStrategy: mergeMethod,
deleteSourceBranch: true,
mergeCommitMessage: pr.title,
},
};
logger.trace(
`Updating PR ${pullRequestId} to status ${PullRequestStatus.Completed} (${
PullRequestStatus[PullRequestStatus.Completed]
}) with lastMergeSourceCommit ${
// TODO: types (#7154)
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
pr.lastMergeSourceCommit?.commitId
} using mergeStrategy ${mergeMethod} (${
GitPullRequestMergeStrategy[mergeMethod]
})`
);
try {
const response = await azureApiGit.updatePullRequest(
objToUpdate,
config.repoId,
pullRequestId
);
let retries = 0;
let isClosed = response.status === PullRequestStatus.Completed;
while (!isClosed && retries < 5) {
retries += 1;
const sleepMs = retries * 1000;
logger.trace(
{ pullRequestId, status: pr.status, retries },
`Updated PR to closed status but change has not taken effect yet. Retrying...`
);
await delay(sleepMs);
pr = await azureApiGit.getPullRequestById(pullRequestId, config.project);
isClosed = pr.status === PullRequestStatus.Completed;
}
if (!isClosed) {
logger.warn(
{ pullRequestId, status: pr.status },
`Expected PR to have status ${
PullRequestStatus[PullRequestStatus.Completed]
// TODO #7154
}. However, it is ${PullRequestStatus[pr.status!]}.`
);
}
return true;
} catch (err) {
logger.debug({ err }, 'Failed to set the PR as completed.');
return false;
}
}
export function massageMarkdown(input: string): string {
// Remove any HTML we use
return smartTruncate(input, 4000)
.replace(
'you tick the rebase/retry checkbox',
'rename PR to start with "rebase!"'
)
.replace(regEx(`\n---\n\n.*?<!-- rebase-check -->.*?\n`), '')
.replace(regEx(/<!--renovate-(?:debug|config-hash):.*?-->/g), '');
}
/* istanbul ignore next */
export function findIssue(): Promise<Issue | null> {
logger.warn(`findIssue() is not implemented`);
return Promise.resolve(null);
}
/* istanbul ignore next */
export function ensureIssue(): Promise<EnsureIssueResult | null> {
logger.warn(`ensureIssue() is not implemented`);
return Promise.resolve(null);
}
/* istanbul ignore next */
export function ensureIssueClosing(): Promise<void> {
return Promise.resolve();
}
/* istanbul ignore next */
export function getIssueList(): Promise<Issue[]> {
logger.debug(`getIssueList()`);
// TODO: Needs implementation (#9592)
return Promise.resolve([]);
}
async function getUserIds(users: string[]): Promise<User[]> {
const azureApiGit = await azureApi.gitApi();
const azureApiCore = await azureApi.coreApi();
const repos = await azureApiGit.getRepositories();
const repo = repos.filter((c) => c.id === config.repoId)[0];
const requiredReviewerPrefix = 'required:';
// TODO #7154
const teams = await azureApiCore.getTeams(repo.project!.id!);
const members = await Promise.all(
teams.map(
async (t) =>
await azureApiCore.getTeamMembersWithExtendedProperties(
// TODO #7154
repo.project!.id!,
t.id!
)
)
);
const ids: { id: string; name: string; isRequired: boolean }[] = [];
members.forEach((listMembers) => {
listMembers.forEach((m) => {
users.forEach((r) => {
let reviewer = r;
let isRequired = false;
if (reviewer.startsWith(requiredReviewerPrefix)) {
reviewer = reviewer.replace(requiredReviewerPrefix, '');
isRequired = true;
}
if (
reviewer.toLowerCase() === m.identity?.displayName?.toLowerCase() ||
reviewer.toLowerCase() === m.identity?.uniqueName?.toLowerCase()
) {
if (ids.filter((c) => c.id === m.identity?.id).length === 0) {
// TODO #7154
ids.push({
id: m.identity.id!,
name: reviewer,
isRequired,
});
}
}
});
});
});
teams.forEach((t) => {
users.forEach((r) => {
let reviewer = r;
let isRequired = false;
if (reviewer.startsWith(requiredReviewerPrefix)) {
reviewer = reviewer.replace(requiredReviewerPrefix, '');
isRequired = true;
}
if (reviewer.toLowerCase() === t.name?.toLowerCase()) {
if (ids.filter((c) => c.id === t.id).length === 0) {
// TODO #7154
ids.push({ id: t.id!, name: reviewer, isRequired });
}
}
});
});
return ids;
}
/**
*
* @param {number} issueNo
* @param {string[]} assignees
*/
export async function addAssignees(
issueNo: number,
assignees: string[]
): Promise<void> {
logger.trace(`addAssignees(${issueNo}, [${assignees.join(', ')}])`);
const ids = await getUserIds(assignees);
await ensureComment({
number: issueNo,
topic: 'Add Assignees',
content: ids.map((a) => `@<${a.id}>`).join(', '),
});
}
/**
*
* @param {number} prNo
* @param {string[]} reviewers
*/
export async function addReviewers(
prNo: number,
reviewers: string[]
): Promise<void> {
logger.trace(`addReviewers(${prNo}, [${reviewers.join(', ')}])`);
const azureApiGit = await azureApi.gitApi();
const ids = await getUserIds(reviewers);
await Promise.all(
ids.map(async (obj) => {
await azureApiGit.createPullRequestReviewer(
{
isRequired: obj.isRequired,
},
config.repoId,
prNo,
obj.id
);
logger.debug(`Reviewer added: ${obj.name}`);
})
);
}
export async function deleteLabel(
prNumber: number,
label: string
): Promise<void> {
logger.debug(`Deleting label ${label} from #${prNumber}`);
const azureApiGit = await azureApi.gitApi();
await azureApiGit.deletePullRequestLabels(config.repoId, prNumber, label);
}
export function getVulnerabilityAlerts(): Promise<VulnerabilityAlert[]> {
return Promise.resolve([]);
}