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

GitVcsDriver.ts

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