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