Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodePath from "node:path";
3
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { it } from "@effect/vitest";
6import { ThreadId, type VcsError } from "@t3tools/contracts";
7import * as HostProcess from "@t3tools/shared/HostProcess";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as PlatformError from "effect/PlatformError";
12import * as Scope from "effect/Scope";
13import { describe, expect } from "vite-plus/test";
14
15import { checkpointRefForThreadTurn } from "./Utils.ts";
16import { parseTurnDiffFilesFromNumstat } from "./Diffs.ts";
17import * as CheckpointStore from "./CheckpointStore.ts";
18import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
19import * as VcsProcess from "../vcs/VcsProcess.ts";
20import * as ServerConfig from "../config.ts";
21
22const layerServerConfig = ServerConfig.ServerConfig.layerTest(process.cwd(), {
23 prefix: "t3-checkpoint-store-test-",
24});
25const layerVcsProcessTest = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
26const layerVcsDriverTest = VcsDriverRegistry.layer.pipe(Layer.provide(layerVcsProcessTest));
27const layerCheckpointStoreTest = CheckpointStore.layer.pipe(
28 Layer.provideMerge(layerVcsDriverTest),
29 Layer.provideMerge(NodeServices.layer),
30);
31const layerTest = layerCheckpointStoreTest.pipe(
32 Layer.provideMerge(layerVcsProcessTest),
33 Layer.provideMerge(layerVcsDriverTest),
34 Layer.provideMerge(layerServerConfig),
35 Layer.provideMerge(NodeServices.layer),
36);
37
38function makeTmpDir(
39 prefix = "checkpoint-store-test-",
40): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> {
41 return Effect.gen(function* () {
42 const fileSystem = yield* FileSystem.FileSystem;
43 return yield* fileSystem.makeTempDirectoryScoped({ prefix });
44 });
45}
46
47function writeTextFile(
48 filePath: string,
49 contents: string,
50): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
51 return Effect.gen(function* () {
52 const fileSystem = yield* FileSystem.FileSystem;
53 yield* fileSystem.writeFileString(filePath, contents);
54 });
55}
56
57function git(
58 cwd: string,
59 args: ReadonlyArray<string>,
60 options: { readonly committedAt?: string; readonly allowNonZeroExit?: boolean } = {},
61): Effect.Effect<string, VcsError, VcsProcess.VcsProcess> {
62 return Effect.gen(function* () {
63 const vcsProcess = yield* VcsProcess.VcsProcess;
64 const result = yield* vcsProcess.run({
65 operation: "CheckpointStore.test.git",
66 command: "git",
67 cwd,
68 args,
69 timeoutMs: 10_000,
70 ...(options.committedAt === undefined
71 ? {}
72 : { env: { ...process.env, GIT_COMMITTER_DATE: options.committedAt } }),
73 ...(options.allowNonZeroExit === undefined
74 ? {}
75 : { allowNonZeroExit: options.allowNonZeroExit }),
76 });
77 return result.stdout.trim();
78 });
79}
80
81function initRepoWithCommit(
82 cwd: string,
83): Effect.Effect<
84 void,
85 VcsError | PlatformError.PlatformError,
86 VcsProcess.VcsProcess | FileSystem.FileSystem
87> {
88 return Effect.gen(function* () {
89 yield* git(cwd, ["init"]);
90 yield* git(cwd, ["config", "user.email", "test@test.com"]);
91 yield* git(cwd, ["config", "user.name", "Test"]);
92 yield* writeTextFile(NodePath.join(cwd, "README.md"), "# test\n");
93 yield* git(cwd, ["add", "."]);
94 yield* git(cwd, ["commit", "-m", "initial commit"]);
95 });
96}
97
98function buildLargeText(lineCount = 5_000): string {
99 return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`)
100 .join("\n")
101 .concat("\n");
102}
103
104it.layer(layerTest)("CheckpointStore.layer", (it) => {
105 it.effect("detects a nested workspace without its own .git entry", () =>
106 Effect.gen(function* () {
107 const tmp = yield* makeTmpDir();
108 yield* initRepoWithCommit(tmp);
109 const fileSystem = yield* FileSystem.FileSystem;
110 const nested = NodePath.join(tmp, "packages", "nested");
111 yield* fileSystem.makeDirectory(nested, { recursive: true });
112 const checkpointStore = yield* CheckpointStore.CheckpointStore;
113 expect(yield* checkpointStore.isGitRepository(nested)).toBe(true);
114 }),
115 );
116 describe("diffCheckpoints", () => {
117 it.effect("returns full oversized checkpoint diffs without truncation", () =>
118 Effect.gen(function* () {
119 const tmp = yield* makeTmpDir();
120 yield* initRepoWithCommit(tmp);
121 const checkpointStore = yield* CheckpointStore.CheckpointStore;
122 const threadId = ThreadId.make("thread-checkpoint-store");
123 const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
124 const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
125
126 yield* checkpointStore.captureCheckpoint({
127 cwd: tmp,
128 checkpointRef: fromCheckpointRef,
129 });
130 yield* writeTextFile(NodePath.join(tmp, "README.md"), buildLargeText());
131 yield* checkpointStore.captureCheckpoint({
132 cwd: tmp,
133 checkpointRef: toCheckpointRef,
134 });
135
136 const diff = yield* checkpointStore.diffCheckpoints({
137 cwd: tmp,
138 fromCheckpointRef,
139 toCheckpointRef,
140 ignoreWhitespace: true,
141 });
142
143 expect(diff).toContain("diff --git");
144 expect(diff).not.toContain("[truncated]");
145 expect(diff).toContain("+line 04999");
146 }),
147 );
148
149 it.effect("keeps a/ and b/ patch prefixes when the repository disables them", () =>
150 Effect.gen(function* () {
151 const tmp = yield* makeTmpDir();
152 yield* initRepoWithCommit(tmp);
153 yield* git(tmp, ["config", "diff.noprefix", "true"]);
154 const checkpointStore = yield* CheckpointStore.CheckpointStore;
155 const threadId = ThreadId.make("thread-checkpoint-store-noprefix");
156 const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
157 const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
158
159 yield* checkpointStore.captureCheckpoint({
160 cwd: tmp,
161 checkpointRef: fromCheckpointRef,
162 });
163 yield* writeTextFile(NodePath.join(tmp, "README.md"), "# changed\n");
164 yield* checkpointStore.captureCheckpoint({
165 cwd: tmp,
166 checkpointRef: toCheckpointRef,
167 });
168
169 const diff = yield* checkpointStore.diffCheckpoints({
170 cwd: tmp,
171 fromCheckpointRef,
172 toCheckpointRef,
173 ignoreWhitespace: false,
174 });
175
176 expect(diff).toContain("diff --git a/README.md b/README.md");
177 }),
178 );
179
180 it.effect("can hide indentation churn when changes wrap existing lines", () =>
181 Effect.gen(function* () {
182 const tmp = yield* makeTmpDir();
183 yield* initRepoWithCommit(tmp);
184 const checkpointStore = yield* CheckpointStore.CheckpointStore;
185 const threadId = ThreadId.make("thread-checkpoint-store-whitespace");
186 const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
187 const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
188
189 const componentPath = NodePath.join(tmp, "Component.tsx");
190 yield* writeTextFile(
191 componentPath,
192 [
193 "export function View() {",
194 " return (",
195 " <section>",
196 " <h1>Title</h1>",
197 " <p>Body</p>",
198 " </section>",
199 " );",
200 "}",
201 "",
202 ].join("\n"),
203 );
204 yield* checkpointStore.captureCheckpoint({
205 cwd: tmp,
206 checkpointRef: fromCheckpointRef,
207 });
208 yield* writeTextFile(
209 componentPath,
210 [
211 "export function View() {",
212 " return (",
213 " <section>",
214 " {isReady ? (",
215 " <div>",
216 " <h1>Title</h1>",
217 " <p>Body</p>",
218 " </div>",
219 " ) : null}",
220 " </section>",
221 " );",
222 "}",
223 "",
224 ].join("\n"),
225 );
226 yield* checkpointStore.captureCheckpoint({
227 cwd: tmp,
228 checkpointRef: toCheckpointRef,
229 });
230
231 const normalDiff = yield* checkpointStore.diffCheckpoints({
232 cwd: tmp,
233 fromCheckpointRef,
234 toCheckpointRef,
235 ignoreWhitespace: false,
236 });
237 const whitespaceIgnoredDiff = yield* checkpointStore.diffCheckpoints({
238 cwd: tmp,
239 fromCheckpointRef,
240 toCheckpointRef,
241 ignoreWhitespace: true,
242 });
243
244 expect(normalDiff).toContain("diff --git");
245 expect(normalDiff).toContain("- <h1>Title</h1>");
246 expect(normalDiff).toContain("+ <h1>Title</h1>");
247 expect(whitespaceIgnoredDiff).toContain("diff --git");
248 expect(whitespaceIgnoredDiff).toContain("+ {isReady ? (");
249 expect(whitespaceIgnoredDiff).toContain("+ <div>");
250 expect(whitespaceIgnoredDiff).not.toContain("- <h1>Title</h1>");
251 expect(whitespaceIgnoredDiff).not.toContain("+ <h1>Title</h1>");
252
253 for (const ignoreWhitespace of [false, true]) {
254 const numstat = yield* checkpointStore.diffCheckpoints({
255 cwd: tmp,
256 fromCheckpointRef,
257 toCheckpointRef,
258 ignoreWhitespace,
259 format: "numstat",
260 });
261 expect(parseTurnDiffFilesFromNumstat(numstat)).toEqual([
262 {
263 path: "Component.tsx",
264 additions: ignoreWhitespace ? 4 : 6,
265 deletions: ignoreWhitespace ? 0 : 2,
266 },
267 ]);
268 }
269 }),
270 );
271 });
272
273 describe("checkpoint file summaries", () => {
274 it.effect("counts changes whose full patch exceeds the output limit", () =>
275 Effect.gen(function* () {
276 const tmp = yield* makeTmpDir();
277 yield* initRepoWithCommit(tmp);
278 const checkpointStore = yield* CheckpointStore.CheckpointStore;
279 const threadId = ThreadId.make("large-checkpoint-summary");
280 const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
281 const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
282 const filePath = NodePath.join(tmp, "README.md");
283 const lineCount = 20_000;
284 yield* writeTextFile(filePath, `${"before".repeat(50)}\n`.repeat(lineCount));
285 yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
286 yield* writeTextFile(filePath, `${"after".repeat(60)}\n`.repeat(lineCount));
287 yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
288
289 const numstat = yield* checkpointStore.diffCheckpoints({
290 cwd: tmp,
291 fromCheckpointRef,
292 toCheckpointRef,
293 ignoreWhitespace: false,
294 format: "numstat",
295 });
296
297 expect(parseTurnDiffFilesFromNumstat(numstat)).toEqual([
298 { path: "README.md", additions: lineCount, deletions: lineCount },
299 ]);
300 expect(numstat.length).toBeLessThan(100);
301 }),
302 );
303
304 it.effect("preserves file paths and turn ranges without changing the user index", () =>
305 Effect.gen(function* () {
306 const tmp = yield* makeTmpDir();
307 yield* initRepoWithCommit(tmp);
308 yield* git(tmp, ["config", "diff.renames", "copies"]);
309 const fileSystem = yield* FileSystem.FileSystem;
310 const checkpointStore = yield* CheckpointStore.CheckpointStore;
311 const threadId = ThreadId.make("checkpoint-summary-paths");
312 const baseline = checkpointRefForThreadTurn(threadId, 0);
313 const firstTurn = checkpointRefForThreadTurn(threadId, 1);
314 const secondTurn = checkpointRefForThreadTurn(threadId, 2);
315 const copiedText = Array.from({ length: 20 }, (_, index) => `copy line ${index}\n`).join(
316 "",
317 );
318 const platform = yield* HostProcess.Platform;
319 const renamedPath = platform === "win32" ? "renamed café.txt" : "renamed\tcafé\nname.txt";
320 const addedPath = platform === "win32" ? "new café.txt" : "new\tfile\n名.txt";
321 for (const [path, contents] of Object.entries({
322 "copy-source.txt": copiedText,
323 "deleted.txt": "delete me\n",
324 "rename-old.txt": "before\nkeep one\nkeep two\nkeep three\n",
325 "binary.bin": "\0before",
326 })) {
327 yield* writeTextFile(NodePath.join(tmp, path), contents);
328 }
329 yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: baseline });
330
331 yield* fileSystem.rename(
332 NodePath.join(tmp, "rename-old.txt"),
333 NodePath.join(tmp, renamedPath),
334 );
335 yield* fileSystem.remove(NodePath.join(tmp, "deleted.txt"));
336 for (const [path, contents] of Object.entries({
337 "copy-source.txt": `${copiedText}one more\n`,
338 "copied.txt": copiedText,
339 [renamedPath]: "after\nkeep one\nkeep two\nkeep three\n",
340 "binary.bin": "\0after",
341 "empty.txt": "",
342 [addedPath]: "first\nsecond\n",
343 })) {
344 yield* writeTextFile(NodePath.join(tmp, path), contents);
345 }
346 yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: firstTurn });
347 const userIndex = yield* fileSystem.readFile(NodePath.join(tmp, ".git/index"));
348 const input = {
349 cwd: tmp,
350 fromCheckpointRef: baseline,
351 toCheckpointRef: firstTurn,
352 ignoreWhitespace: false,
353 format: "numstat" as const,
354 };
355 const firstSummary = parseTurnDiffFilesFromNumstat(
356 yield* checkpointStore.diffCheckpoints(input),
357 );
358 const expectedFiles = [
359 { path: "binary.bin", additions: 0, deletions: 0 },
360 { path: "copied.txt", previousPath: "copy-source.txt", additions: 0, deletions: 0 },
361 { path: "copy-source.txt", additions: 1, deletions: 0 },
362 { path: "deleted.txt", additions: 0, deletions: 1 },
363 { path: "empty.txt", additions: 0, deletions: 0 },
364 { path: addedPath, additions: 2, deletions: 0 },
365 { path: renamedPath, previousPath: "rename-old.txt", additions: 1, deletions: 1 },
366 ].toSorted((left, right) => left.path.localeCompare(right.path));
367 expect(firstSummary).toEqual(expectedFiles);
368
369 yield* fileSystem.remove(NodePath.join(tmp, "empty.txt"));
370 yield* writeTextFile(NodePath.join(tmp, "copy-source.txt"), "replacement\n");
371 yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: secondTurn });
372 const secondSummary = parseTurnDiffFilesFromNumstat(
373 yield* checkpointStore.diffCheckpoints({
374 ...input,
375 fromCheckpointRef: firstTurn,
376 toCheckpointRef: secondTurn,
377 }),
378 );
379 expect(secondSummary).toEqual([
380 { path: "copy-source.txt", additions: 1, deletions: 21 },
381 { path: "empty.txt", additions: 0, deletions: 0 },
382 ]);
383
384 const inclusiveSummary = parseTurnDiffFilesFromNumstat(
385 yield* checkpointStore.diffCheckpoints({ ...input, toCheckpointRef: secondTurn }),
386 );
387 expect(inclusiveSummary).toEqual(
388 expectedFiles
389 .filter((file) => file.path !== "empty.txt")
390 .map((file) =>
391 file.path === "copy-source.txt" ? { ...file, additions: 1, deletions: 20 } : file,
392 ),
393 );
394 expect(
395 yield* checkpointStore.diffCheckpoints({ ...input, toCheckpointRef: baseline }),
396 ).toBe("");
397 expect(yield* fileSystem.readFile(NodePath.join(tmp, ".git/index"))).toEqual(userIndex);
398 }),
399 );
400
401 it.effect("uses HEAD for a missing baseline only when requested", () =>
402 Effect.gen(function* () {
403 const tmp = yield* makeTmpDir();
404 yield* initRepoWithCommit(tmp);
405 const checkpointStore = yield* CheckpointStore.CheckpointStore;
406 const threadId = ThreadId.make("checkpoint-summary-fallback");
407 const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
408 const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
409 yield* writeTextFile(NodePath.join(tmp, "README.md"), "changed\n");
410 yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
411 const input = {
412 cwd: tmp,
413 fromCheckpointRef,
414 toCheckpointRef,
415 ignoreWhitespace: false,
416 format: "numstat" as const,
417 };
418
419 const error = yield* Effect.flip(checkpointStore.diffCheckpoints(input));
420 expect(error._tag).toBe("VcsProcessExitError");
421 const numstat = yield* checkpointStore.diffCheckpoints({
422 ...input,
423 fallbackFromToHead: true,
424 });
425 expect(parseTurnDiffFilesFromNumstat(numstat)).toEqual([
426 { path: "README.md", additions: 1, deletions: 1 },
427 ]);
428 }),
429 );
430 it.effect("limits a diff to repository paths from a subdirectory workspace", () =>
431 Effect.gen(function* () {
432 const tmp = yield* makeTmpDir();
433 yield* initRepoWithCommit(tmp);
434 const fileSystem = yield* FileSystem.FileSystem;
435 const cwd = NodePath.join(tmp, "app");
436 yield* fileSystem.makeDirectory(cwd);
437 const checkpointStore = yield* CheckpointStore.CheckpointStore;
438 const threadId = ThreadId.make("checkpoint-file-paths-subdirectory");
439 const refs = {
440 cwd,
441 fromCheckpointRef: checkpointRefForThreadTurn(threadId, 0),
442 toCheckpointRef: checkpointRefForThreadTurn(threadId, 1),
443 };
444 yield* checkpointStore.captureCheckpoint({ cwd, checkpointRef: refs.fromCheckpointRef });
445 yield* writeTextFile(NodePath.join(cwd, "kept.txt"), "kept\n");
446 yield* writeTextFile(NodePath.join(tmp, "README.md"), "# hidden\n");
447 yield* checkpointStore.captureCheckpoint({ cwd, checkpointRef: refs.toCheckpointRef });
448
449 const patch = yield* checkpointStore.diffCheckpoints({
450 ...refs,
451 ignoreWhitespace: false,
452 filePaths: ["app/kept.txt"],
453 });
454 expect(patch).toContain("+kept");
455 expect(patch).not.toContain("hidden");
456 }),
457 );
458 });
459
460 describe("listAuthoredPaths", () => {
461 it.effect("leaves out paths that only a merged upstream changed", () =>
462 Effect.gen(function* () {
463 const tmp = yield* makeTmpDir();
464 yield* initRepoWithCommit(tmp);
465 const checkpointStore = yield* CheckpointStore.CheckpointStore;
466 const threadId = ThreadId.make("checkpoint-authored-paths");
467 const refs = {
468 cwd: tmp,
469 fromCheckpointRef: checkpointRefForThreadTurn(threadId, 0),
470 toCheckpointRef: checkpointRefForThreadTurn(threadId, 1),
471 };
472 const commitBeforeTurn = (file: string, contents: string) =>
473 Effect.gen(function* () {
474 yield* writeTextFile(NodePath.join(tmp, file), contents);
475 yield* git(tmp, ["add", "."]);
476 yield* git(tmp, ["commit", "-m", file], { committedAt: "2020-01-01T00:00:00Z" });
477 });
478
479 yield* git(tmp, ["checkout", "-b", "upstream"]);
480 yield* commitBeforeTurn("upstream.txt", "upstream\n");
481 yield* commitBeforeTurn("shared.txt", "upstream\n");
482 yield* git(tmp, ["checkout", "-"]);
483 yield* commitBeforeTurn("shared.txt", "ours\n");
484 yield* checkpointStore.captureCheckpoint({
485 cwd: tmp,
486 checkpointRef: refs.fromCheckpointRef,
487 });
488
489 yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: refs.toCheckpointRef });
490 expect(yield* checkpointStore.listAuthoredPaths(refs)).toBeNull();
491
492 yield* git(tmp, ["merge", "upstream", "--no-edit"], { allowNonZeroExit: true });
493 yield* writeTextFile(NodePath.join(tmp, "shared.txt"), "upstream\n");
494 yield* git(tmp, ["commit", "-am", "merge upstream"]);
495 yield* writeTextFile(NodePath.join(tmp, "README.md"), "# edited\n");
496 yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: refs.toCheckpointRef });
497
498 const numstat = yield* checkpointStore.diffCheckpoints({
499 ...refs,
500 ignoreWhitespace: false,
501 format: "numstat",
502 });
503 expect(parseTurnDiffFilesFromNumstat(numstat).map((file) => file.path)).toEqual([
504 "README.md",
505 "shared.txt",
506 "upstream.txt",
507 ]);
508 expect(yield* checkpointStore.listAuthoredPaths(refs)).toEqual(
509 new Set(["README.md", "shared.txt"]),
510 );
511 }),
512 );
513 });
514});