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

GitVcsDriver.ts

1,164 lines37.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 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 // Git renames loose objects and refs into place without fsync by default, so
754 // an unclean restart can leave 0-byte files under refs/t3/** that break every
755 // later fetch and push. Checkpoint writes flush before they are published;
756 // macOS defaults to writeout-only, which does not reach the disk either.
757 const durableWrite = [
758 "-c",
759 "core.fsync=objects,reference",
760 "-c",
761 "core.fsyncMethod=fsync",
762 ] as const;
763​
764 const checkpoints: VcsDriver.VcsCheckpointOps = {
765 captureCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureCheckpoint")(function* (input) {
766 const operation = "GitVcsDriver.checkpoints.captureCheckpoint";
767 const indexConfig = [
768 "-c",
769 "core.fsmonitor=false",
770 "-c",
771 "sparse.expectFilesOutsideOfPatterns=false",
772 ];
773 const gitCommonDir = yield* resolveGitCommonDir(input.cwd);
774 const tempIndexPath = path.join(
775 gitCommonDir,
776 `t3-checkpoint-index-${NodeCrypto.randomUUID()}`,
777 );
778 const commitEnv: NodeJS.ProcessEnv = {
779 ...process.env,
780 GIT_INDEX_FILE: tempIndexPath,
781 GIT_AUTHOR_NAME: "T3 Code",
782 GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com",
783 GIT_COMMITTER_NAME: "T3 Code",
784 GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com",
785 };
786​
787 const cleanupTempIndex = fileSystem
788 .remove(tempIndexPath, { force: true })
789 .pipe(Effect.ignore);
790​
791 yield* Effect.gen(function* () {
792 const headExists = yield* hasHeadCommit(input.cwd);
793 const sparseConfig = yield* execute({
794 operation,
795 cwd: input.cwd,
796 args: ["config", "--bool", "core.sparseCheckout"],
797 allowNonZeroExit: true,
798 });
799 let sparseCheckout = sparseConfig.stdout.trim() === "true";
800 if (sparseCheckout) {
801 const help = yield* execute({
802 operation,
803 cwd: input.cwd,
804 args: ["add", "-h"],
805 allowNonZeroExit: true,
806 });
807 sparseCheckout = /--(?:\[no-\])?sparse\b/.test(`${help.stdout}${help.stderr}`);
808 }
809 if (headExists) {
810 const reusedIndex = yield* Effect.gen(function* () {
811 const indexPath = yield* execute({
812 operation,
813 cwd: input.cwd,
814 args: ["rev-parse", "--path-format=absolute", "--git-path", "index"],
815 });
816 const { mtime } = yield* fileSystem.stat(indexPath.stdout.trim());
817 if (Option.isNone(mtime)) return false;
818 // Stay below the source timestamp even if Date rounded up, preserving Git's racy check.
819 const indexTime = Math.floor((mtime.value.getTime() - 1) / 1000);
820 if (indexTime <= 0) return false;
821 yield* fileSystem.copyFile(indexPath.stdout.trim(), tempIndexPath);
822 // Retain stat data only where the copied index already matches HEAD.
823 yield* execute({
824 operation,
825 cwd: input.cwd,
826 args: [...indexConfig, "read-tree", "--reset", "HEAD"],
827 env: commitEnv,
828 });
829 // read-tree can rewrite the index, so restore its racy timestamp afterward.
830 yield* fileSystem.utimes(tempIndexPath, indexTime, indexTime);
831 let specialFlags = false;
832 let recordStart = true;
833 let skipped = false;
834 let skippedRecord: number[] = [];
835 const skippedPaths: string[] = [];
836 yield* vcsProcess.run({
837 operation,
838 command: "git",
839 cwd: input.cwd,
840 args: [...indexConfig, "ls-files", "--full-name", "--sparse", "-v", "-z"],
841 env: commitEnv,
842 maxOutputBytes: 4_096,
843 outputMode: "truncate",
844 // Inspect every tag; retain only skipped file paths for checking sparse rules.
845 onStdoutChunk: (chunk) => {
846 for (const byte of chunk) {
847 if (recordStart) skipped = byte === 83;
848 if (skipped && sparseCheckout) {
849 if (byte !== 0) skippedRecord.push(byte);
850 else {
851 if (skippedRecord.at(-1) !== 47) {
852 const name = Buffer.from(skippedRecord).subarray(2);
853 if (!NodeBuffer.isUtf8(name)) specialFlags = true;
854 else skippedPaths.push(name.toString("utf8"));
855 }
856 skippedRecord = [];
857 }
858 }
859 if (
860 recordStart &&
861 ((byte >= 97 && byte <= 122) || (!sparseCheckout && byte === 83))
862 ) {
863 specialFlags = true;
864 }
865 recordStart = byte === 0;
866 }
867 },
868 });
869 if (skippedPaths.length > 0 && !specialFlags) {
870 const selected = yield* execute({
871 operation,
872 cwd: input.cwd,
873 args: [...indexConfig, "sparse-checkout", "check-rules", "-z"],
874 stdin: skippedPaths.join("\0") + "\0",
875 env: commitEnv,
876 maxOutputBytes: 1,
877 outputMode: "truncate",
878 });
879 // Any selected skipped file has a manual flag, not a sparse exclusion.
880 specialFlags = selected.stdout.length > 0 || selected.stdoutTruncated;
881 }
882 // Sparse Git clears skip-worktree for present files. Manual flags still need a reset.
883 return !specialFlags;
884 }).pipe(Effect.orElseSucceed(() => false));
885 if (!reusedIndex) {
886 if (sparseCheckout) {
887 const cone = yield* execute({
888 operation,
889 cwd: input.cwd,
890 args: ["config", "--bool", "core.sparseCheckoutCone"],
891 allowNonZeroExit: true,
892 });
893 // Rebuilding a non-cone index loses exclusions; do not publish false deletions.
894 if (cone.stdout.trim() !== "true") {
895 return yield* new VcsProcessExitError({
896 operation,
897 command: "git read-tree",
898 cwd: input.cwd,
899 exitCode: 1,
900 detail: "Cannot rebuild a checkpoint index for non-cone sparse checkout.",
901 });
902 }
903 }
904 yield* cleanupTempIndex;
905 yield* execute({
906 operation,
907 cwd: input.cwd,
908 // A fresh sparse index represents excluded directories without marking them deleted.
909 args: sparseCheckout
910 ? [...indexConfig, "-c", "index.sparse=true", "read-tree", "--reset", "HEAD"]
911 : ["read-tree", "HEAD"],
912 env: commitEnv,
913 });
914 }
915 }
916​
917 yield* execute({
918 operation,
919 cwd: input.cwd,
920 // Preserve absent skipped entries, but capture present nonignored files outside the cone.
921 args: [
922 ...indexConfig,
923 ...durableWrite,
924 "add",
925 ...(sparseCheckout ? ["--sparse"] : []),
926 "-A",
927 "--",
928 ".",
929 ],
930 env: commitEnv,
931 });
932​
933 const writeTreeResult = yield* execute({
934 operation,
935 cwd: input.cwd,
936 args: [...indexConfig, ...durableWrite, "write-tree"],
937 env: commitEnv,
938 });
939 const treeOid = writeTreeResult.stdout.trim();
940 if (treeOid.length === 0) {
941 return yield* new VcsProcessExitError({
942 operation,
943 command: "git write-tree",
944 cwd: input.cwd,
945 exitCode: 0,
946 detail: "git write-tree returned an empty tree oid.",
947 });
948 }
949​
950 const message = `t3 checkpoint ref=${input.checkpointRef}`;
951 const commitTreeResult = yield* execute({
952 operation,
953 cwd: input.cwd,
954 args: [...durableWrite, "commit-tree", treeOid, "-m", message],
955 env: commitEnv,
956 });
957 const commitOid = commitTreeResult.stdout.trim();
958 if (commitOid.length === 0) {
959 return yield* new VcsProcessExitError({
960 operation,
961 command: "git commit-tree",
962 cwd: input.cwd,
963 exitCode: 0,
964 detail: "git commit-tree returned an empty commit oid.",
965 });
966 }
967​
968 yield* execute({
969 operation,
970 cwd: input.cwd,
971 args: [...durableWrite, "update-ref", input.checkpointRef, commitOid],
972 });
973 }).pipe(Effect.ensuring(cleanupTempIndex));
974 }),
975​
976 hasCheckpointRef: (input) =>
977 resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
978 Effect.map((commit) => commit !== null),
979 ),
980​
981 restoreCheckpoint: Effect.fn("GitVcsDriver.checkpoints.restoreCheckpoint")(function* (input) {
982 const operation = "GitVcsDriver.checkpoints.restoreCheckpoint";
983​
984 let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
985​
986 if (!commitOid && input.fallbackToHead === true) {
987 commitOid = yield* resolveHeadCommit(input.cwd);
988 }
989​
990 if (!commitOid) {
991 return false;
992 }
993​
994 const tracked = yield* execute({
995 operation,
996 cwd: input.cwd,
997 args: ["ls-files", "--cached", `--with-tree=${commitOid}`, "-z", "--", "."],
998 });
999 // An empty index and checkpoint have nothing for git restore's pathspec to match.
1000 if (tracked.stdout.length > 0) {
1001 yield* execute({
1002 operation,
1003 cwd: input.cwd,
1004 args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
1005 });
1007 // Restoring away the last tracked file can remove a nested workspace directory.
1008 yield* fileSystem.makeDirectory(input.cwd, { recursive: true }).pipe(
1009 Effect.mapError(
1010 (cause) =>
1011 new VcsProcessExitError({
1012 operation,
1013 command: "git restore",
1014 cwd: input.cwd,
1015 exitCode: 0,
1016 detail: `Could not recreate the checkpoint workspace: ${cause.message}`,
1017 }),
1018 ),
1019 );
1020 const cleaned = yield* execute({
1021 operation,
1022 cwd: input.cwd,
1023 args: ["clean", "-fd", "--", "."],
1024 allowNonZeroExit: true,
1025 });
1026 if (cleaned.exitCode !== 0) {
1027 // Git can remove every child, then fail trying to remove './' itself.
1028 const emptiedWorkspace =
1029 cleaned.exitCode === 1 &&
1030 /^warning: failed to remove \.\/: [^\n]+$/.test(cleaned.stderr.trim()) &&
1031 (yield* fileSystem.readDirectory(input.cwd).pipe(
1032 Effect.map((entries) => entries.length === 0),
1033 Effect.catch(() => Effect.succeed(false)),
1034 ));
1035 if (!emptiedWorkspace)
1036 return yield* new VcsProcessExitError({
1037 operation,
1038 command: "git clean",
1039 cwd: input.cwd,
1040 exitCode: cleaned.exitCode,
1041 detail: cleaned.stderr.trim() || "Could not clean the checkpoint workspace.",
1042 });
1044​
1045 const headExists = yield* hasHeadCommit(input.cwd);
1046 if (headExists) {
1047 yield* execute({
1048 operation,
1049 cwd: input.cwd,
1050 args: ["reset", "--quiet", "--", "."],
1051 });
1053​
1054 return true;
1055 }),
1056​
1057 diffCheckpoints: Effect.fn("GitVcsDriver.checkpoints.diffCheckpoints")(function* (input) {
1058 const operation = "GitVcsDriver.checkpoints.diffCheckpoints";
1059 yield* Effect.annotateCurrentSpan({
1060 "checkpoint.cwd": input.cwd,
1061 "checkpoint.from_ref": input.fromCheckpointRef,
1062 "checkpoint.to_ref": input.toCheckpointRef,
1063 "checkpoint.ignore_whitespace": input.ignoreWhitespace,
1064 "checkpoint.format": input.format ?? "patch",
1065 "checkpoint.fallback_from_to_head": input.fallbackFromToHead,
1066 });
1067​
1068 let fromRevision: string = input.fromCheckpointRef;
1069 if (input.fallbackFromToHead === true) {
1070 const resolvedFromCommit = yield* resolveCheckpointCommit(
1071 input.cwd,
1072 input.fromCheckpointRef,
1073 );
1074 if (resolvedFromCommit) {
1075 fromRevision = resolvedFromCommit;
1076 } else {
1077 const headCommit = yield* resolveHeadCommit(input.cwd);
1078 if (!headCommit) {
1079 return yield* new VcsProcessExitError({
1080 operation,
1081 command: "git diff",
1082 cwd: input.cwd,
1083 exitCode: 1,
1084 detail: "Checkpoint ref is unavailable for diff operation.",
1085 });
1087 fromRevision = headCommit;
1090​
1091 const result = yield* execute({
1092 operation,
1093 cwd: input.cwd,
1094 args: [
1095 "diff",
1096 ...(input.format === "numstat" ? ["--numstat", "-z"] : ["--patch"]),
1097 "--no-color",
1098 "--no-ext-diff",
1099 "--no-textconv",
1100 ...PATCH_RENDER_PREFIX_ARGS,
1101 ...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
1102 `${fromRevision}^{commit}`,
1103 `${input.toCheckpointRef}^{commit}`,
1104 ],
1105 allowNonZeroExit: true,
1106 maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
1107 outputMode: input.format === "numstat" ? "error" : "truncate",
1108 });
1109​
1110 if (result.exitCode !== 0) {
1111 return yield* new VcsProcessExitError({
1112 operation,
1113 command: "git diff",
1114 cwd: input.cwd,
1115 exitCode: result.exitCode,
1116 detail: result.stderr.trim() || "Checkpoint ref is unavailable for diff operation.",
1117 });
1119​
1120 return result.stdout;
1121 }),
1122​
1123 deleteCheckpointRefs: Effect.fn("GitVcsDriver.checkpoints.deleteCheckpointRefs")(
1124 function* (input) {
1125 yield* Effect.forEach(
1126 input.checkpointRefs,
1127 (checkpointRef) =>
1128 execute({
1129 operation: "GitVcsDriver.checkpoints.deleteCheckpointRefs",
1130 cwd: input.cwd,
1131 args: ["update-ref", "-d", checkpointRef],
1132 allowNonZeroExit: true,
1133 }),
1134 { discard: true },
1135 );
1136 },
1137 ),
1138 };
1139​
1140 return {
1141 capabilities,
1142 execute,
1143 checkpoints,
1144 detectRepository,
1145 isInsideWorkTree,
1146 listWorkspaceFiles,
1147 listRemotes,
1148 filterIgnoredPaths,
1149 initRepository,
1150 };
1151});
1152​
1153export const makeVcsDriver = Effect.gen(function* () {
1154 const driver = yield* makeVcsDriverShape();
1155 return VcsDriver.VcsDriver.of(driver);
1156});
1157​
1158export const make = Effect.gen(function* () {
1159 const git = yield* makeGitVcsDriverCore();
1160 return GitVcsDriver.of(git);
1161});
1162​
1163export const vcsLayer = Layer.effect(VcsDriver.VcsDriver, makeVcsDriver);
1164export const layer = Layer.effect(GitVcsDriver, make);