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

GitVcsDriver.ts

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