Open History to see the last commit
1/**
2 * Snapshot collection: pulls open PRs/issues/discussions (with timelines) and
3 * recently closed items from the GitHub GraphQL API and normalizes them into
4 * the shapes in types.ts. Read-only — never mutates anything.
5 */
6
7import { isBotLogin } from './config'
8import type { GitHubClient } from './github'
9import type {
10 CIState,
11 ClosedItem,
12 DiscussionItem,
13 IssueItem,
14 PRItem,
15 RepoSnapshot,
16 TimelineEvent,
17 ToolsetConfig,
18} from './types'
19
20const CLOSED_LOOKBACK_DAYS = 14
21
22interface GqlActor {
23 login?: string
24 __typename?: string
25 createdAt?: string
26}
27
28interface GqlTimelineNode {
29 __typename: string
30 actor?: GqlActor | null
31 assignee?: GqlActor | null
32 requestedReviewer?: GqlActor | null
33 author?: GqlActor | null
34 createdAt?: string
35 submittedAt?: string
36 state?: string
37 body?: string
38 commit?: {
39 committedDate: string
40 author?: { user?: { login: string } | null } | null
41 } | null
42}
43
44function actorLogin(actor: GqlActor | null | undefined): string | null {
45 return actor?.login ?? null
46}
47
48function actorIsBot(
49 actor: GqlActor | null | undefined,
50 config: ToolsetConfig,
51): boolean {
52 if (actor?.__typename === 'Bot') return true
53 return isBotLogin(actorLogin(actor), config)
54}
55
56function normalizeTimeline(
57 nodes: Array<GqlTimelineNode | null>,
58 fallbackAuthor: string | null,
59 config: ToolsetConfig,
60): Array<TimelineEvent> {
61 const events: Array<TimelineEvent> = []
62 for (const node of nodes) {
63 if (!node) continue
64 if (
65 (node.__typename === 'AssignedEvent' ||
66 node.__typename === 'ReviewRequestedEvent') &&
67 node.createdAt
68 ) {
69 events.push({
70 kind:
71 node.__typename === 'AssignedEvent' ? 'assigned' : 'review-requested',
72 actor: actorLogin(node.actor),
73 subject: actorLogin(node.assignee ?? node.requestedReviewer),
74 isBot: actorIsBot(node.actor, config),
75 at: node.createdAt,
76 })
77 } else if (node.__typename === 'IssueComment' && node.createdAt) {
78 events.push({
79 kind: 'comment',
80 actor: actorLogin(node.author),
81 isBot: actorIsBot(node.author, config),
82 at: node.createdAt,
83 body: node.body ?? '',
84 })
85 } else if (node.__typename === 'PullRequestReview' && node.submittedAt) {
86 events.push({
87 kind: 'review',
88 actor: actorLogin(node.author),
89 isBot: actorIsBot(node.author, config),
90 at: node.submittedAt,
91 reviewState: node.state,
92 })
93 } else if (node.__typename === 'PullRequestCommit' && node.commit) {
94 const login = node.commit.author?.user?.login ?? fallbackAuthor
95 events.push({
96 kind: 'commit',
97 actor: login,
98 isBot: isBotLogin(login, config),
99 at: node.commit.committedDate,
100 })
101 }
102 }
103 return events
104}
105
106function normalizeCIState(state: string | null | undefined): CIState {
107 switch (state) {
108 case 'SUCCESS':
109 return 'success'
110 case 'FAILURE':
111 case 'ERROR':
112 return 'failure'
113 case 'PENDING':
114 case 'EXPECTED':
115 return 'pending'
116 default:
117 return 'unknown'
118 }
119}
120
121const COMMENT_FRAGMENT = `
122 __typename
123 ... on IssueComment { author { login __typename } createdAt body }
124`
125
126const PR_TIMELINE_FRAGMENT = `
127 ${COMMENT_FRAGMENT}
128 ... on AssignedEvent { actor { login __typename } createdAt assignee { ... on User { login } } }
129 ... on ReviewRequestedEvent { actor { login __typename } createdAt requestedReviewer { ... on User { login } } }
130 ... on PullRequestReview { author { login __typename } submittedAt state }
131 ... on PullRequestCommit { commit { committedDate author { user { login } } } }
132`
133
134const OPEN_PRS_QUERY = `
135query($owner: String!, $name: String!, $cursor: String) {
136 repository(owner: $owner, name: $name) {
137 pullRequests(states: OPEN, first: 20, after: $cursor, orderBy: {field: CREATED_AT, direction: DESC}) {
138 pageInfo { hasNextPage endCursor }
139 nodes {
140 number title url createdAt updatedAt isDraft mergeable reviewDecision
141 additions deletions changedFiles authorAssociation
142 author { login __typename ... on User { createdAt } }
143 labels(first: 20) { nodes { name } }
144 assignees(first: 10) { nodes { login } }
145 files(first: 100) { nodes { path } pageInfo { hasNextPage endCursor } }
146 reviewRequests(first: 100) { nodes { requestedReviewer { ... on User { login } } } pageInfo { hasNextPage endCursor } }
147 closingIssuesReferences(first: 10) { nodes { number } }
148 commits(last: 1) { nodes { commit { statusCheckRollup { state } } } }
149 timelineItems(first: 100, itemTypes: [ISSUE_COMMENT, PULL_REQUEST_REVIEW, PULL_REQUEST_COMMIT, ASSIGNED_EVENT, REVIEW_REQUESTED_EVENT]) {
150 pageInfo { hasNextPage endCursor }
151 nodes { ${PR_TIMELINE_FRAGMENT} }
152 }
153 }
154 }
155 }
156}`
157
158const OPEN_ISSUES_QUERY = `
159query($owner: String!, $name: String!, $cursor: String) {
160 repository(owner: $owner, name: $name) {
161 issues(states: OPEN, first: 40, after: $cursor, orderBy: {field: CREATED_AT, direction: DESC}) {
162 pageInfo { hasNextPage endCursor }
163 nodes {
164 number title url createdAt updatedAt body authorAssociation
165 author { login __typename }
166 labels(first: 20) { nodes { name } }
167 assignees(first: 10) { nodes { login } }
168 timelineItems(last: 100, itemTypes: [ISSUE_COMMENT]) {
169 nodes { ${COMMENT_FRAGMENT} }
170 }
171 }
172 }
173 }
174}`
175
176const DISCUSSIONS_QUERY = `
177query($owner: String!, $name: String!, $cursor: String) {
178 repository(owner: $owner, name: $name) {
179 discussions(first: 50, after: $cursor, states: OPEN, orderBy: {field: UPDATED_AT, direction: DESC}) {
180 pageInfo { hasNextPage endCursor }
181 nodes {
182 number title url createdAt updatedAt isAnswered upvoteCount
183 category { name }
184 author { login __typename }
185 comments(last: 20) {
186 totalCount
187 nodes { author { login __typename } createdAt }
188 }
189 }
190 }
191 }
192}`
193
194const CLOSED_SEARCH_QUERY = `
195query($query: String!, $cursor: String) {
196 search(query: $query, type: ISSUE, first: 50, after: $cursor) {
197 pageInfo { hasNextPage endCursor }
198 nodes {
199 __typename
200 ... on PullRequest {
201 number title url createdAt closedAt mergedAt
202 author { login __typename }
203 files(first: 100) { nodes { path } pageInfo { hasNextPage endCursor } }
204 timelineItems(first: 100, itemTypes: [ISSUE_COMMENT, PULL_REQUEST_REVIEW, PULL_REQUEST_COMMIT, ASSIGNED_EVENT, REVIEW_REQUESTED_EVENT]) {
205 pageInfo { hasNextPage endCursor }
206 nodes { ${PR_TIMELINE_FRAGMENT} }
207 }
208 }
209 ... on Issue {
210 number title url createdAt closedAt
211 author { login __typename }
212 timelineItems(first: 30, itemTypes: [ISSUE_COMMENT]) {
213 nodes { ${COMMENT_FRAGMENT} }
214 }
215 }
216 }
217 }
218}`
219
220async function paginate<TNode>(
221 fetchPage: (cursor: string | null) => Promise<{
222 nodes: Array<TNode | null>
223 pageInfo: { hasNextPage: boolean; endCursor: string | null }
224 }>,
225 maxPages = Infinity,
226): Promise<Array<TNode>> {
227 const all: Array<TNode> = []
228 let cursor: string | null = null
229 for (let page = 0; page < maxPages; page++) {
230 const result = await fetchPage(cursor)
231 for (const node of result.nodes) if (node !== null) all.push(node)
232 if (!result.pageInfo.hasNextPage) break
233 cursor = result.pageInfo.endCursor
234 }
235 return all
236}
237
238export async function collectSnapshot(
239 client: GitHubClient,
240 config: ToolsetConfig,
241 now: Date = new Date(),
242): Promise<RepoSnapshot> {
243 const [owner, repo] = config.repo.split('/') as [string, string]
244 const vars = { owner, name: repo }
245
246 interface Connection {
247 nodes: Array<Record<string, any> | null>
248 pageInfo: { hasNextPage: boolean; endCursor: string | null }
249 }
250
251 const ownership = await client.graphql<{
252 repository: { object: { text: string } | null }
253 }>(
254 `
255 query($owner: String!, $name: String!) {
256 repository(owner: $owner, name: $name) {
257 object(expression: "HEAD:.github/CODEOWNERS") { ... on Blob { text } }
258 }
259 }`,
260 vars,
261 )
262 if (!ownership.repository.object)
263 throw new Error('Default-branch CODEOWNERS is missing')
264
265 const prNodes = await paginate((cursor) =>
266 client
267 .graphql<{ repository: { pullRequests: Connection } }>(OPEN_PRS_QUERY, {
268 ...vars,
269 cursor,
270 })
271 .then((d) => d.repository.pullRequests),
272 )
273
274 const issueNodes = await paginate((cursor) =>
275 client
276 .graphql<{ repository: { issues: Connection } }>(OPEN_ISSUES_QUERY, {
277 ...vars,
278 cursor,
279 })
280 .then((d) => d.repository.issues),
281 )
282
283 const discussionNodes = await paginate(
284 (cursor) =>
285 client
286 .graphql<{
287 repository: { discussions: Connection }
288 }>(DISCUSSIONS_QUERY, { ...vars, cursor })
289 .then((d) => d.repository.discussions),
290 4,
291 )
292
293 const sinceDate = new Date(
294 now.getTime() - CLOSED_LOOKBACK_DAYS * 24 * 60 * 60 * 1000,
295 )
296 .toISOString()
297 .slice(0, 10)
298 const closedNodes = await paginate((cursor) =>
299 client
300 .graphql<{ search: Connection }>(CLOSED_SEARCH_QUERY, {
301 query: `repo:${config.repo} closed:>=${sinceDate}`,
302 cursor,
303 })
304 .then((d) => d.search),
305 )
306
307 // Page nested connections too: a core-owned path or review may be beyond page one.
308 for (const node of [
309 ...prNodes,
310 ...closedNodes.filter((n) => n.__typename === 'PullRequest'),
311 ]) {
312 for (const [field, selection] of [
313 ['files', 'nodes { path }'],
314 [
315 'reviewRequests',
316 'nodes { requestedReviewer { ... on User { login } } }',
317 ],
318 ['timelineItems', `nodes { ${PR_TIMELINE_FRAGMENT} }`],
319 ]) {
320 const connection = node[field!]
321 if (!connection?.pageInfo?.hasNextPage) continue
322 const remaining = await paginate((cursor) =>
323 client
324 .graphql<{
325 repository: { pullRequest: Record<string, Connection> }
326 }>(
327 `
328 query($owner: String!, $name: String!, $number: Int!, $cursor: String) {
329 repository(owner: $owner, name: $name) {
330 pullRequest(number: $number) {
331 ${field}(first: 100, after: $cursor${field === 'timelineItems' ? ', itemTypes: [ISSUE_COMMENT, PULL_REQUEST_REVIEW, PULL_REQUEST_COMMIT, ASSIGNED_EVENT, REVIEW_REQUESTED_EVENT]' : ''}) {
332 ${selection}
333 pageInfo { hasNextPage endCursor }
334 }
335 }
336 }
337 }`,
338 {
339 ...vars,
340 number: node.number,
341 cursor: cursor ?? connection.pageInfo.endCursor,
342 },
343 )
344 .then((d) => d.repository.pullRequest[field!]!),
345 )
346 connection.nodes.push(...remaining)
347 }
348 }
349
350 const prs: Array<PRItem> = prNodes.map((n) => {
351 const author = actorLogin(n.author)
352 return {
353 type: 'pr',
354 number: n.number,
355 title: n.title,
356 url: n.url,
357 author,
358 authorIsBot: actorIsBot(n.author, config),
359 authorAccountCreatedAt: n.author?.createdAt ?? null,
360 authorAssociation: n.authorAssociation ?? 'NONE',
361 createdAt: n.createdAt,
362 updatedAt: n.updatedAt,
363 isDraft: Boolean(n.isDraft),
364 mergeable: n.mergeable ?? 'UNKNOWN',
365 reviewDecision: n.reviewDecision ?? '',
366 additions: n.additions ?? 0,
367 deletions: n.deletions ?? 0,
368 changedFiles: n.changedFiles ?? 0,
369 files: (n.files?.nodes ?? [])
370 .filter(Boolean)
371 .map((f: { path: string }) => f.path),
372 labels: (n.labels?.nodes ?? [])
373 .filter(Boolean)
374 .map((l: { name: string }) => l.name),
375 assignees: (n.assignees?.nodes ?? [])
376 .filter(Boolean)
377 .map((a: { login: string }) => a.login),
378 requestedReviewers: (n.reviewRequests?.nodes ?? []).flatMap(
379 (r: { requestedReviewer?: { login?: string } | null }) =>
380 r?.requestedReviewer?.login ? [r.requestedReviewer.login] : [],
381 ),
382 ciState: normalizeCIState(
383 n.commits?.nodes?.[0]?.commit?.statusCheckRollup?.state,
384 ),
385 linkedIssues: (n.closingIssuesReferences?.nodes ?? [])
386 .filter(Boolean)
387 .map((i: { number: number }) => i.number),
388 timeline: normalizeTimeline(n.timelineItems?.nodes ?? [], author, config),
389 }
390 })
391
392 const issues: Array<IssueItem> = issueNodes.map((n) => ({
393 type: 'issue',
394 number: n.number,
395 title: n.title,
396 url: n.url,
397 author: actorLogin(n.author),
398 authorIsBot: actorIsBot(n.author, config),
399 authorAssociation: n.authorAssociation ?? 'NONE',
400 createdAt: n.createdAt,
401 updatedAt: n.updatedAt,
402 body: n.body ?? '',
403 labels: (n.labels?.nodes ?? [])
404 .filter(Boolean)
405 .map((l: { name: string }) => l.name),
406 assignees: (n.assignees?.nodes ?? [])
407 .filter(Boolean)
408 .map((a: { login: string }) => a.login),
409 timeline: normalizeTimeline(
410 n.timelineItems?.nodes ?? [],
411 actorLogin(n.author),
412 config,
413 ),
414 }))
415
416 const discussions: Array<DiscussionItem> = discussionNodes.map((n) => ({
417 type: 'discussion',
418 number: n.number,
419 title: n.title,
420 url: n.url,
421 author: actorLogin(n.author),
422 createdAt: n.createdAt,
423 updatedAt: n.updatedAt,
424 isAnswered: Boolean(n.isAnswered),
425 category: n.category?.name ?? '',
426 upvotes: n.upvoteCount ?? 0,
427 commentCount: n.comments?.totalCount ?? 0,
428 comments: (n.comments?.nodes ?? [])
429 .filter(Boolean)
430 .map((c: { author: GqlActor | null; createdAt: string }) => ({
431 actor: actorLogin(c.author),
432 isBot: actorIsBot(c.author, config),
433 at: c.createdAt,
434 })),
435 }))
436
437 const recentlyClosed: Array<ClosedItem> = closedNodes
438 .filter((n) => n.closedAt)
439 .map((n) => ({
440 type:
441 n.__typename === 'PullRequest' ? ('pr' as const) : ('issue' as const),
442 number: n.number,
443 title: n.title,
444 url: n.url,
445 author: actorLogin(n.author),
446 authorIsBot: actorIsBot(n.author, config),
447 createdAt: n.createdAt,
448 closedAt: n.closedAt,
449 mergedAt: n.mergedAt ?? null,
450 files: (n.files?.nodes ?? [])
451 .filter(Boolean)
452 .map((f: { path: string }) => f.path),
453 timeline: normalizeTimeline(
454 n.timelineItems?.nodes ?? [],
455 actorLogin(n.author),
456 config,
457 ),
458 }))
459
460 return {
461 owner,
462 repo,
463 codeowners: ownership.repository.object.text,
464 takenAt: now.toISOString(),
465 prs,
466 issues,
467 discussions,
468 recentlyClosed,
469 }
470}