opencode-github-pr 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +440 -2
- package/demo/fixtures.ts +224 -0
- package/dist/pr-dashboard.tui.js +8710 -0
- package/package.json +65 -4
- package/plugins/app/DashboardView.tsx +373 -0
- package/plugins/app/PRRow.tsx +241 -0
- package/plugins/app/StatusMessage.tsx +22 -0
- package/plugins/app/actions.tsx +25 -0
- package/plugins/app/config.ts +165 -0
- package/plugins/app/theme.ts +53 -0
- package/plugins/app/usePRData.ts +364 -0
- package/plugins/domain/format.ts +27 -0
- package/plugins/domain/messages.ts +183 -0
- package/plugins/domain/pr-filters.ts +40 -0
- package/plugins/domain/pr-links.ts +12 -0
- package/plugins/domain/pr-status.ts +128 -0
- package/plugins/domain/types.ts +94 -0
- package/plugins/infra/git.ts +416 -0
- package/plugins/infra/github-enterprise.ts +31 -0
- package/plugins/infra/loader.ts +356 -0
- package/plugins/infra/mappers.ts +93 -0
- package/plugins/infra/octokit.ts +131 -0
- package/plugins/infra/queries.ts +155 -0
- package/plugins/pr-dashboard.ts +8 -0
- package/plugins/pr-dashboard.tui.tsx +238 -0
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
// High-level data loaders for the PR dashboard.
|
|
2
|
+
// Backed by Octokit (REST + GraphQL), which gives us built-in throttling,
|
|
3
|
+
// retry, and timeouts.
|
|
4
|
+
|
|
5
|
+
import { getOctokit, invalidateOctokit } from "./octokit"
|
|
6
|
+
import { type Repo, type PR, type PRScope, type PRStatusFilter } from "../domain/types"
|
|
7
|
+
import { mapPullFromGraphQL } from "./mappers"
|
|
8
|
+
import {
|
|
9
|
+
PULL_REQUESTS_QUERY,
|
|
10
|
+
PULL_REQUESTS_QUERY_LEGACY,
|
|
11
|
+
PULL_REQUESTS_SEARCH_QUERY,
|
|
12
|
+
PULL_REQUESTS_SEARCH_QUERY_LEGACY,
|
|
13
|
+
} from "./queries"
|
|
14
|
+
|
|
15
|
+
export type { Repo, PR }
|
|
16
|
+
|
|
17
|
+
export const MIN_PAGES_PER_BATCH = 4
|
|
18
|
+
export const DEFAULT_TUI_PAGES_PER_BATCH = 4
|
|
19
|
+
export const DEFAULT_PR_BATCH_SIZE = 4
|
|
20
|
+
export const MAX_SEARCH_RESULTS = 1_000
|
|
21
|
+
export const DEFAULT_RECENT_PRS_LIMIT = 5
|
|
22
|
+
export const MAX_RECENT_PRS_LIMIT = 100
|
|
23
|
+
|
|
24
|
+
// Status is pushed into GitHub's GraphQL query so each listing has its own
|
|
25
|
+
// cursor and closed PRs cannot displace open PRs (or vice versa).
|
|
26
|
+
export type PRListing = PRStatusFilter
|
|
27
|
+
|
|
28
|
+
const LISTING_STATES: Record<PRListing, string[]> = {
|
|
29
|
+
open: ["OPEN"],
|
|
30
|
+
closed: ["CLOSED", "MERGED"],
|
|
31
|
+
all: ["OPEN", "CLOSED", "MERGED"],
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export type RepositoryPRsResult = {
|
|
35
|
+
prs: PR[]
|
|
36
|
+
viewerLogin: string | null
|
|
37
|
+
totalCount: number | null
|
|
38
|
+
filteredPRCount: number
|
|
39
|
+
searchResultsFetched: number
|
|
40
|
+
supplementalPRCount: number
|
|
41
|
+
hasMore: boolean
|
|
42
|
+
fetchedPages: number
|
|
43
|
+
endCursor: string | null
|
|
44
|
+
limitReached: boolean
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
48
|
+
return typeof value === "object" && value !== null
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function readPullRequestPage(value: unknown, connectionName: "pullRequests" | "search"): {
|
|
52
|
+
nodes: unknown[]
|
|
53
|
+
viewerLogin: string | null
|
|
54
|
+
totalCount: number | null
|
|
55
|
+
hasNextPage: boolean
|
|
56
|
+
endCursor: string | null
|
|
57
|
+
} {
|
|
58
|
+
const root = isRecord(value) ? value : {}
|
|
59
|
+
const viewer = isRecord(root.viewer) ? root.viewer : {}
|
|
60
|
+
const repository = isRecord(root.repository) ? root.repository : {}
|
|
61
|
+
const rawConnection = connectionName === "search" ? root.search : repository.pullRequests
|
|
62
|
+
const connection = isRecord(rawConnection) ? rawConnection : {}
|
|
63
|
+
const pageInfo = isRecord(connection.pageInfo) ? connection.pageInfo : {}
|
|
64
|
+
const rawTotalCount = connectionName === "search" ? connection.issueCount : connection.totalCount
|
|
65
|
+
return {
|
|
66
|
+
nodes: Array.isArray(connection.nodes) ? connection.nodes.filter((node) => node != null) : [],
|
|
67
|
+
viewerLogin: typeof viewer.login === "string" ? viewer.login : null,
|
|
68
|
+
totalCount: typeof rawTotalCount === "number" && Number.isFinite(rawTotalCount)
|
|
69
|
+
? rawTotalCount
|
|
70
|
+
: null,
|
|
71
|
+
hasNextPage: pageInfo.hasNextPage === true,
|
|
72
|
+
endCursor: typeof pageInfo.endCursor === "string" ? pageInfo.endCursor : null,
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function readRecentPullRequests(value: unknown): unknown[] {
|
|
77
|
+
const root = isRecord(value) ? value : {}
|
|
78
|
+
const repository = isRecord(root.repository) ? root.repository : {}
|
|
79
|
+
const connection = isRecord(repository.recentPullRequests) ? repository.recentPullRequests : {}
|
|
80
|
+
return Array.isArray(connection.nodes) ? connection.nodes.filter((node) => node != null) : []
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function matchesSearchScope(pr: PR, scope: PRScope, viewerLogin: string | null): boolean {
|
|
84
|
+
if (!viewerLogin) return false
|
|
85
|
+
const login = viewerLogin.toLowerCase()
|
|
86
|
+
return scope === "author"
|
|
87
|
+
? pr.authorLogin.toLowerCase() === login
|
|
88
|
+
: scope === "assignee" && pr.assigneeLogins.some((assignee) => assignee.toLowerCase() === login)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Wraps octokit.graphql to return partial data when some fields error.
|
|
92
|
+
// GitHub's GraphQL API returns both `data` and `errors` when specific
|
|
93
|
+
// fields are inaccessible. Octokit throws on any errors, but the partial
|
|
94
|
+
// data is still usable — errored fields are null in the response.
|
|
95
|
+
async function graphqlPartial(
|
|
96
|
+
query: string,
|
|
97
|
+
vars: Record<string, unknown>,
|
|
98
|
+
requestTimeoutMs: number,
|
|
99
|
+
options: {
|
|
100
|
+
requiredConnection: "pullRequests" | "search"
|
|
101
|
+
optionalRecentPullRequests?: boolean
|
|
102
|
+
fallbackQuery?: string
|
|
103
|
+
onLegacyFallback?: () => void
|
|
104
|
+
},
|
|
105
|
+
): Promise<unknown> {
|
|
106
|
+
const octokit = await getOctokit(requestTimeoutMs)
|
|
107
|
+
try {
|
|
108
|
+
return await octokit.graphql(query, vars)
|
|
109
|
+
} catch (e: unknown) {
|
|
110
|
+
if (isRecord(e) && e.status === 401) invalidateOctokit(octokit)
|
|
111
|
+
if (isRecord(e) && options.fallbackQuery && reportsUnknownPullRequestStatusFields(e)) {
|
|
112
|
+
options.onLegacyFallback?.()
|
|
113
|
+
return graphqlPartial(
|
|
114
|
+
options.fallbackQuery,
|
|
115
|
+
vars,
|
|
116
|
+
requestTimeoutMs,
|
|
117
|
+
{
|
|
118
|
+
requiredConnection: options.requiredConnection,
|
|
119
|
+
optionalRecentPullRequests: options.optionalRecentPullRequests,
|
|
120
|
+
},
|
|
121
|
+
)
|
|
122
|
+
}
|
|
123
|
+
if (isRecord(e) && "data" in e && e.data) {
|
|
124
|
+
const data = isRecord(e.data) ? e.data : {}
|
|
125
|
+
const errors = Array.isArray(e.errors) ? e.errors : []
|
|
126
|
+
const hasFatalType = errors.some((error) => {
|
|
127
|
+
if (isOptionalRecentPullRequestsError(error, options.optionalRecentPullRequests)) return false
|
|
128
|
+
if (!isRecord(error) || typeof error.type !== "string") return false
|
|
129
|
+
if (error.type === "RATE_LIMITED") return true
|
|
130
|
+
if (error.type !== "NOT_FOUND" && error.type !== "FORBIDDEN") return false
|
|
131
|
+
// A nested field can be unavailable while the PR listing remains
|
|
132
|
+
// useful. Root/connection errors make the listing itself unreliable.
|
|
133
|
+
return !Array.isArray(error.path) || error.path.length <= 2
|
|
134
|
+
})
|
|
135
|
+
const root = isRecord(data.repository) ? data.repository : null
|
|
136
|
+
const hasRootFailure =
|
|
137
|
+
data.repository === null ||
|
|
138
|
+
(options.requiredConnection === "search" && data.search === null) ||
|
|
139
|
+
errors.some((error) => {
|
|
140
|
+
if (!isRecord(error) || !Array.isArray(error.path)) return false
|
|
141
|
+
if (isOptionalRecentPullRequestsError(error, options.optionalRecentPullRequests)) return false
|
|
142
|
+
const path = error.path
|
|
143
|
+
return (
|
|
144
|
+
(path.length === 1 && (path[0] === "repository" || path[0] === "search")) ||
|
|
145
|
+
(path.length === 2 &&
|
|
146
|
+
path[0] === "repository" &&
|
|
147
|
+
path[1] === "pullRequests") ||
|
|
148
|
+
(options.requiredConnection === "search" &&
|
|
149
|
+
path.length <= 2 &&
|
|
150
|
+
path[0] === "search")
|
|
151
|
+
)
|
|
152
|
+
})
|
|
153
|
+
if (!hasFatalType && !hasRootFailure && root !== null) return e.data
|
|
154
|
+
}
|
|
155
|
+
throw e
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function isOptionalRecentPullRequestsError(
|
|
160
|
+
error: unknown,
|
|
161
|
+
optionalRecentPullRequests = false,
|
|
162
|
+
): boolean {
|
|
163
|
+
if (!optionalRecentPullRequests || !isRecord(error) || !Array.isArray(error.path)) return false
|
|
164
|
+
return error.path[0] === "repository" && error.path[1] === "recentPullRequests"
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function reportsUnknownPullRequestStatusFields(error: Record<string, unknown>): boolean {
|
|
168
|
+
if (!Array.isArray(error.errors) || error.errors.length === 0) return false
|
|
169
|
+
const unknownStatusField =
|
|
170
|
+
/(?:Cannot query field|Field)\s+['"]?(mergeStateStatus|reviewDecision)['"]?.*(?:doesn't exist|does not exist|on type|is not defined|unknown).*PullRequest/i
|
|
171
|
+
return error.errors.every(
|
|
172
|
+
(item) => isRecord(item) && typeof item.message === "string" && unknownStatusField.test(item.message),
|
|
173
|
+
)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export async function repositoryPRs(
|
|
177
|
+
repo: Repo | null,
|
|
178
|
+
batchSize = DEFAULT_PR_BATCH_SIZE,
|
|
179
|
+
requestTimeoutMs = 15_000,
|
|
180
|
+
listing: PRListing = "open",
|
|
181
|
+
after: string | null = null,
|
|
182
|
+
scope: PRScope = "all",
|
|
183
|
+
scopeValue: string | null = null,
|
|
184
|
+
resultsAlreadyFetched = 0,
|
|
185
|
+
recentPRsLimit = DEFAULT_RECENT_PRS_LIMIT,
|
|
186
|
+
branchOwner: string | null = repo?.owner ?? null,
|
|
187
|
+
): Promise<RepositoryPRsResult> {
|
|
188
|
+
if (!repo) {
|
|
189
|
+
return {
|
|
190
|
+
prs: [],
|
|
191
|
+
viewerLogin: null,
|
|
192
|
+
totalCount: 0,
|
|
193
|
+
filteredPRCount: 0,
|
|
194
|
+
searchResultsFetched: 0,
|
|
195
|
+
supplementalPRCount: 0,
|
|
196
|
+
hasMore: false,
|
|
197
|
+
fetchedPages: 0,
|
|
198
|
+
endCursor: null,
|
|
199
|
+
limitReached: false,
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
if (scope === "branch" && !scopeValue) {
|
|
203
|
+
return {
|
|
204
|
+
prs: [],
|
|
205
|
+
viewerLogin: null,
|
|
206
|
+
totalCount: 0,
|
|
207
|
+
filteredPRCount: 0,
|
|
208
|
+
searchResultsFetched: 0,
|
|
209
|
+
supplementalPRCount: 0,
|
|
210
|
+
hasMore: false,
|
|
211
|
+
fetchedPages: 0,
|
|
212
|
+
endCursor: null,
|
|
213
|
+
limitReached: false,
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
const isSearch = scope === "author" || scope === "assignee"
|
|
217
|
+
const requestedRecords = isSearch
|
|
218
|
+
? Math.min(batchSize, Math.max(0, MAX_SEARCH_RESULTS - resultsAlreadyFetched))
|
|
219
|
+
: batchSize
|
|
220
|
+
if (requestedRecords <= 0) {
|
|
221
|
+
return {
|
|
222
|
+
prs: [],
|
|
223
|
+
viewerLogin: null,
|
|
224
|
+
totalCount: isSearch ? Math.min(resultsAlreadyFetched, MAX_SEARCH_RESULTS) : null,
|
|
225
|
+
filteredPRCount: 0,
|
|
226
|
+
searchResultsFetched: 0,
|
|
227
|
+
supplementalPRCount: 0,
|
|
228
|
+
hasMore: false,
|
|
229
|
+
fetchedPages: 0,
|
|
230
|
+
endCursor: after,
|
|
231
|
+
limitReached: isSearch,
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
const searchQuery = isSearch
|
|
235
|
+
? [
|
|
236
|
+
`repo:${repo.owner}/${repo.repo}`,
|
|
237
|
+
"is:pr",
|
|
238
|
+
scope === "author" ? "author:@me" : "assignee:@me",
|
|
239
|
+
listing === "open" ? "is:open" : listing === "closed" ? "is:closed" : null,
|
|
240
|
+
"sort:updated-desc",
|
|
241
|
+
].filter(Boolean).join(" ")
|
|
242
|
+
: null
|
|
243
|
+
const nodes: unknown[] = []
|
|
244
|
+
let cursor = after
|
|
245
|
+
let viewerLogin: string | null = null
|
|
246
|
+
let totalCount: number | null = null
|
|
247
|
+
let fetchedPages = 0
|
|
248
|
+
let searchResultsFetched = 0
|
|
249
|
+
let recentNodes: unknown[] = []
|
|
250
|
+
let hasNextPage = false
|
|
251
|
+
let endCursor: string | null = null
|
|
252
|
+
let remainingRecords = requestedRecords
|
|
253
|
+
let legacyStatusFieldsUnsupported = false
|
|
254
|
+
let consecutiveEmptyPages = 0
|
|
255
|
+
const seenCursors = new Set<string>(cursor ? [cursor] : [])
|
|
256
|
+
do {
|
|
257
|
+
const first = Math.min(100, remainingRecords)
|
|
258
|
+
const includeRecentPRs =
|
|
259
|
+
isSearch &&
|
|
260
|
+
recentPRsLimit > 0 &&
|
|
261
|
+
!cursor &&
|
|
262
|
+
resultsAlreadyFetched === 0
|
|
263
|
+
const query = isSearch
|
|
264
|
+
? legacyStatusFieldsUnsupported ? PULL_REQUESTS_SEARCH_QUERY_LEGACY : PULL_REQUESTS_SEARCH_QUERY
|
|
265
|
+
: legacyStatusFieldsUnsupported ? PULL_REQUESTS_QUERY_LEGACY : PULL_REQUESTS_QUERY
|
|
266
|
+
const legacyQuery = isSearch ? PULL_REQUESTS_SEARCH_QUERY_LEGACY : PULL_REQUESTS_QUERY_LEGACY
|
|
267
|
+
const data = await graphqlPartial(query, isSearch ? {
|
|
268
|
+
owner: repo.owner,
|
|
269
|
+
name: repo.repo,
|
|
270
|
+
states: LISTING_STATES[listing],
|
|
271
|
+
searchQuery,
|
|
272
|
+
after: cursor,
|
|
273
|
+
first,
|
|
274
|
+
recentPRsLimit: Math.min(MAX_RECENT_PRS_LIMIT, Math.max(1, Math.floor(recentPRsLimit))),
|
|
275
|
+
includeRecentPRs,
|
|
276
|
+
} : {
|
|
277
|
+
owner: repo.owner,
|
|
278
|
+
name: repo.repo,
|
|
279
|
+
states: LISTING_STATES[listing],
|
|
280
|
+
head: scope === "branch" ? scopeValue : null,
|
|
281
|
+
after: cursor,
|
|
282
|
+
first,
|
|
283
|
+
}, requestTimeoutMs, {
|
|
284
|
+
requiredConnection: isSearch ? "search" : "pullRequests",
|
|
285
|
+
optionalRecentPullRequests: isSearch,
|
|
286
|
+
fallbackQuery: legacyStatusFieldsUnsupported ? undefined : legacyQuery,
|
|
287
|
+
onLegacyFallback: () => { legacyStatusFieldsUnsupported = true },
|
|
288
|
+
})
|
|
289
|
+
const page = readPullRequestPage(data, isSearch ? "search" : "pullRequests")
|
|
290
|
+
nodes.push(...page.nodes)
|
|
291
|
+
if (isSearch) {
|
|
292
|
+
searchResultsFetched += page.nodes.length
|
|
293
|
+
if (includeRecentPRs) recentNodes = readRecentPullRequests(data)
|
|
294
|
+
}
|
|
295
|
+
remainingRecords -= page.nodes.length
|
|
296
|
+
consecutiveEmptyPages = page.nodes.length === 0 ? consecutiveEmptyPages + 1 : 0
|
|
297
|
+
if (page.viewerLogin) viewerLogin = page.viewerLogin
|
|
298
|
+
if (page.totalCount !== null) {
|
|
299
|
+
totalCount = isSearch ? Math.min(page.totalCount, MAX_SEARCH_RESULTS) : page.totalCount
|
|
300
|
+
}
|
|
301
|
+
hasNextPage = page.hasNextPage
|
|
302
|
+
endCursor = page.endCursor
|
|
303
|
+
fetchedPages++
|
|
304
|
+
if (!hasNextPage) {
|
|
305
|
+
break
|
|
306
|
+
}
|
|
307
|
+
const nextCursor = endCursor
|
|
308
|
+
if (typeof nextCursor !== "string" || nextCursor.length === 0 || seenCursors.has(nextCursor)) {
|
|
309
|
+
throw new Error("GitHub returned an invalid or repeated pull request pagination cursor")
|
|
310
|
+
}
|
|
311
|
+
seenCursors.add(nextCursor)
|
|
312
|
+
cursor = nextCursor
|
|
313
|
+
if (consecutiveEmptyPages >= 3) break
|
|
314
|
+
} while (hasNextPage && remainingRecords > 0)
|
|
315
|
+
const mappedPRs = nodes.map(mapPullFromGraphQL)
|
|
316
|
+
const filteredPRs = scope === "branch" && branchOwner
|
|
317
|
+
? mappedPRs.filter(
|
|
318
|
+
(pr) => !!pr.headRepositoryOwnerLogin &&
|
|
319
|
+
pr.headRepositoryOwnerLogin.toLowerCase() !== branchOwner.toLowerCase(),
|
|
320
|
+
)
|
|
321
|
+
: []
|
|
322
|
+
const filteredNumbers = new Set(filteredPRs.map((pr) => pr.number))
|
|
323
|
+
const searchPRs = filteredNumbers.size > 0
|
|
324
|
+
? mappedPRs.filter((pr) => !filteredNumbers.has(pr.number))
|
|
325
|
+
: mappedPRs
|
|
326
|
+
let supplementalPRs: PR[] = []
|
|
327
|
+
if (isSearch && recentNodes.length > 0 && viewerLogin) {
|
|
328
|
+
const knownNumbers = new Set(searchPRs.map((pr) => pr.number))
|
|
329
|
+
supplementalPRs = recentNodes
|
|
330
|
+
.map(mapPullFromGraphQL)
|
|
331
|
+
.filter((pr) => matchesSearchScope(pr, scope, viewerLogin) && !knownNumbers.has(pr.number))
|
|
332
|
+
const uniqueNumbers = new Set<number>()
|
|
333
|
+
supplementalPRs = supplementalPRs.filter((pr) => {
|
|
334
|
+
if (uniqueNumbers.has(pr.number)) return false
|
|
335
|
+
uniqueNumbers.add(pr.number)
|
|
336
|
+
return true
|
|
337
|
+
})
|
|
338
|
+
}
|
|
339
|
+
const limitReached = isSearch &&
|
|
340
|
+
hasNextPage &&
|
|
341
|
+
resultsAlreadyFetched + nodes.length >= MAX_SEARCH_RESULTS
|
|
342
|
+
return {
|
|
343
|
+
prs: [...supplementalPRs, ...searchPRs],
|
|
344
|
+
viewerLogin,
|
|
345
|
+
totalCount: totalCount === null
|
|
346
|
+
? null
|
|
347
|
+
: Math.max(0, totalCount - filteredNumbers.size) + supplementalPRs.length,
|
|
348
|
+
filteredPRCount: filteredNumbers.size,
|
|
349
|
+
searchResultsFetched,
|
|
350
|
+
supplementalPRCount: supplementalPRs.length,
|
|
351
|
+
hasMore: hasNextPage && !limitReached,
|
|
352
|
+
fetchedPages,
|
|
353
|
+
endCursor,
|
|
354
|
+
limitReached,
|
|
355
|
+
}
|
|
356
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Maps raw GitHub GraphQL pull requests into the shared PR domain type.
|
|
2
|
+
|
|
3
|
+
import type { PR } from "../domain/types"
|
|
4
|
+
|
|
5
|
+
type RecordValue = Record<string, unknown>
|
|
6
|
+
|
|
7
|
+
function record(value: unknown): RecordValue {
|
|
8
|
+
return typeof value === "object" && value !== null ? value as RecordValue : {}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function string(value: unknown, fallback = ""): string {
|
|
12
|
+
return typeof value === "string" ? value : fallback
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function number(value: unknown, fallback = 0): number {
|
|
16
|
+
return typeof value === "number" && Number.isFinite(value) ? value : fallback
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function array(value: unknown): unknown[] {
|
|
20
|
+
return Array.isArray(value) ? value : []
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Maps a GraphQL PullRequest node to PR.
|
|
24
|
+
export function mapPullFromGraphQL(value: unknown): PR {
|
|
25
|
+
const p = record(value)
|
|
26
|
+
const author = record(p.author)
|
|
27
|
+
const assignees = record(p.assignees)
|
|
28
|
+
const rollup = p.statusCheckRollup == null ? null : record(p.statusCheckRollup)
|
|
29
|
+
const contexts = rollup ? record(rollup.contexts) : {}
|
|
30
|
+
const contextNodes = array(contexts.nodes)
|
|
31
|
+
const contextTotalCount = number(contexts.totalCount, contextNodes.length)
|
|
32
|
+
const reviewThreads = record(p.reviewThreads)
|
|
33
|
+
const reviewThreadNodes = array(reviewThreads.nodes)
|
|
34
|
+
const reviewThreadTotalCount = number(reviewThreads.totalCount, reviewThreadNodes.length)
|
|
35
|
+
const reviewRequests = record(p.reviewRequests)
|
|
36
|
+
const latestReviews = record(p.latestReviews)
|
|
37
|
+
return {
|
|
38
|
+
number: number(p.number),
|
|
39
|
+
title: string(p.title),
|
|
40
|
+
url: string(p.url),
|
|
41
|
+
isDraft: p.isDraft === true,
|
|
42
|
+
isMerged: p.state === "MERGED" || p.merged === true,
|
|
43
|
+
isClosed: p.state === "CLOSED" || p.state === "MERGED" || p.merged === true,
|
|
44
|
+
headRefName: string(p.headRefName),
|
|
45
|
+
headRepositoryOwnerLogin: string(record(p.headRepositoryOwner).login),
|
|
46
|
+
authorLogin: string(author.login),
|
|
47
|
+
assigneeLogins: array(assignees.nodes)
|
|
48
|
+
.map((assignee) => string(record(assignee).login))
|
|
49
|
+
.filter(Boolean),
|
|
50
|
+
additions: number(p.additions),
|
|
51
|
+
deletions: number(p.deletions),
|
|
52
|
+
baseRefName: string(p.baseRefName),
|
|
53
|
+
mergeable: string(p.mergeable, "UNKNOWN").toUpperCase(),
|
|
54
|
+
mergeStateStatus: string(p.mergeStateStatus, "UNKNOWN").toUpperCase(),
|
|
55
|
+
reviewDecision: p.reviewDecision === null
|
|
56
|
+
? null
|
|
57
|
+
: string(p.reviewDecision, "UNKNOWN").toUpperCase(),
|
|
58
|
+
statusCheckRollup: rollup ? { state: string(rollup.state, "UNKNOWN") } : null,
|
|
59
|
+
// The rollup still captures aggregate CI state when contexts are
|
|
60
|
+
// truncated, without pretending the first 100 are all of it.
|
|
61
|
+
checkStatuses: contextTotalCount > contextNodes.length
|
|
62
|
+
? null
|
|
63
|
+
: Array.isArray(contexts.nodes)
|
|
64
|
+
? contextNodes
|
|
65
|
+
.map((value) => {
|
|
66
|
+
const context = record(value)
|
|
67
|
+
return context.__typename === "CheckRun"
|
|
68
|
+
? string(context.conclusion) || string(context.status)
|
|
69
|
+
: string(context.state)
|
|
70
|
+
})
|
|
71
|
+
.filter(Boolean)
|
|
72
|
+
: null,
|
|
73
|
+
reviewThreads: Array.isArray(reviewThreads.nodes)
|
|
74
|
+
? reviewThreadNodes.map((thread) => ({ isResolved: record(thread).isResolved === true }))
|
|
75
|
+
: null,
|
|
76
|
+
reviewThreadsTruncated: reviewThreadTotalCount > reviewThreadNodes.length,
|
|
77
|
+
reviewRequests: array(reviewRequests.nodes)
|
|
78
|
+
.map((node) => record(record(node).requestedReviewer))
|
|
79
|
+
.flatMap<NonNullable<PR["reviewRequests"]>[number]>((reviewer) => {
|
|
80
|
+
const login = string(reviewer.login)
|
|
81
|
+
if (login) return [{ type: "user" as const, login }]
|
|
82
|
+
const slug = string(reviewer.slug)
|
|
83
|
+
return slug ? [{ type: "team" as const, slug }] : []
|
|
84
|
+
}),
|
|
85
|
+
latestReviews: array(latestReviews.nodes).map((value) => {
|
|
86
|
+
const review = record(value)
|
|
87
|
+
return {
|
|
88
|
+
author: { login: string(record(review.author).login) },
|
|
89
|
+
state: string(review.state),
|
|
90
|
+
}
|
|
91
|
+
}),
|
|
92
|
+
}
|
|
93
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// Octokit client factory for the PR dashboard.
|
|
2
|
+
// Auth: reads a GitHub token from the environment, then falls back to `gh auth token`.
|
|
3
|
+
//
|
|
4
|
+
// Plugins: throttling (respects X-RateLimit-Reset / Retry-After / secondary
|
|
5
|
+
// rate limits) and retry (handles 5xx and 429 with exponential backoff +
|
|
6
|
+
// jitter). doNotRetry covers 4xx that won't recover on their own.
|
|
7
|
+
|
|
8
|
+
import { Octokit } from "@octokit/rest"
|
|
9
|
+
import type { Octokit as CoreOctokit } from "@octokit/core"
|
|
10
|
+
import type { EndpointDefaults } from "@octokit/types"
|
|
11
|
+
import { throttling } from "@octokit/plugin-throttling"
|
|
12
|
+
import { retry } from "@octokit/plugin-retry"
|
|
13
|
+
import { execFile } from "node:child_process"
|
|
14
|
+
import { errorMessages } from "../domain/messages"
|
|
15
|
+
import { enterpriseApiBaseUrl, enterpriseHostname } from "./github-enterprise"
|
|
16
|
+
const OctokitWithPlugins = Octokit.plugin(throttling, retry)
|
|
17
|
+
|
|
18
|
+
function readGhAuthToken(hostname?: string): Promise<string | undefined> {
|
|
19
|
+
return new Promise((resolve) => {
|
|
20
|
+
const args = ["auth", "token"]
|
|
21
|
+
if (hostname) args.push("--hostname", hostname)
|
|
22
|
+
execFile("gh", args, {
|
|
23
|
+
encoding: "utf8",
|
|
24
|
+
windowsHide: true,
|
|
25
|
+
timeout: 5_000,
|
|
26
|
+
}, (error, stdout) => {
|
|
27
|
+
if (error) {
|
|
28
|
+
resolve(undefined)
|
|
29
|
+
return
|
|
30
|
+
}
|
|
31
|
+
const token = stdout.trim()
|
|
32
|
+
resolve(token || undefined)
|
|
33
|
+
})
|
|
34
|
+
})
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function getAuthToken(
|
|
38
|
+
env: Record<string, string | undefined> = process.env,
|
|
39
|
+
ghAuthToken: (hostname?: string) => string | undefined | Promise<string | undefined> = readGhAuthToken,
|
|
40
|
+
): Promise<string> {
|
|
41
|
+
const token = env.GITHUB_TOKEN || env.GH_TOKEN || env.GITHUB_PERSONAL_ACCESS_TOKEN
|
|
42
|
+
if (token) return token
|
|
43
|
+
const ghToken = await ghAuthToken(enterpriseHostname(env.GITHUB_ENTERPRISE_URL) ?? undefined)
|
|
44
|
+
if (ghToken) return ghToken
|
|
45
|
+
throw new Error(errorMessages.noAuthToken)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export type OctokitOpts = {
|
|
49
|
+
token?: string
|
|
50
|
+
enterpriseUrl?: string
|
|
51
|
+
fetch?: typeof globalThis.fetch
|
|
52
|
+
requestTimeoutMs?: number
|
|
53
|
+
throttle?: boolean
|
|
54
|
+
retry?: boolean
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function createOctokit(opts: OctokitOpts = {}): Octokit {
|
|
58
|
+
return new OctokitWithPlugins({
|
|
59
|
+
userAgent: "opencode-gh-pr",
|
|
60
|
+
auth: opts.token,
|
|
61
|
+
baseUrl: enterpriseApiBaseUrl(opts.enterpriseUrl) ?? undefined,
|
|
62
|
+
request: { timeout: opts.requestTimeoutMs ?? 15_000, fetch: opts.fetch },
|
|
63
|
+
throttle:
|
|
64
|
+
opts.throttle === false
|
|
65
|
+
? { enabled: false }
|
|
66
|
+
: {
|
|
67
|
+
onRateLimit: (
|
|
68
|
+
retryAfter: number,
|
|
69
|
+
options: Required<EndpointDefaults>,
|
|
70
|
+
octokit: CoreOctokit,
|
|
71
|
+
retryCount: number,
|
|
72
|
+
) => {
|
|
73
|
+
octokit.log.warn(
|
|
74
|
+
`[pr-dashboard] rate limit hit on ${options.method} ${options.url}; retry ${retryCount} after ${retryAfter}s`,
|
|
75
|
+
)
|
|
76
|
+
// Primary limits can last for an hour or more. Only let the
|
|
77
|
+
// plugin retry brief waits; longer cooldowns are surfaced to
|
|
78
|
+
// the dashboard so it can stop scheduling more requests.
|
|
79
|
+
return retryCount < 2 && retryAfter <= 5
|
|
80
|
+
},
|
|
81
|
+
onSecondaryRateLimit: (retryAfter: number, options: Required<EndpointDefaults>, octokit: CoreOctokit) => {
|
|
82
|
+
octokit.log.warn(
|
|
83
|
+
`[pr-dashboard] secondary rate limit on ${options.method} ${options.url}; would wait ${retryAfter}s, aborting`,
|
|
84
|
+
)
|
|
85
|
+
return false
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
retry:
|
|
89
|
+
opts.retry === false
|
|
90
|
+
? { enabled: false }
|
|
91
|
+
: {
|
|
92
|
+
doNotRetry: [400, 401, 403, 404, 422],
|
|
93
|
+
},
|
|
94
|
+
})
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
let cached: {
|
|
98
|
+
token: string
|
|
99
|
+
requestTimeoutMs: number
|
|
100
|
+
baseUrl: string | null
|
|
101
|
+
client: Octokit
|
|
102
|
+
} | null = null
|
|
103
|
+
|
|
104
|
+
export async function getOctokit(
|
|
105
|
+
requestTimeoutMs = 15_000,
|
|
106
|
+
resolveToken: () => Promise<string> = getAuthToken,
|
|
107
|
+
): Promise<Octokit> {
|
|
108
|
+
const enterpriseUrl = process.env.GITHUB_ENTERPRISE_URL
|
|
109
|
+
const baseUrl = enterpriseApiBaseUrl(enterpriseUrl)
|
|
110
|
+
if (cached?.baseUrl === baseUrl && cached.requestTimeoutMs === requestTimeoutMs) {
|
|
111
|
+
return cached.client
|
|
112
|
+
}
|
|
113
|
+
// A token selected for github.com must not be carried across a host change:
|
|
114
|
+
// gh may have a distinct credential for the enterprise hostname.
|
|
115
|
+
const token = cached?.baseUrl === baseUrl ? cached.token : await resolveToken()
|
|
116
|
+
const client = createOctokit({ token, requestTimeoutMs, enterpriseUrl })
|
|
117
|
+
cached = { token, requestTimeoutMs, baseUrl, client }
|
|
118
|
+
return client
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function invalidateOctokit(client: Octokit): void {
|
|
122
|
+
if (cached?.client === client) cached = null
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function setOctokit(client: Octokit | null): void {
|
|
126
|
+
if (client === null) {
|
|
127
|
+
cached = null
|
|
128
|
+
} else {
|
|
129
|
+
cached = { token: "test", requestTimeoutMs: 15_000, baseUrl: null, client }
|
|
130
|
+
}
|
|
131
|
+
}
|