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

GitVcsDriver.test.ts

1,243 lines55.0 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 // The real index points at a sharedindex.* file. Reading it fails if the capture expired it.
266 assert.strictEqual((yield* git(["ls-files", "--cached"])).stdout, "file.txt\n");
267 assert.strictEqual((yield* git(["diff", "--cached", "--name-only"])).stdout, "file.txt\n");
268 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
269);
270​
271it.effect("checkpoint recovery discovers nested HEAD independently of inherited GIT_DIR", () =>
272 Effect.gen(function* () {
273 const fs = yield* FileSystem.FileSystem;
274 const path = yield* Path.Path;
275 const driver = yield* GitVcsDriver.makeVcsDriverShape();
276 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-git-dir-" });
277 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
278 yield* git(["init", "empty"]);
279 const originalIndex = yield* fs.readFile(path.join(cwd, ".git", "index"));
280 yield* Effect.acquireUseRelease(
281 Effect.sync(() => {
282 const previous = process.env.GIT_DIR;
283 process.env.GIT_DIR = path.join(cwd, ".git");
284 return previous;
285 }),
286 () => driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }),
287 (previous) =>
288 Effect.sync(() => {
289 if (previous === undefined) delete process.env.GIT_DIR;
290 else process.env.GIT_DIR = previous;
291 }),
292 );
293 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "unstaged\n");
294 assert.strictEqual((yield* git(["ls-tree", "-r", checkpointRef, "--", "empty"])).stdout, "");
295 assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git", "index")), originalIndex);
296 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
297);
298​
299it.effect("checkpoint capture still fails when a clean filter rejects a file", () =>
300 Effect.gen(function* () {
301 const fileSystem = yield* FileSystem.FileSystem;
302 const path = yield* Path.Path;
303 const driver = yield* GitVcsDriver.makeVcsDriverShape();
304 const cwd = yield* fileSystem.makeTempDirectoryScoped({
305 prefix: "t3-checkpoint-filter-failure-",
306 });
307 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
308 yield* fileSystem.writeFileString(path.join(cwd, ".gitattributes"), "file.txt filter=reject\n");
309 yield* git(["config", "filter.reject.clean", "false"]);
310 yield* git(["config", "filter.reject.required", "true"]);
311 const originalIndex = yield* fileSystem.readFile(path.join(cwd, ".git", "index"));
312​
313 const result = yield* Effect.result(
314 driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }),
315 );
316​
317 assert.strictEqual(result._tag, "Failure");
318 if (result._tag === "Failure") {
319 assert.strictEqual(result.failure._tag, "VcsProcessExitError");
320 }
321 assert.deepEqual(yield* fileSystem.readFile(path.join(cwd, ".git", "index")), originalIndex);
322 assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }));
323 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
324);
325​
326it.effect("checkpoint capture refuses a truncated nested repository listing", () =>
327 Effect.gen(function* () {
328 const fs = yield* FileSystem.FileSystem;
329 const liveProcess = yield* VcsProcess.VcsProcess;
330 const driver = yield* GitVcsDriver.makeVcsDriverShape();
331 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-truncated-" });
332 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
333 yield* git(["init", "empty"]);
334 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
335 Effect.provideService(VcsProcess.VcsProcess, {
336 run: (input) =>
337 liveProcess
338 .run(input)
339 .pipe(
340 Effect.map((result) =>
341 input.args.includes("--others") ? { ...result, stdoutTruncated: true } : result,
342 ),
343 ),
344 }),
345 );
346​
347 const result = yield* Effect.result(
348 captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef }),
349 );
350​
351 assert.strictEqual(result._tag, "Failure");
352 assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }));
353 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
354);
355​
356it.effect("checkpoint capture skips an ignored project while keeping its allowed sibling", () =>
357 Effect.gen(function* () {
358 const fs = yield* FileSystem.FileSystem;
359 const path = yield* Path.Path;
360 const driver = yield* GitVcsDriver.makeVcsDriverShape();
361 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-ignored-" });
362 const { git } = yield* makeCheckpointFixture(driver, parent);
363 yield* fs.writeFileString(
364 path.join(parent, ".gitignore"),
365 "*\n!.gitignore\n!file.txt\n!keep/\n!keep/**\n",
366 );
367 const ignoredCwd = path.join(parent, "ignored");
368 const keepCwd = path.join(parent, "keep");
369 yield* fs.makeDirectory(ignoredCwd);
370 yield* fs.makeDirectory(keepCwd);
371 yield* fs.writeFileString(path.join(ignoredCwd, "secret.txt"), "private\n");
372 yield* fs.writeFileString(path.join(keepCwd, "new.txt"), "new\n");
373 const originalIndex = yield* fs.readFile(path.join(parent, ".git", "index"));
374 const ignoredRef = CheckpointRef.make("refs/t3/checkpoints/ignored");
375 const keepRef = CheckpointRef.make("refs/t3/checkpoints/keep");
376​
377 const ignored = yield* Effect.result(
378 driver.checkpoints.captureCheckpoint({ cwd: ignoredCwd, checkpointRef: ignoredRef }),
379 );
380 yield* driver.checkpoints.captureCheckpoint({ cwd: keepCwd, checkpointRef: keepRef });
381​
382 assert.strictEqual((yield* git(["show", `${keepRef}:keep/new.txt`])).stdout, "new\n");
383 assert.strictEqual((yield* git(["ls-tree", "-r", keepRef, "--", "ignored"])).stdout, "");
384 assert.isFalse(
385 yield* driver.checkpoints.hasCheckpointRef({ cwd: parent, checkpointRef: ignoredRef }),
386 );
387 assert.deepEqual(yield* fs.readFile(path.join(parent, ".git", "index")), originalIndex);
388 assert.strictEqual(ignored._tag, "Failure");
389 if (ignored._tag === "Failure") {
390 assert.strictEqual(ignored.failure._tag, "VcsUnsupportedOperationError");
391 }
392 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
393);
394​
395it.effect.each([
396 { tracking: "committed-only", committed: ["committed.txt"], staged: [] },
397 { tracking: "staged-only", committed: [], staged: ["staged.txt"] },
398 { tracking: "mixed", committed: ["committed.txt"], staged: ["staged.txt"] },
399])(
400 "checkpoint capture keeps $tracking tracked edits but excludes new files in a project ignored later",
401 ({ committed, staged }) =>
402 Effect.gen(function* () {
403 const fs = yield* FileSystem.FileSystem;
404 const path = yield* Path.Path;
405 const driver = yield* GitVcsDriver.makeVcsDriverShape();
406 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-ignored-later-" });
407 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, parent);
408 const cwd = path.join(parent, "sub");
409 yield* fs.makeDirectory(cwd);
410 for (const file of committed) {
411 yield* fs.writeFileString(path.join(cwd, file), "committed\n");
412 yield* git(["add", `sub/${file}`]);
413 }
414 if (committed.length > 0) {
415 yield* git(["commit", "-m", "track project"]);
416 }
417 for (const file of staged) {
418 yield* fs.writeFileString(path.join(cwd, file), "staged\n");
419 yield* git(["add", `sub/${file}`]);
420 }
421 const tracked = [...committed, ...staged];
422 yield* fs.writeFileString(path.join(parent, ".gitignore"), "sub/\n");
423 for (const file of tracked) {
424 yield* fs.writeFileString(path.join(cwd, file), `${file} working\n`);
425 }
426 yield* fs.writeFileString(path.join(cwd, "secret.txt"), "private\n");
427 const originalIndex = yield* fs.readFile(path.join(parent, ".git", "index"));
428​
429 const captured = yield* Effect.result(
430 driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }),
431 );
432​
433 assert.deepEqual(yield* fs.readFile(path.join(parent, ".git", "index")), originalIndex);
434 if (captured._tag === "Failure") return yield* captured.failure;
435 assert.strictEqual(
436 (yield* git(["ls-tree", "-r", "--name-only", checkpointRef, "--", "sub"])).stdout,
437 tracked.map((file) => `sub/${file}\n`).join(""),
438 );
439 for (const file of tracked) {
440 assert.strictEqual(
441 (yield* git(["show", `${checkpointRef}:sub/${file}`])).stdout,
442 `${file} working\n`,
443 );
444 }
445 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
446);
447​
448it.effect.each([
449 { phase: "add", nestedRecovery: false, expireRecovery: false },
450 { phase: "update-ref", nestedRecovery: false, expireRecovery: false },
451 { phase: "update-ref", nestedRecovery: true, expireRecovery: false },
452 { phase: "add", nestedRecovery: true, expireRecovery: false },
453 { phase: "add", nestedRecovery: true, expireRecovery: true },
454])(
455 "checkpoint handles a $phase lock with nestedRecovery=$nestedRecovery, expireRecovery=$expireRecovery",
456 ({ phase, nestedRecovery, expireRecovery }) =>
457 Effect.gen(function* () {
458 const fs = yield* FileSystem.FileSystem;
459 const path = yield* Path.Path;
460 const liveRunner = yield* ProcessRunner.ProcessRunner;
461 const driver = yield* GitVcsDriver.makeVcsDriverShape();
462 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-ref-race-" });
463 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
464 if (nestedRecovery) yield* git(["init", "empty"]);
465 const originalIndex = yield* fs.readFile(path.join(cwd, ".git", "index"));
466 const refLockPath = path.join(cwd, ".git", `${checkpointRef}.lock`);
467 const failed = yield* Deferred.make<void>();
468 const retryReached = yield* Deferred.make<void>();
469 const allowRetry = yield* Deferred.make<void>();
470 const clock = yield* Clock.Clock;
471 const privateIndexes = new Set<string>();
472 let racedAttempts = 0;
473 let discoveries = 0;
474 let stageError: VcsProcessExitError | undefined;
475 const captureProcess = yield* VcsProcess.make.pipe(
476 Effect.provideService(ProcessRunner.ProcessRunner, {
477 run: (input) => {
478 if (input.args.includes("--others")) discoveries += 1;
479 if (input.env?.GIT_INDEX_FILE) privateIndexes.add(input.env.GIT_INDEX_FILE);
480 const initialStage =
481 phase === "add" &&
482 nestedRecovery &&
483 !input.args.some((arg) => arg.startsWith(":(exclude,literal)"));
484 if (!input.args.includes(phase) || initialStage || ++racedAttempts !== 1) {
485 return liveRunner.run(input);
486 }
487 const lockPath = phase === "add" ? `${input.env!.GIT_INDEX_FILE!}.lock` : refLockPath;
488 return Effect.gen(function* () {
489 yield* fs
490 .makeDirectory(path.dirname(lockPath), { recursive: true })
491 .pipe(Effect.orDie);
492 yield* fs.writeFileString(lockPath, "concurrent ref writer").pipe(Effect.orDie);
493 return yield* liveRunner.run(input).pipe(
494 Effect.ensuring(fs.remove(lockPath).pipe(Effect.orDie)),
495 Effect.tap(() => Deferred.succeed(failed, undefined)),
496 );
497 });
498 },
499 }),
500 );
501 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
502 Effect.provideService(VcsProcess.VcsProcess, {
503 run: (input) =>
504 captureProcess.run(input).pipe(
505 Effect.tapError((error) => {
506 if (input.args.includes("add") && error._tag === "VcsProcessExitError")
507 stageError = error;
508 return Effect.void;
509 }),
510 ),
511 }),
512 );
513 const captureStore = yield* makeCaptureStore(captureDriver, cwd);
514 const fiber = yield* captureStore.captureCheckpoint({ cwd, checkpointRef }).pipe(
515 Effect.provideService(Clock.Clock, {
516 ...clock,
517 sleep: (duration) =>
518 Duration.toMillis(duration) === 75
519 ? Deferred.succeed(retryReached, undefined).pipe(
520 Effect.andThen(Deferred.await(allowRetry)),
521 )
522 : clock.sleep(duration),
523 }),
524 Effect.exit,
525 Effect.forkScoped,
526 );
527 yield* Deferred.await(failed);
528 yield* Deferred.await(retryReached);
529 if (expireRecovery) yield* TestClock.adjust("5 seconds");
530 else yield* Deferred.succeed(allowRetry, undefined);
531 const result = yield* Fiber.join(fiber);
532 if (expireRecovery) {
533 if (Exit.isSuccess(result))
534 return yield* Effect.die("Expected the recovery deadline to expire");
535 const error = Cause.findErrorOption(result.cause);
536 assert.isTrue(error._tag === "Some");
537 if (error._tag === "Some") assert.strictEqual(error.value, stageError);
538 } else assert.isTrue(Exit.isSuccess(result));
539 assert.strictEqual(racedAttempts, expireRecovery ? 1 : 2);
540 assert.strictEqual(discoveries, nestedRecovery ? 1 : 0);
541 assert.strictEqual(privateIndexes.size, 1);
542 assert.strictEqual(
543 yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }),
544 !expireRecovery,
545 );
546 for (const index of privateIndexes) {
547 assert.isFalse(yield* fs.exists(index));
548 assert.isFalse(yield* fs.exists(`${index}.lock`));
549 }
550 assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git", "index")), originalIndex);
551 }).pipe(Effect.scoped, Effect.provide(layerGitCaptureContract)),
552);
553​
554it.effect("checkpoint recovery preserves interruption and removes the private index", () =>
555 Effect.gen(function* () {
556 const fs = yield* FileSystem.FileSystem;
557 const liveProcess = yield* VcsProcess.VcsProcess;
558 const driver = yield* GitVcsDriver.makeVcsDriverShape();
559 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-recovery-interrupt-" });
560 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
561 yield* git(["init", "empty"]);
562 const entered = yield* Deferred.make<void>();
563 let privateIndex: string | undefined;
564 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
565 Effect.provideService(VcsProcess.VcsProcess, {
566 run: (input) => {
567 if (input.args.includes("add") && input.args.includes("-A"))
568 privateIndex = input.env?.GIT_INDEX_FILE;
569 return input.args.includes("--others")
570 ? Deferred.succeed(entered, undefined).pipe(Effect.andThen(Effect.never))
571 : liveProcess.run(input);
572 },
573 }),
574 );
575 const fiber = yield* captureDriver.checkpoints
576 .captureCheckpoint({ cwd, checkpointRef })
577 .pipe(Effect.forkScoped);
578 yield* Deferred.await(entered);
579 yield* Fiber.interrupt(fiber);
580 const exit = yield* Fiber.await(fiber);
581 assert.isTrue(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause));
582 assert.isDefined(privateIndex);
583 assert.isFalse(yield* fs.exists(privateIndex!));
584 assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }));
585 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
586);
587​
588it.effect.each(
589 [false, true].flatMap((nested) =>
590 (["sparse", "flags", "manual-skip", "missing", "non-cone-missing"] as const).map(
591 (indexState) => ({ nested, indexState }),
592 ),
593 ),
594)(
595 "sparse checkpoint preserves two captures (nested=$nested, index=$indexState)",
596 ({ nested, indexState }) =>
597 Effect.gen(function* () {
598 const fs = yield* FileSystem.FileSystem;
599 const path = yield* Path.Path;
600 const driver = yield* GitVcsDriver.makeVcsDriverShape();
601 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-sparse-" });
602 const { git } = yield* makeCheckpointFixture(driver, cwd);
603 const write = Effect.fn(function* (name: string, contents: string) {
604 yield* fs.makeDirectory(path.dirname(path.join(cwd, name)), { recursive: true });
605 yield* fs.writeFileString(path.join(cwd, name), contents);
606 });
607 for (const name of [
608 "scope/in/edit",
609 "scope/in/delete",
610 "scope/out/deep/absent",
611 "scope/out/present",
612 "elsewhere/file",
613 ]) {
614 yield* write(name, "original\n");
615 }
616 yield* git(["add", "."]);
617 yield* git(["commit", "-m", "sparse fixture"]);
618 yield* git(["sparse-checkout", "set", "--cone", "--sparse-index", "scope/in", "elsewhere"]);
619 if (indexState === "non-cone-missing")
620 yield* git(["sparse-checkout", "set", "--no-cone", "/scope/in/", "/elsewhere/"]);
621 yield* write("scope/in/edit", "staged\n");
622 yield* write("elsewhere/file", "staged outside\n");
623 yield* git(["add", "."]);
624 if (indexState === "flags")
625 yield* git(["update-index", "--assume-unchanged", "scope/in/delete"]);
626 if (indexState === "manual-skip")
627 yield* git(["update-index", "--skip-worktree", "scope/in/delete"]);
628 yield* git(["config", "sparse.expectFilesOutsideOfPatterns", "true"]);
629 yield* write("scope/in/edit", "working\n");
630 yield* write("scope/out/present", "modified skipped\n");
631 yield* write("scope/out/new file", "new outside cone\n");
632 yield* write("elsewhere/file", "working outside\n");
633 yield* fs.remove(path.join(cwd, "scope/in/delete"));
634 const indexPath = path.join(cwd, ".git/index");
635 if (indexState.endsWith("missing")) yield* fs.remove(indexPath);
636 const originalIndex = yield* fs.readFile(indexPath).pipe(Effect.orElseSucceed(() => null));
637 const captureCwd = nested ? path.join(cwd, "scope") : cwd;
638 for (const turn of [1, 2]) {
639 const ref = CheckpointRef.make(`refs/t3/checkpoints/sparse/${turn}`);
640 if (turn === 2) {
641 yield* write("scope/in/edit", "second\n");
642 yield* fs.remove(path.join(cwd, "scope/out/new file"));
643 yield* write("scope/out/second", "second addition\n");
644 }
645 const capture = driver.checkpoints.captureCheckpoint({
646 cwd: captureCwd,
647 checkpointRef: ref,
648 });
649 if (indexState === "non-cone-missing") {
650 assert.strictEqual((yield* capture.pipe(Effect.flip))._tag, "VcsProcessExitError");
651 assert.isFalse(
652 yield* driver.checkpoints.hasCheckpointRef({ cwd: captureCwd, checkpointRef: ref }),
653 );
654 assert.isFalse(yield* fs.exists(indexPath));
655 break;
656 }
657 yield* capture;
658 for (const [name, content] of [
659 ["scope/out/deep/absent", "original\n"],
660 ["scope/out/present", "modified skipped\n"],
661 ["scope/in/edit", turn === 1 ? "working\n" : "second\n"],
662 ["elsewhere/file", nested ? "original\n" : "working outside\n"],
663 [
664 turn === 1 ? "scope/out/new file" : "scope/out/second",
665 turn === 1 ? "new outside cone\n" : "second addition\n",
666 ],
667 ]) {
668 assert.strictEqual((yield* git(["show", `${ref}:${name}`])).stdout, content);
669 }
670 const files = (yield* git(["ls-tree", "-rz", "--name-only", ref])).stdout.split("\0");
671 assert.notInclude(files, "scope/in/delete");
672 if (turn === 2) assert.notInclude(files, "scope/out/new file");
673 assert.deepEqual(
674 yield* fs.readFile(indexPath).pipe(Effect.orElseSucceed(() => null)),
675 originalIndex,
676 );
677 assert.isFalse(yield* fs.exists(path.join(cwd, "scope/out/deep/absent")));
678 assert.strictEqual(
679 yield* fs.readFileString(path.join(cwd, "elsewhere/file")),
680 "working outside\n",
681 );
682 }
683 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
684);
685​
686it.effect.each(["normal", "flags", "sparse"] as const)(
687 "checkpoint index inspection handles entries beyond the output cap (index=%s)",
688 (indexMode) =>
689 Effect.gen(function* () {
690 const fs = yield* FileSystem.FileSystem;
691 const path = yield* Path.Path;
692 const liveProcess = yield* VcsProcess.VcsProcess;
693 const driver = yield* GitVcsDriver.makeVcsDriverShape();
694 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-inspection-" });
695 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
696 yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "stable filter=probe\n");
697 yield* fs.writeFileString(path.join(cwd, "stable"), "unchanged\n");
698 yield* fs.writeFileString(path.join(cwd, "z-skipped"), "original\n");
699 yield* fs.makeDirectory(path.join(cwd, "excluded"));
700 yield* fs.writeFileString(path.join(cwd, "excluded/file"), "absent\n");
701 yield* fs.writeFileString(
702 path.join(cwd, ".git/filter.cjs"),
703 'require("node:fs").appendFileSync(".git/reads", "read\\n"); process.stdin.pipe(process.stdout);',
704 );
705 yield* git(["config", "filter.probe.clean", "node .git/filter.cjs"]);
706 yield* fs.utimes(path.join(cwd, "stable"), 1_700_000_000, 1_700_000_000);
707 yield* git(["add", "."]);
708 yield* git(["commit", "-m", "inspection fixture"]);
709 if (indexMode === "flags") yield* git(["update-index", "--skip-worktree", "z-skipped"]);
710 if (indexMode === "sparse")
711 yield* git(["sparse-checkout", "set", "--cone", "--sparse-index", "included"]);
712 yield* fs.writeFileString(path.join(cwd, "z-skipped"), "modified\n");
713 yield* fs.writeFileString(path.join(cwd, ".git/reads"), "");
714 const originalIndex = yield* fs.readFile(path.join(cwd, ".git/index"));
715 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
716 Effect.provideService(VcsProcess.VcsProcess, {
717 run: (input) =>
718 liveProcess.run(
719 input.args.includes("ls-files")
720 ? {
721 ...input,
722 maxOutputBytes: 8,
723 onStdoutChunk: (chunk) => {
724 for (let i = 0; i < chunk.length; i++)
725 input.onStdoutChunk?.(chunk.subarray(i, i + 1));
726 },
727 }
728 : input,
729 ),
730 }),
731 );
732 yield* captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
733 assert.strictEqual((yield* git(["show", `${checkpointRef}:z-skipped`])).stdout, "modified\n");
734 if (indexMode !== "flags")
735 assert.strictEqual(yield* fs.readFileString(path.join(cwd, ".git/reads")), "");
736 assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git/index")), originalIndex);
737 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
738);
739​
740it.effect.each([1_700_000_000, 1_700_000_000.9999])(
741 "checkpoint capture preserves same-size edits with racy index timestamps (%s)",
742 (timestamp) =>
743 Effect.gen(function* () {
744 const fileSystem = yield* FileSystem.FileSystem;
745 const path = yield* Path.Path;
746 const driver = yield* GitVcsDriver.makeVcsDriverShape();
747 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-racy-" });
748 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
749 const filePath = path.join(cwd, "file.txt");
750 const indexPath = path.join(cwd, ".git", "index");
751 yield* git(["config", "core.trustctime", "false"]);
752 yield* fileSystem.writeFileString(filePath, "before\n");
753 yield* fileSystem.utimes(filePath, timestamp, timestamp);
754 yield* git(["add", "file.txt"]);
755 yield* git(["commit", "-m", "record racy file"]);
756 yield* fileSystem.utimes(indexPath, timestamp, timestamp);
757 const originalIndex = yield* fileSystem.readFile(indexPath);
758 const originalIndexMtime = (yield* fileSystem.stat(indexPath)).mtime;
759 yield* fileSystem.writeFileString(filePath, "after!\n");
760 yield* fileSystem.utimes(filePath, timestamp, timestamp);
761​
762 yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
763​
764 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "after!\n");
765 assert.deepEqual(yield* fileSystem.readFile(indexPath), originalIndex);
766 assert.deepEqual((yield* fileSystem.stat(indexPath)).mtime, originalIndexMtime);
767 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
768);
769​
770it.effect("checkpoint capture preserves racy edits made after resetting the index", () =>
771 Effect.gen(function* () {
772 const fileSystem = yield* FileSystem.FileSystem;
773 const path = yield* Path.Path;
774 const liveProcess = yield* VcsProcess.VcsProcess;
775 const driver = yield* GitVcsDriver.makeVcsDriverShape();
776 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-racy-reset-" });
777 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
778 const racyPath = path.join(cwd, "racy.txt");
779 const indexPath = path.join(cwd, ".git", "index");
780 const timestamp = 1_700_000_000;
781 yield* git(["config", "core.trustctime", "false"]);
782 yield* fileSystem.writeFileString(racyPath, "before\n");
783 yield* fileSystem.utimes(racyPath, timestamp, timestamp);
784 yield* git(["add", "."]);
785 yield* git(["commit", "-m", "record racy file"]);
786 yield* fileSystem.writeFileString(path.join(cwd, "file.txt"), "staged\n");
787 yield* git(["add", "file.txt"]);
788 yield* fileSystem.utimes(indexPath, timestamp, timestamp);
789 const originalIndex = yield* fileSystem.readFile(indexPath);
790 const originalIndexMtime = (yield* fileSystem.stat(indexPath)).mtime;
791 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
792 Effect.provideService(VcsProcess.VcsProcess, {
793 run: Effect.fn(function* (input: VcsProcess.VcsProcessInput) {
794 const result = yield* liveProcess.run(input);
795 if (input.args.includes("read-tree") && input.args.includes("--reset")) {
796 yield* fileSystem.writeFileString(racyPath, "after!\n").pipe(Effect.orDie);
797 yield* fileSystem.utimes(racyPath, timestamp, timestamp).pipe(Effect.orDie);
798 }
799 return result;
800 }),
801 }),
802 );
803​
804 yield* captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
805​
806 assert.strictEqual((yield* git(["show", `${checkpointRef}:racy.txt`])).stdout, "after!\n");
807 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "staged\n");
808 assert.deepEqual(yield* fileSystem.readFile(indexPath), originalIndex);
809 assert.deepEqual((yield* fileSystem.stat(indexPath)).mtime, originalIndexMtime);
810 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
811);
812​
813it.effect.each(
814 [false, true].flatMap((nested) =>
815 (["normal", "flags", "split"] as const).map((indexMode) => ({ nested, indexMode })),
816 ),
817)(
818 "checkpoint index reuse preserves two turns (nested=$nested, index=$indexMode)",
819 ({ nested, indexMode }) =>
820 Effect.gen(function* () {
821 const fileSystem = yield* FileSystem.FileSystem;
822 const path = yield* Path.Path;
823 const driver = yield* GitVcsDriver.makeVcsDriverShape();
824 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-turns-" });
825 const { git } = yield* makeCheckpointFixture(driver, cwd);
826 const write = (name: string, contents: string) =>
827 fileSystem.writeFileString(path.join(cwd, name), contents);
828 yield* fileSystem.makeDirectory(path.join(cwd, "scope"));
829 for (const name of [
830 "scope/staged",
831 "scope/deleted",
832 "scope/assumed",
833 "scope/skipped",
834 "outside",
835 ]) {
836 yield* write(name, "original\n");
837 }
838 yield* git(["add", "."]);
839 yield* git(["commit", "-m", "initial scoped files"]);
840 yield* write("scope/staged", "staged\n");
841 yield* write("scope/new-deleted", "staged then deleted\n");
842 yield* write("outside", "staged outside\n");
843 yield* git(["add", "."]);
844 if (indexMode === "flags") {
845 yield* git(["update-index", "--assume-unchanged", "scope/assumed"]);
846 yield* git(["update-index", "--skip-worktree", "scope/skipped"]);
847 }
848 if (indexMode === "split") {
849 yield* git(["update-index", "--split-index"]);
850 }
851 const originalIndex = yield* fileSystem.readFile(path.join(cwd, ".git", "index"));
852 for (const name of ["scope/staged", "scope/assumed", "scope/skipped", "outside"]) {
853 yield* write(name, "working\n");
854 }
855 yield* write("scope/new", "first\n");
856 yield* fileSystem.remove(path.join(cwd, "scope/deleted"));
857 yield* fileSystem.remove(path.join(cwd, "scope/new-deleted"));
858 const captureCwd = nested ? path.join(cwd, "scope") : cwd;
859 const first = CheckpointRef.make("refs/t3/checkpoints/turns/1");
860 const second = CheckpointRef.make("refs/t3/checkpoints/turns/2");
861 yield* driver.checkpoints.captureCheckpoint({ cwd: captureCwd, checkpointRef: first });
862 for (const name of ["scope/staged", "scope/assumed", "scope/skipped"]) {
863 assert.strictEqual((yield* git(["show", `${first}:${name}`])).stdout, "working\n");
864 }
865 assert.strictEqual(
866 (yield* git(["show", `${first}:outside`])).stdout,
867 nested ? "original\n" : "working\n",
868 );
869 const files = (yield* git(["ls-tree", "-r", "--name-only", first])).stdout.split("\n");
870 assert.notInclude(files, "scope/deleted");
871 assert.notInclude(files, "scope/new-deleted");
872 assert.include(files, "scope/new");
873​
874 yield* write("scope/staged", "second\n");
875 yield* fileSystem.remove(path.join(cwd, "scope/new"));
876 yield* write("scope/second", "added in second turn\n");
877 yield* driver.checkpoints.captureCheckpoint({ cwd: captureCwd, checkpointRef: second });
878 assert.strictEqual(
879 (yield* git(["diff", "--name-only", first, second])).stdout,
880 "scope/new\nscope/second\nscope/staged\n",
881 );
882 assert.strictEqual((yield* git(["show", `${second}:scope/staged`])).stdout, "second\n");
883 assert.strictEqual(
884 (yield* git(["show", `${second}:scope/second`])).stdout,
885 "added in second turn\n",
886 );
887 assert.deepEqual(yield* fileSystem.readFile(path.join(cwd, ".git", "index")), originalIndex);
888 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
889);
890​
891it.effect.each(["missing", "invalid"] as const)(
892 "checkpoint capture falls back when the user index is %s",
893 (indexState) =>
894 Effect.gen(function* () {
895 const fileSystem = yield* FileSystem.FileSystem;
896 const path = yield* Path.Path;
897 const driver = yield* GitVcsDriver.makeVcsDriverShape();
898 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-index-" });
899 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
900 const indexPath = path.join(cwd, ".git", "index");
901 if (indexState === "missing") {
902 yield* fileSystem.remove(indexPath);
903 } else {
904 yield* fileSystem.writeFileString(indexPath, "invalid index");
905 }
906​
907 yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
908​
909 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "unstaged\n");
910 if (indexState === "missing") {
911 assert.isFalse(yield* fileSystem.exists(indexPath));
912 } else {
913 assert.strictEqual(yield* fileSystem.readFileString(indexPath), "invalid index");
914 }
915 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
916);
917​
918it.effect("restores empty checkpoints without changing paths outside the workspace", () =>
919 Effect.gen(function* () {
920 const fileSystem = yield* FileSystem.FileSystem;
921 const path = yield* Path.Path;
922 const driver = yield* GitVcsDriver.makeVcsDriverShape();
923 for (const nested of [false, true]) {
924 const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-empty-checkpoint-" });
925 yield* runGit(root, ["init"]);
926 yield* runGit(root, ["config", "user.email", "test@test.com"]);
927 yield* runGit(root, ["config", "user.name", "Test"]);
928 if (nested) {
929 yield* fileSystem.writeFileString(path.join(root, "outside.txt"), "original\n");
930 yield* runGit(root, ["add", "."]);
931 }
932 yield* runGit(root, ["commit", "--allow-empty", "-m", "initial"]);
933 const cwd = nested ? path.join(root, "nested") : root;
934 yield* fileSystem.makeDirectory(cwd, { recursive: true });
935 const checkpointRef = CheckpointRef.make("refs/t3/checkpoints/empty");
936 yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
937 if (nested) {
938 yield* fileSystem.writeFileString(path.join(root, "outside.txt"), "changed\n");
939 yield* runGit(root, ["add", "outside.txt"]);
940 }
941 for (const staged of [false, true]) {
942 const addedPath = path.join(cwd, "added.txt");
943 yield* fileSystem.writeFileString(addedPath, "new\n");
944 if (staged) yield* runGit(cwd, ["add", "added.txt"]);
945 assert.isTrue(
946 yield* driver.checkpoints.restoreCheckpoint({
947 cwd,
948 checkpointRef,
949 fallbackToHead: false,
950 }),
951 );
952 assert.isTrue(yield* fileSystem.exists(cwd));
953 assert.isFalse(yield* fileSystem.exists(addedPath));
954 }
955 yield* fileSystem.writeFileString(
956 path.join(root, ".git", "info", "exclude"),
957 "ignored.txt\n",
958 );
959 yield* fileSystem.writeFileString(path.join(cwd, "ignored.txt"), "keep\n");
960 yield* fileSystem.makeDirectory(path.join(cwd, "untracked"));
961 yield* fileSystem.writeFileString(path.join(cwd, "untracked", "file.txt"), "remove\n");
962 assert.isTrue(
963 yield* driver.checkpoints.restoreCheckpoint({ cwd, checkpointRef, fallbackToHead: false }),
964 );
965 assert.strictEqual(yield* fileSystem.readFileString(path.join(cwd, "ignored.txt")), "keep\n");
966 assert.isFalse(yield* fileSystem.exists(path.join(cwd, "untracked")));
967 if (nested) {
968 assert.strictEqual(
969 yield* fileSystem.readFileString(path.join(root, "outside.txt")),
970 "changed\n",
971 );
972 const staged = yield* driver.execute({
973 operation: "test",
974 cwd: root,
975 args: ["diff", "--cached", "--name-only"],
976 });
977 assert.strictEqual(staged.stdout.trim(), "outside.txt");
978 }
979 }
980 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
981);
982​
983// The real VCS process, spawning `command` wherever the driver runs git.
984const vcsProcessSpawning = (command: string) =>
985 Layer.effect(
986 VcsProcess.VcsProcess,
987 Effect.map(VcsProcess.make, (vcsProcess) =>
988 VcsProcess.VcsProcess.of({ run: (input) => vcsProcess.run({ ...input, command }) }),
989 ),
990 ).pipe(Layer.provide(ProcessRunner.layer), Layer.provideMerge(NodeServices.layer));
991​
992it.effect("GitVcsDriver treats a missing git executable as outside any repository", () =>
993 Effect.gen(function* () {
994 const fileSystem = yield* FileSystem.FileSystem;
995 const path = yield* Path.Path;
996 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-missing-git-" });
997 const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
998 Effect.provide(vcsProcessSpawning(path.join(cwd, "git"))),
999 );
1000​
1001 assert.strictEqual(yield* driver.isInsideWorkTree(cwd), false);
1002 assert.strictEqual(yield* driver.detectRepository(cwd), null);
1003 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1005​
1006it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
1007 "GitVcsDriver still fails detection when git exists but cannot be spawned",
1008 () =>
1009 Effect.gen(function* () {
1010 const fileSystem = yield* FileSystem.FileSystem;
1011 // A file without the execute bit fails to spawn with a permission error.
1012 const notExecutable = yield* fileSystem.makeTempFileScoped({ prefix: "t3-git-" });
1013 const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
1014 Effect.provide(vcsProcessSpawning(notExecutable)),
1015 );
1016​
1017 const error = yield* driver.isInsideWorkTree(process.cwd()).pipe(Effect.flip);
1018 assert.strictEqual(error._tag, "VcsProcessSpawnError");
1019 const detectionError = yield* driver.detectRepository(process.cwd()).pipe(Effect.flip);
1020 assert.strictEqual(detectionError._tag, "VcsProcessSpawnError");
1021 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1023​
1024const gitCommandCount = (operation: string, outcome: string) =>
1025 Metric.value(
1026 Metric.withAttributes(gitCommandsTotal, [
1027 ["operation", operation],
1028 ["outcome", outcome],
1029 ]),
1030 ).pipe(Effect.map((state) => state.count));
1031​
1032const gitCommandTiming = (operation: string) =>
1033 Metric.value(Metric.withAttributes(gitCommandDuration, [["operation", operation]]));
1034​
1035// Keep VcsProcess's exit classification; replace only the subprocess and its clock.
1036const makeMeteredDriver = Effect.fn("test.makeMeteredDriver")(function* (exitCode: number) {
1037 const process = yield* VcsProcess.make.pipe(
1038 Effect.provideService(ProcessRunner.ProcessRunner, {
1039 run: () =>
1040 TestClock.adjust("250 millis").pipe(
1041 Effect.as({
1042 code: ChildProcessSpawner.ExitCode(exitCode),
1043 stdout: "git output",
1044 stderr: exitCode === 0 ? "" : "fatal: test failure",
1045 timedOut: false,
1046 stdoutTruncated: false,
1047 stderrTruncated: false,
1048 stdoutInvalidUtf8: false,
1049 stderrInvalidUtf8: false,
1050 }),
1051 ),
1052 }),
1053 );
1054 return yield* GitVcsDriver.makeVcsDriverShape().pipe(
1055 Effect.provideService(VcsProcess.VcsProcess, process),
1056 );
1057});
1058​
1059it.effect("GitVcsDriver meters each git command once under its operation", () =>
1060 Effect.gen(function* () {
1061 const operation = "GitVcsDriver.checkpoints.resolveHeadCommit";
1062 const driver = yield* makeMeteredDriver(0);
1063​
1064 const result = yield* driver.execute({ operation, cwd: "/repo", args: ["rev-parse", "HEAD"] });
1065 yield* driver.execute({ operation, cwd: "/another-repo", args: ["rev-parse", "other-ref"] });
1066​
1067 assert.strictEqual(result.stdout, "git output");
1068 assert.strictEqual(yield* gitCommandCount(operation, "success"), 2);
1069 assert.strictEqual(yield* gitCommandCount(operation, "failure"), 0);
1070 const timing = yield* gitCommandTiming(operation);
1071 assert.strictEqual(timing.count, 2);
1072 assert.strictEqual(timing.sum, 500);
1073 }).pipe(
1074 Effect.provide(NodeServices.layer),
1075 Effect.provideService(Metric.MetricRegistry, new Map()),
1076 ),
1078​
1079it.effect("GitVcsDriver counts an allowed non-zero exit as a success", () =>
1080 Effect.gen(function* () {
1081 const operation = "GitVcsDriver.checkpoints.hasHeadCommit";
1082 const driver = yield* makeMeteredDriver(1);
1083​
1084 const result = yield* driver.execute({
1085 operation,
1086 cwd: "/repo",
1087 args: ["rev-parse", "--verify", "HEAD"],
1088 allowNonZeroExit: true,
1089 });
1090​
1091 assert.strictEqual(result.exitCode, 1);
1092 assert.strictEqual(yield* gitCommandCount(operation, "success"), 1);
1093 assert.strictEqual(yield* gitCommandCount(operation, "failure"), 0);
1094 const timing = yield* gitCommandTiming(operation);
1095 assert.strictEqual(timing.count, 1);
1096 assert.strictEqual(timing.sum, 250);
1097 }).pipe(
1098 Effect.provide(NodeServices.layer),
1099 Effect.provideService(Metric.MetricRegistry, new Map()),
1100 ),
1102​
1103it.effect("GitVcsDriver counts a failed git command as a failure", () =>
1104 Effect.gen(function* () {
1105 const operation = "GitVcsDriver.checkpoints.resolveHeadCommit";
1106 const driver = yield* makeMeteredDriver(128);
1107​
1108 const error = yield* driver
1109 .execute({ operation, cwd: "/repo", args: ["rev-parse", "HEAD"] })
1110 .pipe(Effect.flip);
1111​
1112 assert.strictEqual(error._tag, "VcsProcessExitError");
1113 assert.strictEqual(yield* gitCommandCount(operation, "failure"), 1);
1114 assert.strictEqual(yield* gitCommandCount(operation, "success"), 0);
1115 const timing = yield* gitCommandTiming(operation);
1116 assert.strictEqual(timing.count, 1);
1117 assert.strictEqual(timing.sum, 250);
1118 }).pipe(
1119 Effect.provide(NodeServices.layer),
1120 Effect.provideService(Metric.MetricRegistry, new Map()),
1121 ),
1123​
1124it.effect("checkpoint capture meters every git process it starts, including streamed ones", () =>
1125 Effect.gen(function* () {
1126 const fileSystem = yield* FileSystem.FileSystem;
1127 const liveProcess = yield* VcsProcess.VcsProcess;
1128 const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION;
1129 let started = 0;
1130 let streamed = 0;
1131 const driver = yield* GitVcsDriver.makeVcsDriverShape();
1132 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
1133 Effect.provideService(VcsProcess.VcsProcess, {
1134 run: (input) => {
1135 if (input.operation === operation) {
1136 started++;
1137 if (input.onStdoutChunk !== undefined) streamed++;
1139 return liveProcess.run(input);
1140 },
1141 }),
1142 );
1143 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-metrics-" });
1144 const { checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
1145​
1146 yield* captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
1147​
1148 assert.isAbove(streamed, 0);
1149 assert.strictEqual(yield* gitCommandCount(operation, "success"), started);
1150 assert.strictEqual(yield* gitCommandCount(operation, "failure"), 0);
1151 assert.strictEqual((yield* gitCommandTiming(operation)).count, started);
1152 }).pipe(
1153 Effect.scoped,
1154 Effect.provide(layerGitContract),
1155 Effect.provideService(Metric.MetricRegistry, new Map()),
1156 ),
1158​
1159it.effect("git metrics finalize cancellation without exposing arbitrary operation labels", () =>
1160 Effect.gen(function* () {
1161 const started = yield* Deferred.make<void>();
1162 const process = yield* VcsProcess.make.pipe(
1163 Effect.provideService(ProcessRunner.ProcessRunner, {
1164 run: () => Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never)),
1165 }),
1166 );
1167 const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
1168 Effect.provideService(VcsProcess.VcsProcess, process),
1169 );
1170 const operation = "arbitrary operation /private/path";
1171 const fiber = yield* driver
1172 .execute({ operation, cwd: "/repo", args: ["rev-parse", "HEAD"] })
1173 .pipe(Effect.forkChild);
1174 yield* Deferred.await(started);
1175 yield* TestClock.adjust("250 millis");
1176 yield* Fiber.interrupt(fiber);
1177​
1178 assert.strictEqual(yield* gitCommandCount("other", "interrupt"), 1);
1179 assert.strictEqual(yield* gitCommandCount(operation, "interrupt"), 0);
1180 const timing = yield* gitCommandTiming("other");
1181 assert.strictEqual(timing.count, 1);
1182 assert.strictEqual(timing.sum, 250);
1183 }).pipe(
1184 Effect.provide(NodeServices.layer),
1185 Effect.provideService(Metric.MetricRegistry, new Map()),
1186 ),
1188​
1189it.effect("git metrics count fsync fallback and transient retry subprocesses separately", () =>
1190 Effect.gen(function* () {
1191 const retryReady = yield* Deferred.make<void>();
1192 const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION;
1193 let attempts = 0;
1194 const process = yield* VcsProcess.make.pipe(
1195 Effect.provideService(HostProcess.Platform, "darwin"),
1196 Effect.provideService(ProcessRunner.ProcessRunner, {
1197 run: (input) =>
1198 Effect.gen(function* () {
1199 attempts++;
1200 yield* TestClock.adjust("250 millis");
1201 if (attempts === 2) {
1202 assert.include(input.args, "core.fsyncMethod=writeout-only");
1203 yield* Deferred.succeed(retryReady, undefined);
1205 return {
1206 code: ChildProcessSpawner.ExitCode(attempts < 3 ? 128 : 0),
1207 stdout: "",
1208 stderr:
1209 attempts === 1
1210 ? "fatal: fsync error on '.git/objects/test': Operation not supported"
1211 : attempts === 2
1212 ? "fatal: Unable to create '/repo/.git/index.lock': File exists."
1213 : "",
1214 timedOut: false,
1215 stdoutTruncated: false,
1216 stderrTruncated: false,
1217 stdoutInvalidUtf8: false,
1218 stderrInvalidUtf8: false,
1219 };
1220 }),
1221 }),
1222 );
1223 const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
1224 Effect.provideService(VcsProcess.VcsProcess, process),
1225 );
1226 const fiber = yield* driver
1227 .execute({ operation, cwd: "/repo", args: ["-c", "core.fsyncMethod=batch", "add"] })
1228 .pipe(Effect.forkChild);
1229 yield* Deferred.await(retryReady);
1230 yield* TestClock.adjust("75 millis");
1231 yield* Fiber.join(fiber);
1232​
1233 assert.strictEqual(attempts, 3);
1234 assert.strictEqual(yield* gitCommandCount(operation, "failure"), 2);
1235 assert.strictEqual(yield* gitCommandCount(operation, "success"), 1);
1236 const timing = yield* gitCommandTiming(operation);
1237 assert.strictEqual(timing.count, 3);
1238 assert.strictEqual(timing.sum, 750);
1239 }).pipe(
1240 Effect.provide(NodeServices.layer),
1241 Effect.provideService(Metric.MetricRegistry, new Map()),
1242 ),