fix(forge): read commit ranges like the pinned pull request diff

The compare read now takes the same arguments as the comparison helper of the
pinned-diff change: explicit commits, the diff media type, and
--allow-escape-sequences, which gh 2.97 and newer requires to print a patch
whose files hold terminal escape sequences. HTTP 406, GitHub's refusal to
render a diff over its limits, reads as too-large.
This commit is contained in:
Yichen Jiang committed 2026-11-06 18:18:51 +08:00
1 parent 325b2d27e5
commit c9997e03c7
6 files changed
+46 -17

No files matched your search

+3 -3
View File
@@ -97,8 +97,8 @@ if (args[0] === 'pr' && args[1] === 'diff') {
await new Promise(resolve => process.stdout.write(readFileSync(join(here, 'pr-' + args[2] + '.diff'), 'utf8'), resolve))
process.exit(0)
}
if (args[0] === 'api' && args[3] === '-H' && args[4] === 'Accept: application/vnd.github.diff') {
const range = args[5].slice('repos/octo/demo/compare/'.length)
if (args[0] === 'api' && args.includes('Accept: application/vnd.github.diff')) {
const range = args.at(-1).slice('repos/octo/demo/compare/'.length)
const patch = existsSync(join(here, 'compare.json')) ? JSON.parse(readFileSync(join(here, 'compare.json'), 'utf8'))[range] : undefined
if (patch === undefined) {
process.stderr.write('gh: Not Found (HTTP 404)\\n')
@@ -1744,7 +1744,7 @@ it.skipIf(MODE === 'record')('reviews a change request by layer, hides test file
await expect.poll(() => shownPaths(view), { timeout: 20_000 }).toEqual(['docs/schema.json', 'locale/zh.json', 'src/panel.spec.ts', 'package.json'])
await expect.poll(() => lens.getByRole('radio').allTextContents()).toEqual(['全部4', '接口1', '实现0', '测试3'])
const calls = (await readFile(join(root, 'calls.jsonl'), 'utf8')).split('\n').filter(line => line.length > 0).map(line => JSON.parse(line) as string[])
expect(calls.filter(args => args[0] === 'api' && args[4] === 'Accept: application/vnd.github.diff').map(args => args[5])).toEqual([
expect(calls.filter(args => args[0] === 'api' && args.includes('Accept: application/vnd.github.diff')).map(args => args.at(-1))).toEqual([
`repos/octo/demo/compare/${'1'.repeat(40)}...${'2'.repeat(40)}`, `repos/octo/demo/compare/${'1'.repeat(40)}...${HEAD7}`,
])
await view.getByRole('button', { name: `查看的提交:2222222…${HEAD7.slice(0, 7)}`, exact: true }).click()
@@ -15,8 +15,8 @@
en: d152484eb41ac6b4
zh: 2f8a621b991260a1
/deepseek-ai-dsh-experimental-forge-github/use-this-package:
en: 282129be7093ee26
zh: ff1eeeb907a46245
en: 63285a5e2f7b6085
zh: c5114f7c5d06879f
/deepseek-ai-dsh-experimental-forge-github/understand-the-implementation:
en: 90f3c10096be642a
zh: 4e1b663c52019ac2
+1 -1
View File
@@ -44,7 +44,7 @@ Unfinished check runs and completed runs with stale, missing, or unrecognized co
A pull request is `mergeReady` when it is open, not a draft, GitHub reports its merge state as `CLEAN`, `HAS_HOOKS`, or `UNSTABLE`, and the signed-in user has write, maintain, or admin permission. `mergeMethods` lists the squash, merge-commit, and rebase methods the repository allows, the user's default merge method first. Marking ready runs `gh pr ready <number> --repo <host>/<owner>/<name>`. Merging calls `PUT repos/<owner>/<name>/pulls/<number>/merge` through `gh api` with the method and the expected head SHA, so GitHub refuses once new commits arrived, which is reported as `stale`. Unlike `gh pr merge`, it never enables auto-merge, never joins a merge queue, and never deletes the head branch. A refused action reports GitHub's message, and a diagnostic that mentions authentication becomes `unauthenticated`.
`diff` runs `gh pr diff <number> --repo <host>/<owner>/<name> --color never`. `fileText` reads `repos/<owner>/<name>/contents/<path>?ref=<commit>` through `gh api` with the raw media type and accepts only a full 40- or 64-digit hexadecimal commit. `fileUrl` returns `https://<host>/<owner>/<name>/blob/<commit>/<path>`. Both paths percent-encode each segment. `commits` reads a pull request's commits through GraphQL, 100 per page with the owner, name, number, and cursor as variables, until `maxCommits`; every page must report the head of the first one, else the listing is `unavailable`. `compare` reads `repos/<owner>/<name>/compare/<base>...<head>` with the diff media type, accepting only full commits, and fails like `diff`. A refused read becomes `not-found` for HTTP 404, `unauthenticated` for a diagnostic that mentions authentication, `too-large` for GitHub's `too_large` error, which a diff over its own size limit draws, and `unavailable` otherwise, with GitHub's message. A read whose output exceeds `maxOutputBytes` becomes `too-large`, and one that outlives `timeoutMs` becomes `unavailable`.
`diff` runs `gh pr diff <number> --repo <host>/<owner>/<name> --color never`. `fileText` reads `repos/<owner>/<name>/contents/<path>?ref=<commit>` through `gh api` with the raw media type and accepts only a full 40- or 64-digit hexadecimal commit. `fileUrl` returns `https://<host>/<owner>/<name>/blob/<commit>/<path>`. Both paths percent-encode each segment. `commits` reads a pull request's commits through GraphQL, 100 per page with the owner, name, number, and cursor as variables, until `maxCommits`; every page must report the head of the first one, else the listing is `unavailable`. `compare` reads `repos/<owner>/<name>/compare/<base>...<head>` with the diff media type and `--allow-escape-sequences`, which `gh` 2.97 and newer requires to print a patch whose files hold terminal escape sequences; it accepts only full commits and fails like `diff`, with HTTP 406, GitHub's refusal to render a diff over its limits, as `too-large`. A refused read becomes `not-found` for HTTP 404, `unauthenticated` for a diagnostic that mentions authentication, `too-large` for GitHub's `too_large` error, which a diff over its own size limit draws, and `unavailable` otherwise, with GitHub's message. A read whose output exceeds `maxOutputBytes` becomes `too-large`, and one that outlives `timeoutMs` becomes `unavailable`.
Review submission checks the current pull request head, then posts a single inline comment or one completed review through the REST API with an explicit `commit_id`. Multiline comments carry their side and inclusive start and end lines. Review decisions are Comment, Approve, and Request changes. JSON request bodies travel on stdin. The provider never retries a mutation: a timeout, unexpected response, or server error after dispatch returns an unknown outcome that the caller must reconcile on GitHub. A commit arriving between the check and the write can make the explicitly addressed review outdated; GitHub does not offer an atomic head precondition on these endpoints.
@@ -44,7 +44,7 @@ kind: "package-reference"
pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为 `CLEAN`、`HAS_HOOKS` 或 `UNSTABLE`,且已登录用户具有 write、maintain 或 admin 权限时,`mergeReady` 为真。`mergeMethods` 列出仓库允许的压缩合并、合并提交与变基合并方式,用户默认的合并方式排在最前。标记为可评审运行 `gh pr ready <number> --repo <host>/<owner>/<name>`。合并经 `gh api` 调用 `PUT repos/<owner>/<name>/pulls/<number>/merge`,带上合并方式与预期的 head SHA,因此有新提交到达后 GitHub 会拒绝,报告为 `stale`。与 `gh pr merge` 不同,它从不启用自动合并、从不加入合并队列,也从不删除 head 分支。被拒绝的操作报告 GitHub 的原因,提到身份验证的诊断转为 `unauthenticated`。
`diff` 运行 `gh pr diff <number> --repo <host>/<owner>/<name> --color never`。`fileText` 经 `gh api` 以 raw 媒体类型读取 `repos/<owner>/<name>/contents/<path>?ref=<commit>`,只接受完整的 40 位或 64 位十六进制提交。`fileUrl` 返回 `https://<host>/<owner>/<name>/blob/<commit>/<path>`。两者的路径都逐段做百分号编码。`commits` 经 GraphQL 读取拉取请求的提交,每页 100 个,owner、name、number 与游标作为变量传入,直到 `maxCommits`;每一页报告的 head 必须与第一页相同,否则返回 `unavailable`。`compare` 以 diff 媒体类型读取 `repos/<owner>/<name>/compare/<base>...<head>`,只接受完整提交,失败时与 `diff` 相同。被拒绝的读取在 HTTP 404 时为 `not-found`,诊断提到身份验证时为 `unauthenticated`,GitHub 报告 `too_large` 错误时(diff 超过其自身大小上限即会如此)为 `too-large`,其余为 `unavailable`,并带有 GitHub 的原因。输出超过 `maxOutputBytes` 的读取为 `too-large`,超过 `timeoutMs` 的为 `unavailable`。
`diff` 运行 `gh pr diff <number> --repo <host>/<owner>/<name> --color never`。`fileText` 经 `gh api` 以 raw 媒体类型读取 `repos/<owner>/<name>/contents/<path>?ref=<commit>`,只接受完整的 40 位或 64 位十六进制提交。`fileUrl` 返回 `https://<host>/<owner>/<name>/blob/<commit>/<path>`。两者的路径都逐段做百分号编码。`commits` 经 GraphQL 读取拉取请求的提交,每页 100 个,owner、name、number 与游标作为变量传入,直到 `maxCommits`;每一页报告的 head 必须与第一页相同,否则返回 `unavailable`。`compare` 以 diff 媒体类型并带 `--allow-escape-sequences` 读取 `repos/<owner>/<name>/compare/<base>...<head>`(文件中含终端转义序列时,`gh` 2.97 及更新版本需要该参数才会输出补丁);只接受完整提交,失败时与 `diff` 相同,其中 HTTP 406(GitHub 拒绝渲染超出上限的 diff)返回 `too-large`。被拒绝的读取在 HTTP 404 时为 `not-found`,诊断提到身份验证时为 `unauthenticated`,GitHub 报告 `too_large` 错误时(diff 超过其自身大小上限即会如此)为 `too-large`,其余为 `unavailable`,并带有 GitHub 的原因。输出超过 `maxOutputBytes` 的读取为 `too-large`,超过 `timeoutMs` 的为 `unavailable`。
提交评审时先检查 PR 当前的 head,再通过 REST API 发布单条行内评论或一次完整评审,并显式指定 `commit_id`。多行评论携带所属侧及包含端点的起止行号。评审结论为“评论”“批准”或“请求更改”。JSON 请求正文通过标准输入传递。provider 不会重试写操作;发送后的超时、异常响应或服务端错误会返回结果不明,由调用方到 GitHub 核对。检查与写入之间到来的新提交可能让已明确定位到旧提交的评审过时;GitHub 的这些接口不提供原子的 head 前置条件。
@@ -24,6 +24,9 @@ const HTTP_STATUS = /\(HTTP (\d{3})\)/
*/
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
@@ -177,15 +180,9 @@ export class GitHubProvider implements ForgeProvider {
/** Read the changes between two commits through the compare API in its diff form. */
async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise<string | ForgeFailure> {
const { host, owner, name } = checkedRepository(ref)
const failure = this.hostFailure(host)
const failure = this.hostFailure(checkedRepository(ref).host)
if (failure !== undefined) return failure
for (const commit of [base, head]) {
if (!COMMIT.test(commit)) throw new Error(`forge-github: invalid commit ${JSON.stringify(commit)}`)
}
return await this.read([
'api', '--hostname', host, '-H', 'Accept: application/vnd.github.diff', `repos/${owner}/${name}/compare/${base}...${head}`,
], signal)
return await readComparison(async (args, operation) => await this.read(args, operation), ref.repository, base, head, signal)
}
fileUrl(ref: ChangeRequestRef, commit: string, path: string): string {
@@ -223,7 +220,7 @@ export class GitHubProvider implements ForgeProvider {
if (output.exitCode === 0) return output.stdout
const { message, status } = refusal(output)
if (AUTHENTICATION.test(output.stderr)) return { code: 'unauthenticated', message }
if (TOO_LARGE.test(output.stderr) || TOO_LARGE.test(output.stdout)) return { code: 'too-large', message }
if (status === NOT_ACCEPTABLE || TOO_LARGE.test(output.stderr) || TOO_LARGE.test(output.stdout)) return { code: 'too-large', message }
return { code: status === '404' || /could not resolve to a pullrequest/i.test(output.stderr) ? 'not-found' : 'unavailable', message }
}
@@ -343,3 +340,31 @@ 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)
}
@@ -478,8 +478,12 @@ describe('GitHub provider commits', () => {
await expect(provider(gh.run).compare(pull(7, enterprise), sha(1), sha(3), signal)).resolves.toBe('diff --git a/x b/x\n')
expect(gh.calls).toEqual([[
'api', '--hostname', 'ghe.corp.example', '-H', 'Accept: application/vnd.github.diff', `repos/team/svc/compare/${sha(1)}...${sha(3)}`,
'api', '--hostname', 'ghe.corp.example', '--allow-escape-sequences', '-H', 'Accept: application/vnd.github.diff',
`repos/team/svc/compare/${sha(1)}...${sha(3)}`,
]])
const refused = 'gh: Sorry, this diff is taking too long to generate. (HTTP 406)'
await expect(provider(fakeGh(() => output({ message: 'Sorry, this diff is taking too long to generate.' }, 1, refused)).run)
.compare(pull(7), sha(1), sha(3), signal)).resolves.toEqual({ code: 'too-large', message: 'Sorry, this diff is taking too long to generate.' })
await expect(provider(gh.run).compare(pull(7), 'main', sha(3), signal)).rejects.toThrow('forge-github: invalid commit "main"')
await expect(provider(gh.run).compare(pull(7), sha(1), 'HEAD~1', signal)).rejects.toThrow('forge-github: invalid commit "HEAD~1"')
})