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