feat(forge): list the signed-in user's change requests and read descriptions
ForgeProvider gains an optional viewer capability with listForViewer and countForViewer, which read the review-requested, authored, and involved lists of open change requests on a host, and readDescription, which reads a change request's Markdown description, labels, and image addresses a browser can load without a host session. ForgeFailure.code gains rate-limited. forge-github reads each list through one GraphQL search (one document that searches several lists draws a gateway error), counts all lists in one request, pairs uploaded images with the signed addresses of the rendered description, and reports GitHub rate limits as rate-limited. Refs #8312
This commit is contained in:
1 parent
5e7206f6c6
commit
f71ee7cb2e
35 files changed
+1637
-45
No files matched your search
@@ -0,0 +1,118 @@
|
||||
/** Pull request descriptions through GraphQL, with the image addresses a browser can load without a GitHub session. */
|
||||
|
||||
import type { ChangeRequestDescription, ChangeRequestRef, ForgeFailure } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import { z } from 'zod'
|
||||
import type { GraphqlReader } from './commits.ts'
|
||||
import { checkedRepository } from './urls.ts'
|
||||
|
||||
/** Most labels one read lists, GitHub's connection maximum. */
|
||||
const LABELS = 100
|
||||
|
||||
/** One pull request's description, its rendered form, and its labels; variables `owner`, `name`, and the integer `number`. */
|
||||
export const DESCRIPTION_QUERY = `query($owner: String!, $name: String!, $number: Int!) {
|
||||
repository(owner: $owner, name: $name) {
|
||||
pullRequest(number: $number) { body bodyHTML createdAt labels(first: ${LABELS}) { totalCount nodes { name color } } }
|
||||
}
|
||||
}`
|
||||
|
||||
const descriptionSchema = z.object({
|
||||
data: z.object({
|
||||
repository: z.object({
|
||||
pullRequest: z.object({
|
||||
body: z.string(),
|
||||
bodyHTML: z.string(),
|
||||
createdAt: z.string(),
|
||||
labels: z.object({
|
||||
totalCount: z.number().int().nonnegative(),
|
||||
nodes: z.array(z.object({ name: z.string(), color: z.string() })),
|
||||
}),
|
||||
}).nullable(),
|
||||
}).nullable(),
|
||||
}),
|
||||
})
|
||||
|
||||
/** A UUID, as GitHub names an uploaded attachment. */
|
||||
const UUID = String.raw`[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}`
|
||||
|
||||
/** An attachment address in Markdown: `https://<host>/user-attachments/assets/<uuid>`. */
|
||||
const ATTACHMENT = new RegExp(String.raw`https://[^\s"'()<>]+/user-attachments/assets/(${UUID})`, 'gi')
|
||||
|
||||
/** A rendered image source signed for loading without a session, ending in `-<uuid>.<ext>?jwt=<token>`. */
|
||||
const SIGNED = new RegExp(String.raw`<img\b[^>]*\bsrc="(https://[^"]+-(${UUID})\.[a-z0-9]+\?[^"]*\bjwt=([^"&]+)[^"]*)"`, 'gi')
|
||||
|
||||
const HEX_COLOR = /^[0-9a-f]{6}$/i
|
||||
|
||||
const claimsSchema = z.object({ exp: z.number() })
|
||||
|
||||
/**
|
||||
* Read a pull request's description. On a private repository an uploaded image's Markdown address answers only with the
|
||||
* user's GitHub session, while the rendered description names a short-lived signed address for the same upload; each
|
||||
* upload the Markdown names is mapped to its signed address. The rendered description is used for nothing else.
|
||||
* @param read - runs one GraphQL request.
|
||||
* @param ref - pull request.
|
||||
* @param signal - cancellation of the read.
|
||||
* @returns the description, or why GitHub did not provide it.
|
||||
*/
|
||||
export async function readDescription(
|
||||
read: GraphqlReader, ref: ChangeRequestRef, signal: AbortSignal,
|
||||
): Promise<ChangeRequestDescription | ForgeFailure> {
|
||||
const { host, owner, name } = checkedRepository(ref)
|
||||
const output = await read(['api', 'graphql', '--hostname', host, '-f', `query=${DESCRIPTION_QUERY}`, '-f', `owner=${owner}`,
|
||||
'-f', `name=${name}`, '-F', `number=${ref.number}`], signal)
|
||||
if (!output.ok) return output.failure
|
||||
const parsed = descriptionSchema.safeParse(output.body)
|
||||
if (!parsed.success) return { code: 'unavailable', message: 'unexpected GitHub response to the description read' }
|
||||
const pull = parsed.data.data.repository?.pullRequest
|
||||
if (pull == null) return { code: 'not-found', message: `pull request ${ref.number} was not found` }
|
||||
const { images, expiresAt } = signedImages(pull.body, pull.bodyHTML)
|
||||
return {
|
||||
body: pull.body,
|
||||
labels: pull.labels.nodes.map(label => ({ name: label.name, color: HEX_COLOR.test(label.color) ? label.color.toLowerCase() : null })),
|
||||
labelsTruncated: pull.labels.totalCount > pull.labels.nodes.length,
|
||||
images,
|
||||
imagesExpireAt: expiresAt,
|
||||
createdAt: pull.createdAt,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pair each attachment address in the Markdown with the signed address the rendered description gives its upload.
|
||||
* @param body - Markdown source.
|
||||
* @param html - GitHub's rendering of `body`.
|
||||
* @returns the pairs, and the earliest expiry the signed addresses name, or null when none names one.
|
||||
*/
|
||||
function signedImages(body: string, html: string): { readonly images: Record<string, string>; readonly expiresAt: string | null } {
|
||||
const signed = new Map<string, { readonly url: string; readonly expires: number | undefined }>()
|
||||
for (const [, source = '', uuid = '', token = ''] of html.matchAll(SIGNED)) {
|
||||
const url = source.replaceAll('&', '&')
|
||||
signed.set(uuid.toLowerCase(), { url, expires: expiryOf(token) })
|
||||
}
|
||||
const images: Record<string, string> = {}
|
||||
let earliest: number | undefined
|
||||
for (const [address = '', uuid = ''] of body.matchAll(ATTACHMENT)) {
|
||||
const match = signed.get(uuid.toLowerCase())
|
||||
if (match === undefined) continue
|
||||
images[address] = match.url
|
||||
if (match.expires !== undefined) earliest = Math.min(earliest ?? match.expires, match.expires)
|
||||
}
|
||||
return { images, expiresAt: earliest === undefined ? null : new Date(earliest * 1000).toISOString() }
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the expiry of a signed address from its JSON Web Token.
|
||||
* @param token - the `jwt` query value.
|
||||
* @returns the `exp` claim in epoch seconds, or undefined when the token names none.
|
||||
*/
|
||||
function expiryOf(token: string): number | undefined {
|
||||
const [, payload] = token.split('.')
|
||||
if (payload === undefined) return undefined
|
||||
let claims: unknown
|
||||
try {
|
||||
claims = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))
|
||||
} catch (error) {
|
||||
void error // A token GitHub did not sign as JSON names no expiry.
|
||||
return undefined
|
||||
}
|
||||
const parsed = claimsSchema.safeParse(claims)
|
||||
return parsed.success ? parsed.data.exp : undefined
|
||||
}
|
||||
@@ -255,7 +255,7 @@ const MERGERS: ReadonlySet<string> = new Set(['ADMIN', 'MAINTAIN', 'WRITE'])
|
||||
const TRIAGERS: ReadonlySet<string> = new Set(['ADMIN', 'MAINTAIN', 'WRITE', 'TRIAGE'])
|
||||
|
||||
/** Outcome of a submitted review by GitHub state; a pending review is not submitted. */
|
||||
const VERDICTS: Readonly<Record<string, ReviewVerdict>> = {
|
||||
export const VERDICTS: Readonly<Record<string, ReviewVerdict>> = {
|
||||
APPROVED: 'approved', CHANGES_REQUESTED: 'changes-requested', COMMENTED: 'commented', DISMISSED: 'dismissed',
|
||||
}
|
||||
|
||||
@@ -357,8 +357,10 @@ export async function mapSnapshotResponse(
|
||||
?? (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 if (error !== undefined) {
|
||||
const code = error.type === 'NOT_FOUND' ? 'not-found' : error.type === 'RATE_LIMITED' ? 'rate-limited' : 'unavailable'
|
||||
results.set(key, { code, 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' })
|
||||
}
|
||||
return results
|
||||
@@ -657,7 +659,12 @@ function statusContextState(state: string): CheckState {
|
||||
}
|
||||
}
|
||||
|
||||
function checksRollup(state: string | undefined): ChecksRollup {
|
||||
/**
|
||||
* Map GitHub's `StatusCheckRollup.state`.
|
||||
* @param state - the rollup state, or undefined for a head commit without checks.
|
||||
* @returns the combined check outcome; states outside the documented set read as pending.
|
||||
*/
|
||||
export function checksRollup(state: string | undefined): ChecksRollup {
|
||||
switch (state) {
|
||||
case undefined: return 'none'
|
||||
case 'SUCCESS': return 'success'
|
||||
@@ -675,7 +682,12 @@ function mergeability(value: string): Mergeability {
|
||||
}
|
||||
}
|
||||
|
||||
function reviewDecision(value: string | null): ReviewDecision {
|
||||
/**
|
||||
* Map GitHub's `PullRequest.reviewDecision`.
|
||||
* @param value - the decision, or null when the base branch requires none.
|
||||
* @returns the aggregate review outcome.
|
||||
*/
|
||||
export function reviewDecision(value: string | null): ReviewDecision {
|
||||
switch (value) {
|
||||
case 'APPROVED': return 'approved'
|
||||
case 'CHANGES_REQUESTED': return 'changes-requested'
|
||||
|
||||
@@ -29,6 +29,8 @@ export interface Config {
|
||||
maxCommits?: number
|
||||
/** Most files whose viewed marks one read lists; GitHub lists at most 3,000 files of a pull request. */
|
||||
maxViewedFiles?: number
|
||||
/** Most pull requests one viewer list read returns, at most 100, the size of one GitHub search page. */
|
||||
maxViewerItems?: number
|
||||
}
|
||||
|
||||
export const Config: z<Config> = z.object({
|
||||
@@ -39,8 +41,12 @@ export const Config: z<Config> = z.object({
|
||||
maxReviewThreads: z.number().default(1_000),
|
||||
maxCommits: z.number().default(250),
|
||||
maxViewedFiles: z.number().default(3_000),
|
||||
maxViewerItems: z.number().default(50),
|
||||
})
|
||||
|
||||
/** Most results one GitHub search page returns. */
|
||||
const SEARCH_PAGE = 100
|
||||
|
||||
const HOST = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d+)?$/i
|
||||
|
||||
export function apply(ctx: Context, config: Config): void {
|
||||
@@ -53,8 +59,9 @@ 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', 'maxReviewThreads', 'maxCommits', 'maxViewedFiles'] as const) {
|
||||
for (const key of ['maxOutputBytes', 'maxReviewThreads', 'maxCommits', 'maxViewedFiles', 'maxViewerItems'] as const) {
|
||||
if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-github: ${key} must be a positive safe integer`)
|
||||
}
|
||||
if (resolved.maxViewerItems > SEARCH_PAGE) throw new Error(`forge-github: maxViewerItems must be no greater than ${SEARCH_PAGE}`)
|
||||
ctx.forge.register(new GitHubProvider(ghRunner(resolved), resolved.hosts, resolved))
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type {
|
||||
BranchUpdateRequest, ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure,
|
||||
BranchUpdateRequest, ChangeRequestDescription, ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure,
|
||||
ForgeCommitList, ForgeFailure, ForgeViewerCapability, ForgeViewerFilter, ForgeViewerList, ForgeViewerQuery,
|
||||
ForgeProvider, ForgeReadiness, ForgeRepository, ForgeRerunRequest, ForgeReviewData, ForgeReviewerCandidate, ForgeReviewersRequest,
|
||||
ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, ForgeViewedFiles, ForgeViewedRequest, MergeRequest,
|
||||
} from '@deepseek-ai/dsh-experimental-forge'
|
||||
@@ -23,9 +24,17 @@ import { readViewed, writeViewed } from './viewed.ts'
|
||||
import { gitHubReviewerCandidates, requestGitHubReviews, updateGitHubBranch } from './overview.ts'
|
||||
import { writeGitHubReview } from './review-writes.ts'
|
||||
import { readReviewThreads } from './threads.ts'
|
||||
import { readDescription } from './description.ts'
|
||||
import { countViewerLists, readViewerList, VIEWER_FILTERS } from './viewer.ts'
|
||||
|
||||
const AUTHENTICATION = /gh auth login|authentication|bad credentials|HTTP 401/i
|
||||
|
||||
/** GitHub's wording of a primary or secondary rate limit refusal, in a GraphQL error or a REST error body. */
|
||||
const RATE_LIMIT = /\brate limit\b/i
|
||||
|
||||
/** HTTP status GitHub answers when a client sends requests too quickly. */
|
||||
const TOO_MANY_REQUESTS = '429'
|
||||
|
||||
/** Status code `gh api` appends to the message of a failed request. */
|
||||
const HTTP_STATUS = /\(HTTP (\d{3})\)/
|
||||
|
||||
@@ -48,11 +57,14 @@ export interface GitHubLimits {
|
||||
readonly maxCommits: number
|
||||
/** Most files whose viewed marks one read lists. */
|
||||
readonly maxViewedFiles: number
|
||||
/** Most pull requests one viewer list read returns, at most GitHub's search page size of 100. */
|
||||
readonly maxViewerItems: number
|
||||
}
|
||||
|
||||
/** Reads GitHub and GitHub Enterprise pull requests through a `gh` runner. */
|
||||
export class GitHubProvider implements ForgeProvider {
|
||||
readonly forge = 'github'
|
||||
readonly viewer: ForgeViewerCapability
|
||||
private readonly hosts: ReadonlySet<string>
|
||||
|
||||
async submitReview(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult> {
|
||||
@@ -86,11 +98,46 @@ 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 limits - bounds on retained check and review bytes, counted and read review threads, listed commits, and listed
|
||||
* viewed files.
|
||||
* @param limits - bounds on retained check and review bytes, counted and read review threads, listed commits, listed
|
||||
* viewed files, and listed viewer pull requests.
|
||||
*/
|
||||
constructor(private readonly gh: GhRunner, hosts: readonly string[], private readonly limits: GitHubLimits) {
|
||||
this.hosts = new Set(hosts.map(host => host.toLowerCase()))
|
||||
this.viewer = { hosts: [...this.hosts], filters: VIEWER_FILTERS, maxItems: limits.maxViewerItems }
|
||||
}
|
||||
|
||||
/**
|
||||
* Read one list of the signed-in user's open pull requests through one GraphQL search.
|
||||
* @see readViewerList
|
||||
* @throws when the limit is not a positive integer no greater than `maxViewerItems`.
|
||||
*/
|
||||
async listForViewer(query: ForgeViewerQuery, signal: AbortSignal): Promise<ForgeViewerList | ForgeFailure> {
|
||||
const failure = this.hostFailure(query.host)
|
||||
if (failure !== undefined) return failure
|
||||
if (!Number.isSafeInteger(query.limit) || query.limit <= 0 || query.limit > this.limits.maxViewerItems) {
|
||||
throw new Error(`forge-github: viewer list limit must be a positive integer no greater than ${this.limits.maxViewerItems}`)
|
||||
}
|
||||
return await readViewerList(this.graphql, query, signal)
|
||||
}
|
||||
|
||||
/**
|
||||
* Count the signed-in user's open pull requests in every list through one GraphQL request.
|
||||
* @see countViewerLists
|
||||
*/
|
||||
async countForViewer(host: string, signal: AbortSignal): Promise<ReadonlyMap<ForgeViewerFilter, number> | ForgeFailure> {
|
||||
const failure = this.hostFailure(host)
|
||||
if (failure !== undefined) return failure
|
||||
return await countViewerLists(this.graphql, host, signal)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a pull request's description and labels through GraphQL.
|
||||
* @see readDescription
|
||||
*/
|
||||
async readDescription(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestDescription | ForgeFailure> {
|
||||
const failure = this.hostFailure(ref.repository.host)
|
||||
if (failure !== undefined) return failure
|
||||
return await readDescription(this.graphql, ref, signal)
|
||||
}
|
||||
|
||||
repositoryFromRemote(url: string): ForgeRepository | undefined {
|
||||
@@ -390,6 +437,7 @@ export class GitHubProvider implements ForgeProvider {
|
||||
const { message, status } = refusal(output)
|
||||
if (AUTHENTICATION.test(output.stderr)) return { code: 'unauthenticated', message }
|
||||
if (status === NOT_ACCEPTABLE || TOO_LARGE.test(output.stderr) || TOO_LARGE.test(output.stdout)) return { code: 'too-large', message }
|
||||
if (status === TOO_MANY_REQUESTS || RATE_LIMIT.test(message)) return { code: 'rate-limited', message }
|
||||
return { code: status === '404' || /could not resolve to a pullrequest/i.test(output.stderr) ? 'not-found' : 'unavailable', message }
|
||||
}
|
||||
|
||||
@@ -534,7 +582,8 @@ function responseFailure(output: GhOutput, body: unknown): ForgeFailure {
|
||||
? firstLine(body.message) : undefined
|
||||
const message = firstLine(output.stderr) ?? detail
|
||||
?? (output.exitCode === 0 ? 'unexpected GitHub response' : `gh exited with ${output.exitCode}`)
|
||||
return { code: AUTHENTICATION.test(message) ? 'unauthenticated' : 'unavailable', message }
|
||||
const limited = typeof body === 'object' && body !== null && 'type' in body && body.type === 'RATE_LIMITED'
|
||||
return { code: AUTHENTICATION.test(message) ? 'unauthenticated' : limited || RATE_LIMIT.test(message) ? 'rate-limited' : 'unavailable', message }
|
||||
}
|
||||
|
||||
function parseJson(text: string): unknown {
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
/** Lists of the signed-in user's open pull requests through the GitHub GraphQL search. */
|
||||
|
||||
import type {
|
||||
ChangeRequestSummary, ForgeFailure, ForgeViewerFilter, ForgeViewerList, ForgeViewerQuery,
|
||||
} from '@deepseek-ai/dsh-experimental-forge'
|
||||
import { z } from 'zod'
|
||||
import type { GraphqlReader } from './commits.ts'
|
||||
import { checksRollup, reviewDecision, VERDICTS } from './graphql.ts'
|
||||
import { isSegment } from './urls.ts'
|
||||
|
||||
/** The lists GitHub search reads, each the same search the GitHub pull request page offers. */
|
||||
export const VIEWER_FILTERS: ReadonlySet<ForgeViewerFilter> = new Set(['review-requested', 'authored', 'involved'])
|
||||
|
||||
/** Most closing issues one list item names. */
|
||||
const CLOSING_ISSUES = 3
|
||||
|
||||
/**
|
||||
* Search qualifiers of each list. `involved` leaves out the other two lists, so the three never share a pull request;
|
||||
* `review-requested:@me` also matches a request to one of the user's teams.
|
||||
*/
|
||||
const QUALIFIERS: Readonly<Record<ForgeViewerFilter, string>> = {
|
||||
'review-requested': 'review-requested:@me',
|
||||
'authored': 'author:@me',
|
||||
'involved': 'involves:@me -author:@me -review-requested:@me',
|
||||
}
|
||||
|
||||
const ROW_FIELDS = `number title url isDraft updatedAt headRefOid reviewDecision
|
||||
repository { name owner { login } }
|
||||
author { __typename login avatarUrl }
|
||||
commits(last: 1) { nodes { commit { statusCheckRollup { state } } } }
|
||||
viewerLatestReview { state commit { oid } }
|
||||
viewerLatestReviewRequest { requestedReviewer { __typename ... on Team { combinedSlug } } }
|
||||
closingIssuesReferences(first: ${CLOSING_ISSUES}) { totalCount nodes { number title state url repository { name owner { login } } } }`
|
||||
|
||||
/** One page of one list with the signed-in user; variables `q` and the integer `first`. */
|
||||
export const VIEWER_LIST_QUERY = `query($q: String!, $first: Int!) {
|
||||
viewer { login }
|
||||
search(type: ISSUE, query: $q, first: $first) { issueCount nodes { __typename ... on PullRequest { ${ROW_FIELDS} } } }
|
||||
}`
|
||||
|
||||
/** The size of every list in one request; variables `review`, `authored`, and `involved`. */
|
||||
export const VIEWER_COUNT_QUERY = `query($review: String!, $authored: String!, $involved: String!) {
|
||||
review: search(type: ISSUE, query: $review, first: 0) { issueCount }
|
||||
authored: search(type: ISSUE, query: $authored, first: 0) { issueCount }
|
||||
involved: search(type: ISSUE, query: $involved, first: 0) { issueCount }
|
||||
}`
|
||||
|
||||
const ownerSchema = z.object({ name: z.string(), owner: z.object({ login: z.string() }) })
|
||||
|
||||
const rowSchema = z.object({
|
||||
__typename: z.literal('PullRequest'),
|
||||
number: z.number().int().positive(),
|
||||
title: z.string(),
|
||||
url: z.string(),
|
||||
isDraft: z.boolean(),
|
||||
updatedAt: z.string(),
|
||||
headRefOid: z.string(),
|
||||
reviewDecision: z.string().nullable(),
|
||||
repository: ownerSchema,
|
||||
author: z.object({ __typename: z.string(), login: z.string(), avatarUrl: z.string().nullable() }).nullable(),
|
||||
commits: z.object({ nodes: z.array(z.object({ commit: z.object({ statusCheckRollup: z.object({ state: z.string() }).nullable() }) })) }),
|
||||
viewerLatestReview: z.object({ state: z.string(), commit: z.object({ oid: z.string() }).nullable() }).nullable(),
|
||||
viewerLatestReviewRequest: z.object({
|
||||
requestedReviewer: z.object({ __typename: z.string(), combinedSlug: z.string().optional() }).nullable(),
|
||||
}).nullable(),
|
||||
closingIssuesReferences: z.object({
|
||||
totalCount: z.number().int().nonnegative(),
|
||||
nodes: z.array(z.object({
|
||||
number: z.number().int().positive(), title: z.string(), state: z.string(), url: z.string(), repository: ownerSchema,
|
||||
})),
|
||||
}),
|
||||
})
|
||||
|
||||
const listSchema = z.object({
|
||||
data: z.object({
|
||||
viewer: z.object({ login: z.string() }),
|
||||
search: z.object({ issueCount: z.number().int().nonnegative(), nodes: z.array(z.unknown()) }),
|
||||
}),
|
||||
})
|
||||
|
||||
const countSchema = z.object({
|
||||
data: z.object({
|
||||
review: z.object({ issueCount: z.number().int().nonnegative() }),
|
||||
authored: z.object({ issueCount: z.number().int().nonnegative() }),
|
||||
involved: z.object({ issueCount: z.number().int().nonnegative() }),
|
||||
}),
|
||||
})
|
||||
|
||||
/**
|
||||
* Build the search text of one list.
|
||||
* @param filter - the list.
|
||||
* @param repository - one repository to search in, or null for every repository the user can read.
|
||||
* @returns the search text, most recently updated first, or undefined for a repository whose owner or name cannot be
|
||||
* a search qualifier.
|
||||
*/
|
||||
export function searchText(filter: ForgeViewerFilter, repository: ForgeViewerQuery['repository']): string | undefined {
|
||||
if (repository !== null && (!isSegment(repository.owner) || !isSegment(repository.name))) return undefined
|
||||
const scope = repository === null ? '' : ` repo:${repository.owner}/${repository.name}`
|
||||
return `is:pr is:open archived:false ${QUALIFIERS[filter]}${scope} sort:updated-desc`
|
||||
}
|
||||
|
||||
/**
|
||||
* Read one list through one search request: GitHub answers a search of several lists in one document with a gateway
|
||||
* error, so every list is its own request. A search result that is not a pull request, or names a repository this
|
||||
* provider cannot address, is left out.
|
||||
* @param read - runs one GraphQL request.
|
||||
* @param query - host, list, repository, and a limit the caller already bounded.
|
||||
* @param signal - cancellation of the read.
|
||||
* @returns the list, or why GitHub did not provide it.
|
||||
*/
|
||||
export async function readViewerList(
|
||||
read: GraphqlReader, query: ForgeViewerQuery, signal: AbortSignal,
|
||||
): Promise<ForgeViewerList | ForgeFailure> {
|
||||
const text = searchText(query.filter, query.repository)
|
||||
if (text === undefined) return { code: 'not-found', message: 'the repository name cannot be searched' }
|
||||
const output = await read(['api', 'graphql', '--hostname', query.host, '-f', `query=${VIEWER_LIST_QUERY}`, '-f', `q=${text}`,
|
||||
'-F', `first=${query.limit}`], signal)
|
||||
if (!output.ok) return output.failure
|
||||
const parsed = listSchema.safeParse(output.body)
|
||||
if (!parsed.success) return { code: 'unavailable', message: 'unexpected GitHub response to the pull request search' }
|
||||
const items: ChangeRequestSummary[] = []
|
||||
for (const node of parsed.data.data.search.nodes) {
|
||||
const row = rowSchema.safeParse(node)
|
||||
if (!row.success) continue
|
||||
const item = summaryOf(query.host, row.data)
|
||||
if (item !== undefined) items.push(item)
|
||||
}
|
||||
return { viewer: parsed.data.data.viewer.login, items, total: parsed.data.data.search.issueCount }
|
||||
}
|
||||
|
||||
/**
|
||||
* Count every list on one host in one request.
|
||||
* @param read - runs one GraphQL request.
|
||||
* @param host - host to count on.
|
||||
* @param signal - cancellation of the read.
|
||||
* @returns the size of each list, or why GitHub did not provide them.
|
||||
*/
|
||||
export async function countViewerLists(
|
||||
read: GraphqlReader, host: string, signal: AbortSignal,
|
||||
): Promise<ReadonlyMap<ForgeViewerFilter, number> | ForgeFailure> {
|
||||
const text = (filter: ForgeViewerFilter): string => `is:pr is:open archived:false ${QUALIFIERS[filter]}`
|
||||
const output = await read(['api', 'graphql', '--hostname', host, '-f', `query=${VIEWER_COUNT_QUERY}`,
|
||||
'-f', `review=${text('review-requested')}`, '-f', `authored=${text('authored')}`, '-f', `involved=${text('involved')}`], signal)
|
||||
if (!output.ok) return output.failure
|
||||
const parsed = countSchema.safeParse(output.body)
|
||||
if (!parsed.success) return { code: 'unavailable', message: 'unexpected GitHub response to the pull request count' }
|
||||
const { review, authored, involved } = parsed.data.data
|
||||
return new Map<ForgeViewerFilter, number>([
|
||||
['review-requested', review.issueCount], ['authored', authored.issueCount], ['involved', involved.issueCount],
|
||||
])
|
||||
}
|
||||
|
||||
/**
|
||||
* Map one search result.
|
||||
* @param host - host the search ran on.
|
||||
* @param row - the pull request fields.
|
||||
* @returns the summary, or undefined for a repository this provider cannot address.
|
||||
*/
|
||||
function summaryOf(host: string, row: z.infer<typeof rowSchema>): ChangeRequestSummary | undefined {
|
||||
const { owner: { login: owner }, name } = row.repository
|
||||
if (!isSegment(owner) || !isSegment(name)) return undefined
|
||||
const review = row.viewerLatestReview
|
||||
const verdict = review === null ? undefined : VERDICTS[review.state]
|
||||
const reviewer = row.viewerLatestReviewRequest?.requestedReviewer
|
||||
return {
|
||||
ref: { repository: { forge: 'github', host, owner, name }, number: row.number },
|
||||
url: row.url,
|
||||
title: row.title,
|
||||
draft: row.isDraft,
|
||||
author: row.author === null ? null : { login: row.author.login, avatarUrl: row.author.avatarUrl, bot: row.author.__typename === 'Bot' },
|
||||
headSha: row.headRefOid,
|
||||
checksRollup: checksRollup(row.commits.nodes[0]?.commit.statusCheckRollup?.state),
|
||||
reviewDecision: reviewDecision(row.reviewDecision),
|
||||
viewerReview: review === null || verdict === undefined ? null : { verdict, reviewedSha: review.commit?.oid ?? null },
|
||||
viewerRequest: reviewer == null ? null : { team: reviewer.__typename === 'Team' ? reviewer.combinedSlug ?? null : null },
|
||||
closingIssues: row.closingIssuesReferences.nodes.flatMap((issue) => {
|
||||
const { owner: { login: issueOwner }, name: issueName } = issue.repository
|
||||
if (!isSegment(issueOwner) || !isSegment(issueName)) return []
|
||||
return [{
|
||||
repository: { forge: 'github', host, owner: issueOwner, name: issueName },
|
||||
number: issue.number,
|
||||
title: issue.title,
|
||||
state: issue.state === 'OPEN' ? 'open' as const : 'closed' as const,
|
||||
url: issue.url,
|
||||
}]
|
||||
}),
|
||||
closingIssuesTruncated: row.closingIssuesReferences.totalCount > row.closingIssuesReferences.nodes.length,
|
||||
updatedAt: row.updatedAt,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user