/
index.ts
778 lines (706 loc) · 20.3 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
import {
GitPullRequest,
GitPullRequestCommentThread,
GitPullRequestMergeStrategy,
} from 'azure-devops-node-api/interfaces/GitInterfaces';
import { RenovateConfig } from '../../config/common';
import { REPOSITORY_DISABLED } from '../../constants/error-messages';
import { PLATFORM_TYPE_AZURE } from '../../constants/platforms';
import {
PR_STATE_ALL,
PR_STATE_NOT_OPEN,
PR_STATE_OPEN,
} from '../../constants/pull-requests';
import { logger } from '../../logger';
import { BranchStatus } from '../../types';
import * as hostRules from '../../util/host-rules';
import { sanitize } from '../../util/sanitize';
import { ensureTrailingSlash } from '../../util/url';
import {
BranchStatusConfig,
CommitFilesConfig,
CreatePRConfig,
EnsureCommentConfig,
EnsureCommentRemovalConfig,
EnsureIssueResult,
FindPRConfig,
Issue,
PlatformConfig,
Pr,
RepoConfig,
RepoParams,
VulnerabilityAlert,
} from '../common';
import GitStorage, { StatusResult } from '../git/storage';
import { smartTruncate } from '../utils/pr-body';
import * as azureApi from './azure-got-wrapper';
import * as azureHelper from './azure-helper';
import { AzurePr } from './types';
interface Config {
storage: GitStorage;
repoForceRebase: boolean;
mergeMethod: GitPullRequestMergeStrategy;
baseCommitSHA: string | undefined;
baseBranch: string;
defaultBranch: string;
owner: string;
repoId: string;
project: string;
azureWorkItemId: string;
prList: AzurePr[];
fileList: null;
repository: string;
}
interface User {
id: string;
name: string;
}
let config: Config = {} as any;
const defaults: any = {
hostType: PLATFORM_TYPE_AZURE,
};
export function initPlatform({
endpoint,
token,
username,
password,
}: RenovateConfig): Promise<PlatformConfig> {
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
const res = {
endpoint: ensureTrailingSlash(endpoint),
};
defaults.endpoint = res.endpoint;
azureApi.setEndpoint(res.endpoint);
const platformConfig: PlatformConfig = {
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();
return repos.map((repo) => `${repo.project.name}/${repo.name}`);
}
async function getBranchCommit(fullBranchName: string): Promise<string> {
const azureApiGit = await azureApi.gitApi();
const commit = await azureApiGit.getBranch(
config.repoId,
azureHelper.getBranchNameWithoutRefsheadsPrefix(fullBranchName)!
);
return commit.commit.commitId;
}
export async function initRepo({
repository,
localDir,
azureWorkItemId,
optimizeForDisabled,
}: RepoParams): Promise<RepoConfig> {
logger.debug(`initRepo("${repository}")`);
config = { repository, azureWorkItemId } as any;
const azureApiGit = await azureApi.gitApi();
const repos = await azureApiGit.getRepositories();
const names = azureHelper.getProjectAndRepo(repository);
const repo = repos.filter(
(c) =>
c.name.toLowerCase() === names.repo.toLowerCase() &&
c.project.name.toLowerCase() === names.project.toLowerCase()
)[0];
logger.debug({ repositoryDetails: repo }, 'Repository details');
config.repoId = repo.id;
config.project = repo.project.name;
config.owner = '?owner?';
logger.debug(`${repository} owner = ${config.owner}`);
// Use default branch as PR target unless later overridden
config.defaultBranch = repo.defaultBranch.replace('refs/heads/', '');
config.baseBranch = config.defaultBranch;
logger.debug(`${repository} default branch = ${config.defaultBranch}`);
config.baseCommitSHA = await getBranchCommit(config.baseBranch);
config.mergeMethod = await azureHelper.getMergeMethod(repo.id, names.project);
config.repoForceRebase = false;
if (optimizeForDisabled) {
interface RenovateConfig {
enabled: boolean;
}
let renovateConfig: RenovateConfig;
try {
const json = await azureHelper.getFile(
repo.id,
'renovate.json',
config.defaultBranch
);
renovateConfig = JSON.parse(json);
} catch {
// Do nothing
}
if (renovateConfig && renovateConfig.enabled === false) {
throw new Error(REPOSITORY_DISABLED);
}
}
config.storage = new GitStorage();
const [projectName, repoName] = repository.split('/');
const opts = hostRules.find({
hostType: defaults.hostType,
url: defaults.endpoint,
});
const url =
defaults.endpoint +
`${encodeURIComponent(projectName)}/_git/${encodeURIComponent(repoName)}`;
await config.storage.initRepo({
...config,
localDir,
url,
extraCloneOpts: azureHelper.getStorageExtraCloneOpts(opts),
gitAuthorName: global.gitAuthor?.name,
gitAuthorEmail: global.gitAuthor?.email,
});
const repoConfig: RepoConfig = {
baseBranch: config.baseBranch,
isFork: false,
};
return repoConfig;
}
export function getRepoForceRebase(): Promise<boolean> {
return Promise.resolve(config.repoForceRebase === true);
}
// Search
export /* istanbul ignore next */ function getFileList(): Promise<string[]> {
return config.storage.getFileList();
}
export /* istanbul ignore next */ async function setBaseBranch(
branchName = config.baseBranch
): Promise<string> {
logger.debug(`Setting baseBranch to ${branchName}`);
config.baseBranch = branchName;
delete config.baseCommitSHA;
const baseBranchSha = await config.storage.setBaseBranch(branchName);
return baseBranchSha;
}
export /* istanbul ignore next */ function setBranchPrefix(
branchPrefix: string
): Promise<void> {
return config.storage.setBranchPrefix(branchPrefix);
}
// Branch
export /* istanbul ignore next */ function branchExists(
branchName: string
): Promise<boolean> {
return config.storage.branchExists(branchName);
}
export /* istanbul ignore next */ function getAllRenovateBranches(
branchPrefix: string
): Promise<string[]> {
return config.storage.getAllRenovateBranches(branchPrefix);
}
export /* istanbul ignore next */ function isBranchStale(
branchName: string
): Promise<boolean> {
return config.storage.isBranchStale(branchName);
}
export /* istanbul ignore next */ function getFile(
filePath: string,
branchName: string
): Promise<string> {
return config.storage.getFile(filePath, branchName);
}
// istanbul ignore next
async function abandonPr(prNo: number): Promise<void> {
logger.debug(`abandonPr(prNo)(${prNo})`);
const azureApiGit = await azureApi.gitApi();
await azureApiGit.updatePullRequest(
{
status: 2,
},
config.repoId,
prNo
);
}
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(azureHelper.getRenovatePRFormat);
logger.debug({ length: config.prList.length }, 'Retrieved Pull Requests');
}
return config.prList;
}
/* istanbul ignore next */
export async function getPrFiles(pr: Pr): Promise<string[]> {
return config.storage.getBranchFiles(pr.branchName, pr.targetBranch);
}
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);
const commits = await azureApiGit.getPullRequestCommits(
config.repoId,
pullRequestId
);
azurePr.isModified =
commits.length > 0 &&
commits[0].author.name !== commits[commits.length - 1].author.name;
return azurePr;
}
export async function findPr({
branchName,
prTitle,
state = PR_STATE_ALL,
}: FindPRConfig): Promise<Pr | null> {
let prsFiltered: Pr[] = [];
try {
const prs = await getPrList();
prsFiltered = prs.filter(
(item) => item.sourceRefName === azureHelper.getNewBranchName(branchName)
);
if (prTitle) {
prsFiltered = prsFiltered.filter((item) => item.title === prTitle);
}
switch (state) {
case PR_STATE_ALL:
// no more filter needed, we can go further...
break;
case PR_STATE_NOT_OPEN:
prsFiltered = prsFiltered.filter(
(item) => item.state !== PR_STATE_OPEN
);
break;
default:
prsFiltered = prsFiltered.filter((item) => item.state === state);
break;
}
} catch (error) {
logger.error('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: PR_STATE_OPEN,
});
return existingPr ? getPr(existingPr.number) : null;
}
export /* istanbul ignore next */ async function deleteBranch(
branchName: string,
abandonAssociatedPr = false
): Promise<void> {
await config.storage.deleteBranch(branchName);
if (abandonAssociatedPr) {
const pr = await getBranchPr(branchName);
await abandonPr(pr.number);
}
}
export /* istanbul ignore next */ function getBranchLastCommitTime(
branchName: string
): Promise<Date> {
return config.storage.getBranchLastCommitTime(branchName);
}
export /* istanbul ignore next */ function getRepoStatus(): Promise<
StatusResult
> {
return config.storage.getRepoStatus();
}
export /* istanbul ignore next */ function mergeBranch(
branchName: string
): Promise<void> {
return config.storage.mergeBranch(branchName);
}
export /* istanbul ignore next */ function commitFiles({
branchName,
files,
message,
}: CommitFilesConfig): Promise<string | null> {
return config.storage.commitFiles({
branchName,
files,
message,
});
}
export /* istanbul ignore next */ function getCommitMessages(): Promise<
string[]
> {
return config.storage.getCommitMessages();
}
export async function getBranchStatusCheck(
branchName: string,
context: string
): Promise<BranchStatus> {
logger.trace(`getBranchStatusCheck(${branchName}, ${context})`);
const azureApiGit = await azureApi.gitApi();
const branch = await azureApiGit.getBranch(
config.repoId,
azureHelper.getBranchNameWithoutRefsheadsPrefix(branchName)!
);
if (branch.aheadCount === 0) {
return BranchStatus.green;
}
return BranchStatus.yellow;
}
export async function getBranchStatus(
branchName: string,
requiredStatusChecks: string[]
): Promise<BranchStatus> {
logger.debug(`getBranchStatus(${branchName})`);
if (!requiredStatusChecks) {
// null means disable status checks, so it always succeeds
return BranchStatus.green;
}
if (requiredStatusChecks.length) {
// This is Unsupported
logger.warn({ requiredStatusChecks }, `Unsupported requiredStatusChecks`);
return BranchStatus.red;
}
const branchStatusCheck = await getBranchStatusCheck(branchName, null);
return branchStatusCheck;
}
export async function createPr({
branchName,
prTitle: title,
prBody: body,
labels,
useDefaultBranch,
platformOptions = {},
}: CreatePRConfig): Promise<Pr> {
const sourceRefName = azureHelper.getNewBranchName(branchName);
const targetRefName = azureHelper.getNewBranchName(
useDefaultBranch ? config.defaultBranch : config.baseBranch
);
const description = azureHelper.max4000Chars(sanitize(body));
const azureApiGit = await azureApi.gitApi();
const workItemRefs = [
{
id: config.azureWorkItemId,
},
];
let pr: GitPullRequest = await azureApiGit.createPullRequest(
{
sourceRefName,
targetRefName,
title,
description,
workItemRefs,
},
config.repoId
);
if (platformOptions.azureAutoComplete) {
pr = await azureApiGit.updatePullRequest(
{
autoCompleteSetBy: {
id: pr.createdBy.id,
},
completionOptions: {
mergeStrategy: config.mergeMethod,
deleteSourceBranch: true,
},
},
config.repoId,
pr.pullRequestId
);
}
await Promise.all(
labels.map((label) =>
azureApiGit.createPullRequestLabel(
{
name: label,
},
config.repoId,
pr.pullRequestId
)
)
);
return azureHelper.getRenovatePRFormat(pr);
}
export async function updatePr(
prNo: number,
title: string,
body?: string
): Promise<void> {
logger.debug(`updatePr(${prNo}, ${title}, body)`);
const azureApiGit = await azureApi.gitApi();
const objToUpdate: GitPullRequest = {
title,
};
if (body) {
objToUpdate.description = azureHelper.max4000Chars(sanitize(body));
}
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 = null;
let commentIdFound = null;
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,
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({
number: issueNo,
topic,
content,
}: EnsureCommentRemovalConfig): Promise<void> {
logger.debug(
`Ensuring comment "${topic || content}" in #${issueNo} is removed`
);
const azureApiGit = await azureApi.gitApi();
const threads = await azureApiGit.getThreads(config.repoId, issueNo);
const byTopic = (thread: GitPullRequestCommentThread): boolean =>
thread.comments[0].content.startsWith(`### ${topic}\n\n`);
const byContent = (thread: GitPullRequestCommentThread): boolean =>
thread.comments[0].content.trim() === content;
let threadIdFound: number | null = null;
if (topic) {
threadIdFound = threads.find(byTopic)?.id;
} else if (content) {
threadIdFound = threads.find(byContent)?.id;
}
if (threadIdFound) {
await azureApiGit.updateThread(
{
status: 4, // close
},
config.repoId,
issueNo,
threadIdFound
);
}
}
export function setBranchStatus({
branchName,
context,
description,
state,
url: targetUrl,
}: BranchStatusConfig): Promise<void> {
logger.debug(
`setBranchStatus(${branchName}, ${context}, ${description}, ${state}, ${targetUrl}) - Not supported by Azure DevOps (yet!)`
);
return Promise.resolve();
}
export function mergePr(pr: number, branchName: string): Promise<boolean> {
logger.debug(`mergePr(pr)(${pr}) - Not supported by Azure DevOps (yet!)`);
return Promise.resolve(false);
}
export function getPrBody(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(new RegExp(`\n---\n\n.*?<!-- rebase-check -->.*?\n`), '')
.replace('<summary>', '**')
.replace('</summary>', '**')
.replace('<details>', '')
.replace('</details>', '');
}
export /* istanbul ignore next */ function findIssue(): Promise<Issue | null> {
logger.warn(`findIssue() is not implemented`);
return null;
}
export /* istanbul ignore next */ function ensureIssue(): Promise<EnsureIssueResult | null> {
logger.warn(`ensureIssue() is not implemented`);
return Promise.resolve(null);
}
export /* istanbul ignore next */ function ensureIssueClosing(): Promise<void> {
return Promise.resolve();
}
export /* istanbul ignore next */ function getIssueList(): Promise<Issue[]> {
logger.debug(`getIssueList()`);
// TODO: Needs implementation
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 teams = await azureApiCore.getTeams(repo.project.id);
const members = await Promise.all(
teams.map(
async (t) =>
/* eslint-disable no-return-await */
await azureApiCore.getTeamMembersWithExtendedProperties(
repo.project.id,
t.id
)
)
);
const ids: { id: string; name: string }[] = [];
members.forEach((listMembers) => {
listMembers.forEach((m) => {
users.forEach((r) => {
if (
r.toLowerCase() === m.identity.displayName.toLowerCase() ||
r.toLowerCase() === m.identity.uniqueName.toLowerCase()
) {
if (ids.filter((c) => c.id === m.identity.id).length === 0) {
ids.push({ id: m.identity.id, name: r });
}
}
});
});
});
teams.forEach((t) => {
users.forEach((r) => {
if (r.toLowerCase() === t.name.toLowerCase()) {
if (ids.filter((c) => c.id === t.id).length === 0) {
ids.push({ id: t.id, name: r });
}
}
});
});
return ids;
}
/**
*
* @param {number} issueNo
* @param {string[]} assignees
*/
export async function addAssignees(
issueNo: number,
assignees: string[]
): Promise<void> {
logger.trace(`addAssignees(${issueNo}, ${assignees})`);
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})`);
const azureApiGit = await azureApi.gitApi();
const ids = await getUserIds(reviewers);
await Promise.all(
ids.map(async (obj) => {
await azureApiGit.createPullRequestReviewer(
{},
config.repoId,
prNo,
obj.id
);
logger.debug(`Reviewer added: ${obj.name}`);
})
);
}
export /* istanbul ignore next */ 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([]);
}
export function cleanRepo(): Promise<void> {
// istanbul ignore if
if (config.storage && config.storage.cleanRepo) {
config.storage.cleanRepo();
}
config = {} as any;
return Promise.resolve();
}