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