Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as Cause from "effect/Cause";
4import * as Clock from "effect/Clock";
5import * as Duration from "effect/Duration";
6import * as Exit from "effect/Exit";
7import * as Deferred from "effect/Deferred";
8import * as Effect from "effect/Effect";
9import * as Fiber from "effect/Fiber";
10import * as TestClock from "effect/testing/TestClock";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Path from "effect/Path";
15import * as PlatformError from "effect/PlatformError";
16import { ChildProcessSpawner } from "effect/process";
17import * as Metric from "effect/Metric";
18import { assert, it } from "@effect/vitest";
19
20import { CheckpointRef, GitCommandError, VcsProcessExitError } from "@t3tools/contracts";
21import * as HostProcess from "@t3tools/shared/HostProcess";
22import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
23import * as ServerConfig from "../config.ts";
24import { gitCommandDuration, gitCommandsTotal } from "../observability/Metrics.ts";
25import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
26import * as ProcessRunner from "../processRunner.ts";
27import * as GitVcsDriver from "./GitVcsDriver.ts";
28import type * as VcsDriver from "./VcsDriver.ts";
29import * as VcsDriverRegistry from "./VcsDriverRegistry.ts";
30import * as VcsProcess from "./VcsProcess.ts";
31import { runVcsDriverContractSuite } from "./testing/VcsDriverContractHarness.ts";
32
33const layerServerConfig = ServerConfig.layerTest(process.cwd(), {
34 prefix: "t3-git-vcs-contract-",
35});
36const layerGitContract = Layer.mergeAll(GitVcsDriver.layerVcs, GitVcsDriver.layer).pipe(
37 Layer.provide(layerServerConfig),
38 Layer.provideMerge(VcsProcess.layer),
39 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
40);
41const layerGitCaptureContract = Layer.merge(
42 layerGitContract,
43 ProcessRunner.layer.pipe(Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
44);
45
46const runGit = (cwd: string, args: ReadonlyArray<string>) =>
47 Effect.gen(function* () {
48 const driver = yield* GitVcsDriver.GitVcsDriver;
49 yield* driver.execute({
50 operation: "GitVcsDriver.contract.git",
51 cwd,
52 args,
53 timeoutMs: 10_000,
54 });
55 });
56
57const makeCaptureStore = Effect.fn("test.makeCaptureStore")(function* (
58 driver: VcsDriver.VcsDriver["Service"],
59 cwd: string,
60) {
61 const repository = yield* driver.detectRepository(cwd);
62 if (repository === null) return yield* Effect.die("Expected a test Git repository");
63 const handle = { kind: repository.kind, repository, driver };
64 return yield* CheckpointStore.make.pipe(
65 Effect.provideService(VcsDriverRegistry.VcsDriverRegistry, {
66 get: () => Effect.succeed(driver),
67 detect: () => Effect.succeed(handle),
68 resolve: () => Effect.succeed(handle),
69 }),
70 );
71});
72
73type GitContractError = GitCommandError | PlatformError.PlatformError;
74
75runVcsDriverContractSuite<GitVcsDriver.GitVcsDriver, GitContractError>({
76 name: "Git",
77 kind: "git",
78 layer: layerGitContract,
79 fixture: {
80 createRepo: (cwd) =>
81 Effect.gen(function* () {
82 yield* runGit(cwd, ["init"]);
83 yield* runGit(cwd, ["config", "user.email", "test@test.com"]);
84 yield* runGit(cwd, ["config", "user.name", "Test"]);
85 }),
86 writeFile: (cwd, relativePath, contents) =>
87 Effect.gen(function* () {
88 const fileSystem = yield* FileSystem.FileSystem;
89 const path = yield* Path.Path;
90 const absolutePath = path.join(cwd, relativePath);
91 yield* fileSystem.makeDirectory(path.dirname(absolutePath), { recursive: true });
92 yield* fileSystem.writeFileString(absolutePath, contents);
93 }),
94 trackFile: (cwd, relativePath) => runGit(cwd, ["add", relativePath]),
95 commit: (cwd, message) => runGit(cwd, ["commit", "-m", message]),
96 ignorePath: (cwd, pattern) =>
97 Effect.gen(function* () {
98 const fileSystem = yield* FileSystem.FileSystem;
99 const path = yield* Path.Path;
100 yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), `${pattern}\n`);
101 }),
102 },
103});
104
105it.effect("lists the fetch and push URLs of a partial clone remote", () =>
106 Effect.gen(function* () {
107 const fileSystem = yield* FileSystem.FileSystem;
108 const cwd = yield* fileSystem.makeTempDirectoryScoped({
109 prefix: "t3-partial-clone-remotes-",
110 });
111 const driver = yield* GitVcsDriver.makeVcsDriverShape();
112 yield* runGit(cwd, ["init"]);
113 yield* runGit(cwd, ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"]);
114 yield* runGit(cwd, [
115 "remote",
116 "set-url",
117 "--push",
118 "origin",
119 "git@github.com:octocat/t3code.git",
120 ]);
121 yield* runGit(cwd, ["config", "remote.origin.promisor", "true"]);
122 yield* runGit(cwd, ["config", "remote.origin.partialclonefilter", "blob:none"]);
123
124 const result = yield* driver.listRemotes(cwd);
125 assert.deepEqual(result.remotes, [
126 {
127 name: "origin",
128 url: "https://github.com/pingdotgg/t3code.git",
129 pushUrl: Option.some("git@github.com:octocat/t3code.git"),
130 isPrimary: true,
131 },
132 ]);
133 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
134);
135
136const makeCheckpointFixture = Effect.fn("makeCheckpointFixture")(function* (
137 driver: Effect.Success<ReturnType<typeof GitVcsDriver.makeVcsDriverShape>>,
138 cwd: string,
139) {
140 const fileSystem = yield* FileSystem.FileSystem;
141 const path = yield* Path.Path;
142 const git = (args: ReadonlyArray<string>) =>
143 driver.execute({ operation: "checkpoint-test", cwd, args });
144 yield* git(["init"]);
145 yield* git(["config", "user.name", "Test"]);
146 yield* git(["config", "user.email", "test@test.com"]);
147 yield* fileSystem.writeFileString(path.join(cwd, "file.txt"), "initial\n");
148 yield* git(["add", "."]);
149 yield* git(["commit", "-m", "initial"]);
150 const checkpointRef = CheckpointRef.make("refs/t3/checkpoints/test");
151 yield* fileSystem.writeFileString(path.join(cwd, "file.txt"), "staged\n");
152 yield* git(["add", "."]);
153 yield* fileSystem.writeFileString(path.join(cwd, "file.txt"), "unstaged\n");
154 return { git, checkpointRef };
155});
156
157it.effect("checkpoint capture skips untracked nested repositories without a commit", () =>
158 Effect.gen(function* () {
159 const fileSystem = yield* FileSystem.FileSystem;
160 const path = yield* Path.Path;
161 const driver = yield* GitVcsDriver.makeVcsDriverShape();
162 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-unborn-" });
163 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
164 const nested = "scratch/empty [repo]";
165 yield* git(["init", nested]);
166 yield* git(["init", "another empty"]);
167 yield* fileSystem.writeFileString(path.join(cwd, nested, "private.txt"), "nested\n");
168 yield* git(["init", "committed"]);
169 yield* git([
170 "-C",
171 "committed",
172 "-c",
173 "user.name=Test",
174 "-c",
175 "user.email=test@test.com",
176 "commit",
177 "--allow-empty",
178 "-m",
179 "initial",
180 ]);
181 const nestedHead = (yield* git(["-C", "committed", "rev-parse", "HEAD"])).stdout.trim();
182 yield* fileSystem.writeFileString(path.join(cwd, "untracked.txt"), "new\n");
183 const originalIndex = yield* fileSystem.readFile(path.join(cwd, ".git", "index"));
184
185 yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
186
187 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "unstaged\n");
188 assert.strictEqual((yield* git(["show", `${checkpointRef}:untracked.txt`])).stdout, "new\n");
189 assert.strictEqual((yield* git(["ls-tree", "-r", checkpointRef, "--", nested])).stdout, "");
190 assert.strictEqual((yield* git(["ls-tree", checkpointRef, "--", "another empty"])).stdout, "");
191 assert.strictEqual(
192 (yield* git(["ls-tree", checkpointRef, "--", "committed"])).stdout,
193 `160000 commit ${nestedHead}\tcommitted\n`,
194 );
195 assert.deepEqual(yield* fileSystem.readFile(path.join(cwd, ".git", "index")), originalIndex);
196 assert.strictEqual(
197 yield* fileSystem.readFileString(path.join(cwd, nested, "private.txt")),
198 "nested\n",
199 );
200 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
201);
202
203it.effect.skipIf(!symlinksSupported)(
204 "checkpoint capture writes its index into the real git dir when cwd is a symlinked subdirectory",
205 () =>
206 Effect.gen(function* () {
207 const fileSystem = yield* FileSystem.FileSystem;
208 const path = yield* Path.Path;
209 const liveRunner = yield* ProcessRunner.ProcessRunner;
210 const indexFiles: string[] = [];
211 const captureProcess = yield* VcsProcess.make.pipe(
212 Effect.provideService(ProcessRunner.ProcessRunner, {
213 run: (input) => {
214 const indexFile = input.env?.GIT_INDEX_FILE;
215 if (indexFile !== undefined) indexFiles.push(indexFile);
216 return liveRunner.run(input);
217 },
218 }),
219 );
220 const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
221 Effect.provideService(VcsProcess.VcsProcess, captureProcess),
222 );
223 const sandbox = yield* fileSystem.makeTempDirectoryScoped({
224 prefix: "t3-checkpoint-symlink-",
225 });
226 const repo = path.join(sandbox, "repo");
227 const subdir = path.join(repo, "sub", "dir");
228 const link = path.join(sandbox, "nest", "link");
229 yield* fileSystem.makeDirectory(subdir, { recursive: true });
230 yield* fileSystem.makeDirectory(path.dirname(link), { recursive: true });
231 yield* fileSystem.symlink(subdir, link);
232 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, repo);
233 // Git returns ../../.git from the target; resolving it against the link reaches the decoy.
234 yield* git(["-C", sandbox, "init"]);
235 yield* fileSystem.writeFileString(path.join(subdir, "nested.txt"), "from-link\n");
236 const realCommonDir = yield* fileSystem.realPath(path.join(repo, ".git"));
237
238 yield* driver.checkpoints.captureCheckpoint({ cwd: link, checkpointRef });
239
240 assert.isTrue(indexFiles.length > 0);
241 for (const indexFile of indexFiles) {
242 assert.strictEqual(yield* fileSystem.realPath(path.dirname(indexFile)), realCommonDir);
243 }
244 assert.strictEqual(
245 (yield* git(["show", `${checkpointRef}:sub/dir/nested.txt`])).stdout,
246 "from-link\n",
247 );
248 }).pipe(Effect.scoped, Effect.provide(layerGitCaptureContract)),
249);
250
251it.effect("checkpoint capture keeps the shared index a split index still uses", () =>
252 Effect.gen(function* () {
253 const fileSystem = yield* FileSystem.FileSystem;
254 const path = yield* Path.Path;
255 const driver = yield* GitVcsDriver.makeVcsDriverShape();
256 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-split-" });
257 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
258 yield* git(["config", "core.splitIndex", "true"]);
259 yield* git(["config", "splitIndex.sharedIndexExpire", "now"]);
260 yield* git(["update-index", "--split-index"]);
261 yield* fileSystem.writeFileString(path.join(cwd, "untracked.txt"), "new\n");
262
263 yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
264
265 assert.strictEqual((yield* git(["show", `${checkpointRef}:untracked.txt`])).stdout, "new\n");
266 assert.strictEqual((yield* git(["ls-files", "--cached"])).stdout, "file.txt\n");
267 assert.strictEqual((yield* git(["diff", "--cached", "--name-only"])).stdout, "file.txt\n");
268 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
269);
270
271it.effect("checkpoint recovery discovers nested HEAD independently of inherited GIT_DIR", () =>
272 Effect.gen(function* () {
273 const fs = yield* FileSystem.FileSystem;
274 const path = yield* Path.Path;
275 const driver = yield* GitVcsDriver.makeVcsDriverShape();
276 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-git-dir-" });
277 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
278 yield* git(["init", "empty"]);
279 const originalIndex = yield* fs.readFile(path.join(cwd, ".git", "index"));
280 yield* Effect.acquireUseRelease(
281 Effect.sync(() => {
282 const previous = process.env.GIT_DIR;
283 process.env.GIT_DIR = path.join(cwd, ".git");
284 return previous;
285 }),
286 () => driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }),
287 (previous) =>
288 Effect.sync(() => {
289 if (previous === undefined) delete process.env.GIT_DIR;
290 else process.env.GIT_DIR = previous;
291 }),
292 );
293 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "unstaged\n");
294 assert.strictEqual((yield* git(["ls-tree", "-r", checkpointRef, "--", "empty"])).stdout, "");
295 assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git", "index")), originalIndex);
296 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
297);
298
299it.effect("checkpoint capture still fails when a clean filter rejects a file", () =>
300 Effect.gen(function* () {
301 const fileSystem = yield* FileSystem.FileSystem;
302 const path = yield* Path.Path;
303 const driver = yield* GitVcsDriver.makeVcsDriverShape();
304 const cwd = yield* fileSystem.makeTempDirectoryScoped({
305 prefix: "t3-checkpoint-filter-failure-",
306 });
307 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
308 yield* fileSystem.writeFileString(path.join(cwd, ".gitattributes"), "file.txt filter=reject\n");
309 yield* git(["config", "filter.reject.clean", "false"]);
310 yield* git(["config", "filter.reject.required", "true"]);
311 const originalIndex = yield* fileSystem.readFile(path.join(cwd, ".git", "index"));
312
313 const result = yield* Effect.result(
314 driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }),
315 );
316
317 assert.strictEqual(result._tag, "Failure");
318 if (result._tag === "Failure") {
319 assert.strictEqual(result.failure._tag, "VcsProcessExitError");
320 }
321 assert.deepEqual(yield* fileSystem.readFile(path.join(cwd, ".git", "index")), originalIndex);
322 assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }));
323 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
324);
325
326it.effect("checkpoint capture refuses a truncated nested repository listing", () =>
327 Effect.gen(function* () {
328 const fs = yield* FileSystem.FileSystem;
329 const liveProcess = yield* VcsProcess.VcsProcess;
330 const driver = yield* GitVcsDriver.makeVcsDriverShape();
331 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-truncated-" });
332 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
333 yield* git(["init", "empty"]);
334 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
335 Effect.provideService(VcsProcess.VcsProcess, {
336 run: (input) =>
337 liveProcess
338 .run(input)
339 .pipe(
340 Effect.map((result) =>
341 input.args.includes("--others") ? { ...result, stdoutTruncated: true } : result,
342 ),
343 ),
344 }),
345 );
346
347 const result = yield* Effect.result(
348 captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef }),
349 );
350
351 assert.strictEqual(result._tag, "Failure");
352 assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }));
353 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
354);
355
356it.effect("checkpoint capture skips an ignored project while keeping its allowed sibling", () =>
357 Effect.gen(function* () {
358 const fs = yield* FileSystem.FileSystem;
359 const path = yield* Path.Path;
360 const driver = yield* GitVcsDriver.makeVcsDriverShape();
361 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-ignored-" });
362 const { git } = yield* makeCheckpointFixture(driver, parent);
363 yield* fs.writeFileString(
364 path.join(parent, ".gitignore"),
365 "*\n!.gitignore\n!file.txt\n!keep/\n!keep/**\n",
366 );
367 const ignoredCwd = path.join(parent, "ignored");
368 const keepCwd = path.join(parent, "keep");
369 yield* fs.makeDirectory(ignoredCwd);
370 yield* fs.makeDirectory(keepCwd);
371 yield* fs.writeFileString(path.join(ignoredCwd, "secret.txt"), "private\n");
372 yield* fs.writeFileString(path.join(keepCwd, "new.txt"), "new\n");
373 const originalIndex = yield* fs.readFile(path.join(parent, ".git", "index"));
374 const ignoredRef = CheckpointRef.make("refs/t3/checkpoints/ignored");
375 const keepRef = CheckpointRef.make("refs/t3/checkpoints/keep");
376
377 const ignored = yield* Effect.result(
378 driver.checkpoints.captureCheckpoint({ cwd: ignoredCwd, checkpointRef: ignoredRef }),
379 );
380 yield* driver.checkpoints.captureCheckpoint({ cwd: keepCwd, checkpointRef: keepRef });
381
382 assert.strictEqual((yield* git(["show", `${keepRef}:keep/new.txt`])).stdout, "new\n");
383 assert.strictEqual((yield* git(["ls-tree", "-r", keepRef, "--", "ignored"])).stdout, "");
384 assert.isFalse(
385 yield* driver.checkpoints.hasCheckpointRef({ cwd: parent, checkpointRef: ignoredRef }),
386 );
387 assert.deepEqual(yield* fs.readFile(path.join(parent, ".git", "index")), originalIndex);
388 assert.strictEqual(ignored._tag, "Failure");
389 if (ignored._tag === "Failure") {
390 assert.strictEqual(ignored.failure._tag, "VcsUnsupportedOperationError");
391 }
392 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
393);
394
395it.effect.each([
396 { tracking: "committed-only", committed: ["committed.txt"], staged: [] },
397 { tracking: "staged-only", committed: [], staged: ["staged.txt"] },
398 { tracking: "mixed", committed: ["committed.txt"], staged: ["staged.txt"] },
399])(
400 "checkpoint capture keeps $tracking tracked edits but excludes new files in a project ignored later",
401 ({ committed, staged }) =>
402 Effect.gen(function* () {
403 const fs = yield* FileSystem.FileSystem;
404 const path = yield* Path.Path;
405 const driver = yield* GitVcsDriver.makeVcsDriverShape();
406 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-ignored-later-" });
407 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, parent);
408 const cwd = path.join(parent, "sub");
409 yield* fs.makeDirectory(cwd);
410 for (const file of committed) {
411 yield* fs.writeFileString(path.join(cwd, file), "committed\n");
412 yield* git(["add", `sub/${file}`]);
413 }
414 if (committed.length > 0) {
415 yield* git(["commit", "-m", "track project"]);
416 }
417 for (const file of staged) {
418 yield* fs.writeFileString(path.join(cwd, file), "staged\n");
419 yield* git(["add", `sub/${file}`]);
420 }
421 const tracked = [...committed, ...staged];
422 yield* fs.writeFileString(path.join(parent, ".gitignore"), "sub/\n");
423 for (const file of tracked) {
424 yield* fs.writeFileString(path.join(cwd, file), `${file} working\n`);
425 }
426 yield* fs.writeFileString(path.join(cwd, "secret.txt"), "private\n");
427 const originalIndex = yield* fs.readFile(path.join(parent, ".git", "index"));
428
429 const captured = yield* Effect.result(
430 driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }),
431 );
432
433 assert.deepEqual(yield* fs.readFile(path.join(parent, ".git", "index")), originalIndex);
434 if (captured._tag === "Failure") return yield* captured.failure;
435 assert.strictEqual(
436 (yield* git(["ls-tree", "-r", "--name-only", checkpointRef, "--", "sub"])).stdout,
437 tracked.map((file) => `sub/${file}\n`).join(""),
438 );
439 for (const file of tracked) {
440 assert.strictEqual(
441 (yield* git(["show", `${checkpointRef}:sub/${file}`])).stdout,
442 `${file} working\n`,
443 );
444 }
445 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
446);
447
448it.effect.each([
449 { phase: "add", nestedRecovery: false, expireRecovery: false },
450 { phase: "update-ref", nestedRecovery: false, expireRecovery: false },
451 { phase: "update-ref", nestedRecovery: true, expireRecovery: false },
452 { phase: "add", nestedRecovery: true, expireRecovery: false },
453 { phase: "add", nestedRecovery: true, expireRecovery: true },
454])(
455 "checkpoint handles a $phase lock with nestedRecovery=$nestedRecovery, expireRecovery=$expireRecovery",
456 ({ phase, nestedRecovery, expireRecovery }) =>
457 Effect.gen(function* () {
458 const fs = yield* FileSystem.FileSystem;
459 const path = yield* Path.Path;
460 const liveRunner = yield* ProcessRunner.ProcessRunner;
461 const driver = yield* GitVcsDriver.makeVcsDriverShape();
462 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-ref-race-" });
463 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
464 if (nestedRecovery) yield* git(["init", "empty"]);
465 const originalIndex = yield* fs.readFile(path.join(cwd, ".git", "index"));
466 const refLockPath = path.join(cwd, ".git", `${checkpointRef}.lock`);
467 const failed = yield* Deferred.make<void>();
468 const retryReached = yield* Deferred.make<void>();
469 const allowRetry = yield* Deferred.make<void>();
470 const clock = yield* Clock.Clock;
471 const privateIndexes = new Set<string>();
472 let racedAttempts = 0;
473 let discoveries = 0;
474 let stageError: VcsProcessExitError | undefined;
475 const captureProcess = yield* VcsProcess.make.pipe(
476 Effect.provideService(ProcessRunner.ProcessRunner, {
477 run: (input) => {
478 if (input.args.includes("--others")) discoveries += 1;
479 if (input.env?.GIT_INDEX_FILE) privateIndexes.add(input.env.GIT_INDEX_FILE);
480 const initialStage =
481 phase === "add" &&
482 nestedRecovery &&
483 !input.args.some((arg) => arg.startsWith(":(exclude,literal)"));
484 if (!input.args.includes(phase) || initialStage || ++racedAttempts !== 1) {
485 return liveRunner.run(input);
486 }
487 const lockPath = phase === "add" ? `${input.env!.GIT_INDEX_FILE!}.lock` : refLockPath;
488 return Effect.gen(function* () {
489 yield* fs
490 .makeDirectory(path.dirname(lockPath), { recursive: true })
491 .pipe(Effect.orDie);
492 yield* fs.writeFileString(lockPath, "concurrent ref writer").pipe(Effect.orDie);
493 return yield* liveRunner.run(input).pipe(
494 Effect.ensuring(fs.remove(lockPath).pipe(Effect.orDie)),
495 Effect.tap(() => Deferred.succeed(failed, undefined)),
496 );
497 });
498 },
499 }),
500 );
501 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
502 Effect.provideService(VcsProcess.VcsProcess, {
503 run: (input) =>
504 captureProcess.run(input).pipe(
505 Effect.tapError((error) => {
506 if (input.args.includes("add") && error._tag === "VcsProcessExitError")
507 stageError = error;
508 return Effect.void;
509 }),
510 ),
511 }),
512 );
513 const captureStore = yield* makeCaptureStore(captureDriver, cwd);
514 const fiber = yield* captureStore.captureCheckpoint({ cwd, checkpointRef }).pipe(
515 Effect.provideService(Clock.Clock, {
516 ...clock,
517 sleep: (duration) =>
518 Duration.toMillis(duration) === 75
519 ? Deferred.succeed(retryReached, undefined).pipe(
520 Effect.andThen(Deferred.await(allowRetry)),
521 )
522 : clock.sleep(duration),
523 }),
524 Effect.exit,
525 Effect.forkScoped,
526 );
527 yield* Deferred.await(failed);
528 yield* Deferred.await(retryReached);
529 if (expireRecovery) yield* TestClock.adjust("5 seconds");
530 else yield* Deferred.succeed(allowRetry, undefined);
531 const result = yield* Fiber.join(fiber);
532 if (expireRecovery) {
533 if (Exit.isSuccess(result))
534 return yield* Effect.die("Expected the recovery deadline to expire");
535 const error = Cause.findErrorOption(result.cause);
536 assert.isTrue(error._tag === "Some");
537 if (error._tag === "Some") assert.strictEqual(error.value, stageError);
538 } else assert.isTrue(Exit.isSuccess(result));
539 assert.strictEqual(racedAttempts, expireRecovery ? 1 : 2);
540 assert.strictEqual(discoveries, nestedRecovery ? 1 : 0);
541 assert.strictEqual(privateIndexes.size, 1);
542 assert.strictEqual(
543 yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }),
544 !expireRecovery,
545 );
546 for (const index of privateIndexes) {
547 assert.isFalse(yield* fs.exists(index));
548 assert.isFalse(yield* fs.exists(`${index}.lock`));
549 }
550 assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git", "index")), originalIndex);
551 }).pipe(Effect.scoped, Effect.provide(layerGitCaptureContract)),
552);
553
554it.effect("checkpoint recovery preserves interruption and removes the private index", () =>
555 Effect.gen(function* () {
556 const fs = yield* FileSystem.FileSystem;
557 const liveProcess = yield* VcsProcess.VcsProcess;
558 const driver = yield* GitVcsDriver.makeVcsDriverShape();
559 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-recovery-interrupt-" });
560 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
561 yield* git(["init", "empty"]);
562 const entered = yield* Deferred.make<void>();
563 let privateIndex: string | undefined;
564 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
565 Effect.provideService(VcsProcess.VcsProcess, {
566 run: (input) => {
567 if (input.args.includes("add") && input.args.includes("-A"))
568 privateIndex = input.env?.GIT_INDEX_FILE;
569 return input.args.includes("--others")
570 ? Deferred.succeed(entered, undefined).pipe(Effect.andThen(Effect.never))
571 : liveProcess.run(input);
572 },
573 }),
574 );
575 const fiber = yield* captureDriver.checkpoints
576 .captureCheckpoint({ cwd, checkpointRef })
577 .pipe(Effect.forkScoped);
578 yield* Deferred.await(entered);
579 yield* Fiber.interrupt(fiber);
580 const exit = yield* Fiber.await(fiber);
581 assert.isTrue(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause));
582 assert.isDefined(privateIndex);
583 assert.isFalse(yield* fs.exists(privateIndex!));
584 assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }));
585 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
586);
587
588it.effect.each(
589 [false, true].flatMap((nested) =>
590 (["sparse", "flags", "manual-skip", "missing", "non-cone-missing"] as const).map(
591 (indexState) => ({ nested, indexState }),
592 ),
593 ),
594)(
595 "sparse checkpoint preserves two captures (nested=$nested, index=$indexState)",
596 ({ nested, indexState }) =>
597 Effect.gen(function* () {
598 const fs = yield* FileSystem.FileSystem;
599 const path = yield* Path.Path;
600 const driver = yield* GitVcsDriver.makeVcsDriverShape();
601 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-sparse-" });
602 const { git } = yield* makeCheckpointFixture(driver, cwd);
603 const write = Effect.fn(function* (name: string, contents: string) {
604 yield* fs.makeDirectory(path.dirname(path.join(cwd, name)), { recursive: true });
605 yield* fs.writeFileString(path.join(cwd, name), contents);
606 });
607 for (const name of [
608 "scope/in/edit",
609 "scope/in/delete",
610 "scope/out/deep/absent",
611 "scope/out/present",
612 "elsewhere/file",
613 ]) {
614 yield* write(name, "original\n");
615 }
616 yield* git(["add", "."]);
617 yield* git(["commit", "-m", "sparse fixture"]);
618 yield* git(["sparse-checkout", "set", "--cone", "--sparse-index", "scope/in", "elsewhere"]);
619 if (indexState === "non-cone-missing")
620 yield* git(["sparse-checkout", "set", "--no-cone", "/scope/in/", "/elsewhere/"]);
621 yield* write("scope/in/edit", "staged\n");
622 yield* write("elsewhere/file", "staged outside\n");
623 yield* git(["add", "."]);
624 if (indexState === "flags")
625 yield* git(["update-index", "--assume-unchanged", "scope/in/delete"]);
626 if (indexState === "manual-skip")
627 yield* git(["update-index", "--skip-worktree", "scope/in/delete"]);
628 yield* git(["config", "sparse.expectFilesOutsideOfPatterns", "true"]);
629 yield* write("scope/in/edit", "working\n");
630 yield* write("scope/out/present", "modified skipped\n");
631 yield* write("scope/out/new file", "new outside cone\n");
632 yield* write("elsewhere/file", "working outside\n");
633 yield* fs.remove(path.join(cwd, "scope/in/delete"));
634 const indexPath = path.join(cwd, ".git/index");
635 if (indexState.endsWith("missing")) yield* fs.remove(indexPath);
636 const originalIndex = yield* fs.readFile(indexPath).pipe(Effect.orElseSucceed(() => null));
637 const captureCwd = nested ? path.join(cwd, "scope") : cwd;
638 for (const turn of [1, 2]) {
639 const ref = CheckpointRef.make(`refs/t3/checkpoints/sparse/${turn}`);
640 if (turn === 2) {
641 yield* write("scope/in/edit", "second\n");
642 yield* fs.remove(path.join(cwd, "scope/out/new file"));
643 yield* write("scope/out/second", "second addition\n");
644 }
645 const capture = driver.checkpoints.captureCheckpoint({
646 cwd: captureCwd,
647 checkpointRef: ref,
648 });
649 if (indexState === "non-cone-missing") {
650 assert.strictEqual((yield* capture.pipe(Effect.flip))._tag, "VcsProcessExitError");
651 assert.isFalse(
652 yield* driver.checkpoints.hasCheckpointRef({ cwd: captureCwd, checkpointRef: ref }),
653 );
654 assert.isFalse(yield* fs.exists(indexPath));
655 break;
656 }
657 yield* capture;
658 for (const [name, content] of [
659 ["scope/out/deep/absent", "original\n"],
660 ["scope/out/present", "modified skipped\n"],
661 ["scope/in/edit", turn === 1 ? "working\n" : "second\n"],
662 ["elsewhere/file", nested ? "original\n" : "working outside\n"],
663 [
664 turn === 1 ? "scope/out/new file" : "scope/out/second",
665 turn === 1 ? "new outside cone\n" : "second addition\n",
666 ],
667 ]) {
668 assert.strictEqual((yield* git(["show", `${ref}:${name}`])).stdout, content);
669 }
670 const files = (yield* git(["ls-tree", "-rz", "--name-only", ref])).stdout.split("\0");
671 assert.notInclude(files, "scope/in/delete");
672 if (turn === 2) assert.notInclude(files, "scope/out/new file");
673 assert.deepEqual(
674 yield* fs.readFile(indexPath).pipe(Effect.orElseSucceed(() => null)),
675 originalIndex,
676 );
677 assert.isFalse(yield* fs.exists(path.join(cwd, "scope/out/deep/absent")));
678 assert.strictEqual(
679 yield* fs.readFileString(path.join(cwd, "elsewhere/file")),
680 "working outside\n",
681 );
682 }
683 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
684);
685
686it.effect.each(
687 (["normal", "flags", "sparse"] as const).flatMap((indexMode) =>
688 [1, 3, 4096].map((chunkSize) => ({ indexMode, chunkSize })),
689 ),
690)(
691 "checkpoint index inspection handles entries beyond the output cap (index=$indexMode, chunk=$chunkSize)",
692 ({ indexMode, chunkSize }) =>
693 Effect.gen(function* () {
694 const fs = yield* FileSystem.FileSystem;
695 const path = yield* Path.Path;
696 const liveProcess = yield* VcsProcess.VcsProcess;
697 const driver = yield* GitVcsDriver.makeVcsDriverShape();
698 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-inspection-" });
699 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
700 yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "stable filter=probe\n");
701 yield* fs.writeFileString(path.join(cwd, "stable"), "unchanged\n");
702 yield* fs.writeFileString(path.join(cwd, "z-skipped"), "original\n");
703 yield* fs.makeDirectory(path.join(cwd, "excluded"));
704 yield* fs.writeFileString(path.join(cwd, "excluded/file"), "absent\n");
705 yield* fs.writeFileString(
706 path.join(cwd, ".git/filter.cjs"),
707 'require("node:fs").appendFileSync(".git/reads", "read\\n"); process.stdin.pipe(process.stdout);',
708 );
709 yield* git(["config", "filter.probe.clean", "node .git/filter.cjs"]);
710 yield* fs.utimes(path.join(cwd, "stable"), 1_700_000_000, 1_700_000_000);
711 yield* git(["add", "."]);
712 yield* git(["commit", "-m", "inspection fixture"]);
713 if (indexMode === "flags") yield* git(["update-index", "--skip-worktree", "z-skipped"]);
714 if (indexMode === "sparse")
715 yield* git(["sparse-checkout", "set", "--cone", "--sparse-index", "included"]);
716 yield* fs.writeFileString(path.join(cwd, "z-skipped"), "modified\n");
717 yield* fs.writeFileString(path.join(cwd, ".git/reads"), "");
718 const originalIndex = yield* fs.readFile(path.join(cwd, ".git/index"));
719 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
720 Effect.provideService(VcsProcess.VcsProcess, {
721 run: (input) =>
722 liveProcess.run(
723 input.args.includes("ls-files")
724 ? {
725 ...input,
726 maxOutputBytes: 8,
727 onStdoutChunk: (chunk) => {
728 for (let i = 0; i < chunk.length; i += chunkSize)
729 input.onStdoutChunk?.(chunk.subarray(i, i + chunkSize));
730 },
731 }
732 : input,
733 ),
734 }),
735 );
736 yield* captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
737 assert.strictEqual((yield* git(["show", `${checkpointRef}:z-skipped`])).stdout, "modified\n");
738 if (indexMode !== "flags")
739 assert.strictEqual(yield* fs.readFileString(path.join(cwd, ".git/reads")), "");
740 assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git/index")), originalIndex);
741 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
742);
743
744it.effect.each([1_700_000_000, 1_700_000_000.9999])(
745 "checkpoint capture preserves same-size edits with racy index timestamps (%s)",
746 (timestamp) =>
747 Effect.gen(function* () {
748 const fileSystem = yield* FileSystem.FileSystem;
749 const path = yield* Path.Path;
750 const driver = yield* GitVcsDriver.makeVcsDriverShape();
751 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-racy-" });
752 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
753 const filePath = path.join(cwd, "file.txt");
754 const indexPath = path.join(cwd, ".git", "index");
755 yield* git(["config", "core.trustctime", "false"]);
756 yield* fileSystem.writeFileString(filePath, "before\n");
757 yield* fileSystem.utimes(filePath, timestamp, timestamp);
758 yield* git(["add", "file.txt"]);
759 yield* git(["commit", "-m", "record racy file"]);
760 yield* fileSystem.utimes(indexPath, timestamp, timestamp);
761 const originalIndex = yield* fileSystem.readFile(indexPath);
762 const originalIndexMtime = (yield* fileSystem.stat(indexPath)).mtime;
763 yield* fileSystem.writeFileString(filePath, "after!\n");
764 yield* fileSystem.utimes(filePath, timestamp, timestamp);
765
766 yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
767
768 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "after!\n");
769 assert.deepEqual(yield* fileSystem.readFile(indexPath), originalIndex);
770 assert.deepEqual((yield* fileSystem.stat(indexPath)).mtime, originalIndexMtime);
771 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
772);
773
774it.effect("checkpoint capture preserves racy edits made after resetting the index", () =>
775 Effect.gen(function* () {
776 const fileSystem = yield* FileSystem.FileSystem;
777 const path = yield* Path.Path;
778 const liveProcess = yield* VcsProcess.VcsProcess;
779 const driver = yield* GitVcsDriver.makeVcsDriverShape();
780 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-racy-reset-" });
781 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
782 const racyPath = path.join(cwd, "racy.txt");
783 const indexPath = path.join(cwd, ".git", "index");
784 const timestamp = 1_700_000_000;
785 yield* git(["config", "core.trustctime", "false"]);
786 yield* fileSystem.writeFileString(racyPath, "before\n");
787 yield* fileSystem.utimes(racyPath, timestamp, timestamp);
788 yield* git(["add", "."]);
789 yield* git(["commit", "-m", "record racy file"]);
790 yield* fileSystem.writeFileString(path.join(cwd, "file.txt"), "staged\n");
791 yield* git(["add", "file.txt"]);
792 yield* fileSystem.utimes(indexPath, timestamp, timestamp);
793 const originalIndex = yield* fileSystem.readFile(indexPath);
794 const originalIndexMtime = (yield* fileSystem.stat(indexPath)).mtime;
795 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
796 Effect.provideService(VcsProcess.VcsProcess, {
797 run: Effect.fn(function* (input: VcsProcess.VcsProcessInput) {
798 const result = yield* liveProcess.run(input);
799 if (input.args.includes("read-tree") && input.args.includes("--reset")) {
800 yield* fileSystem.writeFileString(racyPath, "after!\n").pipe(Effect.orDie);
801 yield* fileSystem.utimes(racyPath, timestamp, timestamp).pipe(Effect.orDie);
802 }
803 return result;
804 }),
805 }),
806 );
807
808 yield* captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
809
810 assert.strictEqual((yield* git(["show", `${checkpointRef}:racy.txt`])).stdout, "after!\n");
811 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "staged\n");
812 assert.deepEqual(yield* fileSystem.readFile(indexPath), originalIndex);
813 assert.deepEqual((yield* fileSystem.stat(indexPath)).mtime, originalIndexMtime);
814 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
815);
816
817it.effect.each(
818 [false, true].flatMap((nested) =>
819 (["normal", "flags", "split"] as const).map((indexMode) => ({ nested, indexMode })),
820 ),
821)(
822 "checkpoint index reuse preserves two turns (nested=$nested, index=$indexMode)",
823 ({ nested, indexMode }) =>
824 Effect.gen(function* () {
825 const fileSystem = yield* FileSystem.FileSystem;
826 const path = yield* Path.Path;
827 const driver = yield* GitVcsDriver.makeVcsDriverShape();
828 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-turns-" });
829 const { git } = yield* makeCheckpointFixture(driver, cwd);
830 const write = (name: string, contents: string) =>
831 fileSystem.writeFileString(path.join(cwd, name), contents);
832 yield* fileSystem.makeDirectory(path.join(cwd, "scope"));
833 for (const name of [
834 "scope/staged",
835 "scope/deleted",
836 "scope/assumed",
837 "scope/skipped",
838 "outside",
839 ]) {
840 yield* write(name, "original\n");
841 }
842 yield* git(["add", "."]);
843 yield* git(["commit", "-m", "initial scoped files"]);
844 yield* write("scope/staged", "staged\n");
845 yield* write("scope/new-deleted", "staged then deleted\n");
846 yield* write("outside", "staged outside\n");
847 yield* git(["add", "."]);
848 if (indexMode === "flags") {
849 yield* git(["update-index", "--assume-unchanged", "scope/assumed"]);
850 yield* git(["update-index", "--skip-worktree", "scope/skipped"]);
851 }
852 if (indexMode === "split") {
853 yield* git(["update-index", "--split-index"]);
854 }
855 const originalIndex = yield* fileSystem.readFile(path.join(cwd, ".git", "index"));
856 for (const name of ["scope/staged", "scope/assumed", "scope/skipped", "outside"]) {
857 yield* write(name, "working\n");
858 }
859 yield* write("scope/new", "first\n");
860 yield* fileSystem.remove(path.join(cwd, "scope/deleted"));
861 yield* fileSystem.remove(path.join(cwd, "scope/new-deleted"));
862 const captureCwd = nested ? path.join(cwd, "scope") : cwd;
863 const first = CheckpointRef.make("refs/t3/checkpoints/turns/1");
864 const second = CheckpointRef.make("refs/t3/checkpoints/turns/2");
865 yield* driver.checkpoints.captureCheckpoint({ cwd: captureCwd, checkpointRef: first });
866 for (const name of ["scope/staged", "scope/assumed", "scope/skipped"]) {
867 assert.strictEqual((yield* git(["show", `${first}:${name}`])).stdout, "working\n");
868 }
869 assert.strictEqual(
870 (yield* git(["show", `${first}:outside`])).stdout,
871 nested ? "original\n" : "working\n",
872 );
873 const files = (yield* git(["ls-tree", "-r", "--name-only", first])).stdout.split("\n");
874 assert.notInclude(files, "scope/deleted");
875 assert.notInclude(files, "scope/new-deleted");
876 assert.include(files, "scope/new");
877
878 yield* write("scope/staged", "second\n");
879 yield* fileSystem.remove(path.join(cwd, "scope/new"));
880 yield* write("scope/second", "added in second turn\n");
881 yield* driver.checkpoints.captureCheckpoint({ cwd: captureCwd, checkpointRef: second });
882 assert.strictEqual(
883 (yield* git(["diff", "--name-only", first, second])).stdout,
884 "scope/new\nscope/second\nscope/staged\n",
885 );
886 assert.strictEqual((yield* git(["show", `${second}:scope/staged`])).stdout, "second\n");
887 assert.strictEqual(
888 (yield* git(["show", `${second}:scope/second`])).stdout,
889 "added in second turn\n",
890 );
891 assert.deepEqual(yield* fileSystem.readFile(path.join(cwd, ".git", "index")), originalIndex);
892 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
893);
894
895it.effect.each(["missing", "invalid"] as const)(
896 "checkpoint capture falls back when the user index is %s",
897 (indexState) =>
898 Effect.gen(function* () {
899 const fileSystem = yield* FileSystem.FileSystem;
900 const path = yield* Path.Path;
901 const driver = yield* GitVcsDriver.makeVcsDriverShape();
902 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-index-" });
903 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
904 const indexPath = path.join(cwd, ".git", "index");
905 if (indexState === "missing") {
906 yield* fileSystem.remove(indexPath);
907 } else {
908 yield* fileSystem.writeFileString(indexPath, "invalid index");
909 }
910
911 yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
912
913 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "unstaged\n");
914 if (indexState === "missing") {
915 assert.isFalse(yield* fileSystem.exists(indexPath));
916 } else {
917 assert.strictEqual(yield* fileSystem.readFileString(indexPath), "invalid index");
918 }
919 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
920);
921
922const captureRecordingGitCommands = Effect.fn("test.captureRecordingGitCommands")(function* (
923 cwd: string,
924 checkpointRef: CheckpointRef,
925) {
926 const liveProcess = yield* VcsProcess.VcsProcess;
927 const commands: Array<string | undefined> = [];
928 const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
929 Effect.provideService(VcsProcess.VcsProcess, {
930 run: (input) => {
931 let index = 0;
932 while (input.args[index] === "-C" || input.args[index] === "-c") index += 2;
933 commands.push(input.args[index]);
934 return liveProcess.run(input);
935 },
936 }),
937 );
938 yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
939 return commands;
940});
941
942it.effect.each(["committed", "unborn"] as const)(
943 "checkpoint capture reads the repository with one rev-parse (HEAD=%s)",
944 (head) =>
945 Effect.gen(function* () {
946 const fileSystem = yield* FileSystem.FileSystem;
947 const path = yield* Path.Path;
948 const driver = yield* GitVcsDriver.makeVcsDriverShape();
949 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-processes-" });
950 const git = (args: ReadonlyArray<string>) =>
951 driver.execute({ operation: "checkpoint-test", cwd, args });
952 const checkpointRef = CheckpointRef.make("refs/t3/checkpoints/test");
953 if (head === "committed") {
954 yield* makeCheckpointFixture(driver, cwd);
955 } else {
956 yield* git(["init"]);
957 yield* fileSystem.writeFileString(path.join(cwd, "file.txt"), "unstaged\n");
958 }
959
960 const commands = yield* captureRecordingGitCommands(cwd, checkpointRef);
961
962 assert.deepStrictEqual(commands, [
963 "rev-parse",
964 "config",
965 ...(head === "committed" ? ["read-tree", "ls-files"] : []),
966 "check-ignore",
967 "add",
968 "write-tree",
969 "commit-tree",
970 "update-ref",
971 ]);
972 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "unstaged\n");
973 const [, ...parents] = (yield* git([
974 "rev-list",
975 "--parents",
976 "-n",
977 "1",
978 checkpointRef,
979 ])).stdout
980 .trim()
981 .split(" ");
982 assert.deepStrictEqual(
983 parents,
984 head === "committed" ? [(yield* git(["rev-parse", "HEAD"])).stdout.trim()] : [],
985 );
986 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
987);
988
989it.effect("checkpoint capture outside a repository fails with the common dir lookup error", () =>
990 Effect.gen(function* () {
991 const fileSystem = yield* FileSystem.FileSystem;
992 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-no-repo-" });
993
994 const error = yield* captureRecordingGitCommands(
995 cwd,
996 CheckpointRef.make("refs/t3/checkpoints/test"),
997 ).pipe(Effect.flip);
998
999 assert.instanceOf(error, VcsProcessExitError);
1000 assert.strictEqual(error.operation, "GitVcsDriver.checkpoints.resolveGitCommonDir");
1001 assert.strictEqual(error.exitCode, 128);
1002 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
1003);
1004
1005it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
1006 "checkpoint capture handles a repository path containing a newline",
1007 () =>
1008 Effect.gen(function* () {
1009 const fileSystem = yield* FileSystem.FileSystem;
1010 const path = yield* Path.Path;
1011 const driver = yield* GitVcsDriver.makeVcsDriverShape();
1012 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-new\nline-" });
1013 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
1014 const originalIndex = yield* fileSystem.readFile(path.join(cwd, ".git", "index"));
1015
1016 const commands = yield* captureRecordingGitCommands(cwd, checkpointRef);
1017
1018 assert.deepStrictEqual(commands, [
1019 "rev-parse",
1020 "rev-parse",
1021 "config",
1022 "rev-parse",
1023 "read-tree",
1024 "ls-files",
1025 "check-ignore",
1026 "add",
1027 "write-tree",
1028 "commit-tree",
1029 "update-ref",
1030 ]);
1031 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "unstaged\n");
1032 assert.deepEqual(yield* fileSystem.readFile(path.join(cwd, ".git", "index")), originalIndex);
1033 assert.deepStrictEqual(
1034 (yield* fileSystem.readDirectory(path.join(cwd, ".git"))).filter((name) =>
1035 name.startsWith("t3-checkpoint-index-"),
1036 ),
1037 [],
1038 );
1039 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
1040);
1041
1042it.effect("restores empty checkpoints without changing paths outside the workspace", () =>
1043 Effect.gen(function* () {
1044 const fileSystem = yield* FileSystem.FileSystem;
1045 const path = yield* Path.Path;
1046 const driver = yield* GitVcsDriver.makeVcsDriverShape();
1047 for (const nested of [false, true]) {
1048 const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-empty-checkpoint-" });
1049 yield* runGit(root, ["init"]);
1050 yield* runGit(root, ["config", "user.email", "test@test.com"]);
1051 yield* runGit(root, ["config", "user.name", "Test"]);
1052 if (nested) {
1053 yield* fileSystem.writeFileString(path.join(root, "outside.txt"), "original\n");
1054 yield* runGit(root, ["add", "."]);
1055 }
1056 yield* runGit(root, ["commit", "--allow-empty", "-m", "initial"]);
1057 const cwd = nested ? path.join(root, "nested") : root;
1058 yield* fileSystem.makeDirectory(cwd, { recursive: true });
1059 const checkpointRef = CheckpointRef.make("refs/t3/checkpoints/empty");
1060 yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
1061 if (nested) {
1062 yield* fileSystem.writeFileString(path.join(root, "outside.txt"), "changed\n");
1063 yield* runGit(root, ["add", "outside.txt"]);
1064 }
1065 for (const staged of [false, true]) {
1066 const addedPath = path.join(cwd, "added.txt");
1067 yield* fileSystem.writeFileString(addedPath, "new\n");
1068 if (staged) yield* runGit(cwd, ["add", "added.txt"]);
1069 assert.isTrue(
1070 yield* driver.checkpoints.restoreCheckpoint({
1071 cwd,
1072 checkpointRef,
1073 fallbackToHead: false,
1074 }),
1075 );
1076 assert.isTrue(yield* fileSystem.exists(cwd));
1077 assert.isFalse(yield* fileSystem.exists(addedPath));
1078 }
1079 yield* fileSystem.writeFileString(
1080 path.join(root, ".git", "info", "exclude"),
1081 "ignored.txt\n",
1082 );
1083 yield* fileSystem.writeFileString(path.join(cwd, "ignored.txt"), "keep\n");
1084 yield* fileSystem.makeDirectory(path.join(cwd, "untracked"));
1085 yield* fileSystem.writeFileString(path.join(cwd, "untracked", "file.txt"), "remove\n");
1086 assert.isTrue(
1087 yield* driver.checkpoints.restoreCheckpoint({ cwd, checkpointRef, fallbackToHead: false }),
1088 );
1089 assert.strictEqual(yield* fileSystem.readFileString(path.join(cwd, "ignored.txt")), "keep\n");
1090 assert.isFalse(yield* fileSystem.exists(path.join(cwd, "untracked")));
1091 if (nested) {
1092 assert.strictEqual(
1093 yield* fileSystem.readFileString(path.join(root, "outside.txt")),
1094 "changed\n",
1095 );
1096 const staged = yield* driver.execute({
1097 operation: "test",
1098 cwd: root,
1099 args: ["diff", "--cached", "--name-only"],
1100 });
1101 assert.strictEqual(staged.stdout.trim(), "outside.txt");
1102 }
1103 }
1104 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
1105);
1106
1107// The real VCS process, spawning `command` wherever the driver runs git.
1108const vcsProcessSpawning = (command: string) =>
1109 Layer.effect(
1110 VcsProcess.VcsProcess,
1111 Effect.map(VcsProcess.make, (vcsProcess) =>
1112 VcsProcess.VcsProcess.of({ run: (input) => vcsProcess.run({ ...input, command }) }),
1113 ),
1114 ).pipe(
1115 Layer.provide(ProcessRunner.layer),
1116 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
1117 );
1118
1119it.effect("GitVcsDriver treats a missing git executable as outside any repository", () =>
1120 Effect.gen(function* () {
1121 const fileSystem = yield* FileSystem.FileSystem;
1122 const path = yield* Path.Path;
1123 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-missing-git-" });
1124 const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
1125 Effect.provide(vcsProcessSpawning(path.join(cwd, "git"))),
1126 );
1127
1128 assert.strictEqual(yield* driver.isInsideWorkTree(cwd), false);
1129 assert.strictEqual(yield* driver.detectRepository(cwd), null);
1130 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
1131);
1132
1133it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
1134 "GitVcsDriver detects a repository whose path contains a newline",
1135 () =>
1136 Effect.gen(function* () {
1137 const fileSystem = yield* FileSystem.FileSystem;
1138 const path = yield* Path.Path;
1139 const parent = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-newline-repo-" });
1140 const cwd = path.join(parent, "multi\nline");
1141 yield* fileSystem.makeDirectory(cwd);
1142 yield* runGit(cwd, ["init"]);
1143 const driver = yield* GitVcsDriver.makeVcsDriverShape();
1144
1145 const repository = yield* driver.detectRepository(cwd);
1146 assert.strictEqual(repository?.rootPath, yield* fileSystem.realPath(cwd));
1147 assert.strictEqual(repository?.metadataPath, ".git");
1148 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
1149);
1150
1151it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
1152 "GitVcsDriver still fails detection when git exists but cannot be spawned",
1153 () =>
1154 Effect.gen(function* () {
1155 const fileSystem = yield* FileSystem.FileSystem;
1156 // A file without the execute bit fails to spawn with a permission error.
1157 const notExecutable = yield* fileSystem.makeTempFileScoped({ prefix: "t3-git-" });
1158 const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
1159 Effect.provide(vcsProcessSpawning(notExecutable)),
1160 );
1161
1162 const error = yield* driver.isInsideWorkTree(process.cwd()).pipe(Effect.flip);
1163 assert.strictEqual(error._tag, "VcsProcessSpawnError");
1164 const detectionError = yield* driver.detectRepository(process.cwd()).pipe(Effect.flip);
1165 assert.strictEqual(detectionError._tag, "VcsProcessSpawnError");
1166 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
1167);
1168
1169const gitCommandCount = (operation: string, outcome: string) =>
1170 Metric.value(
1171 Metric.withAttributes(gitCommandsTotal, [
1172 ["operation", operation],
1173 ["outcome", outcome],
1174 ]),
1175 ).pipe(Effect.map((state) => state.count));
1176
1177const gitCommandTiming = (operation: string) =>
1178 Metric.value(Metric.withAttributes(gitCommandDuration, [["operation", operation]]));
1179
1180// Keep VcsProcess's exit classification; replace only the subprocess and its clock.
1181const makeMeteredDriver = Effect.fn("test.makeMeteredDriver")(function* (exitCode: number) {
1182 const process = yield* VcsProcess.make.pipe(
1183 Effect.provideService(ProcessRunner.ProcessRunner, {
1184 run: () =>
1185 TestClock.adjust("250 millis").pipe(
1186 Effect.as({
1187 code: ChildProcessSpawner.ExitCode(exitCode),
1188 stdout: "git output",
1189 stderr: exitCode === 0 ? "" : "fatal: test failure",
1190 timedOut: false,
1191 stdoutTruncated: false,
1192 stderrTruncated: false,
1193 stdoutInvalidUtf8: false,
1194 stderrInvalidUtf8: false,
1195 }),
1196 ),
1197 }),
1198 );
1199 return yield* GitVcsDriver.makeVcsDriverShape().pipe(
1200 Effect.provideService(VcsProcess.VcsProcess, process),
1201 );
1202});
1203
1204it.effect("GitVcsDriver meters each git command once under its operation", () =>
1205 Effect.gen(function* () {
1206 const operation = "GitVcsDriver.checkpoints.resolveHeadCommit";
1207 const driver = yield* makeMeteredDriver(0);
1208
1209 const result = yield* driver.execute({ operation, cwd: "/repo", args: ["rev-parse", "HEAD"] });
1210 yield* driver.execute({ operation, cwd: "/another-repo", args: ["rev-parse", "other-ref"] });
1211
1212 assert.strictEqual(result.stdout, "git output");
1213 assert.strictEqual(yield* gitCommandCount(operation, "success"), 2);
1214 assert.strictEqual(yield* gitCommandCount(operation, "failure"), 0);
1215 const timing = yield* gitCommandTiming(operation);
1216 assert.strictEqual(timing.count, 2);
1217 assert.strictEqual(timing.sum, 500);
1218 }).pipe(
1219 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
1220 Effect.provideService(Metric.MetricRegistry, new Map()),
1221 ),
1222);
1223
1224it.effect("GitVcsDriver counts an allowed non-zero exit as a success", () =>
1225 Effect.gen(function* () {
1226 const operation = "GitVcsDriver.checkpoints.hasHeadCommit";
1227 const driver = yield* makeMeteredDriver(1);
1228
1229 const result = yield* driver.execute({
1230 operation,
1231 cwd: "/repo",
1232 args: ["rev-parse", "--verify", "HEAD"],
1233 allowNonZeroExit: true,
1234 });
1235
1236 assert.strictEqual(result.exitCode, 1);
1237 assert.strictEqual(yield* gitCommandCount(operation, "success"), 1);
1238 assert.strictEqual(yield* gitCommandCount(operation, "failure"), 0);
1239 const timing = yield* gitCommandTiming(operation);
1240 assert.strictEqual(timing.count, 1);
1241 assert.strictEqual(timing.sum, 250);
1242 }).pipe(
1243 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
1244 Effect.provideService(Metric.MetricRegistry, new Map()),
1245 ),
1246);
1247
1248it.effect("GitVcsDriver counts a failed git command as a failure", () =>
1249 Effect.gen(function* () {
1250 const operation = "GitVcsDriver.checkpoints.resolveHeadCommit";
1251 const driver = yield* makeMeteredDriver(128);
1252
1253 const error = yield* driver
1254 .execute({ operation, cwd: "/repo", args: ["rev-parse", "HEAD"] })
1255 .pipe(Effect.flip);
1256
1257 assert.strictEqual(error._tag, "VcsProcessExitError");
1258 assert.strictEqual(yield* gitCommandCount(operation, "failure"), 1);
1259 assert.strictEqual(yield* gitCommandCount(operation, "success"), 0);
1260 const timing = yield* gitCommandTiming(operation);
1261 assert.strictEqual(timing.count, 1);
1262 assert.strictEqual(timing.sum, 250);
1263 }).pipe(
1264 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
1265 Effect.provideService(Metric.MetricRegistry, new Map()),
1266 ),
1267);
1268
1269it.effect("checkpoint capture meters every git process it starts, including streamed ones", () =>
1270 Effect.gen(function* () {
1271 const fileSystem = yield* FileSystem.FileSystem;
1272 const liveProcess = yield* VcsProcess.VcsProcess;
1273 const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION;
1274 let started = 0;
1275 let streamed = 0;
1276 const driver = yield* GitVcsDriver.makeVcsDriverShape();
1277 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
1278 Effect.provideService(VcsProcess.VcsProcess, {
1279 run: (input) => {
1280 if (input.operation === operation) {
1281 started++;
1282 if (input.onStdoutChunk !== undefined) streamed++;
1283 }
1284 return liveProcess.run(input);
1285 },
1286 }),
1287 );
1288 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-metrics-" });
1289 const { checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
1290
1291 yield* captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
1292
1293 assert.isAbove(streamed, 0);
1294 assert.strictEqual(yield* gitCommandCount(operation, "success"), started);
1295 assert.strictEqual(yield* gitCommandCount(operation, "failure"), 0);
1296 assert.strictEqual((yield* gitCommandTiming(operation)).count, started);
1297 }).pipe(
1298 Effect.scoped,
1299 Effect.provide(layerGitContract),
1300 Effect.provideService(Metric.MetricRegistry, new Map()),
1301 ),
1302);
1303
1304it.effect("git metrics finalize cancellation without exposing arbitrary operation labels", () =>
1305 Effect.gen(function* () {
1306 const started = yield* Deferred.make<void>();
1307 const process = yield* VcsProcess.make.pipe(
1308 Effect.provideService(ProcessRunner.ProcessRunner, {
1309 run: () => Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never)),
1310 }),
1311 );
1312 const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
1313 Effect.provideService(VcsProcess.VcsProcess, process),
1314 );
1315 const operation = "arbitrary operation /private/path";
1316 const fiber = yield* driver
1317 .execute({ operation, cwd: "/repo", args: ["rev-parse", "HEAD"] })
1318 .pipe(Effect.forkChild);
1319 yield* Deferred.await(started);
1320 yield* TestClock.adjust("250 millis");
1321 yield* Fiber.interrupt(fiber);
1322
1323 assert.strictEqual(yield* gitCommandCount("other", "interrupt"), 1);
1324 assert.strictEqual(yield* gitCommandCount(operation, "interrupt"), 0);
1325 const timing = yield* gitCommandTiming("other");
1326 assert.strictEqual(timing.count, 1);
1327 assert.strictEqual(timing.sum, 250);
1328 }).pipe(
1329 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
1330 Effect.provideService(Metric.MetricRegistry, new Map()),
1331 ),
1332);
1333
1334it.effect("git metrics count fsync fallback and transient retry subprocesses separately", () =>
1335 Effect.gen(function* () {
1336 const retryReady = yield* Deferred.make<void>();
1337 const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION;
1338 let attempts = 0;
1339 const process = yield* VcsProcess.make.pipe(
1340 Effect.provideService(HostProcess.Platform, "darwin"),
1341 Effect.provideService(ProcessRunner.ProcessRunner, {
1342 run: (input) =>
1343 Effect.gen(function* () {
1344 attempts++;
1345 yield* TestClock.adjust("250 millis");
1346 if (attempts === 2) {
1347 assert.include(input.args, "core.fsyncMethod=writeout-only");
1348 yield* Deferred.succeed(retryReady, undefined);
1349 }
1350 return {
1351 code: ChildProcessSpawner.ExitCode(attempts < 3 ? 128 : 0),
1352 stdout: "",
1353 stderr:
1354 attempts === 1
1355 ? "fatal: fsync error on '.git/objects/test': Operation not supported"
1356 : attempts === 2
1357 ? "fatal: Unable to create '/repo/.git/index.lock': File exists."
1358 : "",
1359 timedOut: false,
1360 stdoutTruncated: false,
1361 stderrTruncated: false,
1362 stdoutInvalidUtf8: false,
1363 stderrInvalidUtf8: false,
1364 };
1365 }),
1366 }),
1367 );
1368 const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
1369 Effect.provideService(VcsProcess.VcsProcess, process),
1370 );
1371 const fiber = yield* driver
1372 .execute({ operation, cwd: "/repo", args: ["-c", "core.fsyncMethod=batch", "add"] })
1373 .pipe(Effect.forkChild);
1374 yield* Deferred.await(retryReady);
1375 yield* TestClock.adjust("75 millis");
1376 yield* Fiber.join(fiber);
1377
1378 assert.strictEqual(attempts, 3);
1379 assert.strictEqual(yield* gitCommandCount(operation, "failure"), 2);
1380 assert.strictEqual(yield* gitCommandCount(operation, "success"), 1);
1381 const timing = yield* gitCommandTiming(operation);
1382 assert.strictEqual(timing.count, 3);
1383 assert.strictEqual(timing.sum, 750);
1384 }).pipe(
1385 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
1386 Effect.provideService(Metric.MetricRegistry, new Map()),
1387 ),
1388);