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

GitVcsDriver.ts

1,145 lines37.1 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 GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
383const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
384const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [
385 "-c",
386 "core.fsmonitor=false",
387 "-c",
388 "core.untrackedCache=false",
389] as const;
390​
391const nowFreshness = Effect.fn("GitVcsDriver.nowFreshness")(function* () {
392 const now = yield* DateTime.now;
393 return {
394 source: "live-local" as const,
395 observedAt: now,
396 expiresAt: Option.none(),
397 };
398});
399​
400function chunkPathsForGitCheckIgnore(relativePaths: ReadonlyArray<string>): string[][] {
401 const chunks: string[][] = [];
402 let chunk: string[] = [];
403 let chunkBytes = 0;
404​
405 for (const relativePath of relativePaths) {
406 const relativePathBytes = Buffer.byteLength(relativePath) + 1;
407 if (chunk.length > 0 && chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
408 chunks.push(chunk);
409 chunk = [];
410 chunkBytes = 0;
411 }
412​
413 chunk.push(relativePath);
414 chunkBytes += relativePathBytes;
415​
416 if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
417 chunks.push(chunk);
418 chunk = [];
419 chunkBytes = 0;
420 }
421 }
422​
423 if (chunk.length > 0) {
424 chunks.push(chunk);
425 }
426​
427 return chunks;
429​
430function parseGitRemoteVerboseOutput(
431 output: string,
432): Map<string, { url?: string; pushUrl?: string }> {
433 const remotes = new Map<string, { url?: string; pushUrl?: string }>();
434 for (const line of output.split("\n")) {
435 const trimmed = line.trim();
436 if (trimmed.length === 0) {
437 continue;
438 }
439​
440 const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed);
441 if (!match) {
442 continue;
443 }
444​
445 const name = match[1];
446 const url = match[2];
447 const direction = match[3];
448 if (!name || !url || !direction) {
449 continue;
450 }
451 const remote = remotes.get(name) ?? {};
452 if (direction === "fetch") {
453 remote.url = url;
454 } else {
455 remote.pushUrl = url;
456 }
457 remotes.set(name, remote);
458 }
459 return remotes;
461​
462const gitCommand = (
463 process: VcsProcess.VcsProcess["Service"],
464 operation: string,
465 cwd: string,
466 args: ReadonlyArray<string>,
467 options?: {
468 readonly stdin?: string;
469 readonly env?: NodeJS.ProcessEnv;
470 readonly allowNonZeroExit?: boolean;
471 readonly timeoutMs?: number;
472 readonly maxOutputBytes?: number;
473 readonly outputMode?: VcsProcess.VcsProcessInput["outputMode"];
474 readonly appendTruncationMarker?: boolean;
475 },
476) =>
477 process.run({
478 operation,
479 command: "git",
480 args: ["-C", cwd, ...args],
481 cwd,
482 spawnCwd: globalThis.process.cwd(),
483 ...(options?.stdin !== undefined ? { stdin: options.stdin } : {}),
484 ...(options?.env !== undefined ? { env: options.env } : {}),
485 ...(options?.allowNonZeroExit !== undefined
486 ? { allowNonZeroExit: options.allowNonZeroExit }
487 : {}),
488 ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
489 ...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
490 ...(options?.outputMode !== undefined ? { outputMode: options.outputMode } : {}),
491 ...(options?.appendTruncationMarker !== undefined
492 ? { appendTruncationMarker: options.appendTruncationMarker }
493 : {}),
494 });
495​
496export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* () {
497 const fileSystem = yield* FileSystem.FileSystem;
498 const path = yield* Path.Path;
499 const vcsProcess = yield* VcsProcess.VcsProcess;
500 const capabilities = {
501 kind: "git" as const,
502 supportsWorktrees: true,
503 supportsBookmarks: false,
504 supportsAtomicSnapshot: false,
505 supportsPushDefaultRemote: true,
506 ignoreClassifier: "native" as const,
507 };
508​
509 const isInsideWorkTree: VcsDriver.VcsDriver["Service"]["isInsideWorkTree"] = (cwd) =>
510 gitCommand(
511 vcsProcess,
512 "GitVcsDriver.isInsideWorkTree",
513 cwd,
514 ["rev-parse", "--is-inside-work-tree"],
515 {
516 allowNonZeroExit: true,
517 timeoutMs: 5_000,
518 maxOutputBytes: 4_096,
519 },
520 ).pipe(Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"));
521​
522 const execute: VcsDriver.VcsDriver["Service"]["execute"] = (input) =>
523 gitCommand(vcsProcess, input.operation, input.cwd, input.args, {
524 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
525 ...(input.env !== undefined ? { env: input.env } : {}),
526 ...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}),
527 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
528 ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
529 ...(input.outputMode !== undefined ? { outputMode: input.outputMode } : {}),
530 ...(input.appendTruncationMarker !== undefined
531 ? { appendTruncationMarker: input.appendTruncationMarker }
532 : {}),
533 });
534​
535 const detectRepository: VcsDriver.VcsDriver["Service"]["detectRepository"] = Effect.fn(
536 "detectRepository",
537 )(function* (cwd) {
538 if (!(yield* isInsideWorkTree(cwd))) {
539 return null;
540 }
541​
542 const root = yield* gitCommand(vcsProcess, "GitVcsDriver.detectRepository.root", cwd, [
543 "rev-parse",
544 "--show-toplevel",
545 ]);
546 const gitCommonDir = yield* gitCommand(
547 vcsProcess,
548 "GitVcsDriver.detectRepository.commonDir",
549 cwd,
550 ["rev-parse", "--git-common-dir"],
551 ).pipe(Effect.orElseSucceed(() => null));
552​
553 return {
554 kind: "git" as const,
555 rootPath: root.stdout.trim(),
556 metadataPath: gitCommonDir?.stdout.trim() || null,
557 freshness: yield* nowFreshness(),
558 };
559 });
560​
561 const listWorkspaceFiles: VcsDriver.VcsDriver["Service"]["listWorkspaceFiles"] = (cwd) =>
562 gitCommand(
563 vcsProcess,
564 "GitVcsDriver.listWorkspaceFiles",
565 cwd,
566 [
567 ...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
568 "ls-files",
569 "--cached",
570 "--others",
571 "--exclude-standard",
572 "-z",
573 ],
574 {
575 allowNonZeroExit: true,
576 timeoutMs: 20_000,
577 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
578 appendTruncationMarker: true,
579 },
580 ).pipe(
581 Effect.flatMap((result) =>
582 result.exitCode === 0
583 ? Effect.gen(function* () {
584 const freshness = yield* nowFreshness();
585 return {
586 paths: splitNullSeparatedGitStdoutPaths(result),
587 truncated: result.stdoutTruncated,
588 freshness,
589 };
590 })
591 : Effect.fail(
592 new VcsProcessExitError({
593 operation: "GitVcsDriver.listWorkspaceFiles",
594 command: "git ls-files",
595 cwd,
596 exitCode: result.exitCode,
597 detail: result.stderr.trim() || "git ls-files failed",
598 }),
599 ),
600 ),
601 );
602​
603 const listRemotes: VcsDriver.VcsDriver["Service"]["listRemotes"] = Effect.fn("listRemotes")(
604 function* (cwd) {
605 const result = yield* gitCommand(
606 vcsProcess,
607 "GitVcsDriver.listRemotes",
608 cwd,
609 ["remote", "-v"],
610 {
611 allowNonZeroExit: true,
612 timeoutMs: 5_000,
613 maxOutputBytes: 64 * 1024,
614 },
615 );
616​
617 if (result.exitCode !== 0) {
618 return yield* new VcsProcessExitError({
619 operation: "GitVcsDriver.listRemotes",
620 command: "git remote -v",
621 cwd,
622 exitCode: result.exitCode,
623 detail: result.stderr.trim() || "git remote -v failed",
624 });
625 }
626​
627 const parsed = parseGitRemoteVerboseOutput(result.stdout);
628 const remotes = Array.from(parsed.entries()).flatMap(([name, remote]) => {
629 if (!remote.url) {
630 return [];
631 }
632 return [
633 {
634 name,
635 url: remote.url,
636 pushUrl: remote.pushUrl ? Option.some(remote.pushUrl) : Option.none(),
637 isPrimary: name === "origin",
638 },
639 ];
640 });
641​
642 return {
643 remotes,
644 freshness: yield* nowFreshness(),
645 };
646 },
647 );
648​
649 const filterIgnoredPaths: VcsDriver.VcsDriver["Service"]["filterIgnoredPaths"] = Effect.fn(
650 "filterIgnoredPaths",
651 )(function* (cwd, relativePaths) {
652 if (relativePaths.length === 0) {
653 return relativePaths;
654 }
655​
656 const ignoredPaths = new Set<string>();
657 const chunks = chunkPathsForGitCheckIgnore(relativePaths);
658​
659 for (const chunk of chunks) {
660 const result = yield* gitCommand(
661 vcsProcess,
662 "GitVcsDriver.filterIgnoredPaths",
663 cwd,
664 [...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
665 {
666 stdin: `${chunk.join("\0")}\0`,
667 allowNonZeroExit: true,
668 timeoutMs: 20_000,
669 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
670 appendTruncationMarker: true,
671 },
672 );
673​
674 if (result.exitCode !== 0 && result.exitCode !== 1) {
675 return yield* new VcsProcessExitError({
676 operation: "GitVcsDriver.filterIgnoredPaths",
677 command: "git check-ignore",
678 cwd,
679 exitCode: result.exitCode,
680 detail: result.stderr.trim() || "git check-ignore failed",
681 });
682 }
683​
684 for (const ignoredPath of splitNullSeparatedGitStdoutPaths(result)) {
685 ignoredPaths.add(ignoredPath);
686 }
687 }
688​
689 if (ignoredPaths.size === 0) {
690 return relativePaths;
691 }
692​
693 return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
694 });
695​
696 const initRepository: VcsDriver.VcsDriver["Service"]["initRepository"] = (input) =>
697 gitCommand(vcsProcess, "GitVcsDriver.initRepository", input.cwd, ["init"], {
698 timeoutMs: 10_000,
699 maxOutputBytes: 64 * 1024,
700 }).pipe(Effect.asVoid);
701​
702 const resolveHeadCommit = (cwd: string) =>
703 execute({
704 operation: "GitVcsDriver.checkpoints.resolveHeadCommit",
705 cwd,
706 args: ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
707 allowNonZeroExit: true,
708 }).pipe(
709 Effect.map((result) => {
710 if (result.exitCode !== 0) {
711 return null;
712 }
713 const commit = result.stdout.trim();
714 return commit.length > 0 ? commit : null;
715 }),
716 );
717​
718 const hasHeadCommit = (cwd: string) =>
719 execute({
720 operation: "GitVcsDriver.checkpoints.hasHeadCommit",
721 cwd,
722 args: ["rev-parse", "--verify", "HEAD"],
723 allowNonZeroExit: true,
724 }).pipe(Effect.map((result) => result.exitCode === 0));
725​
726 const resolveCheckpointCommit = (cwd: string, checkpointRef: string) =>
727 execute({
728 operation: "GitVcsDriver.checkpoints.resolveCheckpointCommit",
729 cwd,
730 args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`],
731 allowNonZeroExit: true,
732 }).pipe(
733 Effect.map((result) => {
734 if (result.exitCode !== 0) {
735 return null;
736 }
737 const commit = result.stdout.trim();
738 return commit.length > 0 ? commit : null;
739 }),
740 );
741​
742 const resolveGitCommonDir = (cwd: string) =>
743 Effect.gen(function* () {
744 const result = yield* execute({
745 operation: "GitVcsDriver.checkpoints.resolveGitCommonDir",
746 cwd,
747 args: ["rev-parse", "--git-common-dir"],
748 });
749 const gitCommonDir = result.stdout.trim();
750 return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
751 });
752​
753 const checkpoints: VcsDriver.VcsCheckpointOps = {
754 captureCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureCheckpoint")(function* (input) {
755 const operation = "GitVcsDriver.checkpoints.captureCheckpoint";
756 const indexConfig = [
757 "-c",
758 "core.fsmonitor=false",
759 "-c",
760 "sparse.expectFilesOutsideOfPatterns=false",
761 ];
762 const gitCommonDir = yield* resolveGitCommonDir(input.cwd);
763 const tempIndexPath = path.join(
764 gitCommonDir,
765 `t3-checkpoint-index-${NodeCrypto.randomUUID()}`,
766 );
767 const commitEnv: NodeJS.ProcessEnv = {
768 ...process.env,
769 GIT_INDEX_FILE: tempIndexPath,
770 GIT_AUTHOR_NAME: "T3 Code",
771 GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com",
772 GIT_COMMITTER_NAME: "T3 Code",
773 GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com",
774 };
775​
776 const cleanupTempIndex = fileSystem
777 .remove(tempIndexPath, { force: true })
778 .pipe(Effect.ignore);
779​
780 yield* Effect.gen(function* () {
781 const headExists = yield* hasHeadCommit(input.cwd);
782 const sparseConfig = yield* execute({
783 operation,
784 cwd: input.cwd,
785 args: ["config", "--bool", "core.sparseCheckout"],
786 allowNonZeroExit: true,
787 });
788 let sparseCheckout = sparseConfig.stdout.trim() === "true";
789 if (sparseCheckout) {
790 const help = yield* execute({
791 operation,
792 cwd: input.cwd,
793 args: ["add", "-h"],
794 allowNonZeroExit: true,
795 });
796 sparseCheckout = /--(?:\[no-\])?sparse\b/.test(`${help.stdout}${help.stderr}`);
797 }
798 if (headExists) {
799 const reusedIndex = yield* Effect.gen(function* () {
800 const indexPath = yield* execute({
801 operation,
802 cwd: input.cwd,
803 args: ["rev-parse", "--path-format=absolute", "--git-path", "index"],
804 });
805 const { mtime } = yield* fileSystem.stat(indexPath.stdout.trim());
806 if (Option.isNone(mtime)) return false;
807 // Stay below the source timestamp even if Date rounded up, preserving Git's racy check.
808 const indexTime = Math.floor((mtime.value.getTime() - 1) / 1000);
809 if (indexTime <= 0) return false;
810 yield* fileSystem.copyFile(indexPath.stdout.trim(), tempIndexPath);
811 // Retain stat data only where the copied index already matches HEAD.
812 yield* execute({
813 operation,
814 cwd: input.cwd,
815 args: [...indexConfig, "read-tree", "--reset", "HEAD"],
816 env: commitEnv,
817 });
818 // read-tree can rewrite the index, so restore its racy timestamp afterward.
819 yield* fileSystem.utimes(tempIndexPath, indexTime, indexTime);
820 let specialFlags = false;
821 let recordStart = true;
822 let skipped = false;
823 let skippedRecord: number[] = [];
824 const skippedPaths: string[] = [];
825 yield* vcsProcess.run({
826 operation,
827 command: "git",
828 cwd: input.cwd,
829 args: [...indexConfig, "ls-files", "--full-name", "--sparse", "-v", "-z"],
830 env: commitEnv,
831 maxOutputBytes: 4_096,
832 outputMode: "truncate",
833 // Inspect every tag; retain only skipped file paths for checking sparse rules.
834 onStdoutChunk: (chunk) => {
835 for (const byte of chunk) {
836 if (recordStart) skipped = byte === 83;
837 if (skipped && sparseCheckout) {
838 if (byte !== 0) skippedRecord.push(byte);
839 else {
840 if (skippedRecord.at(-1) !== 47) {
841 const name = Buffer.from(skippedRecord).subarray(2);
842 if (!NodeBuffer.isUtf8(name)) specialFlags = true;
843 else skippedPaths.push(name.toString("utf8"));
844 }
845 skippedRecord = [];
846 }
847 }
848 if (
849 recordStart &&
850 ((byte >= 97 && byte <= 122) || (!sparseCheckout && byte === 83))
851 ) {
852 specialFlags = true;
853 }
854 recordStart = byte === 0;
855 }
856 },
857 });
858 if (skippedPaths.length > 0 && !specialFlags) {
859 const selected = yield* execute({
860 operation,
861 cwd: input.cwd,
862 args: [...indexConfig, "sparse-checkout", "check-rules", "-z"],
863 stdin: skippedPaths.join("\0") + "\0",
864 env: commitEnv,
865 maxOutputBytes: 1,
866 outputMode: "truncate",
867 });
868 // Any selected skipped file has a manual flag, not a sparse exclusion.
869 specialFlags = selected.stdout.length > 0 || selected.stdoutTruncated;
870 }
871 // Sparse Git clears skip-worktree for present files. Manual flags still need a reset.
872 return !specialFlags;
873 }).pipe(Effect.orElseSucceed(() => false));
874 if (!reusedIndex) {
875 if (sparseCheckout) {
876 const cone = yield* execute({
877 operation,
878 cwd: input.cwd,
879 args: ["config", "--bool", "core.sparseCheckoutCone"],
880 allowNonZeroExit: true,
881 });
882 // Rebuilding a non-cone index loses exclusions; do not publish false deletions.
883 if (cone.stdout.trim() !== "true") {
884 return yield* new VcsProcessExitError({
885 operation,
886 command: "git read-tree",
887 cwd: input.cwd,
888 exitCode: 1,
889 detail: "Cannot rebuild a checkpoint index for non-cone sparse checkout.",
890 });
891 }
892 }
893 yield* cleanupTempIndex;
894 yield* execute({
895 operation,
896 cwd: input.cwd,
897 // A fresh sparse index represents excluded directories without marking them deleted.
898 args: sparseCheckout
899 ? [...indexConfig, "-c", "index.sparse=true", "read-tree", "--reset", "HEAD"]
900 : ["read-tree", "HEAD"],
901 env: commitEnv,
902 });
903 }
904 }
905​
906 yield* execute({
907 operation,
908 cwd: input.cwd,
909 // Preserve absent skipped entries, but capture present nonignored files outside the cone.
910 args: [...indexConfig, "add", ...(sparseCheckout ? ["--sparse"] : []), "-A", "--", "."],
911 env: commitEnv,
912 });
913​
914 const writeTreeResult = yield* execute({
915 operation,
916 cwd: input.cwd,
917 args: [...indexConfig, "write-tree"],
918 env: commitEnv,
919 });
920 const treeOid = writeTreeResult.stdout.trim();
921 if (treeOid.length === 0) {
922 return yield* new VcsProcessExitError({
923 operation,
924 command: "git write-tree",
925 cwd: input.cwd,
926 exitCode: 0,
927 detail: "git write-tree returned an empty tree oid.",
928 });
929 }
930​
931 const message = `t3 checkpoint ref=${input.checkpointRef}`;
932 const commitTreeResult = yield* execute({
933 operation,
934 cwd: input.cwd,
935 args: ["commit-tree", treeOid, "-m", message],
936 env: commitEnv,
937 });
938 const commitOid = commitTreeResult.stdout.trim();
939 if (commitOid.length === 0) {
940 return yield* new VcsProcessExitError({
941 operation,
942 command: "git commit-tree",
943 cwd: input.cwd,
944 exitCode: 0,
945 detail: "git commit-tree returned an empty commit oid.",
946 });
947 }
948​
949 yield* execute({
950 operation,
951 cwd: input.cwd,
952 args: ["update-ref", input.checkpointRef, commitOid],
953 });
954 }).pipe(Effect.ensuring(cleanupTempIndex));
955 }),
956​
957 hasCheckpointRef: (input) =>
958 resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
959 Effect.map((commit) => commit !== null),
960 ),
961​
962 restoreCheckpoint: Effect.fn("GitVcsDriver.checkpoints.restoreCheckpoint")(function* (input) {
963 const operation = "GitVcsDriver.checkpoints.restoreCheckpoint";
964​
965 let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
966​
967 if (!commitOid && input.fallbackToHead === true) {
968 commitOid = yield* resolveHeadCommit(input.cwd);
969 }
970​
971 if (!commitOid) {
972 return false;
973 }
974​
975 const tracked = yield* execute({
976 operation,
977 cwd: input.cwd,
978 args: ["ls-files", "--cached", `--with-tree=${commitOid}`, "-z", "--", "."],
979 });
980 // An empty index and checkpoint have nothing for git restore's pathspec to match.
981 if (tracked.stdout.length > 0) {
982 yield* execute({
983 operation,
984 cwd: input.cwd,
985 args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
986 });
987 }
988 // Restoring away the last tracked file can remove a nested workspace directory.
989 yield* fileSystem.makeDirectory(input.cwd, { recursive: true }).pipe(
990 Effect.mapError(
991 (cause) =>
992 new VcsProcessExitError({
993 operation,
994 command: "git restore",
995 cwd: input.cwd,
996 exitCode: 0,
997 detail: `Could not recreate the checkpoint workspace: ${cause.message}`,
998 }),
999 ),
1000 );
1001 const cleaned = yield* execute({
1002 operation,
1003 cwd: input.cwd,
1004 args: ["clean", "-fd", "--", "."],
1005 allowNonZeroExit: true,
1006 });
1007 if (cleaned.exitCode !== 0) {
1008 // Git can remove every child, then fail trying to remove './' itself.
1009 const emptiedWorkspace =
1010 cleaned.exitCode === 1 &&
1011 /^warning: failed to remove \.\/: [^\n]+$/.test(cleaned.stderr.trim()) &&
1012 (yield* fileSystem.readDirectory(input.cwd).pipe(
1013 Effect.map((entries) => entries.length === 0),
1014 Effect.catch(() => Effect.succeed(false)),
1015 ));
1016 if (!emptiedWorkspace)
1017 return yield* new VcsProcessExitError({
1018 operation,
1019 command: "git clean",
1020 cwd: input.cwd,
1021 exitCode: cleaned.exitCode,
1022 detail: cleaned.stderr.trim() || "Could not clean the checkpoint workspace.",
1023 });
1025​
1026 const headExists = yield* hasHeadCommit(input.cwd);
1027 if (headExists) {
1028 yield* execute({
1029 operation,
1030 cwd: input.cwd,
1031 args: ["reset", "--quiet", "--", "."],
1032 });
1034​
1035 return true;
1036 }),
1037​
1038 diffCheckpoints: Effect.fn("GitVcsDriver.checkpoints.diffCheckpoints")(function* (input) {
1039 const operation = "GitVcsDriver.checkpoints.diffCheckpoints";
1040 yield* Effect.annotateCurrentSpan({
1041 "checkpoint.cwd": input.cwd,
1042 "checkpoint.from_ref": input.fromCheckpointRef,
1043 "checkpoint.to_ref": input.toCheckpointRef,
1044 "checkpoint.ignore_whitespace": input.ignoreWhitespace,
1045 "checkpoint.format": input.format ?? "patch",
1046 "checkpoint.fallback_from_to_head": input.fallbackFromToHead,
1047 });
1048​
1049 let fromRevision: string = input.fromCheckpointRef;
1050 if (input.fallbackFromToHead === true) {
1051 const resolvedFromCommit = yield* resolveCheckpointCommit(
1052 input.cwd,
1053 input.fromCheckpointRef,
1054 );
1055 if (resolvedFromCommit) {
1056 fromRevision = resolvedFromCommit;
1057 } else {
1058 const headCommit = yield* resolveHeadCommit(input.cwd);
1059 if (!headCommit) {
1060 return yield* new VcsProcessExitError({
1061 operation,
1062 command: "git diff",
1063 cwd: input.cwd,
1064 exitCode: 1,
1065 detail: "Checkpoint ref is unavailable for diff operation.",
1066 });
1068 fromRevision = headCommit;
1071​
1072 const result = yield* execute({
1073 operation,
1074 cwd: input.cwd,
1075 args: [
1076 "diff",
1077 ...(input.format === "numstat" ? ["--numstat", "-z"] : ["--patch"]),
1078 "--no-color",
1079 "--no-ext-diff",
1080 "--no-textconv",
1081 ...PATCH_RENDER_PREFIX_ARGS,
1082 ...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
1083 `${fromRevision}^{commit}`,
1084 `${input.toCheckpointRef}^{commit}`,
1085 ],
1086 allowNonZeroExit: true,
1087 maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
1088 outputMode: input.format === "numstat" ? "error" : "truncate",
1089 });
1090​
1091 if (result.exitCode !== 0) {
1092 return yield* new VcsProcessExitError({
1093 operation,
1094 command: "git diff",
1095 cwd: input.cwd,
1096 exitCode: result.exitCode,
1097 detail: result.stderr.trim() || "Checkpoint ref is unavailable for diff operation.",
1098 });
1100​
1101 return result.stdout;
1102 }),
1103​
1104 deleteCheckpointRefs: Effect.fn("GitVcsDriver.checkpoints.deleteCheckpointRefs")(
1105 function* (input) {
1106 yield* Effect.forEach(
1107 input.checkpointRefs,
1108 (checkpointRef) =>
1109 execute({
1110 operation: "GitVcsDriver.checkpoints.deleteCheckpointRefs",
1111 cwd: input.cwd,
1112 args: ["update-ref", "-d", checkpointRef],
1113 allowNonZeroExit: true,
1114 }),
1115 { discard: true },
1116 );
1117 },
1118 ),
1119 };
1120​
1121 return {
1122 capabilities,
1123 execute,
1124 checkpoints,
1125 detectRepository,
1126 isInsideWorkTree,
1127 listWorkspaceFiles,
1128 listRemotes,
1129 filterIgnoredPaths,
1130 initRepository,
1131 };
1132});
1133​
1134export const makeVcsDriver = Effect.gen(function* () {
1135 const driver = yield* makeVcsDriverShape();
1136 return VcsDriver.VcsDriver.of(driver);
1137});
1138​
1139export const make = Effect.gen(function* () {
1140 const git = yield* makeGitVcsDriverCore();
1141 return GitVcsDriver.of(git);
1142});
1143​
1144export const vcsLayer = Layer.effect(VcsDriver.VcsDriver, makeVcsDriver);
1145export const layer = Layer.effect(GitVcsDriver, make);