Open History to see the last commit
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(
686 (["normal", "flags", "sparse"] as const).flatMap((indexMode) =>
687 [1, 3, 4096].map((chunkSize) => ({ indexMode, chunkSize })),
688 ),
689)(
690 "checkpoint index inspection handles entries beyond the output cap (index=$indexMode, chunk=$chunkSize)",
691 ({ indexMode, chunkSize }) =>
692 Effect.gen(function* () {
693 const fs = yield* FileSystem.FileSystem;
694 const path = yield* Path.Path;
695 const liveProcess = yield* VcsProcess.VcsProcess;
696 const driver = yield* GitVcsDriver.makeVcsDriverShape();
697 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-inspection-" });
698 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
699 yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "stable filter=probe\n");
700 yield* fs.writeFileString(path.join(cwd, "stable"), "unchanged\n");
701 yield* fs.writeFileString(path.join(cwd, "z-skipped"), "original\n");
702 yield* fs.makeDirectory(path.join(cwd, "excluded"));
703 yield* fs.writeFileString(path.join(cwd, "excluded/file"), "absent\n");
704 yield* fs.writeFileString(
705 path.join(cwd, ".git/filter.cjs"),
706 'require("node:fs").appendFileSync(".git/reads", "read\\n"); process.stdin.pipe(process.stdout);',
707 );
708 yield* git(["config", "filter.probe.clean", "node .git/filter.cjs"]);
709 yield* fs.utimes(path.join(cwd, "stable"), 1_700_000_000, 1_700_000_000);
710 yield* git(["add", "."]);
711 yield* git(["commit", "-m", "inspection fixture"]);
712 if (indexMode === "flags") yield* git(["update-index", "--skip-worktree", "z-skipped"]);
713 if (indexMode === "sparse")
714 yield* git(["sparse-checkout", "set", "--cone", "--sparse-index", "included"]);
715 yield* fs.writeFileString(path.join(cwd, "z-skipped"), "modified\n");
716 yield* fs.writeFileString(path.join(cwd, ".git/reads"), "");
717 const originalIndex = yield* fs.readFile(path.join(cwd, ".git/index"));
718 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
719 Effect.provideService(VcsProcess.VcsProcess, {
720 run: (input) =>
721 liveProcess.run(
722 input.args.includes("ls-files")
723 ? {
724 ...input,
725 maxOutputBytes: 8,
726 onStdoutChunk: (chunk) => {
727 for (let i = 0; i < chunk.length; i += chunkSize)
728 input.onStdoutChunk?.(chunk.subarray(i, i + chunkSize));
729 },
730 }
731 : input,
732 ),
733 }),
734 );
735 yield* captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
736 assert.strictEqual((yield* git(["show", `${checkpointRef}:z-skipped`])).stdout, "modified\n");
737 if (indexMode !== "flags")
738 assert.strictEqual(yield* fs.readFileString(path.join(cwd, ".git/reads")), "");
739 assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git/index")), originalIndex);
740 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
741);
742
743it.effect.each([1_700_000_000, 1_700_000_000.9999])(
744 "checkpoint capture preserves same-size edits with racy index timestamps (%s)",
745 (timestamp) =>
746 Effect.gen(function* () {
747 const fileSystem = yield* FileSystem.FileSystem;
748 const path = yield* Path.Path;
749 const driver = yield* GitVcsDriver.makeVcsDriverShape();
750 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-racy-" });
751 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
752 const filePath = path.join(cwd, "file.txt");
753 const indexPath = path.join(cwd, ".git", "index");
754 yield* git(["config", "core.trustctime", "false"]);
755 yield* fileSystem.writeFileString(filePath, "before\n");
756 yield* fileSystem.utimes(filePath, timestamp, timestamp);
757 yield* git(["add", "file.txt"]);
758 yield* git(["commit", "-m", "record racy file"]);
759 yield* fileSystem.utimes(indexPath, timestamp, timestamp);
760 const originalIndex = yield* fileSystem.readFile(indexPath);
761 const originalIndexMtime = (yield* fileSystem.stat(indexPath)).mtime;
762 yield* fileSystem.writeFileString(filePath, "after!\n");
763 yield* fileSystem.utimes(filePath, timestamp, timestamp);
764
765 yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
766
767 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "after!\n");
768 assert.deepEqual(yield* fileSystem.readFile(indexPath), originalIndex);
769 assert.deepEqual((yield* fileSystem.stat(indexPath)).mtime, originalIndexMtime);
770 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
771);
772
773it.effect("checkpoint capture preserves racy edits made after resetting the index", () =>
774 Effect.gen(function* () {
775 const fileSystem = yield* FileSystem.FileSystem;
776 const path = yield* Path.Path;
777 const liveProcess = yield* VcsProcess.VcsProcess;
778 const driver = yield* GitVcsDriver.makeVcsDriverShape();
779 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-racy-reset-" });
780 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
781 const racyPath = path.join(cwd, "racy.txt");
782 const indexPath = path.join(cwd, ".git", "index");
783 const timestamp = 1_700_000_000;
784 yield* git(["config", "core.trustctime", "false"]);
785 yield* fileSystem.writeFileString(racyPath, "before\n");
786 yield* fileSystem.utimes(racyPath, timestamp, timestamp);
787 yield* git(["add", "."]);
788 yield* git(["commit", "-m", "record racy file"]);
789 yield* fileSystem.writeFileString(path.join(cwd, "file.txt"), "staged\n");
790 yield* git(["add", "file.txt"]);
791 yield* fileSystem.utimes(indexPath, timestamp, timestamp);
792 const originalIndex = yield* fileSystem.readFile(indexPath);
793 const originalIndexMtime = (yield* fileSystem.stat(indexPath)).mtime;
794 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
795 Effect.provideService(VcsProcess.VcsProcess, {
796 run: Effect.fn(function* (input: VcsProcess.VcsProcessInput) {
797 const result = yield* liveProcess.run(input);
798 if (input.args.includes("read-tree") && input.args.includes("--reset")) {
799 yield* fileSystem.writeFileString(racyPath, "after!\n").pipe(Effect.orDie);
800 yield* fileSystem.utimes(racyPath, timestamp, timestamp).pipe(Effect.orDie);
801 }
802 return result;
803 }),
804 }),
805 );
806
807 yield* captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
808
809 assert.strictEqual((yield* git(["show", `${checkpointRef}:racy.txt`])).stdout, "after!\n");
810 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "staged\n");
811 assert.deepEqual(yield* fileSystem.readFile(indexPath), originalIndex);
812 assert.deepEqual((yield* fileSystem.stat(indexPath)).mtime, originalIndexMtime);
813 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
814);
815
816it.effect.each(
817 [false, true].flatMap((nested) =>
818 (["normal", "flags", "split"] as const).map((indexMode) => ({ nested, indexMode })),
819 ),
820)(
821 "checkpoint index reuse preserves two turns (nested=$nested, index=$indexMode)",
822 ({ nested, indexMode }) =>
823 Effect.gen(function* () {
824 const fileSystem = yield* FileSystem.FileSystem;
825 const path = yield* Path.Path;
826 const driver = yield* GitVcsDriver.makeVcsDriverShape();
827 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-turns-" });
828 const { git } = yield* makeCheckpointFixture(driver, cwd);
829 const write = (name: string, contents: string) =>
830 fileSystem.writeFileString(path.join(cwd, name), contents);
831 yield* fileSystem.makeDirectory(path.join(cwd, "scope"));
832 for (const name of [
833 "scope/staged",
834 "scope/deleted",
835 "scope/assumed",
836 "scope/skipped",
837 "outside",
838 ]) {
839 yield* write(name, "original\n");
840 }
841 yield* git(["add", "."]);
842 yield* git(["commit", "-m", "initial scoped files"]);
843 yield* write("scope/staged", "staged\n");
844 yield* write("scope/new-deleted", "staged then deleted\n");
845 yield* write("outside", "staged outside\n");
846 yield* git(["add", "."]);
847 if (indexMode === "flags") {
848 yield* git(["update-index", "--assume-unchanged", "scope/assumed"]);
849 yield* git(["update-index", "--skip-worktree", "scope/skipped"]);
850 }
851 if (indexMode === "split") {
852 yield* git(["update-index", "--split-index"]);
853 }
854 const originalIndex = yield* fileSystem.readFile(path.join(cwd, ".git", "index"));
855 for (const name of ["scope/staged", "scope/assumed", "scope/skipped", "outside"]) {
856 yield* write(name, "working\n");
857 }
858 yield* write("scope/new", "first\n");
859 yield* fileSystem.remove(path.join(cwd, "scope/deleted"));
860 yield* fileSystem.remove(path.join(cwd, "scope/new-deleted"));
861 const captureCwd = nested ? path.join(cwd, "scope") : cwd;
862 const first = CheckpointRef.make("refs/t3/checkpoints/turns/1");
863 const second = CheckpointRef.make("refs/t3/checkpoints/turns/2");
864 yield* driver.checkpoints.captureCheckpoint({ cwd: captureCwd, checkpointRef: first });
865 for (const name of ["scope/staged", "scope/assumed", "scope/skipped"]) {
866 assert.strictEqual((yield* git(["show", `${first}:${name}`])).stdout, "working\n");
867 }
868 assert.strictEqual(
869 (yield* git(["show", `${first}:outside`])).stdout,
870 nested ? "original\n" : "working\n",
871 );
872 const files = (yield* git(["ls-tree", "-r", "--name-only", first])).stdout.split("\n");
873 assert.notInclude(files, "scope/deleted");
874 assert.notInclude(files, "scope/new-deleted");
875 assert.include(files, "scope/new");
876
877 yield* write("scope/staged", "second\n");
878 yield* fileSystem.remove(path.join(cwd, "scope/new"));
879 yield* write("scope/second", "added in second turn\n");
880 yield* driver.checkpoints.captureCheckpoint({ cwd: captureCwd, checkpointRef: second });
881 assert.strictEqual(
882 (yield* git(["diff", "--name-only", first, second])).stdout,
883 "scope/new\nscope/second\nscope/staged\n",
884 );
885 assert.strictEqual((yield* git(["show", `${second}:scope/staged`])).stdout, "second\n");
886 assert.strictEqual(
887 (yield* git(["show", `${second}:scope/second`])).stdout,
888 "added in second turn\n",
889 );
890 assert.deepEqual(yield* fileSystem.readFile(path.join(cwd, ".git", "index")), originalIndex);
891 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
892);
893
894it.effect.each(["missing", "invalid"] as const)(
895 "checkpoint capture falls back when the user index is %s",
896 (indexState) =>
897 Effect.gen(function* () {
898 const fileSystem = yield* FileSystem.FileSystem;
899 const path = yield* Path.Path;
900 const driver = yield* GitVcsDriver.makeVcsDriverShape();
901 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-index-" });
902 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
903 const indexPath = path.join(cwd, ".git", "index");
904 if (indexState === "missing") {
905 yield* fileSystem.remove(indexPath);
906 } else {
907 yield* fileSystem.writeFileString(indexPath, "invalid index");
908 }
909
910 yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
911
912 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "unstaged\n");
913 if (indexState === "missing") {
914 assert.isFalse(yield* fileSystem.exists(indexPath));
915 } else {
916 assert.strictEqual(yield* fileSystem.readFileString(indexPath), "invalid index");
917 }
918 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
919);
920
921it.effect("restores empty checkpoints without changing paths outside the workspace", () =>
922 Effect.gen(function* () {
923 const fileSystem = yield* FileSystem.FileSystem;
924 const path = yield* Path.Path;
925 const driver = yield* GitVcsDriver.makeVcsDriverShape();
926 for (const nested of [false, true]) {
927 const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-empty-checkpoint-" });
928 yield* runGit(root, ["init"]);
929 yield* runGit(root, ["config", "user.email", "test@test.com"]);
930 yield* runGit(root, ["config", "user.name", "Test"]);
931 if (nested) {
932 yield* fileSystem.writeFileString(path.join(root, "outside.txt"), "original\n");
933 yield* runGit(root, ["add", "."]);
934 }
935 yield* runGit(root, ["commit", "--allow-empty", "-m", "initial"]);
936 const cwd = nested ? path.join(root, "nested") : root;
937 yield* fileSystem.makeDirectory(cwd, { recursive: true });
938 const checkpointRef = CheckpointRef.make("refs/t3/checkpoints/empty");
939 yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
940 if (nested) {
941 yield* fileSystem.writeFileString(path.join(root, "outside.txt"), "changed\n");
942 yield* runGit(root, ["add", "outside.txt"]);
943 }
944 for (const staged of [false, true]) {
945 const addedPath = path.join(cwd, "added.txt");
946 yield* fileSystem.writeFileString(addedPath, "new\n");
947 if (staged) yield* runGit(cwd, ["add", "added.txt"]);
948 assert.isTrue(
949 yield* driver.checkpoints.restoreCheckpoint({
950 cwd,
951 checkpointRef,
952 fallbackToHead: false,
953 }),
954 );
955 assert.isTrue(yield* fileSystem.exists(cwd));
956 assert.isFalse(yield* fileSystem.exists(addedPath));
957 }
958 yield* fileSystem.writeFileString(
959 path.join(root, ".git", "info", "exclude"),
960 "ignored.txt\n",
961 );
962 yield* fileSystem.writeFileString(path.join(cwd, "ignored.txt"), "keep\n");
963 yield* fileSystem.makeDirectory(path.join(cwd, "untracked"));
964 yield* fileSystem.writeFileString(path.join(cwd, "untracked", "file.txt"), "remove\n");
965 assert.isTrue(
966 yield* driver.checkpoints.restoreCheckpoint({ cwd, checkpointRef, fallbackToHead: false }),
967 );
968 assert.strictEqual(yield* fileSystem.readFileString(path.join(cwd, "ignored.txt")), "keep\n");
969 assert.isFalse(yield* fileSystem.exists(path.join(cwd, "untracked")));
970 if (nested) {
971 assert.strictEqual(
972 yield* fileSystem.readFileString(path.join(root, "outside.txt")),
973 "changed\n",
974 );
975 const staged = yield* driver.execute({
976 operation: "test",
977 cwd: root,
978 args: ["diff", "--cached", "--name-only"],
979 });
980 assert.strictEqual(staged.stdout.trim(), "outside.txt");
981 }
982 }
983 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
984);
985
986// The real VCS process, spawning `command` wherever the driver runs git.
987const vcsProcessSpawning = (command: string) =>
988 Layer.effect(
989 VcsProcess.VcsProcess,
990 Effect.map(VcsProcess.make, (vcsProcess) =>
991 VcsProcess.VcsProcess.of({ run: (input) => vcsProcess.run({ ...input, command }) }),
992 ),
993 ).pipe(Layer.provide(ProcessRunner.layer), Layer.provideMerge(NodeServices.layer));
994
995it.effect("GitVcsDriver treats a missing git executable as outside any repository", () =>
996 Effect.gen(function* () {
997 const fileSystem = yield* FileSystem.FileSystem;
998 const path = yield* Path.Path;
999 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-missing-git-" });
1000 const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
1001 Effect.provide(vcsProcessSpawning(path.join(cwd, "git"))),
1002 );
1003
1004 assert.strictEqual(yield* driver.isInsideWorkTree(cwd), false);
1005 assert.strictEqual(yield* driver.detectRepository(cwd), null);
1006 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1007);
1008
1009it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
1010 "GitVcsDriver detects a repository whose path contains a newline",
1011 () =>
1012 Effect.gen(function* () {
1013 const fileSystem = yield* FileSystem.FileSystem;
1014 const path = yield* Path.Path;
1015 const parent = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-newline-repo-" });
1016 const cwd = path.join(parent, "multi\nline");
1017 yield* fileSystem.makeDirectory(cwd);
1018 yield* runGit(cwd, ["init"]);
1019 const driver = yield* GitVcsDriver.makeVcsDriverShape();
1020
1021 const repository = yield* driver.detectRepository(cwd);
1022 assert.strictEqual(repository?.rootPath, yield* fileSystem.realPath(cwd));
1023 assert.strictEqual(repository?.metadataPath, ".git");
1024 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
1025);
1026
1027it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
1028 "GitVcsDriver still fails detection when git exists but cannot be spawned",
1029 () =>
1030 Effect.gen(function* () {
1031 const fileSystem = yield* FileSystem.FileSystem;
1032 // A file without the execute bit fails to spawn with a permission error.
1033 const notExecutable = yield* fileSystem.makeTempFileScoped({ prefix: "t3-git-" });
1034 const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
1035 Effect.provide(vcsProcessSpawning(notExecutable)),
1036 );
1037
1038 const error = yield* driver.isInsideWorkTree(process.cwd()).pipe(Effect.flip);
1039 assert.strictEqual(error._tag, "VcsProcessSpawnError");
1040 const detectionError = yield* driver.detectRepository(process.cwd()).pipe(Effect.flip);
1041 assert.strictEqual(detectionError._tag, "VcsProcessSpawnError");
1042 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1043);
1044
1045const gitCommandCount = (operation: string, outcome: string) =>
1046 Metric.value(
1047 Metric.withAttributes(gitCommandsTotal, [
1048 ["operation", operation],
1049 ["outcome", outcome],
1050 ]),
1051 ).pipe(Effect.map((state) => state.count));
1052
1053const gitCommandTiming = (operation: string) =>
1054 Metric.value(Metric.withAttributes(gitCommandDuration, [["operation", operation]]));
1055
1056// Keep VcsProcess's exit classification; replace only the subprocess and its clock.
1057const makeMeteredDriver = Effect.fn("test.makeMeteredDriver")(function* (exitCode: number) {
1058 const process = yield* VcsProcess.make.pipe(
1059 Effect.provideService(ProcessRunner.ProcessRunner, {
1060 run: () =>
1061 TestClock.adjust("250 millis").pipe(
1062 Effect.as({
1063 code: ChildProcessSpawner.ExitCode(exitCode),
1064 stdout: "git output",
1065 stderr: exitCode === 0 ? "" : "fatal: test failure",
1066 timedOut: false,
1067 stdoutTruncated: false,
1068 stderrTruncated: false,
1069 stdoutInvalidUtf8: false,
1070 stderrInvalidUtf8: false,
1071 }),
1072 ),
1073 }),
1074 );
1075 return yield* GitVcsDriver.makeVcsDriverShape().pipe(
1076 Effect.provideService(VcsProcess.VcsProcess, process),
1077 );
1078});
1079
1080it.effect("GitVcsDriver meters each git command once under its operation", () =>
1081 Effect.gen(function* () {
1082 const operation = "GitVcsDriver.checkpoints.resolveHeadCommit";
1083 const driver = yield* makeMeteredDriver(0);
1084
1085 const result = yield* driver.execute({ operation, cwd: "/repo", args: ["rev-parse", "HEAD"] });
1086 yield* driver.execute({ operation, cwd: "/another-repo", args: ["rev-parse", "other-ref"] });
1087
1088 assert.strictEqual(result.stdout, "git output");
1089 assert.strictEqual(yield* gitCommandCount(operation, "success"), 2);
1090 assert.strictEqual(yield* gitCommandCount(operation, "failure"), 0);
1091 const timing = yield* gitCommandTiming(operation);
1092 assert.strictEqual(timing.count, 2);
1093 assert.strictEqual(timing.sum, 500);
1094 }).pipe(
1095 Effect.provide(NodeServices.layer),
1096 Effect.provideService(Metric.MetricRegistry, new Map()),
1097 ),
1098);
1099
1100it.effect("GitVcsDriver counts an allowed non-zero exit as a success", () =>
1101 Effect.gen(function* () {
1102 const operation = "GitVcsDriver.checkpoints.hasHeadCommit";
1103 const driver = yield* makeMeteredDriver(1);
1104
1105 const result = yield* driver.execute({
1106 operation,
1107 cwd: "/repo",
1108 args: ["rev-parse", "--verify", "HEAD"],
1109 allowNonZeroExit: true,
1110 });
1111
1112 assert.strictEqual(result.exitCode, 1);
1113 assert.strictEqual(yield* gitCommandCount(operation, "success"), 1);
1114 assert.strictEqual(yield* gitCommandCount(operation, "failure"), 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 ),
1122);
1123
1124it.effect("GitVcsDriver counts a failed git command as a failure", () =>
1125 Effect.gen(function* () {
1126 const operation = "GitVcsDriver.checkpoints.resolveHeadCommit";
1127 const driver = yield* makeMeteredDriver(128);
1128
1129 const error = yield* driver
1130 .execute({ operation, cwd: "/repo", args: ["rev-parse", "HEAD"] })
1131 .pipe(Effect.flip);
1132
1133 assert.strictEqual(error._tag, "VcsProcessExitError");
1134 assert.strictEqual(yield* gitCommandCount(operation, "failure"), 1);
1135 assert.strictEqual(yield* gitCommandCount(operation, "success"), 0);
1136 const timing = yield* gitCommandTiming(operation);
1137 assert.strictEqual(timing.count, 1);
1138 assert.strictEqual(timing.sum, 250);
1139 }).pipe(
1140 Effect.provide(NodeServices.layer),
1141 Effect.provideService(Metric.MetricRegistry, new Map()),
1142 ),
1143);
1144
1145it.effect("checkpoint capture meters every git process it starts, including streamed ones", () =>
1146 Effect.gen(function* () {
1147 const fileSystem = yield* FileSystem.FileSystem;
1148 const liveProcess = yield* VcsProcess.VcsProcess;
1149 const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION;
1150 let started = 0;
1151 let streamed = 0;
1152 const driver = yield* GitVcsDriver.makeVcsDriverShape();
1153 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
1154 Effect.provideService(VcsProcess.VcsProcess, {
1155 run: (input) => {
1156 if (input.operation === operation) {
1157 started++;
1158 if (input.onStdoutChunk !== undefined) streamed++;
1159 }
1160 return liveProcess.run(input);
1161 },
1162 }),
1163 );
1164 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-metrics-" });
1165 const { checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
1166
1167 yield* captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
1168
1169 assert.isAbove(streamed, 0);
1170 assert.strictEqual(yield* gitCommandCount(operation, "success"), started);
1171 assert.strictEqual(yield* gitCommandCount(operation, "failure"), 0);
1172 assert.strictEqual((yield* gitCommandTiming(operation)).count, started);
1173 }).pipe(
1174 Effect.scoped,
1175 Effect.provide(layerGitContract),
1176 Effect.provideService(Metric.MetricRegistry, new Map()),
1177 ),
1178);
1179
1180it.effect("git metrics finalize cancellation without exposing arbitrary operation labels", () =>
1181 Effect.gen(function* () {
1182 const started = yield* Deferred.make<void>();
1183 const process = yield* VcsProcess.make.pipe(
1184 Effect.provideService(ProcessRunner.ProcessRunner, {
1185 run: () => Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never)),
1186 }),
1187 );
1188 const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
1189 Effect.provideService(VcsProcess.VcsProcess, process),
1190 );
1191 const operation = "arbitrary operation /private/path";
1192 const fiber = yield* driver
1193 .execute({ operation, cwd: "/repo", args: ["rev-parse", "HEAD"] })
1194 .pipe(Effect.forkChild);
1195 yield* Deferred.await(started);
1196 yield* TestClock.adjust("250 millis");
1197 yield* Fiber.interrupt(fiber);
1198
1199 assert.strictEqual(yield* gitCommandCount("other", "interrupt"), 1);
1200 assert.strictEqual(yield* gitCommandCount(operation, "interrupt"), 0);
1201 const timing = yield* gitCommandTiming("other");
1202 assert.strictEqual(timing.count, 1);
1203 assert.strictEqual(timing.sum, 250);
1204 }).pipe(
1205 Effect.provide(NodeServices.layer),
1206 Effect.provideService(Metric.MetricRegistry, new Map()),
1207 ),
1208);
1209
1210it.effect("git metrics count fsync fallback and transient retry subprocesses separately", () =>
1211 Effect.gen(function* () {
1212 const retryReady = yield* Deferred.make<void>();
1213 const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION;
1214 let attempts = 0;
1215 const process = yield* VcsProcess.make.pipe(
1216 Effect.provideService(HostProcess.Platform, "darwin"),
1217 Effect.provideService(ProcessRunner.ProcessRunner, {
1218 run: (input) =>
1219 Effect.gen(function* () {
1220 attempts++;
1221 yield* TestClock.adjust("250 millis");
1222 if (attempts === 2) {
1223 assert.include(input.args, "core.fsyncMethod=writeout-only");
1224 yield* Deferred.succeed(retryReady, undefined);
1225 }
1226 return {
1227 code: ChildProcessSpawner.ExitCode(attempts < 3 ? 128 : 0),
1228 stdout: "",
1229 stderr:
1230 attempts === 1
1231 ? "fatal: fsync error on '.git/objects/test': Operation not supported"
1232 : attempts === 2
1233 ? "fatal: Unable to create '/repo/.git/index.lock': File exists."
1234 : "",
1235 timedOut: false,
1236 stdoutTruncated: false,
1237 stderrTruncated: false,
1238 stdoutInvalidUtf8: false,
1239 stderrInvalidUtf8: false,
1240 };
1241 }),
1242 }),
1243 );
1244 const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
1245 Effect.provideService(VcsProcess.VcsProcess, process),
1246 );
1247 const fiber = yield* driver
1248 .execute({ operation, cwd: "/repo", args: ["-c", "core.fsyncMethod=batch", "add"] })
1249 .pipe(Effect.forkChild);
1250 yield* Deferred.await(retryReady);
1251 yield* TestClock.adjust("75 millis");
1252 yield* Fiber.join(fiber);
1253
1254 assert.strictEqual(attempts, 3);
1255 assert.strictEqual(yield* gitCommandCount(operation, "failure"), 2);
1256 assert.strictEqual(yield* gitCommandCount(operation, "success"), 1);
1257 const timing = yield* gitCommandTiming(operation);
1258 assert.strictEqual(timing.count, 3);
1259 assert.strictEqual(timing.sum, 750);
1260 }).pipe(
1261 Effect.provide(NodeServices.layer),
1262 Effect.provideService(Metric.MetricRegistry, new Map()),
1263 ),
1264);