Skip to content

Commit b84f15c

Browse files
SunkenInTimeclaudejuliusmarminge
authored
fix(server): removing a worktree on Windows no longer leaves junctions behind (pingdotgg#15833)
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]> Co-authored-by: Julius Marminge <[email protected]>
1 parent 39bd164 commit b84f15c

3 files changed

Lines changed: 146 additions & 1 deletion

File tree

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

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4019,6 +4019,57 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
40194019
}),
40204020
);
40214021

4022+
it.effect.each([false, true])(
4023+
"cleans up links left by successful worktree removal, preserving ordinary files: %s",
4024+
(keepFile) =>
4025+
Effect.gen(function* () {
4026+
const cwd = yield* makeTmpDir();
4027+
const fileSystem = yield* FileSystem.FileSystem;
4028+
const pathService = yield* Path.Path;
4029+
const outside = yield* makeTmpDir("git-worktree-link-target-");
4030+
yield* writeTextFile(outside, "keep.txt", "external target\n");
4031+
const worktreePath = pathService.join(cwd, "leftover");
4032+
const nested = pathService.join(worktreePath, "node_modules");
4033+
yield* fileSystem.makeDirectory(nested, { recursive: true });
4034+
yield* fileSystem.makeDirectory(pathService.join(worktreePath, "empty"));
4035+
NodeFS.symlinkSync(outside, pathService.join(worktreePath, "linked"), "junction");
4036+
NodeFS.symlinkSync(outside, pathService.join(nested, "pkg"), "junction");
4037+
if (keepFile) {
4038+
yield* writeTextFile(worktreePath, "notes/draft.txt", "new work\n");
4039+
}
4040+
4041+
// Git removes symlinks on Unix; simulate its successful Windows removal
4042+
// leaving junctions behind so the cleanup is exercised on every platform.
4043+
const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
4044+
const spawner = ChildProcessSpawner.make((command) =>
4045+
ChildProcess.isStandardCommand(command) &&
4046+
command.args.join(" ").includes("worktree remove")
4047+
? Effect.succeed(makeSuccessfulHandle(""))
4048+
: delegate.spawn(command),
4049+
);
4050+
const driver = yield* makeGitVcsDriverCore().pipe(
4051+
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
4052+
Effect.provide(layerServerConfig),
4053+
);
4054+
4055+
yield* driver.removeWorktree({ cwd, path: worktreePath });
4056+
4057+
assert.equal(
4058+
yield* fileSystem.readFileString(pathService.join(outside, "keep.txt")),
4059+
"external target\n",
4060+
);
4061+
if (keepFile) {
4062+
assert.deepEqual(yield* fileSystem.readDirectory(worktreePath), ["notes"]);
4063+
assert.equal(
4064+
yield* fileSystem.readFileString(pathService.join(worktreePath, "notes/draft.txt")),
4065+
"new work\n",
4066+
);
4067+
} else {
4068+
assert.equal(yield* fileSystem.exists(worktreePath), false);
4069+
}
4070+
}),
4071+
);
4072+
40224073
it.effect("keeps a worktree whose untracked files status is configured to hide", () =>
40234074
Effect.gen(function* () {
40244075
const cwd = yield* makeTmpDir();
@@ -4047,6 +4098,33 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
40474098
}),
40484099
);
40494100

