TypeScript
fix(server): removing a worktree on Windows no longer deletes what its junctions point to (#21099)
Dara Adedejifa42465ff648
diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.tsindex 48529f28a9d..33cc1874281 100644--- a/apps/server/src/storageCleanup.test.ts+++ b/apps/server/src/storageCleanup.test.ts@@ -276,7 +276,12 @@ const cleanupFixture = (...git,execute: (input) =>Effect.gen(function* () {- if (editBeforeRemoval && input.args.includes("remove"))+ // Before Git's own clean check: inside `git worktree remove`, or on+ // Windows the same status check the removal makes before deleting.+ if (+ editBeforeRemoval &&+ (input.args.includes("remove") || input.args.includes("--porcelain"))+ )yield* fs.writeFileString(`${worktree}/tracked.txt`, "late edit\n");return yield* git.execute(input);}),diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.tsindex 4b82338b1f5..1c4eb714fac 100644--- a/apps/server/src/storageCleanup.ts+++ b/apps/server/src/storageCleanup.ts@@ -46,6 +46,7 @@ import * as Settings from "./serverSettings.ts";import * as TerminalManager from "./terminal/Manager.ts";import { isFilesystemRoot, managedWorktreesDirectories } from "./worktreesDirectory.ts";import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";+import { removeLinkedWorktree } from "./vcs/worktreeRemoval.ts";import { withWorkspaceLease } from "./workspace/workspaceLease.ts";import * as HostProcess from "@t3tools/shared/HostProcess";import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";@@ -1013,20 +1014,15 @@ const make = Effect.gen(function* () {const changes = yield* localChangesReason(worktreePath, settings);if (changes !== null) return keep(changes);}- yield* cleanupGit(- project.workspaceRoot,- [- "-c",- "status.showUntrackedFiles=normal",- "worktree",- "remove",- // Git requires force for submodules; recursive checks above cannot make removal atomic.- ...(submodules.force ? ["--force"] : []),- "--",- worktreePath,- ],- "git worktree remove",- );+ yield* removeLinkedWorktree({+ operation: "StorageCleanup.cleanupGit",+ cwd: project.workspaceRoot,+ worktreePath,+ // Git requires force for submodules; recursive checks above cannot make removal atomic.+ force: submodules.force,+ execute: git.execute,+ run: (args) => cleanupGit(project.workspaceRoot, [...args], "git worktree remove"),+ });entries.push({ ...entry, outcome: "removed", reason: sentence(removalReason), bytes });yield* gitManager.invalidateStatus(project.workspaceRoot);// Preserve branch and path: ProviderTurnStartService recreates the checkoutdiff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.tsindex 4bda1dbd765..c0c5f261563 100644--- a/apps/server/src/vcs/GitVcsDriverCore.test.ts+++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts@@ -3416,6 +3416,73 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {}),);+ it.effect("force-removes a worktree without deleting what its junctions point to", () =>+ Effect.gen(function* () {+ const cwd = yield* makeTmpDir();+ const { initialBranch } = yield* initRepoWithCommit(cwd);+ yield* writeTextFile(cwd, ".gitignore", "node_modules\n");+ yield* git(cwd, ["add", ".gitignore"]);+ yield* git(cwd, ["commit", "-m", "ignore node_modules"]);+ const fileSystem = yield* FileSystem.FileSystem;+ const pathService = yield* Path.Path;+ const outside = yield* makeTmpDir("git-worktree-link-target-");+ yield* writeTextFile(outside, "keep.txt", "keep\n");+ const worktreePath = pathService.join(yield* makeTmpDir("git-worktrees-"), "linked");+ const driver = yield* GitVcsDriver.GitVcsDriver;+ yield* driver.createWorktree({+ cwd,+ path: worktreePath,+ refName: initialBranch,+ newRefName: "feature/linked",+ });+ // Junctions on Windows, the way pnpm links packages; symlinks elsewhere.+ NodeFS.mkdirSync(pathService.join(worktreePath, "node_modules"));+ NodeFS.symlinkSync(+ outside,+ pathService.join(worktreePath, "node_modules", "dep"),+ "junction",+ );+ NodeFS.symlinkSync(outside, pathService.join(worktreePath, "shared"), "junction");++ yield* driver.removeWorktree({ cwd, path: worktreePath, force: true });++ assert.deepEqual(NodeFS.readdirSync(pathService.dirname(worktreePath)), []);+ assert.equal(+ yield* fileSystem.readFileString(pathService.join(outside, "keep.txt")),+ "keep\n",+ );+ }),+ );++ it.effect("keeps the junctions of a worktree that git refuses to remove", () =>+ Effect.gen(function* () {+ const cwd = yield* makeTmpDir();+ const { initialBranch } = yield* initRepoWithCommit(cwd);+ yield* writeTextFile(cwd, ".gitignore", "node_modules\n");+ yield* git(cwd, ["add", ".gitignore"]);+ yield* git(cwd, ["commit", "-m", "ignore node_modules"]);+ const pathService = yield* Path.Path;+ const outside = yield* makeTmpDir("git-worktree-link-target-");+ const worktreePath = pathService.join(yield* makeTmpDir("git-worktrees-"), "linked");+ const driver = yield* GitVcsDriver.GitVcsDriver;+ yield* driver.createWorktree({+ cwd,+ path: worktreePath,+ refName: initialBranch,+ newRefName: "feature/linked",+ });+ const link = pathService.join(worktreePath, "node_modules");+ NodeFS.symlinkSync(outside, link, "junction");+ yield* writeTextFile(worktreePath, "notes.txt", "draft\n");++ const result = yield* Effect.result(driver.removeWorktree({ cwd, path: worktreePath }));++ assert.isTrue(Result.isFailure(result));+ assert.isTrue(NodeFS.lstatSync(link).isSymbolicLink());+ assert.deepEqual(NodeFS.readdirSync(pathService.dirname(worktreePath)), ["linked"]);+ }),+ );+it.effect("prunes stale registrations when removing an already-gone worktree", () =>Effect.gen(function* () {const cwd = yield* makeTmpDir();diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.tsindex c49af2624cf..0f3fe9a1e6b 100644--- a/apps/server/src/vcs/GitVcsDriverCore.ts+++ b/apps/server/src/vcs/GitVcsDriverCore.ts@@ -42,6 +42,7 @@ import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observabilimport * as GitVcsDriver from "./GitVcsDriver.ts";import { removeEmptyDirectory } from "./removeEmptyDirectory.ts";import { explicitBareRepositoryEnv, gitConfigEnv } from "./VcsProcess.ts";+import { removeLinkedWorktree } from "./worktreeRemoval.ts";import { resolveWorktreesDirectory } from "../worktreesDirectory.ts";import {parseRemoteNames,@@ -4172,25 +4173,24 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*const removeWorktree: GitVcsDriver.GitVcsDriver["Service"]["removeWorktree"] = Effect.fn("removeWorktree",)(function* (input) {- // Git also accepts a worktree's short name, which can match a different- // folder than the path resolved against `input.cwd`. Resolve it once so Git- // and the leftover cleanup below act on the same directory.+ // Git also matches a worktree by its short name, which can name a different+ // folder than this path. Resolving it once keeps Git, the Windows deletion+ // in removeLinkedWorktree, and the leftover cleanup below on one directory.const target = path.resolve(input.cwd, input.path);- // Git refuses to remove a worktree with untracked files unless forced, but- // its check honors `status.showUntrackedFiles=no` and would delete them.- const args = ["-c", "status.showUntrackedFiles=normal", "worktree", "remove"];- if (input.force) {- args.push("--force");- }- args.push("--", target);- const result = yield* executeGitWithStableDiagnostics(- "GitVcsDriver.removeWorktree",- input.cwd,- args,- {- timeoutMs: WORKTREE_REMOVE_TIMEOUT_MS,- allowNonZeroExit: true,- },+ const result = yield* removeLinkedWorktree({+ operation: "GitVcsDriver.removeWorktree",+ cwd: input.cwd,+ worktreePath: target,+ force: input.force === true,+ execute,+ run: (args) =>+ executeGitWithStableDiagnostics("GitVcsDriver.removeWorktree", input.cwd, args, {+ timeoutMs: WORKTREE_REMOVE_TIMEOUT_MS,+ allowNonZeroExit: true,+ }).pipe(Effect.map((result) => ({ ...result, args }))),+ }).pipe(+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, path),);if (result.exitCode === 0) {// Git for Windows never descends into NTFS junctions, such as pnpm's@@ -4222,7 +4222,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*// than an error.const alreadyGone =isMissingWorktreeStderr(result.stderr) &&- !(yield* fileSystem.exists(input.path).pipe(Effect.orElseSucceed(() => false)));+ !(yield* fileSystem.exists(target).pipe(Effect.orElseSucceed(() => false)));if (alreadyGone) {yield* pruneWorktrees({ cwd: input.cwd });return;@@ -4231,7 +4231,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*`GitVcsDriver.removeWorktree: git worktree remove exited with code ${result.exitCode} for ${input.path} (stderr length ${result.stderr.length}).`,);return yield* new GitCommandError({- ...gitCommandContext({ operation: "GitVcsDriver.removeWorktree", cwd: input.cwd, args }),+ ...gitCommandContext({+ operation: "GitVcsDriver.removeWorktree",+ cwd: input.cwd,+ args: result.args,+ }),detail: "git worktree remove failed",...(result.exitCode === null ? {} : { exitCode: result.exitCode }),stdoutLength: result.stdout.length,diff --git a/apps/server/src/vcs/worktreeRemoval.ts b/apps/server/src/vcs/worktreeRemoval.tsnew file mode 100644index 00000000000..c8feb71c3d8--- /dev/null+++ b/apps/server/src/vcs/worktreeRemoval.ts@@ -0,0 +1,164 @@+import { GitCommandError } from "@t3tools/contracts";+import * as HostProcess from "@t3tools/shared/HostProcess";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Option from "effect/Option";+import * as Path from "effect/Path";++import type * as GitVcsDriver from "./GitVcsDriver.ts";++const INDEX_LIST_MAX_BYTES = 64 * 1024 * 1024;++/**+ * Removes the linked worktree at `worktreePath` by running `git worktree+ * remove` through `run`.+ *+ * Git for Windows before 2.54 follows NTFS junctions while it deletes a+ * worktree, and deletes what they point to, such as a shared node_modules.+ * Later versions skip junctions but leave them, and the folders holding them,+ * behind. On Windows, Git therefore never deletes the files: this makes the+ * checks `git worktree remove` makes before deleting (builtin/worktree.c),+ * deletes the folder with Node's `rm`, which unlinks junctions without+ * following them, and then has Git drop the now-missing worktree's metadata.+ * Git elsewhere only unlinks links, so other hosts run Git as before.+ */+export const removeLinkedWorktree = Effect.fn("WorktreeRemoval.removeLinkedWorktree")(function* <+ A,+ E,+ R,+>(input: {+ readonly operation: string;+ readonly cwd: string;+ readonly worktreePath: string;+ readonly force: boolean;+ readonly execute: GitVcsDriver.GitVcsDriver["Service"]["execute"];+ readonly run: (args: ReadonlyArray<string>) => Effect.Effect<A, E, R>;+}) {+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const worktreePath = input.worktreePath;+ const gitFile = path.join(worktreePath, ".git");+ // Git refuses to remove a worktree with untracked files unless forced, but+ // its check honors `status.showUntrackedFiles=no` and would delete them.+ const statusConfig = ["-c", "status.showUntrackedFiles=normal"];+ const linked =+ (yield* HostProcess.isWindows) &&+ (yield* fileSystem.stat(gitFile).pipe(+ Effect.map((info) => info.type === "File"),+ Effect.orElseSucceed(() => false),+ ));+ if (!linked) {+ return yield* input.run([+ ...statusConfig,+ "worktree",+ "remove",+ ...(input.force ? ["--force"] : []),+ "--",+ worktreePath,+ ]);+ }++ // Git's own refusals, worded the way it prints them.+ const refuse = (message: string, cause?: unknown) =>+ new GitCommandError({+ operation: input.operation,+ command: "git worktree remove",+ cwd: input.cwd,+ detail: `fatal: ${message}`,+ ...(cause === undefined ? {} : { cause }),+ });+ const gitOutput = (cwd: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>+ input+ .execute({+ operation: input.operation,+ cwd,+ args,+ maxOutputBytes: INDEX_LIST_MAX_BYTES,+ ...(env === undefined ? {} : { env }),+ })+ .pipe(Effect.map((result) => result.stdout));+ const samePath = (left: string, right: string) =>+ Effect.all([fileSystem.realPath(left), fileSystem.realPath(right)]).pipe(+ Effect.map(([a, b]) => a.toLowerCase() === b.toLowerCase()),+ Effect.orElseSucceed(() => false),+ );++ // A registered worktree of this repository: its `.git` file names an admin+ // directory under the common `worktrees/`, whose `gitdir` points back.+ const notAWorktree = refuse(`'${worktreePath}' is not a working tree`);+ const adminDir = path.resolve(+ worktreePath,+ (yield* gitOutput(worktreePath, ["rev-parse", "--absolute-git-dir"]).pipe(+ Effect.mapError(() => notAWorktree),+ )).trim(),+ );+ const commonDir = path.resolve(+ input.cwd,+ (yield* gitOutput(input.cwd, ["rev-parse", "--git-common-dir"])).trim(),+ );+ const pointsBack = yield* fileSystem.readFileString(path.join(adminDir, "gitdir")).pipe(+ Effect.flatMap((gitdir) => samePath(path.resolve(adminDir, gitdir.trim()), gitFile)),+ Effect.orElseSucceed(() => false),+ );+ if (!pointsBack || !(yield* samePath(path.dirname(adminDir), path.join(commonDir, "worktrees"))))+ return yield* notAWorktree;+ // Git counts the file's existence as a lock. T3 passes at most one+ // `--force`, which never removes a locked worktree. Anything but a+ // confirmed absence refuses.+ const lockFile = path.join(adminDir, "locked");+ const locked = yield* fileSystem.stat(lockFile).pipe(+ Effect.as(true),+ Effect.catch((error) =>+ error.reason._tag === "NotFound"+ ? Effect.succeed(false)+ : Effect.fail(refuse(`cannot inspect the lock of '${worktreePath}'`, error)),+ ),+ );+ if (locked) {+ const reason = (yield* fileSystem.readFileString(lockFile).pipe(Effect.option)).pipe(+ Option.map((text) => text.trim()),+ Option.getOrElse(() => ""),+ );+ return yield* refuse(+ reason === ""+ ? "cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"+ : `cannot remove a locked working tree, lock reason: ${reason}\nuse 'remove -f -f' to override or unlock first`,+ );+ }+ if (!input.force) {+ // Bound like Git's own check, so `core.worktree` can't point it elsewhere.+ const boundEnv = { GIT_DIR: gitFile, GIT_WORK_TREE: worktreePath };+ const submodules = refuse("working trees containing submodules cannot be moved or removed");+ // An unreadable path counts as present, so a doubt refuses.+ const present = (target: string) =>+ fileSystem.exists(target).pipe(Effect.orElseSucceed(() => true));+ if (yield* present(path.join(adminDir, "modules"))) return yield* submodules;+ const index = yield* gitOutput(worktreePath, ["ls-files", "--stage", "-z"], boundEnv);+ for (const entry of index.split("\0")) {+ if (!entry.startsWith("160000 ")) continue;+ const submodule = entry.slice(entry.indexOf("\t") + 1);+ if (yield* present(path.join(worktreePath, submodule, ".git"))) return yield* submodules;+ }+ const status = yield* gitOutput(+ worktreePath,+ [...statusConfig, "status", "--porcelain", "--ignore-submodules=none"],+ boundEnv,+ );+ if (status !== "")+ return yield* refuse(+ `'${worktreePath}' contains modified or untracked files, use --force to delete it`,+ );+ }++ // A file held open can stop the delete partway. Putting `.git` back, when+ // that works, leaves a worktree that a retry can remove.+ const gitFileContents = yield* fileSystem+ .readFileString(gitFile)+ .pipe(Effect.mapError(() => notAWorktree));+ yield* fileSystem.remove(worktreePath, { recursive: true }).pipe(+ Effect.tapError(() => fileSystem.writeFileString(gitFile, gitFileContents).pipe(Effect.ignore)),+ Effect.mapError((cause) => refuse(`failed to delete '${worktreePath}'`, cause)),+ );+ // The folder is gone, so Git only drops the worktree's metadata.+ return yield* input.run(["worktree", "remove", "--force", "--force", "--", worktreePath]);+});