Open History to see the last commit
1import * as NodeCrypto from "node:crypto";
2import * as NodeBuffer from "node:buffer";
3
4import * as Context from "effect/Context";
5import * as DateTime from "effect/DateTime";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import { ChildProcessSpawner } from "effect/unstable/process";
12
13import {
14 GitCommandError,
15 VcsProcessExitError,
16 type VcsSwitchRefInput,
17 type VcsSwitchRefResult,
18 type VcsCreateRefInput,
19 type VcsCreateRefResult,
20 type VcsCreateWorktreeInput,
21 type VcsCreateWorktreeResult,
22 type ReviewDiffPreviewInput,
23 type ReviewDiffPreviewResult,
24 type ReviewDiffFileContentsInput,
25 type ReviewDiffFileContentsResult,
26 type VcsInitInput,
27 type VcsListRefsInput,
28 type VcsListRefsResult,
29 type VcsPullResult,
30 type VcsRemoveWorktreeInput,
31 type VcsStatusInput,
32 type VcsStatusResult,
33} from "@t3tools/contracts";
34import {
35 makeGitVcsDriverCore,
36 PATCH_RENDER_PREFIX_ARGS,
37 splitNullSeparatedGitStdoutPaths,
38} from "./GitVcsDriverCore.ts";
39import * as VcsDriver from "./VcsDriver.ts";
40import * as VcsProcess from "./VcsProcess.ts";
41
42export interface ExecuteGitInput {
43 readonly operation: string;
44 readonly cwd: string;
45 readonly args: ReadonlyArray<string>;
46 readonly stdin?: string;
47 readonly env?: NodeJS.ProcessEnv;
48 readonly allowNonZeroExit?: boolean;
49 readonly timeoutMs?: number | null;
50 readonly maxOutputBytes?: number;
51 readonly appendTruncationMarker?: boolean;
52 /**
53 * With `appendTruncationMarker`, keep invoking the line callbacks after the
54 * buffered copy is full. For long-running commands whose output is only
55 * consumed through `progress`.
56 */
57 readonly keepLineCallbacksAfterTruncation?: boolean;
58 readonly progress?: ExecuteGitProgress;
59}
60
61export interface ExecuteGitResult {
62 readonly exitCode: ChildProcessSpawner.ExitCode;
63 readonly stdout: string;
64 readonly stderr: string;
65 readonly stdoutTruncated: boolean;
66 readonly stderrTruncated: boolean;
67}
68
69export interface GitStatusDetails {
70 isRepo: boolean;
71 sourceControlProvider?: VcsStatusResult["sourceControlProvider"];
72 hasOriginRemote: boolean;
73 isDefaultBranch: boolean;
74 branch: string | null;
75 upstreamRef: string | null;
76 hasWorkingTreeChanges: boolean;
77 workingTree: VcsStatusResult["workingTree"];
78 hasUpstream: boolean;
79 aheadCount: number;
80 behindCount: number;
81 aheadOfDefaultCount: number;
82}
83
84export interface GitLocalStatusOptions {
85 /** Skip revision walks and return zero divergence counts for local-only consumers. */
86 readonly includeDivergence?: boolean;
87}
88
89export interface GitRemoteStatusDetails {
90 isRepo: boolean;
91 defaultBranch: string | null;
92 isDefaultBranch: boolean;
93 branch: string | null;
94 upstreamRef: string | null;
95 hasUpstream: boolean;
96 aheadCount: number;
97 behindCount: number;
98 aheadOfDefaultCount: number;
99}
100
101export interface GitPreparedCommitContext {
102 stagedSummary: string;
103 stagedPatch: string;
104}
105
106export interface ExecuteGitProgress {
107 readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;
108 readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;
109 readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
110 readonly onHookFinished?: (input: {
111 hookName: string;
112 exitCode: number | null;
113 durationMs: number | null;
114 }) => Effect.Effect<void, never>;
115}
116
117/**
118 * Progress callbacks for `createWorktree`. Git prints `Updating files: 78% (2104/2700)`
119 * to stderr during checkout, and `Submodule path 'x': checked out` during
120 * submodule init. The tracker uses these to drive the worktree setup card.
121 */
122export interface CreateWorktreeProgress {
123 /**
124 * Fires once `git worktree add` has created and registered the directory,
125 * before the (possibly long) submodule step. Git refuses an existing path,
126 * so a path reported here belongs to this call and is safe to remove on
127 * cancel.
128 */
129 readonly onWorktreeClaimed?: (path: string) => Effect.Effect<void, never>;
130 readonly onCheckoutProgress?: (input: {
131 percent: number;
132 completed: number;
133 total: number;
134 }) => Effect.Effect<void, never>;
135 readonly onSubmodulesStarted?: () => Effect.Effect<void, never>;
136 readonly onSubmoduleLine?: (line: string) => Effect.Effect<void, never>;
137 readonly onSubmodulesFinished?: (input: {
138 ok: boolean;
139 detail: string | null;
140 }) => Effect.Effect<void, never>;
141}
142
143export interface CreateWorktreeOptions {
144 readonly progress?: CreateWorktreeProgress;
145}
146
147export interface GitCommitProgress {
148 readonly onOutputLine?: (input: {
149 stream: "stdout" | "stderr";
150 text: string;
151 }) => Effect.Effect<void, never>;
152 readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
153 readonly onHookFinished?: (input: {
154 hookName: string;
155 exitCode: number | null;
156 durationMs: number | null;
157 }) => Effect.Effect<void, never>;
158}
159
160export interface GitCommitOptions {
161 readonly timeoutMs?: number;
162 readonly progress?: GitCommitProgress;
163}
164
165export interface GitDeleteLocalBranchInput {
166 readonly cwd: string;
167 readonly refName: string;
168 readonly force?: boolean;
169}
170
171export interface GitPushResult {
172 status: "pushed" | "skipped_up_to_date";
173 branch: string;
174 upstreamBranch?: string | undefined;
175 setUpstream?: boolean | undefined;
176}
177
178export interface GitRangeContext {
179 commitSummary: string;
180 diffSummary: string;
181 diffPatch: string;
182}
183
184export interface GitRenameBranchInput {
185 cwd: string;
186 oldBranch: string;
187 newBranch: string;
188}
189
190export interface GitRenameBranchResult {
191 branch: string;
192}
193
194export interface GitFetchPullRequestBranchInput {
195 cwd: string;
196 prNumber: number;
197 branch: string;
198}
199
200export interface GitFetchPullRequestHeadCommitInput {
201 cwd: string;
202 prNumber: number;
203}
204
205export interface GitResolveCommitInput {
206 cwd: string;
207 revision: string;
208}
209
210export interface GitResolveCommitResult {
211 commitSha: string;
212}
213
214export interface GitRefreshCheckedOutBranchInput {
215 cwd: string;
216 targetCommit: string;
217 /**
218 * Commit the checkout is allowed to be hard-reset away from: the upstream commit read before
219 * the fetch. HEAD sitting there means the checkout holds no work of its own.
220 */
221 resetWhenHeadCommit?: string | null | undefined;
222}
223
224export interface GitRefreshCheckedOutBranchResult {
225 headCommit: string;
226 moved: boolean;
227 onTarget: boolean;
228}
229
230export interface GitEnsureRemoteInput {
231 cwd: string;
232 preferredName: string;
233 url: string;
234}
235
236export interface GitFetchRemoteBranchInput {
237 cwd: string;
238 remoteName: string;
239 remoteBranch: string;
240 localBranch: string;
241}
242
243export interface GitFetchRemoteTrackingBranchInput {
244 cwd: string;
245 remoteName: string;
246 remoteBranch: string;
247}
248
249export interface GitFetchRemoteInput {
250 cwd: string;
251 remoteName: string;
252 refName?: string;
253}
254
255export interface GitRemoteExistsInput {
256 cwd: string;
257 remoteName: string;
258}
259
260export interface GitRemoteBranchExistsInput extends GitRemoteExistsInput {
261 refName: string;
262}
263
264export interface GitResolveRemoteTrackingCommitInput {
265 cwd: string;
266 refName: string;
267 fallbackRemoteName: string;
268}
269
270export interface GitResolveRemoteTrackingCommitResult {
271 commitSha: string;
272 remoteRefName: string;
273}
274
275export interface GitSetBranchUpstreamInput {
276 cwd: string;
277 branch: string;
278 remoteName: string;
279 remoteBranch: string;
280}
281
282export interface GitRemoteStatusOptions {
283 readonly refreshUpstream?: boolean;
284}
285
286export class GitVcsDriver extends Context.Service<
287 GitVcsDriver,
288 {
289 readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
290 readonly status: (input: VcsStatusInput) => Effect.Effect<VcsStatusResult, GitCommandError>;
291 readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
292 readonly statusDetailsLocal: (
293 cwd: string,
294 options?: GitLocalStatusOptions,
295 ) => Effect.Effect<GitStatusDetails, GitCommandError>;
296 readonly statusDetailsRemote: (
297 cwd: string,
298 options?: GitRemoteStatusOptions,
299 ) => Effect.Effect<GitRemoteStatusDetails, GitCommandError>;
300 readonly prepareCommitContext: (
301 cwd: string,
302 filePaths?: readonly string[],
303 ) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
304 readonly commit: (
305 cwd: string,
306 subject: string,
307 body: string,
308 options?: GitCommitOptions,
309 ) => Effect.Effect<{ commitSha: string }, GitCommandError>;
310 readonly pushCurrentBranch: (
311 cwd: string,
312 fallbackBranch: string | null,
313 options?: { readonly remoteName?: string | null },
314 ) => Effect.Effect<GitPushResult, GitCommandError>;
315 readonly readRangeContext: (
316 cwd: string,
317 baseRef: string,
318 ) => Effect.Effect<GitRangeContext, GitCommandError>;
319 readonly getReviewDiffPreview: (
320 input: ReviewDiffPreviewInput,
321 ) => Effect.Effect<ReviewDiffPreviewResult, GitCommandError>;
322 readonly getReviewDiffFileContents: (
323 input: ReviewDiffFileContentsInput,
324 ) => Effect.Effect<ReviewDiffFileContentsResult, GitCommandError>;
325 readonly readConfigValue: (
326 cwd: string,
327 key: string,
328 ) => Effect.Effect<string | null, GitCommandError>;
329 readonly listRefs: (
330 input: VcsListRefsInput,
331 ) => Effect.Effect<VcsListRefsResult, GitCommandError>;
332 readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
333 readonly createWorktree: (
334 input: VcsCreateWorktreeInput,
335 options?: CreateWorktreeOptions,
336 ) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
337 readonly fetchPullRequestBranch: (
338 input: GitFetchPullRequestBranchInput,
339 ) => Effect.Effect<void, GitCommandError>;
340 /** Fetches `refs/pull/<n>/head` without writing a branch, for heads that exist nowhere else. */
341 readonly fetchPullRequestHeadCommit: (
342 input: GitFetchPullRequestHeadCommitInput,
343 ) => Effect.Effect<GitResolveCommitResult, GitCommandError>;
344 readonly resolveCommit: (
345 input: GitResolveCommitInput,
346 ) => Effect.Effect<GitResolveCommitResult, GitCommandError>;
347 /** Moves the branch checked out in `cwd` onto `targetCommit`, from inside that worktree. */
348 readonly refreshCheckedOutBranch: (
349 input: GitRefreshCheckedOutBranchInput,
350 ) => Effect.Effect<GitRefreshCheckedOutBranchResult, GitCommandError>;
351 readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
352 readonly resolvePrimaryRemoteName: (cwd: string) => Effect.Effect<string, GitCommandError>;
353 readonly resolveDefaultBranchName: (
354 cwd: string,
355 remoteName: string,
356 ) => Effect.Effect<string | null, GitCommandError>;
357 readonly fetchRemote: (input: GitFetchRemoteInput) => Effect.Effect<void, GitCommandError>;
358 readonly remoteExists: (input: GitRemoteExistsInput) => Effect.Effect<boolean, GitCommandError>;
359 readonly remoteBranchExists: (
360 input: GitRemoteBranchExistsInput,
361 ) => Effect.Effect<boolean, GitCommandError>;
362 readonly resolveRemoteTrackingCommit: (
363 input: GitResolveRemoteTrackingCommitInput,
364 ) => Effect.Effect<GitResolveRemoteTrackingCommitResult, GitCommandError>;
365 readonly fetchRemoteBranch: (
366 input: GitFetchRemoteBranchInput,
367 ) => Effect.Effect<void, GitCommandError>;
368 readonly fetchRemoteTrackingBranch: (
369 input: GitFetchRemoteTrackingBranchInput,
370 ) => Effect.Effect<void, GitCommandError>;
371 readonly setBranchUpstream: (
372 input: GitSetBranchUpstreamInput,
373 ) => Effect.Effect<void, GitCommandError>;
374 readonly removeWorktree: (
375 input: VcsRemoveWorktreeInput,
376 ) => Effect.Effect<void, GitCommandError>;
377 /** Drops worktree admin entries whose directory is already gone (`git worktree prune`). */
378 readonly pruneWorktrees: (input: {
379 readonly cwd: string;
380 }) => Effect.Effect<void, GitCommandError>;
381 readonly deleteLocalBranch: (
382 input: GitDeleteLocalBranchInput,
383 ) => Effect.Effect<void, GitCommandError>;
384 readonly renameBranch: (
385 input: GitRenameBranchInput,
386 ) => Effect.Effect<GitRenameBranchResult, GitCommandError>;
387 readonly createRef: (
388 input: VcsCreateRefInput,
389 ) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
390 readonly switchRef: (
391 input: VcsSwitchRefInput,
392 ) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
393 readonly initRepo: (input: VcsInitInput) => Effect.Effect<void, GitCommandError>;
394 readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
395 }
396>()("t3/vcs/GitVcsDriver") {}
397
398const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
399const CHECKPOINT_RECOVERY_MAX_CANDIDATES = 64;
400const CHECKPOINT_RECOVERY_TIMEOUT = "5 seconds";
401const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
402const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
403const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [
404 "-c",
405 "core.fsmonitor=false",
406 "-c",
407 "core.untrackedCache=false",
408] as const;
409
410const nowFreshness = Effect.fn("GitVcsDriver.nowFreshness")(function* () {
411 const now = yield* DateTime.now;
412 return {
413 source: "live-local" as const,
414 observedAt: now,
415 expiresAt: Option.none(),
416 };
417});
418
419function chunkPathsForGitCheckIgnore(relativePaths: ReadonlyArray<string>): string[][] {
420 const chunks: string[][] = [];
421 let chunk: string[] = [];
422 let chunkBytes = 0;
423
424 for (const relativePath of relativePaths) {
425 const relativePathBytes = Buffer.byteLength(relativePath) + 1;
426 if (chunk.length > 0 && chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
427 chunks.push(chunk);
428 chunk = [];
429 chunkBytes = 0;
430 }
431
432 chunk.push(relativePath);
433 chunkBytes += relativePathBytes;
434
435 if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
436 chunks.push(chunk);
437 chunk = [];
438 chunkBytes = 0;
439 }
440 }
441
442 if (chunk.length > 0) {
443 chunks.push(chunk);
444 }
445
446 return chunks;
447}
448
449function parseGitRemoteVerboseOutput(
450 output: string,
451): Map<string, { url?: string; pushUrl?: string }> {
452 const remotes = new Map<string, { url?: string; pushUrl?: string }>();
453 for (const line of output.split("\n")) {
454 const trimmed = line.trim();
455 if (trimmed.length === 0) {
456 continue;
457 }
458
459 const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed);
460 if (!match) {
461 continue;
462 }
463
464 const name = match[1];
465 const url = match[2];
466 const direction = match[3];
467 if (!name || !url || !direction) {
468 continue;
469 }
470 const remote = remotes.get(name) ?? {};
471 if (direction === "fetch") {
472 remote.url = url;
473 } else {
474 remote.pushUrl = url;
475 }
476 remotes.set(name, remote);
477 }
478 return remotes;
479}
480
481const gitCommand = (
482 process: VcsProcess.VcsProcess["Service"],
483 operation: string,
484 cwd: string,
485 args: ReadonlyArray<string>,
486 options?: {
487 readonly stdin?: string;
488 readonly env?: NodeJS.ProcessEnv;
489 readonly allowNonZeroExit?: boolean;
490 readonly timeoutMs?: number;
491 readonly maxOutputBytes?: number;
492 readonly outputMode?: VcsProcess.VcsProcessInput["outputMode"];
493 readonly appendTruncationMarker?: boolean;
494 },
495) =>
496 process.run({
497 operation,
498 command: "git",
499 args: ["-C", cwd, ...args],
500 cwd,
501 spawnCwd: globalThis.process.cwd(),
502 ...(options?.stdin !== undefined ? { stdin: options.stdin } : {}),
503 ...(options?.env !== undefined ? { env: options.env } : {}),
504 ...(options?.allowNonZeroExit !== undefined
505 ? { allowNonZeroExit: options.allowNonZeroExit }
506 : {}),
507 ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
508 ...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
509 ...(options?.outputMode !== undefined ? { outputMode: options.outputMode } : {}),
510 ...(options?.appendTruncationMarker !== undefined
511 ? { appendTruncationMarker: options.appendTruncationMarker }
512 : {}),
513 });
514
515export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* () {
516 const fileSystem = yield* FileSystem.FileSystem;
517 const path = yield* Path.Path;
518 const vcsProcess = yield* VcsProcess.VcsProcess;
519 const capabilities = {
520 kind: "git" as const,
521 supportsWorktrees: true,
522 supportsBookmarks: false,
523 supportsAtomicSnapshot: false,
524 supportsPushDefaultRemote: true,
525 ignoreClassifier: "native" as const,
526 };
527
528 const isInsideWorkTree: VcsDriver.VcsDriver["Service"]["isInsideWorkTree"] = (cwd) =>
529 gitCommand(
530 vcsProcess,
531 "GitVcsDriver.isInsideWorkTree",
532 cwd,
533 ["rev-parse", "--is-inside-work-tree"],
534 {
535 allowNonZeroExit: true,
536 timeoutMs: 5_000,
537 maxOutputBytes: 4_096,
538 },
539 ).pipe(Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"));
540
541 const execute: VcsDriver.VcsDriver["Service"]["execute"] = (input) =>
542 gitCommand(vcsProcess, input.operation, input.cwd, input.args, {
543 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
544 ...(input.env !== undefined ? { env: input.env } : {}),
545 ...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}),
546 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
547 ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
548 ...(input.outputMode !== undefined ? { outputMode: input.outputMode } : {}),
549 ...(input.appendTruncationMarker !== undefined
550 ? { appendTruncationMarker: input.appendTruncationMarker }
551 : {}),
552 });
553
554 const detectRepository: VcsDriver.VcsDriver["Service"]["detectRepository"] = Effect.fn(
555 "detectRepository",
556 )(function* (cwd) {
557 if (!(yield* isInsideWorkTree(cwd))) {
558 return null;
559 }
560
561 const root = yield* gitCommand(vcsProcess, "GitVcsDriver.detectRepository.root", cwd, [
562 "rev-parse",
563 "--show-toplevel",
564 ]);
565 const gitCommonDir = yield* gitCommand(
566 vcsProcess,
567 "GitVcsDriver.detectRepository.commonDir",
568 cwd,
569 ["rev-parse", "--git-common-dir"],
570 ).pipe(Effect.orElseSucceed(() => null));
571
572 return {
573 kind: "git" as const,
574 rootPath: root.stdout.trim(),
575 metadataPath: gitCommonDir?.stdout.trim() || null,
576 freshness: yield* nowFreshness(),
577 };
578 });
579
580 const listWorkspaceFiles: VcsDriver.VcsDriver["Service"]["listWorkspaceFiles"] = (cwd) =>
581 gitCommand(
582 vcsProcess,
583 "GitVcsDriver.listWorkspaceFiles",
584 cwd,
585 [
586 ...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
587 "ls-files",
588 "--cached",
589 "--others",
590 "--exclude-standard",
591 "-z",
592 ],
593 {
594 allowNonZeroExit: true,
595 timeoutMs: 20_000,
596 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
597 appendTruncationMarker: true,
598 },
599 ).pipe(
600 Effect.flatMap((result) =>
601 result.exitCode === 0
602 ? Effect.gen(function* () {
603 const freshness = yield* nowFreshness();
604 return {
605 paths: splitNullSeparatedGitStdoutPaths(result),
606 truncated: result.stdoutTruncated,
607 freshness,
608 };
609 })
610 : Effect.fail(
611 new VcsProcessExitError({
612 operation: "GitVcsDriver.listWorkspaceFiles",
613 command: "git ls-files",
614 cwd,
615 exitCode: result.exitCode,
616 detail: result.stderr.trim() || "git ls-files failed",
617 }),
618 ),
619 ),
620 );
621
622 const listRemotes: VcsDriver.VcsDriver["Service"]["listRemotes"] = Effect.fn("listRemotes")(
623 function* (cwd) {
624 const result = yield* gitCommand(
625 vcsProcess,
626 "GitVcsDriver.listRemotes",
627 cwd,
628 ["remote", "-v"],
629 {
630 allowNonZeroExit: true,
631 timeoutMs: 5_000,
632 maxOutputBytes: 64 * 1024,
633 },
634 );
635
636 if (result.exitCode !== 0) {
637 return yield* new VcsProcessExitError({
638 operation: "GitVcsDriver.listRemotes",
639 command: "git remote -v",
640 cwd,
641 exitCode: result.exitCode,
642 detail: result.stderr.trim() || "git remote -v failed",
643 });
644 }
645
646 const parsed = parseGitRemoteVerboseOutput(result.stdout);
647 const remotes = Array.from(parsed.entries()).flatMap(([name, remote]) => {
648 if (!remote.url) {
649 return [];
650 }
651 return [
652 {
653 name,
654 url: remote.url,
655 pushUrl: remote.pushUrl ? Option.some(remote.pushUrl) : Option.none(),
656 isPrimary: name === "origin",
657 },
658 ];
659 });
660
661 return {
662 remotes,
663 freshness: yield* nowFreshness(),
664 };
665 },
666 );
667
668 const filterIgnoredPaths: VcsDriver.VcsDriver["Service"]["filterIgnoredPaths"] = Effect.fn(
669 "filterIgnoredPaths",
670 )(function* (cwd, relativePaths) {
671 if (relativePaths.length === 0) {
672 return relativePaths;
673 }
674
675 const ignoredPaths = new Set<string>();
676 const chunks = chunkPathsForGitCheckIgnore(relativePaths);
677
678 for (const chunk of chunks) {
679 const result = yield* gitCommand(
680 vcsProcess,
681 "GitVcsDriver.filterIgnoredPaths",
682 cwd,
683 [...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
684 {
685 stdin: `${chunk.join("\0")}\0`,
686 allowNonZeroExit: true,
687 timeoutMs: 20_000,
688 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
689 appendTruncationMarker: true,
690 },
691 );
692
693 if (result.exitCode !== 0 && result.exitCode !== 1) {
694 return yield* new VcsProcessExitError({
695 operation: "GitVcsDriver.filterIgnoredPaths",
696 command: "git check-ignore",
697 cwd,
698 exitCode: result.exitCode,
699 detail: result.stderr.trim() || "git check-ignore failed",
700 });
701 }
702
703 for (const ignoredPath of splitNullSeparatedGitStdoutPaths(result)) {
704 ignoredPaths.add(ignoredPath);
705 }
706 }
707
708 if (ignoredPaths.size === 0) {
709 return relativePaths;
710 }
711
712 return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
713 });
714
715 const initRepository: VcsDriver.VcsDriver["Service"]["initRepository"] = (input) =>
716 gitCommand(vcsProcess, "GitVcsDriver.initRepository", input.cwd, ["init"], {
717 timeoutMs: 10_000,
718 maxOutputBytes: 64 * 1024,
719 }).pipe(Effect.asVoid);
720
721 const resolveHeadCommit = (cwd: string) =>
722 execute({
723 operation: "GitVcsDriver.checkpoints.resolveHeadCommit",
724 cwd,
725 args: ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
726 allowNonZeroExit: true,
727 }).pipe(
728 Effect.map((result) => {
729 if (result.exitCode !== 0) {
730 return null;
731 }
732 const commit = result.stdout.trim();
733 return commit.length > 0 ? commit : null;
734 }),
735 );
736
737 const hasHeadCommit = (cwd: string, env?: NodeJS.ProcessEnv) =>
738 execute({
739 operation: "GitVcsDriver.checkpoints.hasHeadCommit",
740 cwd,
741 args: ["rev-parse", "--verify", "HEAD"],
742 allowNonZeroExit: true,
743 ...(env !== undefined ? { env } : {}),
744 }).pipe(Effect.map((result) => result.exitCode === 0));
745
746 const resolveCheckpointCommit = (cwd: string, checkpointRef: string) =>
747 execute({
748 operation: "GitVcsDriver.checkpoints.resolveCheckpointCommit",
749 cwd,
750 args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`],
751 allowNonZeroExit: true,
752 }).pipe(
753 Effect.map((result) => {
754 if (result.exitCode !== 0) {
755 return null;
756 }
757 const commit = result.stdout.trim();
758 return commit.length > 0 ? commit : null;
759 }),
760 );
761
762 const resolveGitCommonDir = (cwd: string) =>
763 Effect.gen(function* () {
764 const result = yield* execute({
765 operation: "GitVcsDriver.checkpoints.resolveGitCommonDir",
766 cwd,
767 args: ["rev-parse", "--git-common-dir"],
768 });
769 const gitCommonDir = result.stdout.trim();
770 return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
771 });
772
773 // Git renames loose objects and refs into place without fsync by default, so
774 // an unclean restart can leave 0-byte files under refs/t3/** that break every
775 // later fetch and push. Checkpoint writes flush before they are published;
776 // macOS defaults to writeout-only, which does not reach the disk either.
777 const durableWrite = [
778 "-c",
779 "core.fsync=objects,reference",
780 "-c",
781 "core.fsyncMethod=fsync",
782 ] as const;
783
784 const checkpoints: VcsDriver.VcsCheckpointOps = {
785 captureCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureCheckpoint")(function* (input) {
786 const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION;
787 const indexConfig = [
788 "-c",
789 "core.fsmonitor=false",
790 "-c",
791 "sparse.expectFilesOutsideOfPatterns=false",
792 ];
793 const gitCommonDir = yield* resolveGitCommonDir(input.cwd);
794 const tempIndexPath = path.join(
795 gitCommonDir,
796 `t3-checkpoint-index-${NodeCrypto.randomUUID()}`,
797 );
798 const commitEnv: NodeJS.ProcessEnv = {
799 ...process.env,
800 GIT_INDEX_FILE: tempIndexPath,
801 GIT_AUTHOR_NAME: "T3 Code",
802 GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com",
803 GIT_COMMITTER_NAME: "T3 Code",
804 GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com",
805 };
806
807 // Forced process termination can leave Git's private index lock behind.
808 const cleanupTempIndex = Effect.forEach(
809 [tempIndexPath, `${tempIndexPath}.lock`],
810 (indexFile) => fileSystem.remove(indexFile, { force: true }).pipe(Effect.ignore),
811 { discard: true },
812 );
813
814 yield* Effect.gen(function* () {
815 const headExists = yield* hasHeadCommit(input.cwd);
816 const sparseConfig = yield* execute({
817 operation,
818 cwd: input.cwd,
819 args: ["config", "--bool", "core.sparseCheckout"],
820 allowNonZeroExit: true,
821 });
822 let sparseCheckout = sparseConfig.stdout.trim() === "true";
823 if (sparseCheckout) {
824 const help = yield* execute({
825 operation,
826 cwd: input.cwd,
827 args: ["add", "-h"],
828 allowNonZeroExit: true,
829 });
830 sparseCheckout = /--(?:\[no-\])?sparse\b/.test(`${help.stdout}${help.stderr}`);
831 }
832 if (headExists) {
833 const reusedIndex = yield* Effect.gen(function* () {
834 const indexPath = yield* execute({
835 operation,
836 cwd: input.cwd,
837 args: ["rev-parse", "--path-format=absolute", "--git-path", "index"],
838 });
839 const { mtime } = yield* fileSystem.stat(indexPath.stdout.trim());
840 if (Option.isNone(mtime)) return false;
841 // Stay below the source timestamp even if Date rounded up, preserving Git's racy check.
842 const indexTime = Math.floor((mtime.value.getTime() - 1) / 1000);
843 if (indexTime <= 0) return false;
844 yield* fileSystem.copyFile(indexPath.stdout.trim(), tempIndexPath);
845 // Retain stat data only where the copied index already matches HEAD.
846 yield* execute({
847 operation,
848 cwd: input.cwd,
849 args: [...indexConfig, "read-tree", "--reset", "HEAD"],
850 env: commitEnv,
851 });
852 // read-tree can rewrite the index, so restore its racy timestamp afterward.
853 yield* fileSystem.utimes(tempIndexPath, indexTime, indexTime);
854 let specialFlags = false;
855 let recordStart = true;
856 let skipped = false;
857 let skippedRecord: number[] = [];
858 const skippedPaths: string[] = [];
859 yield* vcsProcess.run({
860 operation,
861 command: "git",
862 cwd: input.cwd,
863 args: [...indexConfig, "ls-files", "--full-name", "--sparse", "-v", "-z"],
864 env: commitEnv,
865 maxOutputBytes: 4_096,
866 outputMode: "truncate",
867 // Inspect every tag; retain only skipped file paths for checking sparse rules.
868 onStdoutChunk: (chunk) => {
869 for (const byte of chunk) {
870 if (recordStart) skipped = byte === 83;
871 if (skipped && sparseCheckout) {
872 if (byte !== 0) skippedRecord.push(byte);
873 else {
874 if (skippedRecord.at(-1) !== 47) {
875 const name = Buffer.from(skippedRecord).subarray(2);
876 if (!NodeBuffer.isUtf8(name)) specialFlags = true;
877 else skippedPaths.push(name.toString("utf8"));
878 }
879 skippedRecord = [];
880 }
881 }
882 if (
883 recordStart &&
884 ((byte >= 97 && byte <= 122) || (!sparseCheckout && byte === 83))
885 ) {
886 specialFlags = true;
887 }
888 recordStart = byte === 0;
889 }
890 },
891 });
892 if (skippedPaths.length > 0 && !specialFlags) {
893 const selected = yield* execute({
894 operation,
895 cwd: input.cwd,
896 args: [...indexConfig, "sparse-checkout", "check-rules", "-z"],
897 stdin: skippedPaths.join("\0") + "\0",
898 env: commitEnv,
899 maxOutputBytes: 1,
900 outputMode: "truncate",
901 });
902 // Any selected skipped file has a manual flag, not a sparse exclusion.
903 specialFlags = selected.stdout.length > 0 || selected.stdoutTruncated;
904 }
905 // Sparse Git clears skip-worktree for present files. Manual flags still need a reset.
906 return !specialFlags;
907 }).pipe(Effect.orElseSucceed(() => false));
908 if (!reusedIndex) {
909 if (sparseCheckout) {
910 const cone = yield* execute({
911 operation,
912 cwd: input.cwd,
913 args: ["config", "--bool", "core.sparseCheckoutCone"],
914 allowNonZeroExit: true,
915 });
916 // Rebuilding a non-cone index loses exclusions; do not publish false deletions.
917 if (cone.stdout.trim() !== "true") {
918 return yield* new VcsProcessExitError({
919 operation,
920 command: "git read-tree",
921 cwd: input.cwd,
922 exitCode: 1,
923 detail: "Cannot rebuild a checkpoint index for non-cone sparse checkout.",
924 });
925 }
926 }
927 yield* cleanupTempIndex;
928 yield* execute({
929 operation,
930 cwd: input.cwd,
931 // A fresh sparse index represents excluded directories without marking them deleted.
932 args: sparseCheckout
933 ? [...indexConfig, "-c", "index.sparse=true", "read-tree", "--reset", "HEAD"]
934 : ["read-tree", "HEAD"],
935 env: commitEnv,
936 });
937 }
938 }
939
940 const stageFiles = (exclusions: ReadonlyArray<string>) =>
941 execute({
942 operation,
943 cwd: input.cwd,
944 // Preserve absent skipped entries, but capture present nonignored files outside the cone.
945 args: [
946 ...indexConfig,
947 ...durableWrite,
948 "add",
949 ...(sparseCheckout ? ["--sparse"] : []),
950 "-A",
951 "--",
952 ".",
953 ...exclusions,
954 ],
955 env: commitEnv,
956 });
957 yield* stageFiles([]).pipe(
958 Effect.catchTags({
959 VcsProcessExitError: (error) =>
960 Effect.gen(function* () {
961 // Git cannot stage an embedded repository until it has a commit. Discover these
962 // only after staging fails so ordinary checkpoints do not need another file scan.
963 const untracked = yield* execute({
964 operation,
965 cwd: input.cwd,
966 args: ["ls-files", "--others", "--exclude-standard", "-z", "--", "."],
967 env: commitEnv,
968 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
969 });
970 if (untracked.stdoutTruncated) return yield* error;
971 const candidates = splitNullSeparatedGitStdoutPaths(untracked).filter((entry) =>
972 entry.endsWith("/"),
973 );
974 // Refuse excessive recovery work before probing any nested repositories.
975 if (candidates.length > CHECKPOINT_RECOVERY_MAX_CANDIDATES) return yield* error;
976 // Discover each child's repository instead of inheriting the server's Git bindings.
977 const nestedRepoEnv: NodeJS.ProcessEnv = {
978 ...process.env,
979 GIT_DIR: undefined,
980 GIT_WORK_TREE: undefined,
981 GIT_COMMON_DIR: undefined,
982 GIT_INDEX_FILE: undefined,
983 GIT_OBJECT_DIRECTORY: undefined,
984 GIT_ALTERNATE_OBJECT_DIRECTORIES: undefined,
985 };
986 const exclusions: Array<string> = [];
987 for (const entry of candidates) {
988 const nestedCwd = path.join(input.cwd, entry);
989 if (
990 (yield* fileSystem
991 .exists(path.join(nestedCwd, ".git"))
992 .pipe(Effect.mapError(() => error))) &&
993 !(yield* hasHeadCommit(nestedCwd, nestedRepoEnv))
994 ) {
995 exclusions.push(`:(exclude,literal)${entry}`);
996 }
997 }
998 if (exclusions.length === 0) return yield* error;
999 return yield* stageFiles(exclusions);
1000 }).pipe(
1001 // One budget covers discovery, queued Git admission, probes, and the staging retry.
1002 Effect.timeoutOrElse({
1003 duration: CHECKPOINT_RECOVERY_TIMEOUT,
1004 orElse: () => Effect.fail(error),
1005 }),
1006 ),
1007 }),
1008 );
1009
1010 const writeTreeResult = yield* execute({
1011 operation,
1012 cwd: input.cwd,
1013 args: [...indexConfig, ...durableWrite, "write-tree"],
1014 env: commitEnv,
1015 });
1016 const treeOid = writeTreeResult.stdout.trim();
1017 if (treeOid.length === 0) {
1018 return yield* new VcsProcessExitError({
1019 operation,
1020 command: "git write-tree",
1021 cwd: input.cwd,
1022 exitCode: 0,
1023 detail: "git write-tree returned an empty tree oid.",
1024 });
1025 }
1026
1027 const message = `t3 checkpoint ref=${input.checkpointRef}`;
1028 const commitTreeResult = yield* execute({
1029 operation,
1030 cwd: input.cwd,
1031 args: [...durableWrite, "commit-tree", treeOid, "-m", message],
1032 env: commitEnv,
1033 });
1034 const commitOid = commitTreeResult.stdout.trim();
1035 if (commitOid.length === 0) {
1036 return yield* new VcsProcessExitError({
1037 operation,
1038 command: "git commit-tree",
1039 cwd: input.cwd,
1040 exitCode: 0,
1041 detail: "git commit-tree returned an empty commit oid.",
1042 });
1043 }
1044
1045 yield* execute({
1046 operation,
1047 cwd: input.cwd,
1048 args: [...durableWrite, "update-ref", input.checkpointRef, commitOid],
1049 });
1050 }).pipe(Effect.ensuring(cleanupTempIndex));
1051 }),
1052
1053 hasCheckpointRef: (input) =>
1054 resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
1055 Effect.map((commit) => commit !== null),
1056 ),
1057
1058 restoreCheckpoint: Effect.fn("GitVcsDriver.checkpoints.restoreCheckpoint")(function* (input) {
1059 const operation = "GitVcsDriver.checkpoints.restoreCheckpoint";
1060
1061 let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
1062
1063 if (!commitOid && input.fallbackToHead === true) {
1064 commitOid = yield* resolveHeadCommit(input.cwd);
1065 }
1066
1067 if (!commitOid) {
1068 return false;
1069 }
1070
1071 const tracked = yield* execute({
1072 operation,
1073 cwd: input.cwd,
1074 args: ["ls-files", "--cached", `--with-tree=${commitOid}`, "-z", "--", "."],
1075 });
1076 // An empty index and checkpoint have nothing for git restore's pathspec to match.
1077 if (tracked.stdout.length > 0) {
1078 yield* execute({
1079 operation,
1080 cwd: input.cwd,
1081 args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
1082 });
1083 }
1084 // Restoring away the last tracked file can remove a nested workspace directory.
1085 yield* fileSystem.makeDirectory(input.cwd, { recursive: true }).pipe(
1086 Effect.mapError(
1087 (cause) =>
1088 new VcsProcessExitError({
1089 operation,
1090 command: "git restore",
1091 cwd: input.cwd,
1092 exitCode: 0,
1093 detail: `Could not recreate the checkpoint workspace: ${cause.message}`,
1094 }),
1095 ),
1096 );
1097 const cleaned = yield* execute({
1098 operation,
1099 cwd: input.cwd,
1100 args: ["clean", "-fd", "--", "."],
1101 allowNonZeroExit: true,
1102 });
1103 if (cleaned.exitCode !== 0) {
1104 // Git can remove every child, then fail trying to remove './' itself.
1105 const emptiedWorkspace =
1106 cleaned.exitCode === 1 &&
1107 /^warning: failed to remove \.\/: [^\n]+$/.test(cleaned.stderr.trim()) &&
1108 (yield* fileSystem.readDirectory(input.cwd).pipe(
1109 Effect.map((entries) => entries.length === 0),
1110 Effect.catch(() => Effect.succeed(false)),
1111 ));
1112 if (!emptiedWorkspace)
1113 return yield* new VcsProcessExitError({
1114 operation,
1115 command: "git clean",
1116 cwd: input.cwd,
1117 exitCode: cleaned.exitCode,
1118 detail: cleaned.stderr.trim() || "Could not clean the checkpoint workspace.",
1119 });
1120 }
1121
1122 const headExists = yield* hasHeadCommit(input.cwd);
1123 if (headExists) {
1124 yield* execute({
1125 operation,
1126 cwd: input.cwd,
1127 args: ["reset", "--quiet", "--", "."],
1128 });
1129 }
1130
1131 return true;
1132 }),
1133
1134 diffCheckpoints: Effect.fn("GitVcsDriver.checkpoints.diffCheckpoints")(function* (input) {
1135 const operation = "GitVcsDriver.checkpoints.diffCheckpoints";
1136 yield* Effect.annotateCurrentSpan({
1137 "checkpoint.cwd": input.cwd,
1138 "checkpoint.from_ref": input.fromCheckpointRef,
1139 "checkpoint.to_ref": input.toCheckpointRef,
1140 "checkpoint.ignore_whitespace": input.ignoreWhitespace,
1141 "checkpoint.format": input.format ?? "patch",
1142 "checkpoint.fallback_from_to_head": input.fallbackFromToHead,
1143 });
1144
1145 let fromRevision: string = input.fromCheckpointRef;
1146 if (input.fallbackFromToHead === true) {
1147 const resolvedFromCommit = yield* resolveCheckpointCommit(
1148 input.cwd,
1149 input.fromCheckpointRef,
1150 );
1151 if (resolvedFromCommit) {
1152 fromRevision = resolvedFromCommit;
1153 } else {
1154 const headCommit = yield* resolveHeadCommit(input.cwd);
1155 if (!headCommit) {
1156 return yield* new VcsProcessExitError({
1157 operation,
1158 command: "git diff",
1159 cwd: input.cwd,
1160 exitCode: 1,
1161 detail: "Checkpoint ref is unavailable for diff operation.",
1162 });
1163 }
1164 fromRevision = headCommit;
1165 }
1166 }
1167
1168 const result = yield* execute({
1169 operation,
1170 cwd: input.cwd,
1171 args: [
1172 "diff",
1173 ...(input.format === "numstat" ? ["--numstat", "-z"] : ["--patch"]),
1174 "--no-color",
1175 "--no-ext-diff",
1176 "--no-textconv",
1177 ...PATCH_RENDER_PREFIX_ARGS,
1178 ...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
1179 `${fromRevision}^{commit}`,
1180 `${input.toCheckpointRef}^{commit}`,
1181 ],
1182 allowNonZeroExit: true,
1183 maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
1184 outputMode: input.format === "numstat" ? "error" : "truncate",
1185 });
1186
1187 if (result.exitCode !== 0) {
1188 return yield* new VcsProcessExitError({
1189 operation,
1190 command: "git diff",
1191 cwd: input.cwd,
1192 exitCode: result.exitCode,
1193 detail: result.stderr.trim() || "Checkpoint ref is unavailable for diff operation.",
1194 });
1195 }
1196
1197 return result.stdout;
1198 }),
1199
1200 deleteCheckpointRefs: Effect.fn("GitVcsDriver.checkpoints.deleteCheckpointRefs")(
1201 function* (input) {
1202 yield* Effect.forEach(
1203 input.checkpointRefs,
1204 (checkpointRef) =>
1205 execute({
1206 operation: "GitVcsDriver.checkpoints.deleteCheckpointRefs",
1207 cwd: input.cwd,
1208 args: ["update-ref", "-d", checkpointRef],
1209 allowNonZeroExit: true,
1210 }),
1211 { discard: true },
1212 );
1213 },
1214 ),
1215 };
1216
1217 return {
1218 capabilities,
1219 execute,
1220 checkpoints,
1221 detectRepository,
1222 isInsideWorkTree,
1223 listWorkspaceFiles,
1224 listRemotes,
1225 filterIgnoredPaths,
1226 initRepository,
1227 };
1228});
1229
1230export const makeVcsDriver = Effect.gen(function* () {
1231 const driver = yield* makeVcsDriverShape();
1232 return VcsDriver.VcsDriver.of(driver);
1233});
1234
1235export const make = Effect.gen(function* () {
1236 const git = yield* makeGitVcsDriverCore();
1237 return GitVcsDriver.of(git);
1238});
1239
1240export const vcsLayer = Layer.effect(VcsDriver.VcsDriver, makeVcsDriver);
1241export const layer = Layer.effect(GitVcsDriver, make);