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

GitVcsDriver.ts

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