-
Notifications
You must be signed in to change notification settings - Fork 544
Expand file tree
/
Copy pathgithub.ts
More file actions
1885 lines (1788 loc) · 56.3 KB
/
github.ts
File metadata and controls
1885 lines (1788 loc) · 56.3 KB
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 2019 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, Changes} from 'code-suggester';
import {logger} from './util/logger';
import {Octokit} from '@octokit/rest';
import {request} from '@octokit/request';
import {graphql} from '@octokit/graphql';
import {Endpoints, EndpointOptions, OctokitResponse} from '@octokit/types';
import {RequestError} from '@octokit/request-error';
// The return types for responses have not yet been exposed in the
// @octokit/* libraries, we explicitly define the types below to work
// around this,. See: https://github.com/octokit/rest.js/issues/1624
// https://github.com/octokit/types.ts/issues/25.
import {PromiseValue} from 'type-fest';
type OctokitType = InstanceType<typeof Octokit>;
type PullsListResponseItems = PromiseValue<
ReturnType<InstanceType<typeof Octokit>['pulls']['list']>
>['data'];
type PullsListResponseItem = PromiseValue<
ReturnType<InstanceType<typeof Octokit>['pulls']['get']>
>['data'];
type GitRefResponse = PromiseValue<
ReturnType<InstanceType<typeof Octokit>['git']['getRef']>
>['data'];
type GitGetTreeResponse = PromiseValue<
ReturnType<InstanceType<typeof Octokit>['git']['getTree']>
>['data'];
type IssuesListResponseItem = PromiseValue<
ReturnType<InstanceType<typeof Octokit>['issues']['get']>
>['data'];
type CreateIssueCommentResponse = PromiseValue<
ReturnType<InstanceType<typeof Octokit>['issues']['createComment']>
>['data'];
// see: PromiseValue<
// ReturnType<InstanceType<typeof Octokit>['repos']['createRelease']>
// >['data'];
type CommitsListResponse =
Endpoints['GET /repos/{owner}/{repo}/commits']['response'];
type CommitGetResponse =
Endpoints['GET /repos/{owner}/{repo}/commits/{ref}']['response'];
export type ReleaseCreateResponse = {
name: string;
tag_name: string;
draft: boolean;
html_url: string;
upload_url: string;
body: string;
};
type ReposListTagsResponseItems = {
name: string;
commit: {
sha: string;
url: string;
};
zipball_url: string;
tarball_url: string;
node_id: string;
};
function isReposListResponse(arg: unknown): arg is ReposListTagsResponseItems {
return typeof arg === 'object' && Object.hasOwnProperty.call(arg, 'name');
}
// Extract some types from the `request` package.
type RequestBuilderType = typeof request;
type DefaultFunctionType = RequestBuilderType['defaults'];
type RequestFunctionType = ReturnType<DefaultFunctionType>;
type RequestOptionsType = Parameters<DefaultFunctionType>[0];
type MergedPullRequestFilter = (filter: MergedGitHubPR) => boolean;
type CommitFilter = (
commit: Commit,
pullRequest: MergedGitHubPR | undefined
) => boolean;
import chalk = require('chalk');
import * as semver from 'semver';
import {
Commit,
CommitsResponse,
graphqlToCommits,
PREdge,
} from './graphql-to-commits';
import {Update} from './updaters/update';
import {BranchName} from './util/branch-name';
import {RELEASE_PLEASE, GH_API_URL} from './constants';
import {GitHubConstructorOptions} from '.';
import {DuplicateReleaseError, GitHubAPIError, AuthError} from './errors';
export interface OctokitAPIs {
graphql: Function;
request: RequestFunctionType;
octokit: OctokitType;
}
export interface GitHubTag {
name: string;
sha: string;
version: string;
}
export interface GitHubFileContents {
sha: string;
content: string;
parsedContent: string;
}
export interface GitHubPR {
branch: string;
title: string;
body: string;
updates: Update[];
labels: string[];
changes?: Changes;
}
export interface MergedGitHubPR {
sha: string;
number: number;
baseRefName: string;
headRefName: string;
labels: string[];
title: string;
body: string;
}
interface CommitWithPullRequest {
commit: Commit;
pullRequest?: MergedGitHubPR;
}
interface PullRequestHistory {
pageInfo: {
hasNextPage: boolean;
endCursor: string | undefined;
};
data: CommitWithPullRequest[];
}
interface GraphQLCommit {
sha: string;
message: string;
associatedPullRequests: {
nodes: {
number: number;
title: string;
body: string;
baseRefName: string;
headRefName: string;
labels: {
nodes: {
name: string;
}[];
};
mergeCommit?: {
oid: string;
};
}[];
};
}
export interface MergedGitHubPRWithFiles extends MergedGitHubPR {
files: string[];
}
// GraphQL reponse types
export interface Repository<T> {
repository: T;
}
interface Nodes<T> {
nodes: T[];
}
export interface PageInfo {
endCursor: string;
hasNextPage: boolean;
}
interface PullRequestNode {
title: string;
body: string;
number: number;
mergeCommit: {oid: string};
files: {pageInfo: PageInfo} & Nodes<{path: string}>;
labels: Nodes<{name: string}>;
}
export interface PullRequests {
pullRequests: Nodes<PullRequestNode>;
}
let probotMode = false;
export class GitHub {
defaultBranch?: string;
octokit: OctokitType;
request: RequestFunctionType;
graphql: Function;
token: string | undefined;
owner: string;
repo: string;
apiUrl: string;
fork: boolean;
repositoryDefaultBranch?: string;
constructor(options: GitHubConstructorOptions) {
this.defaultBranch = options.defaultBranch;
this.token = options.token;
this.owner = options.owner;
this.repo = options.repo;
this.fork = !!options.fork;
this.apiUrl = options.apiUrl || GH_API_URL;
if (options.octokitAPIs === undefined) {
this.octokit = new Octokit({
baseUrl: options.apiUrl,
auth: this.token,
});
const defaults: RequestOptionsType = {
baseUrl: this.apiUrl,
headers: {
'user-agent': `${RELEASE_PLEASE}/${
require('../../package.json').version
}`,
Authorization: `token ${this.token}`,
},
};
this.request = request.defaults(defaults);
this.graphql = graphql;
} else {
// for the benefit of probot applications, we allow a configured instance
// of octokit to be passed in as a parameter.
probotMode = true;
this.octokit = options.octokitAPIs.octokit;
this.request = options.octokitAPIs.request;
this.graphql = options.octokitAPIs.graphql;
}
}
private async makeGraphqlRequest(_opts: {
[key: string]: string | number | null | undefined;
}) {
let opts = Object.assign({}, _opts);
if (!probotMode) {
opts = Object.assign(opts, {
url: `${this.apiUrl}/graphql`,
headers: {
authorization: `token ${this.token}`,
'content-type': 'application/vnd.github.v3+json',
},
});
}
return this.graphql(opts);
}
private graphqlRequest = wrapAsync(
async (
opts: {
[key: string]: string | number | null | undefined;
},
maxRetries = 1
) => {
while (maxRetries >= 0) {
try {
return await this.makeGraphqlRequest(opts);
} catch (err) {
if (err.status !== 502) {
throw err;
}
}
maxRetries -= 1;
}
}
);
private decoratePaginateOpts(opts: EndpointOptions): EndpointOptions {
if (probotMode) {
return opts;
} else {
return Object.assign(opts, {
headers: {
Authorization: `token ${this.token}`,
},
});
}
}
/**
* Returns the list of commits since a given SHA on the target branch
*
* @param {string} sha SHA of the base commit or undefined for all commits
* @param {string} path If provided, limit to commits that affect the provided path
* @param {number} per_page Pagination option. Defaults to 100
* @returns {Commit[]} List of commits
* @throws {GitHubAPIError} on an API error
*/
commitsSinceShaRest = wrapAsync(
async (sha?: string, path?: string, per_page = 100): Promise<Commit[]> => {
let page = 1;
let found = false;
const baseBranch = await this.getDefaultBranch();
const commits: [string | null, string][] = [];
while (!found) {
const response = await this.request(
'GET /repos/{owner}/{repo}/commits{?sha,page,per_page,path}',
{
owner: this.owner,
repo: this.repo,
sha: baseBranch,
page,
per_page,
path,
}
);
for (const commit of (response as CommitsListResponse).data) {
if (commit.sha === sha) {
found = true;
break;
}
// skip merge commits
if (commit.parents.length === 2) {
continue;
}
commits.push([commit.sha, commit.commit.message]);
}
page++;
}
const ret = [];
for (const [ref, message] of commits) {
const files = [];
let page = 1;
let moreFiles = true;
while (moreFiles) {
// the "Get Commit" resource is a bit of an outlier in terms of GitHub's
// normal pagination: https://git.io/JmVZq
// The behavior is to return an object representing the commit, a
// property of which is an array of files. GitHub will return as many
// associated files as there are, up to a limit of 300, on the initial
// request. If there are more associated files, it will send "Links"
// headers to get the next set. There is a total limit of 3000
// files returned per commit.
// In practice, the links headers are just the same resourceID plus a
// "page=N" query parameter with "page=1" being the initial set.
//
// TODO: it is more robust to follow the link.next headers (in case
// GitHub ever changes the pattern) OR use ocktokit pagination for this
// endpoint when https://git.io/JmVll is addressed.
const response = (await this.request(
'GET /repos/{owner}/{repo}/commits/{ref}{?page}',
{owner: this.owner, repo: this.repo, ref, page}
)) as CommitGetResponse;
const commitFiles = response.data.files;
if (!commitFiles) {
moreFiles = false;
break;
}
files.push(...commitFiles.map(f => f.filename ?? ''));
// < 300 files means we hit the end
// page === 10 means we're at 3000 and that's the limit GH is gonna
// cough up anyway.
if (commitFiles.length < 300 || page === 10) {
moreFiles = false;
break;
}
page++;
}
ret.push({sha: ref, message, files});
}
return ret;
}
);
/**
* Returns the list of commits since a given SHA on the target branch
*
* Note: Commit.files only for commits from PRs.
*
* @param {string|undefined} sha SHA of the base commit or undefined for all commits
* @param {number} perPage Pagination option. Defaults to 100
* @param {boolean} labels Whether or not to return labels. Defaults to false
* @param {string|null} path If provided, limit to commits that affect the provided path
* @returns {Commit[]} List of commits
* @throws {GitHubAPIError} on an API error
*/
async commitsSinceSha(
sha: string | undefined,
perPage = 100,
labels = false,
path: string | null = null
): Promise<Commit[]> {
const commits: Commit[] = [];
const method = labels ? 'commitsWithLabels' : 'commitsWithFiles';
let cursor;
for (;;) {
const commitsResponse: CommitsResponse = await this[method](
cursor,
perPage,
path
);
for (let i = 0, commit: Commit; i < commitsResponse.commits.length; i++) {
commit = commitsResponse.commits[i];
if (commit.sha === sha) {
return commits;
} else {
commits.push(commit);
}
}
if (commitsResponse.hasNextPage === false || !commitsResponse.endCursor) {
return commits;
} else {
cursor = commitsResponse.endCursor;
}
}
}
private async commitsWithFiles(
cursor: string | undefined = undefined,
perPage = 32,
path: string | null = null,
maxFilesChanged = 64
): Promise<CommitsResponse> {
const baseBranch = await this.getDefaultBranch();
// The GitHub v3 API does not offer an elegant way to fetch commits
// in conjucntion with the path that they modify. We lean on the graphql
// API for this one task, fetching commits in descending chronological
// order along with the file paths attached to them.
const response = await this.graphqlRequest(
{
query: `query commitsWithFiles($cursor: String, $owner: String!, $repo: String!, $baseRef: String!, $perPage: Int, $maxFilesChanged: Int, $path: String) {
repository(owner: $owner, name: $repo) {
ref(qualifiedName: $baseRef) {
target {
... on Commit {
history(first: $perPage, after: $cursor, path: $path) {
edges {
node {
... on Commit {
message
oid
associatedPullRequests(first: 1) {
edges {
node {
... on PullRequest {
number
mergeCommit {
oid
}
files(first: $maxFilesChanged) {
edges {
node {
path
}
}
pageInfo {
endCursor
hasNextPage
}
}
}
}
}
}
}
}
}
pageInfo {
endCursor
hasNextPage
}
}
}
}
}
}
}`,
cursor,
maxFilesChanged,
owner: this.owner,
path,
perPage,
repo: this.repo,
baseRef: `refs/heads/${baseBranch}`,
},
3
);
return graphqlToCommits(this, response);
}
private async commitsWithLabels(
cursor: string | undefined = undefined,
perPage = 32,
path: string | null = null,
maxLabels = 16
): Promise<CommitsResponse> {
const baseBranch = await this.getDefaultBranch();
const response = await this.graphqlRequest(
{
query: `query commitsWithLabels($cursor: String, $owner: String!, $repo: String!, $baseRef: String!, $perPage: Int, $maxLabels: Int, $path: String) {
repository(owner: $owner, name: $repo) {
ref(qualifiedName: $baseRef) {
target {
... on Commit {
history(first: $perPage, after: $cursor, path: $path) {
edges {
node {
... on Commit {
message
oid
associatedPullRequests(first: 1) {
edges {
node {
... on PullRequest {
number
mergeCommit {
oid
}
labels(first: $maxLabels) {
edges {
node {
name
}
}
}
}
}
}
}
}
}
}
pageInfo {
endCursor
hasNextPage
}
}
}
}
}
}
}`,
cursor,
maxLabels,
owner: this.owner,
path,
perPage,
repo: this.repo,
baseRef: `refs/heads/${baseBranch}`,
},
3
);
return graphqlToCommits(this, response);
}
/**
* Return the pull request files
*
* @param {number} num Pull request number
* @param {string} cursor Pagination cursor
* @param {number} maxFilesChanged Number of files to return per page
* @return {PREdge}
* @throws {GitHubAPIError} on an API error
*/
async pullRequestFiles(
num: number,
cursor: string,
maxFilesChanged = 100
): Promise<PREdge> {
// Used to handle the edge-case in which a PR has more than 100
// modified files attached to it.
const response = await this.graphqlRequest({
query: `query pullRequestFiles($cursor: String, $owner: String!, $repo: String!, $maxFilesChanged: Int, $num: Int!) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $num) {
number
files(first: $maxFilesChanged, after: $cursor) {
edges {
node {
path
}
}
pageInfo {
endCursor
hasNextPage
}
}
}
}
}`,
cursor,
maxFilesChanged,
owner: this.owner,
repo: this.repo,
num,
});
return {node: response.repository.pullRequest} as PREdge;
}
/**
* Find the SHA of the commit at the provided tag.
*
* @param {string} name Tag name
* @returns {string} The SHA of the commit
* @throws {GitHubAPIError} on an API error
*/
getTagSha = wrapAsync(async (name: string): Promise<string> => {
const refResponse = (await this.request(
'GET /repos/:owner/:repo/git/refs/tags/:name',
{
owner: this.owner,
repo: this.repo,
name,
}
)) as {data: GitRefResponse};
return refResponse.data.object.sha;
});
/**
* Find the "last" merged PR given a headBranch. "last" here means
* the most recently created. Includes all associated files.
*
* @param {string} headBranch - e.g. "release-please/branches/main"
* @returns {MergedGitHubPRWithFiles} - if found, otherwise undefined.
* @throws {GitHubAPIError} on an API error
*/
async lastMergedPRByHeadBranch(
headBranch: string
): Promise<MergedGitHubPRWithFiles | undefined> {
const baseBranch = await this.getDefaultBranch();
const response: Repository<PullRequests> = await this.graphqlRequest({
query: `query lastMergedPRByHeadBranch($owner: String!, $repo: String!, $baseBranch: String!, $headBranch: String!) {
repository(owner: $owner, name: $repo) {
pullRequests(baseRefName: $baseBranch, states: MERGED, orderBy: {field: CREATED_AT, direction: DESC}, first: 1, headRefName: $headBranch) {
nodes {
title
body
number
mergeCommit {
oid
}
files(first: 100) {
nodes {
path
}
pageInfo {
hasNextPage
endCursor
}
}
labels(first: 10) {
nodes {
name
}
}
}
}
}
}`,
owner: this.owner,
repo: this.repo,
baseBranch,
headBranch,
});
let result: MergedGitHubPRWithFiles | undefined = undefined;
const pr = response.repository.pullRequests.nodes[0];
if (pr) {
const files = pr.files.nodes.map(({path}) => path);
let hasMoreFiles = pr.files.pageInfo.hasNextPage;
let cursor = pr.files.pageInfo.endCursor;
while (hasMoreFiles) {
const next = await this.pullRequestFiles(pr.number, cursor);
const nextFiles = next.node.files.edges.map(fe => fe.node.path);
files.push(...nextFiles);
cursor = next.node.files.pageInfo.endCursor;
hasMoreFiles = next.node.files.pageInfo.hasNextPage;
}
result = {
sha: pr.mergeCommit.oid,
title: pr.title,
body: pr.body,
number: pr.number,
baseRefName: baseBranch,
headRefName: headBranch,
files,
labels: pr.labels.nodes.map(({name}) => name),
};
}
return result;
}
/**
* If we can't find a release branch (a common cause of this, as an example
* is that we might be dealing with the first relese), use the last semver
* tag that's available on the repository:
*
* TODO: it would be good to not need to maintain this logic, and the
* logic that introspects version based on the prior release PR.
*
* @param {string} prefix If provided, filter the tags with this prefix
* @param {boolean} preRelease Whether or not to include pre-releases
* @return {GitHubTag|undefined}
* @throws {GitHubAPIError} on an API error *
*/
async latestTagFallback(
prefix?: string,
preRelease = false
): Promise<GitHubTag | undefined> {
const tags: {[version: string]: GitHubTag} = await this.allTags(prefix);
const versions = Object.keys(tags).filter(t => {
// remove any pre-releases from the list:
return preRelease || !t.includes('-');
});
// no tags have been created yet.
if (versions.length === 0) return undefined;
// We use a slightly modified version of semver's sorting algorithm, which
// prefixes the numeric part of a pre-release with '0's, so that
// 010 is greater than > 002.
versions.sort((v1, v2) => {
if (v1.includes('-')) {
const [prefix, suffix] = v1.split('-');
v1 = prefix + '-' + suffix.replace(/[a-zA-Z.]/, '').padStart(6, '0');
}
if (v2.includes('-')) {
const [prefix, suffix] = v2.split('-');
v2 = prefix + '-' + suffix.replace(/[a-zA-Z.]/, '').padStart(6, '0');
}
return semver.rcompare(v1, v2);
});
return {
name: tags[versions[0]].name,
sha: tags[versions[0]].sha,
version: tags[versions[0]].version,
};
}
private allTags = wrapAsync(
async (
prefix?: string
): Promise<{
[version: string]: GitHubTag;
}> => {
// If we've fallen back to using allTags, support "-", "@", and "/" as a
// suffix separating the library name from the version #. This allows
// a repository to be seamlessly be migrated from a tool like lerna:
const prefixes: string[] = [];
if (prefix) {
prefix = prefix.substring(0, prefix.length - 1);
for (const suffix of ['-', '@', '/']) {
prefixes.push(`${prefix}${suffix}`);
}
}
const tags: {[version: string]: GitHubTag} = {};
for await (const response of this.octokit.paginate.iterator(
this.decoratePaginateOpts({
method: 'GET',
url: `/repos/${this.owner}/${this.repo}/tags?per_page=100`,
})
)) {
response.data.forEach(data => {
// For monorepos, a prefix can be provided, indicating that only tags
// matching the prefix should be returned:
if (!isReposListResponse(data)) return;
let version = data.name;
if (prefix) {
let match = false;
for (prefix of prefixes) {
if (data.name.startsWith(prefix)) {
version = data.name.replace(prefix, '');
match = true;
}
}
if (!match) return;
}
if (semver.valid(version)) {
version = semver.valid(version) as string;
tags[version] = {sha: data.commit.sha, name: data.name, version};
}
});
}
return tags;
}
);
private async mergeCommitsGraphQL(
cursor?: string
): Promise<PullRequestHistory | null> {
const targetBranch = await this.getDefaultBranch();
const response = await this.graphqlRequest({
query: `query pullRequestsSince($owner: String!, $repo: String!, $num: 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
}
}
}
sha: oid
message
}
pageInfo {
hasNextPage
endCursor
}
}
}
}
}
}
}`,
cursor,
owner: this.owner,
repo: this.repo,
num: 25,
targetBranch,
});
// if the branch does exist, return null
if (!response.repository.ref) {
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[];
return {
pageInfo: history.pageInfo,
data: commits.map(graphCommit => {
const commit = {
sha: graphCommit.sha,
message: graphCommit.message,
files: [] as string[],
};
const pullRequest = graphCommit.associatedPullRequests.nodes.find(
pr => {
return pr.mergeCommit && pr.mergeCommit.oid === graphCommit.sha;
}
);
if (pullRequest) {
return {
commit,
pullRequest: {
sha: commit.sha,
number: pullRequest.number,
baseRefName: pullRequest.baseRefName,
headRefName: pullRequest.headRefName,
title: pullRequest.title,
body: pullRequest.body,
labels: pullRequest.labels.nodes.map(node => node.name),
},
};
}
return {
commit,
};
}),
};
}
/**
* Search through commit history to find the latest commit that matches to
* provided filter.
*
* @param {CommitFilter} filter - Callback function that returns whether a
* commit/pull request matches certain criteria
* @param {number} maxResults - Limit the number of results searched.
* Defaults to unlimited.
* @returns {CommitWithPullRequest}
* @throws {GitHubAPIError} on an API error
*/
async findMergeCommit(
filter: CommitFilter,
maxResults: number = Number.MAX_SAFE_INTEGER
): Promise<CommitWithPullRequest | undefined> {
const generator = this.mergeCommitIterator(maxResults);
for await (const commitWithPullRequest of generator) {
if (
filter(commitWithPullRequest.commit, commitWithPullRequest.pullRequest)
) {
return commitWithPullRequest;
}
}
return undefined;
}
/**
* Iterate through commit history with a max number of results scanned.
*
* @param maxResults {number} maxResults - Limit the number of results searched.
* Defaults to unlimited.
* @yields {CommitWithPullRequest}
* @throws {GitHubAPIError} on an API error
*/
async *mergeCommitIterator(maxResults: number = Number.MAX_SAFE_INTEGER) {
let cursor: string | undefined = undefined;
let results = 0;
while (results < maxResults) {
const response: PullRequestHistory | null =
await this.mergeCommitsGraphQL(cursor);
// 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;
}
}
/**
* Iterate through merged pull requests with a max number of results scanned.
*
* @param maxResults {number} maxResults - Limit the number of results searched.
* Defaults to unlimited.
* @yields {MergedGitHubPR}
* @throws {GitHubAPIError} on an API error
*/
async *mergedPullRequestIterator(
branch: string,
maxResults: number = Number.MAX_SAFE_INTEGER
) {
let page = 1;
const results = 0;
while (results < maxResults) {
const pullRequests = await this.findMergedPullRequests(branch, page);
// no response usually means we ran out of results
if (pullRequests.length === 0) {
break;
}
for (let i = 0; i < pullRequests.length; i++) {
yield pullRequests[i];
}
page += 1;
}
}
/**
* Returns the list of commits to the default branch after the provided filter
* query has been satified.
*
* @param {CommitFilter} filter - Callback function that returns whether a
* commit/pull request matches certain criteria
* @param {number} maxResults - Limit the number of results searched.
* Defaults to unlimited.
* @returns {Commit[]} - List of commits to current branch
* @throws {GitHubAPIError} on an API error
*/
async commitsSince(
filter: CommitFilter,
maxResults: number = Number.MAX_SAFE_INTEGER
): Promise<Commit[]> {
const commits: Commit[] = [];
const generator = this.mergeCommitIterator(maxResults);
for await (const commitWithPullRequest of generator) {
if (
filter(commitWithPullRequest.commit, commitWithPullRequest.pullRequest)
) {
break;
}
commits.push(commitWithPullRequest.commit);
}
return commits;
}