Merge pull request #3117 from gsd-build/fix/3056-pruneorphanedworktrees-destroys-linked-w

fix: make orphaned worktree prune non-destructive by default
This commit is contained in:
Tom Boucher
2026-05-04 23:31:13 -04:00
committed by GitHub
3 changed files with 43 additions and 52 deletions

View File

@@ -0,0 +1,5 @@
---
type: Fixed
pr: 3117
---
**Worktree prune regression checks are now path-normalized** — pruning safety tests now parse `git worktree list --porcelain` and assert structured normalized paths, preventing path-separator false negatives across platforms while preserving non-destructive prune guarantees.

View File

@@ -792,19 +792,13 @@ function parseWorktreePorcelain(porcelain) {
}
/**
* Remove linked git worktrees whose branch has already been merged into the
* current HEAD of the main worktree. Also runs `git worktree prune` to clear
* any stale references left by manually-deleted worktree directories.
* Clear stale worktree metadata references via `git worktree prune`.
*
* Safe guards:
* - Never removes the main worktree (first entry in --porcelain output).
* - Never removes the worktree at process.cwd().
* - Never removes a worktree whose branch has unmerged commits.
* - Skips detached-HEAD worktrees (no branch name).
* Destructive linked-worktree removal is disabled by default for safety.
*
* @param {string} repoRoot - absolute path to the main (or any) worktree of
* the repository; used as `cwd` for git commands.
* @returns {string[]} list of worktree paths that were removed
* @returns {string[]} list of worktree paths that were removed (always empty)
*/
function pruneOrphanedWorktrees(repoRoot) {
const pruned = [];
@@ -821,37 +815,14 @@ function pruneOrphanedWorktrees(repoRoot) {
return pruned;
}
// 2. First entry is the main worktree — never touch it
const mainWorktreePath = worktrees[0].path;
// 3. Check each non-main worktree
for (let i = 1; i < worktrees.length; i++) {
const { path: wtPath, branch } = worktrees[i];
// Never remove the worktree for the current process directory
if (wtPath === cwd || cwd.startsWith(wtPath + path.sep)) continue;
// Check if the branch is fully merged into HEAD (main)
// git merge-base --is-ancestor <branch> HEAD exits 0 when merged
const ancestorCheck = execGit(repoRoot, [
'merge-base', '--is-ancestor', branch, 'HEAD',
]);
if (ancestorCheck.exitCode !== 0) {
// Not yet merged — leave it alone
continue;
}
// Remove the worktree and delete the branch
const removeResult = execGit(repoRoot, ['worktree', 'remove', '--force', wtPath]);
if (removeResult.exitCode === 0) {
execGit(repoRoot, ['branch', '-D', branch]);
pruned.push(wtPath);
}
}
// Destructive removal of linked worktrees is intentionally disabled.
// Keep metadata cleanup only (git worktree prune), which clears stale refs
// for manually-deleted directories without removing active sibling worktrees.
void cwd;
void worktrees;
} catch { /* never crash the caller */ }
// 4. Always run prune to clear stale references (e.g. manually-deleted dirs)
// Always run prune to clear stale references (e.g. manually-deleted dirs)
execGit(repoRoot, ['worktree', 'prune']);
return pruned;

View File

@@ -21,6 +21,24 @@ function getPruneOrphanedWorktrees() {
}
// Create a minimal git repo with an initial commit on main.
function canonicalPath(p) {
try {
return fs.realpathSync.native(path.resolve(p));
} catch {
return path.resolve(p);
}
}
function listedWorktreePaths(repoDir) {
const out = execSync('git worktree list --porcelain', { cwd: repoDir, encoding: 'utf8' });
return new Set(
out
.split('\n')
.filter((line) => line.startsWith('worktree '))
.map((line) => canonicalPath(line.slice('worktree '.length).trim()))
);
}
function createGitRepo(dir) {
fs.mkdirSync(dir, { recursive: true });
execSync('git init', { cwd: dir, stdio: 'pipe' });
@@ -49,8 +67,8 @@ describe('pruneOrphanedWorktrees', () => {
cleanup(tmpBase);
});
// Test 1: removes a worktree whose branch is merged into main
test('removes a worktree whose branch is merged into main', () => {
// Test 1: keeps a merged worktree (destructive removal disabled by default)
test('keeps a worktree whose branch is merged into main', () => {
const repoDir = path.join(tmpBase, 'repo');
const worktreeDir = path.join(tmpBase, 'wt-merged');
@@ -72,17 +90,17 @@ describe('pruneOrphanedWorktrees', () => {
const pruneOrphanedWorktrees = getPruneOrphanedWorktrees();
pruneOrphanedWorktrees(repoDir);
// Assert: worktree directory no longer exists
// Assert: worktree directory still exists
assert.ok(
!fs.existsSync(worktreeDir),
'worktree directory should have been removed but still exists: ' + worktreeDir
fs.existsSync(worktreeDir),
'merged worktree should not be removed by default: ' + worktreeDir
);
// Assert: git worktree list no longer shows it
const listOut = execSync('git worktree list', { cwd: repoDir, encoding: 'utf8' });
// Assert: git worktree list still shows it
const listed = listedWorktreePaths(repoDir);
assert.ok(
!listOut.includes(worktreeDir),
'git worktree list still references removed worktree:\n' + listOut
listed.has(canonicalPath(worktreeDir)),
'git worktree list should still reference merged worktree'
);
});
@@ -132,11 +150,8 @@ describe('pruneOrphanedWorktrees', () => {
const pruneOrphanedWorktrees = getPruneOrphanedWorktrees();
const pruned = pruneOrphanedWorktrees(repoDir);
// process.cwd() must not appear in pruned paths
assert.ok(
!pruned.includes(process.cwd()),
'process.cwd() should never be pruned, but found in: ' + JSON.stringify(pruned)
);
// No destructive removals are performed by default
assert.deepStrictEqual(pruned, []);
// The main worktree (repoDir) itself must still exist
assert.ok(