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