diff --git a/src/main/git/command-runner/git-exec-file.ts b/src/main/git/command-runner/git-exec-file.ts index 330ec78797e..9f592705634 100644 --- a/src/main/git/command-runner/git-exec-file.ts +++ b/src/main/git/command-runner/git-exec-file.ts @@ -138,7 +138,7 @@ async function gitExecFileAsyncUnlocked( ) { await terminationState.current const wasMissing = invalidateMissingDirectWslGit(error, resolved) - if (options.canStart?.() === false) { + if (options.canStart?.() === false || (await options.beforeStart?.()) === false) { throw createAbortError() } const fallback = resolveGitCommand(args, effectiveOptions, true, true) @@ -164,7 +164,7 @@ async function gitExecFileAsyncUnlocked( } try { options.admissionSignal?.throwIfAborted() - if (options.canStart?.() === false) { + if (options.canStart?.() === false || (await options.beforeStart?.()) === false) { throw createAbortError() } return await runCapturedCommand() diff --git a/src/main/git/command-runner/git-exec-options.ts b/src/main/git/command-runner/git-exec-options.ts index 1fb3821b0b5..4ea94027091 100644 --- a/src/main/git/command-runner/git-exec-options.ts +++ b/src/main/git/command-runner/git-exec-options.ts @@ -17,6 +17,8 @@ export type GitExecOptions = { admissionSignal?: AbortSignal /** Rechecks owner eligibility after admission, before starting the child. */ canStart?: () => boolean + /** Like canStart, awaited once admitted; it must not run Git itself, which could wait on this slot. */ + beforeStart?: () => Promise wslDistro?: string /** Runs the host's Git even in a WSL-runtime project (local-git-runtime-route.ts); say why. */ hostGit?: true diff --git a/src/main/git/command-runner/host-routing/wsl-path-translation.ts b/src/main/git/command-runner/host-routing/wsl-path-translation.ts index 7fd2d59c794..627781a6685 100644 --- a/src/main/git/command-runner/host-routing/wsl-path-translation.ts +++ b/src/main/git/command-runner/host-routing/wsl-path-translation.ts @@ -32,15 +32,23 @@ export function translateWslOutputPaths( originalCwd: string, options: { wslDistro?: string } = {} ): string { - const wsl = parseWslPath(originalCwd) - const distro = wsl?.distro ?? options.wslDistro - if (!distro) { - return output - } - - // A repo saved under the distro's view of a drive keeps that spelling: its worktree ids use it. - const toWindows = wsl && isDrvfsLinuxPath(wsl.linuxPath) ? toWindowsWslUncPath : toWindowsWslPath - return output.replace(/(?<=worktree )(\/.+)$/gm, (_match, linuxPath: string) => - toWindows(linuxPath, distro) + return output.replace(/(?<=worktree )(\/.+)$/gm, (linuxPath: string) => + translateWslOutputPath(linuxPath, originalCwd, options) ) } + +/** One absolute Linux path from WSL Git output, as a path Node can open on Windows. */ +export function translateWslOutputPath( + linuxPath: string, + originalCwd: string, + options: { wslDistro?: string } = {} +): string { + const wsl = parseWslPath(originalCwd) + const distro = wsl?.distro ?? options.wslDistro + if (!distro || !linuxPath.startsWith('/')) { + return linuxPath + } + // A repo saved under the distro's view of a drive keeps that spelling: its worktree ids use it. + const toWindows = wsl && isDrvfsLinuxPath(wsl.linuxPath) ? toWindowsWslUncPath : toWindowsWslPath + return toWindows(linuxPath, distro) +} diff --git a/src/main/git/worktrees/creation/worktree-add-local-base-refresh.test.ts b/src/main/git/worktrees/creation/worktree-add-local-base-refresh.test.ts index bea59c9948d..56043e45b4b 100644 --- a/src/main/git/worktrees/creation/worktree-add-local-base-refresh.test.ts +++ b/src/main/git/worktrees/creation/worktree-add-local-base-refresh.test.ts @@ -1,4 +1,7 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const { gitExecFileAsyncMock, @@ -29,6 +32,12 @@ vi.mock('../../command-runner/host-routing/wsl-path-translation', async (importO translateWslOutputPaths: translateWslOutputPathsMock })) +// The detached checkout fast-forward would drain later tests' queues; real-Git tests cover it. +vi.mock('./worktree-base-refresh', async (importOriginal) => ({ + ...(await importOriginal>()), + fastForwardCheckedOutLocalBaseAfterCreate: vi.fn() +})) + // Keep the ordered runner queues; worktree-checkout-progress-real-git covers the checkout.workers read. vi.mock('./checkout-workers-git-args', () => ({ checkoutWorkersGitArgs: async () => [] @@ -39,6 +48,10 @@ import { registerWorktreeSuiteHooks } from '../testing/worktree-test-harness' registerWorktreeSuiteHooks() +// A real, empty Git common dir: no rebase or bisect reserves main. +const commonDir = mkdtempSync(join(tmpdir(), 'orca-add-refresh-common-')) +afterAll(() => rmSync(commonDir, { recursive: true, force: true })) + describe('addWorktree', () => { afterEach(() => vi.restoreAllMocks()) beforeEach(() => { @@ -54,39 +67,37 @@ describe('addWorktree', () => { }) gitExecFileAsyncMock .mockReset() - .mockImplementation((args: string[], opts: unknown) => - (args[0] === 'worktree' && args[1] === 'add') || - args[0] === 'config' || - (args[0] === 'branch' && args[1] === '--set-upstream-to') - ? checkoutGitMock(args, opts) - : refreshGitMock(args, opts) + .mockImplementation(async (args: string[], opts: unknown) => + args[0] === 'rev-parse' && args[1] === '--git-common-dir' + ? { stdout: `${commonDir}\n` } + : (args[0] === 'worktree' && args[1] === 'add') || + args[0] === 'config' || + (args[0] === 'branch' && args[1] === '--set-upstream-to') + ? checkoutGitMock(args, opts) + : refreshGitMock(args, opts) ) gitExecFileSyncMock.mockReset() translateWslOutputPathsMock.mockClear() }) it('runs worktree add while the local base refresh is still fast-forwarding', async () => { - const worktreeListOutput = 'worktree /repo\nHEAD abc123\nbranch refs/heads/main\n' - let finishMerge!: () => void - let markMergeStarted!: () => void - const mergeStarted = new Promise((resolve) => { - markMergeStarted = resolve + let finishMove!: () => void + let markMoveStarted!: () => void + const moveStarted = new Promise((resolve) => { + markMoveStarted = resolve }) queueBehindInspection() - .mockResolvedValueOnce({ stdout: worktreeListOutput }) .mockResolvedValueOnce({ stdout: '' }) - .mockResolvedValueOnce({ stdout: 'refs/heads/main\n' }) .mockImplementationOnce( () => new Promise((resolve) => { - finishMerge = () => resolve({ stdout: '' }) - markMergeStarted() + finishMove = () => resolve({ stdout: '' }) + markMoveStarted() }) ) - .mockResolvedValueOnce({ stdout: 'remote-main\n' }) checkoutGitMock.mockImplementationOnce(async () => { - await mergeStarted - finishMerge() + await moveStarted + finishMove() return { stdout: '' } }) @@ -95,16 +106,14 @@ describe('addWorktree', () => { expect(result.localBaseRefRefresh).toEqual({ status: 'updated', baseRef: 'origin/main', - localBranch: 'main', - ownerWorktreePath: '/repo' + localBranch: 'main' }) expect(checkoutGitMock.mock.calls[0]?.[0]).toContain('add') }) it('fast-forwards local base via update-ref when localBranch is not checked out', async () => { - const worktreeListOutput = 'worktree /repo\nHEAD abc123\nbranch refs/heads/develop\n' queueBehindInspection() - .mockResolvedValueOnce({ stdout: worktreeListOutput }) + .mockResolvedValueOnce({ stdout: '' }) .mockResolvedValueOnce({ stdout: '' }) const result = await addWorktree('/repo', '/repo-feature', 'feature/test', 'origin/main', true) @@ -123,67 +132,12 @@ describe('addWorktree', () => { 'remote-main', 'old-main' ], - { cwd: '/repo' } + expect.objectContaining({ cwd: '/repo', beforeStart: expect.any(Function) }) ]) - expect(refreshGitMock.mock.calls.map(([args]) => args)).not.toContainEqual( - ownerFastForwardArgs('remote-main') - ) - }) - - it('reports the owner dirty when the fast-forward refuses to overwrite an edit made after inspection', async () => { - const worktreeListOutput = 'worktree /repo\nHEAD abc123\nbranch refs/heads/main\n' - queueBehindInspection() - .mockResolvedValueOnce({ stdout: worktreeListOutput }) - .mockResolvedValueOnce({ stdout: '' }) - .mockResolvedValueOnce({ stdout: 'refs/heads/main\n' }) - .mockRejectedValueOnce( - Object.assign(new Error('Command failed: git merge'), { - stderr: - 'error: Your local changes to the following files would be overwritten by merge:\n\tpackage.json' - }) - ) - .mockRejectedValueOnce(Object.assign(new Error('not ancestor'), { code: 1 })) // merge-base - - const result = await addWorktree('/repo', '/repo-feature', 'feature/test', 'origin/main', true) - - expect(result.localBaseRefRefresh).toEqual({ - status: 'skipped_dirty_worktree', - baseRef: 'origin/main', - localBranch: 'main', - ownerWorktreePath: '/repo' - }) - expect(refreshGitMock.mock.calls.at(-1)).toEqual([ - ['merge-base', '--is-ancestor', 'remote-main', 'refs/heads/main'], - expect.objectContaining({ cwd: '/repo' }) - ]) - expect(gitExecFileAsyncMock.mock.calls.map(([args]) => args[0])).not.toContain('update-ref') - expect(gitExecFileAsyncMock.mock.calls.map(([args]) => args[0])).not.toContain('reset') - }) - - it('skips local base refresh when the owner worktree switches branches before mutation', async () => { - const worktreeListOutput = 'worktree /repo\nHEAD abc123\nbranch refs/heads/main\n' - queueBehindInspection() - .mockResolvedValueOnce({ stdout: worktreeListOutput }) - .mockResolvedValueOnce({ stdout: '' }) - .mockResolvedValueOnce({ stdout: 'refs/heads/develop\n' }) - .mockRejectedValueOnce(Object.assign(new Error('not ancestor'), { code: 1 })) // merge-base - - const result = await addWorktree('/repo', '/repo-feature', 'feature/test', 'origin/main', true) - - expect(result.localBaseRefRefresh).toEqual({ - status: 'skipped_error', - baseRef: 'origin/main', - localBranch: 'main', - ownerWorktreePath: '/repo' - }) - expect(gitExecFileAsyncMock.mock.calls.map(([args]) => args)).not.toContainEqual( - ownerFastForwardArgs('remote-main') - ) - expect(gitExecFileAsyncMock.mock.calls.map(([args]) => args[0])).not.toContain('update-ref') }) it('skips local base refresh when worktree ownership cannot be listed', async () => { - queueBehindInspection().mockRejectedValueOnce(new Error('worktree list failed')) + queueBehindInspection({ worktrees: new Error('worktree list failed') }) const result = await addWorktree('/repo', '/repo-feature', 'feature/test', 'origin/main', true) @@ -196,97 +150,10 @@ describe('addWorktree', () => { 'rev-parse', 'rev-parse', 'rev-parse', - 'rev-list', 'worktree' ]) }) - it('skips update when the owning worktree is dirty', async () => { - const worktreeListOutput = 'worktree /repo\nHEAD abc123\nbranch refs/heads/main\n' - queueBehindInspection() - .mockResolvedValueOnce({ stdout: worktreeListOutput }) - .mockResolvedValueOnce({ stdout: ' M package.json\n' }) - - const result = await addWorktree('/repo', '/repo-feature', 'feature/test', 'origin/main', true) - - expect(result.localBaseRefRefresh).toEqual({ - status: 'skipped_dirty_worktree', - baseRef: 'origin/main', - localBranch: 'main', - ownerWorktreePath: '/repo' - }) - - expect(refreshGitMock.mock.calls).toHaveLength(6) - expect(refreshGitMock.mock.calls[0]?.[0]).toEqual([ - 'rev-parse', - '--verify', - '--quiet', - 'refs/remotes/origin/main^{commit}' - ]) - expect(checkoutGitMock.mock.calls.map((call) => call[0])).toEqual([ - [ - 'worktree', - 'add', - '--no-track', - '-b', - 'feature/test', - '/repo-feature', - 'refs/remotes/origin/main' - ], - [ - 'config', - '--local', - '--replace-all', - 'branch.feature/test.base', - 'refs/remotes/origin/main' - ], - ['config', '--get', 'push.autoSetupRemote'], - ['config', '--local', 'push.autoSetupRemote', 'true'] - ]) - }) - - it('skips updating the local branch when its drift probe fails but the branch exists', async () => { - queueBehindInspection({ counts: new Error('not a fast-forward') }).mockResolvedValueOnce({ - stdout: '' - }) - - const result = await addWorktree('/repo', '/repo-feature', 'feature/test', 'origin/main', true) - - expect(result.localBaseRefRefresh).toEqual({ - status: 'skipped_not_fast_forward', - baseRef: 'origin/main', - localBranch: 'main' - }) - expect(refreshGitMock.mock.calls).toEqual([ - [ - ['rev-parse', '--verify', '--quiet', 'refs/remotes/origin/main^{commit}'], - expect.objectContaining({ cwd: '/repo' }) - ], - [ - ['rev-parse', '--verify', 'refs/heads/main^{commit}'], - expect.objectContaining({ cwd: '/repo' }) - ], - [ - ['rev-parse', '--verify', 'refs/remotes/origin/main^{commit}'], - expect.objectContaining({ cwd: '/repo' }) - ], - [ - ['rev-list', '--left-right', '--count', 'old-main...remote-main'], - expect.objectContaining({ cwd: '/repo' }) - ], - [ - ['show-ref', '--verify', '--quiet', '--', 'refs/heads/main'], - expect.objectContaining({ cwd: '/repo' }) - ] - ]) - expect(checkoutGitMock.mock.calls.map((call) => call[0][0])).toEqual([ - 'worktree', - 'config', - 'config', - 'config' - ]) - }) - // Creating the base's own local branch leaves nothing to refresh; probing would race the add. it('still suggests nothing but keeps the warning when the local base ref exists and diverged', async () => { @@ -300,68 +167,22 @@ describe('addWorktree', () => { localBranch: 'main' }) // The only call past the counts is the read-only shallow probe; nothing moves main. - expect(refreshGitMock.mock.calls).toHaveLength(5) + expect(refreshGitMock.mock.calls).toHaveLength(6) expect(refreshGitMock.mock.calls.at(-1)?.[0]).toEqual(['rev-parse', '--is-shallow-repository']) }) - - it('reports not-fast-forward when local gained a commit after the inspection', async () => { - const worktreeListOutput = 'worktree /repo\nHEAD abc123\nbranch refs/heads/main\n' - queueBehindInspection() - .mockResolvedValueOnce({ stdout: worktreeListOutput }) - .mockResolvedValueOnce({ stdout: '' }) - .mockResolvedValueOnce({ stdout: 'refs/heads/main\n' }) - .mockRejectedValueOnce( - Object.assign(new Error('Command failed: git merge'), { - stderr: 'fatal: Not possible to fast-forward, aborting.' - }) - ) - .mockRejectedValueOnce(Object.assign(new Error('not ancestor'), { code: 1 })) // merge-base - - const result = await addWorktree('/repo', '/repo-feature', 'feature/test', 'origin/main', true) - - expect(result.localBaseRefRefresh).toEqual({ - status: 'skipped_not_fast_forward', - baseRef: 'origin/main', - localBranch: 'main', - ownerWorktreePath: '/repo' - }) - expect(gitExecFileAsyncMock.mock.calls.map(([args]) => args[0])).not.toContain('reset') - }) }) -function ownerFastForwardArgs(remoteOid: string): string[] { - return [ - '-c', - 'core.hooksPath=/dev/null', - '-c', - 'gc.auto=0', - '-c', - 'maintenance.auto=false', - '-c', - 'merge.autoStash=false', - '-c', - 'branch.main.mergeOptions=', - 'merge', - '--ff-only', - '-s', - 'recursive', - '--no-verify-signatures', - '--no-overwrite-ignore', - '--no-stat', - '-q', - remoteOid - ] -} - function queueBehindInspection( - options: { remoteOid?: string; counts?: { stdout: string } | Error } = {} + options: { worktrees?: string | Error; counts?: { stdout: string } } = {} ) { - const counts = options.counts ?? { stdout: '0\t3\n' } + const worktrees = options.worktrees ?? 'worktree /repo\nHEAD abc123\nbranch refs/heads/develop\n' refreshGitMock .mockResolvedValueOnce({ stdout: 'abc123\n' }) .mockResolvedValueOnce({ stdout: 'old-main\n' }) - .mockResolvedValueOnce({ stdout: `${options.remoteOid ?? 'remote-main'}\n` }) - return counts instanceof Error - ? refreshGitMock.mockRejectedValueOnce(counts) - : refreshGitMock.mockResolvedValueOnce(counts) + .mockResolvedValueOnce({ stdout: 'remote-main\n' }) + if (worktrees instanceof Error) { + return refreshGitMock.mockRejectedValueOnce(worktrees) + } + refreshGitMock.mockResolvedValueOnce({ stdout: worktrees }) + return refreshGitMock.mockResolvedValueOnce(options.counts ?? { stdout: '0\t3\n' }) } diff --git a/src/main/git/worktrees/creation/worktree-add.ts b/src/main/git/worktrees/creation/worktree-add.ts index 845fd942965..a444c79e564 100644 --- a/src/main/git/worktrees/creation/worktree-add.ts +++ b/src/main/git/worktrees/creation/worktree-add.ts @@ -1,9 +1,6 @@ import { GitCommandTimeoutError } from '../../../../shared/git/commands/git-command-timeout' import { resolveWorktreeAddBaseRef } from '../../../../shared/worktree/base-refs/base-ref' -import type { - LocalBaseRefRefreshResult, - LocalBaseRefUpdateSuggestion -} from '../../../../shared/worktree/base-refs/base-ref-drift-types' +import type { LocalBaseRefRefreshResult } from '../../../../shared/worktree/base-refs/base-ref-drift-types' import { windowsLongPathGitArgs } from '../../../../shared/git/compatibility/windows-long-path-git-args' import { checkoutWorkersGitArgs } from './checkout-workers-git-args' import { withRepoRefMaintenancePaused } from '../../refs/maintenance/local-repo-ref-maintenance' @@ -11,6 +8,7 @@ import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { runWithGitReadCacheInvalidation } from '../../source-control/git-read-cache-invalidation' import { invalidateWslLinkedWorktreeGitRouting } from '../../command-runner/host-routing/wsl-linked-worktree-git-routing' import { + fastForwardCheckedOutLocalBaseAfterCreate, getLocalBaseRefUpdateSuggestionForWorktreeCreate, parseRemoteTrackingLocalBaseRef, refreshLocalBaseRefForWorktreeCreate @@ -35,6 +33,8 @@ export type WorktreeAddBaseContext = Pick + /** Call once the create succeeded; updates a checked-out base in the background. */ + updateCheckedOutLocalBase?: () => void } export async function resolveWorktreeAddBaseContext( @@ -83,7 +83,13 @@ export async function resolveWorktreeAddBaseContext( ...(!refreshLocalBaseRef && !options.suggestLocalBaseRefUpdate && effectiveBaseOid ? { effectiveBaseOid } : {}), - ...(pendingLocalBaseRefRefresh ? { pendingLocalBaseRefRefresh } : {}), + ...(pendingLocalBaseRefRefresh + ? { + pendingLocalBaseRefRefresh, + updateCheckedOutLocalBase: () => + fastForwardCheckedOutLocalBaseAfterCreate(repoPath, baseBranch, effectiveBase, options) + } + : {}), ...(localBaseRefUpdateSuggestion ? { localBaseRefUpdateSuggestion } : {}) } } @@ -144,18 +150,6 @@ export async function configurePushAutoSetupRemote( } } -export async function unsetWorktreeCreationBase( - worktreePath: string, - branch: string, - options: GitWorktreeExecOptions = {} -): Promise { - try { - await gitExecFileAsync(['config', '--local', '--unset-all', `branch.${branch}.base`], { - ...gitExecOptions(worktreePath, options) - }) - } catch {} -} - /** Track a same-name remote base; other newly created branches stay untracked. */ export async function trackSameNameRemoteBase( worktreePath: string, @@ -187,8 +181,19 @@ export async function trackSameNameRemoteBase( } } +type AddWorktreeOutcome = { result: AddWorktreeResult; updateCheckedOutLocalBase?: () => void } + /** Create a worktree; new branches record base lineage and may enable repo-wide push.autoSetupRemote. */ export async function addWorktree( + ...args: Parameters +): Promise { + const { result, updateCheckedOutLocalBase } = await addWorktreeDeferringLocalBaseUpdate(...args) + updateCheckedOutLocalBase?.() + return result +} + +/** For callers with checkout work left: they start the checked-out base update once it is done. */ +export async function addWorktreeDeferringLocalBaseUpdate( repoPath: string, worktreePath: string, branch: string, @@ -196,7 +201,7 @@ export async function addWorktree( refreshLocalBaseRef = false, noCheckout = false, options: AddWorktreeOptions = {} -): Promise { +): Promise { try { return await withRepoRefMaintenancePaused('worktree-add', () => runWithGitReadCacheInvalidation(() => @@ -224,11 +229,10 @@ async function performAddWorktree( refreshLocalBaseRef = false, noCheckout = false, options: AddWorktreeOptions = {} -): Promise { +): Promise { // Wait for background removal ownership to end before reusing its path or branch. assertNoPendingWorktreeRemovalConflict(repoPath, { worktreePath, branch }) - let pendingLocalBaseRefRefresh: Promise | undefined - let localBaseRefUpdateSuggestion: LocalBaseRefUpdateSuggestion | undefined + let baseContext: WorktreeAddBaseContext | undefined const args = [...windowsLongPathGitArgs(repoPath), 'worktree', 'add'] let effectiveBase: string | undefined if (options.trackRemoteBranch && !baseBranch) { @@ -245,7 +249,7 @@ async function performAddWorktree( // Avoid inheriting the base's upstream; same-name remote bases are tracked explicitly afterward. args.push('--no-track', '-b', branch, worktreePath) if (baseBranch) { - const baseContext = await resolveWorktreeAddBaseContext( + baseContext = await resolveWorktreeAddBaseContext( repoPath, baseBranch, refreshLocalBaseRef, @@ -258,8 +262,6 @@ async function performAddWorktree( 'Reuse branch requires a remote-tracking ref when the local branch is missing.' ) } - pendingLocalBaseRefRefresh = baseContext.pendingLocalBaseRefRefresh - localBaseRefUpdateSuggestion = baseContext.localBaseRefUpdateSuggestion args.push(effectiveBase) } } @@ -278,7 +280,7 @@ async function performAddWorktree( }) } catch (error) { // Settle the refresh before leaving the caller's maintenance pause on failure. - await pendingLocalBaseRefRefresh + await baseContext?.pendingLocalBaseRefRefresh if (error instanceof GitCommandTimeoutError) { error.message = worktreeAddTimeoutMessage(error.timeoutMs) } @@ -290,7 +292,7 @@ async function performAddWorktree( } if (options.checkoutExistingBranch) { - return {} + return { result: {} } } let upstreamWarning: string | undefined @@ -310,10 +312,14 @@ async function performAddWorktree( // Git >= 2.37 can set an upstream on first push; --local intentionally writes shared repo config. await configurePushAutoSetupRemote(worktreePath, options) - const localBaseRefRefresh = await pendingLocalBaseRefRefresh + const localBaseRefRefresh = await baseContext?.pendingLocalBaseRefRefresh + const localBaseRefUpdateSuggestion = baseContext?.localBaseRefUpdateSuggestion return { - ...(localBaseRefRefresh ? { localBaseRefRefresh } : {}), - ...(upstreamWarning ? { upstreamWarning } : {}), - ...(localBaseRefUpdateSuggestion ? { localBaseRefUpdateSuggestion } : {}) + result: { + ...(localBaseRefRefresh ? { localBaseRefRefresh } : {}), + ...(upstreamWarning ? { upstreamWarning } : {}), + ...(localBaseRefUpdateSuggestion ? { localBaseRefUpdateSuggestion } : {}) + }, + updateCheckedOutLocalBase: baseContext?.updateCheckedOutLocalBase } } diff --git a/src/main/git/worktrees/creation/worktree-base-refresh-contention.test.ts b/src/main/git/worktrees/creation/worktree-base-refresh-contention.test.ts index b4a651fc6cd..363a71436c6 100644 --- a/src/main/git/worktrees/creation/worktree-base-refresh-contention.test.ts +++ b/src/main/git/worktrees/creation/worktree-base-refresh-contention.test.ts @@ -1,4 +1,7 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const { gitExecFileAsyncMock } = vi.hoisted(() => ({ gitExecFileAsyncMock: @@ -20,18 +23,14 @@ import { refreshLocalBaseRefForWorktreeCreate } from './worktree-base-refresh' -const INDEX_LOCK_ERROR = Object.assign(new Error('Command failed: git merge --ff-only'), { - stderr: - "fatal: Unable to create '/repo/.git/index.lock': File exists.\n\nAnother git process seems to be running in this repository" -}) -const OWNER_WORKTREE_LIST = 'worktree /repo\nHEAD old-main\nbranch refs/heads/main\n' +// A real, empty Git common dir: no rebase or bisect reserves main. +const commonDir = mkdtempSync(join(tmpdir(), 'orca-refresh-contention-common-')) +afterAll(() => rmSync(commonDir, { recursive: true, force: true })) type GitFake = { - owner?: boolean mutate: () => Promise<{ stdout: string }> /** Whether local already contains the target when a failed move is re-checked. */ localContainsTarget?: () => boolean - ownerHead?: () => string } /** The git subcommand, past leading `-c key=value` and `--flag` globals. */ @@ -51,27 +50,25 @@ function installGitFake(fake: GitFake): void { gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { const command = commandOf(args) if (command === 'rev-parse') { + if (args[1] === '--git-common-dir') { + return { stdout: `${commonDir}\n` } + } return { stdout: args[2] === 'refs/heads/main^{commit}' ? `${localMain}\n` : 'remote-main\n' } } if (command === 'rev-list') { return { stdout: '0\t3\n' } } - if (command === 'status') { + if (command === 'worktree') { return { stdout: '' } } - if (command === 'worktree') { - return { stdout: fake.owner ? OWNER_WORKTREE_LIST : '' } - } - if (command === 'symbolic-ref') { - return { stdout: `${fake.ownerHead?.() ?? 'refs/heads/main'}\n` } - } if (command === 'merge-base') { - if (fake.localContainsTarget?.()) { + // Local is still an ancestor of the target unless asked whether it already contains it. + if (args[2] !== 'remote-main' || fake.localContainsTarget?.()) { return { stdout: '' } } throw Object.assign(new Error('not an ancestor'), { code: 1 }) } - if (command === 'merge' || command === 'update-ref') { + if (command === 'update-ref') { const result = await fake.mutate() localMain = 'remote-main' return result @@ -92,25 +89,8 @@ function mutationCalls(): string[][] { describe('refreshLocalBaseRefForWorktreeCreate lock contention', () => { beforeEach(() => { - vi.useFakeTimers() gitExecFileAsyncMock.mockReset() }) - afterEach(() => vi.useRealTimers()) - - it('re-confirms the owner has the branch checked out before each retry', async () => { - let symbolicRefReads = 0 - installGitFake({ - owner: true, - mutate: () => Promise.reject(INDEX_LOCK_ERROR), - ownerHead: () => (++symbolicRefReads >= 2 ? 'refs/heads/develop' : 'refs/heads/main') - }) - - const pending = refresh() - await vi.runAllTimersAsync() - - await expect(pending).resolves.toMatchObject({ status: 'skipped_error' }) - expect(mutationCalls()).toHaveLength(1) - }) it('does not retry a failure that is not lock contention', async () => { const casMismatch = Object.assign(new Error('Command failed: git update-ref'), { @@ -118,10 +98,7 @@ describe('refreshLocalBaseRefForWorktreeCreate lock contention', () => { }) installGitFake({ mutate: () => Promise.reject(casMismatch) }) - const pending = refresh() - await vi.runAllTimersAsync() - - await expect(pending).resolves.toMatchObject({ status: 'skipped_error' }) + await expect(refresh()).resolves.toMatchObject({ status: 'skipped_error' }) expect(mutationCalls()).toEqual([ [ 'update-ref', @@ -157,36 +134,36 @@ describe('refreshLocalBaseRefForWorktreeCreate runs one refresh at a time per br function installRepoFake(repoPath: string) { let localOid = 'old-main' - let finishMerge!: () => void - const mergeStarted = new Promise((resolve) => { + let finishMove!: () => void + const moveStarted = new Promise((resolve) => { gitExecFileAsyncMock.mockImplementation(async (args: string[], opts: { cwd: string }) => { const command = commandOf(args) if (opts.cwd.replace(/\/+$/, '') !== repoPath) { return { stdout: command === 'rev-parse' ? 'current\n' : '' } } if (command === 'rev-parse') { + if (args[1] === '--git-common-dir') { + return { stdout: `${commonDir}\n` } + } return { stdout: args[2]?.startsWith('refs/heads/') ? `${localOid}\n` : 'remote-main\n' } } if (command === 'rev-list') { return { stdout: '0\t3\n' } } if (command === 'worktree') { - return { stdout: `worktree ${repoPath}\nHEAD ${localOid}\nbranch refs/heads/main\n` } + return { stdout: `worktree ${repoPath}\nHEAD ${localOid}\nbranch refs/heads/develop\n` } } - if (command === 'symbolic-ref') { - return { stdout: 'refs/heads/main\n' } - } - if (command === 'merge') { + if (command === 'update-ref') { resolve() await new Promise((release) => { - finishMerge = release + finishMove = release }) localOid = 'remote-main' } return { stdout: '' } }) }) - return { mergeStarted, finishMerge: () => finishMerge() } + return { moveStarted, finishMove: () => finishMove() } } it('folds creates that arrive mid-refresh into one follow-up that finds local current', async () => { @@ -195,16 +172,16 @@ describe('refreshLocalBaseRefForWorktreeCreate runs one refresh at a time per br const first = refresh('/repo') const joiners = [refresh('/repo/'), refresh('/repo')] - await repo.mergeStarted - const callsWhileFirstMerges = gitExecFileAsyncMock.mock.calls.length - repo.finishMerge() + await repo.moveStarted + const callsWhileFirstMoves = gitExecFileAsyncMock.mock.calls.length + repo.finishMove() await expect(first).resolves.toMatchObject({ status: 'updated' }) await expect(Promise.all(joiners)).resolves.toEqual([undefined, undefined]) const commands = gitExecFileAsyncMock.mock.calls.map(([args]) => commandOf(args)) - // Joiners share a follow-up inspection only after the first run releases the checkout. - expect(commands.slice(0, callsWhileFirstMerges).filter((c) => c === 'rev-list')).toHaveLength(1) - expect(commands.slice(callsWhileFirstMerges)).toEqual(['rev-parse', 'rev-parse', 'rev-parse']) + // Joiners share a follow-up inspection only after the first run releases the branch. + expect(commands.slice(0, callsWhileFirstMoves).filter((c) => c === 'rev-list')).toHaveLength(1) + expect(commands.slice(callsWhileFirstMoves)).toEqual(['rev-parse', 'rev-parse']) expect(mutationCalls()).toHaveLength(1) expect(warn).not.toHaveBeenCalled() warn.mockRestore() @@ -214,9 +191,9 @@ describe('refreshLocalBaseRefForWorktreeCreate runs one refresh at a time per br const repo = installRepoFake('/repo') const first = refresh('/repo') - await repo.mergeStarted + await repo.moveStarted await expect(refresh('/other')).resolves.toBeUndefined() - repo.finishMerge() + repo.finishMove() await expect(first).resolves.toMatchObject({ status: 'updated' }) }) @@ -227,7 +204,7 @@ describe('refreshLocalBaseRefForWorktreeCreate runs one refresh at a time per br let secondResult: unknown = 'pending' const first = refresh('/repo') - await repo.mergeStarted + await repo.moveStarted await vi.advanceTimersByTimeAsync(10_000) const second = refresh('/repo').then((result) => (secondResult = result)) @@ -240,7 +217,7 @@ describe('refreshLocalBaseRefForWorktreeCreate runs one refresh at a time per br expect(mutationCalls()).toHaveLength(1) expect(warn).toHaveBeenCalledWith(expect.stringContaining('stopped waiting')) - repo.finishMerge() + repo.finishMove() await vi.runAllTimersAsync() await vi.waitFor(() => expect(gitExecFileAsyncMock.mock.calls.at(-1)?.[0][0]).toBe('rev-parse')) expect(mutationCalls()).toHaveLength(1) diff --git a/src/main/git/worktrees/creation/worktree-base-refresh-lock-real-git.test.ts b/src/main/git/worktrees/creation/worktree-base-refresh-lock-real-git.test.ts index 76602012f68..a8f6963e819 100644 --- a/src/main/git/worktrees/creation/worktree-base-refresh-lock-real-git.test.ts +++ b/src/main/git/worktrees/creation/worktree-base-refresh-lock-real-git.test.ts @@ -16,8 +16,8 @@ function git(cwd: string, args: string[]): string { }).trim() } -// Primary checkout on `main` one commit behind `refs/remotes/origin/main`, with its index locked. -async function createBehindRepoWithIndexLock(): Promise<{ +// `main` one commit behind `refs/remotes/origin/main`; `lock` names a file another Git process could hold. +async function createBehindRepo(lock: 'main-ref' | 'index' = 'main-ref'): Promise<{ repoPath: string lockPath: string localOid: string @@ -42,29 +42,32 @@ async function createBehindRepoWithIndexLock(): Promise<{ git(repoPath, ['checkout', '--quiet', 'main']) git(repoPath, ['update-ref', 'refs/remotes/origin/main', remoteOid]) git(repoPath, ['branch', '--quiet', '-D', 'upstream']) - const lockPath = join(repoPath, '.git', 'index.lock') + if (lock === 'main-ref') { + git(repoPath, ['checkout', '--quiet', '-b', 'develop']) + } + const lockPath = join(repoPath, '.git', lock === 'index' ? 'index.lock' : 'refs/heads/main.lock') await writeFile(lockPath, '') return { repoPath, lockPath, localOid, remoteOid } } -function isOwnerFastForward(args: readonly string[]): boolean { - return args.includes('merge') && args.includes('--ff-only') +function isWrite(args: readonly string[]): boolean { + return args.includes('update-ref') || args.includes('merge') } -/** Counts owner fast-forwards; `onFailure` runs after each failed one, before it is reported. */ +/** Counts writes; `onFailure` runs after each failed one, before it is reported. */ function spyOnFastForwards(onFailure: () => Promise | void = () => {}): { - merges: () => number + writes: () => number maxConcurrent: () => number } { const original = gitRunner.gitExecFileAsync - let merges = 0 + let writes = 0 let active = 0 let maxConcurrent = 0 vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args, options) => { - if (!isOwnerFastForward(args)) { + if (!isWrite(args)) { return original(args, options) } - merges += 1 + writes += 1 active += 1 maxConcurrent = Math.max(maxConcurrent, active) try { @@ -76,7 +79,7 @@ function spyOnFastForwards(onFailure: () => Promise | void = () => {}): { active -= 1 } }) - return { merges: () => merges, maxConcurrent: () => maxConcurrent } + return { writes: () => writes, maxConcurrent: () => maxConcurrent } } function refresh(repoPath: string, remote: 'origin' | 'upstream' = 'origin') { @@ -87,19 +90,19 @@ function refresh(repoPath: string, remote: 'origin' | 'upstream' = 'origin') { ) } -// A fork: checked-out `main` behind `origin/main`, which is one commit behind `upstream/main`. +// A fork: `main` behind `origin/main`, which is one commit behind `upstream/main`. async function createForkRepo(): Promise<{ repoPath: string originOid: string upstreamOid: string }> { - const { repoPath, lockPath, remoteOid: originOid } = await createBehindRepoWithIndexLock() + const { repoPath, lockPath, remoteOid: originOid } = await createBehindRepo() await rm(lockPath, { force: true }) git(repoPath, ['checkout', '--quiet', '-b', 'fork-upstream', originOid]) await writeFile(join(repoPath, 'version.txt'), 'three\n') git(repoPath, ['commit', '--quiet', '-am', 'three']) const upstreamOid = git(repoPath, ['rev-parse', 'HEAD']) - git(repoPath, ['checkout', '--quiet', 'main']) + git(repoPath, ['checkout', '--quiet', 'develop']) git(repoPath, ['update-ref', 'refs/remotes/upstream/main', upstreamOid]) git(repoPath, ['branch', '--quiet', '-D', 'fork-upstream']) return { repoPath, originOid, upstreamOid } @@ -117,22 +120,85 @@ afterEach(async () => { await Promise.all(tempRoots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) }) -describe('local base refresh against a held index.lock with real Git', () => { +describe('local base refresh of a checked-out branch with real Git', () => { + it('leaves it alone while another Git process holds its index.lock', async () => { + const { repoPath, lockPath, localOid } = await createBehindRepo('index') + const spy = spyOnFastForwards() + + await expect(refresh(repoPath)).resolves.toBeUndefined() + + expect(spy.writes()).toBe(0) + expect(git(repoPath, ['rev-parse', 'main'])).toBe(localOid) + expect(await readFile(lockPath, 'utf8')).toBe('') + }) +}) + +describe('local base refresh of a branch a rebase has reserved with real Git', () => { + it('leaves it alone although no worktree lists it as checked out', async () => { + const { repoPath, lockPath, localOid } = await createBehindRepo() + await rm(lockPath, { force: true }) + git(repoPath, ['checkout', '--quiet', 'main']) + // Stops mid-rebase with HEAD detached; Git still treats main as in use. + expect(() => git(repoPath, ['rebase', '--quiet', '--root', '--exec', 'false'])).toThrow() + const spy = spyOnFastForwards() + + await expect(refresh(repoPath)).resolves.toBeUndefined() + + expect(spy.writes()).toBe(0) + expect(git(repoPath, ['rev-parse', 'main'])).toBe(localOid) + }) + + it('leaves a branch alone while a linked worktree bisects it', async () => { + const { repoPath, lockPath, localOid } = await createBehindRepo() + await rm(lockPath, { force: true }) + const linkedPath = join(repoPath, '..', 'linked') + git(repoPath, ['worktree', 'add', '--quiet', linkedPath, 'main']) + git(linkedPath, ['bisect', 'start']) + git(linkedPath, ['checkout', '--quiet', '--detach']) + const spy = spyOnFastForwards() + + await expect(refresh(repoPath)).resolves.toBeUndefined() + + expect(spy.writes()).toBe(0) + expect(git(repoPath, ['rev-parse', 'main'])).toBe(localOid) + }) +}) + +describe('local base refresh racing a checkout with real Git', () => { + it('skips the write when the branch is checked out while update-ref waits to start', async () => { + const { repoPath, lockPath, localOid } = await createBehindRepo() + await rm(lockPath, { force: true }) + const original = gitRunner.gitExecFileAsync + vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args, options) => { + if (args[0] === 'update-ref') { + git(repoPath, ['checkout', '--quiet', 'main']) + } + return original(args, options) + }) + + await expect(refresh(repoPath)).resolves.toBeUndefined() + + expect(git(repoPath, ['rev-parse', 'main'])).toBe(localOid) + expect(git(repoPath, ['status', '--porcelain'])).toBe('') + }) +}) + +describe('local base refresh against a held ref lock with real Git', () => { it('retries once the other git process releases the lock', async () => { - const { repoPath, lockPath, remoteOid } = await createBehindRepoWithIndexLock() + const { repoPath, lockPath, remoteOid } = await createBehindRepo() const spy = spyOnFastForwards(() => rm(lockPath, { force: true })) const result = await refresh(repoPath) expect(result).toMatchObject({ status: 'updated' }) - expect(spy.merges()).toBe(2) + expect(spy.writes()).toBe(2) expect(git(repoPath, ['rev-parse', 'main'])).toBe(remoteOid) - expect(await readFile(join(repoPath, 'version.txt'), 'utf8')).toBe('two\n') }) it('reports updated when another process fast-forwarded local while holding the lock', async () => { - const { repoPath, remoteOid } = await createBehindRepoWithIndexLock() - spyOnFastForwards(() => { + const { repoPath, lockPath, remoteOid } = await createBehindRepo() + spyOnFastForwards(async () => { + await rm(lockPath, { force: true }) git(repoPath, ['update-ref', 'refs/heads/main', remoteOid]) }) @@ -143,29 +209,29 @@ describe('local base refresh against a held index.lock with real Git', () => { }) it('reports skipped_error when the lock outlives every retry', async () => { - const { repoPath, localOid } = await createBehindRepoWithIndexLock() + const { repoPath, localOid } = await createBehindRepo() const spy = spyOnFastForwards() const result = await refresh(repoPath) expect(result).toMatchObject({ status: 'skipped_error' }) - expect(spy.merges()).toBe(4) + expect(spy.writes()).toBe(4) expect(git(repoPath, ['rev-parse', 'main'])).toBe(localOid) }) }) describe('concurrent local base refreshes of one repo with real Git', () => { it('runs one fast-forward and resolves every create without a warning', async () => { - const { repoPath, lockPath, remoteOid } = await createBehindRepoWithIndexLock() + const { repoPath, lockPath, remoteOid } = await createBehindRepo() await rm(lockPath, { force: true }) const spy = spyOnFastForwards() const warn = vi.spyOn(console, 'warn') const results = await Promise.all([refresh(repoPath), refresh(repoPath), refresh(repoPath)]) - expect(results[0]).toMatchObject({ status: 'updated', ownerWorktreePath: expect.any(String) }) + expect(results[0]).toEqual({ baseRef: 'origin/main', localBranch: 'main', status: 'updated' }) expect(results.slice(1)).toEqual([undefined, undefined]) - expect(spy.merges()).toBe(1) + expect(spy.writes()).toBe(1) expect(warn).not.toHaveBeenCalled() expect(git(repoPath, ['rev-parse', 'main'])).toBe(remoteOid) }) diff --git a/src/main/git/worktrees/creation/worktree-base-refresh.ts b/src/main/git/worktrees/creation/worktree-base-refresh.ts index 84f21523dc6..312d7593b62 100644 --- a/src/main/git/worktrees/creation/worktree-base-refresh.ts +++ b/src/main/git/worktrees/creation/worktree-base-refresh.ts @@ -1,3 +1,5 @@ +import { readdir, readFile, stat } from 'node:fs/promises' +import { isAbsolute, join } from 'node:path' import type { LocalBaseRefRefreshResult, LocalBaseRefUpdateSuggestion @@ -6,6 +8,7 @@ import { normalizeRuntimePathForComparison } from '../../../../shared/cross-plat import { createCoalescingKeyedRunner } from '../../../../shared/concurrency/coalescing-keyed-runner' import { parseWorktreeList } from '../../../../shared/git/worktrees/git-worktree-porcelain-parser' import { + fastForwardCheckedOutLocalBaseBranch, fastForwardLocalBaseBranch, inspectLocalBaseBranch, toLocalBaseRefRefreshResult, @@ -13,17 +16,24 @@ import { type LocalBaseBranchGit } from '../../../../shared/worktree/base-refs/local-base-branch-fast-forward' import { gitExecFileAsync } from '../../command-runner/git-exec-file' -import { findGitSubcommandIndex } from '../../../../shared/git/commands/git-command-classification' -import { translateWslOutputPaths } from '../../command-runner/host-routing/wsl-path-translation' +import { + translateWslOutputPath, + translateWslOutputPaths +} from '../../command-runner/host-routing/wsl-path-translation' +import { routeLocalGitOptions } from '../../command-runner/host-routing/local-git-runtime-route' +import type { GitExecOptions } from '../../command-runner/git-exec-options' import { runWithGitReadCacheInvalidation } from '../../source-control/git-read-cache-invalidation' import type { AddWorktreeOptions, GitWorktreeExecOptions } from '../worktree-operation-options' -// Bound the create's wait without cancelling the mutating refresh that still owns its checkout. +// Bound the create's wait on the shared ref-only refresh. export const LOCAL_BASE_REF_REFRESH_WAIT_MS = 30_000 -// Serialize per branch to avoid index.lock races; coalesce only matching targets. +// Serialize per branch to avoid ref-lock races; coalesce only matching targets. const runPerLocalBaseBranch = createCoalescingKeyedRunner() +// One checkout fast-forward per repo; creates during one share a single follow-up to the latest remote ref. +const runPerRepoCheckoutFastForward = createCoalescingKeyedRunner() + export function parseRemoteTrackingLocalBaseRef( baseBranch: string, remoteTrackingRef: string, @@ -87,6 +97,37 @@ export async function refreshLocalBaseRefForWorktreeCreate( return toLocalBaseRefRefreshResult(parsed, outcome) } +/** Fast-forward a checked-out base in its own checkout once a create is done; nothing waits on it. */ +export function fastForwardCheckedOutLocalBaseAfterCreate( + repoPath: string, + baseBranch: string, + remoteTrackingRef: string, + options: AddWorktreeOptions +): void { + const parsed = parseRemoteTrackingLocalBaseRef( + baseBranch, + remoteTrackingRef, + options.remoteTrackingBase + ) + if (!parsed) { + return + } + const key = `${options.wslDistro ?? ''}\0${normalizeRuntimePathForComparison(repoPath)}` + // Admission-exempt (bounded by the per-repo runner) so a stalled checkout never holds a slot creates wait on; no deadline, since killing a merge mid-checkout strands a half-updated tree. + const git = localBaseBranchGit(options, { admissionExempt: true }) + void runPerRepoCheckoutFastForward(key, parsed.fullRef, () => + runWithGitReadCacheInvalidation(() => + fastForwardCheckedOutLocalBaseBranch(git, { + repoPath, + fullRef: parsed.fullRef, + remoteTrackingRef + }) + ) + ).catch((error: unknown) => { + console.warn('addWorktree: checked-out local base fast-forward failed unexpectedly', error) + }) +} + export async function getLocalBaseRefUpdateSuggestionForWorktreeCreate( repoPath: string, baseBranch: string, @@ -108,33 +149,148 @@ export async function getLocalBaseRefUpdateSuggestionForWorktreeCreate( : undefined } -function localBaseBranchGit(options: GitWorktreeExecOptions): LocalBaseBranchGit { +function localBaseBranchGit( + options: GitWorktreeExecOptions, + admission: Pick = {} +): LocalBaseBranchGit { // Shared refreshes cannot use any individual create's cancellation signal or timeout. - const execOptions = (cwd: string) => ({ + const execOptions = (cwd: string): GitExecOptions => ({ cwd, ...(options.wslDistro ? { wslDistro: options.wslDistro } : {}), - ...(options.admissionTier ? { admissionTier: options.admissionTier } : {}) + ...(options.admissionTier ? { admissionTier: options.admissionTier } : {}), + ...admission }) + // The runner may route a Windows drive repo into WSL; its Linux output paths need the same distro. + const routed = (cwd: string) => routeLocalGitOptions({ cwd, wslDistro: options.wslDistro }) + const listWorktrees = async (repoPath: string) => { + const { stdout } = await withRepositoryGitCause( + repoPath, + options, + { family: 'catalog', reason: 'creation-base-refresh', cache: 'uncached' }, + () => gitExecFileAsync(['worktree', 'list', '--porcelain'], execOptions(repoPath)) + ) + return parseWorktreeList(translateWslOutputPaths(stdout, repoPath, routed(repoPath))) + } + const commonDirOf = async (repoPath: string) => { + const { stdout } = await gitExecFileAsync( + ['rev-parse', '--git-common-dir'], + execOptions(repoPath) + ) + // Only strip the line ending: a path may end in spaces. + const commonDir = stdout.replace(/\r?\n$/, '') + return isAbsolute(commonDir) + ? translateWslOutputPath(commonDir, repoPath, routed(repoPath)) + : join(repoPath, commonDir) + } return { - exec: (args, cwd) => - gitExecFileAsync(args, { - ...execOptions(cwd), - ...(args[findGitSubcommandIndex(args)] === 'merge' - ? { admissionClass: 'checkout' as const } - : {}) - }), - listWorktrees: async (repoPath) => { - const { stdout } = await withRepositoryGitCause( - repoPath, - options, - { family: 'catalog', reason: 'creation-base-refresh', cache: 'uncached' }, - () => gitExecFileAsync(['worktree', 'list', '--porcelain'], execOptions(repoPath)) - ) - return parseWorktreeList(translateWslOutputPaths(stdout, repoPath, options)) + exec: (args, cwd) => gitExecFileAsync(args, execOptions(cwd)), + listWorktrees, + listReservedBranches: async (repoPath) => + (await readGitDirState(await commonDirOf(repoPath))).reserved, + updateRefUnlessInUse: async (repoPath, fullRef, args) => { + const commonDir = await commonDirOf(repoPath) + const worktrees = await listWorktrees(repoPath) + if (worktrees.some((wt) => wt.branch === fullRef)) { + return false + } + // A bare repo's own HEAD names a branch without checking it out. + const bareCommonDir = worktrees[0]?.isBare === true + let inUse = false + try { + await gitExecFileAsync(args, { + ...execOptions(repoPath), + beforeStart: async () => { + const { heads, reserved } = await readGitDirState(commonDir) + inUse = + reserved.has(fullRef) || + [...heads].some( + ([gitDir, head]) => + !(bareCommonDir && gitDir === commonDir) && + // Reftable keeps HEAD elsewhere and leaves this placeholder: fail closed. + (head === `ref: ${fullRef}` || head === 'ref: refs/heads/.invalid') + ) + return !inUse + } + }) + } catch (error) { + if (inUse) { + return false + } + throw error + } + return true } } } +type GitDirState = { + /** Each git dir's HEAD file, keyed by git dir. */ + heads: ReadonlyMap + /** Branches a rebase (head-name, --update-refs) or bisect reserves: Git's own in-use rule. */ + reserved: ReadonlySet +} + +// Reads files only: this runs inside an admitted command, where running Git could wait on its own slot. +async function readGitDirState(commonDir: string): Promise { + // Fail closed: an unreadable common dir must not look like "nothing in use". + if (!(await stat(commonDir)).isDirectory()) { + throw new Error(`${commonDir} is not a Git directory`) + } + const gitDirs = [commonDir] + try { + for (const entry of await readdir(join(commonDir, 'worktrees'), { withFileTypes: true })) { + if (entry.isDirectory()) { + gitDirs.push(join(commonDir, 'worktrees', entry.name)) + } + } + } catch (error) { + rethrowUnlessMissing(error) + } + const heads = new Map() + const reserved = new Set() + await Promise.all( + gitDirs.map(async (gitDir) => { + const [head, rebaseMerge, rebaseApply, updateRefs, bisectStart] = await Promise.all([ + readOptional(join(gitDir, 'HEAD')), + readOptional(join(gitDir, 'rebase-merge', 'head-name')), + readOptional(join(gitDir, 'rebase-apply', 'head-name')), + readOptional(join(gitDir, 'rebase-merge', 'update-refs')), + readOptional(join(gitDir, 'BISECT_START')) + ]) + heads.set(gitDir, head.trim()) + for (const line of [rebaseMerge, rebaseApply, updateRefs].flatMap((text) => + text.split('\n') + )) { + if (line.startsWith('refs/heads/')) { + reserved.add(line.trim()) + } + } + const bisected = bisectStart.trim() + if (bisected) { + reserved.add(bisected.startsWith('refs/') ? bisected : `refs/heads/${bisected}`) + } + }) + ) + return { heads, reserved } +} + +async function readOptional(path: string): Promise { + try { + return await readFile(path, 'utf8') + } catch (error) { + rethrowUnlessMissing(error) + return '' + } +} + +function rethrowUnlessMissing(error: unknown): void { + const code = + typeof error === 'object' && error !== null && 'code' in error ? error.code : undefined + if (code !== 'ENOENT' && code !== 'ENOTDIR') { + throw error + } +} + function waitAtMost(promise: Promise, timeoutMs: number): Promise { let timer: ReturnType | undefined return Promise.race([ diff --git a/src/main/git/worktrees/creation/worktree-preparation-finalization-work.ts b/src/main/git/worktrees/creation/worktree-preparation-finalization-work.ts index 3c8f8367fd1..ece331b5c4d 100644 --- a/src/main/git/worktrees/creation/worktree-preparation-finalization-work.ts +++ b/src/main/git/worktrees/creation/worktree-preparation-finalization-work.ts @@ -165,6 +165,7 @@ export async function performPreparedWorktreeFinalization( } // Advisory refresh may settle after finalization; it does not determine checkout contents. const localBaseRefRefresh = await baseContext.pendingLocalBaseRefRefresh + baseContext.updateCheckedOutLocalBase?.() return { preparedHeadReset, ...(localBaseRefRefresh ? { localBaseRefRefresh } : {}), diff --git a/src/main/git/worktrees/creation/worktree-sparse-add.ts b/src/main/git/worktrees/creation/worktree-sparse-add.ts index 9e166689c1b..af286bcff18 100644 --- a/src/main/git/worktrees/creation/worktree-sparse-add.ts +++ b/src/main/git/worktrees/creation/worktree-sparse-add.ts @@ -1,10 +1,11 @@ import { windowsLongPathGitArgs } from '../../../../shared/git/compatibility/windows-long-path-git-args' import { checkoutWorkersGitArgs } from './checkout-workers-git-args' import { gitExecFileAsync } from '../../command-runner/git-exec-file' -import { addWorktree, unsetWorktreeCreationBase } from './worktree-add' +import { addWorktreeDeferringLocalBaseUpdate } from './worktree-add' import type { AddWorktreeOptions, AddWorktreeResult, + GitWorktreeExecOptions, SparseWorktreeCreateError } from '../worktree-operation-options' import { gitExecOptions } from '../worktree-operation-options' @@ -22,7 +23,7 @@ export async function addSparseWorktree( let created = false let addResult: AddWorktreeResult = {} try { - addResult = await addWorktree( + const added = await addWorktreeDeferringLocalBaseUpdate( repoPath, worktreePath, branch, @@ -31,6 +32,7 @@ export async function addSparseWorktree( true, options ) + addResult = added.result created = true // --no-checkout wrote no files; these materialization steps need Windows long-path support. const longPathArgs = windowsLongPathGitArgs(worktreePath) @@ -46,6 +48,7 @@ export async function addSparseWorktree( ...gitExecOptions(worktreePath, options), admissionClass: 'checkout' }) + added.updateCheckedOutLocalBase?.() return addResult } catch (error) { const wrapped: SparseWorktreeCreateError = @@ -76,3 +79,15 @@ export async function addSparseWorktree( throw wrapped } } + +async function unsetWorktreeCreationBase( + worktreePath: string, + branch: string, + options: GitWorktreeExecOptions = {} +): Promise { + try { + await gitExecFileAsync(['config', '--local', '--unset-all', `branch.${branch}.base`], { + ...gitExecOptions(worktreePath, options) + }) + } catch {} +} diff --git a/src/shared/worktree/base-refs/local-base-branch-fast-forward-real-git.test.ts b/src/shared/worktree/base-refs/local-base-branch-fast-forward-real-git.test.ts index eeb1b9d7ff7..428a9d78f03 100644 --- a/src/shared/worktree/base-refs/local-base-branch-fast-forward-real-git.test.ts +++ b/src/shared/worktree/base-refs/local-base-branch-fast-forward-real-git.test.ts @@ -1,12 +1,12 @@ import { execFile, execFileSync } from 'node:child_process' -import { existsSync } from 'node:fs' -import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { pathToFileURL } from 'node:url' import { afterEach, describe, expect, it } from 'vitest' import { parseWorktreeList } from '../../git/worktrees/git-worktree-porcelain-parser' import { + fastForwardCheckedOutLocalBaseBranch, fastForwardLocalBaseBranch, type LocalBaseBranchGit } from './local-base-branch-fast-forward' @@ -64,8 +64,8 @@ async function createBehindRepo(): Promise { return { repoPath, env, localOid, remoteOid, git } } -/** Real git; `beforeMerge` runs just before the owner fast-forward, after the inspection passed. */ -function realGit(fixture: Fixture, beforeMerge?: () => Promise | void) { +/** Real git; `afterInspection` runs once the drift count returns. */ +function realGit(fixture: Fixture, afterInspection?: () => Promise | void) { const run = (args: string[], cwd: string) => new Promise<{ stdout: string }>((resolve, reject) => { execFile('git', args, { cwd, env: fixture.env, encoding: 'utf8' }, (error, stdout, stderr) => @@ -74,13 +74,22 @@ function realGit(fixture: Fixture, beforeMerge?: () => Promise | void) { }) const git: LocalBaseBranchGit = { exec: async (args, cwd) => { - if (args.includes('merge')) { - await beforeMerge?.() + const result = await run(args, cwd) + if (args[0] === 'rev-list') { + await afterInspection?.() } - return run(args, cwd) + return result }, listWorktrees: async (repoPath) => - parseWorktreeList((await run(['worktree', 'list', '--porcelain'], repoPath)).stdout) + parseWorktreeList((await run(['worktree', 'list', '--porcelain'], repoPath)).stdout), + listReservedBranches: async () => new Set(), + updateRefUnlessInUse: async (repoPath, fullRef, args) => { + if ((await git.listWorktrees(repoPath)).some((wt) => wt.branch === fullRef)) { + return false + } + await git.exec(args, repoPath) + return true + } } return { git } } @@ -98,73 +107,45 @@ afterEach(async () => { }) describe('fastForwardLocalBaseBranch against real Git', () => { - it('leaves an untracked file at a path the new commit adds, and does not move main', async () => { + it('leaves a checked-out main, its files and its index alone', async () => { const fixture = await createBehindRepo() await writeFile(join(fixture.repoPath, 'added.txt'), 'my notes\n') const outcome = await fastForward(fixture, realGit(fixture).git) - expect(outcome.status).toBe('skipped_dirty_worktree') + expect(outcome).toEqual({ status: 'nothing_to_do' }) + expect(fixture.git(['rev-parse', 'main'])).toBe(fixture.localOid) + expect(await readFile(join(fixture.repoPath, 'version.txt'), 'utf8')).toBe('one\n') expect(await readFile(join(fixture.repoPath, 'added.txt'), 'utf8')).toBe('my notes\n') - expect(fixture.git(['rev-parse', 'main'])).toBe(fixture.localOid) }) - it('leaves an ignored file at a path the new commit adds, and does not move main', async () => { + it('leaves main alone when it is checked out after the inspection', async () => { const fixture = await createBehindRepo() - await writeFile(join(fixture.repoPath, '.git', 'info', 'exclude'), 'added.txt\n') - await writeFile(join(fixture.repoPath, 'added.txt'), 'SECRET=mine\n') - - const outcome = await fastForward(fixture, realGit(fixture).git) - - expect(outcome.status).toBe('skipped_dirty_worktree') - expect(await readFile(join(fixture.repoPath, 'added.txt'), 'utf8')).toBe('SECRET=mine\n') - expect(fixture.git(['rev-parse', 'main'])).toBe(fixture.localOid) - }) - - it('moves main without running the post-merge hook of the checkout', async () => { - const fixture = await createBehindRepo() - const marker = join(fixture.repoPath, '..', 'hook-ran') - const hookPath = join(fixture.repoPath, '.git', 'hooks', 'post-merge') - await writeFile(hookPath, `#!/bin/sh\necho ran > "${marker.replace(/\\/g, '/')}"\n`) - await chmod(hookPath, 0o755) - - const outcome = await fastForward(fixture, realGit(fixture).git) - - expect(outcome).toMatchObject({ status: 'updated' }) - expect(fixture.git(['rev-parse', 'main'])).toBe(fixture.remoteOid) - expect(await readFile(join(fixture.repoPath, 'version.txt'), 'utf8')).toBe('two\n') - expect(existsSync(marker)).toBe(false) - }) - - it('keeps a tracked edit made after the inspection instead of overwriting it', async () => { - const fixture = await createBehindRepo() - const edited = join(fixture.repoPath, 'version.txt') - - const outcome = await fastForward( - fixture, - realGit(fixture, () => writeFile(edited, 'my edit\n')).git - ) - - expect(outcome.status).not.toBe('updated') - expect(outcome.status).toBe('skipped_dirty_worktree') - expect(await readFile(edited, 'utf8')).toBe('my edit\n') - expect(fixture.git(['rev-parse', 'main'])).toBe(fixture.localOid) - }) - - it('keeps a commit made on main after the inspection', async () => { - const fixture = await createBehindRepo() - let userCommit = '' - const commitOnMain = async () => { - await writeFile(join(fixture.repoPath, 'local.txt'), 'local work\n') - fixture.git(['add', 'local.txt']) - fixture.git(['commit', '--quiet', '-m', 'local work']) - userCommit = fixture.git(['rev-parse', 'HEAD']) + fixture.git(['checkout', '--quiet', '-b', 'develop']) + const checkOutMain = () => { + fixture.git(['checkout', '--quiet', 'main']) } - const outcome = await fastForward(fixture, realGit(fixture, commitOnMain).git) + const outcome = await fastForward(fixture, realGit(fixture, checkOutMain).git) - expect(outcome.status).not.toBe('updated') - expect(outcome.status).toBe('skipped_not_fast_forward') + expect(outcome).toEqual({ status: 'nothing_to_do' }) + expect(fixture.git(['rev-parse', 'main'])).toBe(fixture.localOid) + expect(fixture.git(['status', '--porcelain'])).toBe('') + }) + + it('keeps a move of main made after the inspection', async () => { + const fixture = await createBehindRepo() + fixture.git(['checkout', '--quiet', '-b', 'develop']) + let userCommit = '' + const moveMain = () => { + const tree = fixture.git(['rev-parse', `${fixture.localOid}^{tree}`]) + userCommit = fixture.git(['commit-tree', tree, '-p', fixture.localOid, '-m', 'local work']) + fixture.git(['update-ref', 'refs/heads/main', userCommit]) + } + + const outcome = await fastForward(fixture, realGit(fixture, moveMain).git) + + expect(outcome).toEqual({ status: 'skipped_not_fast_forward' }) expect(fixture.git(['rev-parse', 'main'])).toBe(userCommit) }) @@ -183,6 +164,7 @@ describe('fastForwardLocalBaseBranch against real Git', () => { it('flags a local branch hidden below a shallow boundary, and moves it once history is complete', async () => { const fixture = await createBehindRepo() + fixture.git(['checkout', '--quiet', '-b', 'develop']) const upstreamPath = join(fixture.repoPath, '..', 'upstream') fixture.git(['init', '--quiet', '--bare', upstreamPath]) fixture.git(['push', '--quiet', upstreamPath, `${fixture.remoteOid}:refs/heads/main`]) @@ -201,3 +183,31 @@ describe('fastForwardLocalBaseBranch against real Git', () => { expect(fixture.git(['rev-parse', 'main'])).toBe(fixture.remoteOid) }) }) + +describe('fastForwardCheckedOutLocalBaseBranch against real Git', () => { + const refs = (fixture: Fixture) => ({ + repoPath: fixture.repoPath, + fullRef: 'refs/heads/main', + remoteTrackingRef: 'refs/remotes/origin/main' + }) + + it('fast-forwards a clean checked-out main and its files', async () => { + const fixture = await createBehindRepo() + + await fastForwardCheckedOutLocalBaseBranch(realGit(fixture).git, refs(fixture)) + + expect(fixture.git(['rev-parse', 'main'])).toBe(fixture.remoteOid) + expect(await readFile(join(fixture.repoPath, 'added.txt'), 'utf8')).toBe('from upstream\n') + expect(fixture.git(['status', '--porcelain'])).toBe('') + }) + + it('leaves a checked-out main with uncommitted edits alone', async () => { + const fixture = await createBehindRepo() + await writeFile(join(fixture.repoPath, 'version.txt'), 'mine\n') + + await fastForwardCheckedOutLocalBaseBranch(realGit(fixture).git, refs(fixture)) + + expect(fixture.git(['rev-parse', 'main'])).toBe(fixture.localOid) + expect(await readFile(join(fixture.repoPath, 'version.txt'), 'utf8')).toBe('mine\n') + }) +}) diff --git a/src/shared/worktree/base-refs/local-base-branch-fast-forward.ts b/src/shared/worktree/base-refs/local-base-branch-fast-forward.ts index ea0ecd63014..cde16aa50ef 100644 --- a/src/shared/worktree/base-refs/local-base-branch-fast-forward.ts +++ b/src/shared/worktree/base-refs/local-base-branch-fast-forward.ts @@ -1,4 +1,4 @@ -import { readGitCommandFailureText } from '../../git/commands/git-command-failure-text' +import { windowsLongPathGitArgs } from '../../git/compatibility/windows-long-path-git-args' import { retryOnGitLockContention } from '../../git/commands/git-lock-contention' import { parseGitRevListAheadBehindCounts } from '../../git/refs/git-rev-list-output' import { isShowRefNoMatchError } from '../../git/refs/git-show-ref-no-match' @@ -9,6 +9,10 @@ export type LocalBaseBranchGit = { exec: (args: string[], cwd: string) => Promise<{ stdout: string }> /** Each worktree's path and checked-out branch as a full ref, as this host reports them. */ listWorktrees: (repoPath: string) => Promise + /** Full refs a rebase or bisect in any worktree has reserved; their worktrees list a detached HEAD. */ + listReservedBranches: (repoPath: string) => Promise> + /** Runs `update-ref args` unless the branch is in use, rechecked once admitted, just before Git starts; false when skipped. */ + updateRefUnlessInUse: (repoPath: string, fullRef: string, args: string[]) => Promise } export type LocalBaseBranchRefs = { @@ -22,18 +26,18 @@ export type LocalBaseBranchRefs = { type LocalBaseRefRefreshStatus = LocalBaseRefRefreshResult['status'] export type LocalBaseBranchInspection = - /** Nothing stale: local already matches, or does not exist yet (#15331). */ + /** Nothing Orca may move: local matches, does not exist yet (#15331), or its checkout or a rebase/bisect owns it. */ | { status: 'nothing_to_do' } | { status: 'behind' behind: number localOid: string remoteOid: string + /** Set when a worktree has the branch checked out; only that checkout may move it. */ ownerWorktreePath?: string } | { status: Exclude - ownerWorktreePath?: string shallowHistory?: true } @@ -67,32 +71,21 @@ function ownerFastForwardArgs(branch: string, targetOid: string): string[] { ] } -/** Read-only inspection of local drift and checkout readiness. */ +/** Read-only inspection of local drift. A checked-out branch is reported only when strictly behind, so its checkout stays silent otherwise; `skipCheckedOut` stops before walking its history. */ export async function inspectLocalBaseBranch( git: LocalBaseBranchGit, - refs: LocalBaseBranchRefs + refs: LocalBaseBranchRefs, + { skipCheckedOut = false }: { skipCheckedOut?: boolean } = {} ): Promise { const { repoPath, fullRef, remoteTrackingRef } = refs let localOid: string let remoteOid: string - let behind: number try { localOid = await revParseCommit(git, repoPath, fullRef) remoteOid = await revParseCommit(git, repoPath, remoteTrackingRef) if (localOid === remoteOid) { return { status: 'nothing_to_do' } } - const { stdout } = await git.exec( - ['rev-list', '--left-right', '--count', `${localOid}...${remoteOid}`], - repoPath - ) - const counts = parseGitRevListAheadBehindCounts(stdout) - if (counts.status !== 'ok' || counts.ahead !== 0 || counts.behind === 0) { - return (await isHistoryCutByShallowClone(git, repoPath, localOid, remoteOid)) - ? { status: 'skipped_not_fast_forward', shallowHistory: true } - : { status: 'skipped_not_fast_forward' } - } - behind = counts.behind } catch { // Only proven branch absence suppresses the warning; repo/transport failure cannot (#15331). return (await isRefProvenAbsent(git, repoPath, fullRef)) @@ -100,71 +93,113 @@ export async function inspectLocalBaseBranch( : { status: 'skipped_not_fast_forward' } } + let owner: { path: string } | undefined try { - const owner = (await git.listWorktrees(repoPath)).find((wt) => wt.branch === fullRef) - if (!owner) { - return { status: 'behind', behind, localOid, remoteOid } + // Git's in-use rule also counts a branch a rebase or bisect has reserved. + if ((await git.listReservedBranches(repoPath)).has(fullRef)) { + return { status: 'nothing_to_do' } } - if (await hasTrackedChanges(git, owner.path)) { - return { status: 'skipped_dirty_worktree', ownerWorktreePath: owner.path } - } - return { status: 'behind', behind, localOid, remoteOid, ownerWorktreePath: owner.path } + owner = (await git.listWorktrees(repoPath)).find((wt) => wt.branch === fullRef) } catch { return { status: 'skipped_error' } } + if (owner && skipCheckedOut) { + return { status: 'nothing_to_do' } + } + const ownerPath = owner ? { ownerWorktreePath: owner.path } : {} + + let counts: ReturnType + try { + const { stdout } = await git.exec( + ['rev-list', '--left-right', '--count', `${localOid}...${remoteOid}`], + repoPath + ) + counts = parseGitRevListAheadBehindCounts(stdout) + } catch { + return owner ? { status: 'nothing_to_do' } : { status: 'skipped_not_fast_forward' } + } + if (counts.status === 'ok' && counts.ahead === 0 && counts.behind > 0) { + return { status: 'behind', behind: counts.behind, localOid, remoteOid, ...ownerPath } + } + if (owner) { + return { status: 'nothing_to_do' } + } + return (await isHistoryCutByShallowClone(git, repoPath, localOid, remoteOid)) + ? { status: 'skipped_not_fast_forward', shallowHistory: true } + : { status: 'skipped_not_fast_forward' } } -/** Fast-forward with Git’s index-lock protections in an owner checkout, or compare-and-swap update-ref for a free branch. Refuse overwritten edits/untracked files or dropped commits; never reject. */ +/** Fast-forward a branch no worktree has checked out with a compare-and-swap update-ref, never touching a working tree or index. Never rejects. */ export async function fastForwardLocalBaseBranch( git: LocalBaseBranchGit, refs: LocalBaseBranchRefs ): Promise { - const inspection = await inspectLocalBaseBranch(git, refs) + // A checked-out branch is left to fastForwardCheckedOutLocalBaseBranch, after the create. + const inspection = await inspectLocalBaseBranch(git, refs, { skipCheckedOut: true }) if (inspection.status !== 'behind') { return inspection } const { repoPath, fullRef, remoteTrackingRef } = refs - const { localOid, remoteOid, ownerWorktreePath } = inspection - const owner = ownerWorktreePath ? { ownerWorktreePath } : {} - const branch = fullRef.slice('refs/heads/'.length) - if (ownerWorktreePath && branch.includes('=')) { - // Why: `-c branch..mergeOptions=` splits at the first `=`, so such a name cannot be pinned. - return { status: 'skipped_error', ...owner } + const { localOid, remoteOid } = inspection + try { + // A checkout made after the last check would be stranded, so the check runs right before the write. + const moved = await retryOnGitLockContention(() => + git.updateRefUnlessInUse(repoPath, fullRef, [ + 'update-ref', + '-m', + `orca: fast-forward to ${remoteTrackingRef}`, + fullRef, + remoteOid, + localOid + ]) + ) + return moved ? { status: 'updated' } : { status: 'nothing_to_do' } + } catch { + // A concurrent pull/Orca update may already have moved local; a user commit leaves it diverged. + try { + if (await isAncestor(git, repoPath, remoteOid, fullRef)) { + return { status: 'updated' } + } + if (!(await isAncestor(git, repoPath, fullRef, remoteOid))) { + return { status: 'skipped_not_fast_forward' } + } + } catch { + // Git could not answer; report the failure itself. + } + return { status: 'skipped_error' } + } +} + +/** Fast-forward a checked-out branch in its own checkout when it has no tracked changes; Git refuses a held index.lock, overwritten untracked files and dropped commits. Silent; never rejects. */ +export async function fastForwardCheckedOutLocalBaseBranch( + git: LocalBaseBranchGit, + refs: LocalBaseBranchRefs +): Promise { + const inspection = await inspectLocalBaseBranch(git, refs) + if (inspection.status !== 'behind' || !inspection.ownerWorktreePath) { + return + } + const { ownerWorktreePath, remoteOid } = inspection + const branch = refs.fullRef.slice('refs/heads/'.length) + // Why: `-c branch..mergeOptions=` splits at the first `=`, so such a name cannot be pinned. + if (branch.includes('=')) { + return } try { - await retryOnGitLockContention(async () => { - if (!ownerWorktreePath) { - await git.exec( - [ - 'update-ref', - '-m', - `orca: fast-forward to ${remoteTrackingRef}`, - fullRef, - remoteOid, - localOid - ], - repoPath - ) - return - } - // Recheck the owner’s branch before merging HEAD; this narrows the switch race, and post-move verification warns if it occurred. - const { stdout: head } = await git.exec(['symbolic-ref', '-q', 'HEAD'], ownerWorktreePath) - if (head.trim() !== fullRef) { - throw new Error(`${fullRef} is no longer checked out at ${ownerWorktreePath}`) - } - await git.exec(ownerFastForwardArgs(branch, remoteOid), ownerWorktreePath) - }) - // Report updated only if local equals the target, regardless of merge settings. - if (ownerWorktreePath && (await revParseCommit(git, repoPath, fullRef)) !== remoteOid) { - return { status: 'skipped_error', ...owner } + if (await hasTrackedChanges(git, ownerWorktreePath)) { + return } - return { status: 'updated', ...owner } - } catch (error) { - // A concurrent pull/Orca update may already have moved local. - if (await localContains(git, repoPath, fullRef, remoteOid)) { - return { status: 'updated', ...owner } + // Recheck right before merging HEAD: the checkout may have switched branches since the listing. + const { stdout: head } = await git.exec(['symbolic-ref', '-q', 'HEAD'], ownerWorktreePath) + if (head.trim() !== refs.fullRef) { + return } - return { status: classifyFastForwardFailure(error), ...owner } + await git.exec( + [...windowsLongPathGitArgs(ownerWorktreePath), ...ownerFastForwardArgs(branch, remoteOid)], + ownerWorktreePath + ) + } catch { + // A skipped update stays silent; the next create tries again. } } @@ -184,15 +219,13 @@ export function toLocalBaseRefRefreshResult( } } -function classifyFastForwardFailure(error: unknown): Exclude { - const text = readGitCommandFailureText(error) - if (/would be overwritten by merge|would lose untracked files/i.test(text)) { - return 'skipped_dirty_worktree' - } - if (/Not possible to fast-forward/i.test(text)) { - return 'skipped_not_fast_forward' - } - return 'skipped_error' +async function hasTrackedChanges(git: LocalBaseBranchGit, worktreePath: string): Promise { + // Read without index.lock so inspection cannot fail the user's concurrent Git command. + const { stdout } = await git.exec( + ['--no-optional-locks', 'status', '--porcelain', '--untracked-files=no'], + worktreePath + ) + return stdout.trim().length > 0 } async function revParseCommit( @@ -208,15 +241,6 @@ async function revParseCommit( return oid } -async function hasTrackedChanges(git: LocalBaseBranchGit, worktreePath: string): Promise { - // Read without index.lock so inspection cannot fail the user’s concurrent Git command. - const { stdout } = await git.exec( - ['--no-optional-locks', 'status', '--porcelain', '--untracked-files=no'], - worktreePath - ) - return stdout.trim().length > 0 -} - // Shallow boundaries make older commits look ahead; require a missing merge base to distinguish that from divergence. async function isHistoryCutByShallowClone( git: LocalBaseBranchGit, @@ -254,55 +278,20 @@ async function isRefProvenAbsent( } } -async function localContains( +async function isAncestor( git: LocalBaseBranchGit, repoPath: string, - fullRef: string, - oid: string + ancestor: string, + descendant: string ): Promise { try { - await git.exec(['merge-base', '--is-ancestor', oid, fullRef], repoPath) + await git.exec(['merge-base', '--is-ancestor', ancestor, descendant], repoPath) return true - } catch { - return false + } catch (error) { + // Only Git's silent exit 1 means "not an ancestor"; anything else is a failure to answer. + if (isShowRefNoMatchError(error)) { + return false + } + throw error } } - -const REFRESH_STATUSES: readonly LocalBaseRefRefreshStatus[] = [ - 'updated', - 'skipped_dirty_worktree', - 'skipped_not_fast_forward', - 'skipped_error' -] - -/** Reject unrecognized relay replies as errors rather than implying success. */ -export function parseLocalBaseBranchFastForwardOutcome( - value: unknown -): LocalBaseBranchFastForwardOutcome { - if (typeof value !== 'object' || value === null || !('status' in value)) { - return { status: 'skipped_error' } - } - if (value.status === 'nothing_to_do') { - return { status: 'nothing_to_do' } - } - const status = REFRESH_STATUSES.find((candidate) => candidate === value.status) - if (!status) { - return { status: 'skipped_error' } - } - const ownerWorktreePath = 'ownerWorktreePath' in value ? value.ownerWorktreePath : undefined - const shallowHistory = 'shallowHistory' in value && value.shallowHistory === true - return { - status, - ...(typeof ownerWorktreePath === 'string' && ownerWorktreePath ? { ownerWorktreePath } : {}), - ...(shallowHistory ? { shallowHistory: true } : {}) - } -} - -/** How many commits a relay's inspection says local is behind, when it may be fast-forwarded. */ -export function readFastForwardableBehindCount(value: unknown): number | undefined { - if (typeof value !== 'object' || value === null || !('status' in value) || !('behind' in value)) { - return undefined - } - const { behind } = value - return value.status === 'behind' && typeof behind === 'number' && behind > 0 ? behind : undefined -}