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