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