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

GitVcsDriver.ts

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