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

GitVcsDriver.ts

1,224 lines40.7 KB

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