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

GitVcsDriver.ts

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