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

worktreeRemoval.ts

164 lines6.8 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​
12/**
13 * Removes the linked worktree at `worktreePath` by running `git worktree
14 * remove` through `run`.
15 *
16 * Git for Windows before 2.54 follows NTFS junctions while it deletes a
17 * worktree, and deletes what they point to, such as a shared node_modules.
18 * Later versions skip junctions but leave them, and the folders holding them,
19 * behind. On Windows, Git therefore never deletes the files: this makes the
20 * checks `git worktree remove` makes before deleting (builtin/worktree.c),
21 * deletes the folder with Node's `rm`, which unlinks junctions without
22 * following them, and then has Git drop the now-missing worktree's metadata.
23 * Git elsewhere only unlinks links, so other hosts run Git as before.
24 */
25export const removeLinkedWorktree = Effect.fn("WorktreeRemoval.removeLinkedWorktree")(function* <
26 A,
27 E,
28 R,
29>(input: {
30 readonly operation: string;
31 readonly cwd: string;
32 readonly worktreePath: string;
33 readonly force: boolean;
34 readonly execute: GitVcsDriver.GitVcsDriver["Service"]["execute"];
35 readonly run: (args: ReadonlyArray<string>) => Effect.Effect<A, E, R>;
36}) {
37 const fileSystem = yield* FileSystem.FileSystem;
38 const path = yield* Path.Path;
39 const worktreePath = input.worktreePath;
40 const gitFile = path.join(worktreePath, ".git");
41 // Git refuses to remove a worktree with untracked files unless forced, but
42 // its check honors `status.showUntrackedFiles=no` and would delete them.
43 const statusConfig = ["-c", "status.showUntrackedFiles=normal"];
44 const linked =
45 (yield* HostProcess.isWindows) &&
46 (yield* fileSystem.stat(gitFile).pipe(
47 Effect.map((info) => info.type === "File"),
48 Effect.orElseSucceed(() => false),
49 ));
50 if (!linked) {
51 return yield* input.run([
52 ...statusConfig,
53 "worktree",
54 "remove",
55 ...(input.force ? ["--force"] : []),
56 "--",
57 worktreePath,
58 ]);
59 }
60​
61 // Git's own refusals, worded the way it prints them.
62 const refuse = (message: string, cause?: unknown) =>
63 new GitCommandError({
64 operation: input.operation,
65 command: "git worktree remove",
66 cwd: input.cwd,
67 detail: `fatal: ${message}`,
68 ...(cause === undefined ? {} : { cause }),
69 });
70 const gitOutput = (cwd: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
71 input
72 .execute({
73 operation: input.operation,
74 cwd,
75 args,
76 maxOutputBytes: INDEX_LIST_MAX_BYTES,
77 ...(env === undefined ? {} : { env }),
78 })
79 .pipe(Effect.map((result) => result.stdout));
80 const samePath = (left: string, right: string) =>
81 Effect.all([fileSystem.realPath(left), fileSystem.realPath(right)]).pipe(
82 Effect.map(([a, b]) => a.toLowerCase() === b.toLowerCase()),
83 Effect.orElseSucceed(() => false),
84 );
85​
86 // A registered worktree of this repository: its `.git` file names an admin
87 // directory under the common `worktrees/`, whose `gitdir` points back.
88 const notAWorktree = refuse(`'${worktreePath}' is not a working tree`);
89 const adminDir = path.resolve(
90 worktreePath,
91 (yield* gitOutput(worktreePath, ["rev-parse", "--absolute-git-dir"]).pipe(
92 Effect.mapError(() => notAWorktree),
93 )).trim(),
94 );
95 const commonDir = path.resolve(
96 input.cwd,
97 (yield* gitOutput(input.cwd, ["rev-parse", "--git-common-dir"])).trim(),
98 );
99 const pointsBack = yield* fileSystem.readFileString(path.join(adminDir, "gitdir")).pipe(
100 Effect.flatMap((gitdir) => samePath(path.resolve(adminDir, gitdir.trim()), gitFile)),
101 Effect.orElseSucceed(() => false),
102 );
103 if (!pointsBack || !(yield* samePath(path.dirname(adminDir), path.join(commonDir, "worktrees"))))
104 return yield* notAWorktree;
105 // Git counts the file's existence as a lock. T3 passes at most one
106 // `--force`, which never removes a locked worktree. Anything but a
107 // confirmed absence refuses.
108 const lockFile = path.join(adminDir, "locked");
109 const locked = yield* fileSystem.stat(lockFile).pipe(
110 Effect.as(true),
111 Effect.catch((error) =>
112 error.reason._tag === "NotFound"
113 ? Effect.succeed(false)
114 : Effect.fail(refuse(`cannot inspect the lock of '${worktreePath}'`, error)),
115 ),
116 );
117 if (locked) {
118 const reason = (yield* fileSystem.readFileString(lockFile).pipe(Effect.option)).pipe(
119 Option.map((text) => text.trim()),
120 Option.getOrElse(() => ""),
121 );
122 return yield* refuse(
123 reason === ""
124 ? "cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"
125 : `cannot remove a locked working tree, lock reason: ${reason}\nuse 'remove -f -f' to override or unlock first`,
126 );
127 }
128 if (!input.force) {
129 // Bound like Git's own check, so `core.worktree` can't point it elsewhere.
130 const boundEnv = { GIT_DIR: gitFile, GIT_WORK_TREE: worktreePath };
131 const submodules = refuse("working trees containing submodules cannot be moved or removed");
132 // An unreadable path counts as present, so a doubt refuses.
133 const present = (target: string) =>
134 fileSystem.exists(target).pipe(Effect.orElseSucceed(() => true));
135 if (yield* present(path.join(adminDir, "modules"))) return yield* submodules;
136 const index = yield* gitOutput(worktreePath, ["ls-files", "--stage", "-z"], boundEnv);
137 for (const entry of index.split("\0")) {
138 if (!entry.startsWith("160000 ")) continue;
139 const submodule = entry.slice(entry.indexOf("\t") + 1);
140 if (yield* present(path.join(worktreePath, submodule, ".git"))) return yield* submodules;
141 }
142 const status = yield* gitOutput(
143 worktreePath,
144 [...statusConfig, "status", "--porcelain", "--ignore-submodules=none"],
145 boundEnv,
146 );
147 if (status !== "")
148 return yield* refuse(
149 `'${worktreePath}' contains modified or untracked files, use --force to delete it`,
150 );
151 }
152​
153 // A file held open can stop the delete partway. Putting `.git` back, when
154 // that works, leaves a worktree that a retry can remove.
155 const gitFileContents = yield* fileSystem
156 .readFileString(gitFile)
157 .pipe(Effect.mapError(() => notAWorktree));
158 yield* fileSystem.remove(worktreePath, { recursive: true }).pipe(
159 Effect.tapError(() => fileSystem.writeFileString(gitFile, gitFileContents).pipe(Effect.ignore)),
160 Effect.mapError((cause) => refuse(`failed to delete '${worktreePath}'`, cause)),
161 );
162 // The folder is gone, so Git only drops the worktree's metadata.
163 return yield* input.run(["worktree", "remove", "--force", "--force", "--", worktreePath]);
164});