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

GitVcsDriver.ts

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