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

GitVcsDriver.test.ts

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