Merge remote-tracking branch 'origin/master' into feat/forge-review-viewed-lenses
# Conflicts: # apps/web/tests/forge-panel.e2e.ts # docs/config-catalog.md # docs/config-catalog.zh.md # docs/subsystems/forge.i18n.yaml # docs/subsystems/forge.md # docs/subsystems/forge.zh.md # packages/experimental/client-ui-forge/README.i18n.yaml # packages/experimental/client-ui-forge/README.md # packages/experimental/client-ui-forge/README.zh.md # packages/experimental/client-ui-forge/src/client/ChangesTab.tsx # packages/experimental/client-ui-forge/src/index.ts # packages/experimental/client-ui-forge/tests/controller.host.spec.ts # packages/experimental/forge-github/README.i18n.yaml # packages/experimental/forge-github/README.md # packages/experimental/forge-github/README.zh.md # packages/experimental/forge-github/src/index.ts # packages/experimental/forge-github/src/provider.ts # packages/experimental/forge-github/tests/plugin.spec.ts # packages/experimental/forge-github/tests/provider.spec.ts # packages/experimental/forge-github/tests/review.spec.ts # packages/experimental/forge/README.i18n.yaml # packages/extensions/tool-cordis/src/api-catalog.ts
This commit is contained in:
commit
fb637c2bfd
288 files changed
+9511
-1345
No files matched your search
@@ -0,0 +1,43 @@
|
||||
/** Reads GitHub's patch between two commits through the REST compare endpoint. */
|
||||
|
||||
import type { ForgeFailure, ForgeRepository } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import { isCommit } from './urls.ts'
|
||||
|
||||
/** Runs one reading `gh` command and maps a refusal to a failure, as the provider's reads do. */
|
||||
export type GhTextReader = (args: readonly string[], signal: AbortSignal) => Promise<string | ForgeFailure>
|
||||
|
||||
/** `gh` option that prints a response containing terminal escape sequences; `gh` 2.97 added it. */
|
||||
const ALLOW_ESCAPES = '--allow-escape-sequences'
|
||||
|
||||
/** What a `gh` older than 2.97 reports for {@link ALLOW_ESCAPES}, before it sends any request. */
|
||||
const UNKNOWN_ALLOW_ESCAPES = `unknown flag: ${ALLOW_ESCAPES}`
|
||||
|
||||
/**
|
||||
* Read the unified patch from the merge base of `base` and `head` to `head`, as
|
||||
* GitHub computes the diff of a pull request with that base and head commit.
|
||||
* Both ends are commit object names, so the answer never follows a moving
|
||||
* branch. The patch keeps terminal escape sequences that file contents hold:
|
||||
* `gh` 2.97 and newer refuses to print them without `--allow-escape-sequences`,
|
||||
* and an older `gh`, which rejects that option, prints them unchanged, so a
|
||||
* rejection of the option alone repeats the read without it.
|
||||
* GitHub returns the patch however many files it changes; `read` bounds its size.
|
||||
* @param read - runs `gh` with the provider's output limit and failure mapping.
|
||||
* @param repository - repository that holds both commits, with an owner and name already checked for inlining.
|
||||
* @param base - commit whose merge base with `head` starts the patch.
|
||||
* @param head - commit the patch ends at.
|
||||
* @param signal - cancellation of the read.
|
||||
* @returns the patch with `a/` and `b/` path prefixes, or why GitHub did not provide it.
|
||||
* @throws when `base` or `head` is not a full commit object name.
|
||||
*/
|
||||
export async function readComparison(
|
||||
read: GhTextReader, repository: ForgeRepository, base: string, head: string, signal: AbortSignal,
|
||||
): Promise<string | ForgeFailure> {
|
||||
for (const commit of [base, head]) {
|
||||
if (!isCommit(commit)) throw new Error(`forge-github: invalid commit ${JSON.stringify(commit)}`)
|
||||
}
|
||||
const { host, owner, name } = repository
|
||||
const request = ['-H', 'Accept: application/vnd.github.diff', `repos/${owner}/${name}/compare/${base}...${head}`]
|
||||
const patch = await read(['api', '--hostname', host, ALLOW_ESCAPES, ...request], signal)
|
||||
if (typeof patch === 'string' || !patch.message.startsWith(UNKNOWN_ALLOW_ESCAPES)) return patch
|
||||
return await read(['api', '--hostname', host, ...request], signal)
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import type {
|
||||
Mergeability, MergeMethod, ReviewDecision,
|
||||
} from '@deepseek-ai/dsh-experimental-forge'
|
||||
import { z } from 'zod'
|
||||
import { checkedRepository } from './urls.ts'
|
||||
import { checkedRepository, isCommit } from './urls.ts'
|
||||
|
||||
const CHECK_FIELDS = `pageInfo { hasNextPage endCursor }
|
||||
nodes {
|
||||
@@ -19,17 +19,34 @@ const CHECK_FIELDS = `pageInfo { hasNextPage endCursor }
|
||||
... on StatusContext { context state targetUrl createdAt }
|
||||
}`
|
||||
|
||||
const PULL_REQUEST_FIELDS = `number url title state isDraft updatedAt closedAt
|
||||
/** Most nodes GitHub returns in one connection page. */
|
||||
const PAGE_SIZE = 100
|
||||
|
||||
const THREAD_FIELDS = 'pageInfo { hasNextPage endCursor } nodes { isResolved }'
|
||||
|
||||
/**
|
||||
* Pull request fields of one snapshot.
|
||||
* @param threads - review threads the first page holds, at most {@link PAGE_SIZE}.
|
||||
* @returns the selection of the snapshot fragment.
|
||||
*/
|
||||
function pullRequestFields(threads: number): string {
|
||||
return `id number url title state isDraft updatedAt closedAt
|
||||
author { login }
|
||||
headRefName headRefOid baseRefName additions deletions mergeable mergeStateStatus reviewDecision
|
||||
reviewThreads(first: 100) { nodes { isResolved } }
|
||||
commits(last: 1) { nodes { commit { statusCheckRollup { id state contexts(first: 100) {
|
||||
reviewThreads(first: ${threads}) { ${THREAD_FIELDS} }
|
||||
commits(last: 1) { nodes { commit { statusCheckRollup { id state contexts(first: ${PAGE_SIZE}) {
|
||||
${CHECK_FIELDS}
|
||||
} } } } }`
|
||||
}
|
||||
|
||||
/** Continue reading the same commit's rollup even if the pull request head moves. */
|
||||
export const CHECKS_QUERY = `query($id: ID!, $cursor: String!) {
|
||||
node(id: $id) { ... on StatusCheckRollup { contexts(first: 100, after: $cursor) { ${CHECK_FIELDS} } } }
|
||||
node(id: $id) { ... on StatusCheckRollup { contexts(first: ${PAGE_SIZE}, after: $cursor) { ${CHECK_FIELDS} } } }
|
||||
}`
|
||||
|
||||
/** Continue counting a pull request's review threads; variables `id`, `cursor`, and the integer `first`. */
|
||||
export const THREADS_QUERY = `query($id: ID!, $cursor: String!, $first: Int!) {
|
||||
node(id: $id) { ... on PullRequest { reviewThreads(first: $first, after: $cursor) { ${THREAD_FIELDS} } } }
|
||||
}`
|
||||
|
||||
const REPOSITORY_FIELDS = 'squashMergeAllowed mergeCommitAllowed rebaseMergeAllowed viewerPermission viewerDefaultMergeMethod'
|
||||
@@ -42,6 +59,11 @@ export const HEAD_QUERY = `query($owner: String!, $name: String!, $branch: Strin
|
||||
}
|
||||
}`
|
||||
|
||||
/** Head and base commits of one pull request; variables `owner` and `name` are strings, `number` is an integer. */
|
||||
export const PULL_REQUEST_COMMITS_QUERY = `query($owner: String!, $name: String!, $number: Int!) {
|
||||
repository(owner: $owner, name: $name) { pullRequest(number: $number) { headRefOid baseRefOid } }
|
||||
}`
|
||||
|
||||
const checkRunSchema = z.object({
|
||||
__typename: z.literal('CheckRun'),
|
||||
id: z.string(),
|
||||
@@ -66,19 +88,40 @@ const statusContextSchema = z.object({
|
||||
targetUrl: z.string().nullable(),
|
||||
})
|
||||
|
||||
const checkPageSchema = z.object({
|
||||
pageInfo: z.object({ hasNextPage: z.boolean(), endCursor: z.string().nullable() }),
|
||||
nodes: z.array(z.unknown()),
|
||||
})
|
||||
const pageInfoSchema = z.object({ hasNextPage: z.boolean(), endCursor: z.string().nullable() })
|
||||
|
||||
/** Position of a connection page within its connection. */
|
||||
type PageInfo = z.infer<typeof pageInfoSchema>
|
||||
|
||||
const checkPageSchema = z.object({ pageInfo: pageInfoSchema, nodes: z.array(z.unknown()) })
|
||||
|
||||
const threadPageSchema = z.object({ pageInfo: pageInfoSchema, nodes: z.array(z.object({ isResolved: z.boolean() })) })
|
||||
|
||||
/** One validated connection page or a failure that prevents publishing a partial count. */
|
||||
export type PageResult<T> = { readonly ok: true; readonly page: T } | { readonly ok: false; readonly failure: ForgeFailure }
|
||||
|
||||
/** One validated page of check contexts or a failure that prevents publishing a partial count. */
|
||||
export type CheckPageResult = { readonly ok: true; readonly page: z.infer<typeof checkPageSchema> }
|
||||
| { readonly ok: false; readonly failure: ForgeFailure }
|
||||
export type CheckPageResult = PageResult<z.infer<typeof checkPageSchema>>
|
||||
|
||||
/** One validated page of review threads or a failure that prevents publishing a partial count. */
|
||||
export type ThreadPageResult = PageResult<z.infer<typeof threadPageSchema>>
|
||||
|
||||
/** Opaque GitHub node id that pins check pagination to one commit's rollup. */
|
||||
type RollupId = Branded<'GitHubStatusCheckRollupId'>
|
||||
|
||||
/** Opaque GitHub node id of a pull request. */
|
||||
type PullRequestId = Branded<'GitHubPullRequestId'>
|
||||
|
||||
/** Continuation reads that complete one snapshot response. */
|
||||
export interface SnapshotPages {
|
||||
/** Read the next page of a pull request's review threads, holding at most `first` threads. */
|
||||
readonly threads: (id: PullRequestId, cursor: string, first: number) => Promise<ThreadPageResult>
|
||||
/** Read the next check page of a rollup; omission keeps the first check page with its truncation flag. */
|
||||
readonly checks?: (id: RollupId, cursor: string) => Promise<CheckPageResult>
|
||||
}
|
||||
|
||||
const pullRequestSchema = z.object({
|
||||
id: z.string().transform(value => value as PullRequestId),
|
||||
url: z.string(),
|
||||
title: z.string(),
|
||||
state: z.enum(['OPEN', 'CLOSED', 'MERGED']),
|
||||
@@ -94,7 +137,7 @@ const pullRequestSchema = z.object({
|
||||
mergeable: z.string(),
|
||||
mergeStateStatus: z.string(),
|
||||
reviewDecision: z.string().nullable(),
|
||||
reviewThreads: z.object({ nodes: z.array(z.object({ isResolved: z.boolean() })) }),
|
||||
reviewThreads: threadPageSchema,
|
||||
commits: z.object({
|
||||
nodes: z.array(z.object({
|
||||
commit: z.object({
|
||||
@@ -143,6 +186,11 @@ const headSchema = z.object({
|
||||
}),
|
||||
})
|
||||
|
||||
const pullRequestCommitsSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: z.object({
|
||||
headRefOid: z.string().refine(isCommit),
|
||||
baseRefOid: z.string().refine(isCommit),
|
||||
}) }) }) })
|
||||
|
||||
type PullRequestNode = z.infer<typeof pullRequestSchema>
|
||||
type RepositoryNode = z.infer<typeof repositorySchema>
|
||||
|
||||
@@ -169,16 +217,19 @@ export interface SnapshotQuery {
|
||||
readonly document: string
|
||||
/** Change requests keyed by alias path `r<i>.p<j>`. */
|
||||
readonly targets: ReadonlyMap<string, ChangeRequestRef>
|
||||
/** Most review threads counted per change request. */
|
||||
readonly maxReviewThreads: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Build one query that reads every change request in `refs`, grouping them by
|
||||
* repository. Owners, names, and numbers are validated before they are inlined.
|
||||
* @param refs - change requests on one host.
|
||||
* @param maxReviewThreads - positive integer bound on the review threads counted per change request.
|
||||
* @returns the document and its alias targets.
|
||||
* @throws when an owner, name, or number cannot be inlined safely.
|
||||
*/
|
||||
export function snapshotQuery(refs: readonly ChangeRequestRef[]): SnapshotQuery {
|
||||
export function snapshotQuery(refs: readonly ChangeRequestRef[], maxReviewThreads: number): SnapshotQuery {
|
||||
const repositories = new Map<string, { repository: ForgeRepository; numbers: Map<number, ChangeRequestRef> }>()
|
||||
for (const ref of refs) {
|
||||
const { owner, name } = checkedRepository(ref)
|
||||
@@ -201,22 +252,26 @@ export function snapshotQuery(refs: readonly ChangeRequestRef[]): SnapshotQuery
|
||||
const owner = JSON.stringify(repository.owner)
|
||||
fields.push(`r${r}: repository(owner: ${owner}, name: ${JSON.stringify(repository.name)}) { ${REPOSITORY_FIELDS} ${pulls.join(' ')} }`)
|
||||
}
|
||||
return { document: `query { ${fields.join(' ')} }\nfragment ChangeRequestFields on PullRequest { ${PULL_REQUEST_FIELDS} }`, targets }
|
||||
const document = `query { ${fields.join(' ')} }
|
||||
fragment ChangeRequestFields on PullRequest { ${pullRequestFields(Math.min(PAGE_SIZE, maxReviewThreads))} }`
|
||||
return { document, targets, maxReviewThreads }
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a snapshot response, including GitHub's partial-error form, into one
|
||||
* result per alias target. Path-scoped errors apply to their repository or
|
||||
* pull request; errors without a path apply to every unresolved target. A
|
||||
* repository without readable merge settings offers no merge. Polling returns
|
||||
* repository without readable merge settings offers no merge. Review threads
|
||||
* are counted across pages up to `query.maxReviewThreads`. Polling returns
|
||||
* the first check page; an explicit detail read can complete its pagination.
|
||||
* A continuation page that fails or does not advance fails its target.
|
||||
* @param body - parsed JSON printed by `gh api graphql`.
|
||||
* @param query - the query that produced the response.
|
||||
* @param readChecks - optional detail reader for the same commit; omission returns the first page with its truncation flag.
|
||||
* @returns a snapshot with its check truncation flag, or a failure, for every target.
|
||||
* @param pages - continuation reads of review threads and, for a detail read, of checks on the same commit.
|
||||
* @returns a snapshot with its check and thread truncation flags, or a failure, for every target.
|
||||
*/
|
||||
export async function mapSnapshotResponse(
|
||||
body: unknown, query: SnapshotQuery, readChecks?: (id: RollupId, cursor: string) => Promise<CheckPageResult>,
|
||||
body: unknown, query: SnapshotQuery, pages: SnapshotPages,
|
||||
): Promise<Map<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>> {
|
||||
const results = new Map<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>()
|
||||
const parsed = responseSchema.safeParse(body)
|
||||
@@ -235,23 +290,14 @@ export async function mapSnapshotResponse(
|
||||
const node = pullRequestSchema.safeParse(raw)
|
||||
const settings = repositorySchema.safeParse(parsed.data.data?.[repositoryAlias])
|
||||
if (node.success) {
|
||||
const { id, reviewThreads } = node.data
|
||||
const rollup = node.data.commits.nodes[0]?.commit.statusCheckRollup
|
||||
if (rollup !== undefined && rollup !== null) {
|
||||
const cursors = new Set<string>()
|
||||
while (readChecks !== undefined && rollup.contexts.pageInfo.hasNextPage) {
|
||||
const cursor = rollup.contexts.pageInfo.endCursor
|
||||
if (cursor === null || cursors.has(cursor)) {
|
||||
results.set(key, { code: 'unavailable', message: 'GitHub check pagination did not advance' })
|
||||
break
|
||||
}
|
||||
cursors.add(cursor)
|
||||
const next = await readChecks(rollup.id, cursor)
|
||||
if (!next.ok) { results.set(key, next.failure); break }
|
||||
rollup.contexts.nodes.push(...next.page.nodes)
|
||||
rollup.contexts.pageInfo = next.page.pageInfo
|
||||
}
|
||||
}
|
||||
if (!results.has(key)) results.set(key, toSnapshot(ref, node.data, settings.success ? settings.data : undefined))
|
||||
const { checks } = pages
|
||||
const failure = await readPages(reviewThreads, query.maxReviewThreads, 'review thread',
|
||||
async (cursor, first) => await pages.threads(id, cursor, first))
|
||||
?? (rollup === undefined || rollup === null || checks === undefined ? undefined
|
||||
: await readPages(rollup.contexts, Number.POSITIVE_INFINITY, 'check', async cursor => await checks(rollup.id, cursor)))
|
||||
results.set(key, failure ?? toSnapshot(ref, node.data, settings.success ? settings.data : undefined))
|
||||
} else if (error !== undefined) results.set(key, { code: error.type === 'NOT_FOUND' ? 'not-found' : 'unavailable', message: error.message })
|
||||
else if (raw === null || raw === undefined) results.set(key, { code: 'not-found', message: 'pull request not found' })
|
||||
else results.set(key, { code: 'unavailable', message: 'unexpected pull request fields' })
|
||||
@@ -259,21 +305,86 @@ export async function mapSnapshotResponse(
|
||||
return results
|
||||
}
|
||||
|
||||
/**
|
||||
* Append the following pages of a connection until it ends or holds `limit` nodes.
|
||||
* @param connection - first page, extended in place.
|
||||
* @param limit - most nodes to hold.
|
||||
* @param label - what the connection lists, for failure messages.
|
||||
* @param read - reads the page after `cursor`, holding at most `first` nodes.
|
||||
* @returns a failure that prevents publishing the partial connection, or undefined once it ended or is full.
|
||||
*/
|
||||
async function readPages<T>(
|
||||
connection: { nodes: T[]; pageInfo: PageInfo },
|
||||
limit: number,
|
||||
label: string,
|
||||
read: (cursor: string, first: number) => Promise<PageResult<{ readonly nodes: readonly T[]; readonly pageInfo: PageInfo }>>,
|
||||
): Promise<ForgeFailure | undefined> {
|
||||
const cursors = new Set<string>()
|
||||
while (connection.pageInfo.hasNextPage && connection.nodes.length < limit) {
|
||||
const cursor = connection.pageInfo.endCursor
|
||||
if (cursor === null || cursors.has(cursor)) return { code: 'unavailable', message: `GitHub ${label} pagination did not advance` }
|
||||
cursors.add(cursor)
|
||||
const next = await read(cursor, Math.min(PAGE_SIZE, limit - connection.nodes.length))
|
||||
if (!next.ok) return next.failure
|
||||
connection.nodes.push(...next.page.nodes)
|
||||
connection.pageInfo = next.page.pageInfo
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a continuation response before adding its checks to the snapshot.
|
||||
* @param body - parsed GraphQL response for a rollup node.
|
||||
* @returns the complete page or a failure; partial-error pages are not accepted.
|
||||
*/
|
||||
export function mapCheckPageResponse(body: unknown): CheckPageResult {
|
||||
return mapPageResponse(body, z.object({ contexts: checkPageSchema }).transform(node => node.contexts), 'check')
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a continuation response of {@link THREADS_QUERY} before counting its review threads.
|
||||
* @param body - parsed GraphQL response for a pull request node.
|
||||
* @returns the complete page or a failure; partial-error pages are not accepted.
|
||||
*/
|
||||
export function mapThreadPageResponse(body: unknown): ThreadPageResult {
|
||||
return mapPageResponse(body, z.object({ reviewThreads: threadPageSchema }).transform(node => node.reviewThreads), 'review thread')
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate one continuation response of a `node(id:)` query.
|
||||
* @param body - parsed GraphQL response.
|
||||
* @param page - schema that maps the node to its connection page.
|
||||
* @param label - what the connection lists, for failure messages.
|
||||
* @returns the page, or a failure for an error, a missing node, or unexpected fields.
|
||||
*/
|
||||
function mapPageResponse<T>(body: unknown, page: z.ZodType<T>, label: string): PageResult<T> {
|
||||
const parsed = z.object({
|
||||
data: z.object({ node: z.object({ contexts: checkPageSchema }).nullable() }).nullable().optional(),
|
||||
data: z.object({ node: page.nullable() }).nullable().optional(),
|
||||
errors: z.array(z.object({ message: z.string() })).optional(),
|
||||
}).safeParse(body)
|
||||
if (parsed.success && !parsed.data.errors?.length && parsed.data.data?.node != null) {
|
||||
return { ok: true, page: parsed.data.data.node.contexts }
|
||||
}
|
||||
if (parsed.success && !parsed.data.errors?.length && parsed.data.data?.node != null) return { ok: true, page: parsed.data.data.node }
|
||||
return { ok: false, failure: { code: 'unavailable',
|
||||
message: parsed.success ? parsed.data.errors?.[0]?.message ?? 'GitHub check page is unavailable' : 'unexpected GitHub check page' } }
|
||||
message: parsed.success ? parsed.data.errors?.[0]?.message ?? `GitHub ${label} page is unavailable` : `unexpected GitHub ${label} page` } }
|
||||
}
|
||||
|
||||
/** Head and base commits of a pull request as one read of {@link PULL_REQUEST_COMMITS_QUERY} named them. */
|
||||
export interface PullRequestCommits {
|
||||
/** Commit at the head of the pull request. */
|
||||
readonly head: string
|
||||
/** Commit of the base branch GitHub recorded with that head, whose merge base with it starts the pull request's diff. */
|
||||
readonly base: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a read of {@link PULL_REQUEST_COMMITS_QUERY}.
|
||||
* @param body - parsed JSON printed by `gh api graphql`.
|
||||
* @returns both commits, or undefined when the response does not name them as full commit object names.
|
||||
*/
|
||||
export function mapPullRequestCommitsResponse(body: unknown): PullRequestCommits | undefined {
|
||||
const parsed = pullRequestCommitsSchema.safeParse(body)
|
||||
if (!parsed.success) return undefined
|
||||
const { headRefOid, baseRefOid } = parsed.data.data.repository.pullRequest
|
||||
return { head: headRefOid, base: baseRefOid }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -366,6 +477,7 @@ function toSnapshot(
|
||||
checksRollup: summary,
|
||||
checksTruncated: rollup?.contexts.pageInfo.hasNextPage ?? false,
|
||||
unresolvedThreads: node.reviewThreads.nodes.filter(thread => !thread.isResolved).length,
|
||||
threadsTruncated: node.reviewThreads.pageInfo.hasNextPage,
|
||||
updatedAt: node.updatedAt,
|
||||
closedAt: node.closedAt,
|
||||
}
|
||||
|
||||
@@ -20,6 +20,8 @@ export interface Config {
|
||||
timeoutMs?: number
|
||||
/** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read. */
|
||||
maxOutputBytes?: number
|
||||
/** Most review threads counted per pull request in one status read; a pull request with more reports a lower bound. */
|
||||
maxReviewThreads?: number
|
||||
/** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */
|
||||
maxCommits?: number
|
||||
}
|
||||
@@ -29,6 +31,7 @@ export const Config: z<Config> = z.object({
|
||||
hosts: z.array(z.string()).default(['github.com']),
|
||||
timeoutMs: z.number().default(30_000),
|
||||
maxOutputBytes: z.number().default(8_388_608),
|
||||
maxReviewThreads: z.number().default(1_000),
|
||||
maxCommits: z.number().default(250),
|
||||
})
|
||||
|
||||
@@ -44,8 +47,8 @@ export function apply(ctx: Context, config: Config): void {
|
||||
if (!Number.isSafeInteger(resolved.timeoutMs) || resolved.timeoutMs <= 0 || resolved.timeoutMs > MAX_TIMER_DELAY_MS) {
|
||||
throw new Error(`forge-github: timeoutMs must be a positive integer no greater than ${MAX_TIMER_DELAY_MS}`)
|
||||
}
|
||||
for (const key of ['maxOutputBytes', 'maxCommits'] as const) {
|
||||
for (const key of ['maxOutputBytes', 'maxReviewThreads', 'maxCommits'] as const) {
|
||||
if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-github: ${key} must be a positive safe integer`)
|
||||
}
|
||||
ctx.forge.register(new GitHubProvider(ghRunner(resolved), resolved.hosts, resolved.maxOutputBytes, resolved.maxCommits))
|
||||
ctx.forge.register(new GitHubProvider(ghRunner(resolved), resolved.hosts, resolved))
|
||||
}
|
||||
@@ -9,8 +9,13 @@ import { listCommits } from './commits.ts'
|
||||
import type { GraphqlReader } from './commits.ts'
|
||||
import { GhOutputLimitError, GhTimeoutError, GhUnavailableError } from './gh.ts'
|
||||
import type { GhOutput, GhRunner } from './gh.ts'
|
||||
import { CHECKS_QUERY, hasGraphqlFields, HEAD_QUERY, mapCheckPageResponse, mapHeadResponse, mapSnapshotResponse, snapshotQuery } from './graphql.ts'
|
||||
import { checkedRepository, parsePullRequestUrl, parseRemoteUrl } from './urls.ts'
|
||||
import { readComparison } from './compare.ts'
|
||||
import {
|
||||
CHECKS_QUERY, hasGraphqlFields, HEAD_QUERY, mapCheckPageResponse, mapHeadResponse, mapPullRequestCommitsResponse,
|
||||
mapSnapshotResponse, mapThreadPageResponse, PULL_REQUEST_COMMITS_QUERY, snapshotQuery, THREADS_QUERY,
|
||||
} from './graphql.ts'
|
||||
import type { PageResult, SnapshotPages } from './graphql.ts'
|
||||
import { checkedRepository, isCommit, parsePullRequestUrl, parseRemoteUrl } from './urls.ts'
|
||||
import { submitGitHubReview } from './review.ts'
|
||||
|
||||
const AUTHENTICATION = /gh auth login|authentication|bad credentials|HTTP 401/i
|
||||
@@ -19,16 +24,23 @@ const AUTHENTICATION = /gh auth login|authentication|bad credentials|HTTP 401/i
|
||||
const HTTP_STATUS = /\(HTTP (\d{3})\)/
|
||||
|
||||
/**
|
||||
* GitHub's error code for an answer over its size limits, such as a diff over
|
||||
* 300 files: `gh pr diff` prints it after the field, and `gh api` returns it in the JSON error body.
|
||||
* GitHub's error code for an answer over its size limits, such as a file over
|
||||
* the contents API limit: `gh api` returns it in the JSON error body.
|
||||
*/
|
||||
const TOO_LARGE = /\btoo_large\b/
|
||||
|
||||
/** HTTP status GitHub answers when it refuses to render a diff over its limits. */
|
||||
const NOT_ACCEPTABLE = '406'
|
||||
|
||||
/** A full SHA-1 or SHA-256 object name. */
|
||||
const COMMIT = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i
|
||||
/** Bounds on what one read retains or counts. */
|
||||
export interface GitHubLimits {
|
||||
/** Maximum combined JSON bytes retained by an explicit check read. */
|
||||
readonly maxOutputBytes: number
|
||||
/** Most review threads counted per pull request in one status read. */
|
||||
readonly maxReviewThreads: number
|
||||
/** Most commits one commit listing returns. */
|
||||
readonly maxCommits: number
|
||||
}
|
||||
|
||||
/** Reads GitHub and GitHub Enterprise pull requests through a `gh` runner. */
|
||||
export class GitHubProvider implements ForgeProvider {
|
||||
@@ -44,15 +56,9 @@ export class GitHubProvider implements ForgeProvider {
|
||||
/**
|
||||
* @param gh - runner that executes `gh` on the host.
|
||||
* @param hosts - host names this provider serves, such as `github.com` and Enterprise hosts.
|
||||
* @param maxOutputBytes - maximum combined JSON bytes retained by an explicit check read.
|
||||
* @param maxCommits - most commits one commit listing returns.
|
||||
* @param limits - bounds on retained check bytes, counted review threads, and listed commits.
|
||||
*/
|
||||
constructor(
|
||||
private readonly gh: GhRunner,
|
||||
hosts: readonly string[],
|
||||
private readonly maxOutputBytes: number,
|
||||
private readonly maxCommits: number,
|
||||
) {
|
||||
constructor(private readonly gh: GhRunner, hosts: readonly string[], private readonly limits: GitHubLimits) {
|
||||
this.hosts = new Set(hosts.map(host => host.toLowerCase()))
|
||||
}
|
||||
|
||||
@@ -104,10 +110,7 @@ export class GitHubProvider implements ForgeProvider {
|
||||
return results.get(changeRequestKey(ref))!
|
||||
} catch (error) {
|
||||
if (signal.aborted) throw signal.reason
|
||||
if (error instanceof GhUnavailableError || error instanceof GhTimeoutError || error instanceof GhOutputLimitError) {
|
||||
return { code: error instanceof GhOutputLimitError ? 'too-large' : 'unavailable', message: error.message }
|
||||
}
|
||||
throw error
|
||||
return processFailure(error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,19 +147,36 @@ export class GitHubProvider implements ForgeProvider {
|
||||
const { host, owner, name } = checkedRepository(ref)
|
||||
const failure = this.hostFailure(host)
|
||||
if (failure !== undefined) return { code: 'failed', message: failure.message }
|
||||
if (!COMMIT.test(request.headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(request.headSha)}`)
|
||||
if (!isCommit(request.headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(request.headSha)}`)
|
||||
return await this.act([
|
||||
'api', '--hostname', host, '--method', 'PUT', `repos/${owner}/${name}/pulls/${ref.number}/merge`,
|
||||
'-f', `merge_method=${request.method}`, '-f', `sha=${request.headSha}`,
|
||||
], signal)
|
||||
}
|
||||
|
||||
/** Read the pull request's diff with `gh pr diff`, which GitHub computes against the merge base. */
|
||||
async diff(ref: ChangeRequestRef, signal: AbortSignal): Promise<string | ForgeFailure> {
|
||||
/**
|
||||
* Read the pull request's diff at `headSha`. One GraphQL read names the
|
||||
* current head and the base commit GitHub recorded with it; a head other
|
||||
* than `headSha` returns `stale`. Otherwise the compare endpoint reads the
|
||||
* patch from the merge base of that base commit and `headSha`, as the pull
|
||||
* request's own diff does, with both ends fixed.
|
||||
*/
|
||||
async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise<string | ForgeFailure> {
|
||||
const { host, owner, name } = checkedRepository(ref)
|
||||
const failure = this.hostFailure(host)
|
||||
if (failure !== undefined) return failure
|
||||
return await this.read(['pr', 'diff', String(ref.number), '--repo', `${host}/${owner}/${name}`, '--color', 'never'], signal)
|
||||
if (!isCommit(headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(headSha)}`)
|
||||
const output = await this.read([
|
||||
'api', 'graphql', '--hostname', host,
|
||||
'-f', `query=${PULL_REQUEST_COMMITS_QUERY}`, '-f', `owner=${owner}`, '-f', `name=${name}`, '-F', `number=${ref.number}`,
|
||||
], signal)
|
||||
if (typeof output !== 'string') return output
|
||||
const commits = mapPullRequestCommitsResponse(parseJson(output))
|
||||
if (commits === undefined) return { code: 'unavailable', message: 'unexpected GitHub response to the pull request commit read' }
|
||||
if (commits.head.toLowerCase() !== headSha.toLowerCase()) {
|
||||
return { code: 'stale', message: `the pull request head moved from ${headSha} to ${commits.head}` }
|
||||
}
|
||||
return await readComparison(async (args, operation) => await this.read(args, operation), ref.repository, commits.base, headSha, signal)
|
||||
}
|
||||
|
||||
/** Read one file at a commit through the contents API in its raw form. */
|
||||
@@ -164,7 +184,7 @@ export class GitHubProvider implements ForgeProvider {
|
||||
const { host, owner, name } = checkedRepository(ref)
|
||||
const failure = this.hostFailure(host)
|
||||
if (failure !== undefined) return failure
|
||||
if (!COMMIT.test(commit)) throw new Error(`forge-github: invalid commit ${JSON.stringify(commit)}`)
|
||||
if (!isCommit(commit)) throw new Error(`forge-github: invalid commit ${JSON.stringify(commit)}`)
|
||||
return await this.read([
|
||||
'api', '--hostname', host, '-H', 'Accept: application/vnd.github.raw+json',
|
||||
`repos/${owner}/${name}/contents/${encodedPath(path)}?ref=${commit}`,
|
||||
@@ -175,7 +195,7 @@ export class GitHubProvider implements ForgeProvider {
|
||||
async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise<ForgeCommitList | ForgeFailure> {
|
||||
const failure = this.hostFailure(ref.repository.host)
|
||||
if (failure !== undefined) return failure
|
||||
return await listCommits(this.graphql, ref, this.maxCommits, signal)
|
||||
return await listCommits(this.graphql, ref, this.limits.maxCommits, signal)
|
||||
}
|
||||
|
||||
/** Read the changes between two commits through the compare API in its diff form. */
|
||||
@@ -268,34 +288,67 @@ export class GitHubProvider implements ForgeProvider {
|
||||
signal: AbortSignal,
|
||||
completeChecks = false,
|
||||
): Promise<ReadonlyMap<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>> {
|
||||
const query = snapshotQuery(refs)
|
||||
const query = snapshotQuery(refs, this.limits.maxReviewThreads)
|
||||
const output = await this.gh(['api', 'graphql', '--hostname', host, '-f', `query=${query.document}`], signal)
|
||||
const body = parseJson(output.stdout)
|
||||
if (!completeChecks && hasGraphqlFields(body)) return await mapSnapshotResponse(body, query)
|
||||
// A complete check read retains every response it reads, so all of them share one byte budget.
|
||||
let bytes = Buffer.byteLength(output.stdout)
|
||||
const tooLarge: ForgeFailure = { code: 'too-large', message: 'GitHub check details exceed the output size limit' }
|
||||
if (bytes > this.maxOutputBytes) return new Map([...query.targets.values()].map(ref => [changeRequestKey(ref), tooLarge]))
|
||||
if (hasGraphqlFields(body)) return await mapSnapshotResponse(body, query, async (id, cursor) => {
|
||||
signal.throwIfAborted()
|
||||
let page: GhOutput
|
||||
try {
|
||||
page = await this.gh(['api', 'graphql', '--hostname', host,
|
||||
'-f', `query=${CHECKS_QUERY}`, '-f', `id=${id}`, '-f', `cursor=${cursor}`], signal)
|
||||
} catch (error) {
|
||||
if (signal.aborted) throw signal.reason
|
||||
if (error instanceof GhUnavailableError || error instanceof GhTimeoutError || error instanceof GhOutputLimitError) {
|
||||
return { ok: false, failure: { code: error instanceof GhOutputLimitError ? 'too-large' : 'unavailable', message: error.message } }
|
||||
}
|
||||
throw error
|
||||
}
|
||||
const overBudget = (page: GhOutput): boolean => {
|
||||
if (!completeChecks) return false
|
||||
bytes += Buffer.byteLength(page.stdout)
|
||||
if (bytes > this.maxOutputBytes) return { ok: false, failure: tooLarge }
|
||||
return bytes > this.limits.maxOutputBytes
|
||||
}
|
||||
const continuation = async <T>(
|
||||
variables: readonly string[], map: (value: unknown) => PageResult<T>,
|
||||
): Promise<PageResult<T>> => {
|
||||
const page = await this.continuation(host, variables, signal)
|
||||
if (!('stdout' in page)) return { ok: false, failure: page }
|
||||
if (overBudget(page)) return { ok: false, failure: tooLarge }
|
||||
const value = parseJson(page.stdout)
|
||||
return hasGraphqlFields(value) ? mapCheckPageResponse(value) : { ok: false, failure: responseFailure(page, value) }
|
||||
})
|
||||
return hasGraphqlFields(value) ? map(value) : { ok: false, failure: responseFailure(page, value) }
|
||||
}
|
||||
const threads: SnapshotPages['threads'] = async (id, cursor, first) => await continuation(
|
||||
['-f', `query=${THREADS_QUERY}`, '-f', `id=${id}`, '-f', `cursor=${cursor}`, '-F', `first=${first}`], mapThreadPageResponse)
|
||||
if (!completeChecks && hasGraphqlFields(body)) return await mapSnapshotResponse(body, query, { threads })
|
||||
if (bytes > this.limits.maxOutputBytes) return new Map([...query.targets.values()].map(ref => [changeRequestKey(ref), tooLarge]))
|
||||
if (hasGraphqlFields(body)) {
|
||||
return await mapSnapshotResponse(body, query, { threads, checks: async (id, cursor) => await continuation(
|
||||
['-f', `query=${CHECKS_QUERY}`, '-f', `id=${id}`, '-f', `cursor=${cursor}`], mapCheckPageResponse) })
|
||||
}
|
||||
const failure = responseFailure(output, body)
|
||||
return new Map([...query.targets.values()].map(ref => [changeRequestKey(ref), failure] as const))
|
||||
}
|
||||
|
||||
/**
|
||||
* Run one continuation query of a snapshot read.
|
||||
* @param host - host the snapshot was read from.
|
||||
* @param variables - `gh api graphql` field flags, the query first.
|
||||
* @param signal - cancellation of the snapshot read.
|
||||
* @returns the output, or the failure of a `gh` that cannot start, times out, or prints over its limit.
|
||||
* @throws with `signal.reason` when the read is cancelled.
|
||||
*/
|
||||
private async continuation(host: string, variables: readonly string[], signal: AbortSignal): Promise<GhOutput | ForgeFailure> {
|
||||
signal.throwIfAborted()
|
||||
try {
|
||||
return await this.gh(['api', 'graphql', '--hostname', host, ...variables], signal)
|
||||
} catch (error) {
|
||||
if (signal.aborted) throw signal.reason
|
||||
return processFailure(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Report a `gh` invocation that did not run to an exit code.
|
||||
* @param error - what the runner threw.
|
||||
* @returns `too-large` for output over its limit, `unavailable` for a `gh` that cannot start or times out.
|
||||
* @throws `error` when it is any other failure.
|
||||
*/
|
||||
function processFailure(error: unknown): ForgeFailure {
|
||||
if (error instanceof GhOutputLimitError) return { code: 'too-large', message: error.message }
|
||||
if (error instanceof GhUnavailableError || error instanceof GhTimeoutError) return { code: 'unavailable', message: error.message }
|
||||
throw error
|
||||
}
|
||||
|
||||
/** Why `gh` refused: GitHub's message, else its first diagnostic line, with the HTTP status it names. */
|
||||
@@ -340,31 +393,3 @@ function parseJson(text: string): unknown {
|
||||
function firstLine(text: string): string | undefined {
|
||||
return text.split('\n').map(line => line.trim()).find(line => line.length > 0)
|
||||
}
|
||||
|
||||
/** Runs one reading `gh` command and maps a refusal to a failure, as the provider's reads do. */
|
||||
type GhTextReader = (args: readonly string[], signal: AbortSignal) => Promise<string | ForgeFailure>
|
||||
|
||||
/**
|
||||
* Read the unified patch from the merge base of `base` and `head` to `head` through the REST compare endpoint.
|
||||
* Both ends are commit object names, so the answer never follows a moving branch. The patch keeps terminal escape
|
||||
* sequences that file contents hold; `gh` 2.97 and newer refuses to print them without `--allow-escape-sequences`.
|
||||
* @param read - runs `gh` with the provider's output limit and failure mapping.
|
||||
* @param repository - repository that holds both commits, with an owner and name already checked for inlining.
|
||||
* @param base - commit whose merge base with `head` starts the patch.
|
||||
* @param head - commit the patch ends at.
|
||||
* @param signal - cancellation of the read.
|
||||
* @returns the patch with `a/` and `b/` path prefixes, or why GitHub did not provide it.
|
||||
* @throws when `base` or `head` is not a full commit object name.
|
||||
*/
|
||||
async function readComparison(
|
||||
read: GhTextReader, repository: ForgeRepository, base: string, head: string, signal: AbortSignal,
|
||||
): Promise<string | ForgeFailure> {
|
||||
for (const commit of [base, head]) {
|
||||
if (!COMMIT.test(commit)) throw new Error(`forge-github: invalid commit ${JSON.stringify(commit)}`)
|
||||
}
|
||||
const { host, owner, name } = repository
|
||||
return await read([
|
||||
'api', '--hostname', host, '--allow-escape-sequences', '-H', 'Accept: application/vnd.github.diff',
|
||||
`repos/${owner}/${name}/compare/${base}...${head}`,
|
||||
], signal)
|
||||
}
|
||||
@@ -5,6 +5,9 @@ import type { ChangeRequestRef, ForgeRepository } from '@deepseek-ai/dsh-experim
|
||||
/** Characters GitHub permits in owner and repository names. */
|
||||
const SEGMENT = /^[A-Za-z0-9_.-]+$/
|
||||
|
||||
/** A full SHA-1 or SHA-256 object name. */
|
||||
const COMMIT = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i
|
||||
|
||||
/** Host, owner, and repository name addressed by a URL. */
|
||||
export interface GitHubLocation {
|
||||
/** Lowercase host name. */
|
||||
@@ -38,6 +41,15 @@ export function checkedRepository(ref: ChangeRequestRef): ForgeRepository {
|
||||
return ref.repository
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a value is a full commit object name that can be inlined into a request.
|
||||
* @param value - candidate commit.
|
||||
* @returns whether it is 40 or 64 hexadecimal digits.
|
||||
*/
|
||||
export function isCommit(value: string): boolean {
|
||||
return COMMIT.test(value)
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a Git remote URL. Accepts `http(s)://[user@]host[:port]/owner/name`,
|
||||
* `ssh://[user@]host[:port]/owner/name`, `git://host/owner/name`, and the
|
||||
|
||||
Reference in new issue
Block a user