fix: address review findings (#2256)

This commit is contained in:
Jinjing
2026-05-18 11:59:43 -07:00
committed by GitHub
parent 1f07de4d3a
commit e0a5aa24d4
6 changed files with 336 additions and 232 deletions
+166
View File
@@ -0,0 +1,166 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { getPullRequestPushTargetMock, getWorkItemMock } = vi.hoisted(() => ({
getPullRequestPushTargetMock: vi.fn(),
getWorkItemMock: vi.fn()
}))
vi.mock('./client', () => ({
getPullRequestPushTarget: getPullRequestPushTargetMock,
getWorkItem: getWorkItemMock
}))
import { resolveGitHubPrStartPoint } from './pr-start-point'
describe('resolveGitHubPrStartPoint', () => {
beforeEach(() => {
getPullRequestPushTargetMock.mockReset()
getWorkItemMock.mockReset()
})
it('falls back to the GitHub PR head ref when a direct branch fetch fails', async () => {
getPullRequestPushTargetMock.mockResolvedValue({
remoteName: 'pr-contributor-orca',
branchName: 'feat/onboarding-model-choice-782',
remoteUrl: 'git@github.com:contributor/orca.git'
})
const gitExec = vi.fn(async (args: string[]) => {
if (args[0] === 'fetch' && String(args[2]).startsWith('+refs/heads/')) {
throw new Error('fatal: could not find remote ref')
}
if (args[0] === 'rev-parse') {
return { stdout: 'def456\n', stderr: '' }
}
return { stdout: '', stderr: '' }
})
const result = await resolveGitHubPrStartPoint({
repoPath: '/repo-root',
prNumber: 1849,
headRefName: 'feat/onboarding-model-choice-782',
gitExec,
resolveRemote: async () => 'origin'
})
expect(gitExec).toHaveBeenCalledWith([
'fetch',
'origin',
'+refs/heads/feat/onboarding-model-choice-782:refs/remotes/origin/feat/onboarding-model-choice-782'
])
expect(gitExec).toHaveBeenCalledWith(['fetch', 'origin', 'refs/pull/1849/head'])
expect(result).toEqual({
baseBranch: 'def456',
pushTarget: {
remoteName: 'pr-contributor-orca',
branchName: 'feat/onboarding-model-choice-782',
remoteUrl: 'git@github.com:contributor/orca.git'
}
})
})
it('keeps the PR head ref fallback when push-target discovery also fails', async () => {
getPullRequestPushTargetMock.mockRejectedValue(new Error('head repo is unavailable'))
const gitExec = vi.fn(async (args: string[]) => {
if (args[0] === 'fetch' && String(args[2]).startsWith('+refs/heads/')) {
throw new Error('fatal: could not find remote ref')
}
if (args[0] === 'rev-parse') {
return { stdout: 'def456\n', stderr: '' }
}
return { stdout: '', stderr: '' }
})
const result = await resolveGitHubPrStartPoint({
repoPath: '/repo-root',
prNumber: 1849,
headRefName: 'feat/onboarding-model-choice-782',
gitExec,
resolveRemote: async () => 'origin'
})
expect(getPullRequestPushTargetMock).toHaveBeenCalledWith('/repo-root', 1849, null)
expect(result).toEqual({ baseBranch: 'def456' })
})
it('resolves an inaccessible fork PR even when push-target discovery fails', async () => {
getPullRequestPushTargetMock.mockRejectedValue(new Error('head repo is unavailable'))
const gitExec = vi.fn(async (args: string[]) => {
if (args[0] === 'rev-parse') {
return { stdout: 'abc123\n', stderr: '' }
}
return { stdout: '', stderr: '' }
})
const result = await resolveGitHubPrStartPoint({
repoPath: '/repo-root',
prNumber: 1849,
headRefName: 'feat/onboarding-model-choice-782',
isCrossRepository: true,
gitExec,
resolveRemote: async () => 'origin'
})
expect(getPullRequestPushTargetMock).toHaveBeenCalledWith('/repo-root', 1849, null)
expect(gitExec).toHaveBeenCalledWith(['fetch', 'origin', 'refs/pull/1849/head'])
expect(result).toEqual({ baseBranch: 'abc123' })
})
it('uses PR metadata when the caller did not pass a head ref', async () => {
getWorkItemMock.mockResolvedValue({
type: 'pr',
branchName: 'contributor/fix',
isCrossRepository: true
})
getPullRequestPushTargetMock.mockResolvedValue({
remoteName: 'pr-contributor-orca',
branchName: 'contributor/fix',
remoteUrl: 'git@github.com:contributor/orca.git'
})
const gitExec = vi.fn(async (args: string[]) => {
if (args[0] === 'rev-parse') {
return { stdout: 'abc123\n', stderr: '' }
}
return { stdout: '', stderr: '' }
})
const result = await resolveGitHubPrStartPoint({
repoPath: '/repo-root',
prNumber: 1738,
gitExec,
resolveRemote: async () => 'origin'
})
expect(getWorkItemMock).toHaveBeenCalledWith('/repo-root', 1738, 'pr', null)
expect(result).toEqual({
baseBranch: 'abc123',
pushTarget: {
remoteName: 'pr-contributor-orca',
branchName: 'contributor/fix',
remoteUrl: 'git@github.com:contributor/orca.git'
}
})
})
it('returns a tracking ref and push target when same-repo branch fetch succeeds', async () => {
const gitExec = vi.fn(async () => ({ stdout: '', stderr: '' }))
const result = await resolveGitHubPrStartPoint({
repoPath: '/repo-root',
prNumber: 42,
headRefName: 'feature/add-feature',
gitExec,
resolveRemote: async () => 'origin'
})
expect(gitExec).toHaveBeenCalledWith([
'fetch',
'origin',
'+refs/heads/feature/add-feature:refs/remotes/origin/feature/add-feature'
])
expect(gitExec).toHaveBeenCalledWith(['rev-parse', '--verify', 'origin/feature/add-feature'])
expect(result).toEqual({
baseBranch: 'origin/feature/add-feature',
pushTarget: { remoteName: 'origin', branchName: 'feature/add-feature' }
})
})
})
+135
View File
@@ -0,0 +1,135 @@
import type { GitPushTarget } from '../../shared/types'
import { isMissingRemoteRefGitError } from '../git/fetch-error-classification'
import { getPullRequestPushTarget, getWorkItem } from './client'
type GitExec = (args: string[]) => Promise<{ stdout: string; stderr: string }>
type ResolveGitHubPrStartPointArgs = {
repoPath: string
prNumber: number
headRefName?: string
isCrossRepository?: boolean
connectionId?: string | null
gitExec: GitExec
resolveRemote: () => Promise<string>
}
type ResolveGitHubPrStartPointResult =
| { baseBranch: string; pushTarget?: GitPushTarget }
| { error: string }
export async function resolveGitHubPrStartPoint(
args: ResolveGitHubPrStartPointArgs
): Promise<ResolveGitHubPrStartPointResult> {
let headRefName = args.headRefName?.trim() ?? ''
let isCrossRepository = args.isCrossRepository === true
let pushTarget: GitPushTarget | undefined
const resolvePushTarget = async (): Promise<void> => {
if (pushTarget) {
return
}
try {
pushTarget =
(await getPullRequestPushTarget(args.repoPath, args.prNumber, args.connectionId ?? null)) ??
undefined
} catch {
// Why: deleted/inaccessible fork metadata can prevent push-target
// discovery, but GitHub still exposes the PR head ref for checkout.
pushTarget = undefined
}
}
if (!headRefName) {
const item = await getWorkItem(args.repoPath, args.prNumber, 'pr', args.connectionId ?? null)
if (!item || item.type !== 'pr') {
return { error: `PR #${args.prNumber} not found.` }
}
headRefName = (item.branchName ?? '').trim()
if (!headRefName) {
return { error: `PR #${args.prNumber} has no head branch.` }
}
if (item.isCrossRepository === true) {
isCrossRepository = true
}
}
if (isCrossRepository) {
await resolvePushTarget()
}
let remote: string
try {
remote = await args.resolveRemote()
} catch (error) {
return { error: error instanceof Error ? error.message : 'Could not resolve git remote.' }
}
const fetchPullRequestHeadSha = async (): Promise<{ baseBranch: string } | { error: string }> => {
const pullRef = `refs/pull/${args.prNumber}/head`
try {
await args.gitExec(['fetch', remote, pullRef])
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
return {
error: `Failed to fetch ${pullRef}: ${message.split('\n')[0]}`
}
}
let sha: string
try {
const { stdout } = await args.gitExec(['rev-parse', '--verify', 'FETCH_HEAD'])
sha = stdout.trim()
} catch {
return { error: `Could not resolve fork PR #${args.prNumber} head after fetch.` }
}
if (!sha) {
return { error: `Empty SHA resolving fork PR #${args.prNumber} head.` }
}
return { baseBranch: sha }
}
// Why: fork PR heads live on a remote we don't have configured, so
// `git fetch <remote> <headRefName>` would fail. GitHub exposes every
// PR head (fork or same-repo) as refs/pull/<N>/head on the upstream repo.
if (isCrossRepository) {
const result = await fetchPullRequestHeadSha()
if ('error' in result) {
return result
}
return { ...result, ...(pushTarget ? { pushTarget } : {}) }
}
try {
await args.gitExec([
'fetch',
remote,
`+refs/heads/${headRefName}:refs/remotes/${remote}/${headRefName}`
])
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
// Why: missing fork metadata can make a fork PR look like a same-repo
// branch. Only that missing-ref case should fall back to refs/pull.
if (isMissingRemoteRefGitError(error)) {
const result = await fetchPullRequestHeadSha()
if (!('error' in result)) {
await resolvePushTarget()
return { ...result, ...(pushTarget ? { pushTarget } : {}) }
}
}
return {
error: `Failed to fetch ${remote}/${headRefName}: ${message.split('\n')[0]}`
}
}
const remoteRef = `${remote}/${headRefName}`
try {
await args.gitExec(['rev-parse', '--verify', remoteRef])
} catch {
return { error: `Remote ref ${remoteRef} does not exist after fetch.` }
}
return {
baseBranch: remoteRef,
pushTarget: { remoteName: remote, branchName: headRefName }
}
}