/
index.ts
1832 lines (1729 loc) · 53 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
// TODO: types (#7154)
/* eslint-disable @typescript-eslint/restrict-template-expressions */
import URL from 'node:url';
import is from '@sindresorhus/is';
import delay from 'delay';
import JSON5 from 'json5';
import { DateTime } from 'luxon';
import semver from 'semver';
import { GlobalConfig } from '../../../config/global';
import {
PLATFORM_INTEGRATION_UNAUTHORIZED,
REPOSITORY_ACCESS_FORBIDDEN,
REPOSITORY_ARCHIVED,
REPOSITORY_BLOCKED,
REPOSITORY_CANNOT_FORK,
REPOSITORY_CHANGED,
REPOSITORY_DISABLED,
REPOSITORY_EMPTY,
REPOSITORY_FORKED,
REPOSITORY_NOT_FOUND,
REPOSITORY_RENAMED,
} from '../../../constants/error-messages';
import { logger } from '../../../logger';
import type { BranchStatus, VulnerabilityAlert } from '../../../types';
import { ExternalHostError } from '../../../types/errors/external-host-error';
import * as git from '../../../util/git';
import { listCommitTree, pushCommitToRenovateRef } from '../../../util/git';
import type {
CommitFilesConfig,
CommitResult,
CommitSha,
} from '../../../util/git/types';
import * as hostRules from '../../../util/host-rules';
import * as githubHttp from '../../../util/http/github';
import type { GithubHttpOptions } from '../../../util/http/github';
import type { HttpResponse } from '../../../util/http/types';
import { regEx } from '../../../util/regex';
import { sanitize } from '../../../util/sanitize';
import { fromBase64, looseEquals } from '../../../util/string';
import { ensureTrailingSlash } from '../../../util/url';
import type {
AggregatedVulnerabilities,
BranchStatusConfig,
CreatePRConfig,
EnsureCommentConfig,
EnsureCommentRemovalConfig,
EnsureIssueConfig,
EnsureIssueResult,
FindPRConfig,
Issue,
MergePRConfig,
PlatformParams,
PlatformPrOptions,
PlatformResult,
RepoParams,
RepoResult,
UpdatePrConfig,
} from '../types';
import { repoFingerprint } from '../util';
import { smartTruncate } from '../utils/pr-body';
import { coerceRestPr } from './common';
import {
enableAutoMergeMutation,
getIssuesQuery,
repoInfoQuery,
vulnerabilityAlertsQuery,
} from './graphql';
import { massageMarkdownLinks } from './massage-markdown-links';
import { getPrCache, updatePrCache } from './pr';
import type {
BranchProtection,
CombinedBranchStatus,
Comment,
GhAutomergeResponse,
GhBranchStatus,
GhPr,
GhRepo,
GhRestPr,
GhRestRepo,
LocalRepoConfig,
PlatformConfig,
} from './types';
import { getUserDetails, getUserEmail } from './user';
export const id = 'github';
const githubApi = new githubHttp.GithubHttp();
let config: LocalRepoConfig;
let platformConfig: PlatformConfig;
export const GitHubMaxPrBodyLen = 60000;
export function resetConfigs(): void {
config = {} as never;
platformConfig = {
hostType: 'github',
endpoint: 'https://api.github.com/',
};
}
resetConfigs();
function escapeHash(input: string): string {
return input ? input.replace(regEx(/#/g), '%23') : input;
}
export async function detectGhe(token: string): Promise<void> {
platformConfig.isGhe =
URL.parse(platformConfig.endpoint).host !== 'api.github.com';
if (platformConfig.isGhe) {
const gheHeaderKey = 'x-github-enterprise-version';
const gheQueryRes = await githubApi.headJson('/', { token });
const gheHeaders = gheQueryRes?.headers || {};
const [, gheVersion] =
Object.entries(gheHeaders).find(
([k]) => k.toLowerCase() === gheHeaderKey
) ?? [];
platformConfig.gheVersion = semver.valid(gheVersion as string) ?? null;
logger.debug(
`Detected GitHub Enterprise Server, version: ${platformConfig.gheVersion}`
);
}
}
export async function initPlatform({
endpoint,
token: originalToken,
username,
gitAuthor,
}: PlatformParams): Promise<PlatformResult> {
let token = originalToken;
if (!token) {
throw new Error('Init: You must configure a GitHub token');
}
if (token.startsWith('github_pat_')) {
throw new Error(
'Init: Fine-grained Personal Access Tokens do not support the GitHub GraphQL API and cannot be used with Renovate.'
);
}
token = token.replace(/^ghs_/, 'x-access-token:ghs_');
platformConfig.isGHApp = token.startsWith('x-access-token:');
if (endpoint) {
platformConfig.endpoint = ensureTrailingSlash(endpoint);
githubHttp.setBaseUrl(platformConfig.endpoint);
} else {
logger.debug('Using default github endpoint: ' + platformConfig.endpoint);
}
await detectGhe(token);
let renovateUsername: string;
if (username) {
renovateUsername = username;
} else {
platformConfig.userDetails ??= await getUserDetails(
platformConfig.endpoint,
token
);
renovateUsername = platformConfig.userDetails.username;
}
let discoveredGitAuthor: string | undefined;
if (!gitAuthor) {
platformConfig.userDetails ??= await getUserDetails(
platformConfig.endpoint,
token
);
platformConfig.userEmail ??= await getUserEmail(
platformConfig.endpoint,
token
);
if (platformConfig.userEmail) {
discoveredGitAuthor = `${platformConfig.userDetails.name} <${platformConfig.userEmail}>`;
}
}
logger.debug({ platformConfig, renovateUsername }, 'Platform config');
const platformResult: PlatformResult = {
endpoint: platformConfig.endpoint,
gitAuthor: gitAuthor ?? discoveredGitAuthor,
renovateUsername,
token,
};
return platformResult;
}
// Get all repositories that the user has access to
export async function getRepos(): Promise<string[]> {
logger.debug('Autodiscovering GitHub repositories');
try {
if (platformConfig.isGHApp) {
const res = await githubApi.getJson<{
repositories: GhRestRepo[];
}>(`installation/repositories?per_page=100`, {
paginationField: 'repositories',
paginate: 'all',
});
return res.body.repositories
.filter(is.nonEmptyObject)
.filter((repo) => !repo.archived)
.map((repo) => repo.full_name);
} else {
const res = await githubApi.getJson<GhRestRepo[]>(
`user/repos?per_page=100`,
{ paginate: 'all' }
);
return res.body
.filter(is.nonEmptyObject)
.filter((repo) => !repo.archived)
.map((repo) => repo.full_name);
}
} catch (err) /* istanbul ignore next */ {
logger.error({ err }, `GitHub getRepos error`);
throw err;
}
}
async function getBranchProtection(
branchName: string
): Promise<BranchProtection> {
// istanbul ignore if
if (config.parentRepo) {
return {};
}
const res = await githubApi.getJson<BranchProtection>(
`repos/${config.repository}/branches/${escapeHash(branchName)}/protection`
);
return res.body;
}
export async function getRawFile(
fileName: string,
repoName?: string,
branchOrTag?: string
): Promise<string | null> {
const repo = repoName ?? config.repository;
let url = `repos/${repo}/contents/${fileName}`;
if (branchOrTag) {
url += `?ref=` + branchOrTag;
}
const res = await githubApi.getJson<{ content: string }>(url);
const buf = res.body.content;
const str = fromBase64(buf);
return str;
}
export async function getJsonFile(
fileName: string,
repoName?: string,
branchOrTag?: string
): Promise<any | null> {
// TODO #7154
const raw = (await getRawFile(fileName, repoName, branchOrTag)) as string;
return JSON5.parse(raw);
}
export async function getForkOrgs(token: string): Promise<string[]> {
// This function will be adapted later to support configured forkOrgs
if (!config.renovateForkUser) {
try {
logger.debug('Determining fork user from API');
const userDetails = await getUserDetails(platformConfig.endpoint, token);
config.renovateForkUser = userDetails.username;
} catch (err) {
logger.debug({ err }, 'Error getting username for forkToken');
}
}
return config.renovateForkUser ? [config.renovateForkUser] : [];
}
export async function listForks(
token: string,
repository: string
): Promise<GhRestRepo[]> {
try {
// Get list of existing repos
const url = `repos/${repository}/forks?per_page=100`;
const repos = (
await githubApi.getJson<GhRestRepo[]>(url, {
token,
paginate: true,
pageLimit: 100,
})
).body;
logger.debug(`Found ${repos.length} forked repo(s)`);
return repos;
} catch (err) {
if (err.statusCode === 404) {
logger.debug('Cannot list repo forks - it is likely private');
} else {
logger.debug({ err }, 'Unknown error listing repository forks');
}
throw new Error(REPOSITORY_CANNOT_FORK);
}
}
export async function findFork(
token: string,
repository: string
): Promise<GhRestRepo | null> {
const forks = await listForks(token, repository);
const orgs = await getForkOrgs(token);
if (!orgs.length) {
throw new Error(REPOSITORY_CANNOT_FORK);
}
let forkedRepo: GhRestRepo | undefined;
for (const forkOrg of orgs) {
logger.debug(`Searching for forked repo in ${forkOrg}`);
forkedRepo = forks.find((repo) => repo.owner.login === forkOrg);
if (forkedRepo) {
logger.debug(`Found existing forked repo: ${forkedRepo.full_name}`);
break;
}
}
return forkedRepo ?? null;
}
export async function createFork(
token: string,
repository: string
): Promise<GhRestRepo> {
let forkedRepo: GhRestRepo | undefined;
try {
forkedRepo = (
await githubApi.postJson<GhRestRepo>(`repos/${repository}/forks`, {
token,
body: {
name: config.parentRepo!.replace('/', '-_-'),
default_branch_only: true, // no baseBranches support yet
},
})
).body;
} catch (err) {
logger.debug({ err }, 'Error creating fork');
}
if (!forkedRepo) {
throw new Error(REPOSITORY_CANNOT_FORK);
}
logger.debug(`Created forked repo ${forkedRepo.full_name}, now sleeping 30s`);
await delay(30000);
return forkedRepo;
}
// Initialize GitHub by getting base branch and SHA
export async function initRepo({
endpoint,
repository,
forkToken,
renovateUsername,
cloneSubmodules,
ignorePrAuthor,
}: RepoParams): Promise<RepoResult> {
logger.debug(`initRepo("${repository}")`);
// config is used by the platform api itself, not necessary for the app layer to know
config = {
repository,
cloneSubmodules,
ignorePrAuthor,
} as any;
// istanbul ignore if
if (endpoint) {
// Necessary for Renovate Pro - do not remove
logger.debug(`Overriding default GitHub endpoint with ${endpoint}`);
platformConfig.endpoint = endpoint;
githubHttp.setBaseUrl(endpoint);
}
const opts = hostRules.find({
hostType: 'github',
url: platformConfig.endpoint,
});
config.renovateUsername = renovateUsername;
[config.repositoryOwner, config.repositoryName] = repository.split('/');
let repo: GhRepo | undefined;
try {
let infoQuery = repoInfoQuery;
// GitHub Enterprise Server <3.3.0 doesn't support autoMergeAllowed and hasIssuesEnabled objects
// TODO #7154
if (
platformConfig.isGhe &&
// semver not null safe, accepts null and undefined
semver.satisfies(platformConfig.gheVersion!, '<3.3.0')
) {
infoQuery = infoQuery.replace(/\n\s*autoMergeAllowed\s*\n/, '\n');
infoQuery = infoQuery.replace(/\n\s*hasIssuesEnabled\s*\n/, '\n');
}
const res = await githubApi.requestGraphql<{
repository: GhRepo;
}>(infoQuery, {
variables: {
owner: config.repositoryOwner,
name: config.repositoryName,
},
});
repo = res?.data?.repository;
// istanbul ignore if
if (!repo) {
logger.debug({ res }, 'No repository returned');
throw new Error(REPOSITORY_NOT_FOUND);
}
// istanbul ignore if
if (!repo.defaultBranchRef?.name) {
throw new Error(REPOSITORY_EMPTY);
}
if (
repo.nameWithOwner &&
repo.nameWithOwner.toUpperCase() !== repository.toUpperCase()
) {
logger.debug(
{ repository, this_repository: repo.nameWithOwner },
'Repository has been renamed'
);
throw new Error(REPOSITORY_RENAMED);
}
if (repo.isArchived) {
logger.debug(
'Repository is archived - throwing error to abort renovation'
);
throw new Error(REPOSITORY_ARCHIVED);
}
// Use default branch as PR target unless later overridden.
config.defaultBranch = repo.defaultBranchRef.name;
// Base branch may be configured but defaultBranch is always fixed
logger.debug(`${repository} default branch = ${config.defaultBranch}`);
// GitHub allows administrators to block certain types of merge, so we need to check it
if (repo.rebaseMergeAllowed) {
config.mergeMethod = 'rebase';
} else if (repo.squashMergeAllowed) {
config.mergeMethod = 'squash';
} else if (repo.mergeCommitAllowed) {
config.mergeMethod = 'merge';
} else {
// This happens if we don't have Administrator read access, it is not a critical error
logger.debug('Could not find allowed merge methods for repo');
}
config.autoMergeAllowed = repo.autoMergeAllowed;
config.hasIssuesEnabled = repo.hasIssuesEnabled;
} catch (err) /* istanbul ignore next */ {
logger.debug({ err }, 'Caught initRepo error');
if (
err.message === REPOSITORY_ARCHIVED ||
err.message === REPOSITORY_RENAMED ||
err.message === REPOSITORY_NOT_FOUND
) {
throw err;
}
if (err.statusCode === 403) {
throw new Error(REPOSITORY_ACCESS_FORBIDDEN);
}
if (err.statusCode === 404) {
throw new Error(REPOSITORY_NOT_FOUND);
}
if (err.message.startsWith('Repository access blocked')) {
throw new Error(REPOSITORY_BLOCKED);
}
if (err.message === REPOSITORY_FORKED) {
throw err;
}
if (err.message === REPOSITORY_DISABLED) {
throw err;
}
if (err.message === 'Response code 451 (Unavailable for Legal Reasons)') {
throw new Error(REPOSITORY_ACCESS_FORBIDDEN);
}
logger.debug({ 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;
if (forkToken) {
logger.debug('Bot is in fork mode');
config.forkToken = forkToken;
// save parent name then delete
config.parentRepo = config.repository;
config.repository = null;
let forkedRepo = await findFork(forkToken, repository);
if (forkedRepo) {
config.repository = forkedRepo.full_name;
const forkDefaultBranch = forkedRepo.default_branch;
if (forkDefaultBranch !== config.defaultBranch) {
const body = {
ref: `refs/heads/${config.defaultBranch}`,
sha: repo.defaultBranchRef.target.oid,
};
logger.debug(
{
defaultBranch: config.defaultBranch,
forkDefaultBranch,
body,
},
'Fork has different default branch to parent, attempting to create branch'
);
try {
await githubApi.postJson(`repos/${config.repository}/git/refs`, {
body,
token: forkToken,
});
logger.debug('Created new default branch in fork');
} catch (err) /* istanbul ignore next */ {
if (err.response?.body?.message === 'Reference already exists') {
logger.debug(
`Branch ${config.defaultBranch} already exists in the fork`
);
} else {
logger.warn(
{ err, body: err.response?.body },
'Could not create parent defaultBranch in fork'
);
}
}
logger.debug(
`Setting ${config.defaultBranch} as default branch for ${config.repository}`
);
try {
await githubApi.patchJson(`repos/${config.repository}`, {
body: {
name: config.repository.split('/')[1],
default_branch: config.defaultBranch,
},
token: forkToken,
});
logger.debug('Successfully changed default branch for fork');
} catch (err) /* istanbul ignore next */ {
logger.warn({ err }, 'Could not set default branch');
}
}
// This is a lovely "hack" by GitHub that lets us force update our fork's default branch
// with the base commit from the parent repository
const url = `repos/${config.repository}/git/refs/heads/${config.defaultBranch}`;
const sha = repo.defaultBranchRef.target.oid;
try {
logger.debug(
`Updating forked repository default sha ${sha} to match upstream`
);
await githubApi.patchJson(url, {
body: {
sha,
force: true,
},
token: forkToken ?? opts.token,
});
} catch (err) /* istanbul ignore next */ {
logger.warn(
{ url, sha, err: err.err || err },
'Error updating fork from upstream - cannot continue'
);
if (err instanceof ExternalHostError) {
throw err;
}
throw new ExternalHostError(err);
}
} else {
logger.debug('Forked repo is not found - attempting to create it');
forkedRepo = await createFork(forkToken, repository);
config.repository = forkedRepo.full_name;
}
}
const parsedEndpoint = URL.parse(platformConfig.endpoint);
// istanbul ignore else
if (forkToken) {
logger.debug('Using forkToken for git init');
parsedEndpoint.auth = config.forkToken ?? null;
} else {
const tokenType = opts.token?.startsWith('x-access-token:')
? 'app'
: 'personal access';
logger.debug(`Using ${tokenType} token for git init`);
parsedEndpoint.auth = opts.token ?? null;
}
// TODO: null checks (#7154)
parsedEndpoint.host = parsedEndpoint.host!.replace(
'api.github.com',
'github.com'
);
parsedEndpoint.pathname = `${config.repository}.git`;
const url = URL.format(parsedEndpoint);
await git.initRepo({
...config,
url,
});
const repoConfig: RepoResult = {
defaultBranch: config.defaultBranch,
isFork: repo.isFork === true,
repoFingerprint: repoFingerprint(repo.id, platformConfig.endpoint),
};
return repoConfig;
}
export async function getRepoForceRebase(): Promise<boolean> {
if (config.repoForceRebase === undefined) {
try {
config.repoForceRebase = false;
const branchProtection = await getBranchProtection(config.defaultBranch);
logger.debug('Found branch protection');
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.message === PLATFORM_INTEGRATION_UNAUTHORIZED ||
err.statusCode === 403
) {
logger.debug(
'Branch protection: Do not have permissions to detect branch protection'
);
} else {
throw err;
}
}
}
return !!config.repoForceRebase;
}
function cachePr(pr?: GhPr | null): void {
config.prList ??= [];
if (pr) {
updatePrCache(pr);
for (let idx = 0; idx < config.prList.length; idx += 1) {
const cachedPr = config.prList[idx];
if (cachedPr.number === pr.number) {
config.prList[idx] = pr;
return;
}
}
config.prList.push(pr);
}
}
// Fetch fresh Pull Request and cache it when possible
async function fetchPr(prNo: number): Promise<GhPr | null> {
try {
const { body: ghRestPr } = await githubApi.getJson<GhRestPr>(
`repos/${config.parentRepo ?? config.repository}/pulls/${prNo}`
);
const result = coerceRestPr(ghRestPr);
cachePr(result);
return result;
} catch (err) {
logger.warn({ err, prNo }, `GitHub fetchPr error`);
return null;
}
}
// Gets details for a PR
export async function getPr(prNo: number): Promise<GhPr | null> {
if (!prNo) {
return null;
}
const prList = await getPrList();
let pr = prList.find(({ number }) => number === prNo) ?? null;
if (pr) {
logger.debug('Returning PR from cache');
}
pr ??= await fetchPr(prNo);
return pr;
}
function matchesState(state: string, desiredState: string): boolean {
if (desiredState === 'all') {
return true;
}
if (desiredState.startsWith('!')) {
return state !== desiredState.substring(1);
}
return state === desiredState;
}
export async function getPrList(): Promise<GhPr[]> {
if (!config.prList) {
const repo = config.parentRepo ?? config.repository;
const username =
!config.forkToken && !config.ignorePrAuthor && config.renovateUsername
? config.renovateUsername
: null;
// TODO: check null `repo` (#7154)
const prCache = await getPrCache(githubApi, repo!, username);
config.prList = Object.values(prCache).sort(
({ number: a }, { number: b }) => (a > b ? -1 : 1)
);
}
return config.prList;
}
export async function findPr({
branchName,
prTitle,
state = 'all',
}: FindPRConfig): Promise<GhPr | null> {
logger.debug(`findPr(${branchName}, ${prTitle}, ${state})`);
const prList = await getPrList();
const pr = prList.find((p) => {
if (p.sourceBranch !== branchName) {
return false;
}
if (prTitle && prTitle !== p.title) {
return false;
}
if (!matchesState(p.state, state)) {
return false;
}
if (!config.forkToken && !looseEquals(config.repository, p.sourceRepo)) {
return false;
}
return true;
});
if (pr) {
logger.debug(`Found PR #${pr.number}`);
}
return pr ?? null;
}
const REOPEN_THRESHOLD_MILLIS = 1000 * 60 * 60 * 24 * 7;
async function ensureBranchSha(branchName: string, sha: string): Promise<void> {
const refUrl = `/repos/${config.repository}/git/refs/heads/${branchName}`;
let branchExists = false;
try {
await githubApi.head(refUrl, { useCache: false });
branchExists = true;
} catch (err) {
if (err.statusCode !== 404) {
throw err;
}
}
if (branchExists) {
await githubApi.patchJson(refUrl, { body: { sha, force: true } });
return;
}
await githubApi.postJson(`/repos/${config.repository}/git/refs`, {
body: { sha, ref: `refs/heads/${branchName}` },
});
}
// Returns the Pull Request for a branch. Null if not exists.
export async function getBranchPr(branchName: string): Promise<GhPr | null> {
logger.debug(`getBranchPr(${branchName})`);
const openPr = await findPr({
branchName,
state: 'open',
});
if (openPr) {
return openPr;
}
const autoclosedPr = await findPr({
branchName,
state: 'closed',
});
if (
autoclosedPr?.title?.endsWith(' - autoclosed') &&
autoclosedPr?.closedAt
) {
const closedMillisAgo = DateTime.fromISO(autoclosedPr.closedAt)
.diffNow()
.negate()
.toMillis();
if (closedMillisAgo > REOPEN_THRESHOLD_MILLIS) {
return null;
}
logger.debug({ autoclosedPr }, 'Found autoclosed PR for branch');
if (GlobalConfig.get('dryRun')) {
logger.info('DRY-RUN: Would try to reopen autoclosed PR');
return null;
}
const { sha, number } = autoclosedPr;
try {
await ensureBranchSha(branchName, sha!);
logger.debug(`Recreated autoclosed branch ${branchName} with sha ${sha}`);
} catch (err) {
logger.debug('Could not recreate autoclosed branch - skipping reopen');
return null;
}
try {
const title = autoclosedPr.title.replace(regEx(/ - autoclosed$/), '');
const { body: ghPr } = await githubApi.patchJson<GhRestPr>(
`repos/${config.repository}/pulls/${number}`,
{
body: {
state: 'open',
title,
},
}
);
logger.info(
{ branchName, title, number },
'Successfully reopened autoclosed PR'
);
const result = coerceRestPr(ghPr);
cachePr(result);
return result;
} catch (err) {
logger.debug('Could not reopen autoclosed PR');
return null;
}
}
return null;
}
async function getStatus(
branchName: string,
useCache = true
): Promise<CombinedBranchStatus> {
const commitStatusUrl = `repos/${config.repository}/commits/${escapeHash(
branchName
)}/status`;
return (
await githubApi.getJson<CombinedBranchStatus>(commitStatusUrl, { useCache })
).body;
}
// Returns the combined status for a branch.
export async function getBranchStatus(
branchName: string,
internalChecksAsSuccess: boolean
): Promise<BranchStatus> {
logger.debug(`getBranchStatus(${branchName})`);
let commitStatus: CombinedBranchStatus;
try {
commitStatus = await getStatus(branchName);
} catch (err) /* istanbul ignore next */ {
if (err.statusCode === 404) {
logger.debug(
'Received 404 when checking branch status, assuming that branch has been deleted'
);
throw new Error(REPOSITORY_CHANGED);
}
logger.debug('Unknown error when checking branch status');
throw err;
}
logger.debug(
{ state: commitStatus.state, statuses: commitStatus.statuses },
'branch status check result'
);
if (commitStatus.statuses && !internalChecksAsSuccess) {
commitStatus.statuses = commitStatus.statuses.filter(
(status) =>
status.state !== 'success' || !status.context?.startsWith('renovate/')
);
if (!commitStatus.statuses.length) {
logger.debug(
'Successful checks are all internal renovate/ checks, so returning "pending" branch status'
);
commitStatus.state = 'pending';
}
}
let checkRuns: { name: string; status: string; conclusion: string }[] = [];
// API is supported in oldest available GHE version 2.19
try {
const checkRunsUrl = `repos/${config.repository}/commits/${escapeHash(
branchName
)}/check-runs?per_page=100`;
const opts = {
headers: {
accept: 'application/vnd.github.antiope-preview+json',
},
paginate: true,
paginationField: 'check_runs',
};
const checkRunsRaw = (
await githubApi.getJson<{
check_runs: { name: string; status: string; conclusion: string }[];
}>(checkRunsUrl, opts)
).body;
if (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 instanceof ExternalHostError) {
throw err;
}
if (
err.statusCode === 403 ||
err.message === PLATFORM_INTEGRATION_UNAUTHORIZED
) {
logger.debug('No permission to view check runs');
} else {
logger.warn({ err }, 'Error retrieving check runs');
}
}
if (checkRuns.length === 0) {
if (commitStatus.state === 'success') {
return 'green';
}
if (commitStatus.state === 'failure') {
return 'red';
}
return 'yellow';
}
if (
commitStatus.state === 'failure' ||
checkRuns.some((run) => run.conclusion === 'failure')
) {
return 'red';
}
if (
(commitStatus.state === 'success' || commitStatus.statuses.length === 0) &&
checkRuns.every((run) =>
['skipped', 'neutral', 'success'].includes(run.conclusion)
)
) {
return 'green';
}
return 'yellow';
}
async function getStatusCheck(
branchName: string,
useCache = true
): Promise<GhBranchStatus[]> {
const branchCommit = git.getBranchCommit(branchName);
const url = `repos/${config.repository}/commits/${branchCommit}/statuses`;
return (await githubApi.getJson<GhBranchStatus[]>(url, { useCache })).body;
}
interface GithubToRenovateStatusMapping {
[index: string]: BranchStatus;
}
const githubToRenovateStatusMapping: GithubToRenovateStatusMapping = {
success: 'green',
error: 'red',
failure: 'red',
pending: 'yellow',
};
export async function getBranchStatusCheck(
branchName: string,
context: string
): Promise<BranchStatus | null> {
try {
const res = await getStatusCheck(branchName);
for (const check of res) {
if (check.context === context) {
return githubToRenovateStatusMapping[check.state] || 'yellow';
}
}
return null;
} catch (err) /* istanbul ignore next */ {
if (err.statusCode === 404) {
logger.debug('Commit not found when checking statuses');
throw new Error(REPOSITORY_CHANGED);
}
throw err;
}
}
export async function setBranchStatus({
branchName,
context,
description,
state,
url: targetUrl,
}: BranchStatusConfig): Promise<void> {
// istanbul ignore if
if (config.parentRepo) {
logger.debug('Cannot set branch status when in forking mode');
return;
}
const existingStatus = await getBranchStatusCheck(branchName, context);