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 // One spawn answers all three; outside a work tree it exits non-zero or prints "false".
591 const result = yield* gitCommand(
592 vcsProcess,
593 "GitVcsDriver.detectRepository",
594 cwd,
595 ["rev-parse", "--is-inside-work-tree", "--show-toplevel", "--git-common-dir"],
596 {
597 allowNonZeroExit: true,
598 timeoutMs: 5_000,
599 maxOutputBytes: 16_384,
600 },
601 ).pipe(Effect.catchIf(isMissingExecutable, () => Effect.succeed(null)));
602 if (result === null || result.exitCode !== 0) return null;
603 const lines = result.stdout.replace(/\r?\n$/u, "").split(/\r?\n/u);
604 if (lines[0]?.trim() !== "true") return null;
605 // A newline inside a path breaks the line framing; ask for each path on its own.
606 if (lines.length !== 3) {
607 const root = yield* gitCommand(vcsProcess, "GitVcsDriver.detectRepository", cwd, [
608 "rev-parse",
609 "--show-toplevel",
610 ]);
611 const gitCommonDir = yield* gitCommand(vcsProcess, "GitVcsDriver.detectRepository", cwd, [
612 "rev-parse",
613 "--git-common-dir",
614 ]).pipe(Effect.orElseSucceed(() => null));
615 return {
616 kind: "git" as const,
617 rootPath: root.stdout.trim(),
618 metadataPath: gitCommonDir?.stdout.trim() || null,
619 freshness: yield* nowFreshness(),
620 };
621 }
622
623 return {
624 kind: "git" as const,
625 rootPath: lines[1]!.trim(),
626 metadataPath: lines[2]!.trim() || null,
627 freshness: yield* nowFreshness(),
628 };
629 });
630
631 const listWorkspaceFiles: VcsDriver.VcsDriver["Service"]["listWorkspaceFiles"] = (cwd) =>
632 gitCommand(
633 vcsProcess,
634 "GitVcsDriver.listWorkspaceFiles",
635 cwd,
636 [
637 ...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
638 "ls-files",
639 "--cached",
640 "--others",
641 "--exclude-standard",
642 "-z",
643 ],
644 {
645 allowNonZeroExit: true,
646 timeoutMs: 20_000,
647 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
648 appendTruncationMarker: true,
649 },
650 ).pipe(
651 Effect.flatMap((result) =>
652 result.exitCode === 0
653 ? Effect.gen(function* () {
654 const freshness = yield* nowFreshness();
655 return {
656 paths: splitNullSeparatedGitStdoutPaths(result),
657 truncated: result.stdoutTruncated,
658 freshness,
659 };
660 })
661 : Effect.fail(
662 new VcsProcessExitError({
663 operation: "GitVcsDriver.listWorkspaceFiles",
664 command: "git ls-files",
665 cwd,
666 exitCode: result.exitCode,
667 detail: result.stderr.trim() || "git ls-files failed",
668 }),
669 ),
670 ),
671 );
672
673 const listRemotes: VcsDriver.VcsDriver["Service"]["listRemotes"] = Effect.fn("listRemotes")(
674 function* (cwd) {
675 const result = yield* gitCommand(
676 vcsProcess,
677 "GitVcsDriver.listRemotes",
678 cwd,
679 ["remote", "-v"],
680 {
681 allowNonZeroExit: true,
682 timeoutMs: 5_000,
683 maxOutputBytes: 64 * 1024,
684 },
685 );
686
687 if (result.exitCode !== 0) {
688 return yield* new VcsProcessExitError({
689 operation: "GitVcsDriver.listRemotes",
690 command: "git remote -v",
691 cwd,
692 exitCode: result.exitCode,
693 detail: result.stderr.trim() || "git remote -v failed",
694 });
695 }
696
697 const parsed = parseGitRemoteVerboseOutput(result.stdout);
698 const remotes = Array.from(parsed.entries()).flatMap(([name, remote]) => {
699 if (!remote.url) {
700 return [];
701 }
702 return [
703 {
704 name,
705 url: remote.url,
706 pushUrl: remote.pushUrl ? Option.some(remote.pushUrl) : Option.none(),
707 isPrimary: name === "origin",
708 },
709 ];
710 });
711
712 return {
713 remotes,
714 freshness: yield* nowFreshness(),
715 };
716 },
717 );
718
719 const filterIgnoredPaths: VcsDriver.VcsDriver["Service"]["filterIgnoredPaths"] = Effect.fn(
720 "filterIgnoredPaths",
721 )(function* (cwd, relativePaths) {
722 if (relativePaths.length === 0) {
723 return relativePaths;
724 }
725
726 const ignoredPaths = new Set<string>();
727 const chunks = chunkPathsForGitCheckIgnore(relativePaths);
728
729 for (const chunk of chunks) {
730 const result = yield* gitCommand(
731 vcsProcess,
732 "GitVcsDriver.filterIgnoredPaths",
733 cwd,
734 [...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
735 {
736 stdin: `${chunk.join("\0")}\0`,
737 allowNonZeroExit: true,
738 timeoutMs: 20_000,
739 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
740 appendTruncationMarker: true,
741 },
742 );
743
744 if (result.exitCode !== 0 && result.exitCode !== 1) {
745 return yield* new VcsProcessExitError({
746 operation: "GitVcsDriver.filterIgnoredPaths",
747 command: "git check-ignore",
748 cwd,
749 exitCode: result.exitCode,
750 detail: result.stderr.trim() || "git check-ignore failed",
751 });
752 }
753
754 for (const ignoredPath of splitNullSeparatedGitStdoutPaths(result)) {
755 ignoredPaths.add(ignoredPath);
756 }
757 }
758
759 if (ignoredPaths.size === 0) {
760 return relativePaths;
761 }
762
763 return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
764 });
765
766 const initRepository: VcsDriver.VcsDriver["Service"]["initRepository"] = (input) =>
767 gitCommand(vcsProcess, "GitVcsDriver.initRepository", input.cwd, ["init"], {
768 timeoutMs: 10_000,
769 maxOutputBytes: 64 * 1024,
770 }).pipe(Effect.asVoid);
771
772 const resolveHeadCommit = (cwd: string) =>
773 execute({
774 operation: "GitVcsDriver.checkpoints.resolveHeadCommit",
775 cwd,
776 args: ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
777 allowNonZeroExit: true,
778 }).pipe(
779 Effect.map((result) => {
780 if (result.exitCode !== 0) {
781 return null;
782 }
783 const commit = result.stdout.trim();
784 return commit.length > 0 ? commit : null;
785 }),
786 );
787
788 const hasHeadCommit = (cwd: string, env?: NodeJS.ProcessEnv) =>
789 execute({
790 operation: "GitVcsDriver.checkpoints.hasHeadCommit",
791 cwd,
792 args: ["rev-parse", "--verify", "HEAD"],
793 allowNonZeroExit: true,
794 ...(env !== undefined ? { env } : {}),
795 }).pipe(Effect.map((result) => result.exitCode === 0));
796
797 const resolveCheckpointCommit = (cwd: string, checkpointRef: string) =>
798 execute({
799 operation: "GitVcsDriver.checkpoints.resolveCheckpointCommit",
800 cwd,
801 args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`],
802 allowNonZeroExit: true,
803 }).pipe(
804 Effect.map((result) => {
805 if (result.exitCode !== 0) {
806 return null;
807 }
808 const commit = result.stdout.trim();
809 return commit.length > 0 ? commit : null;
810 }),
811 );
812
813 // Git reports relative paths from the physical cwd, which can differ from a symlink.
814 const resolveGitCommonDir = Effect.fn("GitVcsDriver.resolveGitCommonDir")(function* (
815 cwd: string,
816 ) {
817 const result = yield* execute({
818 operation: "GitVcsDriver.checkpoints.resolveGitCommonDir",
819 cwd,
820 args: ["rev-parse", "--git-common-dir"],
821 });
822 const gitCommonDir = result.stdout.trim();
823 if (path.isAbsolute(gitCommonDir)) return gitCommonDir;
824 const physicalCwd = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd));
825 return path.resolve(physicalCwd, gitCommonDir);
826 });
827
828 // Git defaults and macOS writeout-only can leave empty refs after crashes; flush before publication.
829 // Set fsync first: Git 2.36 ignores unknown batch without resetting the method.
830 // Batch fully flushes refs and equals fsync on macOS HFS+/APFS and Windows NTFS/ReFS.
831 // Keep per-object fsync elsewhere; VcsProcess retries unsupported macOS full flushes with plain fsync.
832 const durableWrite = [
833 "-c",
834 "core.fsync=objects,reference",
835 "-c",
836 "core.fsyncMethod=fsync",
837 ...(hostPlatform === "darwin" || hostPlatform === "win32"
838 ? ["-c", "core.fsyncMethod=batch"]
839 : []),
840 ] as const;
841
842 // Checkpoints must handle existing paths beyond Windows MAX_PATH, even when
843 // core.longpaths is disabled in the user's Git configuration.
844 const longPaths = hostPlatform === "win32" ? ["-c", "core.longpaths=true"] : [];
845
846 const checkpoints: VcsDriver.VcsCheckpointOps = {
847 captureCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureCheckpoint")(function* (input) {
848 const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION;
849 // Scratch split-index writes can expire sharedindex files still used by the real index.
850 const indexConfig = [
851 "-c",
852 "core.fsmonitor=false",
853 "-c",
854 "sparse.expectFilesOutsideOfPatterns=false",
855 "-c",
856 "core.splitIndex=false",
857 "-c",
858 "splitIndex.sharedIndexExpire=never",
859 ];
860 const gitCommonDir = yield* resolveGitCommonDir(input.cwd);
861 const indexId = yield* crypto.randomUUIDv4().pipe(Effect.orDie);
862 const tempIndexPath = path.join(gitCommonDir, `t3-checkpoint-index-${indexId}`);
863 const commitEnv: NodeJS.ProcessEnv = {
864 ...process.env,
865 GIT_INDEX_FILE: tempIndexPath,
866 GIT_AUTHOR_NAME: "T3 Code",
867 GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com",
868 GIT_COMMITTER_NAME: "T3 Code",
869 GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com",
870 };
871
872 const cleanupTempIndex = Effect.forEach(
873 [tempIndexPath, `${tempIndexPath}.lock`],
874 (indexFile) => fileSystem.remove(indexFile, { force: true }).pipe(Effect.ignore),
875 { discard: true },
876 );
877
878 yield* Effect.gen(function* () {
879 const headExists = yield* hasHeadCommit(input.cwd);
880 const sparseConfig = yield* execute({
881 operation,
882 cwd: input.cwd,
883 args: ["config", "--bool", "core.sparseCheckout"],
884 allowNonZeroExit: true,
885 });
886 let sparseCheckout = sparseConfig.stdout.trim() === "true";
887 if (sparseCheckout) {
888 const help = yield* execute({
889 operation,
890 cwd: input.cwd,
891 args: ["add", "-h"],
892 allowNonZeroExit: true,
893 });
894 sparseCheckout = /--(?:\[no-\])?sparse\b/.test(`${help.stdout}${help.stderr}`);
895 }
896 if (headExists) {
897 const reusedIndex = yield* Effect.gen(function* () {
898 const indexPath = yield* execute({
899 operation,
900 cwd: input.cwd,
901 args: ["rev-parse", "--path-format=absolute", "--git-path", "index"],
902 });
903 const { mtime } = yield* fileSystem.stat(indexPath.stdout.trim());
904 if (Option.isNone(mtime)) return false;
905 // Stay below the source timestamp even if Date rounded up, preserving Git's racy check.
906 const indexTime = Math.floor((mtime.value.getTime() - 1) / 1000);
907 if (indexTime <= 0) return false;
908 yield* fileSystem.copyFile(indexPath.stdout.trim(), tempIndexPath);
909 yield* execute({
910 operation,
911 cwd: input.cwd,
912 args: [...indexConfig, "read-tree", "--reset", "HEAD"],
913 env: commitEnv,
914 });
915 // read-tree can rewrite the index, so restore its racy timestamp afterward.
916 yield* fileSystem.utimes(tempIndexPath, indexTime, indexTime);
917 let specialFlags = false;
918 let recordStart = true;
919 let skipped = false;
920 let skippedRecord: Uint8Array[] = [];
921 const skippedPaths: string[] = [];
922 yield* vcsProcess.run({
923 operation,
924 command: "git",
925 cwd: input.cwd,
926 args: [...indexConfig, "ls-files", "--full-name", "--sparse", "-v", "-z"],
927 env: commitEnv,
928 maxOutputBytes: 4_096,
929 outputMode: "truncate",
930 // Only tags and sparse skip-worktree paths matter; scan NUL-delimited records.
931 onStdoutChunk: (chunk) => {
932 let start = 0;
933 while (start < chunk.length) {
934 const end = chunk.indexOf(0, start);
935 if (recordStart) {
936 const tag = chunk[start]!;
937 skipped = tag === 83;
938 if ((tag >= 97 && tag <= 122) || (!sparseCheckout && tag === 83)) {
939 specialFlags = true;
940 }
941 }
942 if (skipped && sparseCheckout) {
943 skippedRecord.push(
944 Buffer.from(chunk.subarray(start, end === -1 ? undefined : end)),
945 );
946 if (end !== -1) {
947 const record = Buffer.concat(skippedRecord);
948 if (record.at(-1) !== 47) {
949 const name = record.subarray(2);
950 if (!NodeBuffer.isUtf8(name)) specialFlags = true;
951 else skippedPaths.push(name.toString("utf8"));
952 }
953 skippedRecord = [];
954 }
955 }
956 recordStart = end !== -1;
957 if (!recordStart) break;
958 start = end + 1;
959 }
960 },
961 });
962 if (skippedPaths.length > 0 && !specialFlags) {
963 const selected = yield* execute({
964 operation,
965 cwd: input.cwd,
966 args: [...indexConfig, "sparse-checkout", "check-rules", "-z"],
967 stdin: skippedPaths.join("\0") + "\0",
968 env: commitEnv,
969 maxOutputBytes: 1,
970 outputMode: "truncate",
971 });
972 specialFlags = selected.stdout.length > 0 || selected.stdoutTruncated;
973 }
974 // Sparse Git clears skip-worktree for present files. Manual flags still need a reset.
975 return !specialFlags;
976 }).pipe(Effect.orElseSucceed(() => false));
977 if (!reusedIndex) {
978 if (sparseCheckout) {
979 const cone = yield* execute({
980 operation,
981 cwd: input.cwd,
982 args: ["config", "--bool", "core.sparseCheckoutCone"],
983 allowNonZeroExit: true,
984 });
985 // Rebuilding a non-cone index loses exclusions; do not publish false deletions.
986 if (cone.stdout.trim() !== "true") {
987 return yield* new VcsProcessExitError({
988 operation,
989 command: "git read-tree",
990 cwd: input.cwd,
991 exitCode: 1,
992 detail: "Cannot rebuild a checkpoint index for non-cone sparse checkout.",
993 });
994 }
995 }
996 yield* cleanupTempIndex;
997 yield* execute({
998 operation,
999 cwd: input.cwd,
1000 args: sparseCheckout
1001 ? [...indexConfig, "-c", "index.sparse=true", "read-tree", "--reset", "HEAD"]
1002 : [...indexConfig, "read-tree", "HEAD"],
1003 env: commitEnv,
1004 });
1005 }
1006 }
1007
1008 const workspaceIgnored = (yield* filterIgnoredPaths(input.cwd, ["."])).length === 0;
1009 if (workspaceIgnored) {
1010 // HEAD omits staged-only paths. Seed just this workspace's additions, keeping
1011 // unrelated staged changes and the scratch index's sparse flags untouched.
1012 const additions = yield* execute({
1013 operation,
1014 cwd: input.cwd,
1015 args: [
1016 "-c",
1017 "core.quotePath=true",
1018 "diff",
1019 "--cached",
1020 "--raw",
1021 "--no-abbrev",
1022 "--no-renames",
1023 "--no-relative",
1024 "--ignore-submodules=none",
1025 "--no-color",
1026 "--no-ext-diff",
1027 "--no-textconv",
1028 "--ita-visible-in-index",
1029 "--diff-filter=A",
1030 "--",
1031 ".",
1032 ],
1033 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
1034 outputMode: "error",
1035 });
1036 if (additions.stdout.length > 0) {
1037 // Git's quoted paths round-trip through index-info, including non-UTF-8 names.
1038 yield* execute({
1039 operation,
1040 cwd: input.cwd,
1041 args: [...indexConfig, "-c", "index.sparse=false", "update-index", "--index-info"],
1042 stdin: additions.stdout.replace(
1043 /^:000000 ([0-7]{6}) 0+ ([0-9a-f]+) A\t/gm,
1044 "$1 $2\t",
1045 ),
1046 env: commitEnv,
1047 });
1048 }
1049 const tracked = yield* execute({
1050 operation,
1051 cwd: input.cwd,
1052 args: [...indexConfig, "ls-files", "--cached", "-z", "--", "."],
1053 env: commitEnv,
1054 maxOutputBytes: 1,
1055 outputMode: "truncate",
1056 });
1057 if (tracked.stdout.length === 0) {
1058 return yield* new VcsUnsupportedOperationError({
1059 operation,
1060 kind: "git",
1061 detail: "The workspace directory is ignored by its Git repository.",
1062 });
1063 }
1064 }
1065
1066 const stageFiles = (exclusions: ReadonlyArray<string>) =>
1067 execute({
1068 operation,
1069 cwd: input.cwd,
1070 args: [
1071 ...indexConfig,
1072 ...durableWrite,
1073 ...longPaths,
1074 "add",
1075 ...(sparseCheckout ? ["--sparse"] : []),
1076 // add -A rejects ignored directories even when they contain tracked files.
1077 workspaceIgnored ? "-u" : "-A",
1078 "--",
1079 ".",
1080 ...exclusions,
1081 ],
1082 env: commitEnv,
1083 });
1084 yield* stageFiles([]).pipe(
1085 Effect.catchTags({
1086 VcsProcessExitError: (error) =>
1087 Effect.gen(function* () {
1088 // Git cannot stage uncommitted embedded repos; scan for them only after staging fails.
1089 const untracked = yield* execute({
1090 operation,
1091 cwd: input.cwd,
1092 args: [
1093 ...longPaths,
1094 "ls-files",
1095 "--others",
1096 "--exclude-standard",
1097 "-z",
1098 "--",
1099 ".",
1100 ],
1101 env: commitEnv,
1102 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
1103 });
1104 if (untracked.stdoutTruncated) return yield* error;
1105 const candidates = splitNullSeparatedGitStdoutPaths(untracked).filter((entry) =>
1106 entry.endsWith("/"),
1107 );
1108 if (candidates.length > CHECKPOINT_RECOVERY_MAX_CANDIDATES) return yield* error;
1109 const nestedRepoEnv: NodeJS.ProcessEnv = {
1110 ...process.env,
1111 GIT_DIR: undefined,
1112 GIT_WORK_TREE: undefined,
1113 GIT_COMMON_DIR: undefined,
1114 GIT_INDEX_FILE: undefined,
1115 GIT_OBJECT_DIRECTORY: undefined,
1116 GIT_ALTERNATE_OBJECT_DIRECTORIES: undefined,
1117 };
1118 const exclusions: Array<string> = [];
1119 for (const entry of candidates) {
1120 const nestedCwd = path.join(input.cwd, entry);
1121 if (
1122 (yield* fileSystem
1123 .exists(path.join(nestedCwd, ".git"))
1124 .pipe(Effect.mapError(() => error))) &&
1125 !(yield* hasHeadCommit(nestedCwd, nestedRepoEnv))
1126 ) {
1127 exclusions.push(`:(exclude,literal)${entry}`);
1128 }
1129 }
1130 if (exclusions.length === 0) return yield* error;
1131 return yield* stageFiles(exclusions);
1132 }).pipe(
1133 Effect.timeoutOrElse({
1134 duration: CHECKPOINT_RECOVERY_TIMEOUT,
1135 orElse: () => Effect.fail(error),
1136 }),
1137 ),
1138 }),
1139 );
1140
1141 const writeTreeResult = yield* execute({
1142 operation,
1143 cwd: input.cwd,
1144 args: [...indexConfig, ...durableWrite, "write-tree"],
1145 env: commitEnv,
1146 });
1147 const treeOid = writeTreeResult.stdout.trim();
1148 if (treeOid.length === 0) {
1149 return yield* new VcsProcessExitError({
1150 operation,
1151 command: "git write-tree",
1152 cwd: input.cwd,
1153 exitCode: 0,
1154 detail: "git write-tree returned an empty tree oid.",
1155 });
1156 }
1157
1158 const message = `t3 checkpoint ref=${input.checkpointRef}`;
1159 // HEAD is the parent so listAuthoredPaths can see how HEAD moved between checkpoints.
1160 const commitTreeResult = yield* execute({
1161 operation,
1162 cwd: input.cwd,
1163 args: [
1164 ...durableWrite,
1165 "commit-tree",
1166 treeOid,
1167 ...(headExists ? ["-p", "HEAD"] : []),
1168 "-m",
1169 message,
1170 ],
1171 env: commitEnv,
1172 });
1173 const commitOid = commitTreeResult.stdout.trim();
1174 if (commitOid.length === 0) {
1175 return yield* new VcsProcessExitError({
1176 operation,
1177 command: "git commit-tree",
1178 cwd: input.cwd,
1179 exitCode: 0,
1180 detail: "git commit-tree returned an empty commit oid.",
1181 });
1182 }
1183
1184 yield* execute({
1185 operation,
1186 cwd: input.cwd,
1187 args: [...durableWrite, "update-ref", input.checkpointRef, commitOid],
1188 });
1189 }).pipe(Effect.ensuring(cleanupTempIndex));
1190 }),
1191
1192 hasCheckpointRef: (input) =>
1193 resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
1194 Effect.map((commit) => commit !== null),
1195 ),
1196
1197 restoreCheckpoint: Effect.fn("GitVcsDriver.checkpoints.restoreCheckpoint")(function* (input) {
1198 const operation = "GitVcsDriver.checkpoints.restoreCheckpoint";
1199
1200 let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
1201
1202 if (!commitOid && input.fallbackToHead === true) {
1203 commitOid = yield* resolveHeadCommit(input.cwd);
1204 }
1205
1206 if (!commitOid) {
1207 return false;
1208 }
1209
1210 const tracked = yield* execute({
1211 operation,
1212 cwd: input.cwd,
1213 args: ["ls-files", "--cached", `--with-tree=${commitOid}`, "-z", "--", "."],
1214 });
1215 // An empty index and checkpoint have nothing for git restore's pathspec to match.
1216 if (tracked.stdout.length > 0) {
1217 yield* execute({
1218 operation,
1219 cwd: input.cwd,
1220 args: [
1221 ...longPaths,
1222 "restore",
1223 "--source",
1224 commitOid,
1225 "--worktree",
1226 "--staged",
1227 "--",
1228 ".",
1229 ],
1230 });
1231 }
1232 // Restoring away the last tracked file can remove a nested workspace directory.
1233 const recreateWorkspace = fileSystem.makeDirectory(input.cwd, { recursive: true }).pipe(
1234 Effect.mapError(
1235 (cause) =>
1236 new VcsProcessExitError({
1237 operation,
1238 command: "git restore",
1239 cwd: input.cwd,
1240 exitCode: 0,
1241 detail: `Could not recreate the checkpoint workspace: ${cause.message}`,
1242 }),
1243 ),
1244 );
1245 yield* recreateWorkspace;
1246 const cleaned = yield* execute({
1247 operation,
1248 cwd: input.cwd,
1249 args: [...longPaths, "clean", "-fd", "--", "."],
1250 allowNonZeroExit: true,
1251 });
1252 if (cleaned.exitCode !== 0) {
1253 // Git can remove every child, then fail trying to remove './' itself.
1254 const emptiedWorkspace =
1255 cleaned.exitCode === 1 &&
1256 /^warning: failed to remove \.\/: [^\n]+$/.test(cleaned.stderr.trim()) &&
1257 (yield* fileSystem.readDirectory(input.cwd).pipe(
1258 Effect.map((entries) => entries.length === 0),
1259 Effect.orElseSucceed(() => false),
1260 ));
1261 if (!emptiedWorkspace)
1262 return yield* new VcsProcessExitError({
1263 operation,
1264 command: "git clean",
1265 cwd: input.cwd,
1266 exitCode: cleaned.exitCode,
1267 detail: cleaned.stderr.trim() || "Could not clean the checkpoint workspace.",
1268 });
1269 }
1270 // On Windows the same clean can remove './' and exit 0.
1271 yield* recreateWorkspace;
1272
1273 const headExists = yield* hasHeadCommit(input.cwd);
1274 if (headExists) {
1275 yield* execute({
1276 operation,
1277 cwd: input.cwd,
1278 args: [...longPaths, "reset", "--quiet", "--", "."],
1279 });
1280 }
1281
1282 return true;
1283 }),
1284
1285 diffCheckpoints: Effect.fn("GitVcsDriver.checkpoints.diffCheckpoints")(function* (input) {
1286 const operation = "GitVcsDriver.checkpoints.diffCheckpoints";
1287 if (input.filePaths?.length === 0) return "";
1288 yield* Effect.annotateCurrentSpan({
1289 "checkpoint.cwd": input.cwd,
1290 "checkpoint.from_ref": input.fromCheckpointRef,
1291 "checkpoint.to_ref": input.toCheckpointRef,
1292 "checkpoint.ignore_whitespace": input.ignoreWhitespace,
1293 "checkpoint.format": input.format ?? "patch",
1294 "checkpoint.fallback_from_to_head": input.fallbackFromToHead,
1295 });
1296
1297 let fromRevision: string = input.fromCheckpointRef;
1298 if (input.fallbackFromToHead === true) {
1299 const resolvedFromCommit = yield* resolveCheckpointCommit(
1300 input.cwd,
1301 input.fromCheckpointRef,
1302 );
1303 if (resolvedFromCommit) {
1304 fromRevision = resolvedFromCommit;
1305 } else {
1306 const headCommit = yield* resolveHeadCommit(input.cwd);
1307 if (!headCommit) {
1308 return yield* new VcsProcessExitError({
1309 operation,
1310 command: "git diff",
1311 cwd: input.cwd,
1312 exitCode: 1,
1313 detail: "Checkpoint ref is unavailable for diff operation.",
1314 });
1315 }
1316 fromRevision = headCommit;
1317 }
1318 }
1319
1320 const result = yield* execute({
1321 operation,
1322 cwd: input.cwd,
1323 args: [
1324 "diff",
1325 ...(input.format === "numstat" ? ["--numstat", "-z"] : ["--patch"]),
1326 "--no-color",
1327 "--no-ext-diff",
1328 "--no-textconv",
1329 ...PATCH_RENDER_PREFIX_ARGS,
1330 ...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
1331 `${fromRevision}^{commit}`,
1332 `${input.toCheckpointRef}^{commit}`,
1333 // Paths are repository-relative, while cwd can be a subdirectory.
1334 ...(input.filePaths
1335 ? ["--", ...input.filePaths.map((file) => `:(top,literal)${file}`)]
1336 : []),
1337 ],
1338 allowNonZeroExit: true,
1339 maxOutputBytes: input.maxOutputBytes ?? VcsDriver.CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
1340 outputMode: input.format === "numstat" ? "error" : "truncate",
1341 });
1342
1343 if (result.exitCode !== 0) {
1344 return yield* new VcsProcessExitError({
1345 operation,
1346 command: "git diff",
1347 cwd: input.cwd,
1348 exitCode: result.exitCode,
1349 detail: result.stderr.trim() || "Checkpoint ref is unavailable for diff operation.",
1350 });
1351 }
1352
1353 return result.stdout;
1354 }),
1355
1356 listAuthoredPaths: Effect.fn("GitVcsDriver.checkpoints.listAuthoredPaths")(function* (input) {
1357 const operation = "GitVcsDriver.checkpoints.listAuthoredPaths";
1358 const heads = yield* execute({
1359 operation,
1360 cwd: input.cwd,
1361 args: [
1362 "log",
1363 "--no-walk=unsorted",
1364 "--format=%P %ct",
1365 `${input.fromCheckpointRef}^{commit}`,
1366 `${input.toCheckpointRef}^{commit}`,
1367 ],
1368 });
1369 const [fromLine = "", toLine = ""] = heads.stdout.trimEnd().split("\n");
1370 const [startHead = "", capturedAt = ""] = fromLine.split(" ");
1371 const [endHead = ""] = toLine.split(" ");
1372 if (startHead === "" || endHead === "" || startHead === endHead) {
1373 return null;
1374 }
1375
1376 const listPaths = (args: ReadonlyArray<string>) =>
1377 execute({
1378 operation,
1379 cwd: input.cwd,
1380 args: [...args, "--name-only", "-z", "--no-renames", "--no-ext-diff"],
1381 maxOutputBytes: VcsDriver.CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
1382 outputMode: "error",
1383 }).pipe(Effect.map((result) => result.stdout.split("\0")));
1384 // Remerge diffs retain merge conflict fixes while excluding clean upstream changes.
1385 const pathLists = yield* Effect.all(
1386 [
1387 listPaths(["diff", startHead, `${input.fromCheckpointRef}^{commit}`]),
1388 listPaths(["diff", endHead, `${input.toCheckpointRef}^{commit}`]),
1389 listPaths(["log", "--format=", "--diff-merges=remerge", `${endHead}..${startHead}`]),
1390 listPaths([
1391 "log",
1392 "--format=",
1393 "--diff-merges=remerge",
1394 `--since=@${capturedAt}`,
1395 `${startHead}..${endHead}`,
1396 ]),
1397 ],
1398 { concurrency: "unbounded" },
1399 );
1400 return new Set(pathLists.flat().filter((path) => path.length > 0));
1401 }),
1402
1403 deleteCheckpointRefs: Effect.fn("GitVcsDriver.checkpoints.deleteCheckpointRefs")(
1404 function* (input) {
1405 yield* Effect.forEach(
1406 input.checkpointRefs,
1407 (checkpointRef) =>
1408 execute({
1409 operation: "GitVcsDriver.checkpoints.deleteCheckpointRefs",
1410 cwd: input.cwd,
1411 args: ["update-ref", "-d", checkpointRef],
1412 allowNonZeroExit: true,
1413 }),
1414 { discard: true },
1415 );
1416 },
1417 ),
1418 };
1419
1420 return {
1421 execute,
1422 checkpoints,
1423 detectRepository,
1424 isInsideWorkTree,
1425 listWorkspaceFiles,
1426 listRemotes,
1427 filterIgnoredPaths,
1428 initRepository,
1429 };
1430});
1431
1432export const makeVcsDriver = Effect.gen(function* () {
1433 const driver = yield* makeVcsDriverShape();
1434 return VcsDriver.VcsDriver.of(driver);
1435});
1436
1437export const make = Effect.gen(function* () {
1438 const git = yield* makeGitVcsDriverCore();
1439 return GitVcsDriver.of(git);
1440});
1441
1442export const layerVcs = Layer.effect(VcsDriver.VcsDriver, makeVcsDriver);
1443export const layer = Layer.effect(GitVcsDriver, make);