fix: preserve unmerged branch when removing a worktree (#2927) (#2939)

fix: preserve unmerged branch when removing a worktree (#2927)
This commit is contained in:
Trevin Chow
2026-05-28 20:19:53 -04:00
committed by GitHub
parent 9d82dbabe3
commit 10f97509ea
9 changed files with 164 additions and 21 deletions
+9 -7
View File
@@ -117,11 +117,11 @@ branch refs/heads/main
expect.arrayContaining([
'git worktree remove /repo-feature',
'git worktree prune',
'git branch -D feature/test'
'git branch -d feature/test'
])
)
expectGitCallOrder(calls, 'git worktree remove /repo-feature', 'git worktree prune')
expectGitCallOrder(calls, 'git worktree prune', 'git branch -D feature/test')
expectGitCallOrder(calls, 'git worktree prune', 'git branch -d feature/test')
})
it('preserves the branch when requested for a pre-existing local branch checkout', async () => {
@@ -144,6 +144,7 @@ branch refs/heads/feature/test
expect(calls).toEqual(
expect.arrayContaining(['git worktree remove /repo-feature', 'git worktree prune'])
)
expect(calls).not.toContain('git branch -d feature/test')
expect(calls).not.toContain('git branch -D feature/test')
})
@@ -185,6 +186,7 @@ branch refs/heads/feature/test
'git worktree list --porcelain'
])
)
expect(calls).not.toContain('git branch -d feature/test')
expect(calls).not.toContain('git branch -D feature/test')
expectGitCallOrder(calls, 'git worktree remove /repo-feature', 'git worktree prune')
})
@@ -221,10 +223,10 @@ branch refs/heads/main
expect.arrayContaining([
'git worktree remove /repo-feature',
'git worktree prune',
'git branch -D feature/test'
'git branch -d feature/test'
])
)
expectGitCallOrder(calls, 'git worktree prune', 'git branch -D feature/test')
expectGitCallOrder(calls, 'git worktree prune', 'git branch -d feature/test')
})
it('passes --force before the worktree path when forced removal is requested', async () => {
@@ -279,7 +281,7 @@ branch refs/heads/main
expect.arrayContaining([
'git worktree remove c:\\workspaces\\delete-branch-ui-test',
'git worktree prune',
'git branch -D feature/test'
'git branch -d feature/test'
])
)
})
@@ -303,7 +305,7 @@ HEAD abc123
branch refs/heads/main
`
},
'git branch -D feature/test': {
'git branch -d feature/test': {
error: new Error('branch delete failed'),
stderr: 'branch delete failed'
}
@@ -312,7 +314,7 @@ branch refs/heads/main
await expect(removeWorktree('/repo', '/repo-feature')).resolves.toBeUndefined()
expect(warnSpy).toHaveBeenCalledWith(
'[git] Failed to delete local branch "feature/test" after removing worktree',
'[git] Preserved local branch "feature/test" after removing worktree (not fully merged)',
expect.any(Error)
)
+48 -2
View File
@@ -18,7 +18,7 @@ vi.mock('./runner', () => ({
translateWslOutputPaths: translateWslOutputPathsMock
}))
import { addSparseWorktree, addWorktree, parseWorktreeList } from './worktree'
import { addSparseWorktree, addWorktree, parseWorktreeList, removeWorktree } from './worktree'
describe('parseWorktreeList', () => {
it('parses regular and bare worktree blocks from porcelain output', () => {
@@ -829,7 +829,7 @@ describe('addWorktree', () => {
gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: '' }) // worktree remove
gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: '' }) // worktree prune
gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: afterPrune }) // worktree list after prune
gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: '' }) // branch -D
gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: '' }) // branch -D (rollback force-deletes the fresh branch)
await expect(
addSparseWorktree('/repo', '/repo-feature', 'feature/test', ['src'], 'origin/main')
@@ -841,6 +841,8 @@ describe('addWorktree', () => {
'--unset-all',
'branch.feature/test.base'
])
// Why: rolling back a failed creation force-deletes the just-created branch
// (`-D`) — it has no user commits to protect, unlike a user-initiated delete.
expect(gitExecFileAsyncMock.mock.calls.map((call) => call[0])).toContainEqual([
'branch',
'-D',
@@ -848,3 +850,47 @@ describe('addWorktree', () => {
])
})
})
describe('removeWorktree', () => {
const beforeRemoval =
'worktree /repo\nHEAD abc123\nbranch refs/heads/main\n\nworktree /repo-feature\nHEAD def456\nbranch refs/heads/feature/test\n'
const afterPrune = 'worktree /repo\nHEAD abc123\nbranch refs/heads/main\n'
beforeEach(() => {
gitExecFileAsyncMock.mockReset()
gitExecFileSyncMock.mockReset()
translateWslOutputPathsMock.mockClear()
})
it('uses safe `branch -d` and preserves a branch with unmerged commits', async () => {
gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: beforeRemoval }) // list before
gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: '' }) // worktree remove
gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: '' }) // worktree prune
gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: afterPrune }) // list after prune
// Git refuses to delete an unmerged branch with `-d`.
gitExecFileAsyncMock.mockRejectedValueOnce(new Error('not fully merged')) // branch -d
// Should not throw — the unmerged branch is preserved, not force-deleted.
await expect(removeWorktree('/repo', '/repo-feature', false)).resolves.toBeUndefined()
const calls = gitExecFileAsyncMock.mock.calls.map((call) => call[0])
expect(calls).toContainEqual(['branch', '-d', 'feature/test'])
expect(calls).not.toContainEqual(['branch', '-D', 'feature/test'])
})
it('deletes the branch when `branch -d` succeeds (fully merged)', async () => {
gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: beforeRemoval }) // list before
gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: '' }) // worktree remove
gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: '' }) // worktree prune
gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: afterPrune }) // list after prune
gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: '' }) // branch -d succeeds
await removeWorktree('/repo', '/repo-feature', false)
expect(gitExecFileAsyncMock.mock.calls.map((call) => call[0])).toContainEqual([
'branch',
'-d',
'feature/test'
])
})
})
+18 -4
View File
@@ -432,7 +432,10 @@ export async function addSparseWorktree(
}
try {
await removeWorktree(repoPath, worktreePath, true, {
deleteBranch: !options.checkoutExistingBranch
deleteBranch: !options.checkoutExistingBranch,
// Why: rolling back a failed creation — the just-created branch has no
// user commits, so force-delete it rather than preserving an orphan.
forceBranchDelete: !options.checkoutExistingBranch
})
} catch {
wrapped.cleanupFailed = true
@@ -452,7 +455,11 @@ export async function removeWorktree(
repoPath: string,
worktreePath: string,
force = false,
options: { deleteBranch?: boolean } = {}
// Why: forceBranchDelete is for cleaning up a worktree this code just created
// (e.g. rollback of a failed creation) where the fresh branch has no user work
// and must be removed outright. User-initiated deletes leave it false so unmerged
// commits are preserved.
options: { deleteBranch?: boolean; forceBranchDelete?: boolean } = {}
): Promise<void> {
const worktreesBeforeRemoval = await listWorktrees(repoPath)
const removedWorktree = worktreesBeforeRemoval.find((worktree) =>
@@ -490,10 +497,17 @@ export async function removeWorktree(
// Why: `git worktree remove` only detaches the filesystem entry. Orca also
// drops the now-unused local branch here so delete-worktree does not leave
// behind orphaned feature branches unless another worktree still points at it.
await gitExecFileAsync(['branch', '-D', branchName], { cwd: repoPath })
// Use `-d` (not `-D`): Git refuses to delete a branch with commits not merged
// into its upstream or HEAD, so unpublished work is preserved instead of
// force-deleted. forceBranchDelete opts into `-D` for failed-creation rollback,
// where the fresh branch has no user work to protect.
const deleteFlag = options.forceBranchDelete ? '-D' : '-d'
await gitExecFileAsync(['branch', deleteFlag, branchName], { cwd: repoPath })
} catch (error) {
// Expected when the branch still has unmerged/unpublished commits: keep it.
// Deleting a worktree must never silently discard commits.
console.warn(
`[git] Failed to delete local branch "${branchName}" after removing worktree`,
`[git] Preserved local branch "${branchName}" after removing worktree (not fully merged)`,
error
)
}
+8 -1
View File
@@ -922,7 +922,14 @@ export async function createRemoteWorktree(
if (!checkoutExistingBranch) {
await unsetRemoteWorktreeCreationBase(provider, remotePath, branchName)
}
await provider.removeWorktree(remotePath, true).catch(() => undefined)
await provider
.removeWorktree(remotePath, true, {
deleteBranch: !checkoutExistingBranch,
// Why: sparse setup failed before the user could work in the new
// branch, so rollback should remove the just-created remote branch.
forceBranchDelete: !checkoutExistingBranch
})
.catch(() => undefined)
throw err
}
}
+4 -1
View File
@@ -1470,7 +1470,10 @@ describe('registerWorktreeHandlers', () => {
['config', '--local', '--unset-all', 'branch.sparse-dashboard.base'],
'/remote/repo/../sparse-dashboard'
)
expect(provider.removeWorktree).toHaveBeenCalledWith('/remote/repo/../sparse-dashboard', true)
expect(provider.removeWorktree).toHaveBeenCalledWith('/remote/repo/../sparse-dashboard', true, {
deleteBranch: true,
forceBranchDelete: true
})
})
it('does not create an SSH worktree when remote-tracking base refresh fails', async () => {
+1 -1
View File
@@ -405,7 +405,7 @@ export class SshGitProvider implements IGitProvider {
async removeWorktree(
worktreePath: string,
force?: boolean,
options?: { deleteBranch?: boolean }
options?: { deleteBranch?: boolean; forceBranchDelete?: boolean }
): Promise<void> {
await this.mux.request('git.removeWorktree', { worktreePath, force, ...options })
}
+1 -1
View File
@@ -206,7 +206,7 @@ export type IGitProvider = {
removeWorktree(
worktreePath: string,
force?: boolean,
options?: { deleteBranch?: boolean }
options?: { deleteBranch?: boolean; forceBranchDelete?: boolean }
): Promise<void>
renameCurrentBranch?(worktreePath: string, newBranch: string): Promise<void>
isGitRepo(path: string): boolean
+67 -2
View File
@@ -155,11 +155,75 @@ describe('removeWorktreeOp', () => {
'/repo$ worktree remove /repo-feature',
'/repo$ worktree prune',
'/repo$ worktree list --porcelain',
'/repo$ branch -D feature/test'
'/repo$ branch -d feature/test'
])
})
it('preserves the branch when removing an SSH worktree for an existing local branch', async () => {
it('preserves the branch (does not throw) when `branch -d` refuses an unmerged branch', async () => {
let listCount = 0
const git = vi.fn<GitExec>(async (args) => {
if (args[0] === 'rev-parse') {
return { stdout: '/repo/.git\n', stderr: '' }
}
if (args[0] === 'worktree' && args[1] === 'list') {
listCount += 1
return {
stdout:
listCount === 1
? worktreeList(
{ path: '/repo', branch: 'main' },
{ path: '/repo-feature', branch: 'feature/test' }
)
: worktreeList({ path: '/repo', branch: 'main' }),
stderr: ''
}
}
if (args[0] === 'branch' && args[1] === '-d') {
throw new Error('error: the branch feature/test is not fully merged')
}
return { stdout: '', stderr: '' }
})
// The unmerged-branch refusal must be swallowed, not propagated.
await expect(removeWorktreeOp(git, { worktreePath: '/repo-feature' })).resolves.toBeUndefined()
expect(git).toHaveBeenCalledWith(['branch', '-d', 'feature/test'], expect.any(String))
expect(git).not.toHaveBeenCalledWith(['branch', '-D', 'feature/test'], expect.any(String))
})
it('force-deletes the just-created branch during failed sparse setup rollback', async () => {
let listCount = 0
const git = vi.fn<GitExec>(async (args) => {
if (args[0] === 'rev-parse') {
return { stdout: '/repo/.git\n', stderr: '' }
}
if (args[0] === 'worktree' && args[1] === 'list') {
listCount += 1
return {
stdout:
listCount === 1
? worktreeList(
{ path: '/repo', branch: 'main' },
{ path: '/repo-feature', branch: 'feature/test' }
)
: worktreeList({ path: '/repo', branch: 'main' }),
stderr: ''
}
}
return { stdout: '', stderr: '' }
})
await removeWorktreeOp(git, {
worktreePath: '/repo-feature',
force: true,
forceBranchDelete: true
})
expect(git).toHaveBeenCalledWith(['branch', '-D', 'feature/test'], expect.any(String))
expect(git).not.toHaveBeenCalledWith(['branch', '-d', 'feature/test'], expect.any(String))
})
it('skips branch deletion entirely when deleteBranch is false', async () => {
const calls: string[] = []
const git = vi.fn<GitExec>(async (args, cwd) => {
calls.push(`${cwd}$ ${args.join(' ')}`)
@@ -215,6 +279,7 @@ describe('removeWorktreeOp', () => {
await removeWorktreeOp(git, { worktreePath: '/repo-feature' })
expect(git).not.toHaveBeenCalledWith(['branch', '-d', 'feature/test'], expect.any(String))
expect(git).not.toHaveBeenCalledWith(['branch', '-D', 'feature/test'], expect.any(String))
})
})
+8 -2
View File
@@ -125,6 +125,7 @@ export async function removeWorktreeOp(
const worktreePath = params.worktreePath as string
const force = params.force as boolean | undefined
const deleteBranch = params.deleteBranch !== false
const forceBranchDelete = params.forceBranchDelete === true
let repoPath = worktreePath
try {
@@ -170,10 +171,15 @@ export async function removeWorktreeOp(
}
try {
await git(['branch', '-D', branchName], repoPath)
// Why: use `-d` (not `-D`) to mirror the local removeWorktree fix — Git
// refuses to delete a branch with commits not merged into its upstream or
// HEAD, so unpublished work on a remote worktree is preserved rather than
// force-deleted. forceBranchDelete is reserved for failed create rollback.
await git(['branch', forceBranchDelete ? '-D' : '-d', branchName], repoPath)
} catch (error) {
// Expected when the branch still has unmerged/unpublished commits: keep it.
console.warn(
`relay removeWorktree: failed to delete local branch "${branchName}" after removing worktree`,
`relay removeWorktree: preserved local branch "${branchName}" after removing worktree (not fully merged)`,
error
)
}