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