-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathpull-request.mts
More file actions
494 lines (451 loc) · 13.4 KB
/
Copy pathpull-request.mts
File metadata and controls
494 lines (451 loc) · 13.4 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
import { RequestError } from '@octokit/request-error'
import { UNKNOWN_VALUE } from '@socketsecurity/lib-stable/constants/sentinels'
import { debug, debugDir } from '@socketsecurity/lib-stable/debug/output'
import { errorMessage } from '@socketsecurity/lib-stable/errors/message'
import { isNonEmptyString } from '@socketsecurity/lib-stable/strings/predicates'
import {
getSocketFixBranchPattern,
getSocketFixPullRequestBody,
getSocketFixPullRequestTitle,
} from './git.mts'
import { logPrEvent } from './pr-lifecycle-logger.mts'
import {
GQL_PAGE_SENTINEL,
GQL_PR_STATE_CLOSED,
GQL_PR_STATE_MERGED,
GQL_PR_STATE_OPEN,
} from '../../constants/github.mts'
import { formatErrorWithDetail } from '../../util/error/errors.mjs'
import {
cacheFetch,
getOctokit,
getOctokitGraphql,
handleGraphqlError,
withGitHubRetry,
writeCache,
} from '../../util/git/github.mts'
import type { GhsaDetails, Pr } from '../../util/git/github.mts'
import { createPrProvider } from '../../util/git/provider-factory.mts'
import type { OctokitResponse } from '@octokit/types'
import type { JsonContent } from '@socketsecurity/lib-stable/fs/types'
export type GQL_MERGE_STATE_STATUS =
| 'BEHIND'
| 'BLOCKED'
| 'CLEAN'
| 'DIRTY'
| 'DRAFT'
| 'HAS_HOOKS'
| 'UNKNOWN'
| 'UNSTABLE'
export type GQL_PR_STATE = 'OPEN' | 'CLOSED' | 'MERGED'
export type PrMatch = {
readonly __proto__: null
author: string
baseRefName: string
headRefName: string
mergeStateStatus: GQL_MERGE_STATE_STATUS
number: number
state: GQL_PR_STATE
title: string
}
export function appendMatchingPrNodes(
contextualMatches: ContextualPrMatch[],
nodes: GqlPrNode[],
config: {
author: string | undefined
branchPattern: RegExp
cacheKey: string
checkAuthor: boolean
data: JsonContent
},
): void {
const { author, branchPattern, cacheKey, checkAuthor, data } = {
__proto__: null,
...config,
} as typeof config
for (let i = 0, { length } = nodes; i < length; i += 1) {
const node = nodes[i]!
const login = node.author?.login
if (
(!checkAuthor || login === author) &&
branchPattern.test(node.headRefName)
) {
contextualMatches.push({
__proto__: null,
context: {
__proto__: null,
apiType: 'graphql',
cacheKey,
data,
entry: node,
index: i,
parent: nodes,
},
match: { __proto__: null, ...node, author: login ?? UNKNOWN_VALUE },
})
}
}
}
export function classifyOpenPrError(error: unknown): OpenPrResult {
if (!(error instanceof RequestError)) {
return { ok: false, reason: 'unknown', error: error as Error }
}
const errors = (
error.response?.data as { errors?: unknown | undefined } | undefined
)?.errors
const errorMessages = Array.isArray(errors)
? errors.map(
(detail: {
message?: string | undefined
resource?: string | undefined
field?: string | undefined
code?: string | undefined
}) =>
detail.message?.trim() ??
`${detail.resource}.${detail.field} (${detail.code})`,
)
: []
if (
errorMessages.some(message =>
message.toLowerCase().includes('pull request already exists'),
)
) {
return { ok: false, reason: 'already_exists', error }
}
if (errorMessages.length > 0) {
return {
ok: false,
reason: 'validation_error',
error,
details: errorMessages.map(message => `- ${message}`).join('\n'),
}
}
if (error.status === 403 || error.status === 401) {
return { ok: false, reason: 'permission_denied', error }
}
return error.status && error.status >= 500
? { ok: false, reason: 'network_error', error }
: { ok: false, reason: 'unknown', error }
}
export async function cleanupSocketFixPrs(
owner: string,
repo: string,
ghsaId: string,
): Promise<PrMatch[]> {
const contextualMatches = await getSocketFixPrsWithContext(owner, repo, {
ghsaId,
})
if (!contextualMatches.length) {
return []
}
const cachesToSave = new Map<string, JsonContent>()
const provider = await createPrProvider()
const settledMatches = await Promise.allSettled(
contextualMatches.map(async ({ context, match }) => {
// Update stale PRs.
// https://docs.github.com/en/graphql/reference/enums#mergestatestatus
if (match.mergeStateStatus === 'BEHIND') {
const { number: prNum } = match
const prRef = `PR #${prNum}`
try {
// Update the PR using the provider.
await provider.updatePr({
owner,
repo,
prNumber: prNum,
head: match.headRefName,
base: match.baseRefName,
})
debug(`pr: updated stale ${prRef}`)
logPrEvent('updated', prNum, ghsaId, 'Updated from base branch')
// Update cache entry - only GraphQL is used now.
context.entry.mergeStateStatus = 'CLEAN'
// Mark cache to be saved.
cachesToSave.set(context.cacheKey, context.data)
} catch (e) {
debug(formatErrorWithDetail(`pr: failed to update ${prRef}`, e))
debugDir(e)
}
}
// Clean up merged PR branches.
if (match.state === GQL_PR_STATE_MERGED) {
const { number: prNum } = match
const prRef = `PR #${prNum}`
try {
const success = await provider.deleteBranch(match.headRefName)
if (success) {
debug(`pr: deleted merged branch ${match.headRefName} for ${prRef}`)
logPrEvent('merged', prNum, ghsaId, 'Branch cleaned up')
/* c8 ignore start - branch-delete failure path; depends on remote git state we don't control in tests */
} else {
debug(
`pr: failed to delete branch ${match.headRefName} for ${prRef}`,
)
}
/* c8 ignore stop */
} catch (e) {
// Don't treat this as a hard error - branch might already be deleted.
debug(
formatErrorWithDetail(
`pr: failed to delete branch ${match.headRefName} for ${prRef}`,
e,
),
)
debugDir(e)
}
}
return match
}),
)
if (cachesToSave.size) {
await Promise.allSettled(
Array.from(cachesToSave).map(({ 0: key, 1: data }) =>
writeCache(key, data),
),
)
}
const fulfilledMatches = settledMatches.filter(
(r): r is PromiseFulfilledResult<PrMatch> => r.status === 'fulfilled',
)
return fulfilledMatches.map(r => r.value)
}
export type PrAutoMergeState = {
enabled: boolean
details?: string[] | undefined
}
export type SocketPrsOptions = {
author?: string | undefined
ghsaId?: string | undefined
states?: 'all' | GQL_PR_STATE | GQL_PR_STATE[] | undefined
}
export async function getSocketFixPrs(
owner: string,
repo: string,
options?: SocketPrsOptions | undefined,
): Promise<PrMatch[]> {
return (await getSocketFixPrsWithContext(owner, repo, options)).map(
d => d.match,
)
}
export type GqlPrNode = {
author?:
| {
login: string
}
| undefined
baseRefName: string
headRefName: string
mergeStateStatus: GQL_MERGE_STATE_STATUS
number: number
state: GQL_PR_STATE
title: string
}
export type GqlPullRequestsResponse = {
repository: {
pullRequests: {
pageInfo: {
hasNextPage: boolean
endCursor: string | undefined
}
nodes: GqlPrNode[]
}
}
}
export type ContextualPrMatch = {
readonly __proto__: null
context: {
readonly __proto__: null
apiType: 'graphql' | 'rest'
cacheKey: string
data: JsonContent
entry: GqlPrNode
index: number
parent: GqlPrNode[]
}
match: PrMatch
}
export async function getSocketFixPrsWithContext(
owner: string,
repo: string,
options?: SocketPrsOptions | undefined,
): Promise<ContextualPrMatch[]> {
const {
author,
ghsaId,
states: statesValue = 'all',
} = {
__proto__: null,
...options,
} as SocketPrsOptions
const branchPattern = getSocketFixBranchPattern(ghsaId)
const checkAuthor = isNonEmptyString(author)
const octokitGraphql = getOctokitGraphql()
const contextualMatches: ContextualPrMatch[] = []
const states = (
typeof statesValue === 'string'
? statesValue.toLowerCase() === 'all'
? [GQL_PR_STATE_OPEN, GQL_PR_STATE_CLOSED, GQL_PR_STATE_MERGED]
: [statesValue]
: statesValue
).map(s => s.toUpperCase())
try {
let hasNextPage = true
let cursor: string | undefined = undefined
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(
`
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
}
}
}
}
`,
{
owner,
repo,
states,
after: cursor,
},
),
/* c8 ignore stop */
)) as GqlPullRequestsResponse
const { nodes, pageInfo } = gqlResp?.repository?.pullRequests ?? {
nodes: [],
pageInfo: { hasNextPage: false, endCursor: undefined },
}
appendMatchingPrNodes(contextualMatches, nodes, {
author,
branchPattern,
cacheKey: `${gqlCacheKey}-page-${pageIndex}`,
checkAuthor,
data: gqlResp,
})
// 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 (contextualMatches.length > 0 && ghsaId) {
break
}
}
} catch (e) {
// Use centralized error handling for better error messages.
const errorResult = handleGraphqlError(
e,
`listing PRs for ${owner}/${repo}`,
)
// errorResult is always ok: false from handleGraphqlError.
if (!errorResult.ok) {
debug(errorResult.cause ?? errorResult.message)
}
}
return contextualMatches
}
export type OpenSocketFixPrOptions = {
baseBranch?: string | undefined
cwd?: string | undefined
ghsaDetails?: Map<string, GhsaDetails> | undefined
retries?: number | undefined
}
export type OpenPrResult =
| { ok: true; pr: OctokitResponse<Pr> }
| { ok: false; reason: 'already_exists'; error: RequestError }
| {
ok: false
reason: 'validation_error'
error: RequestError
details: string
}
| { ok: false; reason: 'permission_denied'; error: RequestError }
| { ok: false; reason: 'network_error'; error: RequestError }
| { ok: false; reason: 'unknown'; error: Error }
export async function openSocketFixPr(
owner: string,
repo: string,
branch: string,
ghsaIds: string[],
options?: OpenSocketFixPrOptions | undefined,
): Promise<OpenPrResult> {
const {
baseBranch = 'main',
ghsaDetails,
retries = 3,
} = {
__proto__: null,
...options,
} as OpenSocketFixPrOptions
const provider = await createPrProvider()
try {
const result = await provider.createPr({
owner,
repo,
title: getSocketFixPullRequestTitle(ghsaIds),
head: branch,
base: baseBranch,
body: getSocketFixPullRequestBody(ghsaIds, ghsaDetails),
retries,
})
// Convert provider response to Octokit format for backward compatibility.
const octokit = getOctokit()
const prDetailsResult = await withGitHubRetry(
() =>
octokit.pulls.get({
owner,
repo,
pull_number: result.number,
}),
`fetching PR #${result.number} details`,
)
if (!prDetailsResult.ok) {
return {
ok: false,
reason: 'network_error',
error: new Error(
prDetailsResult.cause || prDetailsResult.message,
) as RequestError,
}
}
return { ok: true, pr: prDetailsResult.data }
} catch (e) {
return reportOpenPrError(e)
}
function reportOpenPrError(e: unknown): OpenPrResult {
debug(formatErrorWithDetail('Failed to create pull request', e))
debugDir(e)
debug(`Failed to create pull request: ${errorMessage(e)}`)
return classifyOpenPrError(e)
}
}