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