Open History to see the last commit
1import * as Clock from "effect/Clock";
2import * as Effect from "effect/Effect";
3import type * as FileSystem from "effect/FileSystem";
4import * as Hash from "effect/Hash";
5import * as Option from "effect/Option";
6import type * as Path from "effect/Path";
7import * as Schema from "effect/Schema";
8
9import type * as VcsDriver from "./VcsDriver.ts";
10import * as VcsProcess from "./VcsProcess.ts";
11
12/**
13 * Each checkpoint scope keeps the scratch index of its last capture, so the next capture's
14 * `git add` trusts the stat data of files it already hashed instead of rehashing every untracked
15 * or modified file. The index lives in the common Git directory, never in the worktree.
16 */
17const DIRECTORY = "t3-checkpoint-indexes";
18// Archived threads stop capturing; their indexes age out instead of waiting for a delete.
19const IDLE_MS = 14 * 24 * 60 * 60 * 1000;
20const MAX_INDEXES = 32;
21const LIST_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
22
23const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION;
24
25const Meta = Schema.Struct({
26 scope: Schema.String,
27 cwd: Schema.String,
28 tree: Schema.String,
29 fingerprint: Schema.String,
30});
31const MetaJson = Schema.fromJsonString(Meta);
32const decodeMeta = Schema.decodeEffect(MetaJson);
33const encodeMeta = Schema.encodeEffect(MetaJson);
34
35/** The capture index no longer matches what a rebuilt index would stage; capture again without it. */
36export class StaleCaptureIndex extends Schema.TaggedError<StaleCaptureIndex>()(
37 "StaleCaptureIndex",
38 {},
39) {}
40
41/** Refs of one scope differ only in their last segment, the ordinal. */
42const scopeOf = (checkpointRef: string) =>
43 checkpointRef.slice(0, checkpointRef.lastIndexOf("/") + 1);
44
45const hex = (value: string) => (Hash.string(value) >>> 0).toString(16).padStart(8, "0");
46
47/** Names every capture index of a scope, whatever folder it captured. */
48export const scopeDirectoryPrefix = (scopeRefPrefix: string) => `${hex(scopeRefPrefix)}-`;
49
50export const storeRoot = (path: Path.Path, gitCommonDir: string) =>
51 path.join(gitCommonDir, DIRECTORY);
52
53/** Removes the capture indexes of scopes whose refs were deleted. */
54export const removeForScopes = Effect.fn("GitVcsDriver.checkpoints.removeCaptureIndexes")(
55 function* (
56 fileSystem: FileSystem.FileSystem,
57 path: Path.Path,
58 gitCommonDir: string,
59 scopeRefPrefixes: Iterable<string>,
60 ) {
61 const root = storeRoot(path, gitCommonDir);
62 const prefixes = [...scopeRefPrefixes].map(scopeDirectoryPrefix);
63 const entries = yield* fileSystem.readDirectory(root);
64 yield* Effect.forEach(
65 entries.filter((entry) => prefixes.some((prefix) => entry.startsWith(prefix))),
66 (entry) => fileSystem.remove(path.join(root, entry), { recursive: true, force: true }),
67 { discard: true },
68 );
69 },
70 (effect) => Effect.ignore(effect),
71);
72
73/**
74 * The value Git uses for `key` in `git config --null --get-regexp` output: the last one, as local
75 * config follows global and system. Null marks a key written without a value.
76 */
77export const lastConfigValue = (stdout: string, key: string) => {
78 let value: string | null | undefined;
79 for (const record of stdout.split("\0")) {
80 const newline = record.indexOf("\n");
81 if ((newline === -1 ? record : record.slice(0, newline)) === key)
82 value = newline === -1 ? null : record.slice(newline + 1);
83 }
84 return value;
85};
86
87/**
88 * Git's boolean rules: a valueless key is true, an empty value false, and an integer true unless
89 * zero. Integers parse as strtoimax base 0 does (leading space, 0x hex, 0 octal), then a k/m/g unit.
90 */
91export const gitBool = (value: string | null) => {
92 if (value === null) return true;
93 if (/^(?:true|yes|on)$/i.test(value)) return true;
94 const integer = /^\s*[+-]?(?:0x([\da-f]+)|([1-9]\d*|0[0-7]*))[kmg]?$/i.exec(value);
95 return integer !== null && /[1-9a-f]/i.test(integer[1] ?? integer[2]!);
96};
97
98const statSignature = (fileSystem: FileSystem.FileSystem, file: string) =>
99 fileSystem.stat(file).pipe(
100 Effect.map(
101 (info) =>
102 `${Option.match(info.mtime, { onNone: () => "", onSome: (at) => at.getTime() })}:${info.size}:${Option.getOrElse(info.ino, () => "")}`,
103 ),
104 Effect.orElseSucceed(() => "-"),
105 );
106
107export const make = (
108 execute: VcsDriver.VcsDriver["Service"]["execute"],
109 fileSystem: FileSystem.FileSystem,
110 path: Path.Path,
111) => {
112 const locate = (input: {
113 readonly gitCommonDir: string;
114 readonly checkpointRef: string;
115 readonly cwd: string;
116 }) => {
117 const scope = scopeOf(input.checkpointRef);
118 const directory = path.join(
119 storeRoot(path, input.gitCommonDir),
120 `${scopeDirectoryPrefix(scope)}${hex(input.cwd)}`,
121 );
122 return { scope, cwd: input.cwd, directory };
123 };
124 type Location = ReturnType<typeof locate>;
125
126 /**
127 * What decides the blob `git add` records for a file whose stat is unchanged, outside the files
128 * a capture stages: conversion config and attribute files above the folder or outside the tree.
129 */
130 const fingerprint = Effect.fn("GitVcsDriver.checkpoints.captureIndexFingerprint")(
131 function* (input: {
132 readonly cwd: string;
133 readonly config: string;
134 readonly gitCommonDir: string;
135 readonly topLevel: string;
136 readonly prefix: string;
137 readonly hostEnv: NodeJS.ProcessEnv;
138 }) {
139 const { HOME: home, XDG_CONFIG_HOME: xdgConfigHome } = input.hostEnv;
140 // Git expands ~, ~user and %(prefix) itself, so only a configured value costs a command.
141 const globalAttributes =
142 lastConfigValue(input.config, "core.attributesfile") === undefined
143 ? xdgConfigHome
144 ? path.join(xdgConfigHome, "git", "attributes")
145 : home
146 ? path.join(home, ".config", "git", "attributes")
147 : ""
148 : (yield* execute({
149 operation,
150 cwd: input.cwd,
151 args: ["config", "--type=path", "--get", "core.attributesFile"],
152 allowNonZeroExit: true,
153 })).stdout.replace(/\n$/, "");
154 // Files inside the folder are staged, so a change to a tracked or untracked .gitattributes
155 // there shows in the tree; an ignored one above it, the root included, does not.
156 const parents = [""];
157 for (
158 let end = input.prefix.indexOf("/");
159 end !== -1;
160 end = input.prefix.indexOf("/", end + 1)
161 ) {
162 if (end + 1 < input.prefix.length) parents.push(input.prefix.slice(0, end + 1));
163 }
164 const signatures = yield* Effect.forEach(
165 [
166 path.join(input.gitCommonDir, "info", "attributes"),
167 // Git reads relative paths after moving to the working-tree root.
168 globalAttributes === "" ? "" : path.resolve(input.topLevel, globalAttributes),
169 ...parents.map((parent) => path.join(input.topLevel, parent, ".gitattributes")),
170 ],
171 (file) => (file === "" ? Effect.succeed("-") : statSignature(fileSystem, file)),
172 );
173 return `${input.config}\0${signatures.join("\0")}`;
174 },
175 );
176
177 /** Whether a capture stages a path, given from the working-tree root. Undefined to rebuild. */
178 const stagedPaths = (input: {
179 readonly prefix: string;
180 readonly excludePaths: ReadonlyArray<string>;
181 }) => {
182 const excluded = input.excludePaths.map(
183 (entry) => `${input.prefix}${entry.replace(/^\.\//, "").replace(/\/+$/, "")}`,
184 );
185 if (excluded.some((entry) => entry === input.prefix || /(?:^|\/)\.\.(?:\/|$)/.test(entry))) {
186 return undefined;
187 }
188 return (entryPath: string) =>
189 entryPath.startsWith(input.prefix) &&
190 !excluded.some((entry) => entryPath === entry || entryPath.startsWith(`${entry}/`));
191 };
192
193 /**
194 * Of captured paths HEAD lacks, the ones `git add -A` would leave out of a rebuilt index, where
195 * they are untracked: it skips them once ignored, and stages a directory that became a
196 * repository as one gitlink. Undefined when Git cannot say.
197 */
198 const noLongerStaged = Effect.fnUntraced(function* (
199 topLevel: string,
200 paths: ReadonlyArray<string>,
201 ) {
202 // ./ avoids leading : pathspec magic; check-ignore rejects --literal-pathspecs.
203 const stdin = paths.map((entryPath) => `./${entryPath}\0`).join("");
204 const ignored = yield* execute({
205 operation,
206 cwd: topLevel,
207 args: ["check-ignore", "--no-index", "-z", "--stdin"],
208 stdin,
209 allowNonZeroExit: true,
210 maxOutputBytes: Buffer.byteLength(stdin),
211 outputMode: "error",
212 });
213 if (ignored.exitCode > 1) return undefined;
214 const ignoredPaths = new Set(
215 ignored.stdout.split("\0").map((entryPath) => entryPath.replace(/^\.\//, "")),
216 );
217 const directories = new Set<string>();
218 for (const entryPath of paths) {
219 for (
220 let end = entryPath.lastIndexOf("/");
221 end > 0 && !directories.has(entryPath.slice(0, end));
222 end = entryPath.lastIndexOf("/", end - 1)
223 ) {
224 directories.add(entryPath.slice(0, end));
225 }
226 }
227 const repositories = new Set<string>();
228 yield* Effect.forEach(
229 directories,
230 (directory) =>
231 fileSystem.exists(path.join(topLevel, directory, ".git")).pipe(
232 Effect.map((exists) => {
233 if (exists) repositories.add(directory);
234 }),
235 ),
236 { concurrency: 64, discard: true },
237 );
238 const insideRepository = (entryPath: string) => {
239 for (
240 let end = entryPath.lastIndexOf("/");
241 end > 0;
242 end = entryPath.lastIndexOf("/", end - 1)
243 ) {
244 if (repositories.has(entryPath.slice(0, end))) return true;
245 }
246 return false;
247 };
248 return new Set(
249 paths.filter((entryPath) => ignoredPaths.has(entryPath) || insideRepository(entryPath)),
250 );
251 });
252
253 /**
254 * Moves the scope's index to `indexFile` and makes it hold exactly what a rebuilt index would
255 * before `git add`: HEAD outside the staged pathspec, and inside it every previously captured
256 * path that `git add -A` would still stage, except a nested checkout HEAD does not track.
257 * Returns the tree it held, or undefined to rebuild.
258 */
259 const claim = Effect.fn("GitVcsDriver.checkpoints.claimCaptureIndex")(
260 function* (input: {
261 readonly location: Location;
262 readonly fingerprint: string;
263 readonly topLevel: string;
264 readonly prefix: string;
265 readonly excludePaths: ReadonlyArray<string>;
266 readonly head: string;
267 readonly indexFile: string;
268 readonly env: NodeJS.ProcessEnv;
269 readonly indexConfig: ReadonlyArray<string>;
270 }) {
271 const metaFile = path.join(input.location.directory, "meta.json");
272 const raw = yield* fileSystem.readFileString(metaFile);
273 // Claimed before use: a capture that fails from here on leaves nothing to trust.
274 yield* fileSystem.remove(metaFile);
275 const meta = yield* decodeMeta(raw);
276 // A rename keeps the index's timestamp, which Git's racy-entry check depends on.
277 yield* fileSystem.rename(
278 path.join(input.location.directory, `index.${meta.tree}`),
279 input.indexFile,
280 );
281 if (
282 meta.scope !== input.location.scope ||
283 meta.cwd !== input.location.cwd ||
284 meta.fingerprint !== input.fingerprint
285 ) {
286 return undefined;
287 }
288 const staged = stagedPaths(input);
289 if (staged === undefined) return undefined;
290
291 const diff = yield* execute({
292 operation,
293 cwd: input.topLevel,
294 args: [
295 "diff-tree",
296 "-r",
297 "-z",
298 "--raw",
299 "--no-abbrev",
300 "--no-renames",
301 meta.tree,
302 input.head,
303 ],
304 maxOutputBytes: LIST_MAX_OUTPUT_BYTES,
305 outputMode: "error",
306 });
307 // Records are ":<old mode> <new mode> <old oid> <new oid> <status> NUL <path> NUL".
308 const fields = diff.stdout.split("\0");
309 const updates: string[] = [];
310 const candidates: Array<{ path: string; oid: string }> = [];
311 const kept = new Set<string>();
312 for (let field = 0; field + 1 < fields.length; field += 2) {
313 const [oldMode = "", newMode = "", oldOid = "", newOid = ""] =
314 fields[field]!.slice(1).split(" ");
315 const entryPath = fields[field + 1]!;
316 // U+FFFD marks a name that is not UTF-8 and so cannot be fed back to Git from here.
317 if (entryPath.includes("�")) return undefined;
318 if (
319 !staged(entryPath) ||
320 oldMode === "000000" ||
321 // A kept gitlink HEAD lacks makes add -A run git status inside that nested checkout.
322 (oldMode === "160000" && newMode === "000000")
323 ) {
324 // HEAD's entry, as a rebuilt index holds it; add -A then decides as it would there.
325 updates.push(
326 newMode === "000000"
327 ? `0 ${oldOid}\t${entryPath}`
328 : `${newMode} ${newOid}\t${entryPath}`,
329 );
330 } else if (newMode === "000000") {
331 candidates.push({ path: entryPath, oid: oldOid });
332 } else if (oldMode !== "160000") {
333 kept.add(oldOid);
334 }
335 }
336
337 if (candidates.length > 0) {
338 const dropped = yield* noLongerStaged(
339 input.topLevel,
340 candidates.map((entry) => entry.path),
341 );
342 if (dropped === undefined) return undefined;
343 for (const entry of candidates) {
344 if (dropped.has(entry.path)) {
345 updates.push(`0 ${entry.oid}\t${entry.path}`);
346 } else {
347 kept.add(entry.oid);
348 }
349 }
350 }
351
352 if (kept.size > 0) {
353 // Only refs keep objects from gc; a blob whose checkpoint was deleted may be gone.
354 const objects = yield* execute({
355 operation,
356 cwd: input.topLevel,
357 args: ["cat-file", "--batch-check=%(objectname) %(objecttype)"],
358 stdin: `${[...kept].join("\n")}\n`,
359 maxOutputBytes: kept.size * 128,
360 outputMode: "error",
361 });
362 const present = new Set(objects.stdout.split("\n"));
363 for (const oid of kept) if (!present.has(`${oid} blob`)) return undefined;
364 }
365
366 if (updates.length > 0) {
367 // Restore the timestamp Git's racy check reads; update-index advances it.
368 const { mtime } = yield* fileSystem.stat(input.indexFile);
369 const indexTime = Option.isSome(mtime) ? Math.floor(mtime.value.getTime() / 1000) : 0;
370 if (indexTime <= 0) return undefined;
371 yield* execute({
372 operation,
373 cwd: input.topLevel,
374 args: [...input.indexConfig, "update-index", "-z", "--index-info"],
375 stdin: `${updates.join("\0")}\0`,
376 env: input.env,
377 });
378 yield* fileSystem.utimes(input.indexFile, indexTime, indexTime);
379 }
380 return meta.tree;
381 },
382 Effect.orElseSucceed(() => undefined),
383 );
384
385 /**
386 * Whether a capture now would write `tree` again: the scope's index is the one that wrote it,
387 * and the `git add -A` of a capture would change nothing a rebuilt index would not also hold.
388 * It only reads, so the index stays as it is for the next capture. False when Git cannot say.
389 */
390 const unchanged = Effect.fn("GitVcsDriver.checkpoints.captureIndexUnchanged")(
391 function* <E>(input: {
392 readonly location: Location;
393 /** Read only once the index is known to be the tree's. */
394 readonly fingerprint: Effect.Effect<string, E>;
395 readonly topLevel: string;
396 readonly prefix: string;
397 readonly excludePaths: ReadonlyArray<string>;
398 /** The commit the index was captured on. */
399 readonly head: string;
400 readonly tree: string;
401 readonly indexConfig: ReadonlyArray<string>;
402 }) {
403 const { directory } = input.location;
404 const meta = yield* decodeMeta(
405 yield* fileSystem.readFileString(path.join(directory, "meta.json")),
406 );
407 if (
408 meta.tree !== input.tree ||
409 meta.scope !== input.location.scope ||
410 meta.cwd !== input.location.cwd ||
411 meta.fingerprint !== (yield* input.fingerprint)
412 ) {
413 return false;
414 }
415 const staged = stagedPaths(input);
416 if (staged === undefined) return false;
417 // The first column compares the index with HEAD, the second the files with the index.
418 const status = yield* execute({
419 operation,
420 cwd: input.location.cwd,
421 args: [
422 ...input.indexConfig,
423 "status",
424 "--porcelain=v2",
425 "--branch",
426 "-z",
427 "--no-renames",
428 "--untracked-files=all",
429 // A gitlink records the commit a nested checkout is on, not the files in it.
430 "--ignore-submodules=dirty",
431 "--",
432 ".",
433 ],
434 // A status that refreshes the index would rewrite the timestamp its racy check reads.
435 env: {
436 GIT_INDEX_FILE: path.join(directory, `index.${meta.tree}`),
437 GIT_OPTIONAL_LOCKS: "0",
438 },
439 maxOutputBytes: LIST_MAX_OUTPUT_BYTES,
440 outputMode: "truncate",
441 });
442 if (status.stdoutTruncated) return false;
443 let head: string | undefined;
444 const added: string[] = [];
445 const deleted: string[] = [];
446 for (const record of status.stdout.split("\0")) {
447 if (record === "") continue;
448 if (record.startsWith("# ")) {
449 if (record.startsWith("# branch.oid ")) head = record.slice(13);
450 continue;
451 }
452 if (record.startsWith("? ")) {
453 if (staged(record.slice(2))) return false;
454 continue;
455 }
456 // "1 <XY> <sub> <mH> <mI> <mW> <hH> <hI> <path>"; an unmerged entry is a change.
457 const fields = record.split(" ");
458 if (fields[0] !== "1" || fields.length < 9) return false;
459 const [, state = "", , , indexMode] = fields;
460 const entryPath = fields.slice(8).join(" ");
461 if (!staged(entryPath)) {
462 // A capture holds HEAD's entry for a path it does not stage.
463 if (state[0] !== ".") return false;
464 continue;
465 }
466 if (state[1] !== ".") return false;
467 if (state[0] !== "A" && state[0] !== "D") continue;
468 // U+FFFD marks a name that is not UTF-8, which the checks below could not look up.
469 if (entryPath.includes("\uFFFD")) return false;
470 if (state[0] === "D") {
471 deleted.push(entryPath);
472 continue;
473 }
474 // A rebuilt index stages a nested checkout HEAD lacks afresh; claim drops it for that.
475 if (indexMode === "160000") return false;
476 added.push(entryPath);
477 }
478 if (head !== input.head) return false;
479 // Status lists a file that came back as untracked, unless it is ignored; add -A stages it
480 // either way, since HEAD tracks it.
481 const restored = yield* Effect.forEach(
482 deleted,
483 (entryPath) => {
484 const file = path.join(input.topLevel, entryPath);
485 return fileSystem.exists(file).pipe(
486 // A dangling symlink does not exist to a stat that follows it.
487 Effect.flatMap((exists) =>
488 exists ? Effect.succeed(true) : Effect.isSuccess(fileSystem.readLink(file)),
489 ),
490 );
491 },
492 { concurrency: 64 },
493 );
494 if (restored.includes(true)) return false;
495 if (added.length === 0) return true;
496 return (yield* noLongerStaged(input.topLevel, added))?.size === 0;
497 },
498 Effect.orElseSucceed(() => false),
499 );
500
501 /** Throws a capture's index away when `git add` may have trusted stale conversion rules. */
502 const attributesChanged = (input: {
503 readonly cwd: string;
504 readonly previousTree: string;
505 readonly tree: string;
506 /** The capture's environment, whose private object store holds the new tree. */
507 readonly env: NodeJS.ProcessEnv;
508 }) =>
509 execute({
510 operation,
511 cwd: input.cwd,
512 env: input.env,
513 args: [
514 "diff-tree",
515 "-r",
516 "-z",
517 "--name-only",
518 "--no-renames",
519 input.previousTree,
520 input.tree,
521 "--",
522 ":(top,glob)**/.gitattributes",
523 ],
524 maxOutputBytes: 1,
525 outputMode: "truncate",
526 }).pipe(Effect.map((result) => result.stdout.length > 0));
527
528 /** Keeps a published capture's index, hard-linked before anything else rewrote it, for the next. */
529 const save = Effect.fn("GitVcsDriver.checkpoints.saveCaptureIndex")(
530 function* (input: {
531 readonly location: Location;
532 readonly indexFile: string;
533 readonly tree: string;
534 readonly fingerprint: string;
535 }) {
536 const { directory } = input.location;
537 const root = path.dirname(directory);
538 yield* fileSystem.makeDirectory(directory, { recursive: true });
539 // Named by its tree, so a racing save can never pair one capture's index with another's meta.
540 const indexName = `index.${input.tree}`;
541 yield* fileSystem.rename(input.indexFile, path.join(directory, indexName));
542 const metaFile = path.join(directory, "meta.json");
543 yield* fileSystem.writeFileString(
544 `${metaFile}.tmp`,
545 yield* encodeMeta({
546 scope: input.location.scope,
547 cwd: input.location.cwd,
548 tree: input.tree,
549 fingerprint: input.fingerprint,
550 }),
551 );
552 yield* fileSystem.rename(`${metaFile}.tmp`, metaFile);
553 yield* Effect.forEach(
554 (yield* fileSystem.readDirectory(directory)).filter(
555 (entry) => entry.startsWith("index.") && entry !== indexName,
556 ),
557 (entry) => fileSystem.remove(path.join(directory, entry), { force: true }),
558 { discard: true },
559 );
560
561 const now = yield* Clock.currentTimeMillis;
562 const others = yield* Effect.forEach(
563 (yield* fileSystem.readDirectory(root)).filter(
564 (entry) => path.join(root, entry) !== directory,
565 ),
566 (entry) =>
567 fileSystem.stat(path.join(root, entry)).pipe(
568 Effect.map((info) => ({
569 entry,
570 at: Option.match(info.mtime, { onNone: () => 0, onSome: (at) => at.getTime() }),
571 })),
572 Effect.orElseSucceed(() => ({ entry, at: 0 })),
573 ),
574 );
575 const stale = others
576 .toSorted((left, right) => right.at - left.at)
577 .filter((other, index) => index >= MAX_INDEXES - 1 || now - other.at > IDLE_MS);
578 yield* Effect.forEach(
579 stale,
580 ({ entry }) =>
581 fileSystem
582 .remove(path.join(root, entry), { recursive: true, force: true })
583 .pipe(Effect.ignore),
584 { discard: true },
585 );
586 },
587 (effect, input) =>
588 effect.pipe(
589 Effect.ignore,
590 Effect.ensuring(fileSystem.remove(input.indexFile, { force: true }).pipe(Effect.ignore)),
591 ),
592 );
593
594 return { locate, fingerprint, claim, unchanged, attributesChanged, save };
595};