-
Notifications
You must be signed in to change notification settings - Fork 390
/
Copy pathgithub.ts
1717 lines (1644 loc) · 51.6 KB
/
github.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
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {createPullRequest} from 'code-suggester';
import {PullRequest} from './pull-request';
import {Commit} from './commit';
import {Octokit} from '@octokit/rest';
import {request} from '@octokit/request';
import {graphql} from '@octokit/graphql';
import {RequestError} from '@octokit/request-error';
import {
GitHubAPIError,
DuplicateReleaseError,
FileNotFoundError,
ConfigurationError,
} from './errors';
const MAX_ISSUE_BODY_SIZE = 65536;
const MAX_SLEEP_SECONDS = 20;
export const GH_API_URL = 'https://api.github.com';
export const GH_GRAPHQL_URL = 'https://api.github.com';
type OctokitType = InstanceType<typeof Octokit>;
import {logger as defaultLogger} from './util/logger';
import {Repository} from './repository';
import {ReleasePullRequest} from './release-pull-request';
import {Update} from './update';
import {Release} from './release';
import {ROOT_PROJECT_PATH} from './manifest';
import {signoffCommitMessage} from './util/signoff-commit-message';
import {
RepositoryFileCache,
GitHubFileContents,
DEFAULT_FILE_MODE,
FileNotFoundError as MissingFileError,
} from '@google-automations/git-file-utils';
import {Logger} from 'code-suggester/build/src/types';
import {HttpsProxyAgent} from 'https-proxy-agent';
import {HttpProxyAgent} from 'http-proxy-agent';
import {PullRequestOverflowHandler} from './util/pull-request-overflow-handler';
// Extract some types from the `request` package.
type RequestBuilderType = typeof request;
type DefaultFunctionType = RequestBuilderType['defaults'];
type RequestFunctionType = ReturnType<DefaultFunctionType>;
export interface OctokitAPIs {
graphql: Function;
request: RequestFunctionType;
octokit: OctokitType;
}
export interface GitHubOptions {
repository: Repository;
octokitAPIs: OctokitAPIs;
logger?: Logger;
}
interface ProxyOption {
host: string;
port: number;
}
interface GitHubCreateOptions {
owner: string;
repo: string;
defaultBranch?: string;
apiUrl?: string;
graphqlUrl?: string;
octokitAPIs?: OctokitAPIs;
token?: string;
logger?: Logger;
proxy?: ProxyOption;
}
type CommitFilter = (commit: Commit) => boolean;
interface GraphQLCommit {
sha: string;
message: string;
associatedPullRequests: {
nodes: GraphQLPullRequest[];
};
}
interface GraphQLPullRequest {
number: number;
title: string;
body: string;
baseRefName: string;
headRefName: string;
labels: {
nodes: {
name: string;
}[];
};
mergeCommit?: {
oid: string;
};
files: {
nodes: {
path: string;
}[];
pageInfo: {
hasNextPage: boolean;
};
};
}
interface GraphQLRelease {
name: string;
tag: {
name: string;
};
tagCommit: {
oid: string;
};
url: string;
description: string;
isDraft: boolean;
}
interface CommitHistory {
pageInfo: {
hasNextPage: boolean;
endCursor: string | undefined;
};
data: Commit[];
}
interface PullRequestHistory {
pageInfo: {
hasNextPage: boolean;
endCursor: string | undefined;
};
data: PullRequest[];
}
interface ReleaseHistory {
pageInfo: {
hasNextPage: boolean;
endCursor: string | undefined;
};
data: GitHubRelease[];
}
interface CommitIteratorOptions {
maxResults?: number;
backfillFiles?: boolean;
}
interface ReleaseIteratorOptions {
maxResults?: number;
}
interface TagIteratorOptions {
maxResults?: number;
}
export interface ReleaseOptions {
draft?: boolean;
prerelease?: boolean;
}
export interface GitHubRelease {
id: number;
name?: string;
tagName: string;
sha: string;
notes?: string;
url: string;
draft?: boolean;
uploadUrl?: string;
}
export interface GitHubTag {
name: string;
sha: string;
}
interface FileDiff {
readonly mode: '100644' | '100755' | '040000' | '160000' | '120000';
readonly content: string | null;
readonly originalContent: string | null;
}
export type ChangeSet = Map<string, FileDiff>;
interface CreatePullRequestOptions {
fork?: boolean;
draft?: boolean;
}
export class GitHub {
readonly repository: Repository;
private octokit: OctokitType;
private request: RequestFunctionType;
private graphql: Function;
private fileCache: RepositoryFileCache;
private logger: Logger;
private constructor(options: GitHubOptions) {
this.repository = options.repository;
this.octokit = options.octokitAPIs.octokit;
this.request = options.octokitAPIs.request;
this.graphql = options.octokitAPIs.graphql;
this.fileCache = new RepositoryFileCache(this.octokit, this.repository);
this.logger = options.logger ?? defaultLogger;
}
static createDefaultAgent(baseUrl: string, defaultProxy?: ProxyOption) {
if (!defaultProxy) {
return undefined;
}
const {host, port} = defaultProxy;
if (new URL(baseUrl).protocol.replace(':', '') === 'http') {
return new HttpProxyAgent(`http://${host}:${port}`);
} else {
return new HttpsProxyAgent(`https://${host}:${port}`);
}
}
/**
* Build a new GitHub client with auto-detected default branch.
*
* @param {GitHubCreateOptions} options Configuration options
* @param {string} options.owner The repository owner.
* @param {string} options.repo The repository name.
* @param {string} options.defaultBranch Optional. The repository's default branch.
* Defaults to the value fetched via the API.
* @param {string} options.apiUrl Optional. The base url of the GitHub API.
* @param {string} options.graphqlUrl Optional. The base url of the GraphQL API.
* @param {OctokitAPISs} options.octokitAPIs Optional. Override the internal
* client instances with a pre-authenticated instance.
* @param {string} token Optional. A GitHub API token used for authentication.
*/
static async create(options: GitHubCreateOptions): Promise<GitHub> {
const apiUrl = options.apiUrl ?? GH_API_URL;
const graphqlUrl = options.graphqlUrl ?? GH_GRAPHQL_URL;
const releasePleaseVersion = require('../../package.json').version;
const apis = options.octokitAPIs ?? {
octokit: new Octokit({
baseUrl: apiUrl,
auth: options.token,
request: {
agent: this.createDefaultAgent(apiUrl, options.proxy),
},
}),
request: request.defaults({
baseUrl: apiUrl,
headers: {
'user-agent': `release-please/${releasePleaseVersion}`,
Authorization: `token ${options.token}`,
},
}),
graphql: graphql.defaults({
baseUrl: graphqlUrl,
request: {
agent: this.createDefaultAgent(graphqlUrl, options.proxy),
},
headers: {
'user-agent': `release-please/${releasePleaseVersion}`,
Authorization: `token ${options.token}`,
'content-type': 'application/vnd.github.v3+json',
},
}),
};
const opts = {
repository: {
owner: options.owner,
repo: options.repo,
defaultBranch:
options.defaultBranch ??
(await GitHub.defaultBranch(
options.owner,
options.repo,
apis.octokit
)),
},
octokitAPIs: apis,
logger: options.logger,
};
return new GitHub(opts);
}
/**
* Returns the default branch for a given repository.
*
* @param {string} owner The GitHub repository owner
* @param {string} repo The GitHub repository name
* @param {OctokitType} octokit An authenticated octokit instance
* @returns {string} Name of the default branch
*/
static async defaultBranch(
owner: string,
repo: string,
octokit: OctokitType
): Promise<string> {
const {data} = await octokit.repos.get({
repo,
owner,
});
return data.default_branch;
}
/**
* Returns the list of commits to the default branch after the provided filter
* query has been satified.
*
* @param {string} targetBranch Target branch of commit
* @param {CommitFilter} filter Callback function that returns whether a
* commit/pull request matches certain criteria
* @param {CommitIteratorOptions} options Query options
* @param {number} options.maxResults Limit the number of results searched.
* Defaults to unlimited.
* @param {boolean} options.backfillFiles If set, use the REST API for
* fetching the list of touched files in this commit. Defaults to `false`.
* @returns {Commit[]} List of commits to current branch
* @throws {GitHubAPIError} on an API error
*/
async commitsSince(
targetBranch: string,
filter: CommitFilter,
options: CommitIteratorOptions = {}
): Promise<Commit[]> {
const commits: Commit[] = [];
const generator = this.mergeCommitIterator(targetBranch, options);
for await (const commit of generator) {
if (filter(commit)) {
break;
}
commits.push(commit);
}
return commits;
}
/**
* Iterate through commit history with a max number of results scanned.
*
* @param {string} targetBranch target branch of commit
* @param {CommitIteratorOptions} options Query options
* @param {number} options.maxResults Limit the number of results searched.
* Defaults to unlimited.
* @param {boolean} options.backfillFiles If set, use the REST API for
* fetching the list of touched files in this commit. Defaults to `false`.
* @yields {Commit}
* @throws {GitHubAPIError} on an API error
*/
async *mergeCommitIterator(
targetBranch: string,
options: CommitIteratorOptions = {}
) {
const maxResults = options.maxResults ?? Number.MAX_SAFE_INTEGER;
let cursor: string | undefined = undefined;
let results = 0;
while (results < maxResults) {
const response: CommitHistory | null = await this.mergeCommitsGraphQL(
targetBranch,
cursor,
options
);
// no response usually means that the branch can't be found
if (!response) {
break;
}
for (let i = 0; i < response.data.length; i++) {
results += 1;
yield response.data[i];
}
if (!response.pageInfo.hasNextPage) {
break;
}
cursor = response.pageInfo.endCursor;
}
}
private async mergeCommitsGraphQL(
targetBranch: string,
cursor?: string,
options: CommitIteratorOptions = {}
): Promise<CommitHistory | null> {
this.logger.debug(
`Fetching merge commits on branch ${targetBranch} with cursor: ${cursor}`
);
const query = `query pullRequestsSince($owner: String!, $repo: String!, $num: Int!, $maxFilesChanged: Int, $targetBranch: String!, $cursor: String) {
repository(owner: $owner, name: $repo) {
ref(qualifiedName: $targetBranch) {
target {
... on Commit {
history(first: $num, after: $cursor) {
nodes {
associatedPullRequests(first: 10) {
nodes {
number
title
baseRefName
headRefName
labels(first: 10) {
nodes {
name
}
}
body
mergeCommit {
oid
}
files(first: $maxFilesChanged) {
nodes {
path
}
pageInfo {
endCursor
hasNextPage
}
}
}
}
sha: oid
message
}
pageInfo {
hasNextPage
endCursor
}
}
}
}
}
}
}`;
const params = {
cursor,
owner: this.repository.owner,
repo: this.repository.repo,
num: 25,
targetBranch,
maxFilesChanged: 100, // max is 100
};
const response = await this.graphqlRequest({
query,
...params,
});
if (!response) {
this.logger.warn(
`Did not receive a response for query: ${query}`,
params
);
return null;
}
// if the branch does exist, return null
if (!response.repository?.ref) {
this.logger.warn(
`Could not find commits for branch ${targetBranch} - it likely does not exist.`
);
return null;
}
const history = response.repository.ref.target.history;
const commits = (history.nodes || []) as GraphQLCommit[];
// Count the number of pull requests associated with each merge commit. This is
// used in the next step to make sure we only find pull requests with a
// merge commit that contain 1 merged commit.
const mergeCommitCount: Record<string, number> = {};
for (const commit of commits) {
for (const pr of commit.associatedPullRequests.nodes) {
if (pr.mergeCommit?.oid) {
mergeCommitCount[pr.mergeCommit.oid] ??= 0;
mergeCommitCount[pr.mergeCommit.oid]++;
}
}
}
const commitData: Commit[] = [];
for (const graphCommit of commits) {
const commit: Commit = {
sha: graphCommit.sha,
message: graphCommit.message,
};
const mergePullRequest = graphCommit.associatedPullRequests.nodes.find(
pr => {
return (
// Only match the pull request with a merge commit if there is a
// single merged commit in the PR. This means merge commits and squash
// merges will be matched, but rebase merged PRs will only be matched
// if they contain a single commit. This is so PRs that are rebased
// and merged will have ßSfiles backfilled from each commit instead of
// the whole PR.
pr.mergeCommit &&
pr.mergeCommit.oid === graphCommit.sha &&
mergeCommitCount[pr.mergeCommit.oid] === 1
);
}
);
const pullRequest =
mergePullRequest || graphCommit.associatedPullRequests.nodes[0];
if (pullRequest) {
commit.pullRequest = {
sha: commit.sha,
number: pullRequest.number,
baseBranchName: pullRequest.baseRefName,
headBranchName: pullRequest.headRefName,
title: pullRequest.title,
body: pullRequest.body,
labels: pullRequest.labels.nodes.map(node => node.name),
files: (pullRequest.files?.nodes || []).map(node => node.path),
};
}
if (mergePullRequest) {
if (
mergePullRequest.files?.pageInfo?.hasNextPage &&
options.backfillFiles
) {
this.logger.info(
`PR #${mergePullRequest.number} has many files, backfilling`
);
commit.files = await this.getCommitFiles(graphCommit.sha);
} else {
// We cannot directly fetch files on commits via graphql, only provide file
// information for commits with associated pull requests
commit.files = (mergePullRequest.files?.nodes || []).map(
node => node.path
);
}
} else if (options.backfillFiles) {
// In this case, there is no squashed merge commit. This could be a simple
// merge commit, a rebase merge commit, or a direct commit to the branch.
// Fallback to fetching the list of commits from the REST API. In the future
// we can perhaps lazy load these.
commit.files = await this.getCommitFiles(graphCommit.sha);
}
commitData.push(commit);
}
return {
pageInfo: history.pageInfo,
data: commitData,
};
}
/**
* Get the list of file paths modified in a given commit.
*
* @param {string} sha The commit SHA
* @returns {string[]} File paths
* @throws {GitHubAPIError} on an API error
*/
getCommitFiles = wrapAsync(async (sha: string): Promise<string[]> => {
this.logger.debug(`Backfilling file list for commit: ${sha}`);
const files: string[] = [];
for await (const resp of this.octokit.paginate.iterator(
'GET /repos/{owner}/{repo}/commits/{ref}',
{
owner: this.repository.owner,
repo: this.repository.repo,
ref: sha,
}
)) {
// Paginate plugin doesn't have types for listing files on a commit
const data = resp.data as any as {files: {filename: string}[]};
for (const f of data.files || []) {
if (f.filename) {
files.push(f.filename);
}
}
}
if (files.length >= 3000) {
this.logger.warn(
`Found ${files.length} files. This may not include all the files.`
);
} else {
this.logger.debug(`Found ${files.length} files`);
}
return files;
});
private graphqlRequest = wrapAsync(
async (
opts: {
[key: string]: string | number | null | undefined;
},
options?: {
maxRetries?: number;
}
) => {
let maxRetries = options?.maxRetries ?? 5;
let seconds = 1;
while (maxRetries >= 0) {
try {
const response = await this.graphql(opts);
if (response) {
return response;
}
this.logger.trace('no GraphQL response, retrying');
} catch (err) {
if ((err as GitHubAPIError).status !== 502) {
throw err;
}
if (maxRetries === 0) {
this.logger.warn('ran out of retries and response is required');
throw err;
}
this.logger.info(
`received 502 error, ${maxRetries} attempts remaining`
);
}
maxRetries -= 1;
if (maxRetries >= 0) {
this.logger.trace(`sleeping ${seconds} seconds`);
await sleepInMs(1000 * seconds);
seconds = Math.min(seconds * 2, MAX_SLEEP_SECONDS);
}
}
this.logger.trace('ran out of retries');
return undefined;
}
);
/**
* Iterate through merged pull requests with a max number of results scanned.
*
* @param {string} targetBranch The base branch of the pull request
* @param {string} status The status of the pull request
* @param {number} maxResults Limit the number of results searched. Defaults to
* unlimited.
* @param {boolean} includeFiles Whether to fetch the list of files included in
* the pull request. Defaults to `true`.
* @yields {PullRequest}
* @throws {GitHubAPIError} on an API error
*/
async *pullRequestIterator(
targetBranch: string,
status: 'OPEN' | 'CLOSED' | 'MERGED' = 'MERGED',
maxResults: number = Number.MAX_SAFE_INTEGER,
includeFiles = true
): AsyncGenerator<PullRequest, void, void> {
const generator = includeFiles
? this.pullRequestIteratorWithFiles(targetBranch, status, maxResults)
: this.pullRequestIteratorWithoutFiles(targetBranch, status, maxResults);
for await (const pullRequest of generator) {
yield pullRequest;
}
}
/**
* Helper implementation of pullRequestIterator that includes files via
* the graphQL API.
*
* @param {string} targetBranch The base branch of the pull request
* @param {string} status The status of the pull request
* @param {number} maxResults Limit the number of results searched
*/
private async *pullRequestIteratorWithFiles(
targetBranch: string,
status: 'OPEN' | 'CLOSED' | 'MERGED' = 'MERGED',
maxResults: number = Number.MAX_SAFE_INTEGER
): AsyncGenerator<PullRequest, void, void> {
let cursor: string | undefined = undefined;
let results = 0;
while (results < maxResults) {
const response: PullRequestHistory | null =
await this.pullRequestsGraphQL(targetBranch, status, cursor);
// no response usually means we ran out of results
if (!response) {
break;
}
for (let i = 0; i < response.data.length; i++) {
results += 1;
yield response.data[i];
}
if (!response.pageInfo.hasNextPage) {
break;
}
cursor = response.pageInfo.endCursor;
}
}
/**
* Helper implementation of pullRequestIterator that excludes files
* via the REST API.
*
* @param {string} targetBranch The base branch of the pull request
* @param {string} status The status of the pull request
* @param {number} maxResults Limit the number of results searched
*/
private async *pullRequestIteratorWithoutFiles(
targetBranch: string,
status: 'OPEN' | 'CLOSED' | 'MERGED' = 'MERGED',
maxResults: number = Number.MAX_SAFE_INTEGER
): AsyncGenerator<PullRequest, void, void> {
const statusMap: Record<string, 'open' | 'closed'> = {
OPEN: 'open',
CLOSED: 'closed',
MERGED: 'closed',
};
let results = 0;
for await (const {data: pulls} of this.octokit.paginate.iterator(
'GET /repos/{owner}/{repo}/pulls',
{
state: statusMap[status],
owner: this.repository.owner,
repo: this.repository.repo,
base: targetBranch,
sort: 'updated',
direction: 'desc',
}
)) {
for (const pull of pulls) {
// The REST API does not have an option for "merged"
// pull requests - they are closed with a `merged_at` timestamp
if (status !== 'MERGED' || pull.merged_at) {
results += 1;
yield {
headBranchName: pull.head.ref,
baseBranchName: pull.base.ref,
number: pull.number,
title: pull.title,
body: pull.body || '',
labels: pull.labels.map(label => label.name),
files: [],
sha: pull.merge_commit_sha || undefined,
};
if (results >= maxResults) {
break;
}
}
}
if (results >= maxResults) {
break;
}
}
}
/**
* Return a list of merged pull requests. The list is not guaranteed to be sorted
* by merged_at, but is generally most recent first.
*
* @param {string} targetBranch - Base branch of the pull request. Defaults to
* the configured default branch.
* @param {number} page - Page of results. Defaults to 1.
* @param {number} perPage - Number of results per page. Defaults to 100.
* @returns {PullRequestHistory | null} - List of merged pull requests
* @throws {GitHubAPIError} on an API error
*/
private async pullRequestsGraphQL(
targetBranch: string,
states: 'OPEN' | 'CLOSED' | 'MERGED' = 'MERGED',
cursor?: string
): Promise<PullRequestHistory | null> {
this.logger.debug(
`Fetching ${states} pull requests on branch ${targetBranch} with cursor ${cursor}`
);
const response = await this.graphqlRequest({
query: `query mergedPullRequests($owner: String!, $repo: String!, $num: Int!, $maxFilesChanged: Int, $targetBranch: String!, $states: [PullRequestState!], $cursor: String) {
repository(owner: $owner, name: $repo) {
pullRequests(first: $num, after: $cursor, baseRefName: $targetBranch, states: $states, orderBy: {field: CREATED_AT, direction: DESC}) {
nodes {
number
title
baseRefName
headRefName
labels(first: 10) {
nodes {
name
}
}
body
mergeCommit {
oid
}
files(first: $maxFilesChanged) {
nodes {
path
}
pageInfo {
endCursor
hasNextPage
}
}
}
pageInfo {
endCursor
hasNextPage
}
}
}
}`,
cursor,
owner: this.repository.owner,
repo: this.repository.repo,
num: 25,
targetBranch,
states,
maxFilesChanged: 64,
});
if (!response?.repository?.pullRequests) {
this.logger.warn(
`Could not find merged pull requests for branch ${targetBranch} - it likely does not exist.`
);
return null;
}
const pullRequests = (response.repository.pullRequests.nodes ||
[]) as GraphQLPullRequest[];
return {
pageInfo: response.repository.pullRequests.pageInfo,
data: pullRequests.map(pullRequest => {
return {
sha: pullRequest.mergeCommit?.oid, // already filtered non-merged
number: pullRequest.number,
baseBranchName: pullRequest.baseRefName,
headBranchName: pullRequest.headRefName,
labels: (pullRequest.labels?.nodes || []).map(l => l.name),
title: pullRequest.title,
body: pullRequest.body + '',
files: (pullRequest.files?.nodes || []).map(node => node.path),
};
}),
};
}
/**
* Iterate through releases with a max number of results scanned.
*
* @param {ReleaseIteratorOptions} options Query options
* @param {number} options.maxResults Limit the number of results searched.
* Defaults to unlimited.
* @yields {GitHubRelease}
* @throws {GitHubAPIError} on an API error
*/
async *releaseIterator(options: ReleaseIteratorOptions = {}) {
const maxResults = options.maxResults ?? Number.MAX_SAFE_INTEGER;
let results = 0;
let cursor: string | undefined = undefined;
while (true) {
const response: ReleaseHistory | null = await this.releaseGraphQL(cursor);
if (!response) {
break;
}
for (let i = 0; i < response.data.length; i++) {
if ((results += 1) > maxResults) {
break;
}
yield response.data[i];
}
if (results > maxResults || !response.pageInfo.hasNextPage) {
break;
}
cursor = response.pageInfo.endCursor;
}
}
private async releaseGraphQL(
cursor?: string
): Promise<ReleaseHistory | null> {
this.logger.debug(`Fetching releases with cursor ${cursor}`);
const response = await this.graphqlRequest({
query: `query releases($owner: String!, $repo: String!, $num: Int!, $cursor: String) {
repository(owner: $owner, name: $repo) {
releases(first: $num, after: $cursor, orderBy: {field: CREATED_AT, direction: DESC}) {
nodes {
name
tag {
name
}
tagCommit {
oid
}
url
description
isDraft
}
pageInfo {
endCursor
hasNextPage
}
}
}
}`,
cursor,
owner: this.repository.owner,
repo: this.repository.repo,
num: 25,
});
if (!response.repository.releases.nodes.length) {
this.logger.warn('Could not find releases.');
return null;
}
const releases = response.repository.releases.nodes as GraphQLRelease[];
return {
pageInfo: response.repository.releases.pageInfo,
data: releases
.filter(release => !!release.tagCommit)
.map(release => {
if (!release.tag || !release.tagCommit) {
this.logger.debug(release);
}
return {
name: release.name || undefined,
tagName: release.tag ? release.tag.name : 'unknown',
sha: release.tagCommit.oid,
notes: release.description,
url: release.url,
draft: release.isDraft,
} as GitHubRelease;
}),
} as ReleaseHistory;
}
/**
* Iterate through tags with a max number of results scanned.
*
* @param {TagIteratorOptions} options Query options
* @param {number} options.maxResults Limit the number of results searched.
* Defaults to unlimited.
* @yields {GitHubTag}
* @throws {GitHubAPIError} on an API error
*/
async *tagIterator(options: TagIteratorOptions = {}) {
const maxResults = options.maxResults || Number.MAX_SAFE_INTEGER;
let results = 0;
for await (const response of this.octokit.paginate.iterator(
'GET /repos/{owner}/{repo}/tags',
{
owner: this.repository.owner,
repo: this.repository.repo,
}
)) {
for (const tag of response.data) {
if ((results += 1) > maxResults) {
break;
}
yield {
name: tag.name,
sha: tag.commit.sha,
};
}
if (results > maxResults) break;
}
}
/**
* Fetch the contents of a file from the configured branch
*
* @param {string} path The path to the file in the repository
* @returns {GitHubFileContents}
* @throws {GitHubAPIError} on other API errors
*/
async getFileContents(path: string): Promise<GitHubFileContents> {
return await this.getFileContentsOnBranch(
path,
this.repository.defaultBranch
);
}
/**
* Fetch the contents of a file
*
* @param {string} path The path to the file in the repository
* @param {string} branch The branch to fetch from
* @returns {GitHubFileContents}
* @throws {FileNotFoundError} if the file cannot be found
* @throws {GitHubAPIError} on other API errors
*/
async getFileContentsOnBranch(
path: string,
branch: string
): Promise<GitHubFileContents> {
this.logger.debug(`Fetching ${path} from branch ${branch}`);
try {
return await this.fileCache.getFileContents(path, branch);
} catch (e) {
if (e instanceof MissingFileError) {
throw new FileNotFoundError(path);
}
throw e;
}
}
async getFileJson<T>(path: string, branch: string): Promise<T> {
const content = await this.getFileContentsOnBranch(path, branch);
return JSON.parse(content.parsedContent);
}
/**
* Returns a list of paths to all files with a given name.
*
* If a prefix is specified, only return paths that match
* the provided prefix.
*
* @param filename The name of the file to find