Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

worktreeRemoval.ts

275 lines10.9 KB

1import { GitCommandError } from "@t3tools/contracts";
2import * as HostProcess from "@t3tools/shared/HostProcess";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Option from "effect/Option";
6import * as Path from "effect/Path";
7​
8import type * as GitVcsDriver from "./GitVcsDriver.ts";
9​
10const INDEX_LIST_MAX_BYTES = 64 * 1024 * 1024;
11// Git's own removal and the checks that mirror it share one bound.
12export const WORKTREE_REMOVE_TIMEOUT_MS = 5 * 60_000;
13​
14/**
15 * git-annex replaces a linked worktree's `.git` file with a symlink to its admin
16 * directory, so its symlinks into `.git/annex` resolve. Git then refuses to remove it.
17 */
18const annexedAdminDir = Effect.fn("WorktreeRemoval.annexedAdminDir")(
19 function* (worktreePath: string) {
20 const fileSystem = yield* FileSystem.FileSystem;
21 const path = yield* Path.Path;
22 const adminDir = path.resolve(
23 worktreePath,
24 yield* fileSystem.readLink(path.join(worktreePath, ".git")),
25 );
26 const pointsBackTo = path.dirname(
27 path.resolve(
28 adminDir,
29 (yield* fileSystem.readFileString(path.join(adminDir, "gitdir"))).trim(),
30 ),
31 );
32 return (yield* fileSystem.realPath(pointsBackTo)) === (yield* fileSystem.realPath(worktreePath))
33 ? Option.some(adminDir)
34 : Option.none();
35 },
36 Effect.orElseSucceed(() => Option.none<string>()),
37);
38​
39export const isLinkedWorktree = Effect.fn("WorktreeRemoval.isLinkedWorktree")(function* (
40 worktreePath: string,
41) {
42 const fileSystem = yield* FileSystem.FileSystem;
43 const path = yield* Path.Path;
44 return (
45 (yield* fileSystem.stat(path.join(worktreePath, ".git"))).type === "File" ||
46 Option.isSome(yield* annexedAdminDir(worktreePath))
47 );
48});
49​
50/**
51 * Git drops a worktree's metadata even when it fails to delete the folder partway, leaving a
52 * folder no repository lists; Git for Windows before 2.54 also follows NTFS junctions. So mirror
53 * Git's removal checks, delete with Node's `rm`, which unlinks junctions without following them,
54 * and only then let Git remove the metadata.
55 */
56export const removeLinkedWorktree = Effect.fn("WorktreeRemoval.removeLinkedWorktree")(function* <
57 A,
58 E,
59 R,
60>(input: {
61 readonly operation: string;
62 readonly cwd: string;
63 readonly worktreePath: string;
64 readonly force: boolean;
65 readonly execute: GitVcsDriver.GitVcsDriver["Service"]["execute"];
66 readonly run: (args: ReadonlyArray<string>, cwd: string) => Effect.Effect<A, E, R>;
67}) {
68 const fileSystem = yield* FileSystem.FileSystem;
69 const path = yield* Path.Path;
70 // Deleting through a symlink would only unlink the alias and leave the checkout.
71 const worktreePath = yield* fileSystem
72 .realPath(input.worktreePath)
73 .pipe(Effect.orElseSucceed(() => input.worktreePath));
74 const gitFile = path.join(worktreePath, ".git");
75 // Git refuses to remove a worktree with untracked files unless forced, but
76 // its check honors `status.showUntrackedFiles=no` and would delete them.
77 const statusConfig = ["-c", "status.showUntrackedFiles=normal"];
78 // Git's own refusals, worded the way it prints them.
79 const refuse = (message: string, cause?: unknown) =>
80 new GitCommandError({
81 operation: input.operation,
82 command: "git worktree remove",
83 cwd: input.cwd,
84 detail: `fatal: ${message}`,
85 ...(cause === undefined ? {} : { cause }),
86 });
87 const annexed = yield* annexedAdminDir(worktreePath);
88 if (Option.isSome(annexed)) {
89 const adminDir = annexed.value;
90 const writeGitFile = fileSystem.writeFileString(gitFile, `gitdir: ${adminDir}\n`);
91 // A kept worktree's annexed files resolve only through the symlink; a gitdir
92 // file is the fallback when it cannot be recreated.
93 yield* Effect.addFinalizer(() =>
94 fileSystem.exists(worktreePath).pipe(
95 Effect.flatMap((kept) =>
96 kept
97 ? fileSystem.remove(gitFile, { force: true }).pipe(
98 Effect.andThen(fileSystem.symlink(adminDir, gitFile)),
99 Effect.catch(() => writeGitFile),
100 )
101 : Effect.void,
102 ),
103 Effect.ignore,
104 ),
105 );
106 yield* fileSystem.remove(gitFile).pipe(
107 Effect.andThen(writeGitFile),
108 Effect.mapError((cause) => refuse(`failed to replace '${gitFile}'`, cause)),
109 );
110 }
111 const linked = yield* fileSystem.stat(gitFile).pipe(
112 Effect.map((info) => info.type === "File"),
113 Effect.orElseSucceed(() => false),
114 );
115 if (!linked) {
116 return yield* input.run(
117 [
118 ...statusConfig,
119 "worktree",
120 "remove",
121 ...(input.force ? ["--force"] : []),
122 "--",
123 worktreePath,
124 ],
125 input.cwd,
126 );
127 }
128​
129 const gitOutput = (cwd: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
130 input
131 .execute({
132 operation: input.operation,
133 cwd,
134 args,
135 maxOutputBytes: INDEX_LIST_MAX_BYTES,
136 timeoutMs: WORKTREE_REMOVE_TIMEOUT_MS,
137 ...(env === undefined ? {} : { env }),
138 })
139 .pipe(Effect.map((result) => result.stdout));
140 // Windows paths ignore case. Elsewhere two repositories' paths can differ only in case,
141 // so the files themselves are compared.
142 const samePath = (yield* HostProcess.isWindows)
143 ? (left: string, right: string) =>
144 Effect.all([fileSystem.realPath(left), fileSystem.realPath(right)]).pipe(
145 Effect.map(([a, b]) => a.toLowerCase() === b.toLowerCase()),
146 Effect.orElseSucceed(() => false),
147 )
148 : (left: string, right: string) =>
149 Effect.all([fileSystem.stat(left), fileSystem.stat(right)]).pipe(
150 Effect.map(
151 ([a, b]) =>
152 a.dev === b.dev &&
153 Option.isSome(a.ino) &&
154 a.ino.value === Option.getOrUndefined(b.ino),
155 ),
156 Effect.orElseSucceed(() => false),
157 );
158​
159 // A registered worktree of this repository: its `.git` file names an admin
160 // directory under the common `worktrees/`, whose `gitdir` points back.
161 const notAWorktree = refuse(`'${worktreePath}' is not a working tree`);
162 const adminDir = path.resolve(
163 worktreePath,
164 (yield* gitOutput(worktreePath, ["rev-parse", "--absolute-git-dir"]).pipe(
165 Effect.mapError(() => notAWorktree),
166 )).replace(/\n$/, ""),
167 );
168 // `safe.bareRepository=explicit` refuses to discover a bare repository from its own folder,
169 // so the common directory comes from the worktree, and `cwd` only has to be or discover it.
170 const commonDir = path.resolve(
171 worktreePath,
172 (yield* gitOutput(worktreePath, ["rev-parse", "--git-common-dir"])).replace(/\n$/, ""),
173 );
174 if (!(yield* samePath(input.cwd, commonDir))) {
175 const cwdCommonDir = path.resolve(
176 input.cwd,
177 (yield* gitOutput(input.cwd, ["rev-parse", "--git-common-dir"])).replace(/\n$/, ""),
178 );
179 if (!(yield* samePath(cwdCommonDir, commonDir))) return yield* notAWorktree;
180 }
181 const pointsBack = yield* fileSystem.readFileString(path.join(adminDir, "gitdir")).pipe(
182 // Folders, not `.git` files: a hard-linked copy of the checkout shares its `.git` file.
183 Effect.flatMap((gitdir) => {
184 const backlink = path.resolve(adminDir, gitdir.trim());
185 return path.basename(backlink) === ".git"
186 ? samePath(path.dirname(backlink), worktreePath)
187 : Effect.succeed(false);
188 }),
189 Effect.orElseSucceed(() => false),
190 );
191 if (!pointsBack || !(yield* samePath(path.dirname(adminDir), path.join(commonDir, "worktrees"))))
192 return yield* notAWorktree;
193 // Git counts the file's existence as a lock. T3 passes at most one
194 // `--force`, which never removes a locked worktree. Anything but a
195 // confirmed absence refuses.
196 const lockFile = path.join(adminDir, "locked");
197 const locked = yield* fileSystem.stat(lockFile).pipe(
198 Effect.as(true),
199 Effect.catch((error) =>
200 error.reason._tag === "NotFound"
201 ? Effect.succeed(false)
202 : Effect.fail(refuse(`cannot inspect the lock of '${worktreePath}'`, error)),
203 ),
204 );
205 if (locked) {
206 const reason = (yield* fileSystem.readFileString(lockFile).pipe(Effect.option)).pipe(
207 Option.map((text) => text.trim()),
208 Option.getOrElse(() => ""),
209 );
210 return yield* refuse(
211 reason === ""
212 ? "cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"
213 : `cannot remove a locked working tree, lock reason: ${reason}\nuse 'remove -f -f' to override or unlock first`,
214 );
215 }
216 if (!input.force) {
217 // Bound like Git's own check, so `core.worktree` can't point it elsewhere.
218 const boundEnv = { GIT_DIR: gitFile, GIT_WORK_TREE: worktreePath };
219 const submodules = refuse("working trees containing submodules cannot be moved or removed");
220 // An unreadable path counts as present, so a doubt refuses.
221 const present = (target: string) =>
222 fileSystem.exists(target).pipe(Effect.orElseSucceed(() => true));
223 if (yield* present(path.join(adminDir, "modules"))) return yield* submodules;
224 const index = yield* gitOutput(worktreePath, ["ls-files", "--stage", "-z"], boundEnv);
225 for (const entry of index.split("\0")) {
226 if (!entry.startsWith("160000 ")) continue;
227 const submodule = entry.slice(entry.indexOf("\t") + 1);
228 if (yield* present(path.join(worktreePath, submodule, ".git"))) return yield* submodules;
229 }
230 const status = yield* gitOutput(
231 worktreePath,
232 [...statusConfig, "status", "--porcelain", "--ignore-submodules=none"],
233 boundEnv,
234 );
235 if (status !== "")
236 return yield* refuse(
237 `'${worktreePath}' contains modified or untracked files, use --force to delete it`,
238 );
239 }
240​
241 // A file held open can stop the delete partway, so `.git` goes last and a retry still
242 // finds the worktree. Node's recursive `rm` reports the first error while sibling
243 // deletes still run, so `.git` must not be among them.
244 const gitFileContents = yield* fileSystem
245 .readFileString(gitFile)
246 .pipe(Effect.mapError(() => notAWorktree));
247 const failedToDelete = (cause: unknown) => refuse(`failed to delete '${worktreePath}'`, cause);
248 for (const name of yield* fileSystem
249 .readDirectory(worktreePath)
250 .pipe(Effect.mapError(failedToDelete))) {
251 if (name === ".git") continue;
252 yield* fileSystem
253 .remove(path.join(worktreePath, name), { recursive: true })
254 .pipe(Effect.mapError(failedToDelete));
255 }
256 yield* fileSystem.remove(gitFile).pipe(Effect.mapError(failedToDelete));
257 yield* fileSystem.remove(worktreePath, { recursive: true }).pipe(
258 Effect.tapError(() => fileSystem.writeFileString(gitFile, gitFileContents).pipe(Effect.ignore)),
259 Effect.mapError(failedToDelete),
260 );
261 // The folder is gone, so Git only drops the worktree's metadata. The caller's `cwd` may
262 // have been inside it; the common Git directory survives, and is named explicitly
263 // because `safe.bareRepository=explicit` refuses to discover it.
264 return yield* input.run(
265 [
266 `--git-dir=${commonDir}`,
267 "worktree",
268 "remove",
269 ...(input.force ? ["--force"] : []),
270 "--",
271 worktreePath,
272 ],
273 commonDir,
274 );
275}, Effect.scoped);