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

GitVcsDriver.ts

1,055 lines33.3 KB

1import * as NodeCrypto from "node:crypto";
2​
3import * as Context from "effect/Context";
4import * as DateTime from "effect/DateTime";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as Path from "effect/Path";
10import { ChildProcessSpawner } from "effect/unstable/process";
11​
12import {
13 GitCommandError,
14 VcsProcessExitError,
15 type VcsSwitchRefInput,
16 type VcsSwitchRefResult,
17 type VcsCreateRefInput,
18 type VcsCreateRefResult,
19 type VcsCreateWorktreeInput,
20 type VcsCreateWorktreeResult,
21 type ReviewDiffPreviewInput,
22 type ReviewDiffPreviewResult,
23 type ReviewDiffFileContentsInput,
24 type ReviewDiffFileContentsResult,
25 type VcsInitInput,
26 type VcsListRefsInput,
27 type VcsListRefsResult,
28 type VcsPullResult,
29 type VcsRemoveWorktreeInput,
30 type VcsStatusInput,
31 type VcsStatusResult,
32} from "@t3tools/contracts";
33import {
34 makeGitVcsDriverCore,
35 PATCH_RENDER_PREFIX_ARGS,
36 splitNullSeparatedGitStdoutPaths,
37} from "./GitVcsDriverCore.ts";
38import * as VcsDriver from "./VcsDriver.ts";
39import * as VcsProcess from "./VcsProcess.ts";
40​
41export interface ExecuteGitInput {
42 readonly operation: string;
43 readonly cwd: string;
44 readonly args: ReadonlyArray<string>;
45 readonly stdin?: string;
46 readonly env?: NodeJS.ProcessEnv;
47 readonly allowNonZeroExit?: boolean;
48 readonly timeoutMs?: number | null;
49 readonly maxOutputBytes?: number;
50 readonly appendTruncationMarker?: boolean;
51 /**
52 * With `appendTruncationMarker`, keep invoking the line callbacks after the
53 * buffered copy is full. For long-running commands whose output is only
54 * consumed through `progress`.
55 */
56 readonly keepLineCallbacksAfterTruncation?: boolean;
57 readonly progress?: ExecuteGitProgress;
59​
60export interface ExecuteGitResult {
61 readonly exitCode: ChildProcessSpawner.ExitCode;
62 readonly stdout: string;
63 readonly stderr: string;
64 readonly stdoutTruncated: boolean;
65 readonly stderrTruncated: boolean;
67​
68export interface GitStatusDetails {
69 isRepo: boolean;
70 sourceControlProvider?: VcsStatusResult["sourceControlProvider"];
71 hasOriginRemote: boolean;
72 isDefaultBranch: boolean;
73 branch: string | null;
74 upstreamRef: string | null;
75 hasWorkingTreeChanges: boolean;
76 workingTree: VcsStatusResult["workingTree"];
77 hasUpstream: boolean;
78 aheadCount: number;
79 behindCount: number;
80 aheadOfDefaultCount: number;
82​
83export interface GitRemoteStatusDetails {
84 isRepo: boolean;
85 defaultBranch: string | null;
86 isDefaultBranch: boolean;
87 branch: string | null;
88 upstreamRef: string | null;
89 hasUpstream: boolean;
90 aheadCount: number;
91 behindCount: number;
92 aheadOfDefaultCount: number;
94​
95export interface GitPreparedCommitContext {
96 stagedSummary: string;
97 stagedPatch: string;
99​
100export interface ExecuteGitProgress {
101 readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;
102 readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;
103 readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
104 readonly onHookFinished?: (input: {
105 hookName: string;
106 exitCode: number | null;
107 durationMs: number | null;
108 }) => Effect.Effect<void, never>;
110​
111/**
112 * Progress callbacks for `createWorktree`. Git prints `Updating files: 78% (2104/2700)`
113 * to stderr during checkout, and `Submodule path 'x': checked out` during
114 * submodule init. The tracker uses these to drive the worktree setup card.
115 */
116export interface CreateWorktreeProgress {
117 /**
118 * Fires once `git worktree add` has created and registered the directory,
119 * before the (possibly long) submodule step. Git refuses an existing path,
120 * so a path reported here belongs to this call and is safe to remove on
121 * cancel.
122 */
123 readonly onWorktreeClaimed?: (path: string) => Effect.Effect<void, never>;
124 readonly onCheckoutProgress?: (input: {
125 percent: number;
126 completed: number;
127 total: number;
128 }) => Effect.Effect<void, never>;
129 readonly onSubmodulesStarted?: () => Effect.Effect<void, never>;
130 readonly onSubmoduleLine?: (line: string) => Effect.Effect<void, never>;
131 readonly onSubmodulesFinished?: (input: {
132 ok: boolean;
133 detail: string | null;
134 }) => Effect.Effect<void, never>;
136​
137export interface CreateWorktreeOptions {
138 readonly progress?: CreateWorktreeProgress;
140​
141export interface GitCommitProgress {
142 readonly onOutputLine?: (input: {
143 stream: "stdout" | "stderr";
144 text: string;
145 }) => Effect.Effect<void, never>;
146 readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
147 readonly onHookFinished?: (input: {
148 hookName: string;
149 exitCode: number | null;
150 durationMs: number | null;
151 }) => Effect.Effect<void, never>;
153​
154export interface GitCommitOptions {
155 readonly timeoutMs?: number;
156 readonly progress?: GitCommitProgress;
158​
159export interface GitPushResult {
160 status: "pushed" | "skipped_up_to_date";
161 branch: string;
162 upstreamBranch?: string | undefined;
163 setUpstream?: boolean | undefined;
165​
166export interface GitRangeContext {
167 commitSummary: string;
168 diffSummary: string;
169 diffPatch: string;
171​
172export interface GitRenameBranchInput {
173 cwd: string;
174 oldBranch: string;
175 newBranch: string;
177​
178export interface GitRenameBranchResult {
179 branch: string;
181​
182export interface GitFetchPullRequestBranchInput {
183 cwd: string;
184 prNumber: number;
185 branch: string;
187​
188export interface GitFetchPullRequestHeadCommitInput {
189 cwd: string;
190 prNumber: number;
192​
193export interface GitResolveCommitInput {
194 cwd: string;
195 revision: string;
197​
198export interface GitResolveCommitResult {
199 commitSha: string;
201​
202export interface GitRefreshCheckedOutBranchInput {
203 cwd: string;
204 targetCommit: string;
205 /**
206 * Commit the checkout is allowed to be hard-reset away from: the upstream commit read before
207 * the fetch. HEAD sitting there means the checkout holds no work of its own.
208 */
209 resetWhenHeadCommit?: string | null | undefined;
211​
212export interface GitRefreshCheckedOutBranchResult {
213 headCommit: string;
214 moved: boolean;
215 onTarget: boolean;
217​
218export interface GitEnsureRemoteInput {
219 cwd: string;
220 preferredName: string;
221 url: string;
223​
224export interface GitFetchRemoteBranchInput {
225 cwd: string;
226 remoteName: string;
227 remoteBranch: string;
228 localBranch: string;
230​
231export interface GitFetchRemoteTrackingBranchInput {
232 cwd: string;
233 remoteName: string;
234 remoteBranch: string;
236​
237export interface GitFetchRemoteInput {
238 cwd: string;
239 remoteName: string;
240 refName?: string;
242​
243export interface GitRemoteExistsInput {
244 cwd: string;
245 remoteName: string;
247​
248export interface GitRemoteBranchExistsInput extends GitRemoteExistsInput {
249 refName: string;
251​
252export interface GitResolveRemoteTrackingCommitInput {
253 cwd: string;
254 refName: string;
255 fallbackRemoteName: string;
257​
258export interface GitResolveRemoteTrackingCommitResult {
259 commitSha: string;
260 remoteRefName: string;
262​
263export interface GitSetBranchUpstreamInput {
264 cwd: string;
265 branch: string;
266 remoteName: string;
267 remoteBranch: string;
269​
270export interface GitRemoteStatusOptions {
271 readonly refreshUpstream?: boolean;
273​
274export class GitVcsDriver extends Context.Service<
275 GitVcsDriver,
276 {
277 readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
278 readonly status: (input: VcsStatusInput) => Effect.Effect<VcsStatusResult, GitCommandError>;
279 readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
280 readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
281 readonly statusDetailsRemote: (
282 cwd: string,
283 options?: GitRemoteStatusOptions,
284 ) => Effect.Effect<GitRemoteStatusDetails, GitCommandError>;
285 readonly prepareCommitContext: (
286 cwd: string,
287 filePaths?: readonly string[],
288 ) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
289 readonly commit: (
290 cwd: string,
291 subject: string,
292 body: string,
293 options?: GitCommitOptions,
294 ) => Effect.Effect<{ commitSha: string }, GitCommandError>;
295 readonly pushCurrentBranch: (
296 cwd: string,
297 fallbackBranch: string | null,
298 options?: { readonly remoteName?: string | null },
299 ) => Effect.Effect<GitPushResult, GitCommandError>;
300 readonly readRangeContext: (
301 cwd: string,
302 baseRef: string,
303 ) => Effect.Effect<GitRangeContext, GitCommandError>;
304 readonly getReviewDiffPreview: (
305 input: ReviewDiffPreviewInput,
306 ) => Effect.Effect<ReviewDiffPreviewResult, GitCommandError>;
307 readonly getReviewDiffFileContents: (
308 input: ReviewDiffFileContentsInput,
309 ) => Effect.Effect<ReviewDiffFileContentsResult, GitCommandError>;
310 readonly readConfigValue: (
311 cwd: string,
312 key: string,
313 ) => Effect.Effect<string | null, GitCommandError>;
314 readonly listRefs: (
315 input: VcsListRefsInput,
316 ) => Effect.Effect<VcsListRefsResult, GitCommandError>;
317 readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
318 readonly createWorktree: (
319 input: VcsCreateWorktreeInput,
320 options?: CreateWorktreeOptions,
321 ) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
322 readonly fetchPullRequestBranch: (
323 input: GitFetchPullRequestBranchInput,
324 ) => Effect.Effect<void, GitCommandError>;
325 /** Fetches `refs/pull/<n>/head` without writing a branch, for heads that exist nowhere else. */
326 readonly fetchPullRequestHeadCommit: (
327 input: GitFetchPullRequestHeadCommitInput,
328 ) => Effect.Effect<GitResolveCommitResult, GitCommandError>;
329 readonly resolveCommit: (
330 input: GitResolveCommitInput,
331 ) => Effect.Effect<GitResolveCommitResult, GitCommandError>;
332 /** Moves the branch checked out in `cwd` onto `targetCommit`, from inside that worktree. */
333 readonly refreshCheckedOutBranch: (
334 input: GitRefreshCheckedOutBranchInput,
335 ) => Effect.Effect<GitRefreshCheckedOutBranchResult, GitCommandError>;
336 readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
337 readonly resolvePrimaryRemoteName: (cwd: string) => Effect.Effect<string, GitCommandError>;
338 readonly resolveDefaultBranchName: (
339 cwd: string,
340 remoteName: string,
341 ) => Effect.Effect<string | null, GitCommandError>;
342 readonly fetchRemote: (input: GitFetchRemoteInput) => Effect.Effect<void, GitCommandError>;
343 readonly remoteExists: (input: GitRemoteExistsInput) => Effect.Effect<boolean, GitCommandError>;
344 readonly remoteBranchExists: (
345 input: GitRemoteBranchExistsInput,
346 ) => Effect.Effect<boolean, GitCommandError>;
347 readonly resolveRemoteTrackingCommit: (
348 input: GitResolveRemoteTrackingCommitInput,
349 ) => Effect.Effect<GitResolveRemoteTrackingCommitResult, GitCommandError>;
350 readonly fetchRemoteBranch: (
351 input: GitFetchRemoteBranchInput,
352 ) => Effect.Effect<void, GitCommandError>;
353 readonly fetchRemoteTrackingBranch: (
354 input: GitFetchRemoteTrackingBranchInput,
355 ) => Effect.Effect<void, GitCommandError>;
356 readonly setBranchUpstream: (
357 input: GitSetBranchUpstreamInput,
358 ) => Effect.Effect<void, GitCommandError>;
359 readonly removeWorktree: (
360 input: VcsRemoveWorktreeInput,
361 ) => Effect.Effect<void, GitCommandError>;
362 /** Drops worktree admin entries whose directory is already gone (`git worktree prune`). */
363 readonly pruneWorktrees: (input: {
364 readonly cwd: string;
365 }) => Effect.Effect<void, GitCommandError>;
366 readonly renameBranch: (
367 input: GitRenameBranchInput,
368 ) => Effect.Effect<GitRenameBranchResult, GitCommandError>;
369 readonly createRef: (
370 input: VcsCreateRefInput,
371 ) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
372 readonly switchRef: (
373 input: VcsSwitchRefInput,
374 ) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
375 readonly initRepo: (input: VcsInitInput) => Effect.Effect<void, GitCommandError>;
376 readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
377 }
378>()("t3/vcs/GitVcsDriver") {}
379​
380const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
381const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
382const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
383const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [
384 "-c",
385 "core.fsmonitor=false",
386 "-c",
387 "core.untrackedCache=false",
388] as const;
389​
390const nowFreshness = Effect.fn("GitVcsDriver.nowFreshness")(function* () {
391 const now = yield* DateTime.now;
392 return {
393 source: "live-local" as const,
394 observedAt: now,
395 expiresAt: Option.none(),
396 };
397});
398​
399function chunkPathsForGitCheckIgnore(relativePaths: ReadonlyArray<string>): string[][] {
400 const chunks: string[][] = [];
401 let chunk: string[] = [];
402 let chunkBytes = 0;
403​
404 for (const relativePath of relativePaths) {
405 const relativePathBytes = Buffer.byteLength(relativePath) + 1;
406 if (chunk.length > 0 && chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
407 chunks.push(chunk);
408 chunk = [];
409 chunkBytes = 0;
410 }
411​
412 chunk.push(relativePath);
413 chunkBytes += relativePathBytes;
414​
415 if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
416 chunks.push(chunk);
417 chunk = [];
418 chunkBytes = 0;
419 }
420 }
421​
422 if (chunk.length > 0) {
423 chunks.push(chunk);
424 }
425​
426 return chunks;
428​
429function parseGitRemoteVerboseOutput(
430 output: string,
431): Map<string, { url?: string; pushUrl?: string }> {
432 const remotes = new Map<string, { url?: string; pushUrl?: string }>();
433 for (const line of output.split("\n")) {
434 const trimmed = line.trim();
435 if (trimmed.length === 0) {
436 continue;
437 }
438​
439 const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed);
440 if (!match) {
441 continue;
442 }
443​
444 const name = match[1];
445 const url = match[2];
446 const direction = match[3];
447 if (!name || !url || !direction) {
448 continue;
449 }
450 const remote = remotes.get(name) ?? {};
451 if (direction === "fetch") {
452 remote.url = url;
453 } else {
454 remote.pushUrl = url;
455 }
456 remotes.set(name, remote);
457 }
458 return remotes;
460​
461const gitCommand = (
462 process: VcsProcess.VcsProcess["Service"],
463 operation: string,
464 cwd: string,
465 args: ReadonlyArray<string>,
466 options?: {
467 readonly stdin?: string;
468 readonly env?: NodeJS.ProcessEnv;
469 readonly allowNonZeroExit?: boolean;
470 readonly timeoutMs?: number;
471 readonly maxOutputBytes?: number;
472 readonly outputMode?: VcsProcess.VcsProcessInput["outputMode"];
473 readonly appendTruncationMarker?: boolean;
474 },
475) =>
476 process.run({
477 operation,
478 command: "git",
479 args: ["-C", cwd, ...args],
480 cwd,
481 spawnCwd: globalThis.process.cwd(),
482 ...(options?.stdin !== undefined ? { stdin: options.stdin } : {}),
483 ...(options?.env !== undefined ? { env: options.env } : {}),
484 ...(options?.allowNonZeroExit !== undefined
485 ? { allowNonZeroExit: options.allowNonZeroExit }
486 : {}),
487 ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
488 ...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
489 ...(options?.outputMode !== undefined ? { outputMode: options.outputMode } : {}),
490 ...(options?.appendTruncationMarker !== undefined
491 ? { appendTruncationMarker: options.appendTruncationMarker }
492 : {}),
493 });
494​
495export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* () {
496 const fileSystem = yield* FileSystem.FileSystem;
497 const path = yield* Path.Path;
498 const vcsProcess = yield* VcsProcess.VcsProcess;
499 const capabilities = {
500 kind: "git" as const,
501 supportsWorktrees: true,
502 supportsBookmarks: false,
503 supportsAtomicSnapshot: false,
504 supportsPushDefaultRemote: true,
505 ignoreClassifier: "native" as const,
506 };
507​
508 const isInsideWorkTree: VcsDriver.VcsDriver["Service"]["isInsideWorkTree"] = (cwd) =>
509 gitCommand(
510 vcsProcess,
511 "GitVcsDriver.isInsideWorkTree",
512 cwd,
513 ["rev-parse", "--is-inside-work-tree"],
514 {
515 allowNonZeroExit: true,
516 timeoutMs: 5_000,
517 maxOutputBytes: 4_096,
518 },
519 ).pipe(Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"));
520​
521 const execute: VcsDriver.VcsDriver["Service"]["execute"] = (input) =>
522 gitCommand(vcsProcess, input.operation, input.cwd, input.args, {
523 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
524 ...(input.env !== undefined ? { env: input.env } : {}),
525 ...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}),
526 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
527 ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
528 ...(input.outputMode !== undefined ? { outputMode: input.outputMode } : {}),
529 ...(input.appendTruncationMarker !== undefined
530 ? { appendTruncationMarker: input.appendTruncationMarker }
531 : {}),
532 });
533​
534 const detectRepository: VcsDriver.VcsDriver["Service"]["detectRepository"] = Effect.fn(
535 "detectRepository",
536 )(function* (cwd) {
537 if (!(yield* isInsideWorkTree(cwd))) {
538 return null;
539 }
540​
541 const root = yield* gitCommand(vcsProcess, "GitVcsDriver.detectRepository.root", cwd, [
542 "rev-parse",
543 "--show-toplevel",
544 ]);
545 const gitCommonDir = yield* gitCommand(
546 vcsProcess,
547 "GitVcsDriver.detectRepository.commonDir",
548 cwd,
549 ["rev-parse", "--git-common-dir"],
550 ).pipe(Effect.orElseSucceed(() => null));
551​
552 return {
553 kind: "git" as const,
554 rootPath: root.stdout.trim(),
555 metadataPath: gitCommonDir?.stdout.trim() || null,
556 freshness: yield* nowFreshness(),
557 };
558 });
559​
560 const listWorkspaceFiles: VcsDriver.VcsDriver["Service"]["listWorkspaceFiles"] = (cwd) =>
561 gitCommand(
562 vcsProcess,
563 "GitVcsDriver.listWorkspaceFiles",
564 cwd,
565 [
566 ...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
567 "ls-files",
568 "--cached",
569 "--others",
570 "--exclude-standard",
571 "-z",
572 ],
573 {
574 allowNonZeroExit: true,
575 timeoutMs: 20_000,
576 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
577 appendTruncationMarker: true,
578 },
579 ).pipe(
580 Effect.flatMap((result) =>
581 result.exitCode === 0
582 ? Effect.gen(function* () {
583 const freshness = yield* nowFreshness();
584 return {
585 paths: splitNullSeparatedGitStdoutPaths(result),
586 truncated: result.stdoutTruncated,
587 freshness,
588 };
589 })
590 : Effect.fail(
591 new VcsProcessExitError({
592 operation: "GitVcsDriver.listWorkspaceFiles",
593 command: "git ls-files",
594 cwd,
595 exitCode: result.exitCode,
596 detail: result.stderr.trim() || "git ls-files failed",
597 }),
598 ),
599 ),
600 );
601​
602 const listRemotes: VcsDriver.VcsDriver["Service"]["listRemotes"] = Effect.fn("listRemotes")(
603 function* (cwd) {
604 const result = yield* gitCommand(
605 vcsProcess,
606 "GitVcsDriver.listRemotes",
607 cwd,
608 ["remote", "-v"],
609 {
610 allowNonZeroExit: true,
611 timeoutMs: 5_000,
612 maxOutputBytes: 64 * 1024,
613 },
614 );
615​
616 if (result.exitCode !== 0) {
617 return yield* new VcsProcessExitError({
618 operation: "GitVcsDriver.listRemotes",
619 command: "git remote -v",
620 cwd,
621 exitCode: result.exitCode,
622 detail: result.stderr.trim() || "git remote -v failed",
623 });
624 }
625​
626 const parsed = parseGitRemoteVerboseOutput(result.stdout);
627 const remotes = Array.from(parsed.entries()).flatMap(([name, remote]) => {
628 if (!remote.url) {
629 return [];
630 }
631 return [
632 {
633 name,
634 url: remote.url,
635 pushUrl: remote.pushUrl ? Option.some(remote.pushUrl) : Option.none(),
636 isPrimary: name === "origin",
637 },
638 ];
639 });
640​
641 return {
642 remotes,
643 freshness: yield* nowFreshness(),
644 };
645 },
646 );
647​
648 const filterIgnoredPaths: VcsDriver.VcsDriver["Service"]["filterIgnoredPaths"] = Effect.fn(
649 "filterIgnoredPaths",
650 )(function* (cwd, relativePaths) {
651 if (relativePaths.length === 0) {
652 return relativePaths;
653 }
654​
655 const ignoredPaths = new Set<string>();
656 const chunks = chunkPathsForGitCheckIgnore(relativePaths);
657​
658 for (const chunk of chunks) {
659 const result = yield* gitCommand(
660 vcsProcess,
661 "GitVcsDriver.filterIgnoredPaths",
662 cwd,
663 [...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
664 {
665 stdin: `${chunk.join("\0")}\0`,
666 allowNonZeroExit: true,
667 timeoutMs: 20_000,
668 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
669 appendTruncationMarker: true,
670 },
671 );
672​
673 if (result.exitCode !== 0 && result.exitCode !== 1) {
674 return yield* new VcsProcessExitError({
675 operation: "GitVcsDriver.filterIgnoredPaths",
676 command: "git check-ignore",
677 cwd,
678 exitCode: result.exitCode,
679 detail: result.stderr.trim() || "git check-ignore failed",
680 });
681 }
682​
683 for (const ignoredPath of splitNullSeparatedGitStdoutPaths(result)) {
684 ignoredPaths.add(ignoredPath);
685 }
686 }
687​
688 if (ignoredPaths.size === 0) {
689 return relativePaths;
690 }
691​
692 return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
693 });
694​
695 const initRepository: VcsDriver.VcsDriver["Service"]["initRepository"] = (input) =>
696 gitCommand(vcsProcess, "GitVcsDriver.initRepository", input.cwd, ["init"], {
697 timeoutMs: 10_000,
698 maxOutputBytes: 64 * 1024,
699 }).pipe(Effect.asVoid);
700​
701 const resolveHeadCommit = (cwd: string) =>
702 execute({
703 operation: "GitVcsDriver.checkpoints.resolveHeadCommit",
704 cwd,
705 args: ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
706 allowNonZeroExit: true,
707 }).pipe(
708 Effect.map((result) => {
709 if (result.exitCode !== 0) {
710 return null;
711 }
712 const commit = result.stdout.trim();
713 return commit.length > 0 ? commit : null;
714 }),
715 );
716​
717 const hasHeadCommit = (cwd: string) =>
718 execute({
719 operation: "GitVcsDriver.checkpoints.hasHeadCommit",
720 cwd,
721 args: ["rev-parse", "--verify", "HEAD"],
722 allowNonZeroExit: true,
723 }).pipe(Effect.map((result) => result.exitCode === 0));
724​
725 const resolveCheckpointCommit = (cwd: string, checkpointRef: string) =>
726 execute({
727 operation: "GitVcsDriver.checkpoints.resolveCheckpointCommit",
728 cwd,
729 args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`],
730 allowNonZeroExit: true,
731 }).pipe(
732 Effect.map((result) => {
733 if (result.exitCode !== 0) {
734 return null;
735 }
736 const commit = result.stdout.trim();
737 return commit.length > 0 ? commit : null;
738 }),
739 );
740​
741 const resolveGitCommonDir = (cwd: string) =>
742 Effect.gen(function* () {
743 const result = yield* execute({
744 operation: "GitVcsDriver.checkpoints.resolveGitCommonDir",
745 cwd,
746 args: ["rev-parse", "--git-common-dir"],
747 });
748 const gitCommonDir = result.stdout.trim();
749 return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
750 });
751​
752 const checkpoints: VcsDriver.VcsCheckpointOps = {
753 captureCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureCheckpoint")(function* (input) {
754 const operation = "GitVcsDriver.checkpoints.captureCheckpoint";
755 const gitCommonDir = yield* resolveGitCommonDir(input.cwd);
756 const tempIndexPath = path.join(
757 gitCommonDir,
758 `t3-checkpoint-index-${NodeCrypto.randomUUID()}`,
759 );
760 const commitEnv: NodeJS.ProcessEnv = {
761 ...process.env,
762 GIT_INDEX_FILE: tempIndexPath,
763 GIT_AUTHOR_NAME: "T3 Code",
764 GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com",
765 GIT_COMMITTER_NAME: "T3 Code",
766 GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com",
767 };
768​
769 const cleanupTempIndex = fileSystem
770 .remove(tempIndexPath, { force: true })
771 .pipe(Effect.ignore);
772​
773 yield* Effect.gen(function* () {
774 const headExists = yield* hasHeadCommit(input.cwd);
775 if (headExists) {
776 const reusedIndex = yield* Effect.gen(function* () {
777 const indexPath = yield* execute({
778 operation,
779 cwd: input.cwd,
780 args: ["rev-parse", "--path-format=absolute", "--git-path", "index"],
781 });
782 const { mtime } = yield* fileSystem.stat(indexPath.stdout.trim());
783 if (Option.isNone(mtime)) return false;
784 // Stay below the source timestamp even if Date rounded up, preserving Git's racy check.
785 const indexTime = Math.floor((mtime.value.getTime() - 1) / 1000);
786 if (indexTime <= 0) return false;
787 yield* fileSystem.copyFile(indexPath.stdout.trim(), tempIndexPath);
788 // Retain stat data only where the copied index already matches HEAD.
789 yield* execute({
790 operation,
791 cwd: input.cwd,
792 args: ["-c", "core.fsmonitor=false", "read-tree", "--reset", "HEAD"],
793 env: commitEnv,
794 });
795 // read-tree can rewrite the index, so restore its racy timestamp afterward.
796 yield* fileSystem.utimes(tempIndexPath, indexTime, indexTime);
797 const entries = yield* execute({
798 operation,
799 cwd: input.cwd,
800 args: ["ls-files", "-v"],
801 env: commitEnv,
802 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
803 });
804 // A fresh index must still capture assume-unchanged/skip-worktree files.
805 return !entries.stdoutTruncated && !/^[a-zS] /m.test(entries.stdout);
806 }).pipe(Effect.orElseSucceed(() => false));
807 if (!reusedIndex) {
808 yield* execute({
809 operation,
810 cwd: input.cwd,
811 args: ["read-tree", "HEAD"],
812 env: commitEnv,
813 });
814 }
815 }
816​
817 yield* execute({
818 operation,
819 cwd: input.cwd,
820 args: ["add", "-A", "--", "."],
821 env: commitEnv,
822 });
823​
824 const writeTreeResult = yield* execute({
825 operation,
826 cwd: input.cwd,
827 args: ["write-tree"],
828 env: commitEnv,
829 });
830 const treeOid = writeTreeResult.stdout.trim();
831 if (treeOid.length === 0) {
832 return yield* new VcsProcessExitError({
833 operation,
834 command: "git write-tree",
835 cwd: input.cwd,
836 exitCode: 0,
837 detail: "git write-tree returned an empty tree oid.",
838 });
839 }
840​
841 const message = `t3 checkpoint ref=${input.checkpointRef}`;
842 const commitTreeResult = yield* execute({
843 operation,
844 cwd: input.cwd,
845 args: ["commit-tree", treeOid, "-m", message],
846 env: commitEnv,
847 });
848 const commitOid = commitTreeResult.stdout.trim();
849 if (commitOid.length === 0) {
850 return yield* new VcsProcessExitError({
851 operation,
852 command: "git commit-tree",
853 cwd: input.cwd,
854 exitCode: 0,
855 detail: "git commit-tree returned an empty commit oid.",
856 });
857 }
858​
859 yield* execute({
860 operation,
861 cwd: input.cwd,
862 args: ["update-ref", input.checkpointRef, commitOid],
863 });
864 }).pipe(Effect.ensuring(cleanupTempIndex));
865 }),
866​
867 hasCheckpointRef: (input) =>
868 resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
869 Effect.map((commit) => commit !== null),
870 ),
871​
872 restoreCheckpoint: Effect.fn("GitVcsDriver.checkpoints.restoreCheckpoint")(function* (input) {
873 const operation = "GitVcsDriver.checkpoints.restoreCheckpoint";
874​
875 let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
876​
877 if (!commitOid && input.fallbackToHead === true) {
878 commitOid = yield* resolveHeadCommit(input.cwd);
879 }
880​
881 if (!commitOid) {
882 return false;
883 }
884​
885 const tracked = yield* execute({
886 operation,
887 cwd: input.cwd,
888 args: ["ls-files", "--cached", `--with-tree=${commitOid}`, "-z", "--", "."],
889 });
890 // An empty index and checkpoint have nothing for git restore's pathspec to match.
891 if (tracked.stdout.length > 0) {
892 yield* execute({
893 operation,
894 cwd: input.cwd,
895 args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
896 });
897 }
898 // Restoring away the last tracked file can remove a nested workspace directory.
899 yield* fileSystem.makeDirectory(input.cwd, { recursive: true }).pipe(
900 Effect.mapError(
901 (cause) =>
902 new VcsProcessExitError({
903 operation,
904 command: "git restore",
905 cwd: input.cwd,
906 exitCode: 0,
907 detail: `Could not recreate the checkpoint workspace: ${cause.message}`,
908 }),
909 ),
910 );
911 const cleaned = yield* execute({
912 operation,
913 cwd: input.cwd,
914 args: ["clean", "-fd", "--", "."],
915 allowNonZeroExit: true,
916 });
917 if (cleaned.exitCode !== 0) {
918 // Git can remove every child, then fail trying to remove './' itself.
919 const emptiedWorkspace =
920 cleaned.exitCode === 1 &&
921 /^warning: failed to remove \.\/: [^\n]+$/.test(cleaned.stderr.trim()) &&
922 (yield* fileSystem.readDirectory(input.cwd).pipe(
923 Effect.map((entries) => entries.length === 0),
924 Effect.catch(() => Effect.succeed(false)),
925 ));
926 if (!emptiedWorkspace)
927 return yield* new VcsProcessExitError({
928 operation,
929 command: "git clean",
930 cwd: input.cwd,
931 exitCode: cleaned.exitCode,
932 detail: cleaned.stderr.trim() || "Could not clean the checkpoint workspace.",
933 });
934 }
935​
936 const headExists = yield* hasHeadCommit(input.cwd);
937 if (headExists) {
938 yield* execute({
939 operation,
940 cwd: input.cwd,
941 args: ["reset", "--quiet", "--", "."],
942 });
943 }
944​
945 return true;
946 }),
947​
948 diffCheckpoints: Effect.fn("GitVcsDriver.checkpoints.diffCheckpoints")(function* (input) {
949 const operation = "GitVcsDriver.checkpoints.diffCheckpoints";
950 yield* Effect.annotateCurrentSpan({
951 "checkpoint.cwd": input.cwd,
952 "checkpoint.from_ref": input.fromCheckpointRef,
953 "checkpoint.to_ref": input.toCheckpointRef,
954 "checkpoint.ignore_whitespace": input.ignoreWhitespace,
955 "checkpoint.format": input.format ?? "patch",
956 "checkpoint.fallback_from_to_head": input.fallbackFromToHead,
957 });
958​
959 let fromRevision: string = input.fromCheckpointRef;
960 if (input.fallbackFromToHead === true) {
961 const resolvedFromCommit = yield* resolveCheckpointCommit(
962 input.cwd,
963 input.fromCheckpointRef,
964 );
965 if (resolvedFromCommit) {
966 fromRevision = resolvedFromCommit;
967 } else {
968 const headCommit = yield* resolveHeadCommit(input.cwd);
969 if (!headCommit) {
970 return yield* new VcsProcessExitError({
971 operation,
972 command: "git diff",
973 cwd: input.cwd,
974 exitCode: 1,
975 detail: "Checkpoint ref is unavailable for diff operation.",
976 });
977 }
978 fromRevision = headCommit;
979 }
980 }
981​
982 const result = yield* execute({
983 operation,
984 cwd: input.cwd,
985 args: [
986 "diff",
987 ...(input.format === "numstat" ? ["--numstat", "-z"] : ["--patch"]),
988 "--no-color",
989 "--no-ext-diff",
990 "--no-textconv",
991 ...PATCH_RENDER_PREFIX_ARGS,
992 ...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
993 `${fromRevision}^{commit}`,
994 `${input.toCheckpointRef}^{commit}`,
995 ],
996 allowNonZeroExit: true,
997 maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
998 outputMode: input.format === "numstat" ? "error" : "truncate",
999 });
1000​
1001 if (result.exitCode !== 0) {
1002 return yield* new VcsProcessExitError({
1003 operation,
1004 command: "git diff",
1005 cwd: input.cwd,
1006 exitCode: result.exitCode,
1007 detail: result.stderr.trim() || "Checkpoint ref is unavailable for diff operation.",
1008 });
1010​
1011 return result.stdout;
1012 }),
1013​
1014 deleteCheckpointRefs: Effect.fn("GitVcsDriver.checkpoints.deleteCheckpointRefs")(
1015 function* (input) {
1016 yield* Effect.forEach(
1017 input.checkpointRefs,
1018 (checkpointRef) =>
1019 execute({
1020 operation: "GitVcsDriver.checkpoints.deleteCheckpointRefs",
1021 cwd: input.cwd,
1022 args: ["update-ref", "-d", checkpointRef],
1023 allowNonZeroExit: true,
1024 }),
1025 { discard: true },
1026 );
1027 },
1028 ),
1029 };
1030​
1031 return {
1032 capabilities,
1033 execute,
1034 checkpoints,
1035 detectRepository,
1036 isInsideWorkTree,
1037 listWorkspaceFiles,
1038 listRemotes,
1039 filterIgnoredPaths,
1040 initRepository,
1041 };
1042});
1043​
1044export const makeVcsDriver = Effect.gen(function* () {
1045 const driver = yield* makeVcsDriverShape();
1046 return VcsDriver.VcsDriver.of(driver);
1047});
1048​
1049export const make = Effect.gen(function* () {
1050 const git = yield* makeGitVcsDriverCore();
1051 return GitVcsDriver.of(git);
1052});
1053​
1054export const vcsLayer = Layer.effect(VcsDriver.VcsDriver, makeVcsDriver);
1055export const layer = Layer.effect(GitVcsDriver, make);