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

GitVcsDriver.ts

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