Open History to see the last commit
1import * as NodeCrypto from "node:crypto";
2
3import * as Context from "effect/Context";
4import * as DateTime from "effect/DateTime";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as Path from "effect/Path";
10import { ChildProcessSpawner } from "effect/unstable/process";
11
12import {
13 GitCommandError,
14 VcsProcessExitError,
15 type VcsSwitchRefInput,
16 type VcsSwitchRefResult,
17 type VcsCreateRefInput,
18 type VcsCreateRefResult,
19 type VcsCreateWorktreeInput,
20 type VcsCreateWorktreeResult,
21 type ReviewDiffPreviewInput,
22 type ReviewDiffPreviewResult,
23 type ReviewDiffFileContentsInput,
24 type ReviewDiffFileContentsResult,
25 type VcsInitInput,
26 type VcsListRefsInput,
27 type VcsListRefsResult,
28 type VcsPullResult,
29 type VcsRemoveWorktreeInput,
30 type VcsStatusInput,
31 type VcsStatusResult,
32} from "@t3tools/contracts";
33import { makeGitVcsDriverCore } from "./GitVcsDriverCore.ts";
34import * as VcsDriver from "./VcsDriver.ts";
35import * as VcsProcess from "./VcsProcess.ts";
36
37export interface ExecuteGitInput {
38 readonly operation: string;
39 readonly cwd: string;
40 readonly args: ReadonlyArray<string>;
41 readonly stdin?: string;
42 readonly env?: NodeJS.ProcessEnv;
43 readonly allowNonZeroExit?: boolean;
44 readonly timeoutMs?: number | null;
45 readonly maxOutputBytes?: number;
46 readonly appendTruncationMarker?: boolean;
47 readonly progress?: ExecuteGitProgress;
48}
49
50export interface ExecuteGitResult {
51 readonly exitCode: ChildProcessSpawner.ExitCode;
52 readonly stdout: string;
53 readonly stderr: string;
54 readonly stdoutTruncated: boolean;
55 readonly stderrTruncated: boolean;
56}
57
58export interface GitStatusDetails {
59 isRepo: boolean;
60 sourceControlProvider?: VcsStatusResult["sourceControlProvider"];
61 hasOriginRemote: boolean;
62 isDefaultBranch: boolean;
63 branch: string | null;
64 upstreamRef: string | null;
65 hasWorkingTreeChanges: boolean;
66 workingTree: VcsStatusResult["workingTree"];
67 hasUpstream: boolean;
68 aheadCount: number;
69 behindCount: number;
70 aheadOfDefaultCount: number;
71}
72
73export interface GitRemoteStatusDetails {
74 isRepo: boolean;
75 defaultBranch: string | null;
76 isDefaultBranch: boolean;
77 branch: string | null;
78 upstreamRef: string | null;
79 hasUpstream: boolean;
80 aheadCount: number;
81 behindCount: number;
82 aheadOfDefaultCount: number;
83}
84
85export interface GitPreparedCommitContext {
86 stagedSummary: string;
87 stagedPatch: string;
88}
89
90export interface ExecuteGitProgress {
91 readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;
92 readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;
93 readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
94 readonly onHookFinished?: (input: {
95 hookName: string;
96 exitCode: number | null;
97 durationMs: number | null;
98 }) => Effect.Effect<void, never>;
99}
100
101export interface GitCommitProgress {
102 readonly onOutputLine?: (input: {
103 stream: "stdout" | "stderr";
104 text: string;
105 }) => Effect.Effect<void, never>;
106 readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
107 readonly onHookFinished?: (input: {
108 hookName: string;
109 exitCode: number | null;
110 durationMs: number | null;
111 }) => Effect.Effect<void, never>;
112}
113
114export interface GitCommitOptions {
115 readonly timeoutMs?: number;
116 readonly progress?: GitCommitProgress;
117}
118
119export interface GitPushResult {
120 status: "pushed" | "skipped_up_to_date";
121 branch: string;
122 upstreamBranch?: string | undefined;
123 setUpstream?: boolean | undefined;
124}
125
126export interface GitRangeContext {
127 commitSummary: string;
128 diffSummary: string;
129 diffPatch: string;
130}
131
132export interface GitRenameBranchInput {
133 cwd: string;
134 oldBranch: string;
135 newBranch: string;
136}
137
138export interface GitRenameBranchResult {
139 branch: string;
140}
141
142export interface GitFetchPullRequestBranchInput {
143 cwd: string;
144 prNumber: number;
145 branch: string;
146}
147
148export interface GitFetchPullRequestHeadCommitInput {
149 cwd: string;
150 prNumber: number;
151}
152
153export interface GitResolveCommitInput {
154 cwd: string;
155 revision: string;
156}
157
158export interface GitResolveCommitResult {
159 commitSha: string;
160}
161
162export interface GitRefreshCheckedOutBranchInput {
163 cwd: string;
164 targetCommit: string;
165 /**
166 * Commit the checkout is allowed to be hard-reset away from: the upstream commit read before
167 * the fetch. HEAD sitting there means the checkout holds no work of its own.
168 */
169 resetWhenHeadCommit?: string | null | undefined;
170}
171
172export interface GitRefreshCheckedOutBranchResult {
173 headCommit: string;
174 moved: boolean;
175 onTarget: boolean;
176}
177
178export interface GitEnsureRemoteInput {
179 cwd: string;
180 preferredName: string;
181 url: string;
182}
183
184export interface GitFetchRemoteBranchInput {
185 cwd: string;
186 remoteName: string;
187 remoteBranch: string;
188 localBranch: string;
189}
190
191export interface GitFetchRemoteTrackingBranchInput {
192 cwd: string;
193 remoteName: string;
194 remoteBranch: string;
195}
196
197export interface GitFetchRemoteInput {
198 cwd: string;
199 remoteName: string;
200}
201
202export interface GitRemoteExistsInput {
203 cwd: string;
204 remoteName: string;
205}
206
207export interface GitResolveRemoteTrackingCommitInput {
208 cwd: string;
209 refName: string;
210 fallbackRemoteName: string;
211}
212
213export interface GitResolveRemoteTrackingCommitResult {
214 commitSha: string;
215 remoteRefName: string;
216}
217
218export interface GitSetBranchUpstreamInput {
219 cwd: string;
220 branch: string;
221 remoteName: string;
222 remoteBranch: string;
223}
224
225export interface GitRemoteStatusOptions {
226 readonly refreshUpstream?: boolean;
227}
228
229export class GitVcsDriver extends Context.Service<
230 GitVcsDriver,
231 {
232 readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
233 readonly status: (input: VcsStatusInput) => Effect.Effect<VcsStatusResult, GitCommandError>;
234 readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
235 readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
236 readonly statusDetailsRemote: (
237 cwd: string,
238 options?: GitRemoteStatusOptions,
239 ) => Effect.Effect<GitRemoteStatusDetails, GitCommandError>;
240 readonly prepareCommitContext: (
241 cwd: string,
242 filePaths?: readonly string[],
243 ) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
244 readonly commit: (
245 cwd: string,
246 subject: string,
247 body: string,
248 options?: GitCommitOptions,
249 ) => Effect.Effect<{ commitSha: string }, GitCommandError>;
250 readonly pushCurrentBranch: (
251 cwd: string,
252 fallbackBranch: string | null,
253 options?: { readonly remoteName?: string | null },
254 ) => Effect.Effect<GitPushResult, GitCommandError>;
255 readonly readRangeContext: (
256 cwd: string,
257 baseRef: string,
258 ) => Effect.Effect<GitRangeContext, GitCommandError>;
259 readonly getReviewDiffPreview: (
260 input: ReviewDiffPreviewInput,
261 ) => Effect.Effect<ReviewDiffPreviewResult, GitCommandError>;
262 readonly getReviewDiffFileContents: (
263 input: ReviewDiffFileContentsInput,
264 ) => Effect.Effect<ReviewDiffFileContentsResult, GitCommandError>;
265 readonly readConfigValue: (
266 cwd: string,
267 key: string,
268 ) => Effect.Effect<string | null, GitCommandError>;
269 readonly listRefs: (
270 input: VcsListRefsInput,
271 ) => Effect.Effect<VcsListRefsResult, GitCommandError>;
272 readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
273 readonly createWorktree: (
274 input: VcsCreateWorktreeInput,
275 ) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
276 readonly fetchPullRequestBranch: (
277 input: GitFetchPullRequestBranchInput,
278 ) => Effect.Effect<void, GitCommandError>;
279 /** Fetches `refs/pull/<n>/head` without writing a branch, for heads that exist nowhere else. */
280 readonly fetchPullRequestHeadCommit: (
281 input: GitFetchPullRequestHeadCommitInput,
282 ) => Effect.Effect<GitResolveCommitResult, GitCommandError>;
283 readonly resolveCommit: (
284 input: GitResolveCommitInput,
285 ) => Effect.Effect<GitResolveCommitResult, GitCommandError>;
286 /** Moves the branch checked out in `cwd` onto `targetCommit`, from inside that worktree. */
287 readonly refreshCheckedOutBranch: (
288 input: GitRefreshCheckedOutBranchInput,
289 ) => Effect.Effect<GitRefreshCheckedOutBranchResult, GitCommandError>;
290 readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
291 readonly resolvePrimaryRemoteName: (cwd: string) => Effect.Effect<string, GitCommandError>;
292 readonly fetchRemote: (input: GitFetchRemoteInput) => Effect.Effect<void, GitCommandError>;
293 readonly remoteExists: (input: GitRemoteExistsInput) => Effect.Effect<boolean, GitCommandError>;
294 readonly resolveRemoteTrackingCommit: (
295 input: GitResolveRemoteTrackingCommitInput,
296 ) => Effect.Effect<GitResolveRemoteTrackingCommitResult, GitCommandError>;
297 readonly fetchRemoteBranch: (
298 input: GitFetchRemoteBranchInput,
299 ) => Effect.Effect<void, GitCommandError>;
300 readonly fetchRemoteTrackingBranch: (
301 input: GitFetchRemoteTrackingBranchInput,
302 ) => Effect.Effect<void, GitCommandError>;
303 readonly setBranchUpstream: (
304 input: GitSetBranchUpstreamInput,
305 ) => Effect.Effect<void, GitCommandError>;
306 readonly removeWorktree: (
307 input: VcsRemoveWorktreeInput,
308 ) => Effect.Effect<void, GitCommandError>;
309 readonly renameBranch: (
310 input: GitRenameBranchInput,
311 ) => Effect.Effect<GitRenameBranchResult, GitCommandError>;
312 readonly createRef: (
313 input: VcsCreateRefInput,
314 ) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
315 readonly switchRef: (
316 input: VcsSwitchRefInput,
317 ) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
318 readonly initRepo: (input: VcsInitInput) => Effect.Effect<void, GitCommandError>;
319 readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
320 }
321>()("t3/vcs/GitVcsDriver") {}
322
323const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
324const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
325const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
326const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [
327 "-c",
328 "core.fsmonitor=false",
329 "-c",
330 "core.untrackedCache=false",
331] as const;
332
333const nowFreshness = Effect.fn("GitVcsDriver.nowFreshness")(function* () {
334 const now = yield* DateTime.now;
335 return {
336 source: "live-local" as const,
337 observedAt: now,
338 expiresAt: Option.none(),
339 };
340});
341
342function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
343 const parts = input.split("\0");
344 if (parts.length === 0) return [];
345
346 if (truncated && parts[parts.length - 1]?.length) {
347 parts.pop();
348 }
349
350 return parts.filter((value) => value.length > 0);
351}
352
353function chunkPathsForGitCheckIgnore(relativePaths: ReadonlyArray<string>): string[][] {
354 const chunks: string[][] = [];
355 let chunk: string[] = [];
356 let chunkBytes = 0;
357
358 for (const relativePath of relativePaths) {
359 const relativePathBytes = Buffer.byteLength(relativePath) + 1;
360 if (chunk.length > 0 && chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
361 chunks.push(chunk);
362 chunk = [];
363 chunkBytes = 0;
364 }
365
366 chunk.push(relativePath);
367 chunkBytes += relativePathBytes;
368
369 if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
370 chunks.push(chunk);
371 chunk = [];
372 chunkBytes = 0;
373 }
374 }
375
376 if (chunk.length > 0) {
377 chunks.push(chunk);
378 }
379
380 return chunks;
381}
382
383function parseGitRemoteVerboseOutput(
384 output: string,
385): Map<string, { url?: string; pushUrl?: string }> {
386 const remotes = new Map<string, { url?: string; pushUrl?: string }>();
387 for (const line of output.split("\n")) {
388 const trimmed = line.trim();
389 if (trimmed.length === 0) {
390 continue;
391 }
392
393 const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed);
394 if (!match) {
395 continue;
396 }
397
398 const name = match[1];
399 const url = match[2];
400 const direction = match[3];
401 if (!name || !url || !direction) {
402 continue;
403 }
404 const remote = remotes.get(name) ?? {};
405 if (direction === "fetch") {
406 remote.url = url;
407 } else {
408 remote.pushUrl = url;
409 }
410 remotes.set(name, remote);
411 }
412 return remotes;
413}
414
415const gitCommand = (
416 process: VcsProcess.VcsProcess["Service"],
417 operation: string,
418 cwd: string,
419 args: ReadonlyArray<string>,
420 options?: {
421 readonly stdin?: string;
422 readonly env?: NodeJS.ProcessEnv;
423 readonly allowNonZeroExit?: boolean;
424 readonly timeoutMs?: number;
425 readonly maxOutputBytes?: number;
426 readonly appendTruncationMarker?: boolean;
427 },
428) =>
429 process.run({
430 operation,
431 command: "git",
432 args: ["-C", cwd, ...args],
433 cwd,
434 spawnCwd: globalThis.process.cwd(),
435 ...(options?.stdin !== undefined ? { stdin: options.stdin } : {}),
436 ...(options?.env !== undefined ? { env: options.env } : {}),
437 ...(options?.allowNonZeroExit !== undefined
438 ? { allowNonZeroExit: options.allowNonZeroExit }
439 : {}),
440 ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
441 ...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
442 ...(options?.appendTruncationMarker !== undefined
443 ? { appendTruncationMarker: options.appendTruncationMarker }
444 : {}),
445 });
446
447export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* () {
448 const fileSystem = yield* FileSystem.FileSystem;
449 const path = yield* Path.Path;
450 const vcsProcess = yield* VcsProcess.VcsProcess;
451 const capabilities = {
452 kind: "git" as const,
453 supportsWorktrees: true,
454 supportsBookmarks: false,
455 supportsAtomicSnapshot: false,
456 supportsPushDefaultRemote: true,
457 ignoreClassifier: "native" as const,
458 };
459
460 const isInsideWorkTree: VcsDriver.VcsDriver["Service"]["isInsideWorkTree"] = (cwd) =>
461 gitCommand(
462 vcsProcess,
463 "GitVcsDriver.isInsideWorkTree",
464 cwd,
465 ["rev-parse", "--is-inside-work-tree"],
466 {
467 allowNonZeroExit: true,
468 timeoutMs: 5_000,
469 maxOutputBytes: 4_096,
470 },
471 ).pipe(Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"));
472
473 const execute: VcsDriver.VcsDriver["Service"]["execute"] = (input) =>
474 gitCommand(vcsProcess, input.operation, input.cwd, input.args, {
475 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
476 ...(input.env !== undefined ? { env: input.env } : {}),
477 ...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}),
478 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
479 ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
480 ...(input.appendTruncationMarker !== undefined
481 ? { appendTruncationMarker: input.appendTruncationMarker }
482 : {}),
483 });
484
485 const detectRepository: VcsDriver.VcsDriver["Service"]["detectRepository"] = Effect.fn(
486 "detectRepository",
487 )(function* (cwd) {
488 if (!(yield* isInsideWorkTree(cwd))) {
489 return null;
490 }
491
492 const root = yield* gitCommand(vcsProcess, "GitVcsDriver.detectRepository.root", cwd, [
493 "rev-parse",
494 "--show-toplevel",
495 ]);
496 const gitCommonDir = yield* gitCommand(
497 vcsProcess,
498 "GitVcsDriver.detectRepository.commonDir",
499 cwd,
500 ["rev-parse", "--git-common-dir"],
501 ).pipe(Effect.orElseSucceed(() => null));
502
503 return {
504 kind: "git" as const,
505 rootPath: root.stdout.trim(),
506 metadataPath: gitCommonDir?.stdout.trim() || null,
507 freshness: yield* nowFreshness(),
508 };
509 });
510
511 const listWorkspaceFiles: VcsDriver.VcsDriver["Service"]["listWorkspaceFiles"] = (cwd) =>
512 gitCommand(
513 vcsProcess,
514 "GitVcsDriver.listWorkspaceFiles",
515 cwd,
516 [
517 ...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
518 "ls-files",
519 "--cached",
520 "--others",
521 "--exclude-standard",
522 "-z",
523 ],
524 {
525 allowNonZeroExit: true,
526 timeoutMs: 20_000,
527 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
528 appendTruncationMarker: true,
529 },
530 ).pipe(
531 Effect.flatMap((result) =>
532 result.exitCode === 0
533 ? Effect.gen(function* () {
534 const freshness = yield* nowFreshness();
535 return {
536 paths: splitNullSeparatedPaths(result.stdout, result.stdoutTruncated),
537 truncated: result.stdoutTruncated,
538 freshness,
539 };
540 })
541 : Effect.fail(
542 new VcsProcessExitError({
543 operation: "GitVcsDriver.listWorkspaceFiles",
544 command: "git ls-files",
545 cwd,
546 exitCode: result.exitCode,
547 detail: result.stderr.trim() || "git ls-files failed",
548 }),
549 ),
550 ),
551 );
552
553 const listRemotes: VcsDriver.VcsDriver["Service"]["listRemotes"] = Effect.fn("listRemotes")(
554 function* (cwd) {
555 const result = yield* gitCommand(
556 vcsProcess,
557 "GitVcsDriver.listRemotes",
558 cwd,
559 ["remote", "-v"],
560 {
561 allowNonZeroExit: true,
562 timeoutMs: 5_000,
563 maxOutputBytes: 64 * 1024,
564 },
565 );
566
567 if (result.exitCode !== 0) {
568 return yield* new VcsProcessExitError({
569 operation: "GitVcsDriver.listRemotes",
570 command: "git remote -v",
571 cwd,
572 exitCode: result.exitCode,
573 detail: result.stderr.trim() || "git remote -v failed",
574 });
575 }
576
577 const parsed = parseGitRemoteVerboseOutput(result.stdout);
578 const remotes = Array.from(parsed.entries()).flatMap(([name, remote]) => {
579 if (!remote.url) {
580 return [];
581 }
582 return [
583 {
584 name,
585 url: remote.url,
586 pushUrl: remote.pushUrl ? Option.some(remote.pushUrl) : Option.none(),
587 isPrimary: name === "origin",
588 },
589 ];
590 });
591
592 return {
593 remotes,
594 freshness: yield* nowFreshness(),
595 };
596 },
597 );
598
599 const filterIgnoredPaths: VcsDriver.VcsDriver["Service"]["filterIgnoredPaths"] = Effect.fn(
600 "filterIgnoredPaths",
601 )(function* (cwd, relativePaths) {
602 if (relativePaths.length === 0) {
603 return relativePaths;
604 }
605
606 const ignoredPaths = new Set<string>();
607 const chunks = chunkPathsForGitCheckIgnore(relativePaths);
608
609 for (const chunk of chunks) {
610 const result = yield* gitCommand(
611 vcsProcess,
612 "GitVcsDriver.filterIgnoredPaths",
613 cwd,
614 [...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
615 {
616 stdin: `${chunk.join("\0")}\0`,
617 allowNonZeroExit: true,
618 timeoutMs: 20_000,
619 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
620 appendTruncationMarker: true,
621 },
622 );
623
624 if (result.exitCode !== 0 && result.exitCode !== 1) {
625 return yield* new VcsProcessExitError({
626 operation: "GitVcsDriver.filterIgnoredPaths",
627 command: "git check-ignore",
628 cwd,
629 exitCode: result.exitCode,
630 detail: result.stderr.trim() || "git check-ignore failed",
631 });
632 }
633
634 for (const ignoredPath of splitNullSeparatedPaths(result.stdout, result.stdoutTruncated)) {
635 ignoredPaths.add(ignoredPath);
636 }
637 }
638
639 if (ignoredPaths.size === 0) {
640 return relativePaths;
641 }
642
643 return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
644 });
645
646 const initRepository: VcsDriver.VcsDriver["Service"]["initRepository"] = (input) =>
647 gitCommand(vcsProcess, "GitVcsDriver.initRepository", input.cwd, ["init"], {
648 timeoutMs: 10_000,
649 maxOutputBytes: 64 * 1024,
650 }).pipe(Effect.asVoid);
651
652 const resolveHeadCommit = (cwd: string) =>
653 execute({
654 operation: "GitVcsDriver.checkpoints.resolveHeadCommit",
655 cwd,
656 args: ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
657 allowNonZeroExit: true,
658 }).pipe(
659 Effect.map((result) => {
660 if (result.exitCode !== 0) {
661 return null;
662 }
663 const commit = result.stdout.trim();
664 return commit.length > 0 ? commit : null;
665 }),
666 );
667
668 const hasHeadCommit = (cwd: string) =>
669 execute({
670 operation: "GitVcsDriver.checkpoints.hasHeadCommit",
671 cwd,
672 args: ["rev-parse", "--verify", "HEAD"],
673 allowNonZeroExit: true,
674 }).pipe(Effect.map((result) => result.exitCode === 0));
675
676 const resolveCheckpointCommit = (cwd: string, checkpointRef: string) =>
677 execute({
678 operation: "GitVcsDriver.checkpoints.resolveCheckpointCommit",
679 cwd,
680 args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`],
681 allowNonZeroExit: true,
682 }).pipe(
683 Effect.map((result) => {
684 if (result.exitCode !== 0) {
685 return null;
686 }
687 const commit = result.stdout.trim();
688 return commit.length > 0 ? commit : null;
689 }),
690 );
691
692 const resolveGitCommonDir = (cwd: string) =>
693 Effect.gen(function* () {
694 const result = yield* execute({
695 operation: "GitVcsDriver.checkpoints.resolveGitCommonDir",
696 cwd,
697 args: ["rev-parse", "--git-common-dir"],
698 });
699 const gitCommonDir = result.stdout.trim();
700 return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
701 });
702
703 const checkpoints: VcsDriver.VcsCheckpointOps = {
704 captureCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureCheckpoint")(function* (input) {
705 const operation = "GitVcsDriver.checkpoints.captureCheckpoint";
706 const gitCommonDir = yield* resolveGitCommonDir(input.cwd);
707 const tempIndexPath = path.join(
708 gitCommonDir,
709 `t3-checkpoint-index-${NodeCrypto.randomUUID()}`,
710 );
711 const commitEnv: NodeJS.ProcessEnv = {
712 ...process.env,
713 GIT_INDEX_FILE: tempIndexPath,
714 GIT_AUTHOR_NAME: "T3 Code",
715 GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com",
716 GIT_COMMITTER_NAME: "T3 Code",
717 GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com",
718 };
719
720 const cleanupTempIndex = fileSystem
721 .remove(tempIndexPath, { force: true })
722 .pipe(Effect.ignore);
723
724 yield* Effect.gen(function* () {
725 const headExists = yield* hasHeadCommit(input.cwd);
726 if (headExists) {
727 yield* execute({
728 operation,
729 cwd: input.cwd,
730 args: ["read-tree", "HEAD"],
731 env: commitEnv,
732 });
733 }
734
735 yield* execute({
736 operation,
737 cwd: input.cwd,
738 args: ["add", "-A", "--", "."],
739 env: commitEnv,
740 });
741
742 const writeTreeResult = yield* execute({
743 operation,
744 cwd: input.cwd,
745 args: ["write-tree"],
746 env: commitEnv,
747 });
748 const treeOid = writeTreeResult.stdout.trim();
749 if (treeOid.length === 0) {
750 return yield* new VcsProcessExitError({
751 operation,
752 command: "git write-tree",
753 cwd: input.cwd,
754 exitCode: 0,
755 detail: "git write-tree returned an empty tree oid.",
756 });
757 }
758
759 const message = `t3 checkpoint ref=${input.checkpointRef}`;
760 const commitTreeResult = yield* execute({
761 operation,
762 cwd: input.cwd,
763 args: ["commit-tree", treeOid, "-m", message],
764 env: commitEnv,
765 });
766 const commitOid = commitTreeResult.stdout.trim();
767 if (commitOid.length === 0) {
768 return yield* new VcsProcessExitError({
769 operation,
770 command: "git commit-tree",
771 cwd: input.cwd,
772 exitCode: 0,
773 detail: "git commit-tree returned an empty commit oid.",
774 });
775 }
776
777 yield* execute({
778 operation,
779 cwd: input.cwd,
780 args: ["update-ref", input.checkpointRef, commitOid],
781 });
782 }).pipe(Effect.ensuring(cleanupTempIndex));
783 }),
784
785 hasCheckpointRef: (input) =>
786 resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
787 Effect.map((commit) => commit !== null),
788 ),
789
790 restoreCheckpoint: Effect.fn("GitVcsDriver.checkpoints.restoreCheckpoint")(function* (input) {
791 const operation = "GitVcsDriver.checkpoints.restoreCheckpoint";
792
793 let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
794
795 if (!commitOid && input.fallbackToHead === true) {
796 commitOid = yield* resolveHeadCommit(input.cwd);
797 }
798
799 if (!commitOid) {
800 return false;
801 }
802
803 yield* execute({
804 operation,
805 cwd: input.cwd,
806 args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
807 });
808 yield* execute({
809 operation,
810 cwd: input.cwd,
811 args: ["clean", "-fd", "--", "."],
812 });
813
814 const headExists = yield* hasHeadCommit(input.cwd);
815 if (headExists) {
816 yield* execute({
817 operation,
818 cwd: input.cwd,
819 args: ["reset", "--quiet", "--", "."],
820 });
821 }
822
823 return true;
824 }),
825
826 diffCheckpoints: Effect.fn("GitVcsDriver.checkpoints.diffCheckpoints")(function* (input) {
827 const operation = "GitVcsDriver.checkpoints.diffCheckpoints";
828 yield* Effect.annotateCurrentSpan({
829 "checkpoint.cwd": input.cwd,
830 "checkpoint.from_ref": input.fromCheckpointRef,
831 "checkpoint.to_ref": input.toCheckpointRef,
832 "checkpoint.ignore_whitespace": input.ignoreWhitespace,
833 "checkpoint.fallback_from_to_head": input.fallbackFromToHead,
834 });
835
836 let fromRevision: string = input.fromCheckpointRef;
837 if (input.fallbackFromToHead === true) {
838 const resolvedFromCommit = yield* resolveCheckpointCommit(
839 input.cwd,
840 input.fromCheckpointRef,
841 );
842 if (resolvedFromCommit) {
843 fromRevision = resolvedFromCommit;
844 } else {
845 const headCommit = yield* resolveHeadCommit(input.cwd);
846 if (!headCommit) {
847 return yield* new VcsProcessExitError({
848 operation,
849 command: "git diff",
850 cwd: input.cwd,
851 exitCode: 1,
852 detail: "Checkpoint ref is unavailable for diff operation.",
853 });
854 }
855 fromRevision = headCommit;
856 }
857 }
858
859 const result = yield* execute({
860 operation,
861 cwd: input.cwd,
862 args: [
863 "diff",
864 "--patch",
865 "--no-color",
866 "--no-ext-diff",
867 "--no-textconv",
868 ...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
869 `${fromRevision}^{commit}`,
870 `${input.toCheckpointRef}^{commit}`,
871 ],
872 allowNonZeroExit: true,
873 maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
874 });
875
876 if (result.exitCode !== 0) {
877 return yield* new VcsProcessExitError({
878 operation,
879 command: "git diff",
880 cwd: input.cwd,
881 exitCode: result.exitCode,
882 detail: result.stderr.trim() || "Checkpoint ref is unavailable for diff operation.",
883 });
884 }
885
886 return result.stdout;
887 }),
888
889 deleteCheckpointRefs: Effect.fn("GitVcsDriver.checkpoints.deleteCheckpointRefs")(
890 function* (input) {
891 yield* Effect.forEach(
892 input.checkpointRefs,
893 (checkpointRef) =>
894 execute({
895 operation: "GitVcsDriver.checkpoints.deleteCheckpointRefs",
896 cwd: input.cwd,
897 args: ["update-ref", "-d", checkpointRef],
898 allowNonZeroExit: true,
899 }),
900 { discard: true },
901 );
902 },
903 ),
904 };
905
906 return {
907 capabilities,
908 execute,
909 checkpoints,
910 detectRepository,
911 isInsideWorkTree,
912 listWorkspaceFiles,
913 listRemotes,
914 filterIgnoredPaths,
915 initRepository,
916 };
917});
918
919export const makeVcsDriver = Effect.gen(function* () {
920 const driver = yield* makeVcsDriverShape();
921 return VcsDriver.VcsDriver.of(driver);
922});
923
924export const make = Effect.gen(function* () {
925 const git = yield* makeGitVcsDriverCore();
926 return GitVcsDriver.of(git);
927});
928
929export const vcsLayer = Layer.effect(VcsDriver.VcsDriver, makeVcsDriver);
930export const layer = Layer.effect(GitVcsDriver, make);