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