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

GitVcsDriver.ts

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