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

GitVcsDriver.test.ts

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