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

WorkspaceWorktrees.ts

354 lines14.0 KB

1/**
2 * Isolated runs in a multi-repo project get a container mirroring the project: one worktree per
3 * repository at its relative path plus links to the other top-level entries, so shared
4 * instructions resolve as in the project. The thread's worktree path is the container.
5 */
6import { GitCommandError, type VcsRepository } from "@t3tools/contracts";
7import {
8 flattenTemporaryWorktreeBranchName,
9 isTemporaryWorktreeBranch,
10 WORKTREE_BRANCH_PREFIX,
11} from "@t3tools/shared/git";
12import * as Context from "effect/Context";
13import * as Effect from "effect/Effect";
14import * as FileSystem from "effect/FileSystem";
15import * as Layer from "effect/Layer";
16import * as Path from "effect/Path";
17import type * as PlatformError from "effect/PlatformError";
18​
19import * as ServerConfig from "../config.ts";
20import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
21import * as WorkspaceRepositories from "../workspace/WorkspaceRepositories.ts";
22​
23export interface CreateWorkspaceWorktreeInput {
24 readonly workspaceRoot: string;
25 readonly repositories: ReadonlyArray<VcsRepository>;
26 readonly branch: string;
27 /** Fetch each repository's default branch and start from the remote's copy. */
28 readonly startFromOrigin: boolean;
30​
31export class WorkspaceWorktrees extends Context.Service<
32 WorkspaceWorktrees,
33 {
34 /**
35 * Create a container with a worktree per repository, each started from its repository's
36 * default branch. The container is reported as soon as it exists so a caller can remove a
37 * partial one with `remove` if a later repository fails.
38 */
39 readonly create: (
40 input: CreateWorkspaceWorktreeInput,
41 options?: { readonly onContainerClaimed?: (path: string) => Effect.Effect<void> },
42 ) => Effect.Effect<{ readonly path: string; readonly branch: string }, GitCommandError>;
43 /** Rename the branch in every repository; the first repository decides the final name. */
44 readonly renameBranch: (input: {
45 readonly path: string;
46 readonly oldBranch: string;
47 readonly newBranch: string;
48 readonly exactName?: boolean;
49 }) => Effect.Effect<{ readonly branch: string }, GitCommandError>;
50 /** Whether `path` is a container this service created. */
51 readonly isContainer: (path: string) => Effect.Effect<boolean>;
52 /**
53 * Remove every repository's worktree, then the links and folders the container added.
54 * Anything else left in the container is kept for the user.
55 */
56 readonly remove: (input: {
57 readonly workspaceRoot: string;
58 readonly path: string;
59 readonly force: boolean;
60 }) => Effect.Effect<void, GitCommandError>;
61 }
62>()("t3/git/WorkspaceWorktrees") {}
63​
64const make = Effect.gen(function* () {
65 const fileSystem = yield* FileSystem.FileSystem;
66 const path = yield* Path.Path;
67 const config = yield* ServerConfig.ServerConfig;
68 const git = yield* GitVcsDriver.GitVcsDriver;
69 const workspaceRepositories = yield* WorkspaceRepositories.WorkspaceRepositories;
70​
71 const fail = (operation: string, cwd: string, detail: string, cause?: unknown) =>
72 new GitCommandError({ operation, command: "worktree", cwd, detail, cause });
73​
74 const join = (root: string, relativePath: string) => path.join(root, ...relativePath.split("/"));
75​
76 const isInsideWorktreesDir = (target: string) => {
77 const relative = path.relative(config.worktreesDir, target);
78 return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
79 };
80​
81 const hasCommit = (cwd: string, refName: string) =>
82 git
83 .execute({
84 operation: "WorkspaceWorktrees.hasCommit",
85 cwd,
86 args: ["rev-parse", "--verify", "--quiet", `${refName}^{commit}`],
87 allowNonZeroExit: true,
88 })
89 .pipe(Effect.map((result) => result.exitCode === 0));
90​
91 // The repository's default branch (from its primary remote), or its current checkout.
92 const resolveStart = Effect.fn("WorkspaceWorktrees.resolveStart")(function* (
93 cwd: string,
94 startFromOrigin: boolean,
95 ) {
96 const remote = yield* git.resolvePrimaryRemoteName(cwd).pipe(Effect.option);
97 const defaultBranch =
98 remote._tag === "None"
99 ? null
100 : yield* git
101 .resolveDefaultBranchName(cwd, remote.value)
102 .pipe(Effect.orElseSucceed(() => null));
103 if (remote._tag === "Some" && defaultBranch !== null && startFromOrigin) {
104 yield* git.fetchRemote({ cwd, remoteName: remote.value, refName: defaultBranch });
105 if (
106 yield* git.remoteBranchExists({ cwd, remoteName: remote.value, refName: defaultBranch })
107 ) {
108 const tracking = yield* git.resolveRemoteTrackingCommit({
109 cwd,
110 refName: defaultBranch,
111 fallbackRemoteName: remote.value,
112 });
113 return { startRef: tracking.commitSha, baseRef: defaultBranch };
114 }
115 }
116 if (defaultBranch !== null && (yield* hasCommit(cwd, defaultBranch))) {
117 return { startRef: defaultBranch, baseRef: defaultBranch };
118 }
119 return { startRef: "HEAD", baseRef: "HEAD" };
120 });
121​
122 // Links are a convenience, so a platform that refuses one only loses that entry. A
123 // `.code-workspace` file defines which folders belong to the workspace, so with one only its
124 // listed folders are linked, along with top-level files and dot-folders, which usually hold
125 // workspace-wide configuration. Without one, every top-level entry is linked.
126 const linkSharedEntries = Effect.fn("WorkspaceWorktrees.linkSharedEntries")(function* (
127 workspaceRoot: string,
128 container: string,
129 ) {
130 const layout = yield* workspaceRepositories.describe(workspaceRoot);
131 const repositoryFolders = new Set(
132 layout.repositories.map((repository) => repository.relativePath.split("/")[0]),
133 );
134 const listedFolders =
135 layout.listedFolders === null
136 ? null
137 : new Set(layout.listedFolders.map((folder) => folder.split("/")[0]));
138 const names = yield* fileSystem
139 .readDirectory(workspaceRoot)
140 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
141 for (const name of names) {
142 if (repositoryFolders.has(name)) continue;
143 const target = path.join(workspaceRoot, name);
144 if (listedFolders !== null && !name.startsWith(".") && !listedFolders.has(name)) {
145 const isDirectory = yield* fileSystem.stat(target).pipe(
146 Effect.map((info) => info.type === "Directory"),
147 Effect.orElseSucceed(() => false),
148 );
149 if (isDirectory) continue;
150 }
151 yield* fileSystem.symlink(target, path.join(container, name)).pipe(
152 Effect.catch((cause) =>
153 Effect.logWarning("Could not link a workspace entry into an isolated run", {
154 container,
155 name,
156 cause,
157 }),
158 ),
159 );
160 }
161 });
162​
163 const create: WorkspaceWorktrees["Service"]["create"] = Effect.fn("WorkspaceWorktrees.create")(
164 function* (input, options) {
165 const operation = "WorkspaceWorktrees.create";
166 // A plain `t3` branch in any repository blocks `t3/*`, so all of them use `t3-<hash>`.
167 let branch = input.branch;
168 if (isTemporaryWorktreeBranch(branch)) {
169 for (const repository of input.repositories) {
170 const cwd = join(input.workspaceRoot, repository.relativePath);
171 if (yield* hasCommit(cwd, `refs/heads/${WORKTREE_BRANCH_PREFIX}`)) {
172 branch = flattenTemporaryWorktreeBranchName(branch);
173 break;
174 }
175 }
176 }
177 const container = path.join(
178 config.worktreesDir,
179 path.basename(input.workspaceRoot),
180 branch.replace(/\//g, "-"),
181 );
182 if (yield* fileSystem.exists(container).pipe(Effect.orElseSucceed(() => true))) {
183 return yield* fail(operation, input.workspaceRoot, `${container} already exists.`);
184 }
185 yield* fileSystem
186 .makeDirectory(container, { recursive: true })
187 .pipe(
188 Effect.mapError((cause) =>
189 fail(operation, input.workspaceRoot, `Could not create ${container}.`, cause),
190 ),
191 );
192 if (options?.onContainerClaimed) yield* options.onContainerClaimed(container);
193 // Link first: a `.code-workspace` link tells `remove` which folders to clean up if a
194 // repository below fails.
195 yield* linkSharedEntries(input.workspaceRoot, container);
196 for (const repository of input.repositories) {
197 const repositoryCwd = join(input.workspaceRoot, repository.relativePath);
198 const worktreePath = join(container, repository.relativePath);
199 yield* fileSystem
200 .makeDirectory(path.dirname(worktreePath), { recursive: true })
201 .pipe(
202 Effect.mapError((cause) =>
203 fail(operation, repositoryCwd, `Could not create ${worktreePath}.`, cause),
204 ),
205 );
206 const start = yield* resolveStart(repositoryCwd, input.startFromOrigin);
207 yield* git.createWorktree({
208 cwd: repositoryCwd,
209 refName: start.startRef,
210 newRefName: branch,
211 baseRefName: start.baseRef,
212 path: worktreePath,
213 });
214 }
215 return { path: container, branch };
216 },
217 );
218​
219 const renameBranch: WorkspaceWorktrees["Service"]["renameBranch"] = Effect.fn(
220 "WorkspaceWorktrees.renameBranch",
221 )(function* (input) {
222 const [first, ...rest] = yield* workspaceRepositories.list(input.path);
223 if (first === undefined) {
224 return yield* fail(
225 "WorkspaceWorktrees.renameBranch",
226 input.path,
227 "The isolated run holds no repositories.",
228 );
229 }
230 const renamed = yield* git.renameBranch({
231 cwd: join(input.path, first.relativePath),
232 oldBranch: input.oldBranch,
233 newBranch: input.newBranch,
234 ...(input.exactName ? { exactName: true } : {}),
235 });
236 for (const [index, repository] of rest.entries()) {
237 yield* git
238 .renameBranch({
239 cwd: join(input.path, repository.relativePath),
240 oldBranch: input.oldBranch,
241 newBranch: renamed.branch,
242 exactName: true,
243 })
244 .pipe(
245 // Put the renamed repositories back so every repository stays on one branch.
246 Effect.tapError(() =>
247 Effect.forEach([first, ...rest.slice(0, index)], (done) =>
248 git
249 .renameBranch({
250 cwd: join(input.path, done.relativePath),
251 oldBranch: renamed.branch,
252 newBranch: input.oldBranch,
253 exactName: true,
254 })
255 .pipe(Effect.ignore({ log: true })),
256 ),
257 ),
258 );
259 }
260 return { branch: renamed.branch };
261 });
262​
263 const hasGitEntry = (directory: string) =>
264 fileSystem.exists(path.join(directory, ".git")).pipe(Effect.orElseSucceed(() => false));
265 const isLink = (target: string) =>
266 fileSystem.readLink(target).pipe(
267 Effect.as(true),
268 Effect.orElseSucceed(() => false),
269 );
270​
271 // A single-repository worktree has a `.git` entry at its root; a container never does.
272 const isContainer: WorkspaceWorktrees["Service"]["isContainer"] = (target) =>
273 isInsideWorktreesDir(target)
274 ? fileSystem.stat(target).pipe(
275 Effect.flatMap((info) =>
276 info.type === "Directory"
277 ? hasGitEntry(target).pipe(Effect.map((found) => !found))
278 : Effect.succeed(false),
279 ),
280 Effect.orElseSucceed(() => false),
281 )
282 : Effect.succeed(false);
283​
284 // The container's worktrees, found in the container itself so removal doesn't depend on
285 // project files that may have changed since the run was created.
286 const findWorktrees: (
287 directory: string,
288 relativePath?: string,
289 ) => Effect.Effect<ReadonlyArray<string>, PlatformError.PlatformError> = Effect.fn(
290 "WorkspaceWorktrees.findWorktrees",
291 )(function* (directory, relativePath = "") {
292 const found: Array<string> = [];
293 for (const name of yield* fileSystem.readDirectory(directory)) {
294 const entry = path.join(directory, name);
295 if ((yield* isLink(entry)) || (yield* fileSystem.stat(entry)).type !== "Directory") {
296 continue;
297 }
298 const child = relativePath === "" ? name : `${relativePath}/${name}`;
299 found.push(...((yield* hasGitEntry(entry)) ? [child] : yield* findWorktrees(entry, child)));
300 }
301 return found;
302 });
303​
304 // Removes links and the folders nested repositories needed, bottom-up, keeping real files.
305 const removeLeftovers: (
306 directory: string,
307 ) => Effect.Effect<boolean, PlatformError.PlatformError> = Effect.fn(
308 "WorkspaceWorktrees.removeLeftovers",
309 )(function* (directory) {
310 for (const name of yield* fileSystem.readDirectory(directory)) {
311 const entry = path.join(directory, name);
312 if (yield* isLink(entry)) {
313 yield* fileSystem.remove(entry);
314 } else if ((yield* fileSystem.stat(entry)).type === "Directory") {
315 yield* removeLeftovers(entry);
316 }
317 }
318 if ((yield* fileSystem.readDirectory(directory)).length > 0) return false;
319 yield* fileSystem.remove(directory, { recursive: true });
320 return true;
321 });
322​
323 const remove: WorkspaceWorktrees["Service"]["remove"] = Effect.fn("WorkspaceWorktrees.remove")(
324 function* (input) {
325 const operation = "WorkspaceWorktrees.remove";
326 if (!isInsideWorktreesDir(input.path)) {
327 return yield* fail(operation, input.path, "Not an isolated run folder.");
328 }
329 const worktrees = yield* findWorktrees(input.path).pipe(
330 Effect.mapError((cause) =>
331 fail(operation, input.path, "Could not read the isolated run folder.", cause),
332 ),
333 );
334 for (const relativePath of worktrees) {
335 yield* git.removeWorktree({
336 cwd: join(input.workspaceRoot, relativePath),
337 path: join(input.path, relativePath),
338 force: input.force,
339 });
340 }
341 yield* removeLeftovers(input.path).pipe(
342 Effect.mapError((cause) =>
343 fail(operation, input.path, "Could not remove the isolated run folder.", cause),
344 ),
345 );
346 },
347 );
348​
349 return WorkspaceWorktrees.of({ create, renameBranch, isContainer, remove });
350});
351​
352export const layer = Layer.effect(WorkspaceWorktrees, make).pipe(
353 Layer.provide(WorkspaceRepositories.layer),
354);