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

GitVcsDriver.ts

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