Make worktree removal idempotent by pruning and cleaning up stale directories instead of throwing on failure

This commit is contained in:
Chris Wanstrath 2026-02-20 07:41:24 -08:00
parent be29b5fcd7
commit 814bbb39a0

View File

@ -60,11 +60,15 @@ export async function createWorktree(branch: string, worktreePath: string, cwd:
} }
} }
/** Remove a worktree. */ /** Remove a worktree. Silently succeeds if the worktree is already gone. */
export async function removeWorktree(worktreePath: string, cwd: string): Promise<void> { export async function removeWorktree(worktreePath: string, cwd: string): Promise<void> {
const result = await $`git worktree remove ${worktreePath} --force`.cwd(cwd).nothrow().quiet() const result = await $`git worktree remove ${worktreePath} --force`.cwd(cwd).nothrow().quiet()
if (result.exitCode !== 0) { if (result.exitCode !== 0) {
throw new Error(`Failed to remove worktree: ${result.stderr.toString().trim()}`) // Worktree may already be gone or stale — prune and clean up the directory
await $`git worktree prune`.cwd(cwd).nothrow().quiet()
if (existsSync(worktreePath)) {
await rm(worktreePath, { recursive: true })
}
} }
} }