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

TaskFolders.ts

1,454 lines60.9 KB

1import {
2 GitCommandError,
3 type ProjectId,
4 type ProjectTrackedFolder,
5 TASK_FOLDER_DEFAULT_REPOSITORIES_MAX,
6 type TaskFolder,
7 TaskFolderError,
8 type TaskFolderRepository,
9 type ThreadId,
10 type VcsCreateWorktreeInput,
11 type VcsCreateWorktreeResult,
12 T3_PROJECT_FILE_NAME,
13} from "@t3tools/contracts";
14import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
15import { flattenTemporaryWorktreeBranchName, isTemporaryWorktreeBranch } from "@t3tools/shared/git";
16import * as HostProcess from "@t3tools/shared/HostProcess";
17import * as KeyedLock from "@t3tools/shared/KeyedLock";
18import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
19import * as Cause from "effect/Cause";
20import * as Context from "effect/Context";
21import * as Digest from "effect/crypto/Digest";
22import * as Effect from "effect/Effect";
23import * as Exit from "effect/Exit";
24import * as Hex from "effect/encoding/Hex";
25import * as FileSystem from "effect/FileSystem";
26import * as Layer from "effect/Layer";
27import * as Option from "effect/Option";
28import * as Path from "effect/Path";
29import type * as PlatformError from "effect/PlatformError";
30import * as Schema from "effect/Schema";
31​
32import * as ServerConfig from "../config.ts";
33import * as GitWorkflowService from "../git/GitWorkflowService.ts";
34import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
35import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
36import * as ServerSettings from "../serverSettings.ts";
37import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
38import * as VcsProcess from "../vcs/VcsProcess.ts";
39import {
40 removeEmptyDirectory,
41 type RemoveEmptyDirectoryError,
42} from "../vcs/removeEmptyDirectory.ts";
43import { resolveWorktreesDirectory } from "../worktreesDirectory.ts";
44import { isWithinRoot } from "./KnownWorkspaces.ts";
45import * as TaskFolderStore from "./TaskFolderStore.ts";
46import { projectFolders, parseGitmodulesPaths } from "./WorkspaceFolders.ts";
47import { withWorkspaceLease } from "./workspaceLease.ts";
48​
49// Each worktree is a checkout: enough at once to finish four repositories together, few enough
50// to leave Git's server-wide process slots to running threads.
51const REPOSITORY_CONCURRENCY = 4;
52const LAYOUT_COMMAND_TIMEOUT_MS = 600_000;
53const BRANCH_NAME_ATTEMPTS = 50;
54​
55/** What a new task folder will hold, decided before anything is created. */
56export interface TaskFolderPlan {
57 readonly projectId: ProjectId;
58 readonly projectRoot: string;
59 readonly projectIsRepository: boolean;
60 readonly anchor: string;
61 /** The tracked Git folders that get a worktree. */
62 readonly repositories: ReadonlyArray<ProjectTrackedFolder>;
63 /** Every tracked Git folder. None is linked into a plain project folder: a link is the original. */
64 readonly trackedRepositories: ReadonlyArray<string>;
66​
67interface TaskFolderRemoval {
68 readonly removed: ReadonlyArray<string>;
69 readonly kept: ReadonlyArray<{ readonly path: string; readonly reason: string }>;
71​
72/** One checkout of a task folder, as removal sees it. */
73interface TaskFolderCheckout {
74 readonly worktreePath: string;
75 /** The checkout this is a worktree of. */
76 readonly repositoryPath: string;
78​
79export class TaskFolders extends Context.Service<
80 TaskFolders,
81 {
82 /**
83 * Null when the project tracks no Git folder: its worktree is then a single checkout, made as
84 * it always was. Omitted `repositories` selects every tracked Git folder up to
85 * `TASK_FOLDER_DEFAULT_REPOSITORIES_MAX`, and none beyond that.
86 */
87 readonly plan: (input: {
88 readonly projectId: ProjectId;
89 readonly repositories?: ReadonlyArray<{ readonly path: string }> | undefined;
90 }) => Effect.Effect<TaskFolderPlan | null, TaskFolderError>;
91 /**
92 * Creates the folder and every worktree on one branch name, which is `branch` unless a
93 * selected repository already has it. A failure removes what this call created.
94 */
95 readonly create: (input: {
96 readonly plan: TaskFolderPlan;
97 readonly branch: string;
98 /** Where the project folder's branch starts; unused when it is not a repository. */
99 readonly projectStart: { readonly refName: string; readonly baseRefName: string };
100 /**
101 * The branch the thread starts from. A repository that has it starts there; one that does
102 * not starts from its own default branch.
103 */
104 readonly baseBranch?: string | undefined;
105 readonly startFromOrigin: boolean;
106 readonly projectProgress?: GitVcsDriver.CreateWorktreeProgress;
107 /** As soon as the folder is recorded, so a cancelled caller knows what to remove. */
108 readonly onClaimed?: (taskFolder: TaskFolder, branch: string) => Effect.Effect<void>;
109 readonly onRepository?: (progress: {
110 readonly name: string;
111 readonly done: number;
112 readonly total: number;
113 }) => Effect.Effect<void>;
114 }) => Effect.Effect<
115 {
116 readonly taskFolder: TaskFolder;
117 readonly branch: string;
118 /** The project's own command made the checkouts, from whatever start it chose. */
119 readonly laidOutByProject: boolean;
120 /** A repository's worktree starts from the commit just fetched from its remote. */
121 readonly repositoriesStartedFromOrigin: boolean;
122 },
123 TaskFolderError
124 >;
125 /**
126 * The worktree an existing thread asks for in its project folder: a task folder with the
127 * default repositories when the project there tracks Git folders. Null otherwise, and for a
128 * request that names its path or checks out an existing branch, which stay a single worktree.
129 */
130 readonly createForProjectFolder: (
131 input: VcsCreateWorktreeInput,
132 ) => Effect.Effect<VcsCreateWorktreeResult | null, TaskFolderError>;
133 /**
134 * Gives a tracked Git folder its worktree in a thread's task folder, on the thread's branch.
135 * `startFromOrigin` defaults to the project's setting for new worktrees.
136 */
137 readonly addRepository: (input: {
138 readonly threadId: ThreadId;
139 readonly repositoryPath: string;
140 readonly startFromOrigin?: boolean | undefined;
141 }) => Effect.Effect<TaskFolder, TaskFolderError>;
142 /** The task folder that is, or contains, `target`. */
143 readonly find: (target: string) => Effect.Effect<TaskFolder | null, TaskFolderError>;
144 /**
145 * Removes repository worktrees, then the project folder, then the links and the folder.
146 * `inspect` may keep a checkout, with the reason to report, or allow forcing it; without it
147 * every checkout is removed with `force`. `forget` drops the record, shrinking it to what was
148 * kept; otherwise the record stays so the folder can be restored when its thread resumes.
149 */
150 readonly remove: (input: {
151 readonly root: string;
152 readonly force: boolean;
153 readonly forget: boolean;
154 readonly deleteBranch?: string | undefined;
155 readonly inspect?: (
156 checkout: TaskFolderCheckout,
157 ) => Effect.Effect<{ readonly keep: string | null; readonly force: boolean }>;
158 }) => Effect.Effect<TaskFolderRemoval, TaskFolderError>;
159 /**
160 * Removes the task folder `path` is the root or the project folder of, for good. False when
161 * it is neither, and a failure naming what could not be removed.
162 */
163 readonly removeIfTaskFolder: (input: {
164 readonly path: string;
165 readonly force: boolean;
166 }) => Effect.Effect<boolean, TaskFolderError>;
167 /** Renames the branch in every checkout to one name free in all of them. */
168 readonly renameBranch: (input: {
169 readonly root: string;
170 readonly oldBranch: string;
171 readonly newBranch: string;
172 readonly exactName?: boolean;
173 }) => Effect.Effect<{ readonly branch: string }, TaskFolderError>;
174 /** Puts back whatever is missing; `recreate` checks a branch out again at a path. */
175 readonly restore: <E>(input: {
176 readonly taskFolder: TaskFolder;
177 /** The thread's branch, for a project that lays its folder out with its own command. */
178 readonly branch: string;
179 readonly recreate: (checkout: TaskFolderCheckout) => Effect.Effect<void, E>;
180 }) => Effect.Effect<void, TaskFolderError | E>;
181 }
182>()("t3/workspace/TaskFolders") {}
183​
184const isTaskFolderError = Schema.is(TaskFolderError);
185​
186const failureDetail = (cause: unknown) =>
187 typeof cause === "object" &&
188 cause !== null &&
189 "detail" in cause &&
190 typeof cause.detail === "string"
191 ? cause.detail
192 : cause instanceof Error
193 ? cause.message
194 : String(cause);
195​
196/** The deepest folder that holds every one of `folders`, or null when they share none. */
197export const commonAncestor = (path: Path.Path, folders: ReadonlyArray<string>) => {
198 let ancestor = folders[0]!;
199 for (const folder of folders.slice(1)) {
200 while (!isWithinRoot(path, folder, ancestor)) {
201 const parent = path.dirname(ancestor);
202 // Two Windows drives meet nowhere, and a drive root is its own parent.
203 if (parent === ancestor) return null;
204 ancestor = parent;
205 }
206 }
207 return ancestor;
208};
209​
210/**
211 * The folder a task folder mirrors: the deepest one holding the project and every tracked
212 * repository that shares a root with it. The rest are `unreachable` and cannot be laid out.
213 */
214export const layoutAnchor = (
215 path: Path.Path,
216 projectRoot: string,
217 repositories: ReadonlyArray<string>,
218) => {
219 let anchor = projectRoot;
220 const unreachable: string[] = [];
221 for (const repository of repositories) {
222 const shared = commonAncestor(path, [anchor, repository]);
223 if (shared === null) unreachable.push(repository);
224 else anchor = shared;
225 }
226 return { anchor, unreachable };
227};
228​
229const isGitCommandError = Schema.is(GitCommandError);
230​
231const make = Effect.gen(function* () {
232 const fileSystem = yield* FileSystem.FileSystem;
233 const path = yield* Path.Path;
234 const digest = yield* Digest.Digest;
235 const config = yield* ServerConfig.ServerConfig;
236 const settings = yield* ServerSettings.ServerSettingsService;
237 const projects = yield* ProjectStore.ProjectStoreV2;
238 const git = yield* GitWorkflowService.GitWorkflowService;
239 const gitDriver = yield* GitVcsDriver.GitVcsDriver;
240 const store = yield* TaskFolderStore.TaskFolderStore;
241 const processes = yield* VcsProcess.VcsProcess;
242 const hostEnvironment = yield* HostProcess.Environment;
243 const hostPlatform = yield* HostProcess.Platform;
244 const onWindows = yield* HostProcess.isWindows;
245 const projections = yield* ProjectionStore.ProjectionStoreV2;
246​
247 const exists = (target: string) =>
248 fileSystem.exists(target).pipe(Effect.orElseSucceed(() => false));
249 const isRepository = (folder: string) => exists(path.join(folder, ".git"));
250 const occupied = Effect.fnUntraced(function* (target: string) {
251 if (!(yield* exists(target))) return false;
252 const isDirectory = (yield* fileSystem.stat(target).pipe(Effect.option)).pipe(
253 Option.exists((info) => info.type === "Directory"),
254 );
255 if (!isDirectory) return true;
256 return (
257 (yield* fileSystem.readDirectory(target).pipe(Effect.orElseSucceed(() => [""]))).length > 0
258 );
259 });
260 const trackedFolders = (project: {
261 readonly workspaceRoot: string;
262 readonly trackedFolders: ReadonlyArray<ProjectTrackedFolder>;
263 }) =>
264 projectFolders(project).pipe(
265 Effect.provideService(FileSystem.FileSystem, fileSystem),
266 Effect.provideService(Path.Path, path),
267 );
268 // The repository that pins a submodule owns its checkout: Git, a hook or a setup script puts it
269 // in that repository's worktree, so it never gets one of its own here.
270 const isSubmodule = Effect.fnUntraced(function* (folder: string) {
271 for (
272 let owner = path.dirname(folder);
273 owner !== path.dirname(owner);
274 owner = path.dirname(owner)
275 ) {
276 if (!(yield* isRepository(owner))) continue;
277 const declared = yield* fileSystem
278 .readFileString(path.join(owner, ".gitmodules"))
279 .pipe(Effect.orElseSucceed(() => ""));
280 return parseGitmodulesPaths(declared).includes(
281 path.relative(owner, folder).split(path.sep).join("/"),
282 );
283 }
284 return false;
285 });
286 const fail =
287 (operation: TaskFolderError["operation"], prefix: string) =>
288 (cause: unknown): TaskFolderError =>
289 new TaskFolderError({ operation, detail: `${prefix}: ${failureDetail(cause)}`, cause });
290​
291 // A project that lays its own thread folder out says so in its `t3.json`.
292 const worktreeLayout = (projectRoot: string) =>
293 fileSystem.readFileString(path.join(projectRoot, T3_PROJECT_FILE_NAME)).pipe(
294 Effect.map((contents) => parseT3ProjectFile(contents)?.worktreeLayout ?? null),
295 Effect.orElseSucceed(() => null),
296 );
297 // One at a time per project: the commands share the project folder, and its workspace files.
298 const layoutLocks = yield* KeyedLock.make<string>();
299 const runLayoutCommand = (
300 operation: TaskFolderError["operation"],
301 command: string,
302 taskFolder: Pick<TaskFolder, "root" | "projectRoot" | "projectPath">,
303 branch: string,
304 baseBranch: string | undefined,
305 repositories: ReadonlyArray<string>,
306 ) =>
307 layoutLocks.withLock(
308 taskFolder.projectRoot,
309 processes
310 .run({
311 operation: "TaskFolders.worktreeLayout",
312 command: onWindows ? "cmd.exe" : "sh",
313 args: onWindows ? ["/d", "/s", "/c", command] : ["-c", command],
314 cwd: taskFolder.projectRoot,
315 env: {
316 ...hostEnvironment,
317 // A `GIT_DIR` the server inherited would point the command's Git at another repository.
318 ...VcsProcess.unsetInheritedRepositoryEnv(hostEnvironment, hostPlatform),
319 T3_PROJECT_ROOT: taskFolder.projectRoot,
320 T3_WORKTREE_ROOT: taskFolder.root,
321 T3_WORKTREE_PROJECT_PATH: taskFolder.projectPath,
322 T3_WORKTREE_BRANCH: branch,
323 T3_WORKTREE_BASE: baseBranch ?? "",
324 T3_WORKTREE_REPOSITORIES: repositories.join("\n"),
325 },
326 timeoutMs: LAYOUT_COMMAND_TIMEOUT_MS,
327 })
328 .pipe(Effect.mapError(fail(operation, "The project's worktree layout command failed"))),
329 );
330​
331 /** Where a folder's `.git` file points, or null when `.git` is a directory or absent. */
332 const gitDirPointer = Effect.fnUntraced(function* (folder: string) {
333 const pointer = yield* fileSystem
334 .readFileString(path.join(folder, ".git"))
335 .pipe(Effect.orElseSucceed(() => ""));
336 const gitDir = /^gitdir:\s*(.+?)\s*$/m.exec(pointer)?.[1];
337 return gitDir === undefined ? null : path.resolve(folder, gitDir);
338 });
339 // A repository that is itself a linked worktree registers worktrees under the Git dir it shares.
340 const commonGitDir = Effect.fnUntraced(function* (repositoryPath: string) {
341 const gitDir = yield* gitDirPointer(repositoryPath);
342 if (gitDir === null) return path.join(repositoryPath, ".git");
343 const common = (yield* fileSystem
344 .readFileString(path.join(gitDir, "commondir"))
345 .pipe(Effect.orElseSucceed(() => ""))).trim();
346 return common === "" ? gitDir : path.resolve(gitDir, common);
347 });
348​
349 // What a layout command leaves must be a checkout this service can later remove, restore and
350 // rename: a worktree linked to the repository, on the thread's branch. Null when it is.
351 /** The checkout's own Git directory when it is a worktree linked to its repository. */
352 const linkedGitDir = Effect.fnUntraced(function* (checkout: TaskFolderCheckout) {
353 const real = (target: string) =>
354 fileSystem.realPath(target).pipe(Effect.orElseSucceed(() => target));
355 const resolved = yield* gitDirPointer(checkout.worktreePath);
356 if (
357 resolved === null ||
358 !isWithinRoot(
359 path,
360 yield* real(resolved),
361 path.join(yield* real(yield* commonGitDir(checkout.repositoryPath)), "worktrees"),
362 )
363 )
364 return null;
365 // Git registers one path per worktree: a copy of the checkout elsewhere points here too.
366 const registered = (yield* fileSystem
367 .readFileString(path.join(resolved, "gitdir"))
368 .pipe(Effect.orElseSucceed(() => ""))).trim();
369 return registered !== "" &&
370 (yield* real(path.dirname(registered))) === (yield* real(checkout.worktreePath))
371 ? resolved
372 : null;
373 });
374 const unadoptable = Effect.fnUntraced(function* (checkout: TaskFolderCheckout, branch: string) {
375 const resolved = yield* linkedGitDir(checkout);
376 if (resolved === null)
377 return `${checkout.worktreePath} is not a Git worktree of ${checkout.repositoryPath}`;
378 const head = (yield* fileSystem
379 .readFileString(path.join(resolved, "HEAD"))
380 .pipe(Effect.orElseSucceed(() => ""))).trim();
381 return head === `ref: refs/heads/${branch}`
382 ? null
383 : `${checkout.worktreePath} is not on the branch ${branch}`;
384 });
385​
386 const mapped = (taskFolder: Pick<TaskFolder, "root" | "anchor">, source: string) =>
387 path.join(taskFolder.root, path.relative(taskFolder.anchor, source));
388 const depth = (target: string) => path.resolve(target).split(path.sep).length;
389​
390 const readProject = Effect.fn("TaskFolders.readProject")(function* (
391 operation: TaskFolderError["operation"],
392 projectId: ProjectId,
393 ) {
394 const row = yield* projects
395 .get(projectId)
396 .pipe(Effect.mapError(fail(operation, "Could not read the project")));
397 if (Option.isNone(row)) {
398 return yield* new TaskFolderError({
399 operation,
400 detail: `Project ${projectId} was not found.`,
401 });
402 }
403 return row.value;
404 });
405​
406 const plan: TaskFolders["Service"]["plan"] = Effect.fn("TaskFolders.plan")(function* (input) {
407 const project = yield* readProject("plan", input.projectId);
408 const projectRoot = path.resolve(project.workspaceRoot);
409 const classified = yield* Effect.forEach(
410 yield* trackedFolders(project),
411 (folder) => {
412 const folderPath = path.resolve(folder.path);
413 return Effect.all([isRepository(folderPath), isSubmodule(folderPath)]).pipe(
414 Effect.map(([git, submodule]) => ({
415 name: folder.name,
416 path: folderPath,
417 git,
418 submodule,
419 })),
420 );
421 },
422 { concurrency: 8 },
423 );
424 const tracked = classified.filter(
425 (folder) => folder.git && !folder.submodule && folder.path !== projectRoot,
426 );
427 // A project that lays its own thread folder out gets one even with nothing else to check out.
428 // An explicit choice still goes through the checks below, so it is refused, not dropped.
429 if (
430 tracked.length === 0 &&
431 (input.repositories ?? []).length === 0 &&
432 (yield* worktreeLayout(projectRoot)) === null
433 )
434 return null;
435 // A repository on another Windows drive has no place in the folder; only choosing it fails.
436 const { anchor, unreachable } = layoutAnchor(
437 path,
438 projectRoot,
439 tracked.map((folder) => folder.path),
440 );
441 const reachable = tracked.filter((folder) => !unreachable.includes(folder.path));
442 let repositories: ReadonlyArray<ProjectTrackedFolder>;
443 if (input.repositories === undefined) {
444 repositories = reachable.length <= TASK_FOLDER_DEFAULT_REPOSITORIES_MAX ? reachable : [];
445 } else {
446 const selected = new Map<string, ProjectTrackedFolder>();
447 for (const requested of input.repositories) {
448 const requestedPath = path.resolve(requested.path);
449 const folder = classified.find((candidate) => candidate.path === requestedPath);
450 // A submodule comes with its repository's worktree; clients cannot tell one apart.
451 if (folder?.submodule === true) continue;
452 if (folder === undefined || !folder.git || folder.path === projectRoot) {
453 return yield* new TaskFolderError({
454 operation: "plan",
455 detail:
456 folder === undefined
457 ? `"${requested.path}" is not a tracked folder of project "${project.title}".`
458 : `"${requested.path}" is not a Git repository, so it cannot get a worktree.`,
459 });
460 }
461 if (unreachable.includes(folder.path)) {
462 return yield* new TaskFolderError({
463 operation: "plan",
464 detail: `"${folder.path}" shares no common root with the project folder ${projectRoot}, so the two cannot be laid out in one worktree folder.`,
465 });
466 }
467 selected.set(folder.path, folder);
468 }
469 repositories = [...selected.values()];
470 }
471 // A repository with no commit yet has nothing to branch from, so it is left out.
472 repositories = yield* Effect.filter(
473 repositories,
474 (folder) =>
475 git.hasCommit({ cwd: folder.path, refName: "HEAD" }).pipe(Effect.orElseSucceed(() => true)),
476 { concurrency: REPOSITORY_CONCURRENCY },
477 );
478 return {
479 projectId: project.projectId,
480 projectRoot,
481 projectIsRepository: yield* isRepository(projectRoot),
482 anchor,
483 repositories: repositories.map(({ name, path: folderPath }) => ({ name, path: folderPath })),
484 trackedRepositories: reachable.map((folder) => folder.path),
485 };
486 });
487​
488 const branchNames = (cwds: ReadonlyArray<string>) =>
489 Effect.forEach(cwds, (cwd) => git.listLocalBranchNames(cwd), {
490 concurrency: REPOSITORY_CONCURRENCY,
491 });
492 // Git stores branches as files, so a name also collides with one it nests under or contains.
493 const collides = (existing: string, candidate: string) =>
494 existing === candidate ||
495 existing.startsWith(`${candidate}/`) ||
496 candidate.startsWith(`${existing}/`);
497​
498 const freeBranchName = (
499 operation: TaskFolderError["operation"],
500 branch: string,
501 names: ReadonlyArray<ReadonlyArray<string>>,
502 ) => {
503 for (let attempt = 1; attempt <= BRANCH_NAME_ATTEMPTS; attempt++) {
504 const candidate = attempt === 1 ? branch : `${branch}-${attempt}`;
505 if (!names.some((list) => list.some((existing) => collides(existing, candidate))))
506 return Effect.succeed(candidate);
507 }
508 return Effect.fail(
509 new TaskFolderError({
510 operation,
511 detail: `No branch name based on "${branch}" is free in every repository.`,
512 }),
513 );
514 };
515​
516 /**
517 * Where a repository's branch starts: `baseBranch` when the repository has it, else its
518 * default branch. The remote commit of either when starting from origin.
519 */
520 const repositoryStart = Effect.fn("TaskFolders.repositoryStart")(function* (
521 cwd: string,
522 startFromOrigin: boolean,
523 baseBranch?: string,
524 ) {
525 // Clients send `HEAD` when no base was chosen; as a name it would match `origin/HEAD`.
526 const wanted = baseBranch?.replace(/^refs\/heads\//, "").replace(/^origin\//, "");
527 const defaultBranch =
528 wanted !== undefined &&
529 wanted !== "" &&
530 wanted !== "HEAD" &&
531 ((yield* git.hasCommit({ cwd, refName: `refs/heads/${wanted}` })) ||
532 (yield* git.hasCommit({ cwd, refName: `refs/remotes/origin/${wanted}` })))
533 ? wanted
534 : ((yield* gitDriver.resolveDefaultBranchName(cwd, "origin")) ??
535 (yield* git.currentBranch(cwd)));
536 let baseRef = "HEAD";
537 if (defaultBranch !== null) {
538 if (yield* git.hasCommit({ cwd, refName: `refs/heads/${defaultBranch}` }))
539 baseRef = defaultBranch;
540 else if (yield* git.hasCommit({ cwd, refName: `refs/remotes/origin/${defaultBranch}` }))
541 baseRef = `origin/${defaultBranch}`;
542 }
543 const remoteBase =
544 startFromOrigin && baseRef !== "HEAD"
545 ? yield* git.fetchWorktreeBaseCommit({ cwd, refName: baseRef })
546 : null;
547 return remoteBase === null
548 ? { refName: baseRef, baseRefName: baseRef }
549 : { refName: remoteBase.commitSha, baseRefName: `refs/remotes/${remoteBase.remoteRefName}` };
550 });
551​
552 /**
553 * Stands in for a folder that is not a repository: every entry links to the original, so
554 * nothing is copied, except the folders that lead to a tracked repository, which are real so a
555 * worktree can sit in them.
556 */
557 const linkFolder: (
558 source: string,
559 target: string,
560 trackedRepositories: ReadonlyArray<string>,
561 skip?: string,
562 ) => Effect.Effect<void, PlatformError.PlatformError> = Effect.fnUntraced(
563 function* (source, target, trackedRepositories, skip) {
564 yield* fileSystem.makeDirectory(target, { recursive: true });
565 for (const name of yield* fileSystem.readDirectory(source)) {
566 const entry = path.join(source, name);
567 const link = path.join(target, name);
568 if (name === ".git" || name === skip || trackedRepositories.includes(entry)) continue;
569 if (yield* exists(link)) continue;
570 if (trackedRepositories.some((repository) => isWithinRoot(path, repository, entry))) {
571 yield* linkFolder(entry, link, trackedRepositories);
572 } else {
573 yield* fileSystem.symlink(entry, link);
574 }
575 }
576 },
577 );
578​
579 /**
580 * Makes room for a worktree at `relative` inside a linked folder: a link on the way becomes a
581 * real folder linking its other entries. Anything there that this service did not link stays.
582 */
583 const openLinkedPath = Effect.fnUntraced(function* (
584 source: string,
585 target: string,
586 relative: string,
587 ) {
588 const segments = relative.split(path.sep);
589 for (const [index, segment] of segments.entries()) {
590 source = path.join(source, segment);
591 target = path.join(target, segment);
592 const last = index === segments.length - 1;
593 const link = yield* fileSystem.readLink(target).pipe(Effect.option);
594 if (Option.isSome(link)) {
595 if (path.resolve(path.dirname(target), link.value) !== source) return false;
596 yield* fileSystem.remove(target);
597 if (!last) yield* linkFolder(source, target, [], segments[index + 1]);
598 } else if (!last) {
599 yield* fileSystem.makeDirectory(target, { recursive: true });
600 }
601 }
602 return true;
603 });
604​
605 /** Unlinks links and removes the folders that leaves empty; files and checkouts stay. */
606 const removeLinks: (
607 target: string,
608 ) => Effect.Effect<boolean, PlatformError.PlatformError | RemoveEmptyDirectoryError> =
609 Effect.fnUntraced(function* (target) {
610 if (Option.isSome(yield* fileSystem.readLink(target).pipe(Effect.option))) {
611 yield* fileSystem.remove(target);
612 return true;
613 }
614 if (!(yield* exists(target))) return true;
615 if ((yield* fileSystem.stat(target)).type !== "Directory") return false;
616 if (yield* isRepository(target)) return false;
617 let empty = true;
618 for (const name of yield* fileSystem.readDirectory(target)) {
619 if (!(yield* removeLinks(path.join(target, name)))) empty = false;
620 }
621 return empty && (yield* removeEmptyDirectory(target));
622 });
623​
624 /** Whether `removeLinks` would leave nothing: only links and folders of links are inside. */
625 const holdsOnlyLinks: (target: string) => Effect.Effect<boolean, PlatformError.PlatformError> =
626 Effect.fnUntraced(function* (target) {
627 if (Option.isSome(yield* fileSystem.readLink(target).pipe(Effect.option))) return true;
628 if (!(yield* exists(target))) return true;
629 if ((yield* fileSystem.stat(target)).type !== "Directory") return false;
630 if (yield* isRepository(target)) return false;
631 for (const name of yield* fileSystem.readDirectory(target)) {
632 if (!(yield* holdsOnlyLinks(path.join(target, name)))) return false;
633 }
634 return true;
635 });
636​
637 const allocateRoot = Effect.fn("TaskFolders.allocateRoot")(function* (
638 taskPlan: TaskFolderPlan,
639 branch: string,
640 ) {
641 const parent = resolveWorktreesDirectory(
642 (yield* settings.getSettings.pipe(Effect.orElseSucceed(() => ({ worktreesDirectory: "" }))))
643 .worktreesDirectory,
644 config.worktreesDir,
645 path,
646 yield* HostProcess.HomeDirectory,
647 );
648 if (parent === null) {
649 return yield* new TaskFolderError({
650 operation: "create",
651 detail:
652 "The worktree location must be an absolute folder on this machine, not a drive root. Change it in Settings → Worktrees.",
653 });
654 }
655 const hash = yield* digest.digest(
656 Digest.sha256,
657 new TextEncoder().encode(`${taskPlan.projectId}\0${taskPlan.anchor}\0${branch}`),
658 );
659 // UTF-8 bytes bound UTF-16 length too, leaving room for files on Windows.
660 let prefix = "";
661 for (const character of branch.replace(/\//g, "-")) {
662 if (Buffer.byteLength(prefix + character) > 23) break;
663 prefix += character;
664 }
665 const base = path.join(
666 parent,
667 path.basename(taskPlan.anchor) || "workspace",
668 `${prefix}-${Hex.encode(hash).slice(0, 16)}`,
669 );
670 const allocateFailed = fail("create", "Could not create the worktree folder");
671 yield* fileSystem
672 .makeDirectory(path.dirname(base), { recursive: true })
673 .pipe(Effect.mapError(allocateFailed));
674 // Made here, not just found free: two creations on one branch must not share a folder.
675 for (let suffix = 1; ; suffix++) {
676 const root = suffix === 1 ? base : `${base}-${suffix}`;
677 const claimed = yield* fileSystem.makeDirectory(root).pipe(
678 Effect.as(true),
679 Effect.catchIf(
680 (cause) => cause.reason._tag === "AlreadyExists",
681 () => Effect.succeed(false),
682 ),
683 Effect.mapError(allocateFailed),
684 );
685 if (claimed) return root;
686 }
687 });
688​
689 const removeCheckout = Effect.fnUntraced(function* (
690 checkout: TaskFolderCheckout,
691 force: boolean,
692 deleteBranch: string | undefined,
693 ) {
694 yield* git.removeWorktree({
695 cwd: checkout.repositoryPath,
696 path: checkout.worktreePath,
697 force,
698 });
699 if (deleteBranch !== undefined) {
700 yield* git
701 .deleteLocalBranch({ cwd: checkout.repositoryPath, refName: deleteBranch, force: true })
702 .pipe(Effect.ignoreCause({ log: true }));
703 }
704 });
705​
706 const removeLocked = Effect.fn("TaskFolders.remove")(function* (
707 taskFolder: TaskFolder,
708 input: Omit<Parameters<TaskFolders["Service"]["remove"]>[0], "root">,
709 /** Repositories whose `deleteBranch` is not this folder's to delete. */
710 keepBranchIn: ReadonlySet<string> = new Set(),
711 /** False when the folder never got as far as its layout command: nothing to tear down. */
712 laidOut = true,
713 ) {
714 const removed: string[] = [];
715 const kept: Array<{ path: string; reason: string }> = [];
716 let remaining = taskFolder.repositories;
717 const verdicts = new Map<string, { readonly keep: string | null; readonly force: boolean }>();
718 const verdict = Effect.fnUntraced(function* (checkout: TaskFolderCheckout) {
719 const known = verdicts.get(checkout.worktreePath);
720 if (known !== undefined) return known;
721 const decided =
722 input.inspect === undefined
723 ? { keep: null, force: input.force }
724 : yield* input.inspect(checkout);
725 verdicts.set(checkout.worktreePath, decided);
726 return decided;
727 });
728 // The project's own teardown goes first; what it leaves is removed below as usual. Only when
729 // every checkout may go: the command cannot be told which ones to keep.
730 const layout = laidOut ? yield* worktreeLayout(taskFolder.projectRoot) : null;
731 if (layout?.remove !== undefined) {
732 const checkouts = [
733 ...taskFolder.repositories,
734 ...(taskFolder.projectIsWorktree
735 ? [{ worktreePath: taskFolder.projectPath, repositoryPath: taskFolder.projectRoot }]
736 : []),
737 ];
738 let allGo = true;
739 for (const checkout of checkouts) {
740 if (!(yield* exists(checkout.worktreePath))) continue;
741 if ((yield* verdict(checkout)).keep === null) continue;
742 allGo = false;
743 break;
744 }
745 if (allGo) {
746 yield* runLayoutCommand(
747 "remove",
748 layout.remove,
749 taskFolder,
750 input.deleteBranch ?? "",
751 undefined,
752 taskFolder.repositories.map((repository) => repository.repositoryPath),
753 ).pipe(Effect.ignoreCause({ log: true }));
754 // The command took its time: what it left is looked at again before it is removed.
755 verdicts.clear();
756 }
757 }
758 const removeOne = Effect.fnUntraced(function* (checkout: TaskFolderCheckout) {
759 if (!(yield* exists(checkout.worktreePath))) {
760 yield* git
761 .pruneWorktrees({ cwd: checkout.repositoryPath })
762 .pipe(Effect.ignoreCause({ log: true }));
763 return true;
764 }
765 const { keep, force } = yield* verdict(checkout);
766 if (keep !== null) {
767 kept.push({ path: checkout.worktreePath, reason: keep });
768 return false;
769 }
770 return yield* removeCheckout(
771 checkout,
772 force,
773 keepBranchIn.has(checkout.repositoryPath) ? undefined : input.deleteBranch,
774 ).pipe(
775 Effect.as(true),
776 Effect.tap(() => Effect.sync(() => removed.push(checkout.worktreePath))),
777 Effect.catch((cause) =>
778 Effect.sync(() => {
779 kept.push({ path: checkout.worktreePath, reason: failureDetail(cause) });
780 return false;
781 }),
782 ),
783 );
784 });
785 // Children first: a worktree nested in another must go before the one that holds it.
786 for (const repository of taskFolder.repositories.toSorted(
787 (left, right) => depth(right.worktreePath) - depth(left.worktreePath),
788 )) {
789 const holdsKept = kept.some((entry) =>
790 isWithinRoot(path, entry.path, repository.worktreePath),
791 );
792 if (holdsKept) {
793 kept.push({ path: repository.worktreePath, reason: "holds a repository that was kept" });
794 continue;
795 }
796 if (!(yield* removeOne(repository))) continue;
797 remaining = remaining.filter((entry) => entry.worktreePath !== repository.worktreePath);
798 // After each one, so a crash leaves a record that matches the disk.
799 if (input.forget) yield* store.put({ ...taskFolder, repositories: remaining });
800 }
801 const projectPath = taskFolder.projectPath;
802 const projectHoldsKept = kept.some((entry) => isWithinRoot(path, entry.path, projectPath));
803 let projectGone = false;
804 if (taskFolder.projectIsWorktree) {
805 if (projectHoldsKept) {
806 if (yield* exists(projectPath))
807 kept.push({ path: projectPath, reason: "holds a repository that was kept" });
808 } else {
809 projectGone = yield* removeOne({
810 worktreePath: projectPath,
811 repositoryPath: taskFolder.projectRoot,
812 });
813 }
814 } else if (!projectHoldsKept) {
815 // A folder that stays keeps its links: restoring relinks only a folder that is gone.
816 projectGone = yield* holdsOnlyLinks(projectPath).pipe(
817 Effect.flatMap((onlyLinks) =>
818 onlyLinks ? removeLinks(projectPath) : Effect.succeed(false),
819 ),
820 Effect.orElseSucceed(() => false),
821 );
822 if (!projectGone && input.force && input.inspect === undefined) {
823 // Forced: what is left are files the thread wrote beside the links.
824 projectGone = yield* fileSystem.remove(projectPath, { recursive: true, force: true }).pipe(
825 Effect.as(true),
826 Effect.orElseSucceed(() => false),
827 );
828 }
829 if (projectGone) removed.push(projectPath);
830 else kept.push({ path: projectPath, reason: "has files that exist only in this folder" });
831 }
832 if (kept.length === 0) {
833 let rootGone = yield* removeLinks(taskFolder.root).pipe(Effect.orElseSucceed(() => false));
834 if (!rootGone && input.force && input.inspect === undefined) {
835 rootGone = yield* fileSystem.remove(taskFolder.root, { recursive: true, force: true }).pipe(
836 Effect.as(true),
837 Effect.orElseSucceed(() => false),
838 );
839 }
840 if (!rootGone) {
841 kept.push({ path: taskFolder.root, reason: "has files that exist only in this folder" });
842 } else if (input.forget) yield* store.remove(taskFolder.root);
843 }
844 return { removed, kept } satisfies TaskFolderRemoval;
845 });
846​
847 const requireTaskFolder = Effect.fnUntraced(function* (
848 operation: TaskFolderError["operation"],
849 target: string,
850 ) {
851 const taskFolder = yield* store.findContaining(target);
852 if (taskFolder === null) {
853 return yield* new TaskFolderError({
854 operation,
855 detail: `"${target}" is not inside a task folder.`,
856 });
857 }
858 return taskFolder;
859 });
860 // The same lease storage cleanup and file rewind take: the thread's worktree path.
861 const locked = <A, E>(taskFolder: Pick<TaskFolder, "projectPath">, effect: Effect.Effect<A, E>) =>
862 withWorkspaceLease(path.resolve(taskFolder.projectPath), effect);
863​
864 const createRepositoryWorktree = Effect.fnUntraced(function* (
865 taskFolder: TaskFolder,
866 repository: ProjectTrackedFolder,
867 branch: string,
868 startFromOrigin: boolean,
869 baseBranch: string | undefined,
870 recordBranch: <A, E>(exit: Exit.Exit<A, E>) => Effect.Effect<void>,
871 ) {
872 const worktreePath = mapped(taskFolder, repository.path);
873 // The project's own checkout (a post-checkout hook, say) already provided this repository.
874 // A link counts even to an empty folder: Git would write the worktree through it.
875 if (
876 Option.isSome(yield* fileSystem.readLink(worktreePath).pipe(Effect.option)) ||
877 (yield* occupied(worktreePath))
878 )
879 return null;
880 yield* fileSystem.makeDirectory(path.dirname(worktreePath), { recursive: true });
881 const start = yield* repositoryStart(repository.path, startFromOrigin, baseBranch);
882 yield* git
883 .createWorktree({
884 cwd: repository.path,
885 refName: start.refName,
886 newRefName: branch,
887 baseRefName: start.baseRefName,
888 path: worktreePath,
889 })
890 .pipe(Effect.onExit(recordBranch));
891 return {
892 repository: {
893 repositoryPath: repository.path,
894 worktreePath,
895 name: repository.name,
896 } satisfies TaskFolderRepository,
897 fromOrigin: start.refName !== start.baseRefName,
898 };
899 });
900​
901 const create: TaskFolders["Service"]["create"] = Effect.fn("TaskFolders.create")(
902 function* (input) {
903 const taskPlan = input.plan;
904 const listFailed = fail("create", "Could not list branches");
905 const names = yield* branchNames(
906 taskPlan.repositories.map((repository) => repository.path),
907 ).pipe(Effect.mapError(listFailed));
908 const projectNames = taskPlan.projectIsRepository
909 ? yield* git.listLocalBranchNames(taskPlan.projectRoot).pipe(Effect.mapError(listFailed))
910 : [];
911 // A temporary name nests under its prefix, which a repository may hold as a branch.
912 const requested =
913 isTemporaryWorktreeBranch(input.branch) &&
914 [...names, projectNames].some((list) =>
915 list.some((existing) => input.branch.startsWith(`${existing}/`)),
916 )
917 ? flattenTemporaryWorktreeBranchName(input.branch)
918 : input.branch;
919 // A name the project folder already has is Git's to refuse, as for a single worktree.
920 const branch = projectNames.some((existing) => collides(existing, requested))
921 ? requested
922 : yield* freeBranchName("create", requested, [...names, projectNames]);
923 const root = yield* allocateRoot(taskPlan, branch);
924 const empty: TaskFolder = {
925 root,
926 projectId: taskPlan.projectId,
927 projectRoot: taskPlan.projectRoot,
928 anchor: taskPlan.anchor,
929 projectPath: path.join(root, path.relative(taskPlan.anchor, taskPlan.projectRoot)),
930 projectIsWorktree: taskPlan.projectIsRepository,
931 repositories: [],
932 };
933 const created: TaskFolderRepository[] = [];
934 let repositoriesStartedFromOrigin = false;
935 const current = (): TaskFolder => ({ ...empty, repositories: [...created] });
936 const checkedOutFrom = [
937 ...(taskPlan.projectIsRepository ? [taskPlan.projectRoot] : []),
938 ...taskPlan.trackedRepositories,
939 ];
940 // A layout command may check out a branch that was already there; a rollback leaves it.
941 const hadBranch = new Set<string>();
942 let layoutStarted = false;
943 // Where this attempt may make the branch: none of them had it when listed.
944 const branchMissingIn = new Set([
945 ...taskPlan.repositories
946 .filter((_, index) => !names[index]!.includes(branch))
947 .map((repository) => repository.path),
948 ...(taskPlan.projectIsRepository && !projectNames.includes(branch)
949 ? [taskPlan.projectRoot]
950 : []),
951 ]);
952 // Where this attempt made the branch: a checkout that fails halfway leaves it behind. Only
953 // a checkout it ran counts, and not one Git refused because another creation made it first.
954 let branchMadeIn: string[] = [];
955 const recordBranch =
956 (cwd: string) =>
957 <A, E>(exit: Exit.Exit<A, E>) =>
958 Effect.sync(() => {
959 const refused =
960 Exit.isFailure(exit) &&
961 exit.cause.reasons.some(
962 (reason) =>
963 Cause.isFailReason(reason) &&
964 isGitCommandError(reason.error) &&
965 reason.error.operation === "GitVcsDriver.createWorktree.createBranch",
966 );
967 if (branchMissingIn.has(cwd) && !refused) branchMadeIn.push(cwd);
968 });
969 return yield* Effect.gen(function* () {
970 yield* fileSystem.makeDirectory(root, { recursive: true });
971 // Recorded before any checkout, so an interrupted creation is still found and removed.
972 yield* store.put(empty);
973 if (input.onClaimed !== undefined) yield* input.onClaimed(empty, branch);
974 const layout = yield* worktreeLayout(taskPlan.projectRoot);
975 if (layout !== null) {
976 const before = yield* branchNames(checkedOutFrom).pipe(Effect.mapError(listFailed));
977 for (const [index, repositoryPath] of checkedOutFrom.entries()) {
978 if (before[index]!.includes(branch)) hadBranch.add(repositoryPath);
979 }
980 branchMadeIn = checkedOutFrom.filter((repositoryPath) => !hadBranch.has(repositoryPath));
981 layoutStarted = true;
982 const ran = yield* Effect.exit(
983 runLayoutCommand(
984 "create",
985 layout.create,
986 empty,
987 branch,
988 input.baseBranch,
989 taskPlan.repositories.map((repository) => repository.path),
990 ),
991 );
992 // Whatever the command checked out where a repository belongs is the thread's. Adopted
993 // even when the command failed, so the rollback removes it instead of leaking it.
994 const refused: string[] = [];
995 for (const repositoryPath of taskPlan.trackedRepositories) {
996 const checkout = { repositoryPath, worktreePath: mapped(empty, repositoryPath) };
997 if (!(yield* isRepository(checkout.worktreePath))) continue;
998 const reason = yield* unadoptable(checkout, branch);
999 if (reason === null) created.push({ ...checkout, name: path.basename(repositoryPath) });
1000 else refused.push(reason);
1002 if (Exit.isFailure(ran)) return yield* Effect.failCause(ran.cause);
1003 if (!(yield* exists(empty.projectPath))) {
1004 return yield* new TaskFolderError({
1005 operation: "create",
1006 detail: `The project's worktree layout command left no folder at ${empty.projectPath}.`,
1007 });
1009 if (taskPlan.projectIsRepository && (yield* isRepository(empty.projectPath))) {
1010 const reason = yield* unadoptable(
1011 { repositoryPath: taskPlan.projectRoot, worktreePath: empty.projectPath },
1012 branch,
1013 );
1014 if (reason !== null) refused.push(reason);
1016 if (refused.length > 0) {
1017 return yield* new TaskFolderError({
1018 operation: "create",
1019 detail: `The project's worktree layout command must make each checkout with git worktree add on the thread's branch: ${refused.join("; ")}.`,
1020 });
1022 const taskFolder: TaskFolder = {
1023 ...current(),
1024 projectIsWorktree:
1025 taskPlan.projectIsRepository && (yield* isRepository(empty.projectPath)),
1026 };
1027 yield* store.put(taskFolder);
1028 return {
1029 taskFolder,
1030 branch,
1031 laidOutByProject: true,
1032 repositoriesStartedFromOrigin: false,
1033 };
1035 if (taskPlan.projectIsRepository) {
1036 yield* fileSystem.makeDirectory(path.dirname(empty.projectPath), { recursive: true });
1037 yield* git
1038 .createWorktree(
1040 cwd: taskPlan.projectRoot,
1041 refName: input.projectStart.refName,
1042 newRefName: branch,
1043 baseRefName: input.projectStart.baseRefName,
1044 path: empty.projectPath,
1045 },
1046 input.projectProgress === undefined ? {} : { progress: input.projectProgress },
1048 .pipe(Effect.onExit(recordBranch(taskPlan.projectRoot)));
1049 } else {
1050 yield* linkFolder(taskPlan.projectRoot, empty.projectPath, taskPlan.trackedRepositories);
1052 let finished = 0;
1053 // Whatever the project put at a skipped path also stands for the repositories inside it.
1054 const skipped: string[] = [];
1055 // A repository inside another waits for the one that holds it.
1056 const levels = Map.groupBy(
1057 taskPlan.repositories,
1058 (repository) =>
1059 taskPlan.repositories.filter(
1060 (other) =>
1061 other.path !== repository.path && isWithinRoot(path, repository.path, other.path),
1062 ).length,
1063 );
1064 for (const level of [...levels.keys()].toSorted((left, right) => left - right)) {
1065 // Every checkout runs to its end: one stopped halfway is registered in its repository
1066 // without being known here, so nothing would remove it.
1067 const exits = yield* Effect.forEach(
1068 levels.get(level)!,
1069 (repository) =>
1070 (skipped.some((outer) => isWithinRoot(path, repository.path, outer))
1071 ? Effect.succeed(null)
1072 : createRepositoryWorktree(
1073 empty,
1074 repository,
1075 branch,
1076 input.startFromOrigin,
1077 input.baseBranch,
1078 recordBranch(repository.path),
1080 ).pipe(
1081 Effect.tap((worktree) =>
1082 Effect.suspend(() => {
1083 finished += 1;
1084 if (worktree === null) skipped.push(repository.path);
1085 else {
1086 created.push(worktree.repository);
1087 repositoriesStartedFromOrigin ||= worktree.fromOrigin;
1089 return (
1090 input.onRepository?.({
1091 name: repository.name,
1092 done: finished,
1093 total: taskPlan.repositories.length,
1094 }) ?? Effect.void
1095 );
1096 }),
1097 ),
1098 Effect.mapError(fail("create", `Could not create the ${repository.name} worktree`)),
1099 Effect.exit,
1100 ),
1101 { concurrency: REPOSITORY_CONCURRENCY },
1102 ).pipe(Effect.uninterruptible);
1103 const failed = exits.find(Exit.isFailure);
1104 if (failed !== undefined) return yield* Effect.failCause(failed.cause);
1106 const taskFolder = current();
1107 yield* store.put(taskFolder);
1108 return { taskFolder, branch, laidOutByProject: false, repositoriesStartedFromOrigin };
1109 }).pipe(
1110 Effect.onError(() =>
1111 // Recorded first: a checkout the rollback cannot remove must still be known afterwards.
1112 store.put(current()).pipe(
1113 Effect.ignoreCause({ log: true }),
1114 Effect.andThen(
1115 removeLocked(
1116 current(),
1117 { force: true, forget: true, deleteBranch: branch },
1118 hadBranch,
1119 layoutStarted,
1120 ),
1121 ),
1122 Effect.tap(({ kept }) =>
1123 kept.length === 0
1124 ? Effect.void
1125 : Effect.logWarning("A failed task folder was not fully removed", { root, kept }),
1126 ),
1127 Effect.ignoreCause({ log: true }),
1128 // A checkout the layout command made and this service refused was deleted as files.
1129 Effect.andThen(
1130 Effect.forEach(
1131 checkedOutFrom,
1132 (cwd) => git.pruneWorktrees({ cwd }).pipe(Effect.ignoreCause({ log: true })),
1133 { concurrency: REPOSITORY_CONCURRENCY, discard: true },
1134 ),
1135 ),
1136 // Only now that no checkout is registered on it; most went with their checkout.
1137 Effect.andThen(
1138 Effect.forEach(
1139 branchMadeIn,
1140 (cwd) =>
1141 git.deleteLocalBranch({ cwd, refName: branch, force: true }).pipe(Effect.ignore),
1142 { concurrency: REPOSITORY_CONCURRENCY, discard: true },
1143 ),
1144 ),
1145 ),
1146 ),
1147 Effect.mapError((cause) =>
1148 isTaskFolderError(cause)
1149 ? cause
1150 : fail("create", "Could not create the worktrees")(cause),
1151 ),
1152 );
1153 },
1154 );
1155​
1156 /** The project's setting for where new worktrees start. */
1157 const startsFromOrigin = (operation: TaskFolderError["operation"], projectId: ProjectId) =>
1158 settings.getSettings.pipe(
1159 Effect.mapError(fail(operation, "Could not read settings")),
1160 Effect.map(
1161 (current) =>
1162 resolveProjectSettings(current, projectId).settings.newWorktreesStartFromOrigin,
1163 ),
1164 );
1165​
1166 const createForProjectFolder: TaskFolders["Service"]["createForProjectFolder"] = Effect.fn(
1167 "TaskFolders.createForProjectFolder",
1168 )(function* (input) {
1169 if (input.path !== null || input.newRefName === undefined) return null;
1170 const project = yield* projects
1171 .findActiveByWorkspaceRoot(input.cwd)
1172 .pipe(Effect.mapError(fail("plan", "Could not read the project")));
1173 if (Option.isNone(project)) return null;
1174 const { projectId } = project.value;
1175 const taskPlan = yield* plan({ projectId });
1176 if (taskPlan === null) return null;
1177 const { taskFolder, branch } = yield* create({
1178 plan: taskPlan,
1179 branch: input.newRefName,
1180 projectStart: { refName: input.refName, baseRefName: input.baseRefName ?? input.refName },
1181 baseBranch: input.baseRefName ?? input.refName,
1182 startFromOrigin: yield* startsFromOrigin("create", projectId),
1183 });
1184 return { worktree: { path: taskFolder.projectPath, refName: branch } };
1185 });
1186​
1187 const addRepository: TaskFolders["Service"]["addRepository"] = Effect.fn(
1188 "TaskFolders.addRepository",
1189 )(function* (input) {
1190 const refuse = (detail: string) => new TaskFolderError({ operation: "add-repository", detail });
1191 const thread = yield* projections
1192 .getThreadShell(input.threadId)
1193 .pipe(Effect.mapError(fail("add-repository", "Could not read the thread")));
1194 if (thread === null || thread.worktreePath === null || thread.branch === null)
1195 return yield* refuse("This thread does not work in a worktree.");
1196 const recordedBranch = thread.branch;
1197 const startFromOrigin =
1198 input.startFromOrigin ?? (yield* startsFromOrigin("add-repository", thread.projectId));
1199 const found = yield* requireTaskFolder("add-repository", thread.worktreePath);
1200 return yield* locked(
1201 found,
1202 Effect.gen(function* () {
1203 // Read again under the lease: another add may have landed.
1204 const taskFolder = yield* requireTaskFolder("add-repository", found.root);
1205 // The thread's record lags a rename of its branch, so a checkout says which one it is.
1206 const checkedOut = taskFolder.projectIsWorktree
1207 ? taskFolder.projectPath
1208 : taskFolder.repositories[0]?.worktreePath;
1209 const branch =
1210 (checkedOut === undefined
1211 ? null
1212 : yield* git.currentBranch(checkedOut).pipe(Effect.orElseSucceed(() => null))) ??
1213 recordedBranch;
1214 const project = yield* readProject("add-repository", taskFolder.projectId);
1215 const repositoryPath = path.resolve(input.repositoryPath);
1216 const folder = (yield* trackedFolders(project)).find(
1217 (candidate) => path.resolve(candidate.path) === repositoryPath,
1218 );
1219 if (folder === undefined)
1220 return yield* refuse(`"${input.repositoryPath}" is not a tracked folder of the project.`);
1221 if (!(yield* isRepository(repositoryPath)))
1222 return yield* refuse(`"${input.repositoryPath}" is not a Git repository.`);
1223 if (yield* isSubmodule(repositoryPath))
1224 return yield* refuse(`${folder.name} is a submodule, so it comes with its repository.`);
1225 if (taskFolder.repositories.some((entry) => entry.repositoryPath === repositoryPath))
1226 return yield* refuse(`${folder.name} already has a worktree in this thread.`);
1227 if (!isWithinRoot(path, repositoryPath, taskFolder.anchor))
1228 return yield* refuse(
1229 `${folder.name} lies outside the folders this thread's worktree was laid out for. Start a new worktree thread to include it.`,
1230 );
1231 const worktreePath = mapped(taskFolder, repositoryPath);
1232 const insideLinkedProject =
1233 !taskFolder.projectIsWorktree &&
1234 isWithinRoot(path, repositoryPath, taskFolder.projectRoot) &&
1235 repositoryPath !== taskFolder.projectRoot;
1236 const wasLinked =
1237 insideLinkedProject &&
1238 Option.isSome(yield* fileSystem.readLink(worktreePath).pipe(Effect.option));
1239 const opened = insideLinkedProject
1240 ? yield* openLinkedPath(
1241 taskFolder.projectRoot,
1242 taskFolder.projectPath,
1243 path.relative(taskFolder.projectRoot, repositoryPath),
1244 ).pipe(Effect.mapError(fail("add-repository", "Could not prepare the folder")))
1245 : true;
1246 if (!opened || (yield* occupied(worktreePath)))
1247 return yield* refuse(`${worktreePath} already holds files, so no worktree can go there.`);
1248 // The link the worktree took the place of comes back when the worktree does not stay.
1249 const relink = wasLinked
1250 ? // Git may or may not have left an empty folder where the link was.
1251 removeEmptyDirectory(worktreePath).pipe(
1252 Effect.ignore,
1253 Effect.andThen(fileSystem.symlink(repositoryPath, worktreePath)),
1254 Effect.ignoreCause({ log: true }),
1256 : Effect.void;
1257 const existing = (yield* git
1258 .listLocalBranchNames(repositoryPath)
1259 .pipe(Effect.mapError(fail("add-repository", "Could not list branches")))).includes(
1260 branch,
1261 );
1262 yield* Effect.gen(function* () {
1263 yield* fileSystem.makeDirectory(path.dirname(worktreePath), { recursive: true });
1264 if (existing) {
1265 // The thread's branch is already there, so it is checked out, not started again.
1266 yield* git.createWorktree({
1267 cwd: repositoryPath,
1268 refName: branch,
1269 path: worktreePath,
1270 });
1271 } else {
1272 const start = yield* repositoryStart(repositoryPath, startFromOrigin);
1273 yield* git.createWorktree({
1274 cwd: repositoryPath,
1275 refName: start.refName,
1276 newRefName: branch,
1277 baseRefName: start.baseRefName,
1278 path: worktreePath,
1279 });
1281 }).pipe(
1282 Effect.onError(() => relink),
1283 Effect.mapError(fail("add-repository", `Could not create the ${folder.name} worktree`)),
1284 );
1285 const updated: TaskFolder = {
1286 ...taskFolder,
1287 repositories: [
1288 ...taskFolder.repositories,
1289 { repositoryPath, worktreePath, name: folder.name },
1290 ],
1291 };
1292 yield* store
1293 .put(updated)
1294 .pipe(
1295 Effect.onError(() =>
1296 removeCheckout(
1297 { repositoryPath, worktreePath },
1298 true,
1299 existing ? undefined : branch,
1300 ).pipe(Effect.ignoreCause({ log: true }), Effect.andThen(relink)),
1301 ),
1302 );
1303 return updated;
1304 }),
1305 );
1306 });
1307​
1308 const remove: TaskFolders["Service"]["remove"] = Effect.fnUntraced(function* (input) {
1309 const taskFolder = yield* store.findContaining(input.root);
1310 if (taskFolder === null || taskFolder.root !== input.root) return { removed: [], kept: [] };
1311 return yield* removeLocked(taskFolder, input);
1312 });
1313​
1314 const removeIfTaskFolder: TaskFolders["Service"]["removeIfTaskFolder"] = Effect.fn(
1315 "TaskFolders.removeIfTaskFolder",
1316 )(function* (input) {
1317 const taskFolder = yield* store.findContaining(input.path);
1318 const target = path.resolve(input.path);
1319 if (taskFolder === null || (target !== taskFolder.root && target !== taskFolder.projectPath))
1320 return false;
1321 const { kept } = yield* removeLocked(taskFolder, { force: input.force, forget: true });
1322 if (kept.length > 0) {
1323 return yield* new TaskFolderError({
1324 operation: "remove",
1325 detail: `Kept ${kept.map((entry) => `${entry.path} (${entry.reason})`).join(", ")}.`,
1326 });
1328 return true;
1329 });
1330​
1331 const renameBranch: TaskFolders["Service"]["renameBranch"] = Effect.fn(
1332 "TaskFolders.renameBranch",
1333 )(function* (input) {
1334 const taskFolder = yield* requireTaskFolder("create", input.root);
1335 const cwds = [
1336 ...(taskFolder.projectIsWorktree ? [taskFolder.projectPath] : []),
1337 ...taskFolder.repositories.map((repository) => repository.worktreePath),
1338 ];
1339 if (cwds.length === 0 || input.oldBranch === input.newBranch)
1340 return { branch: input.oldBranch };
1341 const renameFailed = fail("create", "Could not rename the branch");
1342 const branch =
1343 input.exactName === true
1344 ? input.newBranch
1345 : yield* freeBranchName(
1346 "create",
1347 input.newBranch,
1348 (yield* branchNames(cwds).pipe(Effect.mapError(renameFailed))).map((list) =>
1349 list.filter((existing) => existing !== input.oldBranch),
1350 ),
1351 );
1352 const renamed: string[] = [];
1353 yield* Effect.forEach(
1354 cwds,
1355 (cwd) =>
1356 git
1357 .renameBranch({ cwd, oldBranch: input.oldBranch, newBranch: branch, exactName: true })
1358 .pipe(Effect.tap(() => Effect.sync(() => renamed.push(cwd)))),
1359 { discard: true },
1360 ).pipe(
1361 // One name everywhere or the old one everywhere.
1362 Effect.onError(() =>
1363 Effect.forEach(
1364 renamed,
1365 (cwd) =>
1366 git
1367 .renameBranch({ cwd, oldBranch: branch, newBranch: input.oldBranch, exactName: true })
1368 .pipe(Effect.ignoreCause({ log: true })),
1369 { discard: true },
1370 ),
1371 ),
1372 Effect.mapError(renameFailed),
1373 );
1374 return { branch };
1375 });
1376​
1377 const restore: TaskFolders["Service"]["restore"] = Effect.fn("TaskFolders.restore")(function* ({
1378 taskFolder,
1379 branch,
1380 recreate,
1381 }) {
1382 const restoreFailed = fail("create", "Could not restore the worktrees");
1383 // A project that lays its own folder out rebuilds it; whatever is still missing after that
1384 // comes back as a plain checkout below.
1385 const layout = yield* worktreeLayout(taskFolder.projectRoot);
1386 const present = yield* Effect.forEach(
1387 [taskFolder.projectPath, ...taskFolder.repositories.map((entry) => entry.worktreePath)],
1388 exists,
1389 );
1390 if (layout !== null && present.includes(false)) {
1391 yield* fileSystem
1392 .makeDirectory(taskFolder.root, { recursive: true })
1393 .pipe(Effect.mapError(restoreFailed));
1394 yield* runLayoutCommand(
1395 "create",
1396 layout.create,
1397 taskFolder,
1398 branch,
1399 undefined,
1400 taskFolder.repositories.map((repository) => repository.repositoryPath),
1401 ).pipe(Effect.ignoreCause({ log: true }));
1403 const recreateMissing = Effect.fnUntraced(function* (checkout: TaskFolderCheckout) {
1404 if (yield* isRepository(checkout.worktreePath)) {
1405 // Another checkout in its place is not the thread's: resuming there would work on it.
1406 if ((yield* linkedGitDir(checkout)) !== null) return;
1407 return yield* new TaskFolderError({
1408 operation: "create",
1409 detail: `${checkout.worktreePath} holds a checkout that is not a worktree of ${checkout.repositoryPath}. Move it away to restore the thread's worktree.`,
1410 });
1412 yield* fileSystem
1413 .makeDirectory(path.dirname(checkout.worktreePath), { recursive: true })
1414 .pipe(Effect.mapError(restoreFailed));
1415 yield* recreate(checkout);
1416 });
1417 if (taskFolder.projectIsWorktree) {
1418 yield* recreateMissing({
1419 worktreePath: taskFolder.projectPath,
1420 repositoryPath: taskFolder.projectRoot,
1421 });
1422 } else if (!(yield* exists(taskFolder.projectPath))) {
1423 const project = yield* readProject("create", taskFolder.projectId);
1424 const tracked = yield* Effect.filter(
1425 (yield* trackedFolders(project)).map((folder) => path.resolve(folder.path)),
1426 isRepository,
1427 );
1428 // A recorded repository the project no longer tracks still gets its worktree, never a link.
1429 yield* linkFolder(taskFolder.projectRoot, taskFolder.projectPath, [
1430 ...tracked,
1431 ...taskFolder.repositories.map((repository) => repository.repositoryPath),
1432 ]).pipe(Effect.mapError(restoreFailed));
1434 for (const repository of taskFolder.repositories.toSorted(
1435 (left, right) => depth(left.worktreePath) - depth(right.worktreePath),
1436 )) {
1437 yield* recreateMissing(repository);
1439 });
1440​
1441 return TaskFolders.of({
1442 plan,
1443 create,
1444 createForProjectFolder,
1445 addRepository,
1446 find: store.findContaining,
1447 remove,
1448 removeIfTaskFolder,
1449 renameBranch,
1450 restore,
1451 });
1452});
1453​
1454export const layer = Layer.effect(TaskFolders, make);