4101+
it.effect("leaves a folder alone that only shares the worktree's short name", () =>
4102+
Effect.gen(function* () {
4103+
const cwd = yield* makeTmpDir();
4104+
const { initialBranch } = yield* initRepoWithCommit(cwd);
4105+
const pathService = yield* Path.Path;
4106+
const fileSystem = yield* FileSystem.FileSystem;
4107+
const driver = yield* GitVcsDriver.GitVcsDriver;
4108+
const worktreePath = pathService.join(yield* makeTmpDir("git-worktrees-"), "short");
4109+
yield* driver.createWorktree({
4110+
cwd,
4111+
path: worktreePath,
4112+
refName: initialBranch,
4113+
newRefName: "feature/short",
4114+
});
4115+
// Unrelated to the worktree, but resolving "short" against cwd lands here.
4116+
const outside = yield* makeTmpDir("git-worktree-link-target-");
4117+
const unrelated = pathService.join(cwd, "short");
4118+
NodeFS.mkdirSync(unrelated);
4119+
NodeFS.symlinkSync(outside, pathService.join(unrelated, "linked"), "junction");
4120+
4121+
yield* Effect.result(driver.removeWorktree({ cwd, path: "short" }));
4122+
4123+
assert.isTrue(NodeFS.lstatSync(pathService.join(unrelated, "linked")).isSymbolicLink());
4124+
assert.equal(yield* fileSystem.exists(worktreePath), true);
4125+
}),
4126+
);
4127+
40504128
it.effect("allows worktree removal to run longer than the default command timeout", () =>
40514129
Effect.gen(function* () {
40524130
const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;

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

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import * as Cache from "effect/Cache";
2+
import * as Cause from "effect/Cause";
23
import * as Data from "effect/Data";
34
import * as Crypto from "effect/Crypto";
45
import * as DateTime from "effect/DateTime";
@@ -37,6 +38,7 @@ import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
3738
import { resolveProjectFileBackedSetting } from "@t3tools/shared/projectSettings";
3839
import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts";
3940
import * as GitVcsDriver from "./GitVcsDriver.ts";
41+
import { removeEmptyDirectory } from "./removeEmptyDirectory.ts";
4042
import { explicitBareRepositoryEnv, gitConfigEnv } from "./VcsProcess.ts";
4143
import { resolveWorktreesDirectory } from "../worktreesDirectory.ts";
4244
import {
@@ -3981,16 +3983,41 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
39813983
input.branch,
39823984
]);
39833985

3986+
/**
3987+
* Unlinks links under `target` without following them and removes the
3988+
* directories that leaves empty. Returns false when anything else remains.
3989+
*/
3990+
const removeLeftoverLinks = (
3991+
target: string,
3992+
): Effect.Effect<boolean, PlatformError.PlatformError | Cause.UnknownError> =>
3993+
Effect.gen(function* () {
3994+
if (Option.isSome(yield* fileSystem.readLink(target).pipe(Effect.option))) {
3995+
yield* fileSystem.remove(target);
3996+
return true;
3997+
}
3998+
if ((yield* fileSystem.stat(target)).type !== "Directory") return false;
3999+
let empty = true;
4000+
for (const name of yield* fileSystem.readDirectory(target)) {
4001+
if (!(yield* removeLeftoverLinks(path.join(target, name)))) empty = false;
4002+
}
4003+
// Only an empty directory goes, so files written since the listing stay.
4004+
return empty && (yield* removeEmptyDirectory(target));
4005+
});
4006+
39844007
const removeWorktree: GitVcsDriver.GitVcsDriver["Service"]["removeWorktree"] = Effect.fn(
39854008
"removeWorktree",
39864009
)(function* (input) {
4010+
// Git also accepts a worktree's short name, which can match a different
4011+
// folder than the path resolved against `input.cwd`. Resolve it once so Git
4012+
// and the leftover cleanup below act on the same directory.
4013+
const target = path.resolve(input.cwd, input.path);
39874014
// Git refuses to remove a worktree with untracked files unless forced, but
39884015
// its check honors `status.showUntrackedFiles=no` and would delete them.
39894016
const args = ["-c", "status.showUntrackedFiles=normal", "worktree", "remove"];
39904017
if (input.force) {
39914018
args.push("--force");
39924019
}
3993-
args.push("--", input.path);
4020+
args.push("--", target);
39944021
const result = yield* executeGitWithStableDiagnostics(
39954022
"GitVcsDriver.removeWorktree",
39964023
input.cwd,
@@ -4001,6 +4028,28 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
40014028
},
40024029
);
40034030
if (result.exitCode === 0) {
4031+
// Git for Windows never descends into NTFS junctions, such as pnpm's
4032+
// node_modules links. It reports success but leaves them and their parent
4033+
// directories behind, so a resumed thread would find a stub instead of
4034+
// recreating its checkout. Git has already unregistered the worktree, so
4035+
// anything left here is logged rather than returned: a retry could never
4036+
// succeed.
4037+
if (yield* fileSystem.exists(target).pipe(Effect.orElseSucceed(() => false))) {
4038+
const removed = yield* removeLeftoverLinks(target).pipe(
4039+
Effect.catch((error) =>
4040+
Effect.logWarning("GitVcsDriver.removeWorktree: failed to delete leftover links", {
4041+
path: target,
4042+
error,
4043+
}).pipe(Effect.as(true)),
4044+
),
4045+
);
4046+
if (!removed) {
4047+
yield* Effect.logWarning(
4048+
"GitVcsDriver.removeWorktree: kept files written after git removed the worktree",
4049+
{ path: target },
4050+
);
4051+
}
4052+
}
40044053
return;
40054054
}
40064055
// Threads can share a worktree path, and worktrees get removed or pruned
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// @effect-diagnostics nodeBuiltinImport:off - Effect's FileSystem has no rmdir.
2+
import * as NodeFSP from "node:fs/promises";
3+
4+
import * as Effect from "effect/Effect";
5+
6+
/**
7+
* Removes `path` only while it is an empty directory. Succeeds with false when
8+
* anything else is there, including files written after the caller looked.
9+
* Other failures, such as a permission error, stay errors.
10+
*/
11+
export const removeEmptyDirectory = (path: string) =>
12+
Effect.tryPromise(() => NodeFSP.rmdir(path)).pipe(
13+
Effect.as(true),
14+
Effect.catchIf(
15+
(error) => (error.cause as NodeJS.ErrnoException | undefined)?.code === "ENOTEMPTY",
16+
() => Effect.succeed(false),
17+
),
18+
);

0 commit comments

Comments
 (0)