Skip to content
← Public packages

@kody/github

Call GitHub REST, GraphQL, and pull requests with a GitHub OAuth App or a personal access token.

FollowFork

Files

check-rollup.ts

185 lines · 5.3 KB · TypeScript
import type { GitHubGraphqlError } from '../types.ts'

export const PR_CHECKS_QUERY = `query PrChecks($owner: String!, $repo: String!, $number: Int!, $after: String) {
	repository(owner: $owner, name: $repo) {
		pullRequest(number: $number) {
			headRefOid
			commits(last: 1) {
				nodes {
					commit {
						oid
						statusCheckRollup {
							state
							contexts(first: 100, after: $after) {
								totalCount
								pageInfo { hasNextPage endCursor }
								nodes {
									__typename
									... on CheckRun { name status conclusion detailsUrl startedAt completedAt }
									... on StatusContext { context state targetUrl createdAt }
								}
							}
						}
					}
				}
			}
		}
	}
}`

export type PrCheckState = 'pending' | 'passing' | 'failing'

export type PrCheck = {
	kind: 'check_run' | 'status'
	name: string
	status: string
	conclusion: string | null
	detailsUrl: string | null
	startedAt: string | null
	completedAt: string | null
}

export type PrChecksPage = {
	headSha: string
	state: PrCheckState
	totalCount: number
	checks: Array<PrCheck>
	unreadableCount: number
	endCursor: string | null
}

type RollupContextNode = Record<string, unknown> | null

type PrChecksData = {
	repository?: {
		pullRequest?: {
			headRefOid?: string
			commits?: {
				nodes?: Array<{
					commit?: {
						oid?: string
						statusCheckRollup?: {
							state?: string
							contexts?: {
								totalCount?: number
								pageInfo?: { hasNextPage?: boolean; endCursor?: string | null }
								nodes?: Array<RollupContextNode>
							}
						} | null
					}
				} | null>
			}
		} | null
	} | null
}

const pendingStatusStates = new Set(['PENDING', 'EXPECTED'])

/**
 * Read one page of the PR checks query. `state` comes from GitHub's
 * statusCheckRollup, which counts every check run and commit status even when
 * the token cannot read the check run nodes (fine-grained personal access
 * tokens have no Checks permission, so those nodes come back null with a
 * per-node error).
 */
export function readPrChecksPage(
	data: unknown,
	errors: Array<GitHubGraphqlError> | undefined,
	label: string,
): PrChecksPage {
	const fatalErrors = (errors ?? []).filter((error) => !isContextNodeError(error))
	if (fatalErrors.length > 0) {
		throw new Error(
			`GitHub checks query for ${label} failed: ${fatalErrors.map((error) => error.message).join('; ')}`,
		)
	}
	const pullRequest = (data as PrChecksData | null)?.repository?.pullRequest
	if (!pullRequest) {
		throw new Error(`Could not read pull request ${label}`)
	}
	const commit = pullRequest.commits?.nodes?.[0]?.commit
	const headSha = commit?.oid ?? pullRequest.headRefOid
	if (!headSha) {
		throw new Error(`Could not resolve head SHA for ${label}`)
	}
	const rollup = commit?.statusCheckRollup
	if (!rollup) {
		return {
			headSha,
			state: 'passing',
			totalCount: 0,
			checks: [],
			unreadableCount: 0,
			endCursor: null,
		}
	}
	const nodes = rollup.contexts?.nodes ?? []
	const checks = nodes.flatMap((node) => {
		const check = toPrCheck(node)
		return check ? [check] : []
	})
	const pageInfo = rollup.contexts?.pageInfo
	return {
		headSha,
		state: toPrCheckState(rollup.state),
		totalCount: rollup.contexts?.totalCount ?? checks.length,
		checks,
		unreadableCount: nodes.length - checks.length,
		endCursor: pageInfo?.hasNextPage ? (pageInfo.endCursor ?? null) : null,
	}
}

export function unreadableChecksNote(unreadableCount: number): string | null {
	if (unreadableCount === 0) return null
	return (
		`${unreadableCount} check run(s) could not be read with this token, but state still counts them. ` +
		'Fine-grained personal access tokens have no Checks permission. ' +
		'Name GitHub Actions jobs with Actions: Read-only (GET /repos/{owner}/{repo}/actions/runs?head_sha={sha}, then each run\'s /jobs), ' +
		'or use a classic token with repo (also grants write) or a GitHub App with Checks: Read-only to name every check run.'
	)
}

function isContextNodeError(error: GitHubGraphqlError): boolean {
	const path = error.path ?? []
	const contextsIndex = path.lastIndexOf('contexts')
	return (
		contextsIndex >= 0 &&
		path[contextsIndex + 1] === 'nodes' &&
		typeof path[contextsIndex + 2] === 'number'
	)
}

function toPrCheckState(rollupState: string | undefined): PrCheckState {
	if (rollupState === 'SUCCESS') return 'passing'
	if (rollupState && pendingStatusStates.has(rollupState)) return 'pending'
	return 'failing'
}

function toPrCheck(node: RollupContextNode): PrCheck | null {
	if (!node) return null
	if (node.__typename === 'CheckRun') {
		return {
			kind: 'check_run',
			name: String(node.name),
			status: String(node.status).toLowerCase(),
			conclusion: typeof node.conclusion === 'string' ? node.conclusion.toLowerCase() : null,
			detailsUrl: (node.detailsUrl ?? null) as string | null,
			startedAt: (node.startedAt ?? null) as string | null,
			completedAt: (node.completedAt ?? null) as string | null,
		}
	}
	if (node.__typename === 'StatusContext') {
		const state = String(node.state)
		const pending = pendingStatusStates.has(state)
		return {
			kind: 'status',
			name: String(node.context),
			status: pending ? 'pending' : 'completed',
			conclusion: pending ? null : state.toLowerCase(),
			detailsUrl: (node.targetUrl ?? null) as string | null,
			startedAt: (node.createdAt ?? null) as string | null,
			completedAt: null,
		}
	}
	return null
}