Skip to content

Commit 67c675e

Browse files
SunkenInTimesheehanmunimclaude
committed
fix(server): removing a worktree on Windows no longer deletes what its junctions point to
Git for Windows before 2.54 follows NTFS junctions inside `git worktree remove` and deletes what they point to, such as a shared node_modules. Later versions skip them but leave the worktree folder behind with the junctions in it. On Windows, Git no longer deletes worktree files. Both removal paths (GitVcsDriver.removeWorktree and storage cleanup) make the checks `git worktree remove` makes before deleting (registered, no lock file, and when not forced, no populated submodules and a clean status bound to the worktree with GIT_DIR and GIT_WORK_TREE, as Git binds it), delete the folder with Node's rm, which unlinks junctions without following them, then run `git worktree remove --force --force` on the missing path so Git only drops its metadata. Other platforms run Git as before. Based on the approach in #17076 by @sheehanmunim; replaces #17076 and #15833. Fixes #14990 Co-authored-by: sheehanmunim <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 6a6ebb2 commit 67c675e

5 files changed

Lines changed: 413 additions & 23 deletions

File tree

‎apps/server/src/storageCleanup.test.ts‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's FileSystem can't create an NTFS junction.
2+
import * as NodeFS from "node:fs";
13
import * as NodeServices from "@effect/platform-node/NodeServices";
24
import * as Effect from "effect/Effect";
35
import * as Context from "effect/Context";
@@ -279,7 +281,12 @@ const cleanupFixture = (
279281
...git,
280282
execute: (input) =>
281283
Effect.gen(function* () {
282-
if (editBeforeRemoval && input.args.includes("remove"))
284+
// Before Git's own clean check: inside `git worktree remove`, or on
285+
// Windows the same status check the removal makes before deleting.
286+
if (
287+
editBeforeRemoval &&
288+
(input.args.includes("remove") || input.args.includes("--porcelain"))
289+
)
283290
yield* fs.writeFileString(`${worktree}/tracked.txt`, "late edit\n");
284291
return yield* git.execute(input);
285292
}),
@@ -1225,6 +1232,22 @@ describe("storage cleanup reports and local file policies", () => {
12251232
}),
12261233
),
12271234
);
1235+
it.live("removes a worktree without deleting what its junctions point to", () =>
1236+
runCleanupTest(
1237+
Effect.gen(function* () {
1238+
const { service, fs, worktree } = yield* cleanupFixture();
1239+
const outside = yield* fs.makeTempDirectoryScoped();
1240+
yield* fs.writeFileString(`${outside}/keep.txt`, "keep\n");
1241+
yield* fs.makeDirectory(`${worktree}/node_modules`);
1242+
// A junction on Windows, the way pnpm links packages; a symlink elsewhere.
1243+
NodeFS.symlinkSync(outside, `${worktree}/node_modules/dep`, "junction");
1244+
const report = yield* service.runNow;
1245+
expect(report.entries[0]).toMatchObject({ outcome: "removed" });
1246+
expect(yield* fs.exists(worktree)).toBe(false);
1247+
expect(yield* fs.readFileString(`${outside}/keep.txt`)).toBe("keep\n");
1248+
}),
1249+
),
1250+
);
12281251
it.live("still removes a worktree when measuring its size fails", () =>
12291252
runCleanupTest(
12301253
Effect.gen(function* () {

‎apps/server/src/storageCleanup.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ import * as Settings from "./serverSettings.ts";
4545
import * as TerminalManager from "./terminal/Manager.ts";
4646
import { isFilesystemRoot, managedWorktreesDirectories } from "./worktreesDirectory.ts";
4747
import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
48+
import { removeLinkedWorktree } from "./vcs/worktreeRemoval.ts";
4849
import { withWorkspaceLease } from "./workspace/workspaceLease.ts";
4950
import * as HostProcess from "@t3tools/shared/HostProcess";
5051
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
@@ -833,11 +834,14 @@ const make = Effect.gen(function* () {
833834
// edit arrives after our last status check.
834835
if (settings.worktreeKeepWhen === "tracked-changes")
835836
yield* cleanupGit(worktreePath, ["clean", "-ffdx"], "git clean");
836-
yield* cleanupGit(
837-
project.workspaceRoot,
838-
["-c", "status.showUntrackedFiles=normal", "worktree", "remove", "--", worktreePath],
839-
"git worktree remove",
840-
);
837+
yield* removeLinkedWorktree({
838+
operation: "StorageCleanup.cleanupGit",
839+
cwd: project.workspaceRoot,
840+
worktreePath,
841+
force: false,
842+
execute: git.execute,
843+
run: (args) => cleanupGit(project.workspaceRoot, [...args], "git worktree remove"),
844+
});
841845
entries.push({ ...entry, outcome: "removed", reason: sentence(removalReason), bytes });
842846
yield* gitManager.invalidateStatus(project.workspaceRoot);
843847
// Preserve branch and path: ProviderTurnStartService recreates the checkout

‎apps/server/src/vcs/GitVcsDriverCore.test.ts‎

Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3590,6 +3590,195 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
35903590
}),
35913591
);
35923592

3593+
it.effect("force-removes a worktree without deleting what its junctions point to", () =>
3594+
Effect.gen(function* () {
3595+
const cwd = yield* makeTmpDir();
3596+
const { initialBranch } = yield* initRepoWithCommit(cwd);
3597+
yield* writeTextFile(cwd, ".gitignore", "node_modules\n");
3598+
yield* git(cwd, ["add", ".gitignore"]);
3599+
yield* git(cwd, ["commit", "-m", "ignore node_modules"]);
3600+
const fileSystem = yield* FileSystem.FileSystem;
3601+
const pathService = yield* Path.Path;
3602+
const outside = yield* makeTmpDir("git-worktree-link-target-");
3603+
yield* writeTextFile(outside, "keep.txt", "keep\n");
3604+
const worktreePath = pathService.join(yield* makeTmpDir("git-worktrees-"), "linked");
3605+
const driver = yield* GitVcsDriver.GitVcsDriver;
3606+
yield* driver.createWorktree({
3607+
cwd,
3608+
path: worktreePath,
3609+
refName: initialBranch,
3610+
newRefName: "feature/linked",
3611+
});
3612+
// Junctions on Windows, the way pnpm links packages; symlinks elsewhere.
3613+
NodeFS.mkdirSync(pathService.join(worktreePath, "node_modules"));
3614+
NodeFS.symlinkSync(
3615+
outside,
3616+
pathService.join(worktreePath, "node_modules", "dep"),
3617+
"junction",
3618+
);
3619+
NodeFS.symlinkSync(outside, pathService.join(worktreePath, "shared"), "junction");
3620+
3621+
yield* driver.removeWorktree({ cwd, path: worktreePath, force: true });
3622+
3623+
assert.deepEqual(NodeFS.readdirSync(pathService.dirname(worktreePath)), []);
3624+
assert.equal(
3625+
yield* fileSystem.readFileString(pathService.join(outside, "keep.txt")),
3626+
"keep\n",
3627+
);
3628+
}),
3629+
);
3630+
3631+
it.effect("keeps the junctions of a worktree that git refuses to remove", () =>
3632+
Effect.gen(function* () {
3633+
const cwd = yield* makeTmpDir();
3634+
const { initialBranch } = yield* initRepoWithCommit(cwd);
3635+
yield* writeTextFile(cwd, ".gitignore", "node_modules\n");
3636+
yield* git(cwd, ["add", ".gitignore"]);
3637+
yield* git(cwd, ["commit", "-m", "ignore node_modules"]);
3638+
const pathService = yield* Path.Path;
3639+
const outside = yield* makeTmpDir("git-worktree-link-target-");
3640+
const worktreePath = pathService.join(yield* makeTmpDir("git-worktrees-"), "linked");
3641+
const driver = yield* GitVcsDriver.GitVcsDriver;
3642+
yield* driver.createWorktree({
3643+
cwd,
3644+
path: worktreePath,
3645+
refName: initialBranch,
3646+
newRefName: "feature/linked",
3647+
});
3648+
const link = pathService.join(worktreePath, "node_modules");
3649+
NodeFS.symlinkSync(outside, link, "junction");
3650+
yield* writeTextFile(worktreePath, "notes.txt", "draft\n");
3651+
3652+
const result = yield* Effect.result(driver.removeWorktree({ cwd, path: worktreePath }));
3653+
3654+
assert.isTrue(Result.isFailure(result));
3655+
assert.isTrue(NodeFS.lstatSync(link).isSymbolicLink());
3656+
assert.deepEqual(NodeFS.readdirSync(pathService.dirname(worktreePath)), ["linked"]);
3657+
}),
3658+
);
3659+
3660+
it.effect("keeps a locked worktree whose lock can't be read", () =>
3661+
Effect.gen(function* () {
3662+
const cwd = yield* makeTmpDir();
3663+
const { initialBranch } = yield* initRepoWithCommit(cwd);
3664+
const pathService = yield* Path.Path;
3665+
const fileSystem = yield* FileSystem.FileSystem;
3666+
const worktreePath = pathService.join(yield* makeTmpDir("git-worktrees-"), "linked");
3667+
const driver = yield* GitVcsDriver.GitVcsDriver;
3668+
yield* driver.createWorktree({
3669+
cwd,
3670+
path: worktreePath,
3671+
refName: initialBranch,
3672+
newRefName: "feature/linked",
3673+
});
3674+
// Git counts the lock file's existence; one that can't be read still locks.
3675+
const lockFile = pathService.join(
3676+
yield* git(worktreePath, ["rev-parse", "--absolute-git-dir"]),
3677+
"locked",
3678+
);
3679+
NodeFS.mkdirSync(lockFile);
3680+
3681+
const result = yield* Effect.result(
3682+
driver.removeWorktree({ cwd, path: worktreePath, force: true }),
3683+
);
3684+
3685+
assert.isTrue(Result.isFailure(result));
3686+
assert.equal(yield* fileSystem.exists(pathService.join(worktreePath, "README.md")), true);
3687+
}),
3688+
);
3689+
3690+
it.effect("keeps edits in a worktree whose core.worktree points elsewhere", () =>
3691+
Effect.gen(function* () {
3692+
const cwd = yield* makeTmpDir();
3693+
const { initialBranch } = yield* initRepoWithCommit(cwd);
3694+
const pathService = yield* Path.Path;
3695+
const fileSystem = yield* FileSystem.FileSystem;
3696+
const worktreePath = pathService.join(yield* makeTmpDir("git-worktrees-"), "linked");
3697+
const driver = yield* GitVcsDriver.GitVcsDriver;
3698+
yield* driver.createWorktree({
3699+
cwd,
3700+
path: worktreePath,
3701+
refName: initialBranch,
3702+
newRefName: "feature/linked",
3703+
});
3704+
// A plain `git status` in the worktree now inspects the clean main checkout.
3705+
yield* git(cwd, ["config", "extensions.worktreeConfig", "true"]);
3706+
yield* git(worktreePath, ["config", "--worktree", "core.worktree", cwd]);
3707+
yield* writeTextFile(worktreePath, "README.md", "uncommitted\n");
3708+
3709+
const result = yield* Effect.result(driver.removeWorktree({ cwd, path: worktreePath }));
3710+
3711+
assert.isTrue(Result.isFailure(result));
3712+
assert.equal(
3713+
yield* fileSystem.readFileString(pathService.join(worktreePath, "README.md")),
3714+
"uncommitted\n",
3715+
);
3716+
}),
3717+
);
3718+
3719+
it.effect("removes a worktree whose tracked folder was replaced by a junction", () =>
3720+
Effect.gen(function* () {
3721+
const cwd = yield* makeTmpDir();
3722+
const { initialBranch } = yield* initRepoWithCommit(cwd);
3723+
yield* writeTextFile(cwd, "src/keep.txt", "keep\n");
3724+
yield* git(cwd, ["add", "src"]);
3725+
yield* git(cwd, ["commit", "-m", "add src"]);
3726+
const fileSystem = yield* FileSystem.FileSystem;
3727+
const pathService = yield* Path.Path;
3728+
const worktreePath = pathService.join(yield* makeTmpDir("git-worktrees-"), "linked");
3729+
const driver = yield* GitVcsDriver.GitVcsDriver;
3730+
yield* driver.createWorktree({
3731+
cwd,
3732+
path: worktreePath,
3733+
refName: initialBranch,
3734+
newRefName: "feature/linked",
3735+
});
3736+
// Same bytes as the checkout, so Git sees neither a change nor an untracked file.
3737+
const outside = yield* makeTmpDir("git-worktree-link-target-");
3738+
NodeFS.copyFileSync(
3739+
pathService.join(worktreePath, "src", "keep.txt"),
3740+
pathService.join(outside, "keep.txt"),
3741+
);
3742+
NodeFS.rmSync(pathService.join(worktreePath, "src"), { recursive: true });
3743+
NodeFS.symlinkSync(outside, pathService.join(worktreePath, "src"), "junction");
3744+
3745+
yield* driver.removeWorktree({ cwd, path: worktreePath });
3746+
3747+
assert.deepEqual(NodeFS.readdirSync(pathService.dirname(worktreePath)), []);
3748+
assert.equal(
3749+
yield* fileSystem.readFileString(pathService.join(outside, "keep.txt")),
3750+
"keep\n",
3751+
);
3752+
}),
3753+
);
3754+
3755+
it.effect("leaves a folder alone that only shares the worktree's short name", () =>
3756+
Effect.gen(function* () {
3757+
const cwd = yield* makeTmpDir();
3758+
const { initialBranch } = yield* initRepoWithCommit(cwd);
3759+
const pathService = yield* Path.Path;
3760+
const fileSystem = yield* FileSystem.FileSystem;
3761+
const driver = yield* GitVcsDriver.GitVcsDriver;
3762+
const worktreePath = pathService.join(yield* makeTmpDir("git-worktrees-"), "short");
3763+
yield* driver.createWorktree({
3764+
cwd,
3765+
path: worktreePath,
3766+
refName: initialBranch,
3767+
newRefName: "feature/short",
3768+
});
3769+
// Unrelated to the worktree, but resolving "short" against cwd lands here.
3770+
const outside = yield* makeTmpDir("git-worktree-link-target-");
3771+
const unrelated = pathService.join(cwd, "short");
3772+
NodeFS.mkdirSync(unrelated);
3773+
NodeFS.symlinkSync(outside, pathService.join(unrelated, "linked"), "junction");
3774+
3775+
yield* Effect.result(driver.removeWorktree({ cwd, path: "short", force: true }));
3776+
3777+
assert.isTrue(NodeFS.lstatSync(pathService.join(unrelated, "linked")).isSymbolicLink());
3778+
assert.equal(yield* fileSystem.exists(worktreePath), true);
3779+
}),
3780+
);
3781+
35933782
it.effect("allows worktree removal to run longer than the default command timeout", () =>
35943783
Effect.gen(function* () {
35953784
const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;

‎apps/server/src/vcs/GitVcsDriverCore.ts‎

Lines changed: 25 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import { resolveProjectFileBackedSetting } from "@t3tools/shared/projectSettings
3838
import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts";
3939
import * as GitVcsDriver from "./GitVcsDriver.ts";
4040
import { explicitBareRepositoryEnv, gitConfigEnv } from "./VcsProcess.ts";
41+
import { removeLinkedWorktree } from "./worktreeRemoval.ts";
4142
import { resolveWorktreesDirectory } from "../worktreesDirectory.ts";
4243
import {
4344
parseRemoteNames,
@@ -3820,21 +3821,24 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
38203821
const removeWorktree: GitVcsDriver.GitVcsDriver["Service"]["removeWorktree"] = Effect.fn(
38213822
"removeWorktree",
38223823
)(function* (input) {
3823-
// Git refuses to remove a worktree with untracked files unless forced, but
3824-
// its check honors `status.showUntrackedFiles=no` and would delete them.
3825-
const args = ["-c", "status.showUntrackedFiles=normal", "worktree", "remove"];
3826-
if (input.force) {
3827-
args.push("--force");
3828-
}
3829-
args.push("--", input.path);
3830-
const result = yield* executeGitWithStableDiagnostics(
3831-
"GitVcsDriver.removeWorktree",
3832-
input.cwd,
3833-
args,
3834-
{
3835-
timeoutMs: WORKTREE_REMOVE_TIMEOUT_MS,
3836-
allowNonZeroExit: true,
3837-
},
3824+
// Git also matches a worktree by its short name, which can name a different
3825+
// folder than this path. Resolving it once keeps Git and the Windows
3826+
// deletion in removeLinkedWorktree on the same directory.
3827+
const worktreePath = path.resolve(input.cwd, input.path);
3828+
const result = yield* removeLinkedWorktree({
3829+
operation: "GitVcsDriver.removeWorktree",
3830+
cwd: input.cwd,
3831+
worktreePath,
3832+
force: input.force === true,
3833+
execute,
3834+
run: (args) =>
3835+
executeGitWithStableDiagnostics("GitVcsDriver.removeWorktree", input.cwd, args, {
3836+
timeoutMs: WORKTREE_REMOVE_TIMEOUT_MS,
3837+
allowNonZeroExit: true,
3838+
}).pipe(Effect.map((result) => ({ ...result, args }))),
3839+
}).pipe(
3840+
Effect.provideService(FileSystem.FileSystem, fileSystem),
3841+
Effect.provideService(Path.Path, path),
38383842
);
38393843
if (result.exitCode === 0) {
38403844
return;
@@ -3844,7 +3848,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
38443848
// than an error.
38453849
const alreadyGone =
38463850
isMissingWorktreeStderr(result.stderr) &&
3847-
!(yield* fileSystem.exists(input.path).pipe(Effect.orElseSucceed(() => false)));
3851+
!(yield* fileSystem.exists(worktreePath).pipe(Effect.orElseSucceed(() => false)));
38483852
if (alreadyGone) {
38493853
yield* pruneWorktrees({ cwd: input.cwd });
38503854
return;
@@ -3853,7 +3857,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
38533857
`GitVcsDriver.removeWorktree: git worktree remove exited with code ${result.exitCode} for ${input.path} (stderr length ${result.stderr.length}).`,
38543858
);
38553859
return yield* new GitCommandError({
3856-
...gitCommandContext({ operation: "GitVcsDriver.removeWorktree", cwd: input.cwd, args }),
3860+
...gitCommandContext({
3861+
operation: "GitVcsDriver.removeWorktree",
3862+
cwd: input.cwd,
3863+
args: result.args,
3864+
}),
38573865
detail: "git worktree remove failed",
38583866
...(result.exitCode === null ? {} : { exitCode: result.exitCode }),
38593867
stdoutLength: result.stdout.length,

0 commit comments

Comments
 (0)