Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitVcsDriver.ts

1,408 lines47.1 KB

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