mirror of
https://github.com/stablyai/orca.git
synced 2026-10-21 00:03:46 +00:00
* fix(github): load PR diffs for Enterprise remotes * fix(github): encode PR content paths by segment * Fix PR review actions failing on GitHub Enterprise remotes - Threads GitHub host identity (not just owner/repo) through the client, work-item-details, issues, and RPC layers so gh commands target the correct Enterprise server instead of silently falling back to github.com - Adds a shared github-api-repository helper to resolve/host-qualify repo identity consistently across REST, GraphQL, and CLI shorthand calls - Scopes the gh rate-limit breaker and singleton rate-limit snapshot by host/runtime so a github.com block or probe can't affect GHES or WSL - Coalesces concurrent host-auth probes and paginates PR file fetching beyond 100 results - Propagates `host` through renderer PR caches, checks-panel keys, and preload IPC types so Enterprise and github.com data never collide * Route gh host qualification through runner options instead of argv sniff Move GHES/GH_HOST resolution from parsing --hostname/--repo out of gh argv to an explicit options.host passed through ghExecFileAsync, since SSH-backed repos spawn gh with no cwd and argv sniffing couldn't reliably detect the target host. The runner now injects --hostname and qualifies --repo/-R at spawn time from options.host, and rate-limit scoping/guards use the same explicit host instead of inferring it. Also adds a shared githubRepoIdentityKey helper to keep cache/store keys consistent with the new host-aware repository identity. * Fix gh CLI GHES host pinning and rate-limit scope leaks - Pin `--host` on every gh call site so a process-level GH_HOST can't silently redirect requests, and qualify `-R`/`-R=` repo shorthand alongside the existing `--repo=` handling. - Check the target scope for an active rate-limit block before each WSL/native or host fallback retry, not just on the initial attempt, so a blocked scope can't be hit again through a fallback path. - Compute idempotency once per call instead of re-deriving it after fallback reassigns args. * Fix GitHub Enterprise host identity loss across PR/work-item paths - Thread `host` through mobile PR RPC params, IPC work-item lookups, and RPC schemas so GHES identity survives the renderer/mobile/main boundary instead of silently falling back to a same-named github.com repo. - Qualify `--repo`/`-R` args for github.com too (not just GHES), since gh resolves bare shorthand against a process-level GH_HOST that can redirect pinned github.com commands. - Cache `getOriginGitHubApiRepository` to avoid a per-call uncached `git remote get-url` round trip on connection-backed repos. - Add a local-fork fallback in `getWorkItemDetails` so PRs living on a base repo (not visible via the origin slug) still resolve via cwd. - Centralize the github.com-vs-GHES host predicate in `isDefaultGitHubHost` so cache keys, quota scoping, and identity checks can't drift out of sync. * Make repository identity host-aware across all GitHub surfaces Generalize the auth-gated enterprise resolver to any remote and build a cached hosted-identity family (origin/issue/candidates/source) on top of it, then migrate every github.com-only consumer: Tasks listing/counting, branch-to-PR discovery, push targets, fork upstream, issue operations, Projects, web links, avatars, and PR-link facts. Scope the rate-limit breaker probe per runtime:host and classify WSL UNC cwds correctly. Co-authored-by: Orca <help@stably.ai> * Fix expected slug to include host field in GitHub PR link test Updates the smart-source paste-intent test fixture to match the repository slug shape that now carries a `host` field, keeping GHES host identity intact through the paste-intent parsing path. * Surface per-host gh auth state for GitHub Enterprise diagnoseGhAuth accepts the host a surface needs credentials for, scopes the account/scope diagnosis to that host, and reports whether gh has any login there; GhAuthErrorHelp renders host-qualified login/refresh commands so an unauthenticated GHES host stops masquerading as a github.com scope problem. Also fixes the mobile paste-intent expectation for host-carrying parsed links. Co-authored-by: Orca <help@stably.ai> * Bound GHES identity caches and preserve non-default ports in host identity Cap the origin-repo and host-auth caches like ownerRepoCache; keep ports from remote/link URLs so GHES on a non-default port is a distinct identity; make positional github.com slugs explicit against GH_HOST; compare work-item sources by host-aware identity key; bail cwd-less branch lookups when no repository candidate resolved; thread host through the renderer work-item slug lookup. Co-authored-by: Orca <help@stably.ai> * Thread GitHub host through issue detail requests Incorporates ghes-issue-host-support (ed6bb96ef): one hosted issue repository identity is resolved before the details fan-out so comments, timeline, participants, and mention lookups cannot drift across hosts, with SSH guards so unresolved issue/PR repositories never fall through to gh's default host. Co-authored-by: Orca <help@stably.ai> * Scope remaining GitHub rate-limit accounting * Resolve typed PR lookups across hosted repository candidates getWorkItem's PR path probes upstream-then-origin hosted candidates instead of origin alone, so fork checkouts resolve the base repo's PR with the right host; issue detail resolution reuses the up-front hosted identity and keeps the SSH unresolved-host guards. Co-authored-by: Orca <help@stably.ai> * Refactor GitHub repository execution setup * Carry host on smart-submit link intents Co-authored-by: Orca <help@stably.ai> * Carry the project host on GitHub item dialog origins Co-authored-by: Orca <help@stably.ai> * Keep GHES web ports but drop SSH transport ports in host identity Supersedes PR #9118 on this branch: http(s) remote ports identify the Enterprise web/API endpoint and are preserved, while ssh/git transport ports (including ssh.github.com:443) never leak into gh's host identity. Replaces the ssh.github.com:443 special case with the structural protocol split and ports the PR's parsing test suite. Co-authored-by: Orca <help@stably.ai> * Support GitHub Enterprise diffs and mutations with host-scoped caches Parse GitHub host identity from work-item URLs and carry it through PR/issue mutations, labels, and assignments. Bound rate-limit and scope-probe caches (1024 and 512 entries) to prevent unbounded growth when interacting with multiple GHES instances. Normalize repository identity keys to include host so github.com and GHES slugs don't collide in cache and equality checks. * Support GitHub Enterprise diffs and mutations with host-scoped caches - Carry host identity through PR mutations and reads so fork PRs on different GHES instances don't collide in cache or state tracking. - Validate host authentication before routing requests to unconfigured Enterprise servers; ambient credentials must never reach untrusted hosts. - Scope rate-limit guards and spend tracking per host so GHES quota stays independent from github.com quota. - Respect explicit --hostname arguments in gh CLI calls ahead of GH_HOST or ambient defaults, so breaker state follows the actual request target. - Detect implicit WSL runtimes from UNC paths for consistent host auth and execution-options scoping across mobile and desktop clients. * Support GitHub Enterprise work-item diffs with host-scoped execution Enterprise PRs must use their selected host consistently across diff, comments, and file-content loads. Validate repository slugs before authenticated execution to prevent path-injection via renderer overrides. Scope project browsing cache and rate-limit tracking by host to prevent cross-host pollution. Use parsed URLs as authoritative over ambient hosts for project resolution. * Support GitHub Enterprise work-item diffs with host-scoped execution Preserve host identity on PR/issue work items throughout the mutation and diff pipeline so Enterprise instances (including ported endpoints like github.acme.test:8443) can execute mutations without ambiguity. Rate-limit gh commands by the pre-qualified --repo host, cache auth state per ported host, and surface Enterprise hosts in project metadata and error messages. * fix(review): drop dead rateLimitGuard/noteRateLimitSpend re-export Both callers (project-view.ts, mutations.ts) moved to the host-scoped repositoryRateLimitGuard/noteRepositoryRateLimitSpend; the bucket-only re-export in internals.ts had zero importers left. Co-authored-by: Orca <help@stably.ai> * fix(ci): split Enterprise host work-item tests under max-lines Move GHES/SSH host-routing cases out of work-item-details.test.ts so the suite stays within the 800-line test max-lines budget. * test(github): align mocks with host-scoped repository resolution - Route origin repository resolution through getOwnerRepoForRemote, not getOwnerRepo, to match production path - Pin github.com host on origin results so host-less fixtures pass host gate in resolveGitHubApiRepository - Add generation-based invalidation to prevent stale slug-cache writes from in-flight resolutions - Fix ref-sync race in ProjectPicker: use useLayoutEffect so committed tree owns browse cache key - Defer handledCrossRepoUrlRef assignment in SmartWorkspaceNameField until resolution succeeds - Update Enterprise host routing: found work items must not silently fall back to default host when unresolved - Normalize GHES avatar URLs: accept explicit port 443 as canonical form, not a fallback trigger --------- Co-authored-by: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Co-authored-by: Orca <help@stably.ai>
394 lines
14 KiB
TypeScript
394 lines
14 KiB
TypeScript
/*
|
|
* Issue #9171 — "Wrong PR diffs displayed when checking out the default branch".
|
|
*
|
|
* A repo's default branch is `master`. In the past someone opened a PR whose
|
|
* HEAD was `master` (accidentally opening a PR *from* the default branch); it
|
|
* was closed long ago. getPRForBranch looks a PR up purely by head branch name
|
|
* with `state=all`, so without a guard that stale closed PR gets attached to
|
|
* the default-branch checkout, surfacing its wrong diffs and checks.
|
|
*
|
|
* These tests assert the CORRECT behavior: an implicit (non-linked) branch or
|
|
* fallback-number match on the repo default branch never surfaces a non-open
|
|
* PR, while open PRs on the trunk and closed/merged PRs on feature branches
|
|
* keep today's behavior. The default branch is resolved by the REAL
|
|
* resolveDefaultBaseRefViaExec over the mocked git exec layer, so the
|
|
* symbolic-ref / rev-parse plumbing and the `origin/` strip are exercised.
|
|
*/
|
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
|
|
|
type RateLimitGuardResult =
|
|
| { blocked: false }
|
|
| { blocked: true; remaining: number; limit: number; resetAt: number }
|
|
|
|
const {
|
|
execFileAsyncMock,
|
|
ghExecFileAsyncMock,
|
|
getOwnerRepoMock,
|
|
getIssueOwnerRepoMock,
|
|
getOwnerRepoForRemoteMock,
|
|
resolvePRRepositoryCandidatesMock,
|
|
getRemoteUrlForRepoMock,
|
|
gitExecFileAsyncMock,
|
|
getRateLimitMock,
|
|
rateLimitGuardMock,
|
|
noteRateLimitSpendMock,
|
|
ghRepoExecOptionsMock,
|
|
githubRepoContextMock,
|
|
getSshGitProviderMock,
|
|
readLocalGitConfigSignatureMock,
|
|
acquireMock,
|
|
releaseMock
|
|
} = vi.hoisted(() => ({
|
|
execFileAsyncMock: vi.fn(),
|
|
ghExecFileAsyncMock: vi.fn(),
|
|
getOwnerRepoMock: vi.fn(),
|
|
getIssueOwnerRepoMock: vi.fn(),
|
|
getOwnerRepoForRemoteMock: vi.fn(),
|
|
resolvePRRepositoryCandidatesMock: vi.fn(),
|
|
getRemoteUrlForRepoMock: vi.fn(),
|
|
gitExecFileAsyncMock: vi.fn(),
|
|
getRateLimitMock: vi.fn(),
|
|
rateLimitGuardMock: vi.fn<(bucket?: string) => RateLimitGuardResult>(() => ({
|
|
blocked: false
|
|
})),
|
|
noteRateLimitSpendMock: vi.fn(),
|
|
ghRepoExecOptionsMock: vi.fn((context) =>
|
|
context.connectionId
|
|
? {}
|
|
: {
|
|
cwd: context.repoPath,
|
|
...(context.wslDistro ? { wslDistro: context.wslDistro } : {})
|
|
}
|
|
),
|
|
githubRepoContextMock: vi.fn((repoPath, connectionId, localGitOptions) => ({
|
|
repoPath,
|
|
connectionId: connectionId ?? null,
|
|
...localGitOptions
|
|
})),
|
|
getSshGitProviderMock: vi.fn(),
|
|
readLocalGitConfigSignatureMock: vi.fn(),
|
|
acquireMock: vi.fn(),
|
|
releaseMock: vi.fn()
|
|
}))
|
|
|
|
vi.mock('./gh-utils', () => ({
|
|
execFileAsync: execFileAsyncMock,
|
|
ghExecFileAsync: ghExecFileAsyncMock,
|
|
getOwnerRepo: getOwnerRepoMock,
|
|
getIssueOwnerRepo: getIssueOwnerRepoMock,
|
|
getOwnerRepoForRemote: getOwnerRepoForRemoteMock,
|
|
resolvePRRepositoryCandidates: resolvePRRepositoryCandidatesMock,
|
|
getRemoteUrlForRepo: getRemoteUrlForRepoMock,
|
|
gitExecFileAsync: gitExecFileAsyncMock,
|
|
ghRepoExecOptions: ghRepoExecOptionsMock,
|
|
githubRepoContext: githubRepoContextMock,
|
|
classifyGhError: (stderr: string) => {
|
|
const lower = stderr.toLowerCase()
|
|
if (lower.includes('not found') || stderr.includes('HTTP 404')) {
|
|
return { type: 'not_found', message: stderr }
|
|
}
|
|
if (lower.includes('rate limit')) {
|
|
return { type: 'rate_limited', message: stderr }
|
|
}
|
|
return { type: 'unknown', message: stderr }
|
|
},
|
|
parseGitHubOwnerRepo: (remoteUrl: string) => {
|
|
const match = remoteUrl.trim().match(/github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?$/)
|
|
return match ? { owner: match[1], repo: match[2] } : null
|
|
},
|
|
acquire: acquireMock,
|
|
release: releaseMock,
|
|
_resetOwnerRepoCache: vi.fn()
|
|
}))
|
|
|
|
vi.mock('../git/runner', () => ({
|
|
gitExecFileAsync: gitExecFileAsyncMock
|
|
}))
|
|
|
|
vi.mock('../providers/ssh-git-dispatch', () => ({
|
|
getSshGitProvider: getSshGitProviderMock
|
|
}))
|
|
|
|
vi.mock('./local-git-config-signature', () => ({
|
|
readLocalGitConfigSignature: readLocalGitConfigSignatureMock
|
|
}))
|
|
|
|
vi.mock('./rate-limit', () => ({
|
|
getRateLimit: getRateLimitMock,
|
|
rateLimitGuard: rateLimitGuardMock,
|
|
noteRateLimitSpend: noteRateLimitSpendMock
|
|
}))
|
|
|
|
import {
|
|
getPRForBranch,
|
|
getPRForBranchOutcome,
|
|
_resetOwnerRepoCache,
|
|
_resetMergeQueueCacheForTests,
|
|
__resetTrackedUpstreamBranchCacheForTests
|
|
} from './client'
|
|
import { __resetPRConflictSummaryCachesForTests } from './conflict-summary'
|
|
import { resetMergedPRCommitMembershipCacheForTest } from './merged-pr-commit-membership'
|
|
import { __resetRepoDefaultBranchCacheForTests } from '../source-control/repo-default-branch'
|
|
|
|
const DEFAULT_BRANCH_REF = 'refs/remotes/origin/master'
|
|
|
|
/**
|
|
* Answer the real resolveDefaultBaseRefViaExec probes (origin/HEAD
|
|
* symbolic-ref + rev-parse verification), the merged-at-head `rev-parse HEAD`
|
|
* probe, and the tracked-upstream `for-each-ref` snapshot.
|
|
*/
|
|
function primeGitExecForDefaultBranch({
|
|
defaultRef = DEFAULT_BRANCH_REF,
|
|
headOid = 'checkout-head-oid'
|
|
}: { defaultRef?: string; headOid?: string } = {}): void {
|
|
gitExecFileAsyncMock.mockImplementation(async (args: string[]) => {
|
|
if (args[0] === 'symbolic-ref' && args.includes('refs/remotes/origin/HEAD')) {
|
|
return { stdout: `${defaultRef}\n`, stderr: '' }
|
|
}
|
|
if (args[0] === 'rev-parse' && args[1] === '--verify') {
|
|
if (args.includes(defaultRef)) {
|
|
return { stdout: 'default-branch-oid\n', stderr: '' }
|
|
}
|
|
throw new Error(`fatal: Needed a single revision: ${args.join(' ')}`)
|
|
}
|
|
if (args[0] === 'rev-parse' && args[1] === 'HEAD') {
|
|
return { stdout: `${headOid}\n`, stderr: '' }
|
|
}
|
|
if (args[0] === 'for-each-ref') {
|
|
return { stdout: '', stderr: '' }
|
|
}
|
|
throw new Error(`unexpected git call: ${args.join(' ')}`)
|
|
})
|
|
}
|
|
|
|
type RestPRShape = {
|
|
number?: number
|
|
state?: string
|
|
merged_at?: string | null
|
|
head_ref?: string
|
|
head_sha?: string
|
|
}
|
|
|
|
function restPR({
|
|
number = 7,
|
|
state = 'closed',
|
|
merged_at = null,
|
|
head_ref = 'master',
|
|
head_sha = 'stale-master-oid'
|
|
}: RestPRShape = {}): Record<string, unknown> {
|
|
return {
|
|
number,
|
|
title: 'Historical PR',
|
|
state,
|
|
merged_at,
|
|
html_url: `https://github.com/acme/widgets/pull/${number}`,
|
|
updated_at: '2024-01-01T00:00:00Z',
|
|
draft: false,
|
|
mergeable: null,
|
|
base: { ref: 'old-release', sha: 'base-oid' },
|
|
head: { ref: head_ref, sha: head_sha }
|
|
}
|
|
}
|
|
|
|
/** Route the REST head-branch lookup; every other gh call fails so branch data
|
|
* is kept as-is (hydration falls back to the branch payload). */
|
|
function primeGhExecWithBranchList(list: Record<string, unknown>[]): void {
|
|
ghExecFileAsyncMock.mockImplementation(async (args: string[]) => {
|
|
if (args[0] === 'api' && args[1]?.includes('pulls?head=')) {
|
|
return { stdout: JSON.stringify(list) }
|
|
}
|
|
throw new Error(`gh unavailable: ${args.join(' ')}`)
|
|
})
|
|
}
|
|
|
|
describe('issue #9171: default-branch checkout must not attach a stale non-open PR', () => {
|
|
beforeEach(() => {
|
|
execFileAsyncMock.mockReset()
|
|
ghExecFileAsyncMock.mockReset()
|
|
getOwnerRepoMock.mockReset()
|
|
getOwnerRepoMock.mockResolvedValue({ owner: 'acme', repo: 'widgets' })
|
|
getIssueOwnerRepoMock.mockReset()
|
|
getOwnerRepoForRemoteMock.mockReset()
|
|
// Why: getPRForBranch resolves origin through getOwnerRepoForRemote.
|
|
getOwnerRepoForRemoteMock.mockImplementation(
|
|
async (repoPath: string, remoteName: string, connectionId?: string | null, opts = {}) =>
|
|
remoteName === 'origin' ? getOwnerRepoMock(repoPath, connectionId, opts) : null
|
|
)
|
|
resolvePRRepositoryCandidatesMock.mockReset()
|
|
resolvePRRepositoryCandidatesMock.mockImplementation(async (repoPath, connectionId) => {
|
|
const origin = await getOwnerRepoMock(repoPath, connectionId)
|
|
return { candidates: origin ? [origin] : [], headRepo: origin }
|
|
})
|
|
getRemoteUrlForRepoMock.mockReset()
|
|
gitExecFileAsyncMock.mockReset()
|
|
getRateLimitMock.mockReset()
|
|
getRateLimitMock.mockResolvedValue({ resources: {} })
|
|
rateLimitGuardMock.mockReset()
|
|
rateLimitGuardMock.mockReturnValue({ blocked: false })
|
|
noteRateLimitSpendMock.mockReset()
|
|
ghRepoExecOptionsMock.mockClear()
|
|
githubRepoContextMock.mockClear()
|
|
getSshGitProviderMock.mockReset()
|
|
readLocalGitConfigSignatureMock.mockReset()
|
|
readLocalGitConfigSignatureMock.mockResolvedValue(undefined)
|
|
acquireMock.mockReset()
|
|
releaseMock.mockReset()
|
|
acquireMock.mockResolvedValue(undefined)
|
|
_resetOwnerRepoCache()
|
|
_resetMergeQueueCacheForTests()
|
|
__resetTrackedUpstreamBranchCacheForTests()
|
|
__resetPRConflictSummaryCachesForTests()
|
|
resetMergedPRCommitMembershipCacheForTest()
|
|
__resetRepoDefaultBranchCacheForTests()
|
|
})
|
|
|
|
it('hides a stale CLOSED PR when checked out on the default branch (master)', async () => {
|
|
primeGitExecForDefaultBranch()
|
|
primeGhExecWithBranchList([restPR({ number: 7, state: 'closed' })])
|
|
|
|
const pr = await getPRForBranch('/repo-root', 'master')
|
|
|
|
// The head-branch lookup still runs (state=all) and sees the closed PR…
|
|
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(
|
|
['api', 'repos/acme/widgets/pulls?head=acme%3Amaster&state=all&per_page=1'],
|
|
{ cwd: '/repo-root', host: 'github.com' }
|
|
)
|
|
// …but the default-branch guard discards it: no PR on the trunk (#9171).
|
|
expect(pr).toBeNull()
|
|
})
|
|
|
|
it('reports kind="no-pr" from getPRForBranchOutcome on the default branch', async () => {
|
|
primeGitExecForDefaultBranch()
|
|
primeGhExecWithBranchList([restPR({ number: 7, state: 'closed' })])
|
|
|
|
const outcome = await getPRForBranchOutcome('/repo-root', 'master')
|
|
|
|
expect(outcome.kind).toBe('no-pr')
|
|
})
|
|
|
|
it('keeps a genuinely OPEN PR on the default branch visible', async () => {
|
|
primeGitExecForDefaultBranch()
|
|
primeGhExecWithBranchList([restPR({ number: 8, state: 'open' })])
|
|
|
|
const pr = await getPRForBranch('/repo-root', 'master')
|
|
|
|
expect(pr?.number).toBe(8)
|
|
expect(pr?.state).toBe('open')
|
|
// Open results never consult git for the default branch (lazy resolution).
|
|
expect(gitExecFileAsyncMock).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('keeps a CLOSED PR on a feature branch visible (behavior preserved)', async () => {
|
|
primeGitExecForDefaultBranch()
|
|
primeGhExecWithBranchList([
|
|
restPR({ number: 9, state: 'closed', head_ref: 'feature-x', head_sha: 'feature-oid' })
|
|
])
|
|
|
|
const pr = await getPRForBranch('/repo-root', 'feature-x')
|
|
|
|
expect(pr?.number).toBe(9)
|
|
expect(pr?.state).toBe('closed')
|
|
})
|
|
|
|
it('preserves the merged-at-head carve-out on a feature branch', async () => {
|
|
// Worktree HEAD is exactly the merged PR's final head commit.
|
|
primeGitExecForDefaultBranch({ headOid: 'merged-head-oid' })
|
|
primeGhExecWithBranchList([
|
|
restPR({
|
|
number: 10,
|
|
state: 'closed',
|
|
merged_at: '2024-02-02T00:00:00Z',
|
|
head_ref: 'feature-x',
|
|
head_sha: 'merged-head-oid'
|
|
})
|
|
])
|
|
|
|
const pr = await getPRForBranch('/repo-root', 'feature-x')
|
|
|
|
expect(pr?.number).toBe(10)
|
|
expect(pr?.state).toBe('merged')
|
|
})
|
|
|
|
it('hides a CLOSED fallback-number PR on the default branch (self-heal for persisted stale PRs)', async () => {
|
|
primeGitExecForDefaultBranch()
|
|
ghExecFileAsyncMock.mockImplementation(async (args: string[]) => {
|
|
if (args[0] === 'api' && args[1]?.includes('pulls?head=')) {
|
|
return { stdout: '[]' }
|
|
}
|
|
if (args[0] === 'pr' && args[1] === 'view' && args[2] === '7') {
|
|
return {
|
|
stdout: JSON.stringify({
|
|
number: 7,
|
|
title: 'Historical PR',
|
|
state: 'CLOSED',
|
|
url: 'https://github.com/acme/widgets/pull/7',
|
|
statusCheckRollup: [],
|
|
updatedAt: '2024-01-01T00:00:00Z',
|
|
isDraft: false,
|
|
mergeable: 'UNKNOWN',
|
|
baseRefName: 'old-release',
|
|
headRefName: 'master',
|
|
baseRefOid: 'base-oid',
|
|
headRefOid: 'stale-master-oid'
|
|
})
|
|
}
|
|
}
|
|
throw new Error(`gh unavailable: ${args.join(' ')}`)
|
|
})
|
|
|
|
const outcome = await getPRForBranchOutcome('/repo-root', 'master', null, null, 7)
|
|
|
|
expect(outcome.kind).toBe('no-pr')
|
|
})
|
|
|
|
it('overrides acceptMergedFallbackPR preservation for a merged fallback PR on the default branch', async () => {
|
|
primeGitExecForDefaultBranch()
|
|
ghExecFileAsyncMock.mockImplementation(async (args: string[]) => {
|
|
if (args[0] === 'api' && args[1]?.includes('pulls?head=')) {
|
|
return { stdout: '[]' }
|
|
}
|
|
if (args[0] === 'pr' && args[1] === 'view' && args[2] === '7') {
|
|
return {
|
|
stdout: JSON.stringify({
|
|
number: 7,
|
|
title: 'Historical PR',
|
|
state: 'MERGED',
|
|
url: 'https://github.com/acme/widgets/pull/7',
|
|
statusCheckRollup: [],
|
|
updatedAt: '2024-01-01T00:00:00Z',
|
|
isDraft: false,
|
|
mergeable: 'UNKNOWN',
|
|
baseRefName: 'old-release',
|
|
headRefName: 'master',
|
|
baseRefOid: 'base-oid',
|
|
headRefOid: 'stale-master-oid'
|
|
})
|
|
}
|
|
}
|
|
throw new Error(`gh unavailable: ${args.join(' ')}`)
|
|
})
|
|
|
|
const outcome = await getPRForBranchOutcome('/repo-root', 'master', null, null, 7, {
|
|
acceptMergedFallbackPR: true
|
|
})
|
|
|
|
expect(outcome.kind).toBe('no-pr')
|
|
})
|
|
|
|
it('fails open when the default branch cannot be resolved (stale PR still returned)', async () => {
|
|
// Every git probe fails: no origin/HEAD, no main/master refs.
|
|
gitExecFileAsyncMock.mockImplementation(async (args: string[]) => {
|
|
if (args[0] === 'for-each-ref') {
|
|
return { stdout: '', stderr: '' }
|
|
}
|
|
throw new Error(`fatal: git unavailable: ${args.join(' ')}`)
|
|
})
|
|
primeGhExecWithBranchList([restPR({ number: 7, state: 'closed' })])
|
|
|
|
const pr = await getPRForBranch('/repo-root', 'master')
|
|
|
|
expect(pr?.number).toBe(7)
|
|
expect(pr?.state).toBe('closed')
|
|
})
|
|
})
|