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 = (cwd: string) =>
787 Effect.gen(function* () {
788 const result = yield* execute({
789 operation: "GitVcsDriver.checkpoints.resolveGitCommonDir",
790 cwd,
791 args: ["rev-parse", "--git-common-dir"],
792 });
793 const gitCommonDir = result.stdout.trim();
794 return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
795 });
796
797 // Git renames loose objects and refs into place without fsync by default, so
798 // an unclean restart can leave 0-byte files under refs/t3/** that break every
799 // later fetch and push. Checkpoint writes flush before they are published;
800 // macOS defaults to writeout-only, which does not reach the disk either.
801 // On macOS, VcsProcess retries unsupported full flushes with plain fsync.
802 const durableWrite = [
803 "-c",
804 "core.fsync=objects,reference",
805 "-c",
806 "core.fsyncMethod=fsync",
807 ] as const;
808
809 // Checkpoints must handle existing paths beyond Windows MAX_PATH, even when
810 // core.longpaths is disabled in the user's Git configuration.
811 const longPaths = (yield* HostProcess.Platform) === "win32" ? ["-c", "core.longpaths=true"] : [];
812
813 const checkpoints: VcsDriver.VcsCheckpointOps = {
814 captureCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureCheckpoint")(function* (input) {
815 const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION;
816 // core.splitIndex governs every index Git writes, so an unguarded write to the
817 // scratch index can expire the sharedindex.* the real .git/index still uses.
818 const indexConfig = [
819 "-c",
820 "core.fsmonitor=false",
821 "-c",
822 "sparse.expectFilesOutsideOfPatterns=false",
823 "-c",
824 "core.splitIndex=false",
825 "-c",
826 "splitIndex.sharedIndexExpire=never",
827 ];
828 const gitCommonDir = yield* resolveGitCommonDir(input.cwd);
829 const indexId = yield* crypto.randomUUIDv4().pipe(Effect.orDie);
830 const tempIndexPath = path.join(gitCommonDir, `t3-checkpoint-index-${indexId}`);
831 const commitEnv: NodeJS.ProcessEnv = {
832 ...process.env,
833 GIT_INDEX_FILE: tempIndexPath,
834 GIT_AUTHOR_NAME: "T3 Code",
835 GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com",
836 GIT_COMMITTER_NAME: "T3 Code",
837 GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com",
838 };
839
840 const cleanupTempIndex = Effect.forEach(
841 [tempIndexPath, `${tempIndexPath}.lock`],
842 (indexFile) => fileSystem.remove(indexFile, { force: true }).pipe(Effect.ignore),
843 { discard: true },
844 );
845
846 yield* Effect.gen(function* () {
847 const headExists = yield* hasHeadCommit(input.cwd);
848 const sparseConfig = yield* execute({
849 operation,
850 cwd: input.cwd,
851 args: ["config", "--bool", "core.sparseCheckout"],
852 allowNonZeroExit: true,
853 });
854 let sparseCheckout = sparseConfig.stdout.trim() === "true";
855 if (sparseCheckout) {
856 const help = yield* execute({
857 operation,
858 cwd: input.cwd,
859 args: ["add", "-h"],
860 allowNonZeroExit: true,
861 });
862 sparseCheckout = /--(?:\[no-\])?sparse\b/.test(`${help.stdout}${help.stderr}`);
863 }
864 if (headExists) {
865 const reusedIndex = yield* Effect.gen(function* () {
866 const indexPath = yield* execute({
867 operation,
868 cwd: input.cwd,
869 args: ["rev-parse", "--path-format=absolute", "--git-path", "index"],
870 });
871 const { mtime } = yield* fileSystem.stat(indexPath.stdout.trim());
872 if (Option.isNone(mtime)) return false;
873 // Stay below the source timestamp even if Date rounded up, preserving Git's racy check.
874 const indexTime = Math.floor((mtime.value.getTime() - 1) / 1000);
875 if (indexTime <= 0) return false;
876 yield* fileSystem.copyFile(indexPath.stdout.trim(), tempIndexPath);
877 yield* execute({
878 operation,
879 cwd: input.cwd,
880 args: [...indexConfig, "read-tree", "--reset", "HEAD"],
881 env: commitEnv,
882 });
883 // read-tree can rewrite the index, so restore its racy timestamp afterward.
884 yield* fileSystem.utimes(tempIndexPath, indexTime, indexTime);
885 let specialFlags = false;
886 let recordStart = true;
887 let skipped = false;
888 let skippedRecord: number[] = [];
889 const skippedPaths: string[] = [];
890 yield* vcsProcess.run({
891 operation,
892 command: "git",
893 cwd: input.cwd,
894 args: [...indexConfig, "ls-files", "--full-name", "--sparse", "-v", "-z"],
895 env: commitEnv,
896 maxOutputBytes: 4_096,
897 outputMode: "truncate",
898 onStdoutChunk: (chunk) => {
899 for (const byte of chunk) {
900 if (recordStart) skipped = byte === 83;
901 if (skipped && sparseCheckout) {
902 if (byte !== 0) skippedRecord.push(byte);
903 else {
904 if (skippedRecord.at(-1) !== 47) {
905 const name = Buffer.from(skippedRecord).subarray(2);
906 if (!NodeBuffer.isUtf8(name)) specialFlags = true;
907 else skippedPaths.push(name.toString("utf8"));
908 }
909 skippedRecord = [];
910 }
911 }
912 if (
913 recordStart &&
914 ((byte >= 97 && byte <= 122) || (!sparseCheckout && byte === 83))
915 ) {
916 specialFlags = true;
917 }
918 recordStart = byte === 0;
919 }
920 },
921 });
922 if (skippedPaths.length > 0 && !specialFlags) {
923 const selected = yield* execute({
924 operation,
925 cwd: input.cwd,
926 args: [...indexConfig, "sparse-checkout", "check-rules", "-z"],
927 stdin: skippedPaths.join("\0") + "\0",
928 env: commitEnv,
929 maxOutputBytes: 1,
930 outputMode: "truncate",
931 });
932 specialFlags = selected.stdout.length > 0 || selected.stdoutTruncated;
933 }
934 // Sparse Git clears skip-worktree for present files. Manual flags still need a reset.
935 return !specialFlags;
936 }).pipe(Effect.orElseSucceed(() => false));
937 if (!reusedIndex) {
938 if (sparseCheckout) {
939 const cone = yield* execute({
940 operation,
941 cwd: input.cwd,
942 args: ["config", "--bool", "core.sparseCheckoutCone"],
943 allowNonZeroExit: true,
944 });
945 // Rebuilding a non-cone index loses exclusions; do not publish false deletions.
946 if (cone.stdout.trim() !== "true") {
947 return yield* new VcsProcessExitError({
948 operation,
949 command: "git read-tree",
950 cwd: input.cwd,
951 exitCode: 1,
952 detail: "Cannot rebuild a checkpoint index for non-cone sparse checkout.",
953 });
954 }
955 }
956 yield* cleanupTempIndex;
957 yield* execute({
958 operation,
959 cwd: input.cwd,
960 args: sparseCheckout
961 ? [...indexConfig, "-c", "index.sparse=true", "read-tree", "--reset", "HEAD"]
962 : [...indexConfig, "read-tree", "HEAD"],
963 env: commitEnv,
964 });
965 }
966 }
967
968 const workspaceIgnored = (yield* filterIgnoredPaths(input.cwd, ["."])).length === 0;
969 if (workspaceIgnored) {
970 // HEAD omits staged-only paths. Seed just this workspace's additions, keeping
971 // unrelated staged changes and the scratch index's sparse flags untouched.
972 const additions = yield* execute({
973 operation,
974 cwd: input.cwd,
975 args: [
976 "-c",
977 "core.quotePath=true",
978 "diff",
979 "--cached",
980 "--raw",
981 "--no-abbrev",
982 "--no-renames",
983 "--no-relative",
984 "--ignore-submodules=none",
985 "--no-color",
986 "--no-ext-diff",
987 "--no-textconv",
988 "--ita-visible-in-index",
989 "--diff-filter=A",
990 "--",
991 ".",
992 ],
993 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
994 outputMode: "error",
995 });
996 if (additions.stdout.length > 0) {
997 // Git's quoted paths round-trip through index-info, including non-UTF-8 names.
998 yield* execute({
999 operation,
1000 cwd: input.cwd,
1001 args: [...indexConfig, "-c", "index.sparse=false", "update-index", "--index-info"],
1002 stdin: additions.stdout.replace(
1003 /^:000000 ([0-7]{6}) 0+ ([0-9a-f]+) A\t/gm,
1004 "$1 $2\t",
1005 ),
1006 env: commitEnv,
1007 });
1008 }
1009 const tracked = yield* execute({
1010 operation,
1011 cwd: input.cwd,
1012 args: [...indexConfig, "ls-files", "--cached", "-z", "--", "."],
1013 env: commitEnv,
1014 maxOutputBytes: 1,
1015 outputMode: "truncate",
1016 });
1017 if (tracked.stdout.length === 0) {
1018 return yield* new VcsUnsupportedOperationError({
1019 operation,
1020 kind: "git",
1021 detail: "The workspace directory is ignored by its Git repository.",
1022 });
1023 }
1024 }
1025
1026 const stageFiles = (exclusions: ReadonlyArray<string>) =>
1027 execute({
1028 operation,
1029 cwd: input.cwd,
1030 args: [
1031 ...indexConfig,
1032 ...durableWrite,
1033 ...longPaths,
1034 "add",
1035 ...(sparseCheckout ? ["--sparse"] : []),
1036 // add -A rejects ignored directories even when they contain tracked files.
1037 workspaceIgnored ? "-u" : "-A",
1038 "--",
1039 ".",
1040 ...exclusions,
1041 ],
1042 env: commitEnv,
1043 });
1044 yield* stageFiles([]).pipe(
1045 Effect.catchTags({
1046 VcsProcessExitError: (error) =>
1047 Effect.gen(function* () {
1048 // Git cannot stage an embedded repository until it has a commit. Discover these
1049 // only after staging fails so ordinary checkpoints do not need another file scan.
1050 const untracked = yield* execute({
1051 operation,
1052 cwd: input.cwd,
1053 args: [
1054 ...longPaths,
1055 "ls-files",
1056 "--others",
1057 "--exclude-standard",
1058 "-z",
1059 "--",
1060 ".",
1061 ],
1062 env: commitEnv,
1063 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
1064 });
1065 if (untracked.stdoutTruncated) return yield* error;
1066 const candidates = splitNullSeparatedGitStdoutPaths(untracked).filter((entry) =>
1067 entry.endsWith("/"),
1068 );
1069 if (candidates.length > CHECKPOINT_RECOVERY_MAX_CANDIDATES) return yield* error;
1070 const nestedRepoEnv: NodeJS.ProcessEnv = {
1071 ...process.env,
1072 GIT_DIR: undefined,
1073 GIT_WORK_TREE: undefined,
1074 GIT_COMMON_DIR: undefined,
1075 GIT_INDEX_FILE: undefined,
1076 GIT_OBJECT_DIRECTORY: undefined,
1077 GIT_ALTERNATE_OBJECT_DIRECTORIES: undefined,
1078 };
1079 const exclusions: Array<string> = [];
1080 for (const entry of candidates) {
1081 const nestedCwd = path.join(input.cwd, entry);
1082 if (
1083 (yield* fileSystem
1084 .exists(path.join(nestedCwd, ".git"))
1085 .pipe(Effect.mapError(() => error))) &&
1086 !(yield* hasHeadCommit(nestedCwd, nestedRepoEnv))
1087 ) {
1088 exclusions.push(`:(exclude,literal)${entry}`);
1089 }
1090 }
1091 if (exclusions.length === 0) return yield* error;
1092 return yield* stageFiles(exclusions);
1093 }).pipe(
1094 Effect.timeoutOrElse({
1095 duration: CHECKPOINT_RECOVERY_TIMEOUT,
1096 orElse: () => Effect.fail(error),
1097 }),
1098 ),
1099 }),
1100 );
1101
1102 const writeTreeResult = yield* execute({
1103 operation,
1104 cwd: input.cwd,
1105 args: [...indexConfig, ...durableWrite, "write-tree"],
1106 env: commitEnv,
1107 });
1108 const treeOid = writeTreeResult.stdout.trim();
1109 if (treeOid.length === 0) {
1110 return yield* new VcsProcessExitError({
1111 operation,
1112 command: "git write-tree",
1113 cwd: input.cwd,
1114 exitCode: 0,
1115 detail: "git write-tree returned an empty tree oid.",
1116 });
1117 }
1118
1119 const message = `t3 checkpoint ref=${input.checkpointRef}`;
1120 // HEAD is the parent so listAuthoredPaths can see how HEAD moved between checkpoints.
1121 const commitTreeResult = yield* execute({
1122 operation,
1123 cwd: input.cwd,
1124 args: [
1125 ...durableWrite,
1126 "commit-tree",
1127 treeOid,
1128 ...(headExists ? ["-p", "HEAD"] : []),
1129 "-m",
1130 message,
1131 ],
1132 env: commitEnv,
1133 });
1134 const commitOid = commitTreeResult.stdout.trim();
1135 if (commitOid.length === 0) {
1136 return yield* new VcsProcessExitError({
1137 operation,
1138 command: "git commit-tree",
1139 cwd: input.cwd,
1140 exitCode: 0,
1141 detail: "git commit-tree returned an empty commit oid.",
1142 });
1143 }
1144
1145 yield* execute({
1146 operation,
1147 cwd: input.cwd,
1148 args: [...durableWrite, "update-ref", input.checkpointRef, commitOid],
1149 });
1150 }).pipe(Effect.ensuring(cleanupTempIndex));
1151 }),
1152
1153 hasCheckpointRef: (input) =>
1154 resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
1155 Effect.map((commit) => commit !== null),
1156 ),
1157
1158 restoreCheckpoint: Effect.fn("GitVcsDriver.checkpoints.restoreCheckpoint")(function* (input) {
1159 const operation = "GitVcsDriver.checkpoints.restoreCheckpoint";
1160
1161 let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
1162
1163 if (!commitOid && input.fallbackToHead === true) {
1164 commitOid = yield* resolveHeadCommit(input.cwd);
1165 }
1166
1167 if (!commitOid) {
1168 return false;
1169 }
1170
1171 const tracked = yield* execute({
1172 operation,
1173 cwd: input.cwd,
1174 args: ["ls-files", "--cached", `--with-tree=${commitOid}`, "-z", "--", "."],
1175 });
1176 // An empty index and checkpoint have nothing for git restore's pathspec to match.
1177 if (tracked.stdout.length > 0) {
1178 yield* execute({
1179 operation,
1180 cwd: input.cwd,
1181 args: [
1182 ...longPaths,
1183 "restore",
1184 "--source",
1185 commitOid,
1186 "--worktree",
1187 "--staged",
1188 "--",
1189 ".",
1190 ],
1191 });
1192 }
1193 // Restoring away the last tracked file can remove a nested workspace directory.
1194 const recreateWorkspace = fileSystem.makeDirectory(input.cwd, { recursive: true }).pipe(
1195 Effect.mapError(
1196 (cause) =>
1197 new VcsProcessExitError({
1198 operation,
1199 command: "git restore",
1200 cwd: input.cwd,
1201 exitCode: 0,
1202 detail: `Could not recreate the checkpoint workspace: ${cause.message}`,
1203 }),
1204 ),
1205 );
1206 yield* recreateWorkspace;
1207 const cleaned = yield* execute({
1208 operation,
1209 cwd: input.cwd,
1210 args: [...longPaths, "clean", "-fd", "--", "."],
1211 allowNonZeroExit: true,
1212 });
1213 if (cleaned.exitCode !== 0) {
1214 // Git can remove every child, then fail trying to remove './' itself.
1215 const emptiedWorkspace =
1216 cleaned.exitCode === 1 &&
1217 /^warning: failed to remove \.\/: [^\n]+$/.test(cleaned.stderr.trim()) &&
1218 (yield* fileSystem.readDirectory(input.cwd).pipe(
1219 Effect.map((entries) => entries.length === 0),
1220 Effect.orElseSucceed(() => false),
1221 ));
1222 if (!emptiedWorkspace)
1223 return yield* new VcsProcessExitError({
1224 operation,
1225 command: "git clean",
1226 cwd: input.cwd,
1227 exitCode: cleaned.exitCode,
1228 detail: cleaned.stderr.trim() || "Could not clean the checkpoint workspace.",
1229 });
1230 }
1231 // On Windows the same clean can remove './' and exit 0.
1232 yield* recreateWorkspace;
1233
1234 const headExists = yield* hasHeadCommit(input.cwd);
1235 if (headExists) {
1236 yield* execute({
1237 operation,
1238 cwd: input.cwd,
1239 args: [...longPaths, "reset", "--quiet", "--", "."],
1240 });
1241 }
1242
1243 return true;
1244 }),
1245
1246 diffCheckpoints: Effect.fn("GitVcsDriver.checkpoints.diffCheckpoints")(function* (input) {
1247 const operation = "GitVcsDriver.checkpoints.diffCheckpoints";
1248 if (input.filePaths?.length === 0) return "";
1249 yield* Effect.annotateCurrentSpan({
1250 "checkpoint.cwd": input.cwd,
1251 "checkpoint.from_ref": input.fromCheckpointRef,
1252 "checkpoint.to_ref": input.toCheckpointRef,
1253 "checkpoint.ignore_whitespace": input.ignoreWhitespace,
1254 "checkpoint.format": input.format ?? "patch",
1255 "checkpoint.fallback_from_to_head": input.fallbackFromToHead,
1256 });
1257
1258 let fromRevision: string = input.fromCheckpointRef;
1259 if (input.fallbackFromToHead === true) {
1260 const resolvedFromCommit = yield* resolveCheckpointCommit(
1261 input.cwd,
1262 input.fromCheckpointRef,
1263 );
1264 if (resolvedFromCommit) {
1265 fromRevision = resolvedFromCommit;
1266 } else {
1267 const headCommit = yield* resolveHeadCommit(input.cwd);
1268 if (!headCommit) {
1269 return yield* new VcsProcessExitError({
1270 operation,
1271 command: "git diff",
1272 cwd: input.cwd,
1273 exitCode: 1,
1274 detail: "Checkpoint ref is unavailable for diff operation.",
1275 });
1276 }
1277 fromRevision = headCommit;
1278 }
1279 }
1280
1281 const result = yield* execute({
1282 operation,
1283 cwd: input.cwd,
1284 args: [
1285 "diff",
1286 ...(input.format === "numstat" ? ["--numstat", "-z"] : ["--patch"]),
1287 "--no-color",
1288 "--no-ext-diff",
1289 "--no-textconv",
1290 ...PATCH_RENDER_PREFIX_ARGS,
1291 ...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
1292 `${fromRevision}^{commit}`,
1293 `${input.toCheckpointRef}^{commit}`,
1294 // Paths are repository-relative, while cwd can be a subdirectory.
1295 ...(input.filePaths
1296 ? ["--", ...input.filePaths.map((file) => `:(top,literal)${file}`)]
1297 : []),
1298 ],
1299 allowNonZeroExit: true,
1300 maxOutputBytes: input.maxOutputBytes ?? VcsDriver.CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
1301 outputMode: input.format === "numstat" ? "error" : "truncate",
1302 });
1303
1304 if (result.exitCode !== 0) {
1305 return yield* new VcsProcessExitError({
1306 operation,
1307 command: "git diff",
1308 cwd: input.cwd,
1309 exitCode: result.exitCode,
1310 detail: result.stderr.trim() || "Checkpoint ref is unavailable for diff operation.",
1311 });
1312 }
1313
1314 return result.stdout;
1315 }),
1316
1317 listAuthoredPaths: Effect.fn("GitVcsDriver.checkpoints.listAuthoredPaths")(function* (input) {
1318 const operation = "GitVcsDriver.checkpoints.listAuthoredPaths";
1319 const heads = yield* execute({
1320 operation,
1321 cwd: input.cwd,
1322 args: [
1323 "log",
1324 "--no-walk=unsorted",
1325 "--format=%P %ct",
1326 `${input.fromCheckpointRef}^{commit}`,
1327 `${input.toCheckpointRef}^{commit}`,
1328 ],
1329 });
1330 const [fromLine = "", toLine = ""] = heads.stdout.trimEnd().split("\n");
1331 const [startHead = "", capturedAt = ""] = fromLine.split(" ");
1332 const [endHead = ""] = toLine.split(" ");
1333 if (startHead === "" || endHead === "" || startHead === endHead) {
1334 return null;
1335 }
1336
1337 const listPaths = (args: ReadonlyArray<string>) =>
1338 execute({
1339 operation,
1340 cwd: input.cwd,
1341 args: [...args, "--name-only", "-z", "--no-renames", "--no-ext-diff"],
1342 maxOutputBytes: VcsDriver.CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
1343 outputMode: "error",
1344 }).pipe(Effect.map((result) => result.stdout.split("\0")));
1345 // Remerge diff lists a merge's paths only where the result differs from Git's
1346 // automatic merge, so a merge keeps its conflict fixes and drops clean upstream changes.
1347 const pathLists = yield* Effect.all(
1348 [
1349 listPaths(["diff", startHead, `${input.fromCheckpointRef}^{commit}`]),
1350 listPaths(["diff", endHead, `${input.toCheckpointRef}^{commit}`]),
1351 listPaths(["log", "--format=", "--diff-merges=remerge", `${endHead}..${startHead}`]),
1352 listPaths([
1353 "log",
1354 "--format=",
1355 "--diff-merges=remerge",
1356 `--since=@${capturedAt}`,
1357 `${startHead}..${endHead}`,
1358 ]),
1359 ],
1360 { concurrency: "unbounded" },
1361 );
1362 return new Set(pathLists.flat().filter((path) => path.length > 0));
1363 }),
1364
1365 deleteCheckpointRefs: Effect.fn("GitVcsDriver.checkpoints.deleteCheckpointRefs")(
1366 function* (input) {
1367 yield* Effect.forEach(
1368 input.checkpointRefs,
1369 (checkpointRef) =>
1370 execute({
1371 operation: "GitVcsDriver.checkpoints.deleteCheckpointRefs",
1372 cwd: input.cwd,
1373 args: ["update-ref", "-d", checkpointRef],
1374 allowNonZeroExit: true,
1375 }),
1376 { discard: true },
1377 );
1378 },
1379 ),
1380 };
1381
1382 return {
1383 capabilities,
1384 execute,
1385 checkpoints,
1386 detectRepository,
1387 isInsideWorkTree,
1388 listWorkspaceFiles,
1389 listRemotes,
1390 filterIgnoredPaths,
1391 initRepository,
1392 };
1393});
1394
1395export const makeVcsDriver = Effect.gen(function* () {
1396 const driver = yield* makeVcsDriverShape();
1397 return VcsDriver.VcsDriver.of(driver);
1398});
1399
1400export const make = Effect.gen(function* () {
1401 const git = yield* makeGitVcsDriverCore();
1402 return GitVcsDriver.of(git);
1403});
1404
1405export const layerVcs = Layer.effect(VcsDriver.VcsDriver, makeVcsDriver);
1406export const layer = Layer.effect(GitVcsDriver, make);