Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kentcdodds/github

GitHub REST, GraphQL, and pull request helpers for Kody agents.

FollowFork

Files

merge-queue.ts

122 lines · 4.2 KB · TypeScript
import type { GitHubAccount } from '../types.ts'

/** Minimal GraphQL caller so the queue path is testable without kody:runtime. */
export type MergeQueueGraphql = (options: {
	account: GitHubAccount
	query: string
	variables: Record<string, unknown>
	throwOnError: true
}) => Promise<{ data: unknown }>

export type MergeQueueOutcome =
	| { outcome: 'no_queue' }
	| {
			outcome: 'queued'
			alreadyQueued: boolean
			state: string | null
			position: number | null
	  }

const lookupQuery = `query MergeQueueLookup($owner: String!, $repo: String!, $number: Int!) {
	repository(owner: $owner, name: $repo) {
		pullRequest(number: $number) {
			id
			baseRefName
			mergeQueueEntry { state position }
		}
	}
}`

const branchQueueQuery = `query MergeQueueForBranch($owner: String!, $repo: String!, $branch: String!) {
	repository(owner: $owner, name: $repo) {
		mergeQueue(branch: $branch) { id }
	}
}`

const enqueueMutation = `mutation EnqueuePullRequest($pullRequestId: ID!, $expectedHeadOid: GitObjectID) {
	enqueuePullRequest(input: { pullRequestId: $pullRequestId, expectedHeadOid: $expectedHeadOid }) {
		mergeQueueEntry { state position }
	}
}`

type Entry = { state?: string | null; position?: number | null } | null | undefined

function readEntry(entry: Entry) {
	return {
		state: typeof entry?.state === 'string' ? entry.state : null,
		position: typeof entry?.position === 'number' ? entry.position : null,
	}
}

/**
 * Add a PR to its base branch merge queue. Returns `no_queue` when the base
 * branch has none, and reports an existing entry without enqueueing twice.
 */
export async function enqueueIfMergeQueue(options: {
	graphql: MergeQueueGraphql
	account: GitHubAccount
	owner: string
	repo: string
	prNumber: number
	headSha?: string | null
}): Promise<MergeQueueOutcome> {
	const { graphql, account, owner, repo, prNumber } = options
	const lookup = (await graphql({
		account,
		query: lookupQuery,
		variables: { owner, repo, number: prNumber },
		throwOnError: true,
	})) as {
		data: {
			repository?: {
				pullRequest?: { id: string; baseRefName: string; mergeQueueEntry?: Entry } | null
			} | null
		} | null
	}
	const pr = lookup.data?.repository?.pullRequest
	if (!pr) return { outcome: 'no_queue' }
	if (pr.mergeQueueEntry) {
		return { outcome: 'queued', alreadyQueued: true, ...readEntry(pr.mergeQueueEntry) }
	}
	const branch = (await graphql({
		account,
		query: branchQueueQuery,
		variables: { owner, repo, branch: pr.baseRefName },
		throwOnError: true,
	})) as { data: { repository?: { mergeQueue?: { id: string } | null } | null } | null }
	if (!branch.data?.repository?.mergeQueue) return { outcome: 'no_queue' }
	const enqueued = (await graphql({
		account,
		query: enqueueMutation,
		variables: { pullRequestId: pr.id, expectedHeadOid: options.headSha ?? null },
		throwOnError: true,
	})) as { data: { enqueuePullRequest?: { mergeQueueEntry?: Entry } | null } | null }
	return {
		outcome: 'queued',
		alreadyQueued: false,
		...readEntry(enqueued.data?.enqueuePullRequest?.mergeQueueEntry),
	}
}

/** GitHub refuses a direct merge PUT on branches that require a merge queue. */
export function isMergeQueueRequiredError(error: unknown): boolean {
	if (!error || typeof error !== 'object') return false
	const response = (error as { response?: { status?: unknown; data?: unknown; text?: unknown } }).response
	if (!response || response.status !== 405) return false
	const data = response.data as { message?: unknown } | null | undefined
	const message = typeof data?.message === 'string' ? data.message : ''
	const text = typeof response.text === 'string' ? response.text : ''
	const fallback = error instanceof Error ? error.message : ''
	return /merge queue/i.test(`${message}\n${text}\n${fallback}`)
}

export function describeQueued(prNumber: number, queued: Extract<MergeQueueOutcome, { outcome: 'queued' }>) {
	const where = queued.position === null ? '' : ` at position ${queued.position}`
	const state = queued.state ? ` (state ${queued.state})` : ''
	return {
		message: queued.alreadyQueued
			? `PR #${prNumber} is already in the merge queue${where}${state}.`
			: `PR #${prNumber} was added to the merge queue${where}${state}.`,
		hint: 'The merge queue merges the PR after its checks pass. Call pr/merge again later; it returns already_merged once it lands.',
	}
}