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

GitVcsDriver.ts

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