Repository navigation
Expand file tree
/
Copy pathGithubUtils.ts
More file actions
544 lines (488 loc) Β· 19.9 KB
/
Copy pathGithubUtils.ts
File metadata and controls
544 lines (488 loc) Β· 19.9 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
import type {Octokit as OctokitCore} from '@octokit/core';
import type {graphql} from '@octokit/graphql/types';
import type {PaginateInterface} from '@octokit/plugin-paginate-rest';
import type {Api, RestEndpointMethodTypes} from '@octokit/plugin-rest-endpoint-methods';
/* eslint-disable @typescript-eslint/naming-convention */
import * as core from '@actions/core';
import {getOctokitOptions, GitHub} from '@actions/github/lib/utils';
import {paginateRest} from '@octokit/plugin-paginate-rest';
import {throttling} from '@octokit/plugin-throttling';
import {RequestError} from '@octokit/request-error';
import CONST from './CONST';
// @octokit/plugin-rest-endpoint-methods no longer exports its `RestEndpointMethods` type directly, only `Api`
// (which wraps it as `{rest: RestEndpointMethods}`), so it's derived here instead.
type RestEndpointMethods = Api['rest'];
// These response shapes come from `RestEndpointMethodTypes` rather than `@octokit/openapi-types` directly.
// openapi-types is only a transitive dependency here, so importing it by name resolves to whatever version
// npm hoists β which can differ from the one the endpoint methods were generated against, making otherwise
// identical types mutually unassignable (e.g. `issue.id` is `number` in one and `number | bigint` in the other).
type OctokitIssueItem = RestEndpointMethodTypes['issues']['listForRepo']['response']['data'][number];
type ListForRepoMethod = RestEndpointMethods['issues']['listForRepo'];
type OctokitCommit = RestEndpointMethodTypes['repos']['listCommits']['response']['data'][number];
type CommitType = {
commit: string;
subject: string;
authorName: string;
date: string;
};
type OctokitArtifact = RestEndpointMethodTypes['actions']['listArtifactsForRepo']['response']['data']['artifacts'][number];
type OctokitPR = RestEndpointMethodTypes['pulls']['list']['response']['data'][number];
type CreateCommentResponse = RestEndpointMethodTypes['issues']['createComment']['response'];
type ListCommentsResponse = RestEndpointMethodTypes['issues']['listComments']['response'];
type InternalOctokit = OctokitCore & Api & {paginate: PaginateInterface};
class GithubUtils {
static internalOctokit: InternalOctokit | undefined;
/**
* Initialize internal octokit.
* NOTE: When using GithubUtils in CI, you don't need to call this manually.
*/
static initOctokitWithToken(token: string) {
const Octokit = GitHub.plugin(throttling, paginateRest);
// Save a copy of octokit used in this class
this.internalOctokit = new Octokit(
getOctokitOptions(token, {
throttle: {
retryAfterBaseValue: 2000,
onRateLimit: (retryAfter, options, octokit, retryCount) => {
console.warn(`Request quota exhausted for request ${options.method} ${options.url}`);
// Retry five times when hitting a rate limit error, then give up
if (retryCount <= 5) {
console.log(`Retrying after ${retryAfter} seconds!`);
return true;
}
},
onSecondaryRateLimit: (retryAfter, options) => {
// does not retry, only logs a warning
console.warn(`Abuse detected for request ${options.method} ${options.url}`);
},
},
}),
);
}
/**
* Default initialize method assuming running in CI, getting the token from an input.
*
* @private
*/
static initOctokit() {
const token = process.env.GITHUB_TOKEN ?? core.getInput('GITHUB_TOKEN', {required: true});
if (!token) {
console.error('GitHubUtils could not find GITHUB_TOKEN');
process.exit(1);
}
this.initOctokitWithToken(token);
}
/**
* Either give an existing instance of Octokit rest or create a new one
*
* @readonly
* @static
*/
static get octokit(): RestEndpointMethods {
if (!this.internalOctokit) {
this.initOctokit();
}
// eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style
return (this.internalOctokit as InternalOctokit).rest;
}
/**
* Get the graphql instance from internal octokit.
* @readonly
* @static
*/
static get graphql(): graphql {
if (!this.internalOctokit) {
this.initOctokit();
}
// eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style
return (this.internalOctokit as InternalOctokit).graphql;
}
/**
* Either give an existing instance of Octokit paginate or create a new one
*
* @readonly
* @static
*/
static get paginate(): PaginateInterface {
if (!this.internalOctokit) {
this.initOctokit();
}
// eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style
return (this.internalOctokit as InternalOctokit).paginate;
}
/**
* Fetch all pull requests given a list of PR numbers.
*/
static fetchAllPullRequests(pullRequestNumbers: number[], repo: string = CONST.APP_REPO): Promise<OctokitPR[] | void> {
const oldestPR = pullRequestNumbers.sort((a, b) => a - b).at(0);
return this.paginate(
this.octokit.pulls.list,
{
owner: CONST.GITHUB_OWNER,
repo,
state: 'all',
sort: 'created',
direction: 'desc',
per_page: 100,
},
({data}, done) => {
if (data.find((pr) => pr.number === oldestPR)) {
done();
}
return data;
},
)
.then((prList) => prList?.filter((pr) => pullRequestNumbers.includes(pr.number)) ?? [])
.catch((err) => console.error('Failed to get PR list', err));
}
static getPullRequestMergerLogin(pullRequestNumber: number): Promise<string | undefined> {
return this.octokit.pulls
.get({
owner: CONST.GITHUB_OWNER,
repo: CONST.APP_REPO,
pull_number: pullRequestNumber,
})
.then(({data: pullRequest}) => pullRequest.merged_by?.login);
}
static getPullRequestBody(pullRequestNumber: number): Promise<string | null> {
return this.octokit.pulls
.get({
owner: CONST.GITHUB_OWNER,
repo: CONST.APP_REPO,
pull_number: pullRequestNumber,
})
.then(({data: pullRequestComment}) => pullRequestComment.body);
}
static async getPullRequestMergeBaseSHA(pullRequestNumber: number): Promise<string> {
const {data: pullRequest} = await this.octokit.pulls.get({
owner: CONST.GITHUB_OWNER,
repo: CONST.APP_REPO,
pull_number: pullRequestNumber,
});
const {data: comparison} = await this.octokit.repos.compareCommits({
owner: CONST.GITHUB_OWNER,
repo: CONST.APP_REPO,
base: pullRequest.base.ref,
head: pullRequest.head.sha,
});
return comparison.merge_base_commit.sha;
}
static getAllReviewComments(pullRequestNumber: number): Promise<string[]> {
return this.paginate(
this.octokit.pulls.listReviews,
{
owner: CONST.GITHUB_OWNER,
repo: CONST.APP_REPO,
pull_number: pullRequestNumber,
per_page: 100,
},
(response) => response.data.map((review) => review.body),
);
}
static getAllComments(issueNumber: number): Promise<Array<string | undefined>> {
return this.paginate(
this.octokit.issues.listComments,
{
owner: CONST.GITHUB_OWNER,
repo: CONST.APP_REPO,
issue_number: issueNumber,
per_page: 100,
},
(response) => response.data.map((comment) => comment.body),
);
}
static getAllCommentDetails(issueNumber: number): Promise<ListCommentsResponse['data']> {
return this.paginate(
this.octokit.issues.listComments,
{
owner: CONST.GITHUB_OWNER,
repo: CONST.APP_REPO,
issue_number: issueNumber,
per_page: 100,
},
(response) => response.data,
);
}
/**
* Create comment on pull request
*/
static createComment(repo: string, number: number, messageBody: string): Promise<CreateCommentResponse> {
console.log(`Writing comment on #${number}`);
return this.octokit.issues.createComment({
owner: CONST.GITHUB_OWNER,
repo,
issue_number: number,
body: messageBody,
});
}
/**
* Collapse a comment as spam. Only exposed over GraphQL, and unlike rewriting the body it leaves the
* original text intact and can be undone from the UI.
*/
static minimizeCommentAsSpam(commentNodeID: string): Promise<unknown> {
console.log(`Minimizing comment ${commentNodeID} as spam`);
return this.graphql(
`mutation($subjectId: ID!) {
minimizeComment(input: {subjectId: $subjectId, classifier: SPAM}) {
minimizedComment {
isMinimized
}
}
}`,
{subjectId: commentNodeID},
);
}
/**
* Get the most recent workflow run for the given New Expensify workflow.
*/
/* eslint-disable rulesdir/no-default-id-values */
static getLatestWorkflowRunID(workflow: string | number): Promise<number> {
console.log(`Fetching New Expensify workflow runs for ${workflow}...`);
return this.octokit.actions
.listWorkflowRuns({
owner: CONST.GITHUB_OWNER,
repo: CONST.APP_REPO,
workflow_id: workflow,
})
.then((response) => response.data.workflow_runs.at(0)?.id ?? -1);
}
/**
* List workflow runs for the repository.
*/
static async listWorkflowRunsForRepo(
options: {
per_page?: number;
status?:
| 'completed'
| 'action_required'
| 'cancelled'
| 'failure'
| 'neutral'
| 'skipped'
| 'stale'
| 'success'
| 'timed_out'
| 'in_progress'
| 'queued'
| 'requested'
| 'waiting';
} = {},
) {
return this.octokit.actions.listWorkflowRunsForRepo({
owner: CONST.GITHUB_OWNER,
repo: CONST.APP_REPO,
per_page: options.per_page ?? 50,
...(options.status && {status: options.status}),
});
}
/**
* Get the workflow run URL for a specific commit SHA and workflow file.
* Returns the HTML URL of the matching run, or undefined if not found.
*/
static async getWorkflowRunURLForCommit(commitSha: string, workflowFile: string): Promise<string | undefined> {
try {
const response = await this.octokit.actions.listWorkflowRuns({
owner: CONST.GITHUB_OWNER,
repo: CONST.APP_REPO,
workflow_id: workflowFile,
head_sha: commitSha,
per_page: 1,
});
return response.data.workflow_runs.at(0)?.html_url;
} catch (error) {
console.warn(`Failed to find workflow run for commit ${commitSha}:`, error);
return undefined;
}
}
/**
* Generate the URL of an New Expensify pull request given the PR number.
*/
static getPullRequestURLFromNumber(value: number, repositoryURL: string): string {
return `${repositoryURL}/pull/${value}`;
}
/**
* Parse the pull request number from a URL.
*
* @throws {Error} If the URL is not a valid Github Pull Request.
*/
static getPullRequestNumberFromURL(URL: string): number {
const matches = URL.match(CONST.PULL_REQUEST_REGEX);
if (!Array.isArray(matches) || matches.length !== 2) {
throw new Error(`Provided URL ${URL} is not a Github Pull Request!`);
}
return Number.parseInt(matches[1], 10);
}
/**
* Parse the issue number from a URL.
*
* @throws {Error} If the URL is not a valid Github Issue.
*/
static getIssueNumberFromURL(URL: string): number {
const matches = URL.match(CONST.ISSUE_REGEX);
if (!Array.isArray(matches) || matches.length !== 2) {
throw new Error(`Provided URL ${URL} is not a Github Issue!`);
}
return Number.parseInt(matches[1], 10);
}
/**
* Parse the issue or pull request number from a URL.
*
* @throws {Error} If the URL is not a valid Github Issue or Pull Request.
*/
static getIssueOrPullRequestNumberFromURL(URL: string): number {
const matches = URL.match(CONST.ISSUE_OR_PULL_REQUEST_REGEX);
if (!Array.isArray(matches) || matches.length !== 2) {
throw new Error(`Provided URL ${URL} is not a valid Github Issue or Pull Request!`);
}
return Number.parseInt(matches[1], 10);
}
/**
* Return the login of the actor who closed an issue or PR. If the issue is not closed, return an empty string.
*/
static getActorWhoClosedIssue(issueNumber: number): Promise<string> {
return this.paginate(this.octokit.issues.listEvents, {
owner: CONST.GITHUB_OWNER,
repo: CONST.APP_REPO,
issue_number: issueNumber,
per_page: 100,
})
.then((events) => events.filter((event) => event.event === 'closed'))
.then((closedEvents) => closedEvents.at(-1)?.actor?.login ?? '');
}
/**
* Returns a single artifact by name. If none is found, it returns undefined.
*/
static getArtifactByName(artifactName: string): Promise<OctokitArtifact | undefined> {
return this.octokit.actions
.listArtifactsForRepo({
owner: CONST.GITHUB_OWNER,
repo: CONST.APP_REPO,
per_page: 1,
name: artifactName,
})
.then((response) => response.data.artifacts.at(0));
}
/**
* Given an artifact ID, returns the download URL to a zip file containing the artifact.
*/
static getArtifactDownloadURL(artifactId: number): Promise<string> {
return this.octokit.actions
.downloadArtifact({
owner: CONST.GITHUB_OWNER,
repo: CONST.APP_REPO,
artifact_id: artifactId,
archive_format: 'zip',
})
.then((response) => response.url);
}
/**
* Get the contents of a file from the API at a given ref as a string.
*/
static async getFileContents(path: string, ref: string = CONST.DEFAULT_BASE_REF): Promise<string> {
const {data} = await this.octokit.repos.getContent({
owner: CONST.GITHUB_OWNER,
repo: CONST.APP_REPO,
path,
ref,
});
if (Array.isArray(data)) {
throw new Error(`Provided path ${path} refers to a directory, not a file`);
}
if (!('content' in data)) {
throw new Error(`Provided path ${path} is invalid`);
}
return Buffer.from(data.content, 'base64').toString('utf8');
}
static async getPullRequestChangedSVGFileNames(pullRequestNumber: number): Promise<string[]> {
const files = this.paginate(
this.octokit.pulls.listFiles,
{
owner: CONST.GITHUB_OWNER,
repo: CONST.APP_REPO,
pull_number: pullRequestNumber,
per_page: 100,
},
(response) => response.data.filter((file) => file.filename.endsWith('.svg') && (file.status === 'added' || file.status === 'modified')).map((file) => file.filename),
);
return files;
}
/**
* Get commits between two tags via the GitHub API
*/
static async getCommitHistoryBetweenTags(fromTag: string, toTag: string, repositoryName: string): Promise<CommitType[]> {
console.log('Getting pull requests merged between the following tags:', fromTag, toTag);
core.startGroup('Fetching paginated commits:');
try {
let allCommits: OctokitCommit[] = [];
let page = 1;
const perPage = 250;
let hasMorePages = true;
while (hasMorePages) {
core.info(`π Fetching page ${page} of commits...`);
const response = await this.octokit.repos.compareCommits({
owner: CONST.GITHUB_OWNER,
repo: repositoryName,
base: fromTag,
head: toTag,
per_page: perPage,
page,
});
// Check if we got a proper response with commits
if (response.data?.commits && Array.isArray(response.data.commits)) {
if (page === 1) {
core.info(`π Total commits: ${response.data.total_commits ?? 'unknown'}`);
}
core.info(`β
compareCommits API returned ${response.data.commits.length} commits for page ${page}`);
allCommits = allCommits.concat(response.data.commits);
// Check if we got fewer commits than requested or if we've reached the total
const totalCommits = response.data.total_commits;
if (response.data.commits.length < perPage || (totalCommits && allCommits.length >= totalCommits)) {
hasMorePages = false;
} else {
page++;
}
} else {
core.warning('β οΈ GitHub API returned unexpected response format');
hasMorePages = false;
}
}
core.info(`π Successfully fetched ${allCommits.length} total commits`);
core.endGroup();
console.log('');
return allCommits.map(
(commit): CommitType => ({
commit: commit.sha,
subject: commit.commit.message,
authorName: commit.commit.author?.name ?? 'Unknown',
date: commit.commit.committer?.date ?? '',
}),
);
} catch (error) {
if (error instanceof RequestError && error.status === 404) {
core.error(
`ββ Failed to get commits with the GitHub API. The base tag ('${fromTag}') or head tag ('${toTag}') likely doesn't exist on the remote repository. If this is the case, create or push them.`,
);
}
core.endGroup();
console.log('');
throw error;
}
}
static async getPullRequestDiff(pullRequestNumber: number): Promise<string> {
if (!this.internalOctokit) {
this.initOctokit();
}
// eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style
const response = await (this.internalOctokit as InternalOctokit).request('GET /repos/{owner}/{repo}/pulls/{pull_number}', {
owner: CONST.GITHUB_OWNER,
repo: CONST.APP_REPO,
pull_number: pullRequestNumber,
mediaType: {
format: 'diff',
},
});
return response.data as unknown as string;
}
}
export default GithubUtils;
export type {OctokitIssueItem, ListForRepoMethod, InternalOctokit, CreateCommentResponse, ListCommentsResponse, CommitType};