-
Notifications
You must be signed in to change notification settings - Fork 45
/
octokit.ts
464 lines (414 loc) · 14.4 KB
/
octokit.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { GitHub as GitHubAPI } from '@actions/github'
import { Octokit } from '@octokit/rest'
import { exec } from 'child_process'
import { safeLog } from '../common/utils'
import { Comment, GitHub, GitHubIssue, Issue, Query, User } from './api'
let numRequests = 0
export const getNumRequests = () => numRequests
export class OctoKit implements GitHub {
private _octokit: GitHubAPI
protected get octokit(): GitHubAPI {
numRequests++
return this._octokit
}
// when in readonly mode, record labels just-created so at to not throw unneccesary errors
protected mockLabels: Set<string> = new Set()
constructor(
protected token: string,
protected params: { repo: string; owner: string },
protected options: { readonly: boolean } = { readonly: false },
) {
this._octokit = new GitHubAPI(token)
}
// TODO: just iterate over the issues in a page here instead of making caller do it
async *query(query: Query): AsyncIterableIterator<GitHubIssue[]> {
const q = query.q + ` repo:${this.params.owner}/${this.params.repo}`
const options = this.octokit.search.issuesAndPullRequests.endpoint.merge({
...query,
q,
per_page: 100,
headers: { Accept: 'application/vnd.github.squirrel-girl-preview+json' },
})
let pageNum = 0
const timeout = async () => {
if (pageNum < 2) {
/* pass */
} else if (pageNum < 4) {
await new Promise((resolve) => setTimeout(resolve, 10000))
} else {
await new Promise((resolve) => setTimeout(resolve, 30000))
}
}
for await (const pageResponse of this.octokit.paginate.iterator(options)) {
await timeout()
numRequests++
const page: Array<Octokit.SearchIssuesAndPullRequestsResponseItemsItem> = pageResponse.data
safeLog(`Page ${++pageNum}: ${page.map(({ number }) => number).join(' ')}`)
yield page.map(
(issue) =>
new OctoKitIssue(this.token, this.params, this.octokitIssueToIssue(issue), this.options),
)
}
}
async createIssue(owner: string, repo: string, title: string, body: string): Promise<void> {
safeLog(`Creating issue \`${title}\` on ${owner}/${repo}`)
if (!this.options.readonly) await this.octokit.issues.create({ owner, repo, title, body })
}
protected octokitIssueToIssue(
issue: Octokit.IssuesGetResponse | Octokit.SearchIssuesAndPullRequestsResponseItemsItem,
): Issue {
return {
author: { name: issue.user.login, isGitHubApp: issue.user.type === 'Bot' },
body: issue.body,
number: issue.number,
title: issue.title,
labels: (issue.labels as Octokit.IssuesGetLabelResponse[]).map((label) => label.name),
open: issue.state === 'open',
locked: (issue as any).locked,
numComments: issue.comments,
reactions: (issue as any).reactions,
assignee: issue.assignee?.login ?? (issue as Octokit.IssuesGetResponse).assignees?.[0]?.login,
assignees:
(issue as Octokit.IssuesGetResponse).assignees?.map((assignee) => assignee.login) ?? [],
milestoneId: issue.milestone?.number ?? null,
createdAt: +new Date(issue.created_at),
updatedAt: +new Date(issue.updated_at),
closedAt: issue.closed_at ? +new Date((issue.closed_at as unknown) as string) : undefined,
}
}
private writeAccessCache: Record<string, boolean> = {}
async hasWriteAccess(user: User): Promise<boolean> {
if (user.name in this.writeAccessCache) {
safeLog('Got permissions from cache for ' + user)
return this.writeAccessCache[user.name]
}
safeLog('Fetching permissions for ' + user)
const permissions = (
await this.octokit.repos.getCollaboratorPermissionLevel({
...this.params,
username: user.name,
})
).data.permission
return (this.writeAccessCache[user.name] = permissions === 'admin' || permissions === 'write')
}
async repoHasLabel(name: string): Promise<boolean> {
try {
await this.octokit.issues.getLabel({ ...this.params, name })
return true
} catch (err) {
if (err.status === 404) {
return this.options.readonly && this.mockLabels.has(name)
}
throw err
}
}
async createLabel(name: string, color: string, description: string): Promise<void> {
safeLog('Creating label ' + name)
if (!this.options.readonly)
await this.octokit.issues.createLabel({ ...this.params, color, description, name })
else this.mockLabels.add(name)
}
async deleteLabel(name: string): Promise<void> {
safeLog('Deleting label ' + name)
try {
if (!this.options.readonly) await this.octokit.issues.deleteLabel({ ...this.params, name })
} catch (err) {
if (err.status === 404) {
return
}
throw err
}
}
async readConfig(path: string): Promise<any> {
safeLog('Reading config at ' + path)
const repoPath = `.github/${path}.json`
try {
const data = (await this.octokit.repos.getContents({ ...this.params, path: repoPath })).data
if ('type' in data && data.type === 'file') {
if (data.encoding === 'base64' && data.content) {
return JSON.parse(Buffer.from(data.content, 'base64').toString('utf-8'))
}
throw Error(`Could not read contents "${data.content}" in encoding "${data.encoding}"`)
}
throw Error('Found directory at config path when expecting file' + JSON.stringify(data))
} catch (e) {
throw Error('Error with config file at ' + repoPath + ': ' + JSON.stringify(e))
}
}
async releaseContainsCommit(release: string, commit: string): Promise<'yes' | 'no' | 'unknown'> {
const isHash = (s: string) => /^[a-fA-F0-9]*$/.test(s)
if (!isHash(release) || !isHash(commit)) return 'unknown'
return new Promise((resolve, reject) =>
exec(`git -C ./repo merge-base --is-ancestor ${commit} ${release}`, (err) => {
if (!err || err.code === 1) {
resolve(!err ? 'yes' : 'no')
} else if (err.message.includes(`Not a valid commit name ${release}`)) {
// release branch is forked. Probably in endgame. Not released.
resolve('no')
} else if (err.message.includes(`Not a valid commit name ${commit}`)) {
// commit is probably in a different repo.
resolve('unknown')
} else {
reject(err)
}
}),
)
}
async dispatch(title: string): Promise<void> {
safeLog('Dispatching ' + title)
if (!this.options.readonly)
await this.octokit.repos.createDispatchEvent({ ...this.params, event_type: title })
}
}
export class OctoKitIssue extends OctoKit implements GitHubIssue {
constructor(
token: string,
protected params: { repo: string; owner: string },
private issueData: { number: number } | Issue,
options: { readonly: boolean } = { readonly: false },
) {
super(token, params, options)
safeLog('running bot on issue', issueData.number)
}
async addAssignee(assignee: string): Promise<void> {
safeLog('Adding assignee ' + assignee + ' to ' + this.issueData.number)
if (!this.options.readonly) {
await this.octokit.issues.addAssignees({
...this.params,
issue_number: this.issueData.number,
assignees: [assignee],
})
}
}
async removeAssignee(assignee: string): Promise<void> {
safeLog('Removing assignee ' + assignee + ' to ' + this.issueData.number)
if (!this.options.readonly) {
await this.octokit.issues.removeAssignees({
...this.params,
issue_number: this.issueData.number,
assignees: [assignee],
})
}
}
async closeIssue(): Promise<void> {
safeLog('Closing issue ' + this.issueData.number)
if (!this.options.readonly)
await this.octokit.issues.update({
...this.params,
issue_number: this.issueData.number,
state: 'closed',
})
}
async lockIssue(): Promise<void> {
safeLog('Locking issue ' + this.issueData.number)
if (!this.options.readonly)
await this.octokit.issues.lock({ ...this.params, issue_number: this.issueData.number })
}
async getIssue(): Promise<Issue> {
if (isIssue(this.issueData)) {
safeLog('Got issue data from query result ' + this.issueData.number)
return this.issueData
}
safeLog('Fetching issue ' + this.issueData.number)
const issue = (
await this.octokit.issues.get({
...this.params,
issue_number: this.issueData.number,
mediaType: { previews: ['squirrel-girl'] },
})
).data
return (this.issueData = this.octokitIssueToIssue(issue))
}
async postComment(body: string): Promise<void> {
safeLog(`Posting comment on ${this.issueData.number}`)
if (!this.options.readonly)
await this.octokit.issues.createComment({
...this.params,
issue_number: this.issueData.number,
body,
})
}
async deleteComment(id: number): Promise<void> {
safeLog(`Deleting comment ${id} on ${this.issueData.number}`)
if (!this.options.readonly)
await this.octokit.issues.deleteComment({
owner: this.params.owner,
repo: this.params.repo,
comment_id: id,
})
}
async setMilestone(milestoneId: number) {
safeLog(`Setting milestone for ${this.issueData.number} to ${milestoneId}`)
if (!this.options.readonly)
await this.octokit.issues.update({
...this.params,
issue_number: this.issueData.number,
milestone: milestoneId,
})
}
async *getComments(last?: boolean): AsyncIterableIterator<Comment[]> {
safeLog('Fetching comments for ' + this.issueData.number)
const response = this.octokit.paginate.iterator(
this.octokit.issues.listComments.endpoint.merge({
...this.params,
issue_number: this.issueData.number,
per_page: 100,
...(last ? { per_page: 1, page: (await this.getIssue()).numComments } : {}),
}),
)
for await (const page of response) {
numRequests++
yield (page.data as Octokit.IssuesListCommentsResponseItem[]).map((comment) => ({
author: { name: comment.user.login, isGitHubApp: comment.user.type === 'Bot' },
body: comment.body,
id: comment.id,
timestamp: +new Date(comment.created_at),
}))
}
}
async addLabel(name: string): Promise<void> {
safeLog(`Adding label ${name} to ${this.issueData.number}`)
if (!(await this.repoHasLabel(name))) {
throw Error(`Action could not execute becuase label ${name} is not defined.`)
}
if (!this.options.readonly)
await this.octokit.issues.addLabels({
...this.params,
issue_number: this.issueData.number,
labels: [name],
})
}
async getAssigner(assignee: string): Promise<string> {
const options = this.octokit.issues.listEventsForTimeline.endpoint.merge({
...this.params,
issue_number: this.issueData.number,
})
let assigner: string | undefined
for await (const event of this.octokit.paginate.iterator(options)) {
numRequests++
const timelineEvents = event.data as Octokit.IssuesListEventsForTimelineResponseItem[]
for (const timelineEvent of timelineEvents) {
if (
timelineEvent.event === 'assigned' &&
(timelineEvent as any).assignee.login === assignee
) {
assigner = timelineEvent.actor.login
}
}
}
if (!assigner) {
throw Error('Expected to find ' + assignee + ' in issue timeline but did not.')
}
return assigner
}
async removeLabel(name: string): Promise<void> {
safeLog(`Removing label ${name} from ${this.issueData.number}`)
try {
if (!this.options.readonly)
await this.octokit.issues.removeLabel({
...this.params,
issue_number: this.issueData.number,
name,
})
} catch (err) {
if (err.status === 404) {
safeLog(`Label ${name} not found on issue`)
return
}
throw err
}
}
async getClosingInfo(
alreadyChecked: number[] = [],
): Promise<{ hash: string | undefined; timestamp: number } | undefined> {
if (alreadyChecked.includes(this.issueData.number)) {
return undefined
}
alreadyChecked.push(this.issueData.number)
if ((await this.getIssue()).open) {
return
}
const closingHashComment = /(?:\\|\/)closedWith (?:https:\/\/github\.com\/microsoft\/vscode\/commit\/)?([a-fA-F0-9]{7,40})/
const options = this.octokit.issues.listEventsForTimeline.endpoint.merge({
...this.params,
issue_number: this.issueData.number,
})
let closingCommit: { hash: string | undefined; timestamp: number } | undefined
const crossReferencing: number[] = []
for await (const event of this.octokit.paginate.iterator(options)) {
numRequests++
const timelineEvents = event.data as Octokit.IssuesListEventsForTimelineResponseItem[]
for (const timelineEvent of timelineEvents) {
if (
(timelineEvent.event === 'closed' || timelineEvent.event === 'merged') &&
timelineEvent.commit_id &&
timelineEvent.commit_url
.toLowerCase()
.includes(`/${this.params.owner}/${this.params.repo}/`.toLowerCase())
) {
closingCommit = {
hash: timelineEvent.commit_id,
timestamp: +new Date(timelineEvent.created_at),
}
}
if (timelineEvent.event === 'reopened') {
closingCommit = undefined
}
if (
timelineEvent.event === 'commented' &&
!((timelineEvent as any).body as string)?.includes('UNABLE_TO_LOCATE_COMMIT_MESSAGE') &&
closingHashComment.test((timelineEvent as any).body)
) {
closingCommit = {
hash: closingHashComment.exec((timelineEvent as any).body)![1],
timestamp: +new Date(timelineEvent.created_at),
}
}
if (
timelineEvent.event === 'cross-referenced' &&
(timelineEvent as any).source?.issue?.number &&
(timelineEvent as any).source?.issue?.pull_request?.url.includes(
`/${this.params.owner}/${this.params.repo}/`.toLowerCase(),
)
) {
crossReferencing.push((timelineEvent as any).source.issue.number)
}
}
}
// If we dont have any closing info, try to get it from linked issues (PRs).
// If there's a linked issue that was closed at almost the same time, guess it was a PR that closed this.
if (!closingCommit) {
for (const id of crossReferencing.reverse()) {
const closed = await new OctoKitIssue(this.token, this.params, {
number: id,
}).getClosingInfo(alreadyChecked)
if (closed) {
if (Math.abs(closed.timestamp - ((await this.getIssue()).closedAt ?? 0)) < 5000) {
closingCommit = closed
break
}
}
}
}
safeLog(`Got ${JSON.stringify(closingCommit)} as closing commit of ${this.issueData.number}`)
return closingCommit
}
}
function isIssue(object: any): object is Issue {
const isIssue =
'author' in object &&
'body' in object &&
'title' in object &&
'labels' in object &&
'open' in object &&
'locked' in object &&
'number' in object &&
'numComments' in object &&
'reactions' in object &&
'milestoneId' in object
return isIssue
}