-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathgithub-provider.mts
More file actions
343 lines (308 loc) · 9.17 KB
/
Copy pathgithub-provider.mts
File metadata and controls
343 lines (308 loc) · 9.17 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
import { UNKNOWN_VALUE } from '@socketsecurity/lib-stable/constants/sentinels'
import { debug, debugDir } from '@socketsecurity/lib-stable/debug/output'
import { isNonEmptyString } from '@socketsecurity/lib-stable/strings/predicates'
import {
cacheFetch,
getOctokit,
getOctokitGraphql,
withGitHubRetry,
} from './github.mts'
import { gitDeleteRemoteBranch } from './operations.mts'
import {
GQL_PAGE_SENTINEL,
GQL_PR_STATE_CLOSED,
GQL_PR_STATE_MERGED,
GQL_PR_STATE_OPEN,
} from '../../constants/github.mts'
import { formatErrorWithDetail } from '../error/errors.mts'
import type {
AddCommentConfig,
CreatePrConfig,
ListPrsConfig,
PrMatch,
PrProvider,
PrResponse,
UpdatePrConfig,
} from './provider.mts'
export type GqlPrNode = {
author?:
| {
login: string
}
| undefined
baseRefName: string
headRefName: string
mergeStateStatus:
| 'BEHIND'
| 'BLOCKED'
| 'CLEAN'
| 'DIRTY'
| 'DRAFT'
| 'HAS_HOOKS'
| 'UNKNOWN'
| 'UNSTABLE'
number: number
state: 'OPEN' | 'CLOSED' | 'MERGED'
title: string
}
export type GqlPullRequestsResponse = {
repository: {
pullRequests: {
pageInfo: {
endCursor: string | undefined
hasNextPage: boolean
}
nodes: GqlPrNode[]
}
}
}
/**
* GitHub provider for Pull Request operations.
*
* Implements the PrProvider interface using GitHub's REST and GraphQL APIs via
* Octokit.
*/
export class GitHubProvider implements PrProvider {
async createPr(config: CreatePrConfig): Promise<PrResponse> {
const {
base,
body,
head,
owner,
repo,
retries = 3,
title,
} = { __proto__: null, ...config } as typeof config
const octokit = getOctokit()
const octokitPullsCreateParams = { base, body, head, owner, repo, title }
debugDir({ octokitPullsCreateParams })
const result = await withGitHubRetry(
async () => {
const response = await octokit.pulls.create(octokitPullsCreateParams)
return response
},
`creating pull request for ${owner}/${repo}`,
retries,
)
if (!result.ok) {
throw new Error(result.cause ?? result.message)
}
const response = result.data
return {
number: response.data.number,
state: response.data.merged_at
? 'merged'
: response.data.state === 'closed'
? 'closed'
: 'open',
url: response.data.html_url,
}
}
async updatePr(config: UpdatePrConfig): Promise<void> {
const { base, head, owner, prNumber, repo } = {
__proto__: null,
...config,
} as typeof config
const octokit = getOctokit()
// Merge the base branch into the head branch to update the PR.
const mergeResult = await withGitHubRetry(
() =>
octokit.repos.merge({
// The target branch (source).
head: base,
owner,
repo,
// The PR branch (destination).
base: head,
}),
`updating PR #${prNumber}`,
)
if (!mergeResult.ok) {
throw new Error(mergeResult.cause || mergeResult.message)
}
debug(`pr: updating stale PR #${prNumber}`)
// Check if update resulted in conflicts.
const prDetailsResult = await withGitHubRetry(
() =>
octokit.pulls.get({
owner,
pull_number: prNumber,
repo,
}),
`fetching PR #${prNumber} details`,
)
if (!prDetailsResult.ok) {
throw new Error(prDetailsResult.cause || prDetailsResult.message)
}
if (prDetailsResult.data.data.mergeable_state === 'dirty') {
debug(`pr: PR #${prNumber} has conflicts after update`)
// Add comment explaining conflict.
const commentResult = await withGitHubRetry(
() =>
octokit.issues.createComment({
body:
'This PR has merge conflicts after updating from the base branch. ' +
'Please resolve conflicts manually or close this PR and re-run `socket fix` ' +
'to generate a new fix.',
issue_number: prNumber,
owner,
repo,
}),
`adding conflict comment to PR #${prNumber}`,
)
if (commentResult.ok) {
debug(`pr: added conflict comment to PR #${prNumber}`)
}
}
}
async listPrs(config: ListPrsConfig): Promise<PrMatch[]> {
const {
author,
ghsaId,
owner,
repo,
states: statesValue = 'all',
} = { __proto__: null, ...config } as typeof config
const checkAuthor = isNonEmptyString(author)
const octokitGraphql = getOctokitGraphql()
const matches: PrMatch[] = []
const states = getGitHubPrStates(statesValue)
try {
let cursor: string | undefined = undefined
let hasNextPage = true
let pageIndex = 0
// Include owner in cache key to avoid collisions with same repo name.
const gqlCacheKey = `${owner}::${repo}-pr-graphql-snapshot-${states.join('-').toLowerCase()}`
while (hasNextPage) {
const gqlResp = await cacheFetch(
`${gqlCacheKey}-page-${pageIndex}`,
/* c8 ignore start - cacheFetch factory only fires on cache miss; tests pass mocked cached values directly */
() =>
octokitGraphql<GqlPullRequestsResponse>(
`
query PullRequests($owner: String!, $repo: String!, $states: [PullRequestState!], $after: String) {
repository(owner: $owner, name: $repo) {
pullRequests(first: 100, states: $states, after: $after, orderBy: {field: CREATED_AT, direction: DESC}) {
pageInfo {
hasNextPage
endCursor
}
nodes {
author {
login
}
baseRefName
headRefName
mergeStateStatus
number
state
title
}
}
}
}
`,
{
after: cursor,
owner,
repo,
states,
},
),
/* c8 ignore stop */
)
const { nodes, pageInfo } = gqlResp?.repository?.pullRequests ?? {
nodes: [],
pageInfo: { endCursor: undefined, hasNextPage: false },
}
for (let i = 0, { length } = nodes; i < length; i += 1) {
const node = nodes[i]!
const login = node.author?.login
const matchesAuthor = checkAuthor ? login === author : true
// Note: Branch pattern matching removed - caller should filter.
if (matchesAuthor) {
matches.push({
...node,
author: login ?? UNKNOWN_VALUE,
})
}
}
// Continue to next page.
hasNextPage = pageInfo.hasNextPage
cursor = pageInfo.endCursor
pageIndex += 1
/* c8 ignore start - GQL_PAGE_SENTINEL safety limit; tests page through at most a few pages */
if (pageIndex === GQL_PAGE_SENTINEL) {
debug(
`GraphQL pagination reached safety limit (${GQL_PAGE_SENTINEL} pages) for ${owner}/${repo}`,
)
break
}
/* c8 ignore stop */
// Early exit optimization: if we found matches and only looking for specific GHSA,
// we can stop pagination since we likely found what we need.
if (matches.length > 0 && ghsaId) {
break
}
}
} catch (e) {
debug(`GraphQL pagination failed for ${owner}/${repo}`)
debugDir(e)
}
return matches
}
async deleteBranch(branch: string): Promise<boolean> {
try {
const success = await gitDeleteRemoteBranch(branch)
if (success) {
debug(`pr: deleted merged branch ${branch}`)
} else {
debug(`pr: failed to delete branch ${branch}`)
}
return success
} catch (e) {
// Don't treat this as a hard error - branch might already be deleted.
debug(formatErrorWithDetail(`pr: failed to delete branch ${branch}`, e))
debugDir(e)
return false
}
}
async addComment(config: AddCommentConfig): Promise<void> {
const { body, owner, prNumber, repo } = {
__proto__: null,
...config,
} as typeof config
const octokit = getOctokit()
const result = await withGitHubRetry(
() =>
octokit.issues.createComment({
body,
issue_number: prNumber,
owner,
repo,
}),
`adding comment to PR #${prNumber}`,
)
if (!result.ok) {
throw new Error(result.cause || result.message)
}
debug(`pr: added comment to PR #${prNumber}`)
}
getProviderName(): 'github' {
return 'github'
}
supportsGraphQL(): boolean {
return true
}
}
export function getGitHubPrStates(
statesValue: NonNullable<ListPrsConfig['states']>,
): string[] {
return (
typeof statesValue === 'string'
? statesValue.toLowerCase() === 'all'
? [GQL_PR_STATE_OPEN, GQL_PR_STATE_CLOSED, GQL_PR_STATE_MERGED]
: [statesValue]
: [statesValue]
).map(s => s.toUpperCase())
}