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

GitVcsDriver.ts

938 lines28.3 KB

1import * as NodeCrypto from "node:crypto";
2​
3import * as Context from "effect/Context";
4import * as DateTime from "effect/DateTime";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as Path from "effect/Path";
10import { ChildProcessSpawner } from "effect/unstable/process";
11​
12import {
13 GitCommandError,
14 VcsProcessExitError,
15 type VcsSwitchRefInput,
16 type VcsSwitchRefResult,
17 type VcsCreateRefInput,
18 type VcsCreateRefResult,
19 type VcsCreateWorktreeInput,
20 type VcsCreateWorktreeResult,
21 type ReviewDiffPreviewInput,
22 type ReviewDiffPreviewResult,
23 type ReviewDiffFileContentsInput,
24 type ReviewDiffFileContentsResult,
25 type VcsInitInput,
26 type VcsListRefsInput,
27 type VcsListRefsResult,
28 type VcsPullResult,
29 type VcsRemoveWorktreeInput,
30 type VcsStatusInput,
31 type VcsStatusResult,
32} from "@t3tools/contracts";
33import { 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;
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 splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
351 const parts = input.split("\0");
352 if (parts.length === 0) return [];
353​
354 if (truncated && parts[parts.length - 1]?.length) {
355 parts.pop();
356 }
357​
358 return parts.filter((value) => value.length > 0);
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 appendTruncationMarker?: boolean;
435 },
436) =>
437 process.run({
438 operation,
439 command: "git",
440 args: ["-C", cwd, ...args],
441 cwd,
442 spawnCwd: globalThis.process.cwd(),
443 ...(options?.stdin !== undefined ? { stdin: options.stdin } : {}),
444 ...(options?.env !== undefined ? { env: options.env } : {}),
445 ...(options?.allowNonZeroExit !== undefined
446 ? { allowNonZeroExit: options.allowNonZeroExit }
447 : {}),
448 ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
449 ...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
450 ...(options?.appendTruncationMarker !== undefined
451 ? { appendTruncationMarker: options.appendTruncationMarker }
452 : {}),
453 });
454​
455export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* () {
456 const fileSystem = yield* FileSystem.FileSystem;
457 const path = yield* Path.Path;
458 const vcsProcess = yield* VcsProcess.VcsProcess;
459 const capabilities = {
460 kind: "git" as const,
461 supportsWorktrees: true,
462 supportsBookmarks: false,
463 supportsAtomicSnapshot: false,
464 supportsPushDefaultRemote: true,
465 ignoreClassifier: "native" as const,
466 };
467​
468 const isInsideWorkTree: VcsDriver.VcsDriver["Service"]["isInsideWorkTree"] = (cwd) =>
469 gitCommand(
470 vcsProcess,
471 "GitVcsDriver.isInsideWorkTree",
472 cwd,
473 ["rev-parse", "--is-inside-work-tree"],
474 {
475 allowNonZeroExit: true,
476 timeoutMs: 5_000,
477 maxOutputBytes: 4_096,
478 },
479 ).pipe(Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"));
480​
481 const execute: VcsDriver.VcsDriver["Service"]["execute"] = (input) =>
482 gitCommand(vcsProcess, input.operation, input.cwd, input.args, {
483 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
484 ...(input.env !== undefined ? { env: input.env } : {}),
485 ...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}),
486 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
487 ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
488 ...(input.appendTruncationMarker !== undefined
489 ? { appendTruncationMarker: input.appendTruncationMarker }
490 : {}),
491 });
492​
493 const detectRepository: VcsDriver.VcsDriver["Service"]["detectRepository"] = Effect.fn(
494 "detectRepository",
495 )(function* (cwd) {
496 if (!(yield* isInsideWorkTree(cwd))) {
497 return null;
498 }
499​
500 const root = yield* gitCommand(vcsProcess, "GitVcsDriver.detectRepository.root", cwd, [
501 "rev-parse",
502 "--show-toplevel",
503 ]);
504 const gitCommonDir = yield* gitCommand(
505 vcsProcess,
506 "GitVcsDriver.detectRepository.commonDir",
507 cwd,
508 ["rev-parse", "--git-common-dir"],
509 ).pipe(Effect.orElseSucceed(() => null));
510​
511 return {
512 kind: "git" as const,
513 rootPath: root.stdout.trim(),
514 metadataPath: gitCommonDir?.stdout.trim() || null,
515 freshness: yield* nowFreshness(),
516 };
517 });
518​
519 const listWorkspaceFiles: VcsDriver.VcsDriver["Service"]["listWorkspaceFiles"] = (cwd) =>
520 gitCommand(
521 vcsProcess,
522 "GitVcsDriver.listWorkspaceFiles",
523 cwd,
524 [
525 ...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
526 "ls-files",
527 "--cached",
528 "--others",
529 "--exclude-standard",
530 "-z",
531 ],
532 {
533 allowNonZeroExit: true,
534 timeoutMs: 20_000,
535 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
536 appendTruncationMarker: true,
537 },
538 ).pipe(
539 Effect.flatMap((result) =>
540 result.exitCode === 0
541 ? Effect.gen(function* () {
542 const freshness = yield* nowFreshness();
543 return {
544 paths: splitNullSeparatedPaths(result.stdout, result.stdoutTruncated),
545 truncated: result.stdoutTruncated,
546 freshness,
547 };
548 })
549 : Effect.fail(
550 new VcsProcessExitError({
551 operation: "GitVcsDriver.listWorkspaceFiles",
552 command: "git ls-files",
553 cwd,
554 exitCode: result.exitCode,
555 detail: result.stderr.trim() || "git ls-files failed",
556 }),
557 ),
558 ),
559 );
560​
561 const listRemotes: VcsDriver.VcsDriver["Service"]["listRemotes"] = Effect.fn("listRemotes")(
562 function* (cwd) {
563 const result = yield* gitCommand(
564 vcsProcess,
565 "GitVcsDriver.listRemotes",
566 cwd,
567 ["remote", "-v"],
568 {
569 allowNonZeroExit: true,
570 timeoutMs: 5_000,
571 maxOutputBytes: 64 * 1024,
572 },
573 );
574​
575 if (result.exitCode !== 0) {
576 return yield* new VcsProcessExitError({
577 operation: "GitVcsDriver.listRemotes",
578 command: "git remote -v",
579 cwd,
580 exitCode: result.exitCode,
581 detail: result.stderr.trim() || "git remote -v failed",
582 });
583 }
584​
585 const parsed = parseGitRemoteVerboseOutput(result.stdout);
586 const remotes = Array.from(parsed.entries()).flatMap(([name, remote]) => {
587 if (!remote.url) {
588 return [];
589 }
590 return [
591 {
592 name,
593 url: remote.url,
594 pushUrl: remote.pushUrl ? Option.some(remote.pushUrl) : Option.none(),
595 isPrimary: name === "origin",
596 },
597 ];
598 });
599​
600 return {
601 remotes,
602 freshness: yield* nowFreshness(),
603 };
604 },
605 );
606​
607 const filterIgnoredPaths: VcsDriver.VcsDriver["Service"]["filterIgnoredPaths"] = Effect.fn(
608 "filterIgnoredPaths",
609 )(function* (cwd, relativePaths) {
610 if (relativePaths.length === 0) {
611 return relativePaths;
612 }
613​
614 const ignoredPaths = new Set<string>();
615 const chunks = chunkPathsForGitCheckIgnore(relativePaths);
616​
617 for (const chunk of chunks) {
618 const result = yield* gitCommand(
619 vcsProcess,
620 "GitVcsDriver.filterIgnoredPaths",
621 cwd,
622 [...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
623 {
624 stdin: `${chunk.join("\0")}\0`,
625 allowNonZeroExit: true,
626 timeoutMs: 20_000,
627 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
628 appendTruncationMarker: true,
629 },
630 );
631​
632 if (result.exitCode !== 0 && result.exitCode !== 1) {
633 return yield* new VcsProcessExitError({
634 operation: "GitVcsDriver.filterIgnoredPaths",
635 command: "git check-ignore",
636 cwd,
637 exitCode: result.exitCode,
638 detail: result.stderr.trim() || "git check-ignore failed",
639 });
640 }
641​
642 for (const ignoredPath of splitNullSeparatedPaths(result.stdout, result.stdoutTruncated)) {
643 ignoredPaths.add(ignoredPath);
644 }
645 }
646​
647 if (ignoredPaths.size === 0) {
648 return relativePaths;
649 }
650​
651 return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
652 });
653​
654 const initRepository: VcsDriver.VcsDriver["Service"]["initRepository"] = (input) =>
655 gitCommand(vcsProcess, "GitVcsDriver.initRepository", input.cwd, ["init"], {
656 timeoutMs: 10_000,
657 maxOutputBytes: 64 * 1024,
658 }).pipe(Effect.asVoid);
659​
660 const resolveHeadCommit = (cwd: string) =>
661 execute({
662 operation: "GitVcsDriver.checkpoints.resolveHeadCommit",
663 cwd,
664 args: ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
665 allowNonZeroExit: true,
666 }).pipe(
667 Effect.map((result) => {
668 if (result.exitCode !== 0) {
669 return null;
670 }
671 const commit = result.stdout.trim();
672 return commit.length > 0 ? commit : null;
673 }),
674 );
675​
676 const hasHeadCommit = (cwd: string) =>
677 execute({
678 operation: "GitVcsDriver.checkpoints.hasHeadCommit",
679 cwd,
680 args: ["rev-parse", "--verify", "HEAD"],
681 allowNonZeroExit: true,
682 }).pipe(Effect.map((result) => result.exitCode === 0));
683​
684 const resolveCheckpointCommit = (cwd: string, checkpointRef: string) =>
685 execute({
686 operation: "GitVcsDriver.checkpoints.resolveCheckpointCommit",
687 cwd,
688 args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`],
689 allowNonZeroExit: true,
690 }).pipe(
691 Effect.map((result) => {
692 if (result.exitCode !== 0) {
693 return null;
694 }
695 const commit = result.stdout.trim();
696 return commit.length > 0 ? commit : null;
697 }),
698 );
699​
700 const resolveGitCommonDir = (cwd: string) =>
701 Effect.gen(function* () {
702 const result = yield* execute({
703 operation: "GitVcsDriver.checkpoints.resolveGitCommonDir",
704 cwd,
705 args: ["rev-parse", "--git-common-dir"],
706 });
707 const gitCommonDir = result.stdout.trim();
708 return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
709 });
710​
711 const checkpoints: VcsDriver.VcsCheckpointOps = {
712 captureCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureCheckpoint")(function* (input) {
713 const operation = "GitVcsDriver.checkpoints.captureCheckpoint";
714 const gitCommonDir = yield* resolveGitCommonDir(input.cwd);
715 const tempIndexPath = path.join(
716 gitCommonDir,
717 `t3-checkpoint-index-${NodeCrypto.randomUUID()}`,
718 );
719 const commitEnv: NodeJS.ProcessEnv = {
720 ...process.env,
721 GIT_INDEX_FILE: tempIndexPath,
722 GIT_AUTHOR_NAME: "T3 Code",
723 GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com",
724 GIT_COMMITTER_NAME: "T3 Code",
725 GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com",
726 };
727​
728 const cleanupTempIndex = fileSystem
729 .remove(tempIndexPath, { force: true })
730 .pipe(Effect.ignore);
731​
732 yield* Effect.gen(function* () {
733 const headExists = yield* hasHeadCommit(input.cwd);
734 if (headExists) {
735 yield* execute({
736 operation,
737 cwd: input.cwd,
738 args: ["read-tree", "HEAD"],
739 env: commitEnv,
740 });
741 }
742​
743 yield* execute({
744 operation,
745 cwd: input.cwd,
746 args: ["add", "-A", "--", "."],
747 env: commitEnv,
748 });
749​
750 const writeTreeResult = yield* execute({
751 operation,
752 cwd: input.cwd,
753 args: ["write-tree"],
754 env: commitEnv,
755 });
756 const treeOid = writeTreeResult.stdout.trim();
757 if (treeOid.length === 0) {
758 return yield* new VcsProcessExitError({
759 operation,
760 command: "git write-tree",
761 cwd: input.cwd,
762 exitCode: 0,
763 detail: "git write-tree returned an empty tree oid.",
764 });
765 }
766​
767 const message = `t3 checkpoint ref=${input.checkpointRef}`;
768 const commitTreeResult = yield* execute({
769 operation,
770 cwd: input.cwd,
771 args: ["commit-tree", treeOid, "-m", message],
772 env: commitEnv,
773 });
774 const commitOid = commitTreeResult.stdout.trim();
775 if (commitOid.length === 0) {
776 return yield* new VcsProcessExitError({
777 operation,
778 command: "git commit-tree",
779 cwd: input.cwd,
780 exitCode: 0,
781 detail: "git commit-tree returned an empty commit oid.",
782 });
783 }
784​
785 yield* execute({
786 operation,
787 cwd: input.cwd,
788 args: ["update-ref", input.checkpointRef, commitOid],
789 });
790 }).pipe(Effect.ensuring(cleanupTempIndex));
791 }),
792​
793 hasCheckpointRef: (input) =>
794 resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
795 Effect.map((commit) => commit !== null),
796 ),
797​
798 restoreCheckpoint: Effect.fn("GitVcsDriver.checkpoints.restoreCheckpoint")(function* (input) {
799 const operation = "GitVcsDriver.checkpoints.restoreCheckpoint";
800​
801 let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
802​
803 if (!commitOid && input.fallbackToHead === true) {
804 commitOid = yield* resolveHeadCommit(input.cwd);
805 }
806​
807 if (!commitOid) {
808 return false;
809 }
810​
811 yield* execute({
812 operation,
813 cwd: input.cwd,
814 args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
815 });
816 yield* execute({
817 operation,
818 cwd: input.cwd,
819 args: ["clean", "-fd", "--", "."],
820 });
821​
822 const headExists = yield* hasHeadCommit(input.cwd);
823 if (headExists) {
824 yield* execute({
825 operation,
826 cwd: input.cwd,
827 args: ["reset", "--quiet", "--", "."],
828 });
829 }
830​
831 return true;
832 }),
833​
834 diffCheckpoints: Effect.fn("GitVcsDriver.checkpoints.diffCheckpoints")(function* (input) {
835 const operation = "GitVcsDriver.checkpoints.diffCheckpoints";
836 yield* Effect.annotateCurrentSpan({
837 "checkpoint.cwd": input.cwd,
838 "checkpoint.from_ref": input.fromCheckpointRef,
839 "checkpoint.to_ref": input.toCheckpointRef,
840 "checkpoint.ignore_whitespace": input.ignoreWhitespace,
841 "checkpoint.fallback_from_to_head": input.fallbackFromToHead,
842 });
843​
844 let fromRevision: string = input.fromCheckpointRef;
845 if (input.fallbackFromToHead === true) {
846 const resolvedFromCommit = yield* resolveCheckpointCommit(
847 input.cwd,
848 input.fromCheckpointRef,
849 );
850 if (resolvedFromCommit) {
851 fromRevision = resolvedFromCommit;
852 } else {
853 const headCommit = yield* resolveHeadCommit(input.cwd);
854 if (!headCommit) {
855 return yield* new VcsProcessExitError({
856 operation,
857 command: "git diff",
858 cwd: input.cwd,
859 exitCode: 1,
860 detail: "Checkpoint ref is unavailable for diff operation.",
861 });
862 }
863 fromRevision = headCommit;
864 }
865 }
866​
867 const result = yield* execute({
868 operation,
869 cwd: input.cwd,
870 args: [
871 "diff",
872 "--patch",
873 "--no-color",
874 "--no-ext-diff",
875 "--no-textconv",
876 ...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
877 `${fromRevision}^{commit}`,
878 `${input.toCheckpointRef}^{commit}`,
879 ],
880 allowNonZeroExit: true,
881 maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
882 });
883​
884 if (result.exitCode !== 0) {
885 return yield* new VcsProcessExitError({
886 operation,
887 command: "git diff",
888 cwd: input.cwd,
889 exitCode: result.exitCode,
890 detail: result.stderr.trim() || "Checkpoint ref is unavailable for diff operation.",
891 });
892 }
893​
894 return result.stdout;
895 }),
896​
897 deleteCheckpointRefs: Effect.fn("GitVcsDriver.checkpoints.deleteCheckpointRefs")(
898 function* (input) {
899 yield* Effect.forEach(
900 input.checkpointRefs,
901 (checkpointRef) =>
902 execute({
903 operation: "GitVcsDriver.checkpoints.deleteCheckpointRefs",
904 cwd: input.cwd,
905 args: ["update-ref", "-d", checkpointRef],
906 allowNonZeroExit: true,
907 }),
908 { discard: true },
909 );
910 },
911 ),
912 };
913​
914 return {
915 capabilities,
916 execute,
917 checkpoints,
918 detectRepository,
919 isInsideWorkTree,
920 listWorkspaceFiles,
921 listRemotes,
922 filterIgnoredPaths,
923 initRepository,
924 };
925});
926​
927export const makeVcsDriver = Effect.gen(function* () {
928 const driver = yield* makeVcsDriverShape();
929 return VcsDriver.VcsDriver.of(driver);
930});
931​
932export const make = Effect.gen(function* () {
933 const git = yield* makeGitVcsDriverCore();
934 return GitVcsDriver.of(git);
935});
936​
937export const vcsLayer = Layer.effect(VcsDriver.VcsDriver, makeVcsDriver);
938export const layer = Layer.effect(GitVcsDriver, make);