The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { GitCommandError } from "@t3tools/contracts"; |
| 2 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as FileSystem from "effect/FileSystem"; |
| 5 | import * as Option from "effect/Option"; |
| 6 | import * as Path from "effect/Path"; |
| 7 | |
| 8 | import type * as GitVcsDriver from "./GitVcsDriver.ts"; |
| 9 | |
| 10 | const INDEX_LIST_MAX_BYTES = 64 * 1024 * 1024; |
| 11 | |
| 12 | /** |
| 13 | * git-annex replaces a linked worktree's `.git` file with a symlink to its admin |
| 14 | * directory, so its symlinks into `.git/annex` resolve. Git then refuses to remove it. |
| 15 | */ |
| 16 | const annexedAdminDir = Effect.fn("WorktreeRemoval.annexedAdminDir")( |
| 17 | function* (worktreePath: string) { |
| 18 | const fileSystem = yield* FileSystem.FileSystem; |
| 19 | const path = yield* Path.Path; |
| 20 | const adminDir = path.resolve( |
| 21 | worktreePath, |
| 22 | yield* fileSystem.readLink(path.join(worktreePath, ".git")), |
| 23 | ); |
| 24 | const pointsBackTo = path.dirname( |
| 25 | path.resolve( |
| 26 | adminDir, |
| 27 | (yield* fileSystem.readFileString(path.join(adminDir, "gitdir"))).trim(), |
| 28 | ), |
| 29 | ); |
| 30 | return (yield* fileSystem.realPath(pointsBackTo)) === (yield* fileSystem.realPath(worktreePath)) |
| 31 | ? Option.some(adminDir) |
| 32 | : Option.none(); |
| 33 | }, |
| 34 | Effect.orElseSucceed(() => Option.none<string>()), |
| 35 | ); |
| 36 | |
| 37 | export const isLinkedWorktree = Effect.fn("WorktreeRemoval.isLinkedWorktree")(function* ( |
| 38 | worktreePath: string, |
| 39 | ) { |
| 40 | const fileSystem = yield* FileSystem.FileSystem; |
| 41 | const path = yield* Path.Path; |
| 42 | return ( |
| 43 | (yield* fileSystem.stat(path.join(worktreePath, ".git"))).type === "File" || |
| 44 | Option.isSome(yield* annexedAdminDir(worktreePath)) |
| 45 | ); |
| 46 | }); |
| 47 | |
| 48 | /** |
| 49 | * Git for Windows before 2.54 follows NTFS junctions; newer Git leaves them behind. |
| 50 | * On Windows, mirror Git's removal checks, then delete with Node's `rm`, which |
| 51 | * unlinks junctions without following them. Git then removes the worktree metadata. |
| 52 | */ |
| 53 | export const removeLinkedWorktree = Effect.fn("WorktreeRemoval.removeLinkedWorktree")(function* < |
| 54 | A, |
| 55 | E, |
| 56 | R, |
| 57 | >(input: { |
| 58 | readonly operation: string; |
| 59 | readonly cwd: string; |
| 60 | readonly worktreePath: string; |
| 61 | readonly force: boolean; |
| 62 | readonly execute: GitVcsDriver.GitVcsDriver["Service"]["execute"]; |
| 63 | readonly run: (args: ReadonlyArray<string>) => Effect.Effect<A, E, R>; |
| 64 | }) { |
| 65 | const fileSystem = yield* FileSystem.FileSystem; |
| 66 | const path = yield* Path.Path; |
| 67 | const worktreePath = input.worktreePath; |
| 68 | const gitFile = path.join(worktreePath, ".git"); |
| 69 | // Git refuses to remove a worktree with untracked files unless forced, but |
| 70 | // its check honors `status.showUntrackedFiles=no` and would delete them. |
| 71 | const statusConfig = ["-c", "status.showUntrackedFiles=normal"]; |
| 72 | // Git's own refusals, worded the way it prints them. |
| 73 | const refuse = (message: string, cause?: unknown) => |
| 74 | new GitCommandError({ |
| 75 | operation: input.operation, |
| 76 | command: "git worktree remove", |
| 77 | cwd: input.cwd, |
| 78 | detail: `fatal: ${message}`, |
| 79 | ...(cause === undefined ? {} : { cause }), |
| 80 | }); |
| 81 | const annexed = yield* annexedAdminDir(worktreePath); |
| 82 | if (Option.isSome(annexed)) { |
| 83 | const adminDir = annexed.value; |
| 84 | const writeGitFile = fileSystem.writeFileString(gitFile, `gitdir: ${adminDir}\n`); |
| 85 | // A kept worktree's annexed files resolve only through the symlink; a gitdir |
| 86 | // file is the fallback when it cannot be recreated. |
| 87 | yield* Effect.addFinalizer(() => |
| 88 | fileSystem.exists(worktreePath).pipe( |
| 89 | Effect.flatMap((kept) => |
| 90 | kept |
| 91 | ? fileSystem.remove(gitFile, { force: true }).pipe( |
| 92 | Effect.andThen(fileSystem.symlink(adminDir, gitFile)), |
| 93 | Effect.catch(() => writeGitFile), |
| 94 | ) |
| 95 | : Effect.void, |
| 96 | ), |
| 97 | Effect.ignore, |
| 98 | ), |
| 99 | ); |
| 100 | yield* fileSystem.remove(gitFile).pipe( |
| 101 | Effect.andThen(writeGitFile), |
| 102 | Effect.mapError((cause) => refuse(`failed to replace '${gitFile}'`, cause)), |
| 103 | ); |
| 104 | } |
| 105 | const linked = |
| 106 | (yield* HostProcess.isWindows) && |
| 107 | (yield* fileSystem.stat(gitFile).pipe( |
| 108 | Effect.map((info) => info.type === "File"), |
| 109 | Effect.orElseSucceed(() => false), |
| 110 | )); |
| 111 | if (!linked) { |
| 112 | return yield* input.run([ |
| 113 | ...statusConfig, |
| 114 | "worktree", |
| 115 | "remove", |
| 116 | ...(input.force ? ["--force"] : []), |
| 117 | "--", |
| 118 | worktreePath, |
| 119 | ]); |
| 120 | } |
| 121 | |
| 122 | const gitOutput = (cwd: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) => |
| 123 | input |
| 124 | .execute({ |
| 125 | operation: input.operation, |
| 126 | cwd, |
| 127 | args, |
| 128 | maxOutputBytes: INDEX_LIST_MAX_BYTES, |
| 129 | ...(env === undefined ? {} : { env }), |
| 130 | }) |
| 131 | .pipe(Effect.map((result) => result.stdout)); |
| 132 | const samePath = (left: string, right: string) => |
| 133 | Effect.all([fileSystem.realPath(left), fileSystem.realPath(right)]).pipe( |
| 134 | Effect.map(([a, b]) => a.toLowerCase() === b.toLowerCase()), |
| 135 | Effect.orElseSucceed(() => false), |
| 136 | ); |
| 137 | |
| 138 | // A registered worktree of this repository: its `.git` file names an admin |
| 139 | // directory under the common `worktrees/`, whose `gitdir` points back. |
| 140 | const notAWorktree = refuse(`'${worktreePath}' is not a working tree`); |
| 141 | const adminDir = path.resolve( |
| 142 | worktreePath, |
| 143 | (yield* gitOutput(worktreePath, ["rev-parse", "--absolute-git-dir"]).pipe( |
| 144 | Effect.mapError(() => notAWorktree), |
| 145 | )).trim(), |
| 146 | ); |
| 147 | const commonDir = path.resolve( |
| 148 | input.cwd, |
| 149 | (yield* gitOutput(input.cwd, ["rev-parse", "--git-common-dir"])).trim(), |
| 150 | ); |
| 151 | const pointsBack = yield* fileSystem.readFileString(path.join(adminDir, "gitdir")).pipe( |
| 152 | Effect.flatMap((gitdir) => samePath(path.resolve(adminDir, gitdir.trim()), gitFile)), |
| 153 | Effect.orElseSucceed(() => false), |
| 154 | ); |
| 155 | if (!pointsBack || !(yield* samePath(path.dirname(adminDir), path.join(commonDir, "worktrees")))) |
| 156 | return yield* notAWorktree; |
| 157 | // Git counts the file's existence as a lock. T3 passes at most one |
| 158 | // `--force`, which never removes a locked worktree. Anything but a |
| 159 | // confirmed absence refuses. |
| 160 | const lockFile = path.join(adminDir, "locked"); |
| 161 | const locked = yield* fileSystem.stat(lockFile).pipe( |
| 162 | Effect.as(true), |
| 163 | Effect.catch((error) => |
| 164 | error.reason._tag === "NotFound" |
| 165 | ? Effect.succeed(false) |
| 166 | : Effect.fail(refuse(`cannot inspect the lock of '${worktreePath}'`, error)), |
| 167 | ), |
| 168 | ); |
| 169 | if (locked) { |
| 170 | const reason = (yield* fileSystem.readFileString(lockFile).pipe(Effect.option)).pipe( |
| 171 | Option.map((text) => text.trim()), |
| 172 | Option.getOrElse(() => ""), |
| 173 | ); |
| 174 | return yield* refuse( |
| 175 | reason === "" |
| 176 | ? "cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first" |
| 177 | : `cannot remove a locked working tree, lock reason: ${reason}\nuse 'remove -f -f' to override or unlock first`, |
| 178 | ); |
| 179 | } |
| 180 | if (!input.force) { |
| 181 | // Bound like Git's own check, so `core.worktree` can't point it elsewhere. |
| 182 | const boundEnv = { GIT_DIR: gitFile, GIT_WORK_TREE: worktreePath }; |
| 183 | const submodules = refuse("working trees containing submodules cannot be moved or removed"); |
| 184 | // An unreadable path counts as present, so a doubt refuses. |
| 185 | const present = (target: string) => |
| 186 | fileSystem.exists(target).pipe(Effect.orElseSucceed(() => true)); |
| 187 | if (yield* present(path.join(adminDir, "modules"))) return yield* submodules; |
| 188 | const index = yield* gitOutput(worktreePath, ["ls-files", "--stage", "-z"], boundEnv); |
| 189 | for (const entry of index.split("\0")) { |
| 190 | if (!entry.startsWith("160000 ")) continue; |
| 191 | const submodule = entry.slice(entry.indexOf("\t") + 1); |
| 192 | if (yield* present(path.join(worktreePath, submodule, ".git"))) return yield* submodules; |
| 193 | } |
| 194 | const status = yield* gitOutput( |
| 195 | worktreePath, |
| 196 | [...statusConfig, "status", "--porcelain", "--ignore-submodules=none"], |
| 197 | boundEnv, |
| 198 | ); |
| 199 | if (status !== "") |
| 200 | return yield* refuse( |
| 201 | `'${worktreePath}' contains modified or untracked files, use --force to delete it`, |
| 202 | ); |
| 203 | } |
| 204 | |
| 205 | // A file held open can stop the delete partway. Putting `.git` back, when |
| 206 | // that works, leaves a worktree that a retry can remove. |
| 207 | const gitFileContents = yield* fileSystem |
| 208 | .readFileString(gitFile) |
| 209 | .pipe(Effect.mapError(() => notAWorktree)); |
| 210 | yield* fileSystem.remove(worktreePath, { recursive: true }).pipe( |
| 211 | Effect.tapError(() => fileSystem.writeFileString(gitFile, gitFileContents).pipe(Effect.ignore)), |
| 212 | Effect.mapError((cause) => refuse(`failed to delete '${worktreePath}'`, cause)), |
| 213 | ); |
| 214 | // The folder is gone, so Git only drops the worktree's metadata. |
| 215 | return yield* input.run(["worktree", "remove", "--force", "--force", "--", worktreePath]); |
| 216 | }, Effect.scoped); |