Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitVcsDriver.ts

961 lines29.2 KB

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