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

GitVcsDriver.ts

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