-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
index.js
1537 lines (1475 loc) · 43.8 KB
/
index.js
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
const is = require('@sindresorhus/is');
const addrs = require('email-addresses');
const delay = require('delay');
const URL = require('url');
const get = require('./gh-got-wrapper');
const hostRules = require('../../util/host-rules');
const Storage = require('./storage');
const GitStorage = require('../git/storage');
const {
appName,
appSlug,
configFileNames,
onboardingBranch,
urls,
} = require('../../config/app-strings');
const defaultConfigFile = configFileNames[0];
let config = {};
module.exports = {
// Initialization
getRepos,
cleanRepo,
initRepo,
getRepoStatus,
getRepoForceRebase,
setBaseBranch,
// Search
getFileList,
// Branch
branchExists,
getAllRenovateBranches,
isBranchStale,
getBranchPr,
getBranchStatus,
getBranchStatusCheck,
setBranchStatus,
deleteBranch,
mergeBranch,
getBranchLastCommitTime,
// issue
findIssue,
ensureIssue,
ensureIssueClosing,
addAssignees,
addReviewers,
deleteLabel,
// Comments
ensureComment,
ensureCommentRemoval,
// PR
getPrList,
findPr,
createPr,
getPr,
getPrFiles,
updatePr,
mergePr,
getPrBody,
// file
commitFilesToBranch,
getFile,
// Commits
getCommitMessages,
// vulnerability alerts
getVulnerabilityAlerts,
};
// istanbul ignore next
async function getRenovateUsername() {
if (!global.renovateUsername) {
try {
global.renovateUsername = (await get('user')).body.login;
} catch (err) {
if (err.message === 'integration-unauthorized') {
global.renovateUsername = 'renovate[bot]';
} else {
throw err;
}
}
}
return global.renovateUsername;
}
// Get all repositories that the user has access to
async function getRepos(token, endpoint) {
logger.info('Autodiscovering GitHub repositories');
const opts = hostRules.find({ platform: 'github' }, { token, endpoint });
if (!opts.token) {
throw new Error('No token found for getRepos');
}
hostRules.update({ ...opts, platform: 'github', default: true });
try {
const res = await get('user/repos', { paginate: true });
return res.body.map(repo => repo.full_name);
} catch (err) /* istanbul ignore next */ {
logger.error({ err }, `GitHub getRepos error`);
throw err;
}
}
function cleanRepo() {
// istanbul ignore if
if (config.storage) {
config.storage.cleanRepo();
}
// In theory most of this isn't necessary. In practice..
get.reset();
config = {};
}
// Initialize GitHub by getting base branch and SHA
async function initRepo({
repository,
token,
endpoint,
forkMode,
forkToken,
mirrorMode,
gitAuthor,
gitPrivateKey,
gitFs,
localDir,
includeForks,
}) {
logger.debug(`initRepo("${repository}")`);
const opts = hostRules.find({ platform: 'github' }, { token, endpoint });
if (!opts.token) {
throw new Error(`No token found for GitHub repository ${repository}`);
}
hostRules.update({ ...opts, platform: 'github', default: true });
logger.info('Authenticated as user: ' + (await getRenovateUsername()));
logger.info('Using renovate version: ' + global.renovateVersion);
// config is used by the platform api itself, not necessary for the app layer to know
cleanRepo();
config.isGhe = endpoint && !endpoint.startsWith('https://api.github.com');
config.localDir = localDir;
config.platform = 'github';
config.repository = repository;
[config.repositoryOwner, config.repositoryName] = repository.split('/');
if (gitAuthor) {
try {
config.gitAuthor = addrs.parseOneAddress(gitAuthor);
} catch (err) /* istanbul ignore next */ {
logger.error(
{ gitAuthor, err, message: err.message },
'Invalid gitAuthor'
);
throw new Error('Invalid gitAuthor');
}
}
config.gitPrivateKey = gitPrivateKey;
// platformConfig is passed back to the app layer and contains info about the platform they require
const platformConfig = {};
let res;
try {
res = await get(`repos/${repository}`);
logger.trace({ repositoryDetails: res.body }, 'Repository details');
// istanbul ignore if
if (res.body.fork && gitFs && !includeForks) {
try {
const renovateConfig = JSON.parse(
Buffer.from(
(await get(
`repos/${config.repository}/contents/${defaultConfigFile}`
)).body.content,
'base64'
).toString()
);
if (!renovateConfig.includeForks) {
throw new Error();
}
} catch (err) {
throw new Error('fork');
}
}
// istanbul ignore if
if (res.body.full_name && res.body.full_name !== repository) {
logger.info(
{ repository, this_repository: res.body.full_name },
'Repository has been renamed'
);
throw new Error('renamed');
}
if (res.body.archived) {
logger.info(
'Repository is archived - throwing error to abort renovation'
);
throw new Error('archived');
}
platformConfig.privateRepo = res.body.private === true;
platformConfig.isFork = res.body.fork === true;
const owner = res.body.owner.login;
logger.debug(`${repository} owner = ${owner}`);
// Use default branch as PR target unless later overridden.
config.defaultBranch = res.body.default_branch;
// Base branch may be configured but defaultBranch is always fixed
config.baseBranch = config.defaultBranch;
logger.debug(`${repository} default branch = ${config.baseBranch}`);
// GitHub allows administrators to block certain types of merge, so we need to check it
if (res.body.allow_rebase_merge) {
config.mergeMethod = 'rebase';
} else if (res.body.allow_squash_merge) {
config.mergeMethod = 'squash';
} else if (res.body.allow_merge_commit) {
config.mergeMethod = 'merge';
} else {
// This happens if we don't have Administrator read access, it is not a critical error
logger.info('Could not find allowed merge methods for repo');
}
} catch (err) /* istanbul ignore next */ {
logger.debug('Caught initRepo error');
if (err.message === 'archived' || err.message === 'renamed') {
throw err;
}
if (err.statusCode === 403) {
throw new Error('forbidden');
}
if (err.statusCode === 404) {
throw new Error('not-found');
}
if (err.message.startsWith('Repository access blocked')) {
throw new Error('blocked');
}
if (err.message === 'fork') {
throw err;
}
logger.info({ err }, 'Unknown GitHub initRepo error');
throw err;
}
// This shouldn't be necessary, but occasional strange errors happened until it was added
config.issueList = null;
config.prList = null;
config.openPrList = null;
config.closedPrList = null;
config.storage = new Storage();
await config.storage.initRepo(config);
if (forkMode) {
logger.info('Bot is in forkMode');
config.forkToken = forkToken;
// Save parent SHA then delete
const parentSha = await getBaseCommitSHA();
config.baseCommitSHA = null;
// save parent name then delete
config.parentRepo = config.repository;
config.repository = null;
// Get list of existing repos
const existingRepos = (await get('user/repos?per_page=100', {
token: forkToken || opts.token,
paginate: true,
})).body.map(r => r.full_name);
try {
config.repository = (await get.post(`repos/${repository}/forks`, {
token: forkToken || opts.token,
})).body.full_name;
} catch (err) /* istanbul ignore next */ {
logger.info({ err }, 'Error forking repository');
throw new Error('cannot-fork');
}
if (existingRepos.includes(config.repository)) {
logger.info(
{ repository_fork: config.repository },
'Found existing fork'
);
// Need to update base branch
logger.debug(
{ baseBranch: config.baseBranch, parentSha },
'Setting baseBranch ref in fork'
);
// This is a lovely "hack" by GitHub that lets us force update our fork's master
// with the base commit from the parent repository
try {
await get.patch(
`repos/${config.repository}/git/refs/heads/${config.baseBranch}`,
{
body: {
sha: parentSha,
force: true,
},
token: forkToken || opts.token,
}
);
} catch (err) /* istanbul ignore next */ {
if (
err.statusCode === 422 &&
err.message.startsWith('Object does not exist')
) {
throw new Error('repository-changed');
}
}
} else {
logger.info({ repository_fork: config.repository }, 'Created fork');
// Wait an arbitrary 30s to hopefully give GitHub enough time for forking to complete
await delay(30000);
}
await config.storage.initRepo(config);
}
// istanbul ignore if
if (mirrorMode) {
logger.info('Bot is in mirrorMode');
config.mirrorMode = true;
const parentRepo = res.body.parent.full_name;
logger.debug('Parent repo is ' + parentRepo);
const parentDefaultBranch = (await get(`repos/${repository}`)).body
.default_branch;
logger.debug('Parent default branch is ' + parentDefaultBranch);
const parentSha = (await get(
`repos/${parentRepo}/git/refs/heads/${parentDefaultBranch}`
)).body.object.sha;
logger.debug('Parent sha is ' + parentSha);
// This is a lovely "hack" by GitHub that lets us force update our fork's master
// with the base commit from the parent repository
config.baseCommitSha = await getBaseCommitSHA();
if (parentSha !== config.baseCommitSHA) {
logger.info('Updating fork default branch');
await get.patch(
`repos/${config.repository}/git/refs/heads/${config.baseBranch}`,
{
body: {
sha: parentSha,
force: true,
},
}
);
}
if (!(await branchExists('renovate-config'))) {
await config.storage.createBranch(
'renovate-config',
config.baseCommitSHA
);
}
}
// istanbul ignore if
if (gitFs) {
logger.debug('Enabling Git FS');
let { host } = URL.parse(opts.endpoint);
if (host === 'api.github.com') {
host = null;
}
host = host || 'github.com';
const url = GitStorage.getUrl({
gitFs,
auth:
config.forkToken ||
(global.appMode ? `x-access-token:${opts.token}` : opts.token),
hostname: host,
repository,
});
config.storage = new GitStorage();
await config.storage.initRepo({
...config,
url,
});
}
return platformConfig;
}
async function getRepoForceRebase() {
if (config.repoForceRebase === undefined) {
try {
config.repoForceRebase = false;
const branchProtection = await getBranchProtection(config.baseBranch);
logger.debug('Found branch protection');
if (branchProtection.required_pull_request_reviews) {
logger.debug(
'Branch protection: PR Reviews are required before merging'
);
config.prReviewsRequired = true;
}
if (branchProtection.required_status_checks) {
if (branchProtection.required_status_checks.strict) {
logger.debug(
'Branch protection: PRs must be up-to-date before merging'
);
config.repoForceRebase = true;
}
}
if (branchProtection.restrictions) {
logger.debug(
{
users: branchProtection.restrictions.users,
teams: branchProtection.restrictions.teams,
},
'Branch protection: Pushing to branch is restricted'
);
config.pushProtection = true;
}
} catch (err) {
if (err.statusCode === 404) {
logger.debug(`No branch protection found`);
} else if (err.statusCode === 403) {
logger.debug(
'Branch protection: Do not have permissions to detect branch protection'
);
} else {
throw err;
}
}
}
return config.repoForceRebase;
}
async function getBaseCommitSHA() {
if (!config.baseCommitSHA) {
config.baseCommitSHA = await config.storage.getBranchCommit(
config.baseBranch
);
}
return config.baseCommitSHA;
}
async function getBranchProtection(branchName) {
// istanbul ignore if
if (config.parentRepo) {
return {};
}
const res = await get(
`repos/${config.repository}/branches/${branchName}/protection`
);
return res.body;
}
async function setBaseBranch(branchName) {
if (branchName) {
logger.debug(`Setting baseBranch to ${branchName}`);
config.baseBranch = branchName;
config.baseCommitSHA = null;
config.storage.setBaseBranch(branchName);
await getFileList(branchName);
}
}
// Search
// Get full file list
function getFileList(branchName = config.baseBranch) {
return config.storage.getFileList(branchName);
}
// Branch
// Returns true if branch exists, otherwise false
function branchExists(branchName) {
return config.storage.branchExists(branchName);
}
function getAllRenovateBranches(branchPrefix) {
return config.storage.getAllRenovateBranches(branchPrefix);
}
function isBranchStale(branchName) {
return config.storage.isBranchStale(branchName);
}
function getFile(filePath, branchName) {
return config.storage.getFile(filePath, branchName);
}
function deleteBranch(branchName) {
return config.storage.deleteBranch(branchName);
}
function getBranchLastCommitTime(branchName) {
return config.storage.getBranchLastCommitTime(branchName);
}
// istanbul ignore next
function getRepoStatus() {
return config.storage.getRepoStatus();
}
function mergeBranch(branchName) {
// istanbul ignore if
if (config.pushProtection) {
logger.info(
{ branch: branchName },
'Branch protection: Attempting to merge branch when push protection is enabled'
);
}
return config.storage.mergeBranch(branchName);
}
function commitFilesToBranch(
branchName,
files,
message,
parentBranch = config.baseBranch
) {
return config.storage.commitFilesToBranch(
branchName,
files,
message,
parentBranch
);
}
function getCommitMessages() {
return config.storage.getCommitMessages();
}
// Returns the Pull Request for a branch. Null if not exists.
async function getBranchPr(branchName) {
logger.debug(`getBranchPr(${branchName})`);
const existingPr = await findPr(branchName, null, 'open');
return existingPr ? getPr(existingPr.number) : null;
}
// Returns the combined status for a branch.
async function getBranchStatus(branchName, requiredStatusChecks) {
logger.debug(`getBranchStatus(${branchName})`);
if (!requiredStatusChecks) {
// null means disable status checks, so it always succeeds
logger.debug('Status checks disabled = returning "success"');
return 'success';
}
if (requiredStatusChecks.length) {
// This is Unsupported
logger.warn({ requiredStatusChecks }, `Unsupported requiredStatusChecks`);
return 'failed';
}
const commitStatusUrl = `repos/${
config.repository
}/commits/${branchName}/status`;
const commitStatus = (await get(commitStatusUrl)).body;
logger.debug(
{ state: commitStatus.state, statuses: commitStatus.statuses },
'branch status check result'
);
let checkRuns = [];
if (!config.isGhe) {
try {
const checkRunsUrl = `repos/${
config.repository
}/commits/${branchName}/check-runs`;
const opts = {
headers: {
Accept: 'application/vnd.github.antiope-preview+json',
},
};
const checkRunsRaw = (await get(checkRunsUrl, opts)).body;
if (checkRunsRaw.check_runs && checkRunsRaw.check_runs.length) {
checkRuns = checkRunsRaw.check_runs.map(run => ({
name: run.name,
status: run.status,
conclusion: run.conclusion,
}));
logger.debug({ checkRuns }, 'check runs result');
} else {
// istanbul ignore next
logger.debug({ result: checkRunsRaw }, 'No check runs found');
}
} catch (err) /* istanbul ignore next */ {
if (
err.statusCode === 403 ||
err.message === 'integration-unauthorized'
) {
logger.info('No permission to view check runs');
} else {
logger.warn({ err }, 'Error retrieving check runs');
}
}
}
if (checkRuns.length === 0) {
return commitStatus.state;
}
if (
commitStatus.state === 'failed' ||
checkRuns.some(run => run.conclusion === 'failed')
) {
return 'failed';
}
if (
(commitStatus.state === 'success' || commitStatus.statuses.length === 0) &&
checkRuns.every(run => ['neutral', 'success'].includes(run.conclusion))
) {
return 'success';
}
return 'pending';
}
async function getBranchStatusCheck(branchName, context) {
const branchCommit = await config.storage.getBranchCommit(branchName);
const url = `repos/${config.repository}/commits/${branchCommit}/statuses`;
const res = await get(url);
for (const check of res.body) {
if (check.context === context) {
return check.state;
}
}
return null;
}
async function setBranchStatus(
branchName,
context,
description,
state,
targetUrl
) {
// istanbul ignore if
if (config.parentRepo) {
logger.info('Cannot set branch status when in forking mode');
return;
}
const existingStatus = await getBranchStatusCheck(branchName, context);
if (existingStatus === state) {
return;
}
logger.info({ branch: branchName, context, state }, 'Setting branch status');
const branchCommit = await config.storage.getBranchCommit(branchName);
const url = `repos/${config.repository}/statuses/${branchCommit}`;
const options = {
state,
description,
context,
};
if (targetUrl) {
options.target_url = targetUrl;
}
await get.post(url, { body: options });
}
// Issue
async function getIssueList() {
if (!config.issueList) {
logger.debug('Retrieving issueList');
const renovateUsername = await getRenovateUsername();
const res = await get(
`repos/${config.parentRepo ||
config.repository}/issues?creator=${renovateUsername}&state=all&per_page=100&sort=created&direction=asc`,
{ paginate: 'all', useCache: false }
);
// istanbul ignore if
if (!is.array(res.body)) {
logger.warn({ responseBody: res.body }, 'Could not retrieve issue list');
return [];
}
config.issueList = res.body
.filter(issue => !issue.pull_request)
.map(i => ({
number: i.number,
state: i.state,
title: i.title,
}));
logger.debug('Retrieved ' + config.issueList.length + ' issues');
}
return config.issueList;
}
async function findIssue(title) {
logger.debug(`findIssue(${title})`);
try {
const [issue] = (await getIssueList()).filter(
i => i.state === 'open' && i.title === title
);
if (!issue) {
return null;
}
logger.debug('Found issue ' + issue.number);
const issueBody = (await get(
`repos/${config.parentRepo || config.repository}/issues/${issue.number}`
)).body.body;
return {
number: issue.number,
body: issueBody,
};
} catch (err) /* istanbul ignore next */ {
logger.warn('Error finding issue');
return null;
}
}
async function ensureIssue(title, body, once = false) {
logger.debug(`ensureIssue()`);
try {
const issueList = await getIssueList();
const issues = issueList.filter(i => i.title === title);
if (issues.length) {
let issue = issues.find(i => i.state === 'open');
if (!issue) {
if (once) {
logger.debug('Issue already closed - skipping recreation');
return null;
}
logger.info('Reopening previously closed issue');
issue = issues[issues.length - 1];
}
for (const i of issues) {
if (i.state === 'open' && i.number !== issue.number) {
logger.warn('Closing duplicate issue ' + i.number);
await closeIssue(i.number);
}
}
const issueBody = (await get(
`repos/${config.parentRepo || config.repository}/issues/${issue.number}`
)).body.body;
if (issueBody === body && issue.state === 'open') {
logger.info('Issue is open and up to date - nothing to do');
return null;
}
logger.info('Patching issue');
await get.patch(
`repos/${config.parentRepo || config.repository}/issues/${
issue.number
}`,
{
body: { body, state: 'open' },
}
);
logger.info('Issue updated');
return 'updated';
}
await get.post(`repos/${config.parentRepo || config.repository}/issues`, {
body: {
title,
body,
},
});
logger.info('Issue created');
// reset issueList so that it will be fetched again as-needed
delete config.issueList;
return 'created';
} catch (err) /* istanbul ignore next */ {
if (err.message.startsWith('Issues are disabled for this repo')) {
logger.info(
`Issues are disabled, so could not create issue: ${err.message}`
);
} else {
logger.warn({ err }, 'Could not ensure issue');
}
}
return null;
}
async function closeIssue(issueNumber) {
logger.debug(`closeIssue(${issueNumber})`);
await get.patch(
`repos/${config.parentRepo || config.repository}/issues/${issueNumber}`,
{
body: { state: 'closed' },
}
);
}
async function ensureIssueClosing(title) {
logger.debug(`ensureIssueClosing()`);
const issueList = await getIssueList();
for (const issue of issueList) {
if (issue.state === 'open' && issue.title === title) {
await closeIssue(issue.number);
logger.info({ number: issue.number }, 'Issue closed');
}
}
}
async function addAssignees(issueNo, assignees) {
logger.debug(`Adding assignees ${assignees} to #${issueNo}`);
const repository = config.parentRepo || config.repository;
await get.post(`repos/${repository}/issues/${issueNo}/assignees`, {
body: {
assignees,
},
});
}
async function addReviewers(prNo, reviewers) {
logger.debug(`Adding reviewers ${reviewers} to #${prNo}`);
await get.post(
`repos/${config.parentRepo ||
config.repository}/pulls/${prNo}/requested_reviewers`,
{
body: {
reviewers,
},
}
);
}
async function addLabels(issueNo, labels) {
logger.debug(`Adding labels ${labels} to #${issueNo}`);
const repository = config.parentRepo || config.repository;
if (is.array(labels) && labels.length) {
await get.post(`repos/${repository}/issues/${issueNo}/labels`, {
body: labels,
});
}
}
async function deleteLabel(issueNo, label) {
logger.debug(`Deleting label ${label} from #${issueNo}`);
const repository = config.parentRepo || config.repository;
try {
await get.delete(`repos/${repository}/issues/${issueNo}/labels/${label}`);
} catch (err) /* istanbul ignore next */ {
logger.warn({ err, issueNo, label }, 'Failed to delete label');
}
}
async function getComments(issueNo) {
const pr = (await getClosedPrs())[issueNo];
if (pr) {
logger.debug('Returning closed PR list comments');
return pr.comments;
}
// GET /repos/:owner/:repo/issues/:number/comments
logger.debug(`Getting comments for #${issueNo}`);
const url = `repos/${config.parentRepo ||
config.repository}/issues/${issueNo}/comments?per_page=100`;
const comments = (await get(url, { paginate: true })).body;
logger.debug(`Found ${comments.length} comments`);
return comments;
}
async function addComment(issueNo, body) {
// POST /repos/:owner/:repo/issues/:number/comments
await get.post(
`repos/${config.parentRepo ||
config.repository}/issues/${issueNo}/comments`,
{
body: { body },
}
);
}
async function editComment(commentId, body) {
// PATCH /repos/:owner/:repo/issues/comments/:id
await get.patch(
`repos/${config.parentRepo ||
config.repository}/issues/comments/${commentId}`,
{
body: { body },
}
);
}
async function deleteComment(commentId) {
// DELETE /repos/:owner/:repo/issues/comments/:id
await get.delete(
`repos/${config.parentRepo ||
config.repository}/issues/comments/${commentId}`
);
}
async function ensureComment(issueNo, topic, content) {
const comments = await getComments(issueNo);
let body;
let commentId;
let commentNeedsUpdating;
if (topic) {
logger.debug(`Ensuring comment "${topic}" in #${issueNo}`);
body = `### ${topic}\n\n${content}`;
comments.forEach(comment => {
if (comment.body.startsWith(`### ${topic}\n\n`)) {
commentId = comment.id;
commentNeedsUpdating = comment.body !== body;
}
});
} else {
logger.debug(`Ensuring content-only comment in #${issueNo}`);
body = `${content}`;
comments.forEach(comment => {
if (comment.body === body) {
commentId = comment.id;
commentNeedsUpdating = false;
}
});
}
if (!commentId) {
await addComment(issueNo, body);
logger.info({ repository: config.repository, issueNo }, 'Comment added');
} else if (commentNeedsUpdating) {
await editComment(commentId, body);
logger.info({ repository: config.repository, issueNo }, 'Comment updated');
} else {
logger.debug('Comment is already update-to-date');
}
return true;
}
async function ensureCommentRemoval(issueNo, topic) {
logger.debug(`Ensuring comment "${topic}" in #${issueNo} is removed`);
const comments = await getComments(issueNo);
let commentId;
comments.forEach(comment => {
if (comment.body.startsWith(`### ${topic}\n\n`)) {
commentId = comment.id;
}
});
if (commentId) {
await deleteComment(commentId);
}
}
// Pull Request
async function getPrList() {
logger.trace('getPrList()');
if (!config.prList) {
logger.debug('Retrieving PR list');
const res = await get(
`repos/${config.parentRepo ||
config.repository}/pulls?per_page=100&state=all`,
{ paginate: true }
);
config.prList = res.body.map(pr => ({
number: pr.number,
branchName: pr.head.ref,
sha: pr.head.sha,
title: pr.title,
state:
pr.state === 'closed' && pr.merged_at && pr.merged_at.length
? 'merged'
: pr.state,
createdAt: pr.created_at,
closed_at: pr.closed_at,
sourceRepo: pr.head && pr.head.repo ? pr.head.repo.full_name : undefined,
}));
logger.debug(`Retrieved ${config.prList.length} Pull Requests`);
}
return config.prList;
}
function matchesState(state, desiredState) {
if (desiredState === 'all') {
return true;
}
if (desiredState[0] === '!') {
return state !== desiredState.substring(1);
}
return state === desiredState;
}
async function findPr(branchName, prTitle, state = 'all') {
logger.debug(`findPr(${branchName}, ${prTitle}, ${state})`);
const prList = await getPrList();
const pr = prList.find(
p =>
p.branchName === branchName &&
(!prTitle || p.title === prTitle) &&
matchesState(p.state, state)
);
if (pr) {
logger.debug(`Found PR #${pr.number}`);
}
return pr;
}
// Creates PR and returns PR number
async function createPr(
branchName,
title,
body,
labels,
useDefaultBranch,
statusCheckVerify
) {
let base = useDefaultBranch ? config.defaultBranch : config.baseBranch;
// istanbul ignore if
if (config.mirrorMode && branchName === onboardingBranch) {
logger.debug('Using renovate-config as base branch for mirror config');
base = 'renovate-config';
}
// Include the repository owner to handle forkMode and regular mode
const head = `${config.repository.split('/')[0]}:${branchName}`;
const options = {
body: {
title,
head,
base,
body,
},
};
// istanbul ignore if
if (config.forkToken) {
options.token = config.forkToken;
options.body.maintainer_can_modify = true;
}
logger.debug({ title, head, base }, 'Creating PR');
const pr = (await get.post(
`repos/${config.parentRepo || config.repository}/pulls`,
options
)).body;
logger.debug({ branch: branchName, pr: pr.number }, 'PR created');
// istanbul ignore if
if (config.prList) {
config.prList.push(pr);
}
pr.displayNumber = `Pull Request #${pr.number}`;
pr.branchName = branchName;
await addLabels(pr.number, labels);
if (statusCheckVerify) {
logger.debug('Setting statusCheckVerify');
await setBranchStatus(
branchName,