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

worktreeCheckoutCache.ts

854 lines33.7 KB

1// @effect-diagnostics nodeBuiltinImport:off - Git index stat data needs bigint lstat, which FileSystem lacks.
2import * as NodeCrypto from "node:crypto";
3import * as NodeFSP from "node:fs/promises";
4​
5import { GitCommandError } from "@t3tools/contracts";
6import * as HostProcess from "@t3tools/shared/HostProcess";
7import * as Clock from "effect/Clock";
8import * as Effect from "effect/Effect";
9import * as Exit from "effect/Exit";
10import * as FileSystem from "effect/FileSystem";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
13import * as Schema from "effect/Schema";
14import * as Semaphore from "effect/Semaphore";
15​
16import * as CheckoutCloner from "./CheckoutCloner.ts";
17import type * as GitVcsDriver from "./GitVcsDriver.ts";
18import { indexEntryStat, parseIndex, restatIndex, type IndexEntryStat } from "./gitIndexStat.ts";
19​
20const KEEP_PER_REPOSITORY = 3;
21// Moving a cached checkout costs about 0.1 ms per changed file when a worktree is created, while
22// replacing it means writing and later deleting a whole checkout, which slows the next clone.
23const REBUILD_AFTER_CHANGED_FILES = 500;
24const UNUSED_REPOSITORY_MS = 30 * 24 * 60 * 60 * 1000;
25// Older leftovers came from a crash, not from work in progress. A full build of a huge repository
26// can take minutes, and its staging folder's own mtime does not change while files land inside.
27const ABANDONED_STAGING_MS = 24 * 60 * 60 * 1000;
28const ABANDONED_TRASH_MS = 10 * 60 * 1000;
29const STAT_BATCH = 512;
30const TREE_ID = /^[0-9a-f]{40}$/;
31// `<tree>-<fingerprint>`: checkouts of one tree under different settings never replace each other.
32const ENTRY_NAME = /^([0-9a-f]{40})-([0-9a-f]{16})$/;
33const GIT_FALSE = new Set(["false", "no", "off", "0"]);
34const MAX_LIST_BYTES = 256 * 1024 * 1024;
35const NULL_OID = "0".repeat(40);
36// 2.42 names its system attributes file, which the fingerprint needs; `git hook run` is from 2.36.
37const MIN_GIT = [2, 42] as const;
38// Settings that change what a checkout writes. Read in the new worktree, so conditional includes apply.
39const CHECKOUT_CONFIG =
40 "^(core\\.(autocrlf|eol|symlinks|safecrlf|checkroundtripencoding|precomposeunicode|ignorecase|filemode|attributesfile|sparsecheckout)|filter\\.|lfs\\.|extensions\\.)";
41// Keeps cache indexes in the one format the stat rewriter reads.
42const CACHE_INDEX_CONFIG = [
43 "index.version=2",
44 "index.skipHash=false",
45 "core.splitIndex=false",
46 "core.untrackedCache=false",
47 "core.fsmonitor=false",
48 "core.sparseCheckout=false",
49 // Private builds must not run the repository's hooks.
50 "core.hooksPath=/dev/null",
51 "checkout.workers=0",
52 "submodule.recurse=false",
53].flatMap((setting) => ["-c", setting]);
54​
55// How a case- and normalization-insensitive volume such as default APFS compares names.
56const foldCase = (file: string) => file.normalize("NFC").toLowerCase();
57​
58// `check-attr --all -z` output: any `filter` attribute counts, as `unset` can also name a driver.
59function namesFilter(output: string): boolean {
60 const fields = output.split("\0");
61 for (let index = 1; index < fields.length; index += 3) {
62 if (fields[index] === "filter") return true;
63 }
64 return false;
66​
67/** Every folder that holds one of `paths`, including the root as "". */
68function parentDirectories(paths: Iterable<string>): Set<string> {
69 const directories = new Set([""]);
70 for (const entryPath of paths) {
71 for (let slash = entryPath.lastIndexOf("/"); slash > 0;) {
72 const directory = entryPath.slice(0, slash);
73 if (directories.has(directory)) break;
74 directories.add(directory);
75 slash = directory.lastIndexOf("/");
76 }
77 }
78 return directories;
80​
81class WorktreeCheckoutCacheError extends Schema.TaggedError<WorktreeCheckoutCacheError>()(
82 "WorktreeCheckoutCacheError",
83 { detail: Schema.String },
84) {
85 override get message(): string {
86 return this.detail;
87 }
89​
90interface CacheEntry {
91 readonly directory: string;
92 readonly tree: string;
93 readonly fingerprint: string;
94 readonly mtimeMs: number;
96​
97/**
98 * Clones a private, Git-written checkout with APFS copy-on-write, then rewrites the index's stat
99 * data so Git trusts the clones without re-reading them. An older cached checkout is moved to the
100 * requested tree with `read-tree -m -u`. Undefined where the platform cannot clone a folder.
101 */
102export const makeWorktreeCheckoutCache = Effect.fn("WorktreeCheckoutCache.make")(function* (input: {
103 readonly cacheDir: string;
104 readonly execute: GitVcsDriver.GitVcsDriver["Service"]["execute"];
105}) {
106 const clone = yield* CheckoutCloner.CheckoutCloner;
107 if (clone === undefined) return undefined;
108 const fileSystem = yield* FileSystem.FileSystem;
109 const path = yield* Path.Path;
110 const scope = yield* Effect.scope;
111 const homeDirectory = yield* HostProcess.HomeDirectory;
112 const environment = yield* HostProcess.Environment;
113 const builds = yield* Semaphore.make(1);
114 const pendingBuilds = new Set<string>();
115 // Bumped by `clear`, so a build that started before it does not publish its result.
116 let generation = 0;
117 const { cacheDir, execute } = input;
118​
119 const git = (
120 operation: string,
121 cwd: string,
122 args: ReadonlyArray<string>,
123 env?: NodeJS.ProcessEnv,
124 ) =>
125 execute({
126 operation: `WorktreeCheckoutCache.git.${operation}`,
127 cwd,
128 args,
129 allowNonZeroExit: true,
130 timeoutMs: null,
131 ...(env ? { env } : {}),
132 }).pipe(
133 Effect.map((result) => (result.exitCode === 0 ? result.stdout : null)),
134 Effect.orElseSucceed(() => null),
135 );
136​
137 const gitSupported = yield* Effect.cached(
138 git("version", homeDirectory, ["version"]).pipe(
139 Effect.map((stdout) => {
140 const match = stdout?.match(/git version (\d+)\.(\d+)/);
141 if (!match) return false;
142 const [major, minor] = [Number(match[1]), Number(match[2])];
143 return major > MIN_GIT[0] || (major === MIN_GIT[0] && minor >= MIN_GIT[1]);
144 }),
145 ),
146 );
147​
148 const describe = Effect.fn("WorktreeCheckoutCache.describe")(function* (
149 cwd: string,
150 rev: string,
151 ) {
152 const stdout = yield* git("describe", cwd, [
153 "rev-parse",
154 "--path-format=absolute",
155 "--git-common-dir",
156 "--show-object-format",
157 "--git-path",
158 "hooks/post-index-change",
159 `${rev}^{commit}`,
160 `${rev}^{tree}`,
161 ]);
162 const [commonDir, objectFormat, indexHook, commit, tree] = stdout?.trim().split("\n") ?? [];
163 if (
164 !commonDir ||
165 objectFormat !== "sha1" ||
166 !indexHook ||
167 !commit ||
168 !tree ||
169 !TREE_ID.test(tree)
170 ) {
171 return null;
172 }
173 const realCommonDir = yield* fileSystem
174 .realPath(commonDir)
175 .pipe(Effect.orElseSucceed(() => commonDir));
176 const repositoryKey = NodeCrypto.createHash("sha256")
177 .update(realCommonDir)
178 .digest("hex")
179 .slice(0, 16);
180 return {
181 commonDir,
182 commit,
183 tree,
184 indexHook: path.resolve(cwd, indexHook),
185 bucket: path.join(cacheDir, repositoryKey),
186 };
187 });
188​
189 // Empty when `GIT_ATTR_NOSYSTEM` turns the system attributes file off.
190 const systemAttributePaths = yield* Effect.cached(
191 git("systemAttributes", homeDirectory, ["var", "GIT_ATTR_SYSTEM"]).pipe(
192 Effect.map((stdout) => (stdout?.trim() ? [stdout.trim()] : [])),
193 ),
194 );
195​
196 // Null for setups the cache cannot reproduce, such as sparse checkouts.
197 const fingerprint = Effect.fn("WorktreeCheckoutCache.fingerprint")(function* (
198 cwd: string,
199 commonDir: string,
200 ) {
201 const config =
202 (yield* git("fingerprint", cwd, ["config", "--null", "--get-regexp", CHECKOUT_CONFIG])) ?? "";
203 const pairs = config
204 .split("\0")
205 .filter(Boolean)
206 .map((pair) => {
207 const newline = pair.indexOf("\n");
208 return newline < 0
209 ? ([pair, ""] as const)
210 : ([pair.slice(0, newline), pair.slice(newline + 1)] as const);
211 });
212 const sparse = pairs.findLast(([key]) => key === "core.sparsecheckout")?.[1];
213 if (sparse !== undefined && !GIT_FALSE.has(sparse.toLowerCase())) return null;
214 const attributesFile = pairs
215 .findLast(([key]) => key === "core.attributesfile")?.[1]
216 ?.replace(/^~(?=$|\/)/, homeDirectory);
217 // Git reads a relative path from each checkout, which differs between the cache and the worktree.
218 if (attributesFile !== undefined && !path.isAbsolute(attributesFile)) return null;
219 const attributePaths = [
220 ...(yield* systemAttributePaths),
221 path.join(commonDir, "info", "attributes"),
222 attributesFile ??
223 path.join(
224 environment.XDG_CONFIG_HOME || path.join(homeDirectory, ".config"),
225 "git",
226 "attributes",
227 ),
228 ];
229 const attributes = yield* Effect.forEach(attributePaths, (file) =>
230 fileSystem.readFileString(file).pipe(Effect.orElseSucceed(() => "")),
231 );
232 const hash = NodeCrypto.createHash("sha256").update(config);
233 for (const contents of attributes) hash.update("\0").update(contents);
234 return hash.digest("hex").slice(0, 16);
235 });
236​
237 const listEntries = Effect.fn("WorktreeCheckoutCache.listEntries")(function* (bucket: string) {
238 const names = yield* fileSystem.readDirectory(bucket).pipe(Effect.orElseSucceed(() => []));
239 const entries = yield* Effect.forEach(
240 names.flatMap((name) => {
241 const match = ENTRY_NAME.exec(name);
242 return match ? [{ name, tree: match[1]!, fingerprint: match[2]! }] : [];
243 }),
244 ({ name, tree, fingerprint: entryFingerprint }) => {
245 const directory = path.join(bucket, name);
246 return fileSystem.stat(directory).pipe(
247 Effect.map((info): CacheEntry => ({
248 directory,
249 tree,
250 fingerprint: entryFingerprint,
251 mtimeMs: Option.match(info.mtime, {
252 onNone: () => 0,
253 onSome: (date) => date.getTime(),
254 }),
255 })),
256 Effect.option,
257 );
258 },
259 { concurrency: 8 },
260 );
261 return entries
262 .flatMap((entry) => (entry._tag === "Some" ? [entry.value] : []))
263 .toSorted((left, right) => right.mtimeMs - left.mtimeMs);
264 });
265​
266 const touch = (target: string) =>
267 Clock.currentTimeMillis.pipe(
268 Effect.flatMap((now) =>
269 Effect.tryPromise({
270 try: () => NodeFSP.utimes(target, now / 1000, now / 1000),
271 catch: (cause) =>
272 new WorktreeCheckoutCacheError({ detail: `could not touch ${target}: ${cause}` }),
273 }),
274 ),
275 Effect.ignore,
276 );
277​
278 // Untraced: one stat per tracked file, already covered by the caller's span.
279 const statEntries = Effect.fnUntraced(function* (root: string, paths: ReadonlyArray<string>) {
280 return yield* Effect.tryPromise({
281 try: async () => {
282 const stats: Array<IndexEntryStat | undefined> = [];
283 for (let start = 0; start < paths.length; start += STAT_BATCH) {
284 const batch = await Promise.all(
285 paths.slice(start, start + STAT_BATCH).map((entryPath) =>
286 NodeFSP.lstat(`${root}/${entryPath}`, { bigint: true }).then(
287 indexEntryStat,
288 (error) => {
289 if (error?.code === "ENOENT") return undefined;
290 throw error;
291 },
292 ),
293 ),
294 );
295 stats.push(...batch);
296 }
297 return stats;
298 },
299 catch: (cause) =>
300 new WorktreeCheckoutCacheError({ detail: `could not stat ${root}: ${cause}` }),
301 });
302 });
303​
304 /**
305 * Writes `target` from the index at `source` with stat data from the files under `root`, and
306 * returns what it read. Null when the index or the files cannot be trusted.
307 */
308 const restate = Effect.fn("WorktreeCheckoutCache.restate")(function* (input: {
309 readonly source: string;
310 readonly target: string;
311 readonly root: string;
312 readonly verify: boolean;
313 }) {
314 const parsed = parseIndex(yield* fileSystem.readFile(input.source));
315 if (parsed === null) return null;
316 const paths = parsed.entries.map((entry) => entry.path);
317 const stats = yield* statEntries(input.root, paths);
318 const restated = restatIndex(parsed, stats, { verify: input.verify });
319 if (restated === null) return null;
320 const temporary = `${input.target}.t3-${NodeCrypto.randomUUID()}`;
321 yield* Effect.uninterruptible(
322 fileSystem
323 .writeFile(temporary, restated)
324 .pipe(Effect.andThen(fileSystem.rename(temporary, input.target))),
325 );
326 return { paths, stats };
327 });
328​
329 // Untraced: one stat per folder, already covered by the caller's span.
330 const directoryTimes = Effect.fnUntraced(function* (
331 root: string,
332 directories: ReadonlyArray<string>,
333 ) {
334 return yield* Effect.tryPromise({
335 try: () =>
336 Promise.all(
337 directories.map((directory) =>
338 NodeFSP.lstat(directory === "" ? root : `${root}/${directory}`, { bigint: true }).then(
339 (stat) => String(stat.mtimeNs),
340 () => "missing",
341 ),
342 ),
343 ),
344 catch: (cause) =>
345 new WorktreeCheckoutCacheError({ detail: `could not stat folders in ${root}: ${cause}` }),
346 });
347 });
348​
349 // Adding or removing a file changes its folder's mtime, so this catches files the index lacks.
350 const recordDirectories = Effect.fn("WorktreeCheckoutCache.recordDirectories")(function* (
351 entryDirectory: string,
352 recorded: {
353 readonly paths: ReadonlyArray<string>;
354 readonly stats: ReadonlyArray<IndexEntryStat | undefined>;
355 },
356 ) {
357 const directories = parentDirectories(recorded.paths);
358 for (const [index, entryPath] of recorded.paths.entries()) {
359 if (recorded.stats[index]?.kind === "directory") directories.add(entryPath);
360 }
361 // Folders whose names differ only in case share one spelling on disk, which depends on history.
362 const folded = new Set([...directories].map((directory) => foldCase(directory)));
363 if (folded.size !== directories.size) {
364 return yield* new WorktreeCheckoutCacheError({ detail: "folder names differ only in case" });
365 }
366 const list = [...directories];
367 // Backdated, so any later change moves the time even on a filesystem with a coarse clock.
368 const root = path.join(entryDirectory, "files");
369 yield* Effect.tryPromise({
370 try: () =>
371 Promise.all(
372 list.map((directory) =>
373 NodeFSP.utimes(directory === "" ? root : `${root}/${directory}`, 1_000_000, 1_000_000),
374 ),
375 ),
376 catch: (cause) =>
377 new WorktreeCheckoutCacheError({ detail: `could not backdate cached folders: ${cause}` }),
378 });
379 const times = yield* directoryTimes(root, list);
380 yield* fileSystem.writeFileString(
381 path.join(entryDirectory, "directories"),
382 list.map((directory, index) => `${times[index]}\0${directory}\0`).join(""),
383 );
384 });
385​
386 const directoriesUnchanged = Effect.fn("WorktreeCheckoutCache.directoriesUnchanged")(
387 function* (entry: CacheEntry) {
388 const recorded = (yield* fileSystem.readFileString(path.join(entry.directory, "directories")))
389 .split("\0")
390 .slice(0, -1);
391 const times = recorded.filter((_, index) => index % 2 === 0);
392 const directories = recorded.filter((_, index) => index % 2 === 1);
393 const current = yield* directoryTimes(path.join(entry.directory, "files"), directories);
394 return directories.length > 0 && current.every((time, index) => time === times[index]);
395 },
396 (effect) => Effect.orElseSucceed(effect, () => false),
397 );
398​
399 const changedPaths = Effect.fn("WorktreeCheckoutCache.changedPaths")(function* (
400 cwd: string,
401 from: string,
402 to: string,
403 ) {
404 const stdout = yield* git("changes", cwd, [
405 "diff-tree",
406 "-r",
407 "-z",
408 "--name-status",
409 "--no-renames",
410 from,
411 to,
412 ]);
413 if (stdout === null) return null;
414 const fields = stdout.split("\0");
415 const added: Array<string> = [];
416 const deleted: Array<string> = [];
417 // Added or changed: what `read-tree -m -u` writes itself.
418 const written: Array<string> = [];
419 let count = 0;
420 let attributes = false;
421 for (let index = 0; index + 1 < fields.length; index += 2) {
422 const [status, file] = [fields[index]!, fields[index + 1]!];
423 count++;
424 // `read-tree -m -u` leaves unchanged files alone, even when their attributes changed.
425 if (file === ".gitattributes" || file.endsWith("/.gitattributes")) attributes = true;
426 if (status === "A") added.push(file);
427 if (status === "D") deleted.push(file);
428 else written.push(file);
429 }
430 return { count, attributes, added, deleted, written };
431 });
432​
433 // A smudge filter's output can depend on the environment and the network, as with Git LFS.
434 const usesFilter = Effect.fn("WorktreeCheckoutCache.usesFilter")(function* (
435 cwd: string,
436 bucket: string,
437 tree: string,
438 ) {
439 // An index of the tree lets `check-attr` read its `.gitattributes` on any Git version.
440 const index = path.join(bucket, `.attributes-${NodeCrypto.randomUUID()}`);
441 const env = { GIT_INDEX_FILE: index };
442 const run = (args: ReadonlyArray<string>, stdin?: string) =>
443 execute({
444 operation: "WorktreeCheckoutCache.git.filters",
445 cwd,
446 args,
447 env,
448 allowNonZeroExit: true,
449 maxOutputBytes: MAX_LIST_BYTES,
450 ...(stdin === undefined ? {} : { stdin }),
451 }).pipe(Effect.map((result) => (result.exitCode === 0 ? result.stdout : null)));
452 return yield* Effect.gen(function* () {
453 if ((yield* run([...CACHE_INDEX_CONFIG, "read-tree", tree])) === null) return true;
454 const files = yield* run(["ls-files", "-z"]);
455 if (files === null) return true;
456 const output = yield* run(["check-attr", "--cached", "--all", "-z", "--stdin"], files);
457 return output === null || namesFilter(output);
458 }).pipe(
459 Effect.orElseSucceed(() => true),
460 Effect.ensuring(fileSystem.remove(index).pipe(Effect.ignore)),
461 );
462 });
463​
464 // Attributes come from the cloned `.gitattributes` files, which the move leaves unchanged.
465 const writesWithFilter = Effect.fn("WorktreeCheckoutCache.writesWithFilter")(function* (
466 cwd: string,
467 files: ReadonlyArray<string>,
468 ) {
469 if (files.length === 0) return false;
470 const output = yield* execute({
471 operation: "WorktreeCheckoutCache.git.filters",
472 cwd,
473 args: ["check-attr", "--all", "-z", "--stdin"],
474 stdin: files.map((file) => `${file}\0`).join(""),
475 allowNonZeroExit: true,
476 maxOutputBytes: MAX_LIST_BYTES,
477 }).pipe(
478 Effect.map((result) => (result.exitCode === 0 ? result.stdout : null)),
479 Effect.orElseSucceed(() => null),
480 );
481 return output === null || namesFilter(output);
482 });
483​
484 // Renamed first so nothing clones a half-deleted checkout; deleting a large one takes seconds.
485 const discard = Effect.fn("WorktreeCheckoutCache.discard")(
486 function* (target: string) {
487 const trashed = `${target}.trash-${NodeCrypto.randomUUID()}`;
488 yield* fileSystem.rename(target, trashed);
489 yield* fileSystem.remove(trashed, { recursive: true });
490 },
491 // Uninterruptible: deleting is not resumable, and a half-deleted folder must not be left named.
492 (effect) => Effect.ignore(Effect.uninterruptible(effect)),
493 );
494​
495 const gitDirOf = Effect.fn("WorktreeCheckoutCache.gitDirOf")(function* (worktreePath: string) {
496 const contents = (yield* fileSystem.readFileString(path.join(worktreePath, ".git"))).replace(
497 /[\r\n]+$/u,
498 "",
499 );
500 const prefix = "gitdir: ";
501 if (!contents.startsWith(prefix) || contents.length === prefix.length) {
502 return yield* new WorktreeCheckoutCacheError({
503 detail: `${worktreePath} is not a linked worktree`,
504 });
505 }
506 return path.resolve(worktreePath, contents.slice(prefix.length));
507 });
508​
509 /**
510 * Creates the worktree from the cache. False means nothing was created and the caller should
511 * run `git worktree add`; any partial worktree has been removed again.
512 */
513 const create = Effect.fn("WorktreeCheckoutCache.create")(function* (input: {
514 readonly cwd: string;
515 readonly worktreePath: string;
516 readonly refName: string;
517 readonly checkoutWorkers: string;
518 readonly lockReason?: string | undefined;
519 }) {
520 if (!(yield* gitSupported)) return false;
521 const worktreePath = path.resolve(input.cwd, input.worktreePath);
522 const requested = yield* describe(input.cwd, input.refName);
523 if (requested === null) return false;
524 const entries = yield* listEntries(requested.bucket);
525 if (entries.length === 0) return false;
526 // A clone only works within one volume.
527 const parent = path.dirname(worktreePath);
528 yield* fileSystem.makeDirectory(parent, { recursive: true }).pipe(Effect.ignore);
529 const [bucketInfo, parentInfo] = yield* Effect.all([
530 fileSystem.stat(requested.bucket),
531 fileSystem.stat(parent),
532 ]).pipe(Effect.orElseSucceed(() => [null, null] as const));
533 if (bucketInfo === null || parentInfo === null || bucketInfo.dev !== parentInfo.dev) {
534 return false;
535 }
536​
537 const populate = Effect.gen(function* () {
538 // What Git checked out, which can differ from `requested` when a tag shares the branch name.
539 const target = yield* describe(worktreePath, "HEAD");
540 if (target === null || (yield* fileSystem.exists(target.indexHook))) return null;
541 const worktreeFingerprint = yield* fingerprint(worktreePath, target.commonDir);
542 if (worktreeFingerprint === null) return null;
543 const compatible = entries.filter((entry) => entry.fingerprint === worktreeFingerprint);
544 let base = compatible.find((entry) => entry.tree === target.tree);
545 let changes: Effect.Success<ReturnType<typeof changedPaths>> = null;
546 for (const entry of base === undefined ? compatible : []) {
547 changes = yield* changedPaths(worktreePath, entry.tree, target.tree);
548 if (changes !== null && !changes.attributes) {
549 base = entry;
550 break;
551 }
552 }
553 if (base === undefined) return null;
554 // A cached file changed after Git wrote it; never hand it out again.
555 const reject = (entry: CacheEntry) =>
556 Effect.logWarning("worktree checkout cache entry changed; discarding it", {
557 directory: entry.directory,
558 }).pipe(Effect.andThen(discard(entry.directory)), Effect.as(null));
559 if (!(yield* directoriesUnchanged(base))) return yield* reject(base);
560 yield* Effect.all([touch(base.directory), touch(requested.bucket)], { discard: true });
561​
562 const files = path.join(base.directory, "files");
563 // The worktree folder already holds Git's `.git` file, so its entries are cloned one by one.
564 yield* Effect.forEach(
565 yield* fileSystem.readDirectory(files),
566 (name) => clone(path.join(files, name), path.join(worktreePath, name)),
567 { discard: true },
568 );
569 // Checked again: a file added during the clone would otherwise come along unnoticed.
570 if (!(yield* directoriesUnchanged(base))) return yield* reject(base);
571 // A tracked hooks folder only exists once the files do; Git would have run this hook.
572 if (yield* fileSystem.exists(target.indexHook)) return null;
573 const restated = yield* restate({
574 source: path.join(base.directory, "index"),
575 target: path.join(yield* gitDirOf(worktreePath), "index"),
576 root: worktreePath,
577 verify: true,
578 });
579 if (restated === null) return yield* reject(base);
580 if (base.tree === target.tree || changes === null) return target;
581 // On a case-insensitive volume an added path can land on a file the cached tree kept.
582 const deleted = new Set(changes.deleted);
583 const kept = restated.paths.filter((file) => !deleted.has(file));
584 const names = new Set(kept.map((file) => foldCase(file)));
585 // A new folder whose name differs only in case would keep the cached spelling.
586 const keptFolders = parentDirectories(kept);
587 for (const [index, file] of restated.paths.entries()) {
588 if (restated.stats[index]?.kind === "directory" && !deleted.has(file))
589 keptFolders.add(file);
590 }
591 const spellings = new Map(
592 [...keptFolders].map((directory) => [foldCase(directory), directory]),
593 );
594 for (const file of changes.added) {
595 if (names.has(foldCase(file))) return null;
596 names.add(foldCase(file));
597 for (const directory of parentDirectories([file])) {
598 const existing = spellings.get(foldCase(directory));
599 if (existing !== undefined && existing !== directory) return null;
600 spellings.set(foldCase(directory), directory);
601 }
602 }
603 // A smudge filter run here would see the cached index, not the one Git builds from scratch.
604 if (yield* writesWithFilter(worktreePath, changes.written)) return null;
605 // Hooks off: a hook the move adds runs with Git's checkout environment there, so its
606 // presence afterwards means the caller falls back to that checkout.
607 const moved = yield* git("update", worktreePath, [
608 "-c",
609 `checkout.workers=${input.checkoutWorkers}`,
610 "-c",
611 "core.hooksPath=/dev/null",
612 "-c",
613 "submodule.recurse=false",
614 "read-tree",
615 "-m",
616 "-u",
617 base.tree,
618 target.tree,
619 ]);
620 if (moved === null || (yield* fileSystem.exists(target.indexHook))) return null;
621 return target;
622 });
623 const rollback = (
624 input.lockReason
625 ? git("unlockRollback", input.cwd, ["worktree", "unlock", "--", worktreePath])
626 : Effect.void
627 ).pipe(
628 Effect.andThen(
629 git("rollback", input.cwd, ["worktree", "remove", "--force", "--", worktreePath]),
630 ),
631 Effect.flatMap((removed) =>
632 removed === null
633 ? Effect.logWarning("could not remove a partially created worktree", { worktreePath })
634 : Effect.void,
635 ),
636 );
637 // Registration and the rollback that undoes it can't be separated by an interruption.
638 const target = yield* Effect.uninterruptibleMask((restore) =>
639 Effect.gen(function* () {
640 const registered = yield* git("register", input.cwd, [
641 "worktree",
642 "add",
643 "--no-checkout",
644 ...(input.lockReason ? ["--lock", "--reason", input.lockReason] : []),
645 "--",
646 worktreePath,
647 input.refName,
648 ]);
649 if (registered === null) return null;
650 return yield* restore(populate).pipe(
651 Effect.catch((cause) =>
652 Effect.logWarning("worktree checkout cache failed; using git worktree add", {
653 cause,
654 }).pipe(Effect.as(null)),
655 ),
656 Effect.onExit((exit) =>
657 Exit.isSuccess(exit) && exit.value !== null ? Effect.void : rollback,
658 ),
659 );
660 }),
661 );
662 if (target === null) return false;
663​
664 // `git worktree add --no-checkout` skips this hook; a normal add runs it.
665 const hook = yield* execute({
666 operation: "GitVcsDriver.createWorktree.postCheckout",
667 cwd: worktreePath,
668 args: [
669 "hook",
670 "run",
671 "--ignore-missing",
672 "post-checkout",
673 "--",
674 NULL_OID,
675 target.commit,
676 "1",
677 ],
678 env: { LANGUAGE: "C" },
679 allowNonZeroExit: true,
680 timeoutMs: null,
681 });
682 if (hook.exitCode !== 0) {
683 return yield* new GitCommandError({
684 operation: "GitVcsDriver.createWorktree",
685 command: "git worktree add",
686 cwd: input.cwd,
687 detail: "git worktree add failed: the post-checkout hook failed",
688 exitCode: hook.exitCode,
689 stderrLength: hook.stderr.length,
690 });
691 }
692 return true;
693 });
694​
695 const removeIfAbandoned = Effect.fn("WorktreeCheckoutCache.removeIfAbandoned")(
696 function* (target: string, maxAgeMs: number) {
697 const info = yield* fileSystem.stat(target);
698 const modified = Option.getOrUndefined(info.mtime)?.getTime() ?? 0;
699 if ((yield* Clock.currentTimeMillis) - modified > maxAgeMs) {
700 yield* fileSystem.remove(target, { recursive: true });
701 }
702 },
703 (effect) => Effect.ignore(effect),
704 );
705​
706 /** Caches the tree checked out in `worktreePath`, unless a cached checkout is already close to it. */
707 const build = Effect.fn("WorktreeCheckoutCache.build")(function* (
708 worktreePath: string,
709 // From before the worktree was checked out, so a `clear` during the checkout also counts.
710 generationAtStart: number,
711 ) {
712 if (!(yield* gitSupported)) return;
713 const target = yield* describe(worktreePath, "HEAD");
714 if (target === null) return;
715 const entryFingerprint = yield* fingerprint(worktreePath, target.commonDir);
716 if (entryFingerprint === null) return;
717 const entryName = `${target.tree}-${entryFingerprint}`;
718 yield* fileSystem.makeDirectory(target.bucket, { recursive: true });
719 const entries = yield* listEntries(target.bucket);
720 const compatible = entries.filter((entry) => entry.fingerprint === entryFingerprint);
721 if (compatible.some((entry) => entry.tree === target.tree)) return;
722 // Skip when a cached checkout is close enough to move forward cheaply.
723 let base: CacheEntry | undefined;
724 for (const entry of compatible) {
725 const changes = yield* changedPaths(worktreePath, entry.tree, target.tree);
726 if (changes === null || changes.attributes) continue;
727 if (changes.count < REBUILD_AFTER_CHANGED_FILES) return;
728 base ??= entry;
729 }
730 if (yield* usesFilter(worktreePath, target.bucket, target.tree)) return;
731​
732 for (const name of yield* fileSystem.readDirectory(target.bucket)) {
733 if (!ENTRY_NAME.test(name)) {
734 const leftover = path.join(target.bucket, name);
735 yield* removeIfAbandoned(
736 leftover,
737 name.includes(".trash-") ? ABANDONED_TRASH_MS : ABANDONED_STAGING_MS,
738 );
739 }
740 }
741 const staging = path.join(target.bucket, `.staging-${NodeCrypto.randomUUID()}`);
742 const stagingFiles = path.join(staging, "files");
743 const stagingIndex = path.join(staging, "index");
744 yield* fileSystem.makeDirectory(staging);
745 const withIndex = (args: ReadonlyArray<string>) =>
746 git("build", worktreePath, [...CACHE_INDEX_CONFIG, `--work-tree=${stagingFiles}`, ...args], {
747 GIT_INDEX_FILE: stagingIndex,
748 });
749​
750 yield* Effect.gen(function* () {
751 let built = false;
752 if (base !== undefined && (yield* directoriesUnchanged(base))) {
753 const from = base;
754 built = yield* Effect.gen(function* () {
755 yield* Effect.uninterruptible(clone(path.join(from.directory, "files"), stagingFiles));
756 if (!(yield* directoriesUnchanged(from))) return false;
757 const restated = yield* restate({
758 source: path.join(from.directory, "index"),
759 target: stagingIndex,
760 root: stagingFiles,
761 verify: true,
762 });
763 if (restated === null) return false;
764 return (yield* withIndex(["read-tree", "-m", "-u", from.tree, target.tree])) !== null;
765 }).pipe(Effect.orElseSucceed(() => false));
766 if (!built) {
767 yield* fileSystem.remove(stagingFiles, { recursive: true }).pipe(Effect.ignore);
768 yield* fileSystem.remove(stagingIndex).pipe(Effect.ignore);
769 }
770 }
771 if (!built) {
772 yield* fileSystem.makeDirectory(stagingFiles);
773 if ((yield* withIndex(["read-tree", "--reset", "-u", target.tree])) === null) {
774 return yield* new WorktreeCheckoutCacheError({ detail: "git read-tree failed" });
775 }
776 }
777 // Record the files' own stat data; Git leaves racily written entries for a later re-read.
778 const recorded = yield* restate({
779 source: stagingIndex,
780 target: stagingIndex,
781 root: stagingFiles,
782 verify: false,
783 });
784 if (recorded === null) {
785 return yield* new WorktreeCheckoutCacheError({
786 detail: "the cache index has an unsupported format or colliding paths",
787 });
788 }
789 yield* recordDirectories(staging, recorded);
790 if (generation !== generationAtStart) {
791 return yield* new WorktreeCheckoutCacheError({ detail: "the cache was cleared" });
792 }
793 yield* Effect.uninterruptible(
794 fileSystem.rename(staging, path.join(target.bucket, entryName)),
795 );
796 }).pipe(Effect.onError(() => discard(staging)));
797​
798 yield* touch(target.bucket);
799 yield* Effect.forEach(
800 (yield* listEntries(target.bucket)).slice(KEEP_PER_REPOSITORY),
801 (entry) => discard(entry.directory),
802 { discard: true },
803 );
804 const now = yield* Clock.currentTimeMillis;
805 for (const name of yield* fileSystem.readDirectory(cacheDir)) {
806 const bucket = path.join(cacheDir, name);
807 if (bucket === target.bucket) continue;
808 if (name.includes(".trash-")) {
809 yield* removeIfAbandoned(bucket, ABANDONED_TRASH_MS);
810 continue;
811 }
812 const info = yield* fileSystem.stat(bucket).pipe(Effect.option);
813 const used = info.pipe(
814 Option.flatMap((value) => value.mtime),
815 Option.map((date) => date.getTime()),
816 );
817 if (Option.isSome(used) && now - used.value > UNUSED_REPOSITORY_MS) {
818 yield* discard(bucket);
819 }
820 }
821 });
822​
823 /** Caches the worktree's checkout in the background, so the next worktree can clone it. */
824 const schedule = (worktreePath: string, generationAtStart: number) =>
825 Effect.suspend(() => {
826 if (pendingBuilds.has(worktreePath)) return Effect.void;
827 pendingBuilds.add(worktreePath);
828 return build(worktreePath, generationAtStart).pipe(
829 builds.withPermits(1),
830 Effect.ignoreCause({ log: true }),
831 Effect.ensuring(Effect.sync(() => pendingBuilds.delete(worktreePath))),
832 Effect.forkIn(scope),
833 Effect.asVoid,
834 );
835 });
836​
837 /** Deletes every cached checkout in the background; builds already running are dropped. */
838 const clear = Effect.suspend(() => {
839 generation++;
840 return fileSystem.exists(cacheDir);
841 }).pipe(
842 Effect.flatMap((exists) =>
843 exists
844 ? discard(cacheDir).pipe(builds.withPermits(1), Effect.forkIn(scope), Effect.asVoid)
845 : Effect.void,
846 ),
847 Effect.ignore,
848 );
849​
850 /** Pass to `schedule` from before a checkout starts. */
851 const currentGeneration = Effect.sync(() => generation);
852​
853 return { create, build, schedule, clear, currentGeneration };
854});