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