mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
fix(github): attach PRs from configured push heads and rebased-away heads
Branch PR discovery only tried origin's same-named branch and %(upstream).
A fork reached through a separate pushurl, branch.<name>.pushRemote,
remote.pushDefault, or a push refspec publishing under another name never
matched, so the workspace never attached its PR.
- After those lookups miss, read where a plain push publishes the branch
(the review branch source GitLab already uses) and look up that head's
repository + branch. Push URLs resolve through SSH aliases and
authenticated Enterprise hosts.
- A merged PR whose head was rebased and force-pushed from another
checkout no longer lists the old commit in commits/{sha}/pulls; check
the PR's force-push history so a checkout still at that commit keeps
the merged PR.
This commit is contained in:
@@ -4,7 +4,6 @@ import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../../shared/g
|
||||
import { mergedPRHeadMembership } from '../../pull-requests/refresh/merged-pr-head-membership'
|
||||
import type { MergedReviewCommitMembership as MergedPRCommitMembership } from '../../../source-control/merged-review-membership-memo'
|
||||
import { shouldHideNonOpenReviewOnDefaultBranch } from '../../../source-control/repo-default-branch'
|
||||
import { getGitHubApiRepositoryForRemote } from '../../repositories/github-api-repository-remote-probe'
|
||||
import { resolveGitHubApiRepositoryCandidates } from '../../repositories/github-api-repository'
|
||||
import { exactRepositoryCandidates } from '../pull-request-lookup-candidates'
|
||||
import { mapPRState } from '../../api/github-read-response'
|
||||
@@ -26,8 +25,7 @@ import { lookupPRByBranchName } from './pr-branch-lookup'
|
||||
import { lookupPRByNumber } from './pr-number-lookup'
|
||||
import { derivePRRefreshData } from './branch-lookup-derived-data'
|
||||
import { assemblePRRefreshFoundOutcome } from './pr-refresh-outcome-assembly'
|
||||
import { shouldRetryTrackedUpstreamBranch } from './tracked-upstream-cache'
|
||||
import { getTrackedUpstreamBranch } from './tracked-upstream-branch'
|
||||
import { branchHeadKey, getConfiguredPushHead, getTrackedUpstreamHead } from './branch-review-heads'
|
||||
import {
|
||||
createImplicitDefaultBranchPRPolicy,
|
||||
type ImplicitDefaultBranchPRContext
|
||||
@@ -76,7 +74,7 @@ export async function resolvePRForBranchOutcome(input: {
|
||||
let usedExactNumberLookup = false
|
||||
const defaultBranchPRContext: ImplicitDefaultBranchPRContext = {
|
||||
originHeadRepo: headRepo,
|
||||
trackedUpstream: null,
|
||||
secondaryHeads: [],
|
||||
branchName,
|
||||
linkedPRNumber,
|
||||
repoPath,
|
||||
@@ -165,49 +163,37 @@ export async function resolvePRForBranchOutcome(input: {
|
||||
pendingBranchLookupError = branchLookup.pendingError
|
||||
hasPendingBranchLookupError = true
|
||||
}
|
||||
if (!data) {
|
||||
// Tracked upstream disambiguates head branch and fork owner beyond local branch names.
|
||||
const upstreamBranch = await getTrackedUpstreamBranch(
|
||||
repoPath,
|
||||
branchName,
|
||||
connectionId,
|
||||
localGitOptions
|
||||
)
|
||||
if (upstreamBranch) {
|
||||
const upstreamHeadRepo =
|
||||
(await getGitHubApiRepositoryForRemote(
|
||||
repoPath,
|
||||
upstreamBranch.remoteName,
|
||||
connectionId,
|
||||
localGitOptions
|
||||
)) ?? headRepo
|
||||
if (
|
||||
upstreamHeadRepo &&
|
||||
shouldRetryTrackedUpstreamBranch(upstreamBranch, branchName, upstreamHeadRepo, headRepo)
|
||||
) {
|
||||
defaultBranchPRContext.trackedUpstream = {
|
||||
branch: upstreamBranch,
|
||||
headRepo: upstreamHeadRepo
|
||||
}
|
||||
const upstreamLookup = await lookupPRByBranchName({
|
||||
candidates,
|
||||
headRepo: upstreamHeadRepo,
|
||||
branchName: upstreamBranch.branchName,
|
||||
ghOptions,
|
||||
executionScope,
|
||||
policy: implicitPRPolicy,
|
||||
reads
|
||||
})
|
||||
data = upstreamLookup.data
|
||||
dataRepo = upstreamLookup.dataRepo
|
||||
if (!hasPendingBranchLookupError && 'pendingError' in upstreamLookup) {
|
||||
pendingBranchLookupError = upstreamLookup.pendingError
|
||||
hasPendingBranchLookupError = true
|
||||
}
|
||||
if (data) {
|
||||
dataHeadRepo = upstreamHeadRepo
|
||||
}
|
||||
}
|
||||
// Tracked upstream, then the configured push head, disambiguate head branch and fork owner.
|
||||
const triedHeads = new Set(headRepo ? [branchHeadKey(headRepo, branchName)] : [])
|
||||
const secondaryHeads = [
|
||||
() => getTrackedUpstreamHead(repoPath, branchName, connectionId, localGitOptions, headRepo),
|
||||
() => getConfiguredPushHead(repoPath, branchName, connectionId, localGitOptions)
|
||||
]
|
||||
for (const resolveHead of secondaryHeads) {
|
||||
const head = data ? null : await resolveHead()
|
||||
const key = head ? branchHeadKey(head.headRepo, head.branch.branchName) : null
|
||||
if (!head || !key || triedHeads.has(key)) {
|
||||
continue
|
||||
}
|
||||
triedHeads.add(key)
|
||||
defaultBranchPRContext.secondaryHeads.push(head)
|
||||
const headLookup = await lookupPRByBranchName({
|
||||
candidates,
|
||||
headRepo: head.headRepo,
|
||||
branchName: head.branch.branchName,
|
||||
ghOptions,
|
||||
executionScope,
|
||||
policy: implicitPRPolicy,
|
||||
reads
|
||||
})
|
||||
data = headLookup.data
|
||||
dataRepo = headLookup.dataRepo
|
||||
if (!hasPendingBranchLookupError && 'pendingError' in headLookup) {
|
||||
pendingBranchLookupError = headLookup.pendingError
|
||||
hasPendingBranchLookupError = true
|
||||
}
|
||||
if (data) {
|
||||
dataHeadRepo = head.headRepo
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { githubRepoIdentityKey } from '../../../../shared/github/repositories/repository-identity-key'
|
||||
import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../../shared/github/repositories/repository-identity'
|
||||
import { getGitHubApiRepositoryForRemoteUrl } from '../../repositories/github-api-repository-remote-probe'
|
||||
import type { HostedReviewLocalGitOptions } from './../github-exec-scope'
|
||||
import { getReviewBranchSource, getTrackedUpstreamBranch } from './tracked-upstream-branch'
|
||||
import {
|
||||
shouldRetryTrackedUpstreamBranch,
|
||||
type TrackedUpstreamBranch
|
||||
} from './tracked-upstream-cache'
|
||||
import { getGitHubApiRepositoryForRemote } from '../../repositories/github-api-repository-remote-probe'
|
||||
|
||||
export type BranchHead = { branch: TrackedUpstreamBranch; headRepo: OwnerRepo }
|
||||
|
||||
/**
|
||||
* Where a plain `git push` publishes this branch: branch.<name>.pushRemote, remote.pushDefault, a
|
||||
* separate pushurl, or a push refspec's destination. Null when config names no single GitHub head.
|
||||
*/
|
||||
export async function getConfiguredPushHead(
|
||||
repoPath: string,
|
||||
branchName: string,
|
||||
connectionId: string | null | undefined,
|
||||
localGitOptions: HostedReviewLocalGitOptions
|
||||
): Promise<BranchHead | null> {
|
||||
let source: Awaited<ReturnType<typeof getReviewBranchSource>>
|
||||
try {
|
||||
source = await getReviewBranchSource(repoPath, branchName, connectionId, localGitOptions)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
const repositories = await Promise.all(
|
||||
source.urls.map((url) =>
|
||||
getGitHubApiRepositoryForRemoteUrl(repoPath, url, connectionId, localGitOptions)
|
||||
)
|
||||
)
|
||||
const [headRepo] = repositories
|
||||
// A remote that pushes to several repositories proves no single head.
|
||||
if (
|
||||
!headRepo ||
|
||||
repositories.some(
|
||||
(repository) =>
|
||||
!repository || githubRepoIdentityKey(repository) !== githubRepoIdentityKey(headRepo)
|
||||
)
|
||||
) {
|
||||
return null
|
||||
}
|
||||
return { branch: { remoteName: source.remoteName, branchName: source.branchName }, headRepo }
|
||||
}
|
||||
|
||||
export function branchHeadKey(repo: OwnerRepo, branchName: string): string {
|
||||
return `${githubRepoIdentityKey(repo)}\0${branchName}`
|
||||
}
|
||||
|
||||
/** The branch's %(upstream), when it names a head other than origin's same-named branch. */
|
||||
export async function getTrackedUpstreamHead(
|
||||
repoPath: string,
|
||||
branchName: string,
|
||||
connectionId: string | null | undefined,
|
||||
localGitOptions: HostedReviewLocalGitOptions,
|
||||
originHeadRepo: OwnerRepo | null
|
||||
): Promise<BranchHead | null> {
|
||||
const upstreamBranch = await getTrackedUpstreamBranch(
|
||||
repoPath,
|
||||
branchName,
|
||||
connectionId,
|
||||
localGitOptions
|
||||
)
|
||||
if (!upstreamBranch) {
|
||||
return null
|
||||
}
|
||||
const upstreamHeadRepo =
|
||||
(await getGitHubApiRepositoryForRemote(
|
||||
repoPath,
|
||||
upstreamBranch.remoteName,
|
||||
connectionId,
|
||||
localGitOptions
|
||||
)) ?? originHeadRepo
|
||||
return upstreamHeadRepo &&
|
||||
shouldRetryTrackedUpstreamBranch(upstreamBranch, branchName, upstreamHeadRepo, originHeadRepo)
|
||||
? { branch: upstreamBranch, headRepo: upstreamHeadRepo }
|
||||
: null
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity'
|
||||
import type * as GhExecFileModule from '../../../git/command-runner/hosted-cli/gh-exec-file'
|
||||
import type * as GithubApiRepositoryModule from '../../repositories/github-api-repository'
|
||||
import type * as GithubApiRepositoryRemoteProbeModule from '../../repositories/github-api-repository-remote-probe'
|
||||
import type * as GitExecFileModule from '../../../git/command-runner/git-exec-file'
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type * as GitHubEnterpriseRepositoryModule from '../../repositories/github-enterprise-repository'
|
||||
|
||||
const { clientMocks, moduleMocks } = await vi.hoisted(async () => {
|
||||
const moduleMocks = await import('../client-test-mocks')
|
||||
return { clientMocks: moduleMocks.createGitHubClientMocks(), moduleMocks }
|
||||
})
|
||||
|
||||
vi.mock('../../execution/github-legacy-command', () =>
|
||||
moduleMocks.githubLegacyCommandModuleMock(clientMocks)
|
||||
)
|
||||
|
||||
vi.mock('../../repositories/github-owner-repo-selection', () =>
|
||||
moduleMocks.githubOwnerSelectionModuleMock(clientMocks)
|
||||
)
|
||||
|
||||
vi.mock('../../repositories/github-repository-identity', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof GithubRepositoryIdentityModule>()),
|
||||
...moduleMocks.githubRepositoryIdentityModuleMock(clientMocks)
|
||||
}))
|
||||
|
||||
vi.mock('../../api/gh-error-classification', () =>
|
||||
moduleMocks.githubErrorClassificationModuleMock()
|
||||
)
|
||||
|
||||
vi.mock('../../execution/github-operation-slots', () =>
|
||||
moduleMocks.githubOperationSlotsModuleMock(clientMocks)
|
||||
)
|
||||
|
||||
vi.mock('../../../git/command-runner/git-exec-file', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof GitExecFileModule>()),
|
||||
gitExecFileAsync: clientMocks.gitExecFileAsyncMock
|
||||
}))
|
||||
|
||||
vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof GhExecFileModule>()),
|
||||
...moduleMocks.githubHostedCliModuleMock(clientMocks)
|
||||
}))
|
||||
vi.mock('../../repositories/local-git-config-signature', () =>
|
||||
moduleMocks.localGitConfigSignatureModuleMock(clientMocks)
|
||||
)
|
||||
vi.mock('../../repositories/github-enterprise-repository', async (importOriginal) =>
|
||||
moduleMocks.githubEnterpriseRepositoryModuleMock(
|
||||
await importOriginal<typeof GitHubEnterpriseRepositoryModule>()
|
||||
)
|
||||
)
|
||||
vi.mock('../../api/rate-limit', () => moduleMocks.rateLimitModuleMock(clientMocks))
|
||||
vi.mock('../../repositories/github-api-repository', async (importOriginal) =>
|
||||
moduleMocks.githubApiRepositoryModuleMock(
|
||||
clientMocks,
|
||||
await importOriginal<typeof GithubApiRepositoryModule>()
|
||||
)
|
||||
)
|
||||
|
||||
vi.mock('../../repositories/github-api-repository-remote-probe', async (importOriginal) =>
|
||||
moduleMocks.githubApiRepositoryRemoteProbeModuleMock(
|
||||
clientMocks,
|
||||
await importOriginal<typeof GithubApiRepositoryRemoteProbeModule>()
|
||||
)
|
||||
)
|
||||
|
||||
import { getRestPRForBranch } from './pr-branch-lookup'
|
||||
|
||||
import { resetPRForBranchMocks } from '../client-test-harness'
|
||||
|
||||
const { ghExecFileAsyncMock } = clientMocks
|
||||
|
||||
describe('PR lookup conditional REST reads', () => {
|
||||
beforeEach(() => resetPRForBranchMocks(clientMocks))
|
||||
|
||||
it('revalidates both mixed and active discovery responses before falling back to history', async () => {
|
||||
const repo = { owner: 'acme', repo: 'widgets', host: 'github.com' }
|
||||
const old = Array.from({ length: 10 }, (_, i) => ({
|
||||
number: i + 1,
|
||||
state: 'closed',
|
||||
title: 'Old',
|
||||
head: { ref: 'feature' }
|
||||
}))
|
||||
const open = { number: 11, state: 'open', title: 'Active', head: { ref: 'feature' } }
|
||||
const http = (data: unknown, etag: string) => ({
|
||||
stdout: `HTTP/2.0 200 OK\nEtag: "${etag}"\r\n\r\n${JSON.stringify(data)}`
|
||||
})
|
||||
ghExecFileAsyncMock
|
||||
.mockResolvedValueOnce(http(old, 'recent'))
|
||||
.mockResolvedValueOnce(http([open], 'active'))
|
||||
.mockRejectedValueOnce(
|
||||
Object.assign(new Error('304'), { stdout: 'HTTP/2.0 304 Not Modified\n\n' })
|
||||
)
|
||||
.mockRejectedValueOnce(
|
||||
Object.assign(new Error('304'), { stdout: 'HTTP/2.0 304 Not Modified\n\n' })
|
||||
)
|
||||
await expect(
|
||||
getRestPRForBranch(repo, 'acme', 'feature', { cwd: '/repo' })
|
||||
).resolves.toMatchObject({ number: 11 })
|
||||
await expect(
|
||||
getRestPRForBranch(repo, 'acme', 'feature', { cwd: '/repo' })
|
||||
).resolves.toMatchObject({ number: 11 })
|
||||
expect(ghExecFileAsyncMock.mock.calls[2][0]).toContain('If-None-Match: "recent"')
|
||||
expect(ghExecFileAsyncMock.mock.calls[3][0]).toContain('If-None-Match: "active"')
|
||||
})
|
||||
})
|
||||
import { getPRForBranch } from './get-pr-for-branch'
|
||||
import { resetPRForBranchMocks } from '../client-test-harness'
|
||||
|
||||
const {
|
||||
ghExecFileAsyncMock,
|
||||
getOwnerRepoMock,
|
||||
gitExecFileAsyncMock,
|
||||
resolvePRRepositoryCandidatesMock
|
||||
} = clientMocks
|
||||
|
||||
const BRANCH = 'feature'
|
||||
|
||||
function scriptGit(config: Record<string, string>, remotes: string[]): void {
|
||||
gitExecFileAsyncMock.mockImplementation(async (args: string[]) => {
|
||||
if (args[0] === 'for-each-ref') {
|
||||
return { stdout: `refs/heads/${BRANCH}\0\n`, stderr: '' }
|
||||
}
|
||||
if (args[0] === 'config' && args[1] === '--list') {
|
||||
const records = Object.entries(config).map(([key, value]) => `${key}\n${value}\0`)
|
||||
return { stdout: records.join(''), stderr: '' }
|
||||
}
|
||||
if (args[0] === 'remote' && args[1] === '-v') {
|
||||
return { stdout: `${remotes.join('\n')}\n`, stderr: '' }
|
||||
}
|
||||
return { stdout: '', stderr: '' }
|
||||
})
|
||||
}
|
||||
|
||||
/** Serves one open PR whose head is `headOwner:headBranch` in `webHost`/stablyai/orca. */
|
||||
function scriptGitHub(headOwner: string, headBranch: string, webHost = 'github.com'): void {
|
||||
const head = encodeURIComponent(`${headOwner}:${headBranch}`)
|
||||
const url = `https://${webHost}/stablyai/orca/pull/91`
|
||||
ghExecFileAsyncMock.mockImplementation(async (args: string[]) => {
|
||||
const path = args[1] ?? ''
|
||||
if (args[0] === 'auth') {
|
||||
return {
|
||||
stdout: `${webHost}\n ✓ Logged in to ${webHost} account me (keyring)\n`,
|
||||
stderr: ''
|
||||
}
|
||||
}
|
||||
if (path.includes('/pulls?head=')) {
|
||||
const rows = path.includes(`head=${head}&`)
|
||||
? [
|
||||
{
|
||||
number: 91,
|
||||
title: 'Published from a fork',
|
||||
state: 'open',
|
||||
html_url: url,
|
||||
updated_at: '2026-11-01T00:00:00Z',
|
||||
draft: false,
|
||||
mergeable: true,
|
||||
base: { ref: 'main', sha: 'base-oid' },
|
||||
head: {
|
||||
ref: headBranch,
|
||||
sha: 'head-oid',
|
||||
repo: { name: 'orca', owner: { login: headOwner } }
|
||||
}
|
||||
}
|
||||
]
|
||||
: []
|
||||
return { stdout: JSON.stringify(rows) }
|
||||
}
|
||||
return {
|
||||
stdout: JSON.stringify({
|
||||
number: 91,
|
||||
title: 'Published from a fork',
|
||||
state: 'OPEN',
|
||||
url,
|
||||
statusCheckRollup: [],
|
||||
updatedAt: '2026-11-01T00:00:00Z',
|
||||
isDraft: false,
|
||||
mergeable: 'MERGEABLE',
|
||||
baseRefName: 'main',
|
||||
headRefName: headBranch,
|
||||
baseRefOid: 'base-oid',
|
||||
headRefOid: 'head-oid',
|
||||
isCrossRepository: headOwner !== 'stablyai',
|
||||
headRepositoryOwner: { login: headOwner },
|
||||
headRepository: { name: 'orca' }
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
describe('getPRForBranch configured push head', () => {
|
||||
beforeEach(() => {
|
||||
resetPRForBranchMocks(clientMocks)
|
||||
getOwnerRepoMock.mockResolvedValue({ owner: 'stablyai', repo: 'orca' })
|
||||
})
|
||||
|
||||
it('finds a fork PR through a remote that fetches upstream and pushes to the fork', async () => {
|
||||
scriptGit({ 'remote.origin.url': 'git@github.com:stablyai/orca.git' }, [
|
||||
'origin\tgit@github.com:stablyai/orca.git (fetch)',
|
||||
'origin\tgit@github.com:contributor/orca.git (push)'
|
||||
])
|
||||
scriptGitHub('contributor', BRANCH)
|
||||
|
||||
const pr = await getPRForBranch('/repo-root', BRANCH)
|
||||
|
||||
expect(pr).toMatchObject({
|
||||
number: 91,
|
||||
prRepo: { owner: 'stablyai', repo: 'orca' },
|
||||
headRepo: { owner: 'contributor', repo: 'orca' }
|
||||
})
|
||||
})
|
||||
|
||||
it('finds a fork PR through branch.<name>.pushRemote', async () => {
|
||||
scriptGit(
|
||||
{
|
||||
'remote.origin.url': 'git@github.com:stablyai/orca.git',
|
||||
'remote.fork.url': 'git@github.com:contributor/orca.git',
|
||||
[`branch.${BRANCH}.pushremote`]: 'fork'
|
||||
},
|
||||
[
|
||||
'origin\tgit@github.com:stablyai/orca.git (fetch)',
|
||||
'origin\tgit@github.com:stablyai/orca.git (push)',
|
||||
'fork\tgit@github.com:contributor/orca.git (fetch)',
|
||||
'fork\tgit@github.com:contributor/orca.git (push)'
|
||||
]
|
||||
)
|
||||
scriptGitHub('contributor', BRANCH)
|
||||
|
||||
const pr = await getPRForBranch('/repo-root', BRANCH)
|
||||
|
||||
expect(pr).toMatchObject({ number: 91, headRepo: { owner: 'contributor', repo: 'orca' } })
|
||||
})
|
||||
|
||||
it('finds a PR whose head is the remote branch a push refspec publishes to', async () => {
|
||||
scriptGit(
|
||||
{
|
||||
'remote.origin.url': 'git@github.com:stablyai/orca.git',
|
||||
'remote.origin.push': `refs/heads/${BRANCH}:refs/heads/published-name`
|
||||
},
|
||||
[
|
||||
'origin\tgit@github.com:stablyai/orca.git (fetch)',
|
||||
'origin\tgit@github.com:stablyai/orca.git (push)'
|
||||
]
|
||||
)
|
||||
scriptGitHub('stablyai', 'published-name')
|
||||
|
||||
const pr = await getPRForBranch('/repo-root', BRANCH)
|
||||
|
||||
expect(pr).toMatchObject({ number: 91, headRefName: 'published-name' })
|
||||
})
|
||||
|
||||
it('finds a fork PR through a separate pushurl on a GitHub Enterprise host', async () => {
|
||||
const enterprise = { owner: 'stablyai', repo: 'orca', host: 'ghe.example' }
|
||||
resolvePRRepositoryCandidatesMock.mockResolvedValue({
|
||||
candidates: [enterprise],
|
||||
headRepo: enterprise
|
||||
})
|
||||
scriptGit({ 'remote.origin.url': 'https://ghe.example/stablyai/orca.git' }, [
|
||||
'origin\thttps://ghe.example/stablyai/orca.git (fetch)',
|
||||
'origin\thttps://ghe.example/contributor/orca.git (push)'
|
||||
])
|
||||
scriptGitHub('contributor', BRANCH, 'ghe.example')
|
||||
|
||||
const pr = await getPRForBranch('/repo-root', BRANCH)
|
||||
|
||||
expect(pr).toMatchObject({
|
||||
number: 91,
|
||||
headRepo: { owner: 'contributor', repo: 'orca', host: 'ghe.example' }
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
ownerRepoFromPullRequestUrl
|
||||
} from './../github-exec-scope'
|
||||
|
||||
import type { TrackedUpstreamBranch } from './tracked-upstream-cache'
|
||||
import type { BranchHead } from './branch-review-heads'
|
||||
import {
|
||||
pullRequestHeadRepository,
|
||||
pullRequestMatchesHeadRepository,
|
||||
@@ -21,7 +21,8 @@ import { getRestPRByNumber } from './pr-number-lookup'
|
||||
|
||||
export type ImplicitDefaultBranchPRContext = {
|
||||
originHeadRepo: OwnerRepo | null
|
||||
trackedUpstream: { branch: TrackedUpstreamBranch; headRepo: OwnerRepo } | null
|
||||
/** Heads beyond origin's same-named branch: the tracked upstream, then the configured push head. */
|
||||
secondaryHeads: BranchHead[]
|
||||
branchName: string
|
||||
linkedPRNumber?: number | null
|
||||
repoPath: string
|
||||
@@ -74,9 +75,10 @@ function isForeignSameNamedHead(
|
||||
data: PullRequestLookupData,
|
||||
prRepo: OwnerRepo | null
|
||||
): boolean {
|
||||
const expectedHeads = [context.originHeadRepo, context.trackedUpstream?.headRepo].filter(
|
||||
(head) => head != null
|
||||
)
|
||||
const expectedHeads = [
|
||||
context.originHeadRepo,
|
||||
...context.secondaryHeads.map((head) => head.headRepo)
|
||||
].filter((head) => head != null)
|
||||
if (data.headRefName !== context.branchName) {
|
||||
return false
|
||||
}
|
||||
@@ -107,11 +109,11 @@ async function shouldHideImplicitDefaultBranchPR(
|
||||
}
|
||||
const headRepoKey = githubRepoIdentityKey(headRepo)
|
||||
const remoteName =
|
||||
input.trackedUpstream && githubRepoIdentityKey(input.trackedUpstream.headRepo) === headRepoKey
|
||||
? input.trackedUpstream.branch.remoteName
|
||||
: input.originHeadRepo && githubRepoIdentityKey(input.originHeadRepo) === headRepoKey
|
||||
? 'origin'
|
||||
: null
|
||||
input.secondaryHeads.find((head) => githubRepoIdentityKey(head.headRepo) === headRepoKey)
|
||||
?.branch.remoteName ??
|
||||
(input.originHeadRepo && githubRepoIdentityKey(input.originHeadRepo) === headRepoKey
|
||||
? 'origin'
|
||||
: null)
|
||||
if (!remoteName) {
|
||||
try {
|
||||
// Removed tracking can leave a cached integration PR without a matching remote.
|
||||
|
||||
@@ -91,7 +91,7 @@ describe('sidebar PR query', () => {
|
||||
)
|
||||
const policy = createImplicitDefaultBranchPRPolicy({
|
||||
originHeadRepo: null,
|
||||
trackedUpstream: null,
|
||||
secondaryHeads: [],
|
||||
branchName: fields.headRefName,
|
||||
repoPath: '/folder-workspace',
|
||||
localGitOptions: {},
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { ghExecFileAsyncMock } = vi.hoisted(() => ({ ghExecFileAsyncMock: vi.fn() }))
|
||||
|
||||
vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', () => ({
|
||||
ghExecFileAsync: ghExecFileAsyncMock
|
||||
}))
|
||||
vi.mock('../../api/rate-limit', () => ({
|
||||
repositoryRateLimitGuard: () => ({ blocked: false }),
|
||||
noteRepositoryRateLimitSpend: () => {}
|
||||
}))
|
||||
|
||||
import {
|
||||
isCommitPartOfMergedPR,
|
||||
resetMergedPRCommitMembershipCacheForTest
|
||||
} from './merged-pr-commit-membership'
|
||||
|
||||
const REBASED_AWAY = '6ada46e391c5e4025d13d0304c4c0729af13a923'
|
||||
|
||||
function membership() {
|
||||
return isCommitPartOfMergedPR({
|
||||
ownerRepo: { owner: 'stablyai', repo: 'orca' },
|
||||
prNumber: 41082,
|
||||
commitOid: REBASED_AWAY,
|
||||
ghOptions: { cwd: '/repo' }
|
||||
})
|
||||
}
|
||||
|
||||
function scriptForcePushes(beforeOids: (string | null)[]): void {
|
||||
ghExecFileAsyncMock.mockImplementation(async (args: string[]) => {
|
||||
if (args[1] === 'graphql') {
|
||||
return {
|
||||
stdout: JSON.stringify({
|
||||
data: {
|
||||
repository: {
|
||||
pullRequest: {
|
||||
timelineItems: {
|
||||
totalCount: beforeOids.length,
|
||||
nodes: beforeOids.map((oid) => ({ beforeCommit: oid ? { oid } : null }))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
// GitHub drops a force-pushed-away commit's PR association.
|
||||
return { stdout: '[]' }
|
||||
})
|
||||
}
|
||||
|
||||
describe('isCommitPartOfMergedPR', () => {
|
||||
beforeEach(() => {
|
||||
ghExecFileAsyncMock.mockReset()
|
||||
resetMergedPRCommitMembershipCacheForTest()
|
||||
})
|
||||
|
||||
it('counts a head the PR was force-pushed away from, as after a rebase pushed elsewhere', async () => {
|
||||
scriptForcePushes([null, REBASED_AWAY])
|
||||
await expect(membership()).resolves.toBe('contained')
|
||||
})
|
||||
})
|
||||
@@ -1,3 +1,4 @@
|
||||
import { z } from 'zod'
|
||||
import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file'
|
||||
import { codeHostReadExecutionScope as githubReadExecutionScope } from '../../../source-control/code-host-read-execution-scope'
|
||||
import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../../api/rate-limit'
|
||||
@@ -72,7 +73,7 @@ export async function isCommitPartOfMergedPR(args: {
|
||||
return 'contained'
|
||||
}
|
||||
if (entries.length < COMMIT_PULLS_PAGE_SIZE) {
|
||||
return 'not-contained'
|
||||
return await wasForcePushedAwayFromPR(args.ownerRepo, args.prNumber, oid, ghOptions)
|
||||
}
|
||||
}
|
||||
return 'unknown'
|
||||
@@ -82,3 +83,62 @@ export async function isCommitPartOfMergedPR(args: {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const FORCE_PUSH_EVENTS_LIMIT = 100
|
||||
|
||||
const forcePushTimelineSchema = z.object({
|
||||
data: z.object({
|
||||
repository: z
|
||||
.object({
|
||||
pullRequest: z
|
||||
.object({
|
||||
timelineItems: z.object({
|
||||
totalCount: z.number(),
|
||||
nodes: z.array(
|
||||
z.object({ beforeCommit: z.object({ oid: z.string() }).nullish() }).nullable()
|
||||
)
|
||||
})
|
||||
})
|
||||
.nullable()
|
||||
})
|
||||
.nullable()
|
||||
})
|
||||
})
|
||||
|
||||
// A rebase pushed from another checkout drops this commit's PR association; the PR's force-push
|
||||
// history still names it, so the checkout provably held this PR's head.
|
||||
async function wasForcePushedAwayFromPR(
|
||||
ownerRepo: OwnerRepo,
|
||||
prNumber: number,
|
||||
oid: string,
|
||||
ghOptions: GitHubRepoExecOptions
|
||||
): Promise<MergedPRCommitMembership> {
|
||||
if (repositoryRateLimitGuard(ownerRepo, 'graphql', ghOptions).blocked) {
|
||||
return 'unknown'
|
||||
}
|
||||
noteRepositoryRateLimitSpend(ownerRepo, 'graphql', 1, ghOptions)
|
||||
const { stdout } = await ghExecFileAsync(
|
||||
[
|
||||
'api',
|
||||
'graphql',
|
||||
'-f',
|
||||
`query=query($owner: String!, $repo: String!, $number: Int!) { repository(owner: $owner, name: $repo) { pullRequest(number: $number) { timelineItems(itemTypes: [HEAD_REF_FORCE_PUSHED_EVENT], last: ${FORCE_PUSH_EVENTS_LIMIT}) { totalCount nodes { ... on HeadRefForcePushedEvent { beforeCommit { oid } } } } } } }`,
|
||||
'-f',
|
||||
`owner=${ownerRepo.owner}`,
|
||||
'-f',
|
||||
`repo=${ownerRepo.repo}`,
|
||||
'-F',
|
||||
`number=${prNumber}`
|
||||
],
|
||||
ghOptions
|
||||
)
|
||||
const parsed = forcePushTimelineSchema.safeParse(JSON.parse(stdout))
|
||||
const timeline = parsed.success ? parsed.data.data.repository?.pullRequest?.timelineItems : null
|
||||
if (!timeline) {
|
||||
return 'unknown'
|
||||
}
|
||||
if (timeline.nodes.some((node) => node?.beforeCommit?.oid.toLowerCase().startsWith(oid))) {
|
||||
return 'contained'
|
||||
}
|
||||
return timeline.totalCount > timeline.nodes.length ? 'unknown' : 'not-contained'
|
||||
}
|
||||
|
||||
@@ -9,8 +9,10 @@ import { shouldProbeGitRemote } from '../../git/remotes/remote-name-listing'
|
||||
|
||||
import {
|
||||
getEnterpriseGitHubRepoSlug,
|
||||
getEnterpriseGitHubRepoSlugForRemote
|
||||
getEnterpriseGitHubRepoSlugForRemote,
|
||||
getEnterpriseGitHubRepoSlugForRemoteUrl
|
||||
} from './github-enterprise-repository'
|
||||
import { classifyGitHubOwnerRepoFromRemoteUrl } from './github-ssh-host-alias-resolution'
|
||||
import {
|
||||
githubApiRepositoryProbeCacheKey,
|
||||
resolveGitHubApiRepositoryProbe
|
||||
@@ -135,3 +137,31 @@ export async function getOriginGitHubApiRepository(
|
||||
): Promise<GitHubApiRepository | null> {
|
||||
return getGitHubApiRepositoryForRemote(repoPath, 'origin', connectionId, localGitOptions)
|
||||
}
|
||||
|
||||
/** A remote URL's repository, for URLs no remote name resolves to (a separate `pushurl`). */
|
||||
export async function getGitHubApiRepositoryForRemoteUrl(
|
||||
repoPath: string,
|
||||
remoteUrl: string,
|
||||
connectionId?: string | null,
|
||||
localGitOptions: LocalGitExecOptions = {}
|
||||
): Promise<GitHubApiRepository | null> {
|
||||
const github = await classifyGitHubOwnerRepoFromRemoteUrl(remoteUrl, {
|
||||
repoPath,
|
||||
connectionId,
|
||||
...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {})
|
||||
})
|
||||
if (github.kind === 'github') {
|
||||
return { ...github.ownerRepo, host: 'github.com' }
|
||||
}
|
||||
if (github.kind === 'indeterminate') {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
(await getEnterpriseGitHubRepoSlugForRemoteUrl(
|
||||
repoPath,
|
||||
remoteUrl,
|
||||
connectionId,
|
||||
localGitOptions
|
||||
)) ?? null
|
||||
)
|
||||
}
|
||||
|
||||
@@ -224,12 +224,32 @@ export async function getEnterpriseGitHubRepoSlugForRemote(
|
||||
if (requireVerifiedSshProbe && !remoteUrl) {
|
||||
requireReachableGitRoute(getConnectionExecutionHostId(connectionId))
|
||||
}
|
||||
const identity = remoteUrl ? parseGitHubRemoteIdentity(remoteUrl) : null
|
||||
return remoteUrl
|
||||
? getEnterpriseGitHubRepoSlugForRemoteUrl(
|
||||
repoPath,
|
||||
remoteUrl,
|
||||
connectionId,
|
||||
localGitOptions,
|
||||
requireVerifiedSshProbe
|
||||
)
|
||||
: null
|
||||
}
|
||||
|
||||
/** The authenticated custom GitHub host a remote URL names, such as a separate `pushurl`. */
|
||||
export async function getEnterpriseGitHubRepoSlugForRemoteUrl(
|
||||
repoPath: string,
|
||||
remoteUrl: string,
|
||||
connectionId?: string | null,
|
||||
localGitOptions: LocalGitExecOptions = {},
|
||||
requireVerifiedSshProbe = false
|
||||
): Promise<GitHubEnterpriseRepoSlug | null | undefined> {
|
||||
const context = githubRepoContext(repoPath, connectionId, localGitOptions)
|
||||
const identity = parseGitHubRemoteIdentity(remoteUrl)
|
||||
if (!identity) {
|
||||
return null
|
||||
}
|
||||
let effectiveHost = identity.host
|
||||
const aliasHost = remoteUrl ? gitHubSshConfigHostAlias(remoteUrl) : null
|
||||
const aliasHost = gitHubSshConfigHostAlias(remoteUrl)
|
||||
if (aliasHost) {
|
||||
const { hostname, resolved } = await resolveSshConfigHostname(aliasHost, context)
|
||||
if (!resolved || !hostname) {
|
||||
|
||||
Reference in New Issue
Block a user