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