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