/
index.ts
1780 lines (1716 loc) · 51 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 from 'url';
import is from '@sindresorhus/is';
import delay from 'delay';
import { configFileNames } from '../../config/app-strings';
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 { PLATFORM_TYPE_GITHUB } from '../../constants/platforms';
import {
PR_STATE_ALL,
PR_STATE_CLOSED,
PR_STATE_OPEN,
} from '../../constants/pull-requests';
import { logger } from '../../logger';
import { BranchStatus } from '../../types';
import { ExternalHostError } from '../../types/errors/external-host-error';
import * as git from '../../util/git';
import * as hostRules from '../../util/host-rules';
import * as githubHttp from '../../util/http/github';
import { sanitize } from '../../util/sanitize';
import { ensureTrailingSlash } from '../../util/url';
import {
BranchStatusConfig,
CreatePRConfig,
EnsureCommentConfig,
EnsureCommentRemovalConfig,
EnsureIssueConfig,
EnsureIssueResult,
FindPRConfig,
Issue,
PlatformConfig,
Pr,
RepoConfig,
RepoParams,
VulnerabilityAlert,
} from '../common';
import { smartTruncate } from '../utils/pr-body';
import {
BranchProtection,
CombinedBranchStatus,
Comment,
GhBranchStatus,
GhPr,
LocalRepoConfig,
PrList,
} from './types';
const githubApi = new githubHttp.GithubHttp();
const defaultConfigFile = configFileNames[0];
let config: LocalRepoConfig = {} as any;
const defaults = {
hostType: PLATFORM_TYPE_GITHUB,
endpoint: 'https://api.github.com/',
};
const escapeHash = (input: string): string =>
input ? input.replace(/#/g, '%23') : input;
export async function initPlatform({
endpoint,
token,
}: {
endpoint: string;
token: string;
}): Promise<PlatformConfig> {
if (!token) {
throw new Error('Init: You must configure a GitHub personal access token');
}
if (endpoint) {
defaults.endpoint = ensureTrailingSlash(endpoint);
githubHttp.setBaseUrl(defaults.endpoint);
} else {
logger.debug('Using default github endpoint: ' + defaults.endpoint);
}
let gitAuthor: string;
let renovateUsername: string;
try {
const userData = (
await githubApi.getJson<{ login: string; name: string }>(
defaults.endpoint + 'user',
{
token,
}
)
).body;
renovateUsername = userData.login;
gitAuthor = userData.name;
} catch (err) {
logger.debug({ err }, 'Error authenticating with GitHub');
throw new Error('Init: Authentication failure');
}
try {
const userEmail = (
await githubApi.getJson<{ email: string }[]>(
defaults.endpoint + 'user/emails',
{
token,
}
)
).body;
if (userEmail.length && userEmail[0].email) {
gitAuthor += ` <${userEmail[0].email}>`;
} else {
logger.debug('Cannot find an email address for Renovate user');
gitAuthor = undefined;
}
} catch (err) {
logger.debug(
'Cannot read user/emails endpoint on GitHub to retrieve gitAuthor'
);
gitAuthor = undefined;
}
logger.debug('Authenticated as GitHub user: ' + renovateUsername);
const platformConfig: PlatformConfig = {
endpoint: defaults.endpoint,
gitAuthor,
renovateUsername,
};
return platformConfig;
}
// Get all repositories that the user has access to
export async function getRepos(): Promise<string[]> {
logger.debug('Autodiscovering GitHub repositories');
try {
const res = await githubApi.getJson<{ full_name: string }[]>(
'user/repos?per_page=100',
{ paginate: true }
);
return res.body.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;
}
// Return the commit SHA for a branch
async function getBranchCommit(branchName: string): Promise<string> {
try {
const res = await githubApi.getJson<{ object: { sha: string } }>(
`repos/${config.repository}/git/refs/heads/${escapeHash(branchName)}`
);
return res.body.object.sha;
} catch (err) /* istanbul ignore next */ {
logger.debug({ err }, 'Error getting branch commit');
if (err.statusCode === 404) {
throw new Error(REPOSITORY_CHANGED);
}
if (err.statusCode === 409) {
throw new Error(REPOSITORY_EMPTY);
}
throw err;
}
}
async function getBaseCommitSHA(): Promise<string> {
if (!config.baseCommitSHA) {
config.baseCommitSHA = await getBranchCommit(config.baseBranch);
}
return config.baseCommitSHA;
}
// Initialize GitHub by getting base branch and SHA
export async function initRepo({
endpoint,
repository,
forkMode,
forkToken,
localDir,
includeForks,
renovateUsername,
optimizeForDisabled,
}: RepoParams): Promise<RepoConfig> {
logger.debug(`initRepo("${repository}")`);
// config is used by the platform api itself, not necessary for the app layer to know
config = { localDir, repository } as any;
// istanbul ignore if
if (endpoint) {
// Necessary for Renovate Pro - do not remove
logger.debug({ endpoint }, 'Overriding default GitHub endpoint');
defaults.endpoint = endpoint;
githubHttp.setBaseUrl(endpoint);
}
const opts = hostRules.find({
hostType: PLATFORM_TYPE_GITHUB,
url: defaults.endpoint,
});
config.isGhe = URL.parse(defaults.endpoint).host !== 'api.github.com';
config.renovateUsername = renovateUsername;
[config.repositoryOwner, config.repositoryName] = repository.split('/');
let res;
try {
res = await githubApi.getJson<{ fork: boolean }>(`repos/${repository}`);
logger.trace({ repositoryDetails: res.body }, 'Repository details');
// istanbul ignore if
if (res.body.fork && !includeForks) {
try {
const renovateConfig = JSON.parse(
Buffer.from(
(
await githubApi.getJson<{ content: string }>(
`repos/${config.repository}/contents/${defaultConfigFile}`
)
).body.content,
'base64'
).toString()
);
if (!renovateConfig.includeForks) {
throw new Error();
}
} catch (err) {
throw new Error(REPOSITORY_FORKED);
}
}
if (res.body.full_name && res.body.full_name !== repository) {
logger.debug(
{ repository, this_repository: res.body.full_name },
'Repository has been renamed'
);
throw new Error(REPOSITORY_RENAMED);
}
if (res.body.archived) {
logger.debug(
'Repository is archived - throwing error to abort renovation'
);
throw new Error(REPOSITORY_ARCHIVED);
}
if (optimizeForDisabled) {
let renovateConfig;
try {
renovateConfig = JSON.parse(
Buffer.from(
(
await githubApi.getJson<{ content: string }>(
`repos/${config.repository}/contents/${defaultConfigFile}`
)
).body.content,
'base64'
).toString()
);
} catch (err) {
// Do nothing
}
if (renovateConfig && renovateConfig.enabled === false) {
throw new Error(REPOSITORY_DISABLED);
}
}
// 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.debug('Could not find allowed merge methods for repo');
}
} catch (err) /* istanbul ignore next */ {
logger.debug('Caught initRepo error');
if (
err.message === REPOSITORY_ARCHIVED ||
err.message === REPOSITORY_RENAMED
) {
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;
config.openPrList = null;
config.closedPrList = null;
config.forkMode = !!forkMode;
if (forkMode) {
logger.debug('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 githubApi.getJson<{ full_name: string }[]>(
'user/repos?per_page=100',
{
token: forkToken || opts.token,
paginate: true,
}
)
).body.map((r) => r.full_name);
try {
config.repository = (
await githubApi.postJson<{ full_name: string }>(
`repos/${repository}/forks`,
{
token: forkToken || opts.token,
}
)
).body.full_name;
} catch (err) /* istanbul ignore next */ {
logger.debug({ err }, 'Error forking repository');
throw new Error(REPOSITORY_CANNOT_FORK);
}
if (existingRepos.includes(config.repository)) {
logger.debug(
{ 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 githubApi.patchJson(
`repos/${config.repository}/git/refs/heads/${config.baseBranch}`,
{
body: {
sha: parentSha,
force: true,
},
token: forkToken || opts.token,
}
);
} catch (err) /* istanbul ignore next */ {
logger.debug(
'Error updating fork reference - will try deleting fork to try again next time'
);
try {
await githubApi.deleteJson(`repos/${config.repository}`);
logger.info('Fork deleted');
} catch (deleteErr) {
logger.warn({ err: deleteErr }, 'Could not delete fork');
}
if (err instanceof ExternalHostError) {
throw err;
}
throw new ExternalHostError(err);
}
} else {
logger.debug({ repository_fork: config.repository }, 'Created fork');
// Wait an arbitrary 30s to hopefully give GitHub enough time for forking to complete
await delay(30000);
}
}
const parsedEndpoint = URL.parse(defaults.endpoint);
// istanbul ignore else
if (forkMode) {
logger.debug('Using forkToken for git init');
parsedEndpoint.auth = config.forkToken;
} else if (global.appMode) {
logger.debug('Using app token for git init');
parsedEndpoint.auth = `x-access-token:${opts.token}`;
} else {
logger.debug('Using personal access token for git init');
parsedEndpoint.auth = opts.token;
}
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,
gitAuthorName: global.gitAuthor?.name,
gitAuthorEmail: global.gitAuthor?.email,
});
const repoConfig: RepoConfig = {
baseBranch: config.baseBranch,
isFork: res.body.fork === true,
};
return repoConfig;
}
export async function getRepoForceRebase(): Promise<boolean> {
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;
}
// istanbul ignore next
export async function setBaseBranch(
branchName = config.baseBranch
): Promise<string> {
config.baseBranch = branchName;
config.baseCommitSHA = null;
const baseBranchSha = await git.setBaseBranch(branchName);
return baseBranchSha;
}
// Branch
// istanbul ignore next
export function deleteBranch(
branchName: string,
closePr?: boolean
): Promise<void> {
return git.deleteBranch(branchName);
}
async function getClosedPrs(): Promise<PrList> {
if (!config.closedPrList) {
config.closedPrList = {};
let query;
try {
// prettier-ignore
query = `
query {
repository(owner: "${config.repositoryOwner}", name: "${config.repositoryName}") {
pullRequests(states: [CLOSED, MERGED], first: 100, orderBy: {field: UPDATED_AT, direction: DESC}) {
nodes {
number
state
headRefName
title
comments(last: 100) {
nodes {
databaseId
body
}
}
}
}
}
}
`;
const nodes = await githubApi.getGraphqlNodes<any>(
query,
'pullRequests',
{ paginate: false }
);
const prNumbers: number[] = [];
// istanbul ignore if
if (!nodes?.length) {
logger.debug({ query }, 'No graphql data, returning empty list');
return {};
}
for (const pr of nodes) {
// https://developer.github.com/v4/object/pullrequest/
pr.displayNumber = `Pull Request #${pr.number}`;
pr.state = pr.state.toLowerCase();
pr.branchName = pr.headRefName;
delete pr.headRefName;
pr.comments = pr.comments.nodes.map(
(comment: { databaseId: number; body: string }) => ({
id: comment.databaseId,
body: comment.body,
})
);
pr.body = 'dummy body'; // just in case
config.closedPrList[pr.number] = pr;
prNumbers.push(pr.number);
}
prNumbers.sort();
logger.debug({ prNumbers }, 'Retrieved closed PR list with graphql');
} catch (err) /* istanbul ignore next */ {
logger.warn({ query, err }, 'getClosedPrs error');
}
}
return config.closedPrList;
}
async function getOpenPrs(): Promise<PrList> {
// istanbul ignore if
if (config.isGhe) {
logger.debug(
'Skipping unsupported graphql PullRequests.mergeStateStatus query on GHE'
);
return {};
}
if (!config.openPrList) {
config.openPrList = {};
let query;
try {
// prettier-ignore
query = `
query {
repository(owner: "${config.repositoryOwner}", name: "${config.repositoryName}") {
pullRequests(states: [OPEN], first: 100, orderBy: {field: UPDATED_AT, direction: DESC}) {
nodes {
number
headRefName
baseRefName
title
mergeable
mergeStateStatus
labels(last: 100) {
nodes {
name
}
}
commits(first: 2) {
nodes {
commit {
author {
email
}
committer {
email
}
parents(last: 1) {
edges {
node {
abbreviatedOid
oid
}
}
}
}
}
}
body
reviews(first: 1, states:[CHANGES_REQUESTED]){
nodes{
state
}
}
}
}
}
}
`;
const nodes = await githubApi.getGraphqlNodes<any>(
query,
'pullRequests',
{ paginate: false }
);
const prNumbers: number[] = [];
// istanbul ignore if
if (!nodes?.length) {
logger.debug({ query }, 'No graphql res.data');
return {};
}
for (const pr of nodes) {
// https://developer.github.com/v4/object/pullrequest/
pr.displayNumber = `Pull Request #${pr.number}`;
pr.state = PR_STATE_OPEN;
pr.branchName = pr.headRefName;
const branchName = pr.branchName;
const prNo = pr.number;
delete pr.headRefName;
pr.targetBranch = pr.baseRefName;
delete pr.baseRefName;
// https://developer.github.com/v4/enum/mergeablestate
const canMergeStates = ['BEHIND', 'CLEAN'];
const hasNegativeReview =
pr.reviews && pr.reviews.nodes && pr.reviews.nodes.length > 0;
// istanbul ignore if
if (hasNegativeReview) {
pr.canMerge = false;
pr.canMergeReason = `hasNegativeReview`;
} else if (!canMergeStates.includes(pr.mergeStateStatus)) {
pr.canMerge = false;
pr.canMergeReason = `mergeStateStatus = ${pr.mergeStateStatus}`;
} else {
pr.canMerge = true;
}
// https://developer.github.com/v4/enum/mergestatestatus
if (pr.mergeStateStatus === 'DIRTY') {
pr.isConflicted = true;
} else {
pr.isConflicted = false;
}
if (pr.commits.nodes.length === 1) {
if (global.gitAuthor) {
// Check against gitAuthor
const commitAuthorEmail =
pr.commits?.nodes?.[0]?.commit?.author?.email;
if (commitAuthorEmail === global.gitAuthor.email) {
pr.isModified = false;
} else {
logger.trace(
{
branchName,
prNo,
commitAuthorEmail,
gitAuthorEmail: global.gitAuthor.email,
},
'PR isModified=true: last committer has different email to the bot'
);
pr.isModified = true;
}
} else {
// assume the author is us
// istanbul ignore next
pr.isModified = false;
}
} else {
// assume we can't rebase if more than 1
logger.trace(
{
branchName,
prNo,
},
'PR isModified=true: PR has more than one commit'
);
pr.isModified = true;
}
pr.isStale = false;
if (pr.mergeStateStatus === 'BEHIND') {
pr.isStale = true;
} else {
const baseCommitSHA = await getBaseCommitSHA();
if (
pr.commits?.nodes[0]?.commit?.parents?.edges?.[0]?.node?.oid !==
baseCommitSHA
) {
pr.isStale = true;
}
}
if (pr.labels) {
pr.labels = pr.labels.nodes.map(
(label: { name: string }) => label.name
);
}
delete pr.mergeable;
delete pr.mergeStateStatus;
delete pr.commits;
config.openPrList[pr.number] = pr;
prNumbers.push(pr.number);
}
prNumbers.sort();
logger.trace({ prNumbers }, 'Retrieved open PR list with graphql');
} catch (err) /* istanbul ignore next */ {
logger.warn({ query, err }, 'getOpenPrs error');
}
}
return config.openPrList;
}
// Gets details for a PR
export async function getPr(prNo: number): Promise<Pr | null> {
if (!prNo) {
return null;
}
const openPrs = await getOpenPrs();
const openPr = openPrs[prNo];
if (openPr) {
logger.debug('Returning from graphql open PR list');
return openPr;
}
const closedPrs = await getClosedPrs();
const closedPr = closedPrs[prNo];
if (closedPr) {
logger.debug('Returning from graphql closed PR list');
return closedPr;
}
logger.debug(
{ prNo },
'PR not found in open or closed PRs list - trying to fetch it directly'
);
const pr = (
await githubApi.getJson<any>(
`repos/${config.parentRepo || config.repository}/pulls/${prNo}`
)
).body;
if (!pr) {
return null;
}
// Harmonise PR values
pr.displayNumber = `Pull Request #${pr.number}`;
if (pr.state === PR_STATE_OPEN) {
pr.isModified = true;
pr.branchName = pr.head ? pr.head.ref : undefined;
pr.sha = pr.head ? pr.head.sha : undefined;
if (pr.mergeable === true) {
pr.canMerge = true;
} else {
pr.canMerge = false;
pr.canMergeReason = `mergeable = ${pr.mergeable}`;
}
if (pr.mergeable_state === 'dirty') {
logger.debug({ prNo }, 'PR state is dirty so unmergeable');
pr.isConflicted = true;
}
if (pr.commits === 1) {
if (global.gitAuthor) {
// Check against gitAuthor
const commitAuthorEmail = (
await githubApi.getJson<{ commit: { author: { email } } }[]>(
`repos/${
config.parentRepo || config.repository
}/pulls/${prNo}/commits`
)
).body[0].commit.author.email;
if (commitAuthorEmail === global.gitAuthor.email) {
logger.debug(
{ prNo },
'1 commit matches configured gitAuthor so can rebase'
);
pr.isModified = false;
} else {
logger.trace(
{
prNo,
commitAuthorEmail,
gitAuthorEmail: global.gitAuthor.email,
},
'PR isModified=true: 1 commit and not by configured gitAuthor so cannot rebase'
);
pr.isModified = true;
}
} else {
logger.debug(
{ prNo },
'1 commit and no configured gitAuthor so can rebase'
);
pr.isModified = false;
}
} else {
// Check if only one author of all commits
logger.debug({ prNo }, 'Checking all commits');
const prCommits = (
await githubApi.getJson<
{ committer: { login: string }; commit: { message: string } }[]
>(
`repos/${
config.parentRepo || config.repository
}/pulls/${prNo}/commits`
)
).body;
// Filter out "Update branch" presses
const remainingCommits = prCommits.filter(
(commit: { committer; commit }) => {
const isWebflow =
commit.committer && commit.committer.login === 'web-flow';
if (!isWebflow) {
// Not a web UI commit, so keep it
return true;
}
const isUpdateBranch =
commit.commit &&
commit.commit.message &&
commit.commit.message.startsWith("Merge branch 'master' into");
if (isUpdateBranch) {
// They just clicked the button
return false;
}
// They must have done some other edit through the web UI
return true;
}
);
if (remainingCommits.length <= 1) {
pr.isModified = false;
}
}
const baseCommitSHA = await getBaseCommitSHA();
if (!pr.base || pr.base.sha !== baseCommitSHA) {
pr.isStale = true;
}
}
return pr;
}
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;
}
export async function getPrList(): Promise<Pr[]> {
logger.trace('getPrList()');
if (!config.prList) {
logger.debug('Retrieving PR list');
let res;
try {
res = await githubApi.getJson<{
number: number;
head: { ref: string; sha: string; repo: { full_name: string } };
title: string;
state: string;
merged_at: string;
created_at: string;
closed_at: string;
}>(
`repos/${
config.parentRepo || config.repository
}/pulls?per_page=100&state=all`,
{ paginate: true }
);
} catch (err) /* istanbul ignore next */ {
logger.debug({ err }, 'getPrList err');
throw new ExternalHostError(err, PLATFORM_TYPE_GITHUB);
}
config.prList = res.body.map((pr) => ({
number: pr.number,
branchName: pr.head.ref,
sha: pr.head.sha,
title: pr.title,
state:
pr.state === PR_STATE_CLOSED && pr.merged_at && pr.merged_at.length
? /* istanbul ignore next */ '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;
}
export async function findPr({
branchName,
prTitle,
state = PR_STATE_ALL,
}: FindPRConfig): Promise<Pr | null> {
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) &&
(config.forkMode || config.repository === p.sourceRepo) // #5188
);
if (pr) {
logger.debug(`Found PR #${pr.number}`);
}
return pr;
}
// Returns the Pull Request for a branch. Null if not exists.
export async function getBranchPr(branchName: string): Promise<Pr | null> {
logger.debug(`getBranchPr(${branchName})`);
const existingPr = await findPr({
branchName,
state: PR_STATE_OPEN,
});
return existingPr ? getPr(existingPr.number) : null;
}
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,
requiredStatusChecks: any
): Promise<BranchStatus> {
logger.debug(`getBranchStatus(${branchName})`);
if (!requiredStatusChecks) {
// null means disable status checks, so it always succeeds
logger.debug('Status checks disabled = returning "success"');
return BranchStatus.green;
}
if (requiredStatusChecks.length) {
// This is Unsupported
logger.warn({ requiredStatusChecks }, `Unsupported requiredStatusChecks`);
return BranchStatus.red;
}
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'
);
let checkRuns: { name: string; status: string; conclusion: string }[] = [];
if (!config.isGhe) {
try {
const checkRunsUrl = `repos/${config.repository}/commits/${escapeHash(
branchName
)}/check-runs`;
const opts = {
headers: {
Accept: 'application/vnd.github.antiope-preview+json',
},
};
const checkRunsRaw = (
await githubApi.getJson<{
check_runs: { name: string; status: string; conclusion: string }[];
}>(checkRunsUrl, opts)
).body;
if (checkRunsRaw.check_runs && checkRunsRaw.check_runs.length) {
checkRuns = checkRunsRaw.check_runs.map((run) => ({
name: run.name,