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