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

GitVcsDriver.ts

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