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

GitVcsDriver.test.ts

1,118 lines49.3 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import * as Cause from "effect/Cause";
3import * as Clock from "effect/Clock";
4import * as Duration from "effect/Duration";
5import * as Exit from "effect/Exit";
6import * as Deferred from "effect/Deferred";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as TestClock from "effect/testing/TestClock";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Path from "effect/Path";
13import * as PlatformError from "effect/PlatformError";
14import { ChildProcessSpawner } from "effect/unstable/process";
15import { assert, it } from "@effect/vitest";
16​
17import { CheckpointRef, GitCommandError, VcsProcessExitError } from "@t3tools/contracts";
18import * as ServerConfig from "../config.ts";
19import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
20import * as ProcessRunner from "../processRunner.ts";
21import * as GitVcsDriver from "./GitVcsDriver.ts";
22import type * as VcsDriver from "./VcsDriver.ts";
23import * as VcsDriverRegistry from "./VcsDriverRegistry.ts";
24import * as VcsProcess from "./VcsProcess.ts";
25import { runVcsDriverContractSuite } from "./testing/VcsDriverContractHarness.ts";
26​
27const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
28 prefix: "t3-git-vcs-contract-",
29});
30const GitContractLayer = Layer.mergeAll(GitVcsDriver.vcsLayer, GitVcsDriver.layer).pipe(
31 Layer.provide(ServerConfigLayer),
32 Layer.provideMerge(VcsProcess.layer),
33 Layer.provideMerge(NodeServices.layer),
34);
35const GitCaptureContractLayer = Layer.merge(
36 GitContractLayer,
37 ProcessRunner.layer.pipe(Layer.provide(NodeServices.layer)),
38);
39​
40const runGit = (cwd: string, args: ReadonlyArray<string>) =>
41 Effect.gen(function* () {
42 const driver = yield* GitVcsDriver.GitVcsDriver;
43 yield* driver.execute({
44 operation: "GitVcsDriver.contract.git",
45 cwd,
46 args,
47 timeoutMs: 10_000,
48 });
49 });
50​
51const makeCaptureStore = Effect.fn("test.makeCaptureStore")(function* (
52 driver: VcsDriver.VcsDriver["Service"],
53 cwd: string,
54) {
55 const repository = yield* driver.detectRepository(cwd);
56 if (repository === null) return yield* Effect.die("Expected a test Git repository");
57 const handle = { kind: repository.kind, repository, driver };
58 return yield* CheckpointStore.make.pipe(
59 Effect.provideService(VcsDriverRegistry.VcsDriverRegistry, {
60 get: () => Effect.succeed(driver),
61 detect: () => Effect.succeed(handle),
62 resolve: () => Effect.succeed(handle),
63 }),
64 );
65});
66​
67type GitContractError = GitCommandError | PlatformError.PlatformError;
68​
69runVcsDriverContractSuite<GitVcsDriver.GitVcsDriver, GitContractError>({
70 name: "Git",
71 kind: "git",
72 layer: GitContractLayer,
73 fixture: {
74 createRepo: (cwd) =>
75 Effect.gen(function* () {
76 yield* runGit(cwd, ["init"]);
77 yield* runGit(cwd, ["config", "user.email", "test@test.com"]);
78 yield* runGit(cwd, ["config", "user.name", "Test"]);
79 }),
80 writeFile: (cwd, relativePath, contents) =>
81 Effect.gen(function* () {
82 const fileSystem = yield* FileSystem.FileSystem;
83 const path = yield* Path.Path;
84 const absolutePath = path.join(cwd, relativePath);
85 yield* fileSystem.makeDirectory(path.dirname(absolutePath), { recursive: true });
86 yield* fileSystem.writeFileString(absolutePath, contents);
87 }),
88 trackFile: (cwd, relativePath) => runGit(cwd, ["add", relativePath]),
89 commit: (cwd, message) => runGit(cwd, ["commit", "-m", message]),
90 ignorePath: (cwd, pattern) =>
91 Effect.gen(function* () {
92 const fileSystem = yield* FileSystem.FileSystem;
93 const path = yield* Path.Path;
94 yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), `${pattern}\n`);
95 }),
96 },
97});
98​
99const makeCheckpointFixture = Effect.fn("makeCheckpointFixture")(function* (
100 driver: Effect.Success<ReturnType<typeof GitVcsDriver.makeVcsDriverShape>>,
101 cwd: string,
102) {
103 const fileSystem = yield* FileSystem.FileSystem;
104 const path = yield* Path.Path;
105 const git = (args: ReadonlyArray<string>) =>
106 driver.execute({ operation: "checkpoint-test", cwd, args });
107 yield* git(["init"]);
108 yield* git(["config", "user.name", "Test"]);
109 yield* git(["config", "user.email", "test@test.com"]);
110 yield* fileSystem.writeFileString(path.join(cwd, "file.txt"), "initial\n");
111 yield* git(["add", "."]);
112 yield* git(["commit", "-m", "initial"]);
113 const checkpointRef = CheckpointRef.make("refs/t3/checkpoints/test");
114 yield* fileSystem.writeFileString(path.join(cwd, "file.txt"), "staged\n");
115 yield* git(["add", "."]);
116 yield* fileSystem.writeFileString(path.join(cwd, "file.txt"), "unstaged\n");
117 return { git, checkpointRef };
118});
119​
120it.effect("checkpoint capture skips untracked nested repositories without a commit", () =>
121 Effect.gen(function* () {
122 const fileSystem = yield* FileSystem.FileSystem;
123 const path = yield* Path.Path;
124 const driver = yield* GitVcsDriver.makeVcsDriverShape();
125 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-unborn-" });
126 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
127 const nested = "scratch/empty [repo]";
128 yield* git(["init", nested]);
129 yield* git(["init", "another empty"]);
130 yield* fileSystem.writeFileString(path.join(cwd, nested, "private.txt"), "nested\n");
131 yield* git(["init", "committed"]);
132 yield* git([
133 "-C",
134 "committed",
135 "-c",
136 "user.name=Test",
137 "-c",
138 "user.email=test@test.com",
139 "commit",
140 "--allow-empty",
141 "-m",
142 "initial",
143 ]);
144 const nestedHead = (yield* git(["-C", "committed", "rev-parse", "HEAD"])).stdout.trim();
145 yield* fileSystem.writeFileString(path.join(cwd, "untracked.txt"), "new\n");
146 const originalIndex = yield* fileSystem.readFile(path.join(cwd, ".git", "index"));
147​
148 yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
149​
150 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "unstaged\n");
151 assert.strictEqual((yield* git(["show", `${checkpointRef}:untracked.txt`])).stdout, "new\n");
152 assert.strictEqual((yield* git(["ls-tree", "-r", checkpointRef, "--", nested])).stdout, "");
153 assert.strictEqual((yield* git(["ls-tree", checkpointRef, "--", "another empty"])).stdout, "");
154 assert.strictEqual(
155 (yield* git(["ls-tree", checkpointRef, "--", "committed"])).stdout,
156 `160000 commit ${nestedHead}\tcommitted\n`,
157 );
158 assert.deepEqual(yield* fileSystem.readFile(path.join(cwd, ".git", "index")), originalIndex);
159 assert.strictEqual(
160 yield* fileSystem.readFileString(path.join(cwd, nested, "private.txt")),
161 "nested\n",
162 );
163 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
164);
165​
166it.effect("checkpoint recovery discovers nested HEAD independently of inherited GIT_DIR", () =>
167 Effect.gen(function* () {
168 const fs = yield* FileSystem.FileSystem;
169 const path = yield* Path.Path;
170 const driver = yield* GitVcsDriver.makeVcsDriverShape();
171 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-git-dir-" });
172 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
173 yield* git(["init", "empty"]);
174 const originalIndex = yield* fs.readFile(path.join(cwd, ".git", "index"));
175 yield* Effect.acquireUseRelease(
176 Effect.sync(() => {
177 const previous = process.env.GIT_DIR;
178 process.env.GIT_DIR = path.join(cwd, ".git");
179 return previous;
180 }),
181 () => driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }),
182 (previous) =>
183 Effect.sync(() => {
184 if (previous === undefined) delete process.env.GIT_DIR;
185 else process.env.GIT_DIR = previous;
186 }),
187 );
188 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "unstaged\n");
189 assert.strictEqual((yield* git(["ls-tree", "-r", checkpointRef, "--", "empty"])).stdout, "");
190 assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git", "index")), originalIndex);
191 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
192);
193​
194it.effect("checkpoint capture still fails when a clean filter rejects a file", () =>
195 Effect.gen(function* () {
196 const fileSystem = yield* FileSystem.FileSystem;
197 const path = yield* Path.Path;
198 const driver = yield* GitVcsDriver.makeVcsDriverShape();
199 const cwd = yield* fileSystem.makeTempDirectoryScoped({
200 prefix: "t3-checkpoint-filter-failure-",
201 });
202 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
203 yield* fileSystem.writeFileString(path.join(cwd, ".gitattributes"), "file.txt filter=reject\n");
204 yield* git(["config", "filter.reject.clean", "false"]);
205 yield* git(["config", "filter.reject.required", "true"]);
206 const originalIndex = yield* fileSystem.readFile(path.join(cwd, ".git", "index"));
207​
208 const result = yield* Effect.result(
209 driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }),
210 );
211​
212 assert.strictEqual(result._tag, "Failure");
213 assert.deepEqual(yield* fileSystem.readFile(path.join(cwd, ".git", "index")), originalIndex);
214 assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }));
215 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
216);
217​
218it.effect("checkpoint capture refuses a truncated nested repository listing", () =>
219 Effect.gen(function* () {
220 const fs = yield* FileSystem.FileSystem;
221 const liveProcess = yield* VcsProcess.VcsProcess;
222 const driver = yield* GitVcsDriver.makeVcsDriverShape();
223 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-truncated-" });
224 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
225 yield* git(["init", "empty"]);
226 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
227 Effect.provideService(VcsProcess.VcsProcess, {
228 run: (input) =>
229 liveProcess
230 .run(input)
231 .pipe(
232 Effect.map((result) =>
233 input.args.includes("--others") ? { ...result, stdoutTruncated: true } : result,
234 ),
235 ),
236 }),
237 );
238​
239 const result = yield* Effect.result(
240 captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef }),
241 );
242​
243 assert.strictEqual(result._tag, "Failure");
244 assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }));
245 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
246);
247​
248it.effect("checkpoint recovery refuses excessive candidates before probing", () =>
249 Effect.gen(function* () {
250 const fs = yield* FileSystem.FileSystem;
251 const path = yield* Path.Path;
252 const liveProcess = yield* VcsProcess.VcsProcess;
253 const driver = yield* GitVcsDriver.makeVcsDriverShape();
254 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-recovery-cap-" });
255 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
256 yield* git(["init", "empty0"]);
257 for (let i = 1; i < 65; i++)
258 yield* fs.copy(path.join(cwd, "empty0"), path.join(cwd, `empty${i}`));
259 const originalIndex = yield* fs.readFile(path.join(cwd, ".git", "index"));
260 let stageError: VcsProcessExitError | undefined;
261 let nestedProbes = 0;
262 let stageAttempts = 0;
263 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
264 Effect.provideService(VcsProcess.VcsProcess, {
265 run: (input) => {
266 if (input.cwd !== cwd && input.args.includes("rev-parse")) nestedProbes++;
267 if (input.args.includes("add") && input.args.includes("-A")) stageAttempts++;
268 return liveProcess.run(input).pipe(
269 Effect.tapError((error) => {
270 if (error._tag === "VcsProcessExitError") stageError = error;
271 return Effect.void;
272 }),
273 );
274 },
275 }),
276 );
277 const result = yield* Effect.result(
278 captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef }),
279 );
280 assert.strictEqual(nestedProbes, 0);
281 assert.strictEqual(stageAttempts, 1);
282 assert.strictEqual(result._tag, "Failure");
283 if (result._tag === "Failure") assert.strictEqual(result.failure, stageError);
284 assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }));
285 assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git", "index")), originalIndex);
286 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
287);
288​
289it.effect.each([
290 { phase: "add", nestedRecovery: false, expireRecovery: false },
291 { phase: "update-ref", nestedRecovery: false, expireRecovery: false },
292 { phase: "update-ref", nestedRecovery: true, expireRecovery: false },
293 { phase: "add", nestedRecovery: true, expireRecovery: false },
294 { phase: "add", nestedRecovery: true, expireRecovery: true },
295])(
296 "checkpoint handles a $phase lock with nestedRecovery=$nestedRecovery, expireRecovery=$expireRecovery",
297 ({ phase, nestedRecovery, expireRecovery }) =>
298 Effect.gen(function* () {
299 const fs = yield* FileSystem.FileSystem;
300 const path = yield* Path.Path;
301 const liveRunner = yield* ProcessRunner.ProcessRunner;
302 const driver = yield* GitVcsDriver.makeVcsDriverShape();
303 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-ref-race-" });
304 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
305 if (nestedRecovery) yield* git(["init", "empty"]);
306 const originalIndex = yield* fs.readFile(path.join(cwd, ".git", "index"));
307 const refLockPath = path.join(cwd, ".git", `${checkpointRef}.lock`);
308 const failed = yield* Deferred.make<void>();
309 const retryReached = yield* Deferred.make<void>();
310 const allowRetry = yield* Deferred.make<void>();
311 const clock = yield* Clock.Clock;
312 const privateIndexes = new Set<string>();
313 let racedAttempts = 0;
314 let discoveries = 0;
315 let stageError: VcsProcessExitError | undefined;
316 const captureProcess = yield* VcsProcess.make.pipe(
317 Effect.provideService(ProcessRunner.ProcessRunner, {
318 run: (input) => {
319 if (input.args.includes("--others")) discoveries += 1;
320 if (input.env?.GIT_INDEX_FILE) privateIndexes.add(input.env.GIT_INDEX_FILE);
321 const initialStage =
322 phase === "add" &&
323 nestedRecovery &&
324 !input.args.some((arg) => arg.startsWith(":(exclude,literal)"));
325 if (!input.args.includes(phase) || initialStage || ++racedAttempts !== 1) {
326 return liveRunner.run(input);
327 }
328 const lockPath = phase === "add" ? `${input.env!.GIT_INDEX_FILE!}.lock` : refLockPath;
329 return Effect.gen(function* () {
330 yield* fs
331 .makeDirectory(path.dirname(lockPath), { recursive: true })
332 .pipe(Effect.orDie);
333 yield* fs.writeFileString(lockPath, "concurrent ref writer").pipe(Effect.orDie);
334 return yield* liveRunner.run(input).pipe(
335 Effect.ensuring(fs.remove(lockPath).pipe(Effect.orDie)),
336 Effect.tap(() => Deferred.succeed(failed, undefined)),
337 );
338 });
339 },
340 }),
341 );
342 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
343 Effect.provideService(VcsProcess.VcsProcess, {
344 run: (input) =>
345 captureProcess.run(input).pipe(
346 Effect.tapError((error) => {
347 if (input.args.includes("add") && error._tag === "VcsProcessExitError")
348 stageError = error;
349 return Effect.void;
350 }),
351 ),
352 }),
353 );
354 const captureStore = yield* makeCaptureStore(captureDriver, cwd);
355 const fiber = yield* captureStore.captureCheckpoint({ cwd, checkpointRef }).pipe(
356 Effect.provideService(Clock.Clock, {
357 ...clock,
358 sleep: (duration) =>
359 Duration.toMillis(duration) === 75
360 ? Deferred.succeed(retryReached, undefined).pipe(
361 Effect.andThen(Deferred.await(allowRetry)),
362 )
363 : clock.sleep(duration),
364 }),
365 Effect.exit,
366 Effect.forkScoped,
367 );
368 yield* Deferred.await(failed);
369 yield* Deferred.await(retryReached);
370 if (expireRecovery) yield* TestClock.adjust("5 seconds");
371 else yield* Deferred.succeed(allowRetry, undefined);
372 const result = yield* Fiber.join(fiber);
373 if (expireRecovery) {
374 if (Exit.isSuccess(result))
375 return yield* Effect.die("Expected the recovery deadline to expire");
376 const error = Cause.findErrorOption(result.cause);
377 assert.isTrue(error._tag === "Some");
378 if (error._tag === "Some") assert.strictEqual(error.value, stageError);
379 } else assert.isTrue(Exit.isSuccess(result));
380 assert.strictEqual(racedAttempts, expireRecovery ? 1 : 2);
381 assert.strictEqual(discoveries, nestedRecovery ? 1 : 0);
382 assert.strictEqual(privateIndexes.size, 1);
383 assert.strictEqual(
384 yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }),
385 !expireRecovery,
386 );
387 for (const index of privateIndexes) {
388 assert.isFalse(yield* fs.exists(index));
389 assert.isFalse(yield* fs.exists(`${index}.lock`));
390 }
391 assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git", "index")), originalIndex);
392 }).pipe(Effect.scoped, Effect.provide(GitCaptureContractLayer)),
393);
394​
395for (const blockedPhase of ["discovery", "probe", "retry"] as const) {
396 it.effect(`checkpoint recovery has one deadline including ${blockedPhase}`, () =>
397 Effect.gen(function* () {
398 const fs = yield* FileSystem.FileSystem;
399 const path = yield* Path.Path;
400 const liveProcess = yield* VcsProcess.VcsProcess;
401 const driver = yield* GitVcsDriver.makeVcsDriverShape();
402 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-recovery-timeout-" });
403 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
404 yield* git(["init", "empty"]);
405 const originalIndex = yield* fs.readFile(path.join(cwd, ".git", "index"));
406 const entered = yield* Deferred.make<void>();
407 const discovered = yield* Deferred.make<void>();
408 let stageError: VcsProcessExitError | undefined;
409 let privateIndex: string | undefined;
410 let interrupted = false;
411 let stagingAttempts = 0;
412 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
413 Effect.provideService(VcsProcess.VcsProcess, {
414 run: (input) => {
415 const staging = input.args.includes("add") && input.args.includes("-A");
416 if (staging) {
417 privateIndex = input.env?.GIT_INDEX_FILE;
418 stagingAttempts += 1;
419 }
420 const block =
421 (blockedPhase === "discovery" && input.args.includes("--others")) ||
422 (blockedPhase === "probe" && input.cwd !== cwd && input.args.includes("rev-parse")) ||
423 (blockedPhase === "retry" &&
424 staging &&
425 input.args.some((arg) => arg.startsWith(":(exclude,literal)")));
426 if (block)
427 return (
428 blockedPhase === "retry"
429 ? fs
430 .writeFileString(
431 `${input.env!.GIT_INDEX_FILE!}.lock`,
432 "interrupted index write",
433 )
434 .pipe(Effect.orDie)
435 : Effect.void
436 ).pipe(
437 Effect.andThen(Deferred.succeed(entered, undefined)),
438 Effect.andThen(Effect.never),
439 Effect.onInterrupt(() =>
440 Effect.sync(() => {
441 interrupted = true;
442 }),
443 ),
444 );
445 return liveProcess.run(input).pipe(
446 Effect.tap(() =>
447 blockedPhase === "probe" && input.args.includes("--others")
448 ? Deferred.succeed(discovered, undefined).pipe(
449 Effect.andThen(Effect.sleep("3 seconds")),
450 )
451 : Effect.void,
452 ),
453 Effect.tapError((error) => {
454 if (staging && error._tag === "VcsProcessExitError") stageError = error;
455 return Effect.void;
456 }),
457 );
458 },
459 }),
460 );
461 const captureStore = yield* makeCaptureStore(captureDriver, cwd);
462 const fiber = yield* captureStore
463 .captureCheckpoint({ cwd, checkpointRef })
464 .pipe(Effect.flip, Effect.forkScoped);
465 if (blockedPhase === "probe") {
466 yield* Deferred.await(discovered);
467 yield* TestClock.adjust("3 seconds");
468 }
469 yield* Deferred.await(entered);
470 yield* TestClock.adjust(blockedPhase === "probe" ? "2 seconds" : "5 seconds");
471 const error = yield* Fiber.join(fiber);
472 assert.strictEqual(error, stageError);
473 assert.strictEqual(stagingAttempts, blockedPhase === "retry" ? 2 : 1);
474 assert.isTrue(interrupted);
475 assert.isDefined(privateIndex);
476 assert.isFalse(yield* fs.exists(privateIndex!));
477 assert.isFalse(yield* fs.exists(`${privateIndex!}.lock`));
478 assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }));
479 assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git", "index")), originalIndex);
480 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
481 );
483​
484it.effect("checkpoint recovery preserves interruption and removes the private index", () =>
485 Effect.gen(function* () {
486 const fs = yield* FileSystem.FileSystem;
487 const liveProcess = yield* VcsProcess.VcsProcess;
488 const driver = yield* GitVcsDriver.makeVcsDriverShape();
489 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-recovery-interrupt-" });
490 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
491 yield* git(["init", "empty"]);
492 const entered = yield* Deferred.make<void>();
493 let privateIndex: string | undefined;
494 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
495 Effect.provideService(VcsProcess.VcsProcess, {
496 run: (input) => {
497 if (input.args.includes("add") && input.args.includes("-A"))
498 privateIndex = input.env?.GIT_INDEX_FILE;
499 return input.args.includes("--others")
500 ? Deferred.succeed(entered, undefined).pipe(Effect.andThen(Effect.never))
501 : liveProcess.run(input);
502 },
503 }),
504 );
505 const fiber = yield* captureDriver.checkpoints
506 .captureCheckpoint({ cwd, checkpointRef })
507 .pipe(Effect.forkScoped);
508 yield* Deferred.await(entered);
509 yield* Fiber.interrupt(fiber);
510 const exit = yield* Fiber.await(fiber);
511 assert.isTrue(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause));
512 assert.isDefined(privateIndex);
513 assert.isFalse(yield* fs.exists(privateIndex!));
514 assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }));
515 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
516);
517​
518it.effect("checkpoint capture does not rerun clean filters for unchanged indexed files", () =>
519 Effect.gen(function* () {
520 const fileSystem = yield* FileSystem.FileSystem;
521 const path = yield* Path.Path;
522 const driver = yield* GitVcsDriver.makeVcsDriverShape();
523 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-cache-" });
524 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
525 yield* fileSystem.writeFileString(
526 path.join(cwd, ".gitattributes"),
527 "stable.txt filter=probe\n",
528 );
529 yield* fileSystem.writeFileString(path.join(cwd, "stable.txt"), "unchanged\n");
530 yield* fileSystem.writeFileString(
531 path.join(cwd, ".git", "filter.cjs"),
532 'require("node:fs").appendFileSync(".git/filter-runs", "read\\n"); process.stdin.pipe(process.stdout);',
533 );
534 yield* git(["config", "filter.probe.clean", "node .git/filter.cjs"]);
535 yield* fileSystem.utimes(path.join(cwd, "stable.txt"), 1_700_000_000, 1_700_000_000);
536 yield* git(["add", "."]);
537 yield* git(["commit", "-m", "record stable file"]);
538 yield* fileSystem.writeFileString(path.join(cwd, ".git", "filter-runs"), "");
539 yield* fileSystem.writeFileString(path.join(cwd, "file.txt"), "changed\n");
540 const originalIndex = yield* fileSystem.readFile(path.join(cwd, ".git", "index"));
541​
542 yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
543​
544 assert.strictEqual(yield* fileSystem.readFileString(path.join(cwd, ".git", "filter-runs")), "");
545 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "changed\n");
546 assert.strictEqual((yield* git(["show", `${checkpointRef}:stable.txt`])).stdout, "unchanged\n");
547 assert.deepEqual(yield* fileSystem.readFile(path.join(cwd, ".git", "index")), originalIndex);
548 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
549);
550​
551for (const nested of [false, true]) {
552 for (const indexState of [
553 "sparse",
554 "flags",
555 "manual-skip",
556 "missing",
557 "non-cone-missing",
558 ] as const) {
559 it.effect(
560 `sparse checkpoint preserves two captures (nested=${nested}, index=${indexState})`,
561 () =>
562 Effect.gen(function* () {
563 const fs = yield* FileSystem.FileSystem;
564 const path = yield* Path.Path;
565 const driver = yield* GitVcsDriver.makeVcsDriverShape();
566 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-sparse-" });
567 const { git } = yield* makeCheckpointFixture(driver, cwd);
568 const write = Effect.fn(function* (name: string, contents: string) {
569 yield* fs.makeDirectory(path.dirname(path.join(cwd, name)), { recursive: true });
570 yield* fs.writeFileString(path.join(cwd, name), contents);
571 });
572 for (const name of [
573 "scope/in/edit",
574 "scope/in/delete",
575 "scope/out/deep/absent",
576 "scope/out/present",
577 "elsewhere/file",
578 ]) {
579 yield* write(name, "original\n");
580 }
581 yield* git(["add", "."]);
582 yield* git(["commit", "-m", "sparse fixture"]);
583 yield* git([
584 "sparse-checkout",
585 "set",
586 "--cone",
587 "--sparse-index",
588 "scope/in",
589 "elsewhere",
590 ]);
591 if (indexState === "non-cone-missing")
592 yield* git(["sparse-checkout", "set", "--no-cone", "/scope/in/", "/elsewhere/"]);
593 yield* write("scope/in/edit", "staged\n");
594 yield* write("elsewhere/file", "staged outside\n");
595 yield* git(["add", "."]);
596 if (indexState === "flags")
597 yield* git(["update-index", "--assume-unchanged", "scope/in/delete"]);
598 if (indexState === "manual-skip")
599 yield* git(["update-index", "--skip-worktree", "scope/in/delete"]);
600 yield* git(["config", "sparse.expectFilesOutsideOfPatterns", "true"]);
601 yield* write("scope/in/edit", "working\n");
602 yield* write("scope/out/present", "modified skipped\n");
603 yield* write("scope/out/new file", "new outside cone\n");
604 yield* write("elsewhere/file", "working outside\n");
605 yield* fs.remove(path.join(cwd, "scope/in/delete"));
606 const indexPath = path.join(cwd, ".git/index");
607 if (indexState.endsWith("missing")) yield* fs.remove(indexPath);
608 const originalIndex = yield* fs
609 .readFile(indexPath)
610 .pipe(Effect.orElseSucceed(() => null));
611 const captureCwd = nested ? path.join(cwd, "scope") : cwd;
612 for (const turn of [1, 2]) {
613 const ref = CheckpointRef.make(`refs/t3/checkpoints/sparse/${turn}`);
614 if (turn === 2) {
615 yield* write("scope/in/edit", "second\n");
616 yield* fs.remove(path.join(cwd, "scope/out/new file"));
617 yield* write("scope/out/second", "second addition\n");
618 }
619 const capture = driver.checkpoints.captureCheckpoint({
620 cwd: captureCwd,
621 checkpointRef: ref,
622 });
623 if (indexState === "non-cone-missing") {
624 assert.strictEqual((yield* capture.pipe(Effect.flip))._tag, "VcsProcessExitError");
625 assert.isFalse(
626 yield* driver.checkpoints.hasCheckpointRef({ cwd: captureCwd, checkpointRef: ref }),
627 );
628 assert.isFalse(yield* fs.exists(indexPath));
629 break;
630 }
631 yield* capture;
632 for (const [name, content] of [
633 ["scope/out/deep/absent", "original\n"],
634 ["scope/out/present", "modified skipped\n"],
635 ["scope/in/edit", turn === 1 ? "working\n" : "second\n"],
636 ["elsewhere/file", nested ? "original\n" : "working outside\n"],
637 [
638 turn === 1 ? "scope/out/new file" : "scope/out/second",
639 turn === 1 ? "new outside cone\n" : "second addition\n",
640 ],
641 ]) {
642 assert.strictEqual((yield* git(["show", `${ref}:${name}`])).stdout, content);
643 }
644 const files = (yield* git(["ls-tree", "-rz", "--name-only", ref])).stdout.split("\0");
645 assert.notInclude(files, "scope/in/delete");
646 if (turn === 2) assert.notInclude(files, "scope/out/new file");
647 assert.deepEqual(
648 yield* fs.readFile(indexPath).pipe(Effect.orElseSucceed(() => null)),
649 originalIndex,
650 );
651 assert.isFalse(yield* fs.exists(path.join(cwd, "scope/out/deep/absent")));
652 assert.strictEqual(
653 yield* fs.readFileString(path.join(cwd, "elsewhere/file")),
654 "working outside\n",
655 );
656 }
657 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
658 );
659 }
661​
662it.effect("checkpoint capture keeps the legacy path when Git lacks add --sparse", () =>
663 Effect.gen(function* () {
664 const fs = yield* FileSystem.FileSystem;
665 const path = yield* Path.Path;
666 const liveProcess = yield* VcsProcess.VcsProcess;
667 const driver = yield* GitVcsDriver.makeVcsDriverShape();
668 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-legacy-" });
669 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
670 yield* git(["sparse-checkout", "set", "--cone", "included"]);
671 const originalIndex = yield* fs.readFile(path.join(cwd, ".git/index"));
672 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
673 Effect.provideService(VcsProcess.VcsProcess, {
674 run: (input) => {
675 if (input.args.includes("-h"))
676 return Effect.succeed({
677 exitCode: ChildProcessSpawner.ExitCode(129),
678 stdout: "usage: git add",
679 stderr: "",
680 stdoutTruncated: false,
681 stderrTruncated: false,
682 });
683 return liveProcess.run(
684 input.args.includes("--sparse")
685 ? {
686 ...input,
687 args: input.args.map((arg) =>
688 arg === "--sparse" ? "--unsupported-sparse" : arg,
689 ),
690 }
691 : input,
692 );
693 },
694 }),
695 );
696 yield* captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
697 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "unstaged\n");
698 assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git/index")), originalIndex);
699 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
700);
701​
702for (const indexMode of ["normal", "flags", "sparse"] as const) {
703 it.effect(
704 `checkpoint index inspection handles entries beyond the output cap (index=${indexMode})`,
705 () =>
706 Effect.gen(function* () {
707 const fs = yield* FileSystem.FileSystem;
708 const path = yield* Path.Path;
709 const liveProcess = yield* VcsProcess.VcsProcess;
710 const driver = yield* GitVcsDriver.makeVcsDriverShape();
711 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-inspection-" });
712 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
713 yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "stable filter=probe\n");
714 yield* fs.writeFileString(path.join(cwd, "stable"), "unchanged\n");
715 yield* fs.writeFileString(path.join(cwd, "z-skipped"), "original\n");
716 yield* fs.makeDirectory(path.join(cwd, "excluded"));
717 yield* fs.writeFileString(path.join(cwd, "excluded/file"), "absent\n");
718 yield* fs.writeFileString(
719 path.join(cwd, ".git/filter.cjs"),
720 'require("node:fs").appendFileSync(".git/reads", "read\\n"); process.stdin.pipe(process.stdout);',
721 );
722 yield* git(["config", "filter.probe.clean", "node .git/filter.cjs"]);
723 yield* fs.utimes(path.join(cwd, "stable"), 1_700_000_000, 1_700_000_000);
724 yield* git(["add", "."]);
725 yield* git(["commit", "-m", "inspection fixture"]);
726 if (indexMode === "flags") yield* git(["update-index", "--skip-worktree", "z-skipped"]);
727 if (indexMode === "sparse")
728 yield* git(["sparse-checkout", "set", "--cone", "--sparse-index", "included"]);
729 yield* fs.writeFileString(path.join(cwd, "z-skipped"), "modified\n");
730 yield* fs.writeFileString(path.join(cwd, ".git/reads"), "");
731 const originalIndex = yield* fs.readFile(path.join(cwd, ".git/index"));
732 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
733 Effect.provideService(VcsProcess.VcsProcess, {
734 run: (input) =>
735 liveProcess.run(
736 input.args.includes("ls-files")
737 ? {
738 ...input,
739 maxOutputBytes: 8,
740 onStdoutChunk: (chunk) => {
741 for (let i = 0; i < chunk.length; i++)
742 input.onStdoutChunk?.(chunk.subarray(i, i + 1));
743 },
744 }
745 : input,
746 ),
747 }),
748 );
749 yield* captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
750 assert.strictEqual(
751 (yield* git(["show", `${checkpointRef}:z-skipped`])).stdout,
752 "modified\n",
753 );
754 if (indexMode !== "flags")
755 assert.strictEqual(yield* fs.readFileString(path.join(cwd, ".git/reads")), "");
756 assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git/index")), originalIndex);
757 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
758 );
760​
761for (const timestamp of [1_700_000_000, 1_700_000_000.9999]) {
762 it.effect(
763 `checkpoint capture preserves same-size edits with racy index timestamps (${timestamp})`,
764 () =>
765 Effect.gen(function* () {
766 const fileSystem = yield* FileSystem.FileSystem;
767 const path = yield* Path.Path;
768 const driver = yield* GitVcsDriver.makeVcsDriverShape();
769 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-racy-" });
770 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
771 const filePath = path.join(cwd, "file.txt");
772 const indexPath = path.join(cwd, ".git", "index");
773 yield* git(["config", "core.trustctime", "false"]);
774 yield* fileSystem.writeFileString(filePath, "before\n");
775 yield* fileSystem.utimes(filePath, timestamp, timestamp);
776 yield* git(["add", "file.txt"]);
777 yield* git(["commit", "-m", "record racy file"]);
778 yield* fileSystem.utimes(indexPath, timestamp, timestamp);
779 const originalIndex = yield* fileSystem.readFile(indexPath);
780 const originalIndexMtime = (yield* fileSystem.stat(indexPath)).mtime;
781 yield* fileSystem.writeFileString(filePath, "after!\n");
782 yield* fileSystem.utimes(filePath, timestamp, timestamp);
783​
784 yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
785​
786 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "after!\n");
787 assert.deepEqual(yield* fileSystem.readFile(indexPath), originalIndex);
788 assert.deepEqual((yield* fileSystem.stat(indexPath)).mtime, originalIndexMtime);
789 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
790 );
792​
793it.effect("checkpoint capture preserves racy edits made after resetting the index", () =>
794 Effect.gen(function* () {
795 const fileSystem = yield* FileSystem.FileSystem;
796 const path = yield* Path.Path;
797 const liveProcess = yield* VcsProcess.VcsProcess;
798 const driver = yield* GitVcsDriver.makeVcsDriverShape();
799 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-racy-reset-" });
800 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
801 const racyPath = path.join(cwd, "racy.txt");
802 const indexPath = path.join(cwd, ".git", "index");
803 const timestamp = 1_700_000_000;
804 yield* git(["config", "core.trustctime", "false"]);
805 yield* fileSystem.writeFileString(racyPath, "before\n");
806 yield* fileSystem.utimes(racyPath, timestamp, timestamp);
807 yield* git(["add", "."]);
808 yield* git(["commit", "-m", "record racy file"]);
809 yield* fileSystem.writeFileString(path.join(cwd, "file.txt"), "staged\n");
810 yield* git(["add", "file.txt"]);
811 yield* fileSystem.utimes(indexPath, timestamp, timestamp);
812 const originalIndex = yield* fileSystem.readFile(indexPath);
813 const originalIndexMtime = (yield* fileSystem.stat(indexPath)).mtime;
814 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
815 Effect.provideService(VcsProcess.VcsProcess, {
816 run: Effect.fn(function* (input: VcsProcess.VcsProcessInput) {
817 const result = yield* liveProcess.run(input);
818 if (input.args.includes("read-tree") && input.args.includes("--reset")) {
819 yield* fileSystem.writeFileString(racyPath, "after!\n").pipe(Effect.orDie);
820 yield* fileSystem.utimes(racyPath, timestamp, timestamp).pipe(Effect.orDie);
821 }
822 return result;
823 }),
824 }),
825 );
826​
827 yield* captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
828​
829 assert.strictEqual((yield* git(["show", `${checkpointRef}:racy.txt`])).stdout, "after!\n");
830 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "staged\n");
831 assert.deepEqual(yield* fileSystem.readFile(indexPath), originalIndex);
832 assert.deepEqual((yield* fileSystem.stat(indexPath)).mtime, originalIndexMtime);
833 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
834);
835​
836for (const nested of [false, true]) {
837 for (const indexMode of ["normal", "flags", "split"] as const) {
838 it.effect(
839 `checkpoint index reuse preserves two turns (nested=${nested}, index=${indexMode})`,
840 () =>
841 Effect.gen(function* () {
842 const fileSystem = yield* FileSystem.FileSystem;
843 const path = yield* Path.Path;
844 const driver = yield* GitVcsDriver.makeVcsDriverShape();
845 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-turns-" });
846 const { git } = yield* makeCheckpointFixture(driver, cwd);
847 const write = (name: string, contents: string) =>
848 fileSystem.writeFileString(path.join(cwd, name), contents);
849 yield* fileSystem.makeDirectory(path.join(cwd, "scope"));
850 for (const name of [
851 "scope/staged",
852 "scope/deleted",
853 "scope/assumed",
854 "scope/skipped",
855 "outside",
856 ]) {
857 yield* write(name, "original\n");
858 }
859 yield* git(["add", "."]);
860 yield* git(["commit", "-m", "initial scoped files"]);
861 yield* write("scope/staged", "staged\n");
862 yield* write("scope/new-deleted", "staged then deleted\n");
863 yield* write("outside", "staged outside\n");
864 yield* git(["add", "."]);
865 if (indexMode === "flags") {
866 yield* git(["update-index", "--assume-unchanged", "scope/assumed"]);
867 yield* git(["update-index", "--skip-worktree", "scope/skipped"]);
868 }
869 if (indexMode === "split") {
870 yield* git(["update-index", "--split-index"]);
871 }
872 const originalIndex = yield* fileSystem.readFile(path.join(cwd, ".git", "index"));
873 for (const name of ["scope/staged", "scope/assumed", "scope/skipped", "outside"]) {
874 yield* write(name, "working\n");
875 }
876 yield* write("scope/new", "first\n");
877 yield* fileSystem.remove(path.join(cwd, "scope/deleted"));
878 yield* fileSystem.remove(path.join(cwd, "scope/new-deleted"));
879 const captureCwd = nested ? path.join(cwd, "scope") : cwd;
880 const first = CheckpointRef.make("refs/t3/checkpoints/turns/1");
881 const second = CheckpointRef.make("refs/t3/checkpoints/turns/2");
882 yield* driver.checkpoints.captureCheckpoint({ cwd: captureCwd, checkpointRef: first });
883 for (const name of ["scope/staged", "scope/assumed", "scope/skipped"]) {
884 assert.strictEqual((yield* git(["show", `${first}:${name}`])).stdout, "working\n");
885 }
886 assert.strictEqual(
887 (yield* git(["show", `${first}:outside`])).stdout,
888 nested ? "original\n" : "working\n",
889 );
890 const files = (yield* git(["ls-tree", "-r", "--name-only", first])).stdout.split("\n");
891 assert.notInclude(files, "scope/deleted");
892 assert.notInclude(files, "scope/new-deleted");
893 assert.include(files, "scope/new");
894​
895 yield* write("scope/staged", "second\n");
896 yield* fileSystem.remove(path.join(cwd, "scope/new"));
897 yield* write("scope/second", "added in second turn\n");
898 yield* driver.checkpoints.captureCheckpoint({ cwd: captureCwd, checkpointRef: second });
899 assert.strictEqual(
900 (yield* git(["diff", "--name-only", first, second])).stdout,
901 "scope/new\nscope/second\nscope/staged\n",
902 );
903 assert.strictEqual((yield* git(["show", `${second}:scope/staged`])).stdout, "second\n");
904 assert.strictEqual(
905 (yield* git(["show", `${second}:scope/second`])).stdout,
906 "added in second turn\n",
907 );
908 assert.deepEqual(
909 yield* fileSystem.readFile(path.join(cwd, ".git", "index")),
910 originalIndex,
911 );
912 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
913 );
914 }
916​
917for (const indexState of ["missing", "invalid"] as const) {
918 it.effect(`checkpoint capture falls back when the user index is ${indexState}`, () =>
919 Effect.gen(function* () {
920 const fileSystem = yield* FileSystem.FileSystem;
921 const path = yield* Path.Path;
922 const driver = yield* GitVcsDriver.makeVcsDriverShape();
923 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-index-" });
924 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
925 const indexPath = path.join(cwd, ".git", "index");
926 if (indexState === "missing") {
927 yield* fileSystem.remove(indexPath);
928 } else {
929 yield* fileSystem.writeFileString(indexPath, "invalid index");
930 }
931​
932 yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
933​
934 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "unstaged\n");
935 if (indexState === "missing") {
936 assert.isFalse(yield* fileSystem.exists(indexPath));
937 } else {
938 assert.strictEqual(yield* fileSystem.readFileString(indexPath), "invalid index");
939 }
940 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
941 );
943​
944it.effect("restores empty checkpoints without changing paths outside the workspace", () =>
945 Effect.gen(function* () {
946 const fileSystem = yield* FileSystem.FileSystem;
947 const path = yield* Path.Path;
948 const driver = yield* GitVcsDriver.makeVcsDriverShape();
949 for (const nested of [false, true]) {
950 const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-empty-checkpoint-" });
951 yield* runGit(root, ["init"]);
952 yield* runGit(root, ["config", "user.email", "test@test.com"]);
953 yield* runGit(root, ["config", "user.name", "Test"]);
954 if (nested) {
955 yield* fileSystem.writeFileString(path.join(root, "outside.txt"), "original\n");
956 yield* runGit(root, ["add", "."]);
957 }
958 yield* runGit(root, ["commit", "--allow-empty", "-m", "initial"]);
959 const cwd = nested ? path.join(root, "nested") : root;
960 yield* fileSystem.makeDirectory(cwd, { recursive: true });
961 const checkpointRef = CheckpointRef.make("refs/t3/checkpoints/empty");
962 yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
963 if (nested) {
964 yield* fileSystem.writeFileString(path.join(root, "outside.txt"), "changed\n");
965 yield* runGit(root, ["add", "outside.txt"]);
966 }
967 for (const staged of [false, true]) {
968 const addedPath = path.join(cwd, "added.txt");
969 yield* fileSystem.writeFileString(addedPath, "new\n");
970 if (staged) yield* runGit(cwd, ["add", "added.txt"]);
971 assert.isTrue(
972 yield* driver.checkpoints.restoreCheckpoint({
973 cwd,
974 checkpointRef,
975 fallbackToHead: false,
976 }),
977 );
978 assert.isFalse(yield* fileSystem.exists(addedPath));
979 }
980 yield* fileSystem.writeFileString(
981 path.join(root, ".git", "info", "exclude"),
982 "ignored.txt\n",
983 );
984 yield* fileSystem.writeFileString(path.join(cwd, "ignored.txt"), "keep\n");
985 yield* fileSystem.makeDirectory(path.join(cwd, "untracked"));
986 yield* fileSystem.writeFileString(path.join(cwd, "untracked", "file.txt"), "remove\n");
987 assert.isTrue(
988 yield* driver.checkpoints.restoreCheckpoint({ cwd, checkpointRef, fallbackToHead: false }),
989 );
990 assert.strictEqual(yield* fileSystem.readFileString(path.join(cwd, "ignored.txt")), "keep\n");
991 assert.isFalse(yield* fileSystem.exists(path.join(cwd, "untracked")));
992 if (nested) {
993 assert.strictEqual(
994 yield* fileSystem.readFileString(path.join(root, "outside.txt")),
995 "changed\n",
996 );
997 const staged = yield* driver.execute({
998 operation: "test",
999 cwd: root,
1000 args: ["diff", "--cached", "--name-only"],
1001 });
1002 assert.strictEqual(staged.stdout.trim(), "outside.txt");
1005 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
1007​
1008it.effect("GitVcsDriver forwards execute env to the VCS process", () => {
1009 let observedEnv: NodeJS.ProcessEnv | undefined;
1010 let observedAppendTruncationMarker: boolean | undefined;
1011 let observedOutputMode: VcsProcess.VcsProcessInput["outputMode"];
1012​
1013 return Effect.gen(function* () {
1014 const driver = yield* GitVcsDriver.makeVcsDriverShape();
1015​
1016 yield* driver.execute({
1017 operation: "GitVcsDriver.test.env",
1018 cwd: "/repo",
1019 args: ["status"],
1020 env: {
1021 GIT_INDEX_FILE: "/tmp/t3-index",
1022 },
1023 appendTruncationMarker: true,
1024 outputMode: "error",
1025 });
1026​
1027 assert.deepStrictEqual(observedEnv, {
1028 GIT_INDEX_FILE: "/tmp/t3-index",
1029 });
1030 assert.strictEqual(observedAppendTruncationMarker, true);
1031 assert.strictEqual(observedOutputMode, "error");
1032 }).pipe(
1033 Effect.provide(
1034 Layer.mergeAll(
1035 NodeServices.layer,
1036 Layer.mock(VcsProcess.VcsProcess)({
1037 run: (input) =>
1038 Effect.sync(() => {
1039 observedEnv = input.env;
1040 observedAppendTruncationMarker = input.appendTruncationMarker;
1041 observedOutputMode = input.outputMode;
1042 return {
1043 exitCode: ChildProcessSpawner.ExitCode(0),
1044 stdout: "",
1045 stderr: "",
1046 stdoutTruncated: false,
1047 stderrTruncated: false,
1048 };
1049 }),
1050 }),
1051 ),
1052 ),
1053 );
1054});
1055​
1056it.effect("GitVcsDriver flushes checkpoint objects and refs to disk before publishing them", () => {
1057 const observedArgs: ReadonlyArray<string>[] = [];
1058​
1059 return Effect.gen(function* () {
1060 const driver = yield* GitVcsDriver.makeVcsDriverShape();
1061​
1062 yield* driver.checkpoints.captureCheckpoint({
1063 cwd: "/repo",
1064 checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread/turn/1"),
1065 });
1066​
1067 const writeCommands = ["add", "write-tree", "commit-tree", "update-ref"];
1068 const writes = observedArgs.filter((args) =>
1069 writeCommands.some((command) => args.includes(command)),
1070 );
1071 assert.strictEqual(writes.length, 4);
1072 for (const args of writes) {
1073 const command = args.findIndex((arg) => writeCommands.includes(arg));
1074 for (const setting of ["core.fsync=objects,reference", "core.fsyncMethod=fsync"]) {
1075 const index = args.indexOf(setting);
1076 assert.strictEqual(args[index - 1], "-c", args.join(" "));
1077 assert.isBelow(index, command);
1080 assert.deepStrictEqual(observedArgs.at(-1), [
1081 "-C",
1082 "/repo",
1083 "-c",
1084 "core.fsync=objects,reference",
1085 "-c",
1086 "core.fsyncMethod=fsync",
1087 "update-ref",
1088 "refs/t3/checkpoints/thread/turn/1",
1089 "commit0000",
1090 ]);
1091 }).pipe(
1092 Effect.provide(
1093 Layer.mergeAll(
1094 NodeServices.layer,
1095 Layer.mock(VcsProcess.VcsProcess)({
1096 run: (input) =>
1097 Effect.sync(() => {
1098 observedArgs.push(input.args);
1099 const stdout = input.args.includes("write-tree")
1100 ? "tree0000\n"
1101 : input.args.includes("commit-tree")
1102 ? "commit0000\n"
1103 : input.args.includes("--git-common-dir")
1104 ? ".git\n"
1105 : "";
1106 return {
1107 exitCode: ChildProcessSpawner.ExitCode(0),
1108 stdout,
1109 stderr: "",
1110 stdoutTruncated: false,
1111 stderrTruncated: false,
1112 };
1113 }),
1114 }),
1115 ),
1116 ),
1117 );
1118});