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

GitVcsDriver.ts

1,021 lines31.7 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;
241​
242export interface GitRemoteExistsInput {
243 cwd: string;
244 remoteName: string;
246​
247export interface GitRemoteBranchExistsInput extends GitRemoteExistsInput {
248 refName: string;
250​
251export interface GitResolveRemoteTrackingCommitInput {
252 cwd: string;
253 refName: string;
254 fallbackRemoteName: string;
256​
257export interface GitResolveRemoteTrackingCommitResult {
258 commitSha: string;
259 remoteRefName: string;
261​
262export interface GitSetBranchUpstreamInput {
263 cwd: string;
264 branch: string;
265 remoteName: string;
266 remoteBranch: string;
268​
269export interface GitRemoteStatusOptions {
270 readonly refreshUpstream?: boolean;
272​
273export class GitVcsDriver extends Context.Service<
274 GitVcsDriver,
275 {
276 readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
277 readonly status: (input: VcsStatusInput) => Effect.Effect<VcsStatusResult, GitCommandError>;
278 readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
279 readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
280 readonly statusDetailsRemote: (
281 cwd: string,
282 options?: GitRemoteStatusOptions,
283 ) => Effect.Effect<GitRemoteStatusDetails, GitCommandError>;
284 readonly prepareCommitContext: (
285 cwd: string,
286 filePaths?: readonly string[],
287 ) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
288 readonly commit: (
289 cwd: string,
290 subject: string,
291 body: string,
292 options?: GitCommitOptions,
293 ) => Effect.Effect<{ commitSha: string }, GitCommandError>;
294 readonly pushCurrentBranch: (
295 cwd: string,
296 fallbackBranch: string | null,
297 options?: { readonly remoteName?: string | null },
298 ) => Effect.Effect<GitPushResult, GitCommandError>;
299 readonly readRangeContext: (
300 cwd: string,
301 baseRef: string,
302 ) => Effect.Effect<GitRangeContext, GitCommandError>;
303 readonly getReviewDiffPreview: (
304 input: ReviewDiffPreviewInput,
305 ) => Effect.Effect<ReviewDiffPreviewResult, GitCommandError>;
306 readonly getReviewDiffFileContents: (
307 input: ReviewDiffFileContentsInput,
308 ) => Effect.Effect<ReviewDiffFileContentsResult, GitCommandError>;
309 readonly readConfigValue: (
310 cwd: string,
311 key: string,
312 ) => Effect.Effect<string | null, GitCommandError>;
313 readonly listRefs: (
314 input: VcsListRefsInput,
315 ) => Effect.Effect<VcsListRefsResult, GitCommandError>;
316 readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
317 readonly createWorktree: (
318 input: VcsCreateWorktreeInput,
319 options?: CreateWorktreeOptions,
320 ) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
321 readonly fetchPullRequestBranch: (
322 input: GitFetchPullRequestBranchInput,
323 ) => Effect.Effect<void, GitCommandError>;
324 /** Fetches `refs/pull/<n>/head` without writing a branch, for heads that exist nowhere else. */
325 readonly fetchPullRequestHeadCommit: (
326 input: GitFetchPullRequestHeadCommitInput,
327 ) => Effect.Effect<GitResolveCommitResult, GitCommandError>;
328 readonly resolveCommit: (
329 input: GitResolveCommitInput,
330 ) => Effect.Effect<GitResolveCommitResult, GitCommandError>;
331 /** Moves the branch checked out in `cwd` onto `targetCommit`, from inside that worktree. */
332 readonly refreshCheckedOutBranch: (
333 input: GitRefreshCheckedOutBranchInput,
334 ) => Effect.Effect<GitRefreshCheckedOutBranchResult, GitCommandError>;
335 readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
336 readonly resolvePrimaryRemoteName: (cwd: string) => Effect.Effect<string, GitCommandError>;
337 readonly resolveDefaultBranchName: (
338 cwd: string,
339 remoteName: string,
340 ) => Effect.Effect<string | null, GitCommandError>;
341 readonly fetchRemote: (input: GitFetchRemoteInput) => Effect.Effect<void, GitCommandError>;
342 readonly remoteExists: (input: GitRemoteExistsInput) => Effect.Effect<boolean, GitCommandError>;
343 readonly remoteBranchExists: (
344 input: GitRemoteBranchExistsInput,
345 ) => Effect.Effect<boolean, GitCommandError>;
346 readonly resolveRemoteTrackingCommit: (
347 input: GitResolveRemoteTrackingCommitInput,
348 ) => Effect.Effect<GitResolveRemoteTrackingCommitResult, GitCommandError>;
349 readonly fetchRemoteBranch: (
350 input: GitFetchRemoteBranchInput,
351 ) => Effect.Effect<void, GitCommandError>;
352 readonly fetchRemoteTrackingBranch: (
353 input: GitFetchRemoteTrackingBranchInput,
354 ) => Effect.Effect<void, GitCommandError>;
355 readonly setBranchUpstream: (
356 input: GitSetBranchUpstreamInput,
357 ) => Effect.Effect<void, GitCommandError>;
358 readonly removeWorktree: (
359 input: VcsRemoveWorktreeInput,
360 ) => Effect.Effect<void, GitCommandError>;
361 /** Drops worktree admin entries whose directory is already gone (`git worktree prune`). */
362 readonly pruneWorktrees: (input: {
363 readonly cwd: string;
364 }) => Effect.Effect<void, GitCommandError>;
365 readonly renameBranch: (
366 input: GitRenameBranchInput,
367 ) => Effect.Effect<GitRenameBranchResult, GitCommandError>;
368 readonly createRef: (
369 input: VcsCreateRefInput,
370 ) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
371 readonly switchRef: (
372 input: VcsSwitchRefInput,
373 ) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
374 readonly initRepo: (input: VcsInitInput) => Effect.Effect<void, GitCommandError>;
375 readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
376 }
377>()("t3/vcs/GitVcsDriver") {}
378​
379const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
380const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
381const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
382const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [
383 "-c",
384 "core.fsmonitor=false",
385 "-c",
386 "core.untrackedCache=false",
387] as const;
388​
389const nowFreshness = Effect.fn("GitVcsDriver.nowFreshness")(function* () {
390 const now = yield* DateTime.now;
391 return {
392 source: "live-local" as const,
393 observedAt: now,
394 expiresAt: Option.none(),
395 };
396});
397​
398function chunkPathsForGitCheckIgnore(relativePaths: ReadonlyArray<string>): string[][] {
399 const chunks: string[][] = [];
400 let chunk: string[] = [];
401 let chunkBytes = 0;
402​
403 for (const relativePath of relativePaths) {
404 const relativePathBytes = Buffer.byteLength(relativePath) + 1;
405 if (chunk.length > 0 && chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
406 chunks.push(chunk);
407 chunk = [];
408 chunkBytes = 0;
409 }
410​
411 chunk.push(relativePath);
412 chunkBytes += relativePathBytes;
413​
414 if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
415 chunks.push(chunk);
416 chunk = [];
417 chunkBytes = 0;
418 }
419 }
420​
421 if (chunk.length > 0) {
422 chunks.push(chunk);
423 }
424​
425 return chunks;
427​
428function parseGitRemoteVerboseOutput(
429 output: string,
430): Map<string, { url?: string; pushUrl?: string }> {
431 const remotes = new Map<string, { url?: string; pushUrl?: string }>();
432 for (const line of output.split("\n")) {
433 const trimmed = line.trim();
434 if (trimmed.length === 0) {
435 continue;
436 }
437​
438 const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed);
439 if (!match) {
440 continue;
441 }
442​
443 const name = match[1];
444 const url = match[2];
445 const direction = match[3];
446 if (!name || !url || !direction) {
447 continue;
448 }
449 const remote = remotes.get(name) ?? {};
450 if (direction === "fetch") {
451 remote.url = url;
452 } else {
453 remote.pushUrl = url;
454 }
455 remotes.set(name, remote);
456 }
457 return remotes;
459​
460const gitCommand = (
461 process: VcsProcess.VcsProcess["Service"],
462 operation: string,
463 cwd: string,
464 args: ReadonlyArray<string>,
465 options?: {
466 readonly stdin?: string;
467 readonly env?: NodeJS.ProcessEnv;
468 readonly allowNonZeroExit?: boolean;
469 readonly timeoutMs?: number;
470 readonly maxOutputBytes?: number;
471 readonly outputMode?: VcsProcess.VcsProcessInput["outputMode"];
472 readonly appendTruncationMarker?: boolean;
473 },
474) =>
475 process.run({
476 operation,
477 command: "git",
478 args: ["-C", cwd, ...args],
479 cwd,
480 spawnCwd: globalThis.process.cwd(),
481 ...(options?.stdin !== undefined ? { stdin: options.stdin } : {}),
482 ...(options?.env !== undefined ? { env: options.env } : {}),
483 ...(options?.allowNonZeroExit !== undefined
484 ? { allowNonZeroExit: options.allowNonZeroExit }
485 : {}),
486 ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
487 ...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
488 ...(options?.outputMode !== undefined ? { outputMode: options.outputMode } : {}),
489 ...(options?.appendTruncationMarker !== undefined
490 ? { appendTruncationMarker: options.appendTruncationMarker }
491 : {}),
492 });
493​
494export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* () {
495 const fileSystem = yield* FileSystem.FileSystem;
496 const path = yield* Path.Path;
497 const vcsProcess = yield* VcsProcess.VcsProcess;
498 const capabilities = {
499 kind: "git" as const,
500 supportsWorktrees: true,
501 supportsBookmarks: false,
502 supportsAtomicSnapshot: false,
503 supportsPushDefaultRemote: true,
504 ignoreClassifier: "native" as const,
505 };
506​
507 const isInsideWorkTree: VcsDriver.VcsDriver["Service"]["isInsideWorkTree"] = (cwd) =>
508 gitCommand(
509 vcsProcess,
510 "GitVcsDriver.isInsideWorkTree",
511 cwd,
512 ["rev-parse", "--is-inside-work-tree"],
513 {
514 allowNonZeroExit: true,
515 timeoutMs: 5_000,
516 maxOutputBytes: 4_096,
517 },
518 ).pipe(Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"));
519​
520 const execute: VcsDriver.VcsDriver["Service"]["execute"] = (input) =>
521 gitCommand(vcsProcess, input.operation, input.cwd, input.args, {
522 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
523 ...(input.env !== undefined ? { env: input.env } : {}),
524 ...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}),
525 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
526 ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
527 ...(input.outputMode !== undefined ? { outputMode: input.outputMode } : {}),
528 ...(input.appendTruncationMarker !== undefined
529 ? { appendTruncationMarker: input.appendTruncationMarker }
530 : {}),
531 });
532​
533 const detectRepository: VcsDriver.VcsDriver["Service"]["detectRepository"] = Effect.fn(
534 "detectRepository",
535 )(function* (cwd) {
536 if (!(yield* isInsideWorkTree(cwd))) {
537 return null;
538 }
539​
540 const root = yield* gitCommand(vcsProcess, "GitVcsDriver.detectRepository.root", cwd, [
541 "rev-parse",
542 "--show-toplevel",
543 ]);
544 const gitCommonDir = yield* gitCommand(
545 vcsProcess,
546 "GitVcsDriver.detectRepository.commonDir",
547 cwd,
548 ["rev-parse", "--git-common-dir"],
549 ).pipe(Effect.orElseSucceed(() => null));
550​
551 return {
552 kind: "git" as const,
553 rootPath: root.stdout.trim(),
554 metadataPath: gitCommonDir?.stdout.trim() || null,
555 freshness: yield* nowFreshness(),
556 };
557 });
558​
559 const listWorkspaceFiles: VcsDriver.VcsDriver["Service"]["listWorkspaceFiles"] = (cwd) =>
560 gitCommand(
561 vcsProcess,
562 "GitVcsDriver.listWorkspaceFiles",
563 cwd,
564 [
565 ...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
566 "ls-files",
567 "--cached",
568 "--others",
569 "--exclude-standard",
570 "-z",
571 ],
572 {
573 allowNonZeroExit: true,
574 timeoutMs: 20_000,
575 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
576 appendTruncationMarker: true,
577 },
578 ).pipe(
579 Effect.flatMap((result) =>
580 result.exitCode === 0
581 ? Effect.gen(function* () {
582 const freshness = yield* nowFreshness();
583 return {
584 paths: splitNullSeparatedGitStdoutPaths(result),
585 truncated: result.stdoutTruncated,
586 freshness,
587 };
588 })
589 : Effect.fail(
590 new VcsProcessExitError({
591 operation: "GitVcsDriver.listWorkspaceFiles",
592 command: "git ls-files",
593 cwd,
594 exitCode: result.exitCode,
595 detail: result.stderr.trim() || "git ls-files failed",
596 }),
597 ),
598 ),
599 );
600​
601 const listRemotes: VcsDriver.VcsDriver["Service"]["listRemotes"] = Effect.fn("listRemotes")(
602 function* (cwd) {
603 const result = yield* gitCommand(
604 vcsProcess,
605 "GitVcsDriver.listRemotes",
606 cwd,
607 ["remote", "-v"],
608 {
609 allowNonZeroExit: true,
610 timeoutMs: 5_000,
611 maxOutputBytes: 64 * 1024,
612 },
613 );
614​
615 if (result.exitCode !== 0) {
616 return yield* new VcsProcessExitError({
617 operation: "GitVcsDriver.listRemotes",
618 command: "git remote -v",
619 cwd,
620 exitCode: result.exitCode,
621 detail: result.stderr.trim() || "git remote -v failed",
622 });
623 }
624​
625 const parsed = parseGitRemoteVerboseOutput(result.stdout);
626 const remotes = Array.from(parsed.entries()).flatMap(([name, remote]) => {
627 if (!remote.url) {
628 return [];
629 }
630 return [
631 {
632 name,
633 url: remote.url,
634 pushUrl: remote.pushUrl ? Option.some(remote.pushUrl) : Option.none(),
635 isPrimary: name === "origin",
636 },
637 ];
638 });
639​
640 return {
641 remotes,
642 freshness: yield* nowFreshness(),
643 };
644 },
645 );
646​
647 const filterIgnoredPaths: VcsDriver.VcsDriver["Service"]["filterIgnoredPaths"] = Effect.fn(
648 "filterIgnoredPaths",
649 )(function* (cwd, relativePaths) {
650 if (relativePaths.length === 0) {
651 return relativePaths;
652 }
653​
654 const ignoredPaths = new Set<string>();
655 const chunks = chunkPathsForGitCheckIgnore(relativePaths);
656​
657 for (const chunk of chunks) {
658 const result = yield* gitCommand(
659 vcsProcess,
660 "GitVcsDriver.filterIgnoredPaths",
661 cwd,
662 [...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
663 {
664 stdin: `${chunk.join("\0")}\0`,
665 allowNonZeroExit: true,
666 timeoutMs: 20_000,
667 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
668 appendTruncationMarker: true,
669 },
670 );
671​
672 if (result.exitCode !== 0 && result.exitCode !== 1) {
673 return yield* new VcsProcessExitError({
674 operation: "GitVcsDriver.filterIgnoredPaths",
675 command: "git check-ignore",
676 cwd,
677 exitCode: result.exitCode,
678 detail: result.stderr.trim() || "git check-ignore failed",
679 });
680 }
681​
682 for (const ignoredPath of splitNullSeparatedGitStdoutPaths(result)) {
683 ignoredPaths.add(ignoredPath);
684 }
685 }
686​
687 if (ignoredPaths.size === 0) {
688 return relativePaths;
689 }
690​
691 return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
692 });
693​
694 const initRepository: VcsDriver.VcsDriver["Service"]["initRepository"] = (input) =>
695 gitCommand(vcsProcess, "GitVcsDriver.initRepository", input.cwd, ["init"], {
696 timeoutMs: 10_000,
697 maxOutputBytes: 64 * 1024,
698 }).pipe(Effect.asVoid);
699​
700 const resolveHeadCommit = (cwd: string) =>
701 execute({
702 operation: "GitVcsDriver.checkpoints.resolveHeadCommit",
703 cwd,
704 args: ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
705 allowNonZeroExit: true,
706 }).pipe(
707 Effect.map((result) => {
708 if (result.exitCode !== 0) {
709 return null;
710 }
711 const commit = result.stdout.trim();
712 return commit.length > 0 ? commit : null;
713 }),
714 );
715​
716 const hasHeadCommit = (cwd: string) =>
717 execute({
718 operation: "GitVcsDriver.checkpoints.hasHeadCommit",
719 cwd,
720 args: ["rev-parse", "--verify", "HEAD"],
721 allowNonZeroExit: true,
722 }).pipe(Effect.map((result) => result.exitCode === 0));
723​
724 const resolveCheckpointCommit = (cwd: string, checkpointRef: string) =>
725 execute({
726 operation: "GitVcsDriver.checkpoints.resolveCheckpointCommit",
727 cwd,
728 args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`],
729 allowNonZeroExit: true,
730 }).pipe(
731 Effect.map((result) => {
732 if (result.exitCode !== 0) {
733 return null;
734 }
735 const commit = result.stdout.trim();
736 return commit.length > 0 ? commit : null;
737 }),
738 );
739​
740 const resolveGitCommonDir = (cwd: string) =>
741 Effect.gen(function* () {
742 const result = yield* execute({
743 operation: "GitVcsDriver.checkpoints.resolveGitCommonDir",
744 cwd,
745 args: ["rev-parse", "--git-common-dir"],
746 });
747 const gitCommonDir = result.stdout.trim();
748 return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
749 });
750​
751 const checkpoints: VcsDriver.VcsCheckpointOps = {
752 captureCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureCheckpoint")(function* (input) {
753 const operation = "GitVcsDriver.checkpoints.captureCheckpoint";
754 const gitCommonDir = yield* resolveGitCommonDir(input.cwd);
755 const tempIndexPath = path.join(
756 gitCommonDir,
757 `t3-checkpoint-index-${NodeCrypto.randomUUID()}`,
758 );
759 const commitEnv: NodeJS.ProcessEnv = {
760 ...process.env,
761 GIT_INDEX_FILE: tempIndexPath,
762 GIT_AUTHOR_NAME: "T3 Code",
763 GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com",
764 GIT_COMMITTER_NAME: "T3 Code",
765 GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com",
766 };
767​
768 const cleanupTempIndex = fileSystem
769 .remove(tempIndexPath, { force: true })
770 .pipe(Effect.ignore);
771​
772 yield* Effect.gen(function* () {
773 const headExists = yield* hasHeadCommit(input.cwd);
774 if (headExists) {
775 yield* execute({
776 operation,
777 cwd: input.cwd,
778 args: ["read-tree", "HEAD"],
779 env: commitEnv,
780 });
781 }
782​
783 yield* execute({
784 operation,
785 cwd: input.cwd,
786 args: ["add", "-A", "--", "."],
787 env: commitEnv,
788 });
789​
790 const writeTreeResult = yield* execute({
791 operation,
792 cwd: input.cwd,
793 args: ["write-tree"],
794 env: commitEnv,
795 });
796 const treeOid = writeTreeResult.stdout.trim();
797 if (treeOid.length === 0) {
798 return yield* new VcsProcessExitError({
799 operation,
800 command: "git write-tree",
801 cwd: input.cwd,
802 exitCode: 0,
803 detail: "git write-tree returned an empty tree oid.",
804 });
805 }
806​
807 const message = `t3 checkpoint ref=${input.checkpointRef}`;
808 const commitTreeResult = yield* execute({
809 operation,
810 cwd: input.cwd,
811 args: ["commit-tree", treeOid, "-m", message],
812 env: commitEnv,
813 });
814 const commitOid = commitTreeResult.stdout.trim();
815 if (commitOid.length === 0) {
816 return yield* new VcsProcessExitError({
817 operation,
818 command: "git commit-tree",
819 cwd: input.cwd,
820 exitCode: 0,
821 detail: "git commit-tree returned an empty commit oid.",
822 });
823 }
824​
825 yield* execute({
826 operation,
827 cwd: input.cwd,
828 args: ["update-ref", input.checkpointRef, commitOid],
829 });
830 }).pipe(Effect.ensuring(cleanupTempIndex));
831 }),
832​
833 hasCheckpointRef: (input) =>
834 resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
835 Effect.map((commit) => commit !== null),
836 ),
837​
838 restoreCheckpoint: Effect.fn("GitVcsDriver.checkpoints.restoreCheckpoint")(function* (input) {
839 const operation = "GitVcsDriver.checkpoints.restoreCheckpoint";
840​
841 let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
842​
843 if (!commitOid && input.fallbackToHead === true) {
844 commitOid = yield* resolveHeadCommit(input.cwd);
845 }
846​
847 if (!commitOid) {
848 return false;
849 }
850​
851 const tracked = yield* execute({
852 operation,
853 cwd: input.cwd,
854 args: ["ls-files", "--cached", `--with-tree=${commitOid}`, "-z", "--", "."],
855 });
856 // An empty index and checkpoint have nothing for git restore's pathspec to match.
857 if (tracked.stdout.length > 0) {
858 yield* execute({
859 operation,
860 cwd: input.cwd,
861 args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
862 });
863 }
864 // Restoring away the last tracked file can remove a nested workspace directory.
865 yield* fileSystem.makeDirectory(input.cwd, { recursive: true }).pipe(
866 Effect.mapError(
867 (cause) =>
868 new VcsProcessExitError({
869 operation,
870 command: "git restore",
871 cwd: input.cwd,
872 exitCode: 0,
873 detail: `Could not recreate the checkpoint workspace: ${cause.message}`,
874 }),
875 ),
876 );
877 const cleaned = yield* execute({
878 operation,
879 cwd: input.cwd,
880 args: ["clean", "-fd", "--", "."],
881 allowNonZeroExit: true,
882 });
883 if (cleaned.exitCode !== 0) {
884 // Git can remove every child, then fail trying to remove './' itself.
885 const emptiedWorkspace =
886 cleaned.exitCode === 1 &&
887 /^warning: failed to remove \.\/: [^\n]+$/.test(cleaned.stderr.trim()) &&
888 (yield* fileSystem.readDirectory(input.cwd).pipe(
889 Effect.map((entries) => entries.length === 0),
890 Effect.catch(() => Effect.succeed(false)),
891 ));
892 if (!emptiedWorkspace)
893 return yield* new VcsProcessExitError({
894 operation,
895 command: "git clean",
896 cwd: input.cwd,
897 exitCode: cleaned.exitCode,
898 detail: cleaned.stderr.trim() || "Could not clean the checkpoint workspace.",
899 });
900 }
901​
902 const headExists = yield* hasHeadCommit(input.cwd);
903 if (headExists) {
904 yield* execute({
905 operation,
906 cwd: input.cwd,
907 args: ["reset", "--quiet", "--", "."],
908 });
909 }
910​
911 return true;
912 }),
913​
914 diffCheckpoints: Effect.fn("GitVcsDriver.checkpoints.diffCheckpoints")(function* (input) {
915 const operation = "GitVcsDriver.checkpoints.diffCheckpoints";
916 yield* Effect.annotateCurrentSpan({
917 "checkpoint.cwd": input.cwd,
918 "checkpoint.from_ref": input.fromCheckpointRef,
919 "checkpoint.to_ref": input.toCheckpointRef,
920 "checkpoint.ignore_whitespace": input.ignoreWhitespace,
921 "checkpoint.format": input.format ?? "patch",
922 "checkpoint.fallback_from_to_head": input.fallbackFromToHead,
923 });
924​
925 let fromRevision: string = input.fromCheckpointRef;
926 if (input.fallbackFromToHead === true) {
927 const resolvedFromCommit = yield* resolveCheckpointCommit(
928 input.cwd,
929 input.fromCheckpointRef,
930 );
931 if (resolvedFromCommit) {
932 fromRevision = resolvedFromCommit;
933 } else {
934 const headCommit = yield* resolveHeadCommit(input.cwd);
935 if (!headCommit) {
936 return yield* new VcsProcessExitError({
937 operation,
938 command: "git diff",
939 cwd: input.cwd,
940 exitCode: 1,
941 detail: "Checkpoint ref is unavailable for diff operation.",
942 });
943 }
944 fromRevision = headCommit;
945 }
946 }
947​
948 const result = yield* execute({
949 operation,
950 cwd: input.cwd,
951 args: [
952 "diff",
953 ...(input.format === "numstat" ? ["--numstat", "-z"] : ["--patch"]),
954 "--no-color",
955 "--no-ext-diff",
956 "--no-textconv",
957 ...PATCH_RENDER_PREFIX_ARGS,
958 ...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
959 `${fromRevision}^{commit}`,
960 `${input.toCheckpointRef}^{commit}`,
961 ],
962 allowNonZeroExit: true,
963 maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
964 outputMode: input.format === "numstat" ? "error" : "truncate",
965 });
966​
967 if (result.exitCode !== 0) {
968 return yield* new VcsProcessExitError({
969 operation,
970 command: "git diff",
971 cwd: input.cwd,
972 exitCode: result.exitCode,
973 detail: result.stderr.trim() || "Checkpoint ref is unavailable for diff operation.",
974 });
975 }
976​
977 return result.stdout;
978 }),
979​
980 deleteCheckpointRefs: Effect.fn("GitVcsDriver.checkpoints.deleteCheckpointRefs")(
981 function* (input) {
982 yield* Effect.forEach(
983 input.checkpointRefs,
984 (checkpointRef) =>
985 execute({
986 operation: "GitVcsDriver.checkpoints.deleteCheckpointRefs",
987 cwd: input.cwd,
988 args: ["update-ref", "-d", checkpointRef],
989 allowNonZeroExit: true,
990 }),
991 { discard: true },
992 );
993 },
994 ),
995 };
996​
997 return {
998 capabilities,
999 execute,
1000 checkpoints,
1001 detectRepository,
1002 isInsideWorkTree,
1003 listWorkspaceFiles,
1004 listRemotes,
1005 filterIgnoredPaths,
1006 initRepository,
1007 };
1008});
1009​
1010export const makeVcsDriver = Effect.gen(function* () {
1011 const driver = yield* makeVcsDriverShape();
1012 return VcsDriver.VcsDriver.of(driver);
1013});
1014​
1015export const make = Effect.gen(function* () {
1016 const git = yield* makeGitVcsDriverCore();
1017 return GitVcsDriver.of(git);
1018});
1019​
1020export const vcsLayer = Layer.effect(VcsDriver.VcsDriver, makeVcsDriver);
1021export const layer = Layer.effect(GitVcsDriver, make);