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

GitVcsDriver.ts

944 lines28.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 readonly progress?: ExecuteGitProgress;
53​
54export interface ExecuteGitResult {
55 readonly exitCode: ChildProcessSpawner.ExitCode;
56 readonly stdout: string;
57 readonly stderr: string;
58 readonly stdoutTruncated: boolean;
59 readonly stderrTruncated: boolean;
61​
62export interface GitStatusDetails {
63 isRepo: boolean;
64 sourceControlProvider?: VcsStatusResult["sourceControlProvider"];
65 hasOriginRemote: boolean;
66 isDefaultBranch: boolean;
67 branch: string | null;
68 upstreamRef: string | null;
69 hasWorkingTreeChanges: boolean;
70 workingTree: VcsStatusResult["workingTree"];
71 hasUpstream: boolean;
72 aheadCount: number;
73 behindCount: number;
74 aheadOfDefaultCount: number;
76​
77export interface GitRemoteStatusDetails {
78 isRepo: boolean;
79 defaultBranch: string | null;
80 isDefaultBranch: boolean;
81 branch: string | null;
82 upstreamRef: string | null;
83 hasUpstream: boolean;
84 aheadCount: number;
85 behindCount: number;
86 aheadOfDefaultCount: number;
88​
89export interface GitPreparedCommitContext {
90 stagedSummary: string;
91 stagedPatch: string;
93​
94export interface ExecuteGitProgress {
95 readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;
96 readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;
97 readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
98 readonly onHookFinished?: (input: {
99 hookName: string;
100 exitCode: number | null;
101 durationMs: number | null;
102 }) => Effect.Effect<void, never>;
104​
105export interface GitCommitProgress {
106 readonly onOutputLine?: (input: {
107 stream: "stdout" | "stderr";
108 text: string;
109 }) => Effect.Effect<void, never>;
110 readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
111 readonly onHookFinished?: (input: {
112 hookName: string;
113 exitCode: number | null;
114 durationMs: number | null;
115 }) => Effect.Effect<void, never>;
117​
118export interface GitCommitOptions {
119 readonly timeoutMs?: number;
120 readonly progress?: GitCommitProgress;
122​
123export interface GitPushResult {
124 status: "pushed" | "skipped_up_to_date";
125 branch: string;
126 upstreamBranch?: string | undefined;
127 setUpstream?: boolean | undefined;
129​
130export interface GitRangeContext {
131 commitSummary: string;
132 diffSummary: string;
133 diffPatch: string;
135​
136export interface GitRenameBranchInput {
137 cwd: string;
138 oldBranch: string;
139 newBranch: string;
141​
142export interface GitRenameBranchResult {
143 branch: string;
145​
146export interface GitFetchPullRequestBranchInput {
147 cwd: string;
148 prNumber: number;
149 branch: string;
151​
152export interface GitFetchPullRequestHeadCommitInput {
153 cwd: string;
154 prNumber: number;
156​
157export interface GitResolveCommitInput {
158 cwd: string;
159 revision: string;
161​
162export interface GitResolveCommitResult {
163 commitSha: string;
165​
166export interface GitRefreshCheckedOutBranchInput {
167 cwd: string;
168 targetCommit: string;
169 /**
170 * Commit the checkout is allowed to be hard-reset away from: the upstream commit read before
171 * the fetch. HEAD sitting there means the checkout holds no work of its own.
172 */
173 resetWhenHeadCommit?: string | null | undefined;
175​
176export interface GitRefreshCheckedOutBranchResult {
177 headCommit: string;
178 moved: boolean;
179 onTarget: boolean;
181​
182export interface GitEnsureRemoteInput {
183 cwd: string;
184 preferredName: string;
185 url: string;
187​
188export interface GitFetchRemoteBranchInput {
189 cwd: string;
190 remoteName: string;
191 remoteBranch: string;
192 localBranch: string;
194​
195export interface GitFetchRemoteTrackingBranchInput {
196 cwd: string;
197 remoteName: string;
198 remoteBranch: string;
200​
201export interface GitFetchRemoteInput {
202 cwd: string;
203 remoteName: string;
205​
206export interface GitRemoteExistsInput {
207 cwd: string;
208 remoteName: string;
210​
211export interface GitRemoteBranchExistsInput extends GitRemoteExistsInput {
212 refName: string;
214​
215export interface GitResolveRemoteTrackingCommitInput {
216 cwd: string;
217 refName: string;
218 fallbackRemoteName: string;
220​
221export interface GitResolveRemoteTrackingCommitResult {
222 commitSha: string;
223 remoteRefName: string;
225​
226export interface GitSetBranchUpstreamInput {
227 cwd: string;
228 branch: string;
229 remoteName: string;
230 remoteBranch: string;
232​
233export interface GitRemoteStatusOptions {
234 readonly refreshUpstream?: boolean;
236​
237export class GitVcsDriver extends Context.Service<
238 GitVcsDriver,
239 {
240 readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
241 readonly status: (input: VcsStatusInput) => Effect.Effect<VcsStatusResult, GitCommandError>;
242 readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
243 readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
244 readonly statusDetailsRemote: (
245 cwd: string,
246 options?: GitRemoteStatusOptions,
247 ) => Effect.Effect<GitRemoteStatusDetails, GitCommandError>;
248 readonly prepareCommitContext: (
249 cwd: string,
250 filePaths?: readonly string[],
251 ) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
252 readonly commit: (
253 cwd: string,
254 subject: string,
255 body: string,
256 options?: GitCommitOptions,
257 ) => Effect.Effect<{ commitSha: string }, GitCommandError>;
258 readonly pushCurrentBranch: (
259 cwd: string,
260 fallbackBranch: string | null,
261 options?: { readonly remoteName?: string | null },
262 ) => Effect.Effect<GitPushResult, GitCommandError>;
263 readonly readRangeContext: (
264 cwd: string,
265 baseRef: string,
266 ) => Effect.Effect<GitRangeContext, GitCommandError>;
267 readonly getReviewDiffPreview: (
268 input: ReviewDiffPreviewInput,
269 ) => Effect.Effect<ReviewDiffPreviewResult, GitCommandError>;
270 readonly getReviewDiffFileContents: (
271 input: ReviewDiffFileContentsInput,
272 ) => Effect.Effect<ReviewDiffFileContentsResult, GitCommandError>;
273 readonly readConfigValue: (
274 cwd: string,
275 key: string,
276 ) => Effect.Effect<string | null, GitCommandError>;
277 readonly listRefs: (
278 input: VcsListRefsInput,
279 ) => Effect.Effect<VcsListRefsResult, GitCommandError>;
280 readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
281 readonly createWorktree: (
282 input: VcsCreateWorktreeInput,
283 ) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
284 readonly fetchPullRequestBranch: (
285 input: GitFetchPullRequestBranchInput,
286 ) => Effect.Effect<void, GitCommandError>;
287 /** Fetches `refs/pull/<n>/head` without writing a branch, for heads that exist nowhere else. */
288 readonly fetchPullRequestHeadCommit: (
289 input: GitFetchPullRequestHeadCommitInput,
290 ) => Effect.Effect<GitResolveCommitResult, GitCommandError>;
291 readonly resolveCommit: (
292 input: GitResolveCommitInput,
293 ) => Effect.Effect<GitResolveCommitResult, GitCommandError>;
294 /** Moves the branch checked out in `cwd` onto `targetCommit`, from inside that worktree. */
295 readonly refreshCheckedOutBranch: (
296 input: GitRefreshCheckedOutBranchInput,
297 ) => Effect.Effect<GitRefreshCheckedOutBranchResult, GitCommandError>;
298 readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
299 readonly resolvePrimaryRemoteName: (cwd: string) => Effect.Effect<string, GitCommandError>;
300 readonly resolveDefaultBranchName: (
301 cwd: string,
302 remoteName: string,
303 ) => Effect.Effect<string | null, GitCommandError>;
304 readonly fetchRemote: (input: GitFetchRemoteInput) => Effect.Effect<void, GitCommandError>;
305 readonly remoteExists: (input: GitRemoteExistsInput) => Effect.Effect<boolean, GitCommandError>;
306 readonly remoteBranchExists: (
307 input: GitRemoteBranchExistsInput,
308 ) => Effect.Effect<boolean, GitCommandError>;
309 readonly resolveRemoteTrackingCommit: (
310 input: GitResolveRemoteTrackingCommitInput,
311 ) => Effect.Effect<GitResolveRemoteTrackingCommitResult, GitCommandError>;
312 readonly fetchRemoteBranch: (
313 input: GitFetchRemoteBranchInput,
314 ) => Effect.Effect<void, GitCommandError>;
315 readonly fetchRemoteTrackingBranch: (
316 input: GitFetchRemoteTrackingBranchInput,
317 ) => Effect.Effect<void, GitCommandError>;
318 readonly setBranchUpstream: (
319 input: GitSetBranchUpstreamInput,
320 ) => Effect.Effect<void, GitCommandError>;
321 readonly removeWorktree: (
322 input: VcsRemoveWorktreeInput,
323 ) => Effect.Effect<void, GitCommandError>;
324 /** Drops worktree admin entries whose directory is already gone (`git worktree prune`). */
325 readonly pruneWorktrees: (input: {
326 readonly cwd: string;
327 }) => Effect.Effect<void, GitCommandError>;
328 readonly renameBranch: (
329 input: GitRenameBranchInput,
330 ) => Effect.Effect<GitRenameBranchResult, GitCommandError>;
331 readonly createRef: (
332 input: VcsCreateRefInput,
333 ) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
334 readonly switchRef: (
335 input: VcsSwitchRefInput,
336 ) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
337 readonly initRepo: (input: VcsInitInput) => Effect.Effect<void, GitCommandError>;
338 readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
339 }
340>()("t3/vcs/GitVcsDriver") {}
341​
342const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
343const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
344const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
345const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [
346 "-c",
347 "core.fsmonitor=false",
348 "-c",
349 "core.untrackedCache=false",
350] as const;
351​
352const nowFreshness = Effect.fn("GitVcsDriver.nowFreshness")(function* () {
353 const now = yield* DateTime.now;
354 return {
355 source: "live-local" as const,
356 observedAt: now,
357 expiresAt: Option.none(),
358 };
359});
360​
361function chunkPathsForGitCheckIgnore(relativePaths: ReadonlyArray<string>): string[][] {
362 const chunks: string[][] = [];
363 let chunk: string[] = [];
364 let chunkBytes = 0;
365​
366 for (const relativePath of relativePaths) {
367 const relativePathBytes = Buffer.byteLength(relativePath) + 1;
368 if (chunk.length > 0 && chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
369 chunks.push(chunk);
370 chunk = [];
371 chunkBytes = 0;
372 }
373​
374 chunk.push(relativePath);
375 chunkBytes += relativePathBytes;
376​
377 if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
378 chunks.push(chunk);
379 chunk = [];
380 chunkBytes = 0;
381 }
382 }
383​
384 if (chunk.length > 0) {
385 chunks.push(chunk);
386 }
387​
388 return chunks;
390​
391function parseGitRemoteVerboseOutput(
392 output: string,
393): Map<string, { url?: string; pushUrl?: string }> {
394 const remotes = new Map<string, { url?: string; pushUrl?: string }>();
395 for (const line of output.split("\n")) {
396 const trimmed = line.trim();
397 if (trimmed.length === 0) {
398 continue;
399 }
400​
401 const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed);
402 if (!match) {
403 continue;
404 }
405​
406 const name = match[1];
407 const url = match[2];
408 const direction = match[3];
409 if (!name || !url || !direction) {
410 continue;
411 }
412 const remote = remotes.get(name) ?? {};
413 if (direction === "fetch") {
414 remote.url = url;
415 } else {
416 remote.pushUrl = url;
417 }
418 remotes.set(name, remote);
419 }
420 return remotes;
422​
423const gitCommand = (
424 process: VcsProcess.VcsProcess["Service"],
425 operation: string,
426 cwd: string,
427 args: ReadonlyArray<string>,
428 options?: {
429 readonly stdin?: string;
430 readonly env?: NodeJS.ProcessEnv;
431 readonly allowNonZeroExit?: boolean;
432 readonly timeoutMs?: number;
433 readonly maxOutputBytes?: number;
434 readonly outputMode?: VcsProcess.VcsProcessInput["outputMode"];
435 readonly appendTruncationMarker?: boolean;
436 },
437) =>
438 process.run({
439 operation,
440 command: "git",
441 args: ["-C", cwd, ...args],
442 cwd,
443 spawnCwd: globalThis.process.cwd(),
444 ...(options?.stdin !== undefined ? { stdin: options.stdin } : {}),
445 ...(options?.env !== undefined ? { env: options.env } : {}),
446 ...(options?.allowNonZeroExit !== undefined
447 ? { allowNonZeroExit: options.allowNonZeroExit }
448 : {}),
449 ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
450 ...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
451 ...(options?.outputMode !== undefined ? { outputMode: options.outputMode } : {}),
452 ...(options?.appendTruncationMarker !== undefined
453 ? { appendTruncationMarker: options.appendTruncationMarker }
454 : {}),
455 });
456​
457export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* () {
458 const fileSystem = yield* FileSystem.FileSystem;
459 const path = yield* Path.Path;
460 const vcsProcess = yield* VcsProcess.VcsProcess;
461 const capabilities = {
462 kind: "git" as const,
463 supportsWorktrees: true,
464 supportsBookmarks: false,
465 supportsAtomicSnapshot: false,
466 supportsPushDefaultRemote: true,
467 ignoreClassifier: "native" as const,
468 };
469​
470 const isInsideWorkTree: VcsDriver.VcsDriver["Service"]["isInsideWorkTree"] = (cwd) =>
471 gitCommand(
472 vcsProcess,
473 "GitVcsDriver.isInsideWorkTree",
474 cwd,
475 ["rev-parse", "--is-inside-work-tree"],
476 {
477 allowNonZeroExit: true,
478 timeoutMs: 5_000,
479 maxOutputBytes: 4_096,
480 },
481 ).pipe(Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"));
482​
483 const execute: VcsDriver.VcsDriver["Service"]["execute"] = (input) =>
484 gitCommand(vcsProcess, input.operation, input.cwd, input.args, {
485 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
486 ...(input.env !== undefined ? { env: input.env } : {}),
487 ...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}),
488 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
489 ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
490 ...(input.outputMode !== undefined ? { outputMode: input.outputMode } : {}),
491 ...(input.appendTruncationMarker !== undefined
492 ? { appendTruncationMarker: input.appendTruncationMarker }
493 : {}),
494 });
495​
496 const detectRepository: VcsDriver.VcsDriver["Service"]["detectRepository"] = Effect.fn(
497 "detectRepository",
498 )(function* (cwd) {
499 if (!(yield* isInsideWorkTree(cwd))) {
500 return null;
501 }
502​
503 const root = yield* gitCommand(vcsProcess, "GitVcsDriver.detectRepository.root", cwd, [
504 "rev-parse",
505 "--show-toplevel",
506 ]);
507 const gitCommonDir = yield* gitCommand(
508 vcsProcess,
509 "GitVcsDriver.detectRepository.commonDir",
510 cwd,
511 ["rev-parse", "--git-common-dir"],
512 ).pipe(Effect.orElseSucceed(() => null));
513​
514 return {
515 kind: "git" as const,
516 rootPath: root.stdout.trim(),
517 metadataPath: gitCommonDir?.stdout.trim() || null,
518 freshness: yield* nowFreshness(),
519 };
520 });
521​
522 const listWorkspaceFiles: VcsDriver.VcsDriver["Service"]["listWorkspaceFiles"] = (cwd) =>
523 gitCommand(
524 vcsProcess,
525 "GitVcsDriver.listWorkspaceFiles",
526 cwd,
527 [
528 ...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
529 "ls-files",
530 "--cached",
531 "--others",
532 "--exclude-standard",
533 "-z",
534 ],
535 {
536 allowNonZeroExit: true,
537 timeoutMs: 20_000,
538 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
539 appendTruncationMarker: true,
540 },
541 ).pipe(
542 Effect.flatMap((result) =>
543 result.exitCode === 0
544 ? Effect.gen(function* () {
545 const freshness = yield* nowFreshness();
546 return {
547 paths: splitNullSeparatedGitStdoutPaths(result),
548 truncated: result.stdoutTruncated,
549 freshness,
550 };
551 })
552 : Effect.fail(
553 new VcsProcessExitError({
554 operation: "GitVcsDriver.listWorkspaceFiles",
555 command: "git ls-files",
556 cwd,
557 exitCode: result.exitCode,
558 detail: result.stderr.trim() || "git ls-files failed",
559 }),
560 ),
561 ),
562 );
563​
564 const listRemotes: VcsDriver.VcsDriver["Service"]["listRemotes"] = Effect.fn("listRemotes")(
565 function* (cwd) {
566 const result = yield* gitCommand(
567 vcsProcess,
568 "GitVcsDriver.listRemotes",
569 cwd,
570 ["remote", "-v"],
571 {
572 allowNonZeroExit: true,
573 timeoutMs: 5_000,
574 maxOutputBytes: 64 * 1024,
575 },
576 );
577​
578 if (result.exitCode !== 0) {
579 return yield* new VcsProcessExitError({
580 operation: "GitVcsDriver.listRemotes",
581 command: "git remote -v",
582 cwd,
583 exitCode: result.exitCode,
584 detail: result.stderr.trim() || "git remote -v failed",
585 });
586 }
587​
588 const parsed = parseGitRemoteVerboseOutput(result.stdout);
589 const remotes = Array.from(parsed.entries()).flatMap(([name, remote]) => {
590 if (!remote.url) {
591 return [];
592 }
593 return [
594 {
595 name,
596 url: remote.url,
597 pushUrl: remote.pushUrl ? Option.some(remote.pushUrl) : Option.none(),
598 isPrimary: name === "origin",
599 },
600 ];
601 });
602​
603 return {
604 remotes,
605 freshness: yield* nowFreshness(),
606 };
607 },
608 );
609​
610 const filterIgnoredPaths: VcsDriver.VcsDriver["Service"]["filterIgnoredPaths"] = Effect.fn(
611 "filterIgnoredPaths",
612 )(function* (cwd, relativePaths) {
613 if (relativePaths.length === 0) {
614 return relativePaths;
615 }
616​
617 const ignoredPaths = new Set<string>();
618 const chunks = chunkPathsForGitCheckIgnore(relativePaths);
619​
620 for (const chunk of chunks) {
621 const result = yield* gitCommand(
622 vcsProcess,
623 "GitVcsDriver.filterIgnoredPaths",
624 cwd,
625 [...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
626 {
627 stdin: `${chunk.join("\0")}\0`,
628 allowNonZeroExit: true,
629 timeoutMs: 20_000,
630 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
631 appendTruncationMarker: true,
632 },
633 );
634​
635 if (result.exitCode !== 0 && result.exitCode !== 1) {
636 return yield* new VcsProcessExitError({
637 operation: "GitVcsDriver.filterIgnoredPaths",
638 command: "git check-ignore",
639 cwd,
640 exitCode: result.exitCode,
641 detail: result.stderr.trim() || "git check-ignore failed",
642 });
643 }
644​
645 for (const ignoredPath of splitNullSeparatedGitStdoutPaths(result)) {
646 ignoredPaths.add(ignoredPath);
647 }
648 }
649​
650 if (ignoredPaths.size === 0) {
651 return relativePaths;
652 }
653​
654 return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
655 });
656​
657 const initRepository: VcsDriver.VcsDriver["Service"]["initRepository"] = (input) =>
658 gitCommand(vcsProcess, "GitVcsDriver.initRepository", input.cwd, ["init"], {
659 timeoutMs: 10_000,
660 maxOutputBytes: 64 * 1024,
661 }).pipe(Effect.asVoid);
662​
663 const resolveHeadCommit = (cwd: string) =>
664 execute({
665 operation: "GitVcsDriver.checkpoints.resolveHeadCommit",
666 cwd,
667 args: ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
668 allowNonZeroExit: true,
669 }).pipe(
670 Effect.map((result) => {
671 if (result.exitCode !== 0) {
672 return null;
673 }
674 const commit = result.stdout.trim();
675 return commit.length > 0 ? commit : null;
676 }),
677 );
678​
679 const hasHeadCommit = (cwd: string) =>
680 execute({
681 operation: "GitVcsDriver.checkpoints.hasHeadCommit",
682 cwd,
683 args: ["rev-parse", "--verify", "HEAD"],
684 allowNonZeroExit: true,
685 }).pipe(Effect.map((result) => result.exitCode === 0));
686​
687 const resolveCheckpointCommit = (cwd: string, checkpointRef: string) =>
688 execute({
689 operation: "GitVcsDriver.checkpoints.resolveCheckpointCommit",
690 cwd,
691 args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`],
692 allowNonZeroExit: true,
693 }).pipe(
694 Effect.map((result) => {
695 if (result.exitCode !== 0) {
696 return null;
697 }
698 const commit = result.stdout.trim();
699 return commit.length > 0 ? commit : null;
700 }),
701 );
702​
703 const resolveGitCommonDir = (cwd: string) =>
704 Effect.gen(function* () {
705 const result = yield* execute({
706 operation: "GitVcsDriver.checkpoints.resolveGitCommonDir",
707 cwd,
708 args: ["rev-parse", "--git-common-dir"],
709 });
710 const gitCommonDir = result.stdout.trim();
711 return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
712 });
713​
714 const checkpoints: VcsDriver.VcsCheckpointOps = {
715 captureCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureCheckpoint")(function* (input) {
716 const operation = "GitVcsDriver.checkpoints.captureCheckpoint";
717 const gitCommonDir = yield* resolveGitCommonDir(input.cwd);
718 const tempIndexPath = path.join(
719 gitCommonDir,
720 `t3-checkpoint-index-${NodeCrypto.randomUUID()}`,
721 );
722 const commitEnv: NodeJS.ProcessEnv = {
723 ...process.env,
724 GIT_INDEX_FILE: tempIndexPath,
725 GIT_AUTHOR_NAME: "T3 Code",
726 GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com",
727 GIT_COMMITTER_NAME: "T3 Code",
728 GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com",
729 };
730​
731 const cleanupTempIndex = fileSystem
732 .remove(tempIndexPath, { force: true })
733 .pipe(Effect.ignore);
734​
735 yield* Effect.gen(function* () {
736 const headExists = yield* hasHeadCommit(input.cwd);
737 if (headExists) {
738 yield* execute({
739 operation,
740 cwd: input.cwd,
741 args: ["read-tree", "HEAD"],
742 env: commitEnv,
743 });
744 }
745​
746 yield* execute({
747 operation,
748 cwd: input.cwd,
749 args: ["add", "-A", "--", "."],
750 env: commitEnv,
751 });
752​
753 const writeTreeResult = yield* execute({
754 operation,
755 cwd: input.cwd,
756 args: ["write-tree"],
757 env: commitEnv,
758 });
759 const treeOid = writeTreeResult.stdout.trim();
760 if (treeOid.length === 0) {
761 return yield* new VcsProcessExitError({
762 operation,
763 command: "git write-tree",
764 cwd: input.cwd,
765 exitCode: 0,
766 detail: "git write-tree returned an empty tree oid.",
767 });
768 }
769​
770 const message = `t3 checkpoint ref=${input.checkpointRef}`;
771 const commitTreeResult = yield* execute({
772 operation,
773 cwd: input.cwd,
774 args: ["commit-tree", treeOid, "-m", message],
775 env: commitEnv,
776 });
777 const commitOid = commitTreeResult.stdout.trim();
778 if (commitOid.length === 0) {
779 return yield* new VcsProcessExitError({
780 operation,
781 command: "git commit-tree",
782 cwd: input.cwd,
783 exitCode: 0,
784 detail: "git commit-tree returned an empty commit oid.",
785 });
786 }
787​
788 yield* execute({
789 operation,
790 cwd: input.cwd,
791 args: ["update-ref", input.checkpointRef, commitOid],
792 });
793 }).pipe(Effect.ensuring(cleanupTempIndex));
794 }),
795​
796 hasCheckpointRef: (input) =>
797 resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
798 Effect.map((commit) => commit !== null),
799 ),
800​
801 restoreCheckpoint: Effect.fn("GitVcsDriver.checkpoints.restoreCheckpoint")(function* (input) {
802 const operation = "GitVcsDriver.checkpoints.restoreCheckpoint";
803​
804 let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
805​
806 if (!commitOid && input.fallbackToHead === true) {
807 commitOid = yield* resolveHeadCommit(input.cwd);
808 }
809​
810 if (!commitOid) {
811 return false;
812 }
813​
814 yield* execute({
815 operation,
816 cwd: input.cwd,
817 args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
818 });
819 yield* execute({
820 operation,
821 cwd: input.cwd,
822 args: ["clean", "-fd", "--", "."],
823 });
824​
825 const headExists = yield* hasHeadCommit(input.cwd);
826 if (headExists) {
827 yield* execute({
828 operation,
829 cwd: input.cwd,
830 args: ["reset", "--quiet", "--", "."],
831 });
832 }
833​
834 return true;
835 }),
836​
837 diffCheckpoints: Effect.fn("GitVcsDriver.checkpoints.diffCheckpoints")(function* (input) {
838 const operation = "GitVcsDriver.checkpoints.diffCheckpoints";
839 yield* Effect.annotateCurrentSpan({
840 "checkpoint.cwd": input.cwd,
841 "checkpoint.from_ref": input.fromCheckpointRef,
842 "checkpoint.to_ref": input.toCheckpointRef,
843 "checkpoint.ignore_whitespace": input.ignoreWhitespace,
844 "checkpoint.format": input.format ?? "patch",
845 "checkpoint.fallback_from_to_head": input.fallbackFromToHead,
846 });
847​
848 let fromRevision: string = input.fromCheckpointRef;
849 if (input.fallbackFromToHead === true) {
850 const resolvedFromCommit = yield* resolveCheckpointCommit(
851 input.cwd,
852 input.fromCheckpointRef,
853 );
854 if (resolvedFromCommit) {
855 fromRevision = resolvedFromCommit;
856 } else {
857 const headCommit = yield* resolveHeadCommit(input.cwd);
858 if (!headCommit) {
859 return yield* new VcsProcessExitError({
860 operation,
861 command: "git diff",
862 cwd: input.cwd,
863 exitCode: 1,
864 detail: "Checkpoint ref is unavailable for diff operation.",
865 });
866 }
867 fromRevision = headCommit;
868 }
869 }
870​
871 const result = yield* execute({
872 operation,
873 cwd: input.cwd,
874 args: [
875 "diff",
876 ...(input.format === "numstat" ? ["--numstat", "-z"] : ["--patch"]),
877 "--no-color",
878 "--no-ext-diff",
879 "--no-textconv",
880 ...PATCH_RENDER_PREFIX_ARGS,
881 ...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
882 `${fromRevision}^{commit}`,
883 `${input.toCheckpointRef}^{commit}`,
884 ],
885 allowNonZeroExit: true,
886 maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
887 outputMode: input.format === "numstat" ? "error" : "truncate",
888 });
889​
890 if (result.exitCode !== 0) {
891 return yield* new VcsProcessExitError({
892 operation,
893 command: "git diff",
894 cwd: input.cwd,
895 exitCode: result.exitCode,
896 detail: result.stderr.trim() || "Checkpoint ref is unavailable for diff operation.",
897 });
898 }
899​
900 return result.stdout;
901 }),
902​
903 deleteCheckpointRefs: Effect.fn("GitVcsDriver.checkpoints.deleteCheckpointRefs")(
904 function* (input) {
905 yield* Effect.forEach(
906 input.checkpointRefs,
907 (checkpointRef) =>
908 execute({
909 operation: "GitVcsDriver.checkpoints.deleteCheckpointRefs",
910 cwd: input.cwd,
911 args: ["update-ref", "-d", checkpointRef],
912 allowNonZeroExit: true,
913 }),
914 { discard: true },
915 );
916 },
917 ),
918 };
919​
920 return {
921 capabilities,
922 execute,
923 checkpoints,
924 detectRepository,
925 isInsideWorkTree,
926 listWorkspaceFiles,
927 listRemotes,
928 filterIgnoredPaths,
929 initRepository,
930 };
931});
932​
933export const makeVcsDriver = Effect.gen(function* () {
934 const driver = yield* makeVcsDriverShape();
935 return VcsDriver.VcsDriver.of(driver);
936});
937​
938export const make = Effect.gen(function* () {
939 const git = yield* makeGitVcsDriverCore();
940 return GitVcsDriver.of(git);
941});
942​
943export const vcsLayer = Layer.effect(VcsDriver.VcsDriver, makeVcsDriver);
944export const layer = Layer.effect(GitVcsDriver, make);