/
index.ts
1079 lines (956 loc) · 30.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
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
import url, { URLSearchParams } from 'url';
import delay from 'delay';
import { RenovateConfig } from '../../config/common';
import {
REPOSITORY_CHANGED,
REPOSITORY_DISABLED,
REPOSITORY_NOT_FOUND,
} from '../../constants/error-messages';
import { PLATFORM_TYPE_BITBUCKET_SERVER } from '../../constants/platforms';
import { PR_STATE_ALL, PR_STATE_OPEN } from '../../constants/pull-requests';
import { logger } from '../../logger';
import { BranchStatus } from '../../types';
import * as git from '../../util/git';
import * as hostRules from '../../util/host-rules';
import { HttpResponse } from '../../util/http';
import {
BitbucketServerHttp,
setBaseUrl,
} from '../../util/http/bitbucket-server';
import { sanitize } from '../../util/sanitize';
import { ensureTrailingSlash } from '../../util/url';
import {
BranchStatusConfig,
CommitFilesConfig,
CreatePRConfig,
EnsureCommentConfig,
EnsureCommentRemovalConfig,
EnsureIssueConfig,
EnsureIssueResult,
FindPRConfig,
Issue,
PlatformConfig,
Pr,
RepoConfig,
RepoParams,
VulnerabilityAlert,
} from '../common';
import { smartTruncate } from '../utils/pr-body';
import { BbbsRestPr, BbsConfig, BbsPr, BbsRestUserRef } from './types';
import * as utils from './utils';
import { PartialDeep } from 'type-fest';
/*
* Version: 5.3 (EOL Date: 15 Aug 2019)
* See following docs for api information:
* https://docs.atlassian.com/bitbucket-server/rest/5.3.0/bitbucket-rest.html
* https://docs.atlassian.com/bitbucket-server/rest/5.3.0/bitbucket-build-rest.html
*
* See following page for uptodate supported versions
* https://confluence.atlassian.com/support/atlassian-support-end-of-life-policy-201851003.html#AtlassianSupportEndofLifePolicy-BitbucketServer
*/
let config: BbsConfig = {} as any;
const bitbucketServerHttp = new BitbucketServerHttp();
const defaults: any = {
hostType: PLATFORM_TYPE_BITBUCKET_SERVER,
};
/* istanbul ignore next */
function updatePrVersion(pr: number, version: number): number {
const res = Math.max(config.prVersions.get(pr) || 0, version);
config.prVersions.set(pr, res);
return res;
}
export function initPlatform({
endpoint,
username,
password,
}: RenovateConfig): Promise<PlatformConfig> {
if (!endpoint) {
throw new Error('Init: You must configure a Bitbucket Server endpoint');
}
if (!(username && password)) {
throw new Error(
'Init: You must configure a Bitbucket Server username/password'
);
}
// TODO: Add a connection check that endpoint/username/password combination are valid
defaults.endpoint = ensureTrailingSlash(endpoint);
setBaseUrl(defaults.endpoint);
const platformConfig: PlatformConfig = {
endpoint: defaults.endpoint,
};
return Promise.resolve(platformConfig);
}
// Get all repositories that the user has access to
export async function getRepos(): Promise<string[]> {
logger.debug('Autodiscovering Bitbucket Server repositories');
try {
const repos = await utils.accumulateValues(
`./rest/api/1.0/repos?permission=REPO_WRITE&state=AVAILABLE`
);
const result = repos.map(
(r: { project: { key: string }; slug: string }) =>
`${r.project.key.toLowerCase()}/${r.slug}`
);
logger.debug({ result }, 'result of getRepos()');
return result;
} catch (err) /* istanbul ignore next */ {
logger.error({ err }, `bitbucket getRepos error`);
throw err;
}
}
// Initialize GitLab by getting base branch
export async function initRepo({
repository,
localDir,
optimizeForDisabled,
bbUseDefaultReviewers,
}: RepoParams): Promise<RepoConfig> {
logger.debug(
`initRepo("${JSON.stringify({ repository, localDir }, null, 2)}")`
);
const opts = hostRules.find({
hostType: defaults.hostType,
url: defaults.endpoint,
});
const [projectKey, repositorySlug] = repository.split('/');
if (optimizeForDisabled) {
interface RenovateConfig {
enabled: boolean;
}
interface FileData {
isLastPage: boolean;
lines: string[];
size: number;
}
let renovateConfig: RenovateConfig;
try {
const { body } = await bitbucketServerHttp.getJson<FileData>(
`./rest/api/1.0/projects/${projectKey}/repos/${repositorySlug}/browse/renovate.json?limit=20000`
);
if (!body.isLastPage) {
logger.warn('Renovate config to big: ' + body.size);
} else {
renovateConfig = JSON.parse(body.lines.join());
}
} catch {
// Do nothing
}
if (renovateConfig && renovateConfig.enabled === false) {
throw new Error(REPOSITORY_DISABLED);
}
}
config = {
projectKey,
repositorySlug,
repository,
prVersions: new Map<number, number>(),
username: opts.username,
} as any;
/* istanbul ignore else */
if (bbUseDefaultReviewers !== false) {
logger.debug('Enable bitbucket default reviewer');
config.bbUseDefaultReviewers = true;
}
const { host, pathname } = url.parse(defaults.endpoint!);
const gitUrl = git.getUrl({
protocol: defaults.endpoint!.split(':')[0],
auth: `${opts.username}:${opts.password}`,
host: `${host}${pathname}${
pathname.endsWith('/') ? '' : /* istanbul ignore next */ '/'
}scm`,
repository,
});
await git.initRepo({
...config,
localDir,
url: gitUrl,
gitAuthorName: global.gitAuthor?.name,
gitAuthorEmail: global.gitAuthor?.email,
});
try {
const info = (
await bitbucketServerHttp.getJson<{
project: { key: string };
parent: string;
}>(
`./rest/api/1.0/projects/${config.projectKey}/repos/${config.repositorySlug}`
)
).body;
config.owner = info.project.key;
logger.debug(`${repository} owner = ${config.owner}`);
config.defaultBranch = (
await bitbucketServerHttp.getJson<{ displayId: string }>(
`./rest/api/1.0/projects/${config.projectKey}/repos/${config.repositorySlug}/branches/default`
)
).body.displayId;
config.baseBranch = config.defaultBranch;
config.mergeMethod = 'merge';
const repoConfig: RepoConfig = {
baseBranch: config.baseBranch,
isFork: !!info.parent,
};
return repoConfig;
} catch (err) /* istanbul ignore next */ {
logger.debug(err);
if (err.statusCode === 404) {
throw new Error(REPOSITORY_NOT_FOUND);
}
logger.debug({ err }, 'Unknown Bitbucket initRepo error');
throw err;
}
}
export async function getRepoForceRebase(): Promise<boolean> {
logger.debug(`getRepoForceRebase()`);
// https://docs.atlassian.com/bitbucket-server/rest/7.0.1/bitbucket-rest.html#idp342
const res = await bitbucketServerHttp.getJson<{
mergeConfig: { defaultStrategy: { id: string } };
}>(
`./rest/api/1.0/projects/${config.projectKey}/repos/${config.repositorySlug}/settings/pull-requests`
);
// If the default merge strategy contains `ff-only` the PR can only be merged
// if it is up to date with the base branch.
// The current options for id are:
// no-ff, ff, ff-only, rebase-no-ff, rebase-ff-only, squash, squash-ff-only
return Boolean(
res.body.mergeConfig &&
res.body.mergeConfig.defaultStrategy &&
res.body.mergeConfig.defaultStrategy.id.includes('ff-only')
);
}
export async function setBaseBranch(
branchName: string = config.defaultBranch
): Promise<string> {
config.baseBranch = branchName;
const baseBranchSha = await git.setBaseBranch(branchName);
return baseBranchSha;
}
export /* istanbul ignore next */ function setBranchPrefix(
branchPrefix: string
): Promise<void> {
return git.setBranchPrefix(branchPrefix);
}
// Search
// Get full file list
export function getFileList(): Promise<string[]> {
return git.getFileList();
}
// Branch
// Returns true if branch exists, otherwise false
export function branchExists(branchName: string): Promise<boolean> {
logger.debug(`branchExists(${branchName})`);
return git.branchExists(branchName);
}
export function isBranchStale(branchName: string): Promise<boolean> {
logger.debug(`isBranchStale(${branchName})`);
return git.isBranchStale(branchName);
}
// Gets details for a PR
export async function getPr(
prNo: number,
refreshCache?: boolean
): Promise<BbsPr | null> {
logger.debug(`getPr(${prNo})`);
if (!prNo) {
return null;
}
const res = await bitbucketServerHttp.getJson<BbbsRestPr>(
`./rest/api/1.0/projects/${config.projectKey}/repos/${config.repositorySlug}/pull-requests/${prNo}`,
{ useCache: !refreshCache }
);
const pr: BbsPr = {
displayNumber: `Pull Request #${res.body.id}`,
...utils.prInfo(res.body),
reviewers: res.body.reviewers.map((r) => r.user.name),
isModified: false,
};
pr.version = updatePrVersion(pr.number, pr.version);
if (pr.state === PR_STATE_OPEN) {
const mergeRes = await bitbucketServerHttp.getJson<{
conflicted: string;
canMerge: string;
}>(
`./rest/api/1.0/projects/${config.projectKey}/repos/${config.repositorySlug}/pull-requests/${prNo}/merge`,
{ useCache: !refreshCache }
);
pr.isConflicted = !!mergeRes.body.conflicted;
pr.canMerge = !!mergeRes.body.canMerge;
const prCommits = (
await bitbucketServerHttp.getJson<{
totalCount: number;
values: { author: { emailAddress: string } }[];
}>(
`./rest/api/1.0/projects/${config.projectKey}/repos/${config.repositorySlug}/pull-requests/${prNo}/commits?withCounts=true`,
{ useCache: !refreshCache }
)
).body;
if (prCommits.totalCount === 1) {
if (global.gitAuthor) {
const commitAuthorEmail = prCommits.values[0].author.emailAddress;
if (commitAuthorEmail !== global.gitAuthor.email) {
logger.debug(
{ prNo },
'PR is modified: 1 commit but not by configured gitAuthor'
);
pr.isModified = true;
}
}
} else {
logger.debug(
{ prNo },
`PR is modified: Found ${prCommits.totalCount} commits`
);
pr.isModified = true;
}
}
if (await branchExists(pr.branchName)) {
pr.isStale = await isBranchStale(pr.branchName);
}
return pr;
}
// TODO: coverage
// istanbul ignore next
function matchesState(state: string, desiredState: string): boolean {
if (desiredState === PR_STATE_ALL) {
return true;
}
if (desiredState.startsWith('!')) {
return state !== desiredState.substring(1);
}
return state === desiredState;
}
// TODO: coverage
// istanbul ignore next
const isRelevantPr = (
branchName: string,
prTitle: string | null | undefined,
state: string
) => (p: Pr): boolean =>
p.branchName === branchName &&
(!prTitle || p.title === prTitle) &&
matchesState(p.state, state);
// TODO: coverage
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export async function getPrList(_args?: any): Promise<Pr[]> {
logger.debug(`getPrList()`);
// istanbul ignore next
if (!config.prList) {
const query = new URLSearchParams({
state: 'ALL',
'role.1': 'AUTHOR',
'username.1': config.username,
}).toString();
const values = await utils.accumulateValues(
`./rest/api/1.0/projects/${config.projectKey}/repos/${config.repositorySlug}/pull-requests?${query}`
);
config.prList = values.map(utils.prInfo);
logger.debug({ length: config.prList.length }, 'Retrieved Pull Requests');
} else {
logger.debug('returning cached PR list');
}
return config.prList;
}
/* istanbul ignore next */
export async function getPrFiles(pr: Pr): Promise<string[]> {
return git.getBranchFiles(pr.branchName, pr.targetBranch);
}
// TODO: coverage
// istanbul ignore next
export async function findPr({
branchName,
prTitle,
state = PR_STATE_ALL,
refreshCache,
}: FindPRConfig): Promise<Pr | null> {
logger.debug(`findPr(${branchName}, "${prTitle}", "${state}")`);
const prList = await getPrList({ refreshCache });
const pr = prList.find(isRelevantPr(branchName, prTitle, state));
if (pr) {
logger.debug(`Found PR #${pr.number}`);
} else {
logger.debug(`DID NOT Found PR from branch #${branchName}`);
}
return pr;
}
// Returns the Pull Request for a branch. Null if not exists.
export async function getBranchPr(
branchName: string,
refreshCache?: boolean
): Promise<BbsPr | null> {
logger.debug(`getBranchPr(${branchName})`);
const existingPr = await findPr({
branchName,
state: PR_STATE_OPEN,
});
return existingPr ? getPr(existingPr.number, refreshCache) : null;
}
export function getAllRenovateBranches(
branchPrefix: string
): Promise<string[]> {
logger.debug('getAllRenovateBranches');
return git.getAllRenovateBranches(branchPrefix);
}
export async function commitFiles(
commitFilesConfig: CommitFilesConfig
): Promise<string | null> {
const commit = git.commitFiles(commitFilesConfig);
// wait for pr change propagation
await delay(1000);
// refresh cache
await getBranchPr(commitFilesConfig.branchName, true);
return commit;
}
export function getFile(filePath: string, branchName: string): Promise<string> {
logger.debug(`getFile(${filePath}, ${branchName})`);
return git.getFile(filePath, branchName);
}
export async function deleteBranch(
branchName: string,
closePr = false
): Promise<void> {
logger.debug(`deleteBranch(${branchName}, closePr=${closePr})`);
// TODO: coverage
// istanbul ignore next
if (closePr) {
// getBranchPr
const pr = await getBranchPr(branchName);
if (pr) {
const { body } = await bitbucketServerHttp.postJson<{ version: number }>(
`./rest/api/1.0/projects/${config.projectKey}/repos/${config.repositorySlug}/pull-requests/${pr.number}/decline?version=${pr.version}`
);
updatePrVersion(pr.number, body.version);
}
}
return git.deleteBranch(branchName);
}
export function mergeBranch(branchName: string): Promise<void> {
logger.debug(`mergeBranch(${branchName})`);
return git.mergeBranch(branchName);
}
export function getBranchLastCommitTime(branchName: string): Promise<Date> {
logger.debug(`getBranchLastCommitTime(${branchName})`);
return git.getBranchLastCommitTime(branchName);
}
export /* istanbul ignore next */ function getRepoStatus(): Promise<
git.StatusResult
> {
return git.getRepoStatus();
}
async function getStatus(
branchName: string,
useCache = true
): Promise<utils.BitbucketCommitStatus> {
const branchCommit = await git.getBranchCommit(branchName);
return (
await bitbucketServerHttp.getJson<utils.BitbucketCommitStatus>(
`./rest/build-status/1.0/commits/stats/${branchCommit}`,
{
useCache,
}
)
).body;
}
// Returns the combined status for a branch.
// umbrella for status checks
// https://docs.atlassian.com/bitbucket-server/rest/6.0.0/bitbucket-build-rest.html#idp2
export async function getBranchStatus(
branchName: string,
requiredStatusChecks?: string[] | null
): Promise<BranchStatus> {
logger.debug(
`getBranchStatus(${branchName}, requiredStatusChecks=${!!requiredStatusChecks})`
);
if (!requiredStatusChecks) {
// null means disable status checks, so it always succeeds
logger.debug('Status checks disabled = returning "success"');
return BranchStatus.green;
}
if (!(await branchExists(branchName))) {
throw new Error(REPOSITORY_CHANGED);
}
try {
const commitStatus = await getStatus(branchName);
logger.debug({ commitStatus }, 'branch status check result');
if (commitStatus.failed > 0) {
return BranchStatus.red;
}
if (commitStatus.inProgress > 0) {
return BranchStatus.yellow;
}
return commitStatus.successful > 0
? BranchStatus.green
: BranchStatus.yellow;
} catch (err) {
logger.warn({ err }, `Failed to get branch status`);
return BranchStatus.red;
}
}
async function getStatusCheck(
branchName: string,
useCache = true
): Promise<utils.BitbucketStatus[]> {
const branchCommit = await git.getBranchCommit(branchName);
return utils.accumulateValues(
`./rest/build-status/1.0/commits/${branchCommit}`,
'get',
{ useCache }
);
}
// https://docs.atlassian.com/bitbucket-server/rest/6.0.0/bitbucket-build-rest.html#idp2
export async function getBranchStatusCheck(
branchName: string,
context: string
): Promise<BranchStatus | null> {
logger.debug(`getBranchStatusCheck(${branchName}, context=${context})`);
try {
const states = await getStatusCheck(branchName);
for (const state of states) {
if (state.key === context) {
switch (state.state) {
case 'SUCCESSFUL':
return BranchStatus.green;
case 'INPROGRESS':
return BranchStatus.yellow;
case 'FAILED':
default:
return BranchStatus.red;
}
}
}
} catch (err) {
logger.warn({ err }, `Failed to check branch status`);
}
return null;
}
export async function setBranchStatus({
branchName,
context,
description,
state,
url: targetUrl,
}: BranchStatusConfig): Promise<void> {
logger.debug(`setBranchStatus(${branchName})`);
const existingStatus = await getBranchStatusCheck(branchName, context);
if (existingStatus === state) {
return;
}
logger.debug({ branch: branchName, context, state }, 'Setting branch status');
const branchCommit = await git.getBranchCommit(branchName);
try {
const body: any = {
key: context,
description,
url: targetUrl || 'https://renovatebot.com',
};
switch (state) {
case BranchStatus.green:
body.state = 'SUCCESSFUL';
break;
case BranchStatus.yellow:
body.state = 'INPROGRESS';
break;
case BranchStatus.red:
default:
body.state = 'FAILED';
break;
}
await bitbucketServerHttp.postJson(
`./rest/build-status/1.0/commits/${branchCommit}`,
{ body }
);
// update status cache
await getStatus(branchName, false);
await getStatusCheck(branchName, false);
} catch (err) {
logger.warn({ err }, `Failed to set branch status`);
}
}
// Issue
// function getIssueList() {
// logger.debug(`getIssueList()`);
// // TODO: Needs implementation
// // This is used by Renovate when creating its own issues, e.g. for deprecated package warnings, config error notifications, or "masterIssue"
// // BB Server doesnt have issues
// return [];
// }
export /* istanbul ignore next */ function findIssue(
title: string
): Promise<Issue | null> {
logger.debug(`findIssue(${title})`);
// TODO: Needs implementation
// This is used by Renovate when creating its own issues, e.g. for deprecated package warnings, config error notifications, or "masterIssue"
// BB Server doesnt have issues
return null;
}
export /* istanbul ignore next */ function ensureIssue({
title,
}: EnsureIssueConfig): Promise<EnsureIssueResult | null> {
logger.warn({ title }, 'Cannot ensure issue');
// TODO: Needs implementation
// This is used by Renovate when creating its own issues, e.g. for deprecated package warnings, config error notifications, or "masterIssue"
// BB Server doesnt have issues
return null;
}
export /* istanbul ignore next */ function getIssueList(): Promise<Issue[]> {
logger.debug(`getIssueList()`);
// TODO: Needs implementation
return Promise.resolve([]);
}
export /* istanbul ignore next */ function ensureIssueClosing(
title: string
): Promise<void> {
logger.debug(`ensureIssueClosing(${title})`);
// TODO: Needs implementation
// This is used by Renovate when creating its own issues, e.g. for deprecated package warnings, config error notifications, or "masterIssue"
// BB Server doesnt have issues
return Promise.resolve();
}
export function addAssignees(iid: number, assignees: string[]): Promise<void> {
logger.debug(`addAssignees(${iid}, ${assignees})`);
// TODO: Needs implementation
// Currently Renovate does "Create PR" and then "Add assignee" as a two-step process, with this being the second step.
// BB Server doesnt support assignees
return Promise.resolve();
}
export async function addReviewers(
prNo: number,
reviewers: string[]
): Promise<void> {
logger.debug(`Adding reviewers ${reviewers} to #${prNo}`);
try {
const pr = await getPr(prNo);
if (!pr) {
throw new Error(REPOSITORY_NOT_FOUND);
}
const reviewersSet = new Set([...pr.reviewers, ...reviewers]);
await bitbucketServerHttp.putJson(
`./rest/api/1.0/projects/${config.projectKey}/repos/${config.repositorySlug}/pull-requests/${prNo}`,
{
body: {
title: pr.title,
version: pr.version,
reviewers: Array.from(reviewersSet).map((name) => ({
user: { name },
})),
},
}
);
await getPr(prNo, true);
} catch (err) {
if (err.statusCode === 404) {
throw new Error(REPOSITORY_NOT_FOUND);
} else if (err.statusCode === 409) {
throw new Error(REPOSITORY_CHANGED);
} else {
logger.fatal({ err }, `Failed to add reviewers ${reviewers} to #${prNo}`);
throw err;
}
}
}
export function deleteLabel(issueNo: number, label: string): Promise<void> {
logger.debug(`deleteLabel(${issueNo}, ${label})`);
// TODO: Needs implementation
// Only used for the "request Renovate to rebase a PR using a label" feature
return Promise.resolve();
}
type Comment = { text: string; id: number };
async function getComments(prNo: number): Promise<Comment[]> {
// GET /rest/api/1.0/projects/{projectKey}/repos/{repositorySlug}/pull-requests/{pullRequestId}/activities
let comments = await utils.accumulateValues(
`./rest/api/1.0/projects/${config.projectKey}/repos/${config.repositorySlug}/pull-requests/${prNo}/activities`
);
comments = comments
.filter(
(a: { action: string; commentAction: string }) =>
a.action === 'COMMENTED' && a.commentAction === 'ADDED'
)
.map((a: { comment: Comment }) => a.comment);
logger.debug(`Found ${comments.length} comments`);
return comments;
}
async function addComment(prNo: number, text: string): Promise<void> {
// POST /rest/api/1.0/projects/{projectKey}/repos/{repositorySlug}/pull-requests/{pullRequestId}/comments
await bitbucketServerHttp.postJson(
`./rest/api/1.0/projects/${config.projectKey}/repos/${config.repositorySlug}/pull-requests/${prNo}/comments`,
{
body: { text },
}
);
}
async function getCommentVersion(
prNo: number,
commentId: number
): Promise<number> {
// GET /rest/api/1.0/projects/{projectKey}/repos/{repositorySlug}/pull-requests/{pullRequestId}/comments/{commentId}
const { version } = (
await bitbucketServerHttp.getJson<{ version: number }>(
`./rest/api/1.0/projects/${config.projectKey}/repos/${config.repositorySlug}/pull-requests/${prNo}/comments/${commentId}`
)
).body;
return version;
}
async function editComment(
prNo: number,
commentId: number,
text: string
): Promise<void> {
const version = await getCommentVersion(prNo, commentId);
// PUT /rest/api/1.0/projects/{projectKey}/repos/{repositorySlug}/pull-requests/{pullRequestId}/comments/{commentId}
await bitbucketServerHttp.putJson(
`./rest/api/1.0/projects/${config.projectKey}/repos/${config.repositorySlug}/pull-requests/${prNo}/comments/${commentId}`,
{
body: { text, version },
}
);
}
async function deleteComment(prNo: number, commentId: number): Promise<void> {
const version = await getCommentVersion(prNo, commentId);
// DELETE /rest/api/1.0/projects/{projectKey}/repos/{repositorySlug}/pull-requests/{pullRequestId}/comments/{commentId}
await bitbucketServerHttp.deleteJson(
`./rest/api/1.0/projects/${config.projectKey}/repos/${config.repositorySlug}/pull-requests/${prNo}/comments/${commentId}?version=${version}`
);
}
export async function ensureComment({
number,
topic,
content,
}: EnsureCommentConfig): Promise<boolean> {
const sanitizedContent = sanitize(content);
try {
const comments = await getComments(number);
let body: string;
let commentId: number | undefined;
let commentNeedsUpdating: boolean | undefined;
if (topic) {
logger.debug(`Ensuring comment "${topic}" in #${number}`);
body = `### ${topic}\n\n${sanitizedContent}`;
comments.forEach((comment) => {
if (comment.text.startsWith(`### ${topic}\n\n`)) {
commentId = comment.id;
commentNeedsUpdating = comment.text !== body;
}
});
} else {
logger.debug(`Ensuring content-only comment in #${number}`);
body = `${sanitizedContent}`;
comments.forEach((comment) => {
if (comment.text === body) {
commentId = comment.id;
commentNeedsUpdating = false;
}
});
}
if (!commentId) {
await addComment(number, body);
logger.info(
{ repository: config.repository, prNo: number, topic },
'Comment added'
);
} else if (commentNeedsUpdating) {
await editComment(number, commentId, body);
logger.debug(
{ repository: config.repository, prNo: number },
'Comment updated'
);
} else {
logger.debug('Comment is already update-to-date');
}
return true;
} catch (err) /* istanbul ignore next */ {
logger.warn({ err }, 'Error ensuring comment');
return false;
}
}
export async function ensureCommentRemoval({
number: prNo,
topic,
content,
}: EnsureCommentRemovalConfig): Promise<void> {
try {
logger.debug(
`Ensuring comment "${topic || content}" in #${prNo} is removed`
);
const comments = await getComments(prNo);
const byTopic = (comment: Comment): boolean =>
comment.text.startsWith(`### ${topic}\n\n`);
const byContent = (comment: Comment): boolean =>
comment.text.trim() === content;
let commentId: number | null = null;
if (topic) {
commentId = comments.find(byTopic)?.id;
} else if (content) {
commentId = comments.find(byContent)?.id;
}
if (commentId) {
await deleteComment(prNo, commentId);
}
} catch (err) /* istanbul ignore next */ {
logger.warn({ err }, 'Error ensuring comment removal');
}
}
// Pull Request
const escapeHash = (input: string): string =>
input ? input.replace(/#/g, '%23') : input;
export async function createPr({
branchName,
prTitle: title,
prBody: rawDescription,
useDefaultBranch,
}: CreatePRConfig): Promise<Pr> {
const description = sanitize(rawDescription);
logger.debug(`createPr(${branchName}, title=${title})`);
const base = useDefaultBranch ? config.defaultBranch : config.baseBranch;
let reviewers: BbsRestUserRef[] = [];
/* istanbul ignore else */
if (config.bbUseDefaultReviewers) {
logger.debug(`fetching default reviewers`);
const { id } = (
await bitbucketServerHttp.getJson<{ id: number }>(
`./rest/api/1.0/projects/${config.projectKey}/repos/${config.repositorySlug}`
)
).body;
const defReviewers = (
await bitbucketServerHttp.getJson<{ name: string }[]>(
`./rest/default-reviewers/1.0/projects/${config.projectKey}/repos/${
config.repositorySlug
}/reviewers?sourceRefId=refs/heads/${escapeHash(
branchName
)}&targetRefId=refs/heads/${base}&sourceRepoId=${id}&targetRepoId=${id}`
)
).body;
reviewers = defReviewers.map((u) => ({
user: { name: u.name },
}));
}
const body: PartialDeep<BbbsRestPr> = {
title,
description,
fromRef: {
id: `refs/heads/${branchName}`,
},
toRef: {
id: `refs/heads/${base}`,
},
reviewers,
};
let prInfoRes: HttpResponse<BbbsRestPr>;
try {
prInfoRes = await bitbucketServerHttp.postJson<BbbsRestPr>(
`./rest/api/1.0/projects/${config.projectKey}/repos/${config.repositorySlug}/pull-requests`,
{ body }
);
} catch (err) /* istanbul ignore next */ {
if (
err.body &&
err.body.errors &&
err.body.errors.length &&
err.body.errors[0].exceptionName ===
'com.atlassian.bitbucket.pull.EmptyPullRequestException'
) {
logger.debug(
'Empty pull request - deleting branch so it can be recreated next run'
);
await deleteBranch(branchName);
throw new Error(REPOSITORY_CHANGED);
}
throw err;
}
const pr: BbsPr = {
displayNumber: `Pull Request #${prInfoRes.body.id}`,
isModified: false,
...utils.prInfo(prInfoRes.body),
};
updatePrVersion(pr.number, pr.version);
// istanbul ignore if
if (config.prList) {
config.prList.push(pr);
}
return pr;
}
export async function updatePr(
prNo: number,
title: string,
rawDescription: string
): Promise<void> {
const description = sanitize(rawDescription);
logger.debug(`updatePr(${prNo}, title=${title})`);
try {
const pr = await getPr(prNo);
if (!pr) {
throw Object.assign(new Error(REPOSITORY_NOT_FOUND), { statusCode: 404 });
}
const { body } = await bitbucketServerHttp.putJson<{ version: number }>(
`./rest/api/1.0/projects/${config.projectKey}/repos/${config.repositorySlug}/pull-requests/${prNo}`,
{