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

GitVcsDriver.ts

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