fix(worktree): restore sparse checkout without per-poll git subprocesses (#1316)

Co-authored-by: Orca <help@stably.ai>
Co-authored-by: Colin <colin.chambachan@gmail.com>
This commit is contained in:
Jinwoo Hong
2026-05-01 13:25:22 -07:00
committed by GitHub
co-authored by Orca Colin
parent d4bbf473c1
commit bbd77c2449
35 changed files with 2543 additions and 76 deletions
+224 -17
View File
@@ -1,17 +1,38 @@
/* eslint-disable max-lines -- Why: remove/list/sparse cleanup tests share one git runner
mock harness, and splitting them would duplicate setup without a clearer boundary. */
import type * as FsPromises from 'fs/promises'
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { gitExecFileAsyncMock, gitExecFileSyncMock } = vi.hoisted(() => ({
const {
gitExecFileAsyncMock,
gitExecFileSyncMock,
translateWslOutputPathsMock,
statMock,
resolveGitDirMock
} = vi.hoisted(() => ({
gitExecFileAsyncMock: vi.fn(),
gitExecFileSyncMock: vi.fn()
gitExecFileSyncMock: vi.fn(),
translateWslOutputPathsMock: vi.fn((output: string) => output),
statMock: vi.fn(),
resolveGitDirMock: vi.fn()
}))
vi.mock('./runner', () => ({
gitExecFileAsync: gitExecFileAsyncMock,
gitExecFileSync: gitExecFileSyncMock,
translateWslOutputPaths: (output: string) => output
translateWslOutputPaths: translateWslOutputPathsMock
}))
import { removeWorktree } from './worktree'
vi.mock('./status', () => ({
resolveGitDir: resolveGitDirMock
}))
vi.mock('fs/promises', async () => {
const actual = await vi.importActual<typeof FsPromises>('fs/promises')
return { ...actual, stat: statMock }
})
import { addSparseWorktree, listWorktrees, removeWorktree } from './worktree'
type MockResult = {
error?: Error
@@ -54,11 +75,19 @@ describe('removeWorktree', () => {
beforeEach(() => {
gitExecFileAsyncMock.mockReset()
gitExecFileSyncMock.mockReset()
translateWslOutputPathsMock.mockReset()
translateWslOutputPathsMock.mockImplementation((output: string) => output)
statMock.mockReset()
// Default: no worktree has a sparse-checkout config file. Tests that need
// sparse detection override this.
statMock.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
resolveGitDirMock.mockReset()
resolveGitDirMock.mockImplementation(async (worktreePath: string) => `${worktreePath}/.git`)
})
it('removes the worktree, prunes stale refs, and deletes its local branch', async () => {
mockGitCommands({
'git worktree list --porcelain': {
'git worktree list --porcelain -z': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
@@ -68,7 +97,7 @@ HEAD def456
branch refs/heads/feature/test
`
},
'git worktree list --porcelain#2': {
'git worktree list --porcelain -z#2': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
@@ -92,7 +121,7 @@ branch refs/heads/main
it('skips branch deletion when another worktree still points at the branch', async () => {
mockGitCommands({
'git worktree list --porcelain': {
'git worktree list --porcelain -z': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
@@ -106,7 +135,7 @@ HEAD def456
branch refs/heads/feature/test
`
},
'git worktree list --porcelain#2': {
'git worktree list --porcelain -z#2': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
@@ -125,7 +154,7 @@ branch refs/heads/feature/test
expect.arrayContaining([
'git worktree remove /repo-feature',
'git worktree prune',
'git worktree list --porcelain'
'git worktree list --porcelain -z'
])
)
expect(calls).not.toContain('git branch -D feature/test')
@@ -134,7 +163,7 @@ branch refs/heads/feature/test
it('deletes the branch after prune removes stale sibling worktree entries', async () => {
mockGitCommands({
'git worktree list --porcelain': {
'git worktree list --porcelain -z': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
@@ -149,7 +178,7 @@ branch refs/heads/feature/test
prunable gitdir file points to non-existent location
`
},
'git worktree list --porcelain#2': {
'git worktree list --porcelain -z#2': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
@@ -172,7 +201,7 @@ branch refs/heads/main
it('passes --force before the worktree path when forced removal is requested', async () => {
mockGitCommands({
'git worktree list --porcelain': {
'git worktree list --porcelain -z': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
@@ -182,7 +211,7 @@ HEAD def456
branch refs/heads/feature/test
`
},
'git worktree list --porcelain#2': {
'git worktree list --porcelain -z#2': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
@@ -197,7 +226,7 @@ branch refs/heads/main
it('matches Windows worktree paths before deleting the branch', async () => {
mockGitCommands({
'git worktree list --porcelain': {
'git worktree list --porcelain -z': {
stdout: `worktree C:/repo
HEAD abc123
branch refs/heads/main
@@ -207,7 +236,7 @@ HEAD def456
branch refs/heads/feature/test
`
},
'git worktree list --porcelain#2': {
'git worktree list --porcelain -z#2': {
stdout: `worktree C:/repo
HEAD abc123
branch refs/heads/main
@@ -230,7 +259,7 @@ branch refs/heads/main
it('keeps removal successful when branch cleanup fails', async () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
mockGitCommands({
'git worktree list --porcelain': {
'git worktree list --porcelain -z': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
@@ -240,7 +269,7 @@ HEAD def456
branch refs/heads/feature/test
`
},
'git worktree list --porcelain#2': {
'git worktree list --porcelain -z#2': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
@@ -262,3 +291,181 @@ branch refs/heads/main
warnSpy.mockRestore()
})
})
describe('listWorktrees', () => {
beforeEach(() => {
gitExecFileAsyncMock.mockReset()
gitExecFileSyncMock.mockReset()
translateWslOutputPathsMock.mockReset()
translateWslOutputPathsMock.mockImplementation((output: string) => output)
statMock.mockReset()
// Default: no worktree has a sparse-checkout config file. Tests that need
// sparse detection override this.
statMock.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
resolveGitDirMock.mockReset()
resolveGitDirMock.mockImplementation(async (worktreePath: string) => `${worktreePath}/.git`)
})
it('translates parsed path fields from NUL-delimited porcelain output', async () => {
gitExecFileAsyncMock.mockResolvedValueOnce({
stdout:
'worktree /home/me/repo\0HEAD abc123\0branch refs/heads/main\0\0' +
'worktree /home/me/repo-feature\0HEAD def456\0branch refs/heads/feature/test\0sparse\0\0'
})
translateWslOutputPathsMock.mockImplementation((output: string) => {
expect(output).not.toContain('\0')
return output.replace('/home/me/', '\\\\wsl.localhost\\Ubuntu\\home\\me\\')
})
await expect(listWorktrees('\\\\wsl.localhost\\Ubuntu\\home\\me\\repo')).resolves.toEqual([
{
path: '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo',
head: 'abc123',
branch: 'refs/heads/main',
isBare: false,
isMainWorktree: true
},
{
path: '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo-feature',
head: 'def456',
branch: 'refs/heads/feature/test',
isBare: false,
isSparse: true,
isMainWorktree: false
}
])
// Why: the non-sparse main worktree gets an fs probe of its sparse config
// file; the linked worktree short-circuits on the parsed `sparse` token and
// does not. Only one git subprocess runs regardless of worktree count.
expect(getGitCalls()).toEqual(['git worktree list --porcelain -z'])
expect(statMock).toHaveBeenCalledTimes(1)
expect(translateWslOutputPathsMock).toHaveBeenCalledTimes(2)
})
it('detects sparse checkout after translating paths when porcelain omits sparse token', async () => {
gitExecFileAsyncMock.mockImplementation((args: string[]) => {
if (args.join(' ') === 'worktree list --porcelain -z') {
return {
stdout:
'worktree /home/me/repo\0HEAD abc123\0branch refs/heads/main\0\0' +
'worktree /home/me/repo-feature\0HEAD def456\0branch refs/heads/feature/test\0\0',
stderr: ''
}
}
throw new Error(`Unexpected git call: ${args.join(' ')}`)
})
translateWslOutputPathsMock.mockImplementation((output: string) => {
expect(output).not.toContain('\0')
return output.replace('/home/me/', '\\\\wsl.localhost\\Ubuntu\\home\\me\\')
})
const featureWorktreePath = '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo-feature'
resolveGitDirMock.mockImplementation(async (worktreePath: string) =>
worktreePath === featureWorktreePath
? `${featureWorktreePath}\\.git-worktrees\\feature`
: `${worktreePath}/.git`
)
statMock.mockImplementation(async (filePath: string) => {
if (filePath.includes('repo-feature') && filePath.includes('sparse-checkout')) {
return { isFile: () => true, size: 32 }
}
throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' })
})
const worktrees = await listWorktrees('\\\\wsl.localhost\\Ubuntu\\home\\me\\repo')
expect(worktrees).toEqual([
{
path: '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo',
head: 'abc123',
branch: 'refs/heads/main',
isBare: false,
isMainWorktree: true
},
{
path: '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo-feature',
head: 'def456',
branch: 'refs/heads/feature/test',
isBare: false,
isSparse: true,
isMainWorktree: false
}
])
expect(resolveGitDirMock).toHaveBeenCalledWith(featureWorktreePath)
// Why: the detection path must not spawn a git subprocess per worktree —
// the perf regression in #1131 came from `git sparse-checkout list` firing
// on every poll.
expect(getGitCalls()).toEqual(['git worktree list --porcelain -z'])
})
})
describe('addSparseWorktree', () => {
beforeEach(() => {
gitExecFileAsyncMock.mockReset()
gitExecFileSyncMock.mockReset()
translateWslOutputPathsMock.mockReset()
translateWslOutputPathsMock.mockImplementation((output: string) => output)
statMock.mockReset()
// Default: no worktree has a sparse-checkout config file. Tests that need
// sparse detection override this.
statMock.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
resolveGitDirMock.mockReset()
resolveGitDirMock.mockImplementation(async (worktreePath: string) => `${worktreePath}/.git`)
})
it('separates sparse checkout directory operands from options', async () => {
gitExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' })
await addSparseWorktree('/repo', '/repo-feature', 'feature/test', ['-docs', 'src'])
expect(gitExecFileAsyncMock).toHaveBeenCalledWith(
['sparse-checkout', 'set', '--', '-docs', 'src'],
{ cwd: '/repo-feature' }
)
})
it('removes the worktree and deletes the created branch when sparse setup fails', async () => {
mockGitCommands({
'git sparse-checkout set -- packages/web': {
error: new Error('sparse setup failed')
},
'git worktree list --porcelain -z': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
worktree /repo-feature
HEAD def456
branch refs/heads/feature/test
`
},
'git worktree list --porcelain -z#2': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
`
}
})
await expect(
addSparseWorktree('/repo', '/repo-feature', 'feature/test', ['packages/web'])
).rejects.toThrow('sparse setup failed')
const calls = getGitCalls()
expect(calls).toEqual(
expect.arrayContaining([
'git worktree add --no-checkout -b feature/test /repo-feature',
'git sparse-checkout init --cone',
'git sparse-checkout set -- packages/web',
'git worktree remove --force /repo-feature',
'git worktree prune',
'git branch -D feature/test'
])
)
expectGitCallOrder(
calls,
'git sparse-checkout set -- packages/web',
'git worktree remove --force /repo-feature'
)
expectGitCallOrder(calls, 'git worktree prune', 'git branch -D feature/test')
})
})