-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathindex.ts
656 lines (597 loc) · 17.1 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
import { GitPullRequestMergeStrategy } from 'azure-devops-node-api/interfaces/GitInterfaces';
import * as azureHelper from './azure-helper';
import * as azureApi from './azure-got-wrapper';
import * as hostRules from '../../util/host-rules';
import { appSlug } from '../../config/app-strings';
import GitStorage, { StatusResult, File } from '../git/storage';
import { logger } from '../../logger';
import {
PlatformConfig,
RepoParams,
RepoConfig,
Pr,
Issue,
VulnerabilityAlert,
} from '../common';
import { sanitize } from '../../util/sanitize';
import { smartTruncate } from '../utils/pr-body';
interface Config {
storage: GitStorage;
repoForceRebase: boolean;
mergeMethod: GitPullRequestMergeStrategy;
baseCommitSHA: string | undefined;
baseBranch: string;
defaultBranch: string;
owner: string;
repoId: string;
azureWorkItemId: any;
prList: null;
fileList: null;
repository: string;
}
let config: Config = {} as any;
const defaults: any = {
hostType: 'azure',
};
export function initPlatform({
endpoint,
token,
}: {
endpoint: string;
token: string;
}): PlatformConfig {
if (!endpoint) {
throw new Error('Init: You must configure an Azure DevOps endpoint');
}
if (!token) {
throw new Error('Init: You must configure an Azure DevOps token');
}
// TODO: Add a connection check that endpoint/token combination are valid
const res = {
endpoint: endpoint.replace(/\/?$/, '/'), // always add a trailing slash
};
defaults.endpoint = res.endpoint;
azureApi.setEndpoint(res.endpoint);
const platformConfig: PlatformConfig = {
endpoint: defaults.endpoint,
};
return platformConfig;
}
export async function getRepos(): Promise<string[]> {
logger.info('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.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('disabled');
}
}
config.storage = new GitStorage();
const [projectName, repoName] = repository.split('/');
const opts = hostRules.find({
hostType: defaults.hostType,
url: defaults.endpoint,
});
const url =
defaults.endpoint.replace('https://', `https://token:${opts.token}@`) +
`${encodeURIComponent(projectName)}/_git/${encodeURIComponent(repoName)}`;
await config.storage.initRepo({
...config,
localDir,
url,
});
const repoConfig: RepoConfig = {
baseBranch: config.baseBranch,
isFork: false,
};
return repoConfig;
}
export function getRepoForceRebase(): boolean {
return false;
}
// Search
export /* istanbul ignore next */ function getFileList(
branchName: string
): Promise<string[]> {
return config.storage.getFileList(branchName);
}
export /* istanbul ignore next */ async function setBaseBranch(
branchName = config.baseBranch
): Promise<void> {
logger.debug(`Setting baseBranch to ${branchName}`);
config.baseBranch = branchName;
delete config.baseCommitSHA;
delete config.fileList;
await config.storage.setBaseBranch(branchName);
await getFileList(branchName);
}
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 getPr(pullRequestId: number): Promise<Pr | null> {
logger.debug(`getPr(${pullRequestId})`);
if (!pullRequestId) {
return null;
}
const azureApiGit = await azureApi.gitApi();
const prs = await azureApiGit.getPullRequests(config.repoId, { status: 4 });
const azurePr: any = prs.find(item => item.pullRequestId === pullRequestId);
if (!azurePr) {
return null;
}
const labels = await azureApiGit.getPullRequestLabels(
config.repoId,
pullRequestId
);
azurePr.labels = labels
.filter(label => label.active)
.map(label => label.name);
logger.debug(`pr: (${azurePr})`);
const pr = azureHelper.getRenovatePRFormat(azurePr);
return pr;
}
export async function findPr(
branchName: string,
prTitle: string | null,
state = 'all'
): Promise<Pr | null> {
logger.debug(`findPr(${branchName}, ${prTitle}, ${state})`);
// TODO: fix typing
let prsFiltered: any[] = [];
try {
const azureApiGit = await azureApi.gitApi();
const prs = await azureApiGit.getPullRequests(config.repoId, { status: 4 });
prsFiltered = prs.filter(
item => item.sourceRefName === azureHelper.getNewBranchName(branchName)
);
if (prTitle) {
prsFiltered = prsFiltered.filter(item => item.title === prTitle);
}
// update format
prsFiltered = prsFiltered.map(item =>
azureHelper.getRenovatePRFormat(item)
);
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 (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, null, 'open');
return existingPr ? getPr(existingPr.pullRequestId) : 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 commitFilesToBranch(
branchName: string,
files: File[],
message: string,
parentBranch = config.baseBranch
): Promise<void> {
return config.storage.commitFilesToBranch(
branchName,
files,
message,
parentBranch
);
}
export /* istanbul ignore next */ function getCommitMessages(): Promise<
string[]
> {
return config.storage.getCommitMessages();
}
export function getPrList(): Pr[] {
return [];
}
export async function getBranchStatusCheck(
branchName: string,
context?: string
): Promise<string> {
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 'success';
}
return 'pending';
}
export async function getBranchStatus(
branchName: string,
requiredStatusChecks: any
): Promise<string> {
logger.debug(`getBranchStatus(${branchName})`);
if (!requiredStatusChecks) {
// null means disable status checks, so it always succeeds
return 'success';
}
if (requiredStatusChecks.length) {
// This is Unsupported
logger.warn({ requiredStatusChecks }, `Unsupported requiredStatusChecks`);
return 'failed';
}
const branchStatusCheck = await getBranchStatusCheck(branchName);
return branchStatusCheck;
}
export async function createPr(
branchName: string,
title: string,
body: string,
labels: string[],
useDefaultBranch?: boolean,
platformOptions: any = {}
): 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: any = 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!
);
}
// TODO: fixme
await labels.forEach(async label => {
await azureApiGit.createPullRequestLabel(
{
name: label,
},
config.repoId,
pr.pullRequestId!
);
});
pr.branchName = branchName;
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: any = {
title,
};
if (body) {
objToUpdate.description = azureHelper.max4000Chars(sanitize(body));
}
await azureApiGit.updatePullRequest(objToUpdate, config.repoId, prNo);
}
export async function ensureComment(
issueNo: number,
topic: string | null,
content: string
): Promise<void> {
logger.debug(`ensureComment(${issueNo}, ${topic}, content)`);
const body = `### ${topic}\n\n${sanitize(content)}`;
const azureApiGit = await azureApi.gitApi();
await azureApiGit.createThread(
{
comments: [{ content: body, commentType: 1, parentCommentId: 0 }],
status: 1,
},
config.repoId,
issueNo
);
}
export async function ensureCommentRemoval(
issueNo: number,
topic: string
): Promise<void> {
logger.debug(`ensureCommentRemoval(issueNo, topic)(${issueNo}, ${topic})`);
if (issueNo) {
const azureApiGit = await azureApi.gitApi();
const threads = await azureApiGit.getThreads(config.repoId, issueNo);
let threadIdFound = null;
threads.forEach(thread => {
if (thread.comments![0].content!.startsWith(`### ${topic}\n\n`)) {
threadIdFound = thread.id;
}
});
if (threadIdFound) {
await azureApiGit.updateThread(
{
status: 4, // close
},
config.repoId,
issueNo,
threadIdFound
);
}
}
}
export function setBranchStatus(
branchName: string,
context: string,
description: string,
state: string,
targetUrl: string
): void {
logger.debug(
`setBranchStatus(${branchName}, ${context}, ${description}, ${state}, ${targetUrl}) - Not supported by Azure DevOps (yet!)`
);
}
export async function mergePr(pr: number): Promise<void> {
logger.info(`mergePr(pr)(${pr}) - Not supported by Azure DevOps (yet!)`);
await null;
}
export function getPrBody(input: string): string {
// Remove any HTML we use
return smartTruncate(input, 4000)
.replace(new RegExp(`\n---\n\n.*?<!-- ${appSlug}-rebase -->.*?\n`), '')
.replace('<summary>', '**')
.replace('</summary>', '**')
.replace('<details>', '')
.replace('</details>', '');
}
export /* istanbul ignore next */ function findIssue(): Issue | null {
logger.warn(`findIssue() is not implemented`);
return null;
}
export /* istanbul ignore next */ function ensureIssue(): void {
logger.warn(`ensureIssue() is not implemented`);
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
export /* istanbul ignore next */ function ensureIssueClosing(): void {}
export /* istanbul ignore next */ function getIssueList(): Issue[] {
logger.debug(`getIssueList()`);
// TODO: Needs implementation
return [];
}
/**
*
* @param {number} issueNo
* @param {string[]} assignees
*/
export async function addAssignees(
issueNo: number,
assignees: string[]
): Promise<void> {
logger.trace(`addAssignees(${issueNo}, ${assignees})`);
await ensureComment(
issueNo,
'Add Assignees',
assignees.map(a => `@<${a}>`).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 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: any[] = [];
members.forEach(listMembers => {
listMembers.forEach(m => {
reviewers.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 => {
reviewers.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 });
}
}
});
});
await Promise.all(
ids.map(async obj => {
await azureApiGit.createPullRequestReviewer(
{},
config.repoId,
prNo,
obj.id
);
logger.info(`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);
}
// to become async?
export function getPrFiles(prNo: number): string[] {
logger.info(
`getPrFiles(prNo)(${prNo}) - Not supported by Azure DevOps (yet!)`
);
return [];
}
export function getVulnerabilityAlerts(): VulnerabilityAlert[] {
return [];
}
export function cleanRepo(): void {
// istanbul ignore if
if (config.storage && config.storage.cleanRepo) {
config.storage.cleanRepo();
}
config = {} as any;
}