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