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

GitVcsDriver.ts

1,016 lines31.5 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 {
34 makeGitVcsDriverCore,
35 PATCH_RENDER_PREFIX_ARGS,
36 splitNullSeparatedGitStdoutPaths,
37} from "./GitVcsDriverCore.ts";
38import * as VcsDriver from "./VcsDriver.ts";
39import * as VcsProcess from "./VcsProcess.ts";
40​
41export interface ExecuteGitInput {
42 readonly operation: string;
43 readonly cwd: string;
44 readonly args: ReadonlyArray<string>;
45 readonly stdin?: string;
46 readonly env?: NodeJS.ProcessEnv;
47 readonly allowNonZeroExit?: boolean;
48 readonly timeoutMs?: number | null;
49 readonly maxOutputBytes?: number;
50 readonly appendTruncationMarker?: boolean;
51 readonly progress?: ExecuteGitProgress;
53​
54export interface ExecuteGitResult {
55 readonly exitCode: ChildProcessSpawner.ExitCode;
56 readonly stdout: string;
57 readonly stderr: string;
58 readonly stdoutTruncated: boolean;
59 readonly stderrTruncated: boolean;
61​
62export interface GitStatusDetails {
63 isRepo: boolean;
64 sourceControlProvider?: VcsStatusResult["sourceControlProvider"];
65 hasOriginRemote: boolean;
66 isDefaultBranch: boolean;
67 branch: string | null;
68 upstreamRef: string | null;
69 hasWorkingTreeChanges: boolean;
70 workingTree: VcsStatusResult["workingTree"];
71 hasUpstream: boolean;
72 aheadCount: number;
73 behindCount: number;
74 aheadOfDefaultCount: number;
76​
77export interface GitRemoteStatusDetails {
78 isRepo: boolean;
79 defaultBranch: string | null;
80 isDefaultBranch: boolean;
81 branch: string | null;
82 upstreamRef: string | null;
83 hasUpstream: boolean;
84 aheadCount: number;
85 behindCount: number;
86 aheadOfDefaultCount: number;
88​
89export interface GitPreparedCommitContext {
90 stagedSummary: string;
91 stagedPatch: string;
93​
94export interface ExecuteGitProgress {
95 readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;
96 readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;
97 readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
98 readonly onHookFinished?: (input: {
99 hookName: string;
100 exitCode: number | null;
101 durationMs: number | null;
102 }) => Effect.Effect<void, never>;
104​
105/**
106 * Progress callbacks for `createWorktree`. Git prints `Updating files: 78% (2104/2700)`
107 * to stderr during checkout, and `Submodule path 'x': checked out` during
108 * submodule init. The tracker uses these to drive the worktree setup card.
109 */
110export interface CreateWorktreeProgress {
111 /**
112 * Fires once `git worktree add` has created and registered the directory,
113 * before the (possibly long) submodule step. Git refuses an existing path,
114 * so a path reported here belongs to this call and is safe to remove on
115 * cancel.
116 */
117 readonly onWorktreeClaimed?: (path: string) => Effect.Effect<void, never>;
118 readonly onCheckoutProgress?: (input: {
119 percent: number;
120 completed: number;
121 total: number;
122 }) => Effect.Effect<void, never>;
123 readonly onSubmodulesStarted?: () => Effect.Effect<void, never>;
124 readonly onSubmoduleLine?: (line: string) => Effect.Effect<void, never>;
125 readonly onSubmodulesFinished?: (input: {
126 ok: boolean;
127 detail: string | null;
128 }) => Effect.Effect<void, never>;
130​
131export interface CreateWorktreeOptions {
132 readonly progress?: CreateWorktreeProgress;
134​
135export interface GitCommitProgress {
136 readonly onOutputLine?: (input: {
137 stream: "stdout" | "stderr";
138 text: string;
139 }) => Effect.Effect<void, never>;
140 readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
141 readonly onHookFinished?: (input: {
142 hookName: string;
143 exitCode: number | null;
144 durationMs: number | null;
145 }) => Effect.Effect<void, never>;
147​
148export interface GitCommitOptions {
149 readonly timeoutMs?: number;
150 readonly progress?: GitCommitProgress;
152​
153export interface GitPushResult {
154 status: "pushed" | "skipped_up_to_date";
155 branch: string;
156 upstreamBranch?: string | undefined;
157 setUpstream?: boolean | undefined;
159​
160export interface GitRangeContext {
161 commitSummary: string;
162 diffSummary: string;
163 diffPatch: string;
165​
166export interface GitRenameBranchInput {
167 cwd: string;
168 oldBranch: string;
169 newBranch: string;
171​
172export interface GitRenameBranchResult {
173 branch: string;
175​
176export interface GitFetchPullRequestBranchInput {
177 cwd: string;
178 prNumber: number;
179 branch: string;
181​
182export interface GitFetchPullRequestHeadCommitInput {
183 cwd: string;
184 prNumber: number;
186​
187export interface GitResolveCommitInput {
188 cwd: string;
189 revision: string;
191​
192export interface GitResolveCommitResult {
193 commitSha: string;
195​
196export interface GitRefreshCheckedOutBranchInput {
197 cwd: string;
198 targetCommit: string;
199 /**
200 * Commit the checkout is allowed to be hard-reset away from: the upstream commit read before
201 * the fetch. HEAD sitting there means the checkout holds no work of its own.
202 */
203 resetWhenHeadCommit?: string | null | undefined;
205​
206export interface GitRefreshCheckedOutBranchResult {
207 headCommit: string;
208 moved: boolean;
209 onTarget: boolean;
211​
212export interface GitEnsureRemoteInput {
213 cwd: string;
214 preferredName: string;
215 url: string;
217​
218export interface GitFetchRemoteBranchInput {
219 cwd: string;
220 remoteName: string;
221 remoteBranch: string;
222 localBranch: string;
224​
225export interface GitFetchRemoteTrackingBranchInput {
226 cwd: string;
227 remoteName: string;
228 remoteBranch: string;
230​
231export interface GitFetchRemoteInput {
232 cwd: string;
233 remoteName: string;
234 refName?: string;
236​
237export interface GitRemoteExistsInput {
238 cwd: string;
239 remoteName: string;
241​
242export interface GitRemoteBranchExistsInput extends GitRemoteExistsInput {
243 refName: string;
245​
246export interface GitResolveRemoteTrackingCommitInput {
247 cwd: string;
248 refName: string;
249 fallbackRemoteName: string;
251​
252export interface GitResolveRemoteTrackingCommitResult {
253 commitSha: string;
254 remoteRefName: string;
256​
257export interface GitSetBranchUpstreamInput {
258 cwd: string;
259 branch: string;
260 remoteName: string;
261 remoteBranch: string;
263​
264export interface GitRemoteStatusOptions {
265 readonly refreshUpstream?: boolean;
267​
268export class GitVcsDriver extends Context.Service<
269 GitVcsDriver,
270 {
271 readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
272 readonly status: (input: VcsStatusInput) => Effect.Effect<VcsStatusResult, GitCommandError>;
273 readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
274 readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
275 readonly statusDetailsRemote: (
276 cwd: string,
277 options?: GitRemoteStatusOptions,
278 ) => Effect.Effect<GitRemoteStatusDetails, GitCommandError>;
279 readonly prepareCommitContext: (
280 cwd: string,
281 filePaths?: readonly string[],
282 ) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
283 readonly commit: (
284 cwd: string,
285 subject: string,
286 body: string,
287 options?: GitCommitOptions,
288 ) => Effect.Effect<{ commitSha: string }, GitCommandError>;
289 readonly pushCurrentBranch: (
290 cwd: string,
291 fallbackBranch: string | null,
292 options?: { readonly remoteName?: string | null },
293 ) => Effect.Effect<GitPushResult, GitCommandError>;
294 readonly readRangeContext: (
295 cwd: string,
296 baseRef: string,
297 ) => Effect.Effect<GitRangeContext, GitCommandError>;
298 readonly getReviewDiffPreview: (
299 input: ReviewDiffPreviewInput,
300 ) => Effect.Effect<ReviewDiffPreviewResult, GitCommandError>;
301 readonly getReviewDiffFileContents: (
302 input: ReviewDiffFileContentsInput,
303 ) => Effect.Effect<ReviewDiffFileContentsResult, GitCommandError>;
304 readonly readConfigValue: (
305 cwd: string,
306 key: string,
307 ) => Effect.Effect<string | null, GitCommandError>;
308 readonly listRefs: (
309 input: VcsListRefsInput,
310 ) => Effect.Effect<VcsListRefsResult, GitCommandError>;
311 readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
312 readonly createWorktree: (
313 input: VcsCreateWorktreeInput,
314 options?: CreateWorktreeOptions,
315 ) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
316 readonly fetchPullRequestBranch: (
317 input: GitFetchPullRequestBranchInput,
318 ) => Effect.Effect<void, GitCommandError>;
319 /** Fetches `refs/pull/<n>/head` without writing a branch, for heads that exist nowhere else. */
320 readonly fetchPullRequestHeadCommit: (
321 input: GitFetchPullRequestHeadCommitInput,
322 ) => Effect.Effect<GitResolveCommitResult, GitCommandError>;
323 readonly resolveCommit: (
324 input: GitResolveCommitInput,
325 ) => Effect.Effect<GitResolveCommitResult, GitCommandError>;
326 /** Moves the branch checked out in `cwd` onto `targetCommit`, from inside that worktree. */
327 readonly refreshCheckedOutBranch: (
328 input: GitRefreshCheckedOutBranchInput,
329 ) => Effect.Effect<GitRefreshCheckedOutBranchResult, GitCommandError>;
330 readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
331 readonly resolvePrimaryRemoteName: (cwd: string) => Effect.Effect<string, GitCommandError>;
332 readonly resolveDefaultBranchName: (
333 cwd: string,
334 remoteName: string,
335 ) => Effect.Effect<string | null, GitCommandError>;
336 readonly fetchRemote: (input: GitFetchRemoteInput) => Effect.Effect<void, GitCommandError>;
337 readonly remoteExists: (input: GitRemoteExistsInput) => Effect.Effect<boolean, GitCommandError>;
338 readonly remoteBranchExists: (
339 input: GitRemoteBranchExistsInput,
340 ) => Effect.Effect<boolean, GitCommandError>;
341 readonly resolveRemoteTrackingCommit: (
342 input: GitResolveRemoteTrackingCommitInput,
343 ) => Effect.Effect<GitResolveRemoteTrackingCommitResult, GitCommandError>;
344 readonly fetchRemoteBranch: (
345 input: GitFetchRemoteBranchInput,
346 ) => Effect.Effect<void, GitCommandError>;
347 readonly fetchRemoteTrackingBranch: (
348 input: GitFetchRemoteTrackingBranchInput,
349 ) => Effect.Effect<void, GitCommandError>;
350 readonly setBranchUpstream: (
351 input: GitSetBranchUpstreamInput,
352 ) => Effect.Effect<void, GitCommandError>;
353 readonly removeWorktree: (
354 input: VcsRemoveWorktreeInput,
355 ) => Effect.Effect<void, GitCommandError>;
356 /** Drops worktree admin entries whose directory is already gone (`git worktree prune`). */
357 readonly pruneWorktrees: (input: {
358 readonly cwd: string;
359 }) => Effect.Effect<void, GitCommandError>;
360 readonly renameBranch: (
361 input: GitRenameBranchInput,
362 ) => Effect.Effect<GitRenameBranchResult, GitCommandError>;
363 readonly createRef: (
364 input: VcsCreateRefInput,
365 ) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
366 readonly switchRef: (
367 input: VcsSwitchRefInput,
368 ) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
369 readonly initRepo: (input: VcsInitInput) => Effect.Effect<void, GitCommandError>;
370 readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
371 }
372>()("t3/vcs/GitVcsDriver") {}
373​
374const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
375const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
376const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
377const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [
378 "-c",
379 "core.fsmonitor=false",
380 "-c",
381 "core.untrackedCache=false",
382] as const;
383​
384const nowFreshness = Effect.fn("GitVcsDriver.nowFreshness")(function* () {
385 const now = yield* DateTime.now;
386 return {
387 source: "live-local" as const,
388 observedAt: now,
389 expiresAt: Option.none(),
390 };
391});
392​
393function chunkPathsForGitCheckIgnore(relativePaths: ReadonlyArray<string>): string[][] {
394 const chunks: string[][] = [];
395 let chunk: string[] = [];
396 let chunkBytes = 0;
397​
398 for (const relativePath of relativePaths) {
399 const relativePathBytes = Buffer.byteLength(relativePath) + 1;
400 if (chunk.length > 0 && chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
401 chunks.push(chunk);
402 chunk = [];
403 chunkBytes = 0;
404 }
405​
406 chunk.push(relativePath);
407 chunkBytes += relativePathBytes;
408​
409 if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
410 chunks.push(chunk);
411 chunk = [];
412 chunkBytes = 0;
413 }
414 }
415​
416 if (chunk.length > 0) {
417 chunks.push(chunk);
418 }
419​
420 return chunks;
422​
423function parseGitRemoteVerboseOutput(
424 output: string,
425): Map<string, { url?: string; pushUrl?: string }> {
426 const remotes = new Map<string, { url?: string; pushUrl?: string }>();
427 for (const line of output.split("\n")) {
428 const trimmed = line.trim();
429 if (trimmed.length === 0) {
430 continue;
431 }
432​
433 const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed);
434 if (!match) {
435 continue;
436 }
437​
438 const name = match[1];
439 const url = match[2];
440 const direction = match[3];
441 if (!name || !url || !direction) {
442 continue;
443 }
444 const remote = remotes.get(name) ?? {};
445 if (direction === "fetch") {
446 remote.url = url;
447 } else {
448 remote.pushUrl = url;
449 }
450 remotes.set(name, remote);
451 }
452 return remotes;
454​
455const gitCommand = (
456 process: VcsProcess.VcsProcess["Service"],
457 operation: string,
458 cwd: string,
459 args: ReadonlyArray<string>,
460 options?: {
461 readonly stdin?: string;
462 readonly env?: NodeJS.ProcessEnv;
463 readonly allowNonZeroExit?: boolean;
464 readonly timeoutMs?: number;
465 readonly maxOutputBytes?: number;
466 readonly outputMode?: VcsProcess.VcsProcessInput["outputMode"];
467 readonly appendTruncationMarker?: boolean;
468 },
469) =>
470 process.run({
471 operation,
472 command: "git",
473 args: ["-C", cwd, ...args],
474 cwd,
475 spawnCwd: globalThis.process.cwd(),
476 ...(options?.stdin !== undefined ? { stdin: options.stdin } : {}),
477 ...(options?.env !== undefined ? { env: options.env } : {}),
478 ...(options?.allowNonZeroExit !== undefined
479 ? { allowNonZeroExit: options.allowNonZeroExit }
480 : {}),
481 ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
482 ...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
483 ...(options?.outputMode !== undefined ? { outputMode: options.outputMode } : {}),
484 ...(options?.appendTruncationMarker !== undefined
485 ? { appendTruncationMarker: options.appendTruncationMarker }
486 : {}),
487 });
488​
489export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* () {
490 const fileSystem = yield* FileSystem.FileSystem;
491 const path = yield* Path.Path;
492 const vcsProcess = yield* VcsProcess.VcsProcess;
493 const capabilities = {
494 kind: "git" as const,
495 supportsWorktrees: true,
496 supportsBookmarks: false,
497 supportsAtomicSnapshot: false,
498 supportsPushDefaultRemote: true,
499 ignoreClassifier: "native" as const,
500 };
501​
502 const isInsideWorkTree: VcsDriver.VcsDriver["Service"]["isInsideWorkTree"] = (cwd) =>
503 gitCommand(
504 vcsProcess,
505 "GitVcsDriver.isInsideWorkTree",
506 cwd,
507 ["rev-parse", "--is-inside-work-tree"],
508 {
509 allowNonZeroExit: true,
510 timeoutMs: 5_000,
511 maxOutputBytes: 4_096,
512 },
513 ).pipe(Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"));
514​
515 const execute: VcsDriver.VcsDriver["Service"]["execute"] = (input) =>
516 gitCommand(vcsProcess, input.operation, input.cwd, input.args, {
517 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
518 ...(input.env !== undefined ? { env: input.env } : {}),
519 ...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}),
520 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
521 ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
522 ...(input.outputMode !== undefined ? { outputMode: input.outputMode } : {}),
523 ...(input.appendTruncationMarker !== undefined
524 ? { appendTruncationMarker: input.appendTruncationMarker }
525 : {}),
526 });
527​
528 const detectRepository: VcsDriver.VcsDriver["Service"]["detectRepository"] = Effect.fn(
529 "detectRepository",
530 )(function* (cwd) {
531 if (!(yield* isInsideWorkTree(cwd))) {
532 return null;
533 }
534​
535 const root = yield* gitCommand(vcsProcess, "GitVcsDriver.detectRepository.root", cwd, [
536 "rev-parse",
537 "--show-toplevel",
538 ]);
539 const gitCommonDir = yield* gitCommand(
540 vcsProcess,
541 "GitVcsDriver.detectRepository.commonDir",
542 cwd,
543 ["rev-parse", "--git-common-dir"],
544 ).pipe(Effect.orElseSucceed(() => null));
545​
546 return {
547 kind: "git" as const,
548 rootPath: root.stdout.trim(),
549 metadataPath: gitCommonDir?.stdout.trim() || null,
550 freshness: yield* nowFreshness(),
551 };
552 });
553​
554 const listWorkspaceFiles: VcsDriver.VcsDriver["Service"]["listWorkspaceFiles"] = (cwd) =>
555 gitCommand(
556 vcsProcess,
557 "GitVcsDriver.listWorkspaceFiles",
558 cwd,
559 [
560 ...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
561 "ls-files",
562 "--cached",
563 "--others",
564 "--exclude-standard",
565 "-z",
566 ],
567 {
568 allowNonZeroExit: true,
569 timeoutMs: 20_000,
570 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
571 appendTruncationMarker: true,
572 },
573 ).pipe(
574 Effect.flatMap((result) =>
575 result.exitCode === 0
576 ? Effect.gen(function* () {
577 const freshness = yield* nowFreshness();
578 return {
579 paths: splitNullSeparatedGitStdoutPaths(result),
580 truncated: result.stdoutTruncated,
581 freshness,
582 };
583 })
584 : Effect.fail(
585 new VcsProcessExitError({
586 operation: "GitVcsDriver.listWorkspaceFiles",
587 command: "git ls-files",
588 cwd,
589 exitCode: result.exitCode,
590 detail: result.stderr.trim() || "git ls-files failed",
591 }),
592 ),
593 ),
594 );
595​
596 const listRemotes: VcsDriver.VcsDriver["Service"]["listRemotes"] = Effect.fn("listRemotes")(
597 function* (cwd) {
598 const result = yield* gitCommand(
599 vcsProcess,
600 "GitVcsDriver.listRemotes",
601 cwd,
602 ["remote", "-v"],
603 {
604 allowNonZeroExit: true,
605 timeoutMs: 5_000,
606 maxOutputBytes: 64 * 1024,
607 },
608 );
609​
610 if (result.exitCode !== 0) {
611 return yield* new VcsProcessExitError({
612 operation: "GitVcsDriver.listRemotes",
613 command: "git remote -v",
614 cwd,
615 exitCode: result.exitCode,
616 detail: result.stderr.trim() || "git remote -v failed",
617 });
618 }
619​
620 const parsed = parseGitRemoteVerboseOutput(result.stdout);
621 const remotes = Array.from(parsed.entries()).flatMap(([name, remote]) => {
622 if (!remote.url) {
623 return [];
624 }
625 return [
626 {
627 name,
628 url: remote.url,
629 pushUrl: remote.pushUrl ? Option.some(remote.pushUrl) : Option.none(),
630 isPrimary: name === "origin",
631 },
632 ];
633 });
634​
635 return {
636 remotes,
637 freshness: yield* nowFreshness(),
638 };
639 },
640 );
641​
642 const filterIgnoredPaths: VcsDriver.VcsDriver["Service"]["filterIgnoredPaths"] = Effect.fn(
643 "filterIgnoredPaths",
644 )(function* (cwd, relativePaths) {
645 if (relativePaths.length === 0) {
646 return relativePaths;
647 }
648​
649 const ignoredPaths = new Set<string>();
650 const chunks = chunkPathsForGitCheckIgnore(relativePaths);
651​
652 for (const chunk of chunks) {
653 const result = yield* gitCommand(
654 vcsProcess,
655 "GitVcsDriver.filterIgnoredPaths",
656 cwd,
657 [...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
658 {
659 stdin: `${chunk.join("\0")}\0`,
660 allowNonZeroExit: true,
661 timeoutMs: 20_000,
662 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
663 appendTruncationMarker: true,
664 },
665 );
666​
667 if (result.exitCode !== 0 && result.exitCode !== 1) {
668 return yield* new VcsProcessExitError({
669 operation: "GitVcsDriver.filterIgnoredPaths",
670 command: "git check-ignore",
671 cwd,
672 exitCode: result.exitCode,
673 detail: result.stderr.trim() || "git check-ignore failed",
674 });
675 }
676​
677 for (const ignoredPath of splitNullSeparatedGitStdoutPaths(result)) {
678 ignoredPaths.add(ignoredPath);
679 }
680 }
681​
682 if (ignoredPaths.size === 0) {
683 return relativePaths;
684 }
685​
686 return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
687 });
688​
689 const initRepository: VcsDriver.VcsDriver["Service"]["initRepository"] = (input) =>
690 gitCommand(vcsProcess, "GitVcsDriver.initRepository", input.cwd, ["init"], {
691 timeoutMs: 10_000,
692 maxOutputBytes: 64 * 1024,
693 }).pipe(Effect.asVoid);
694​
695 const resolveHeadCommit = (cwd: string) =>
696 execute({
697 operation: "GitVcsDriver.checkpoints.resolveHeadCommit",
698 cwd,
699 args: ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
700 allowNonZeroExit: true,
701 }).pipe(
702 Effect.map((result) => {
703 if (result.exitCode !== 0) {
704 return null;
705 }
706 const commit = result.stdout.trim();
707 return commit.length > 0 ? commit : null;
708 }),
709 );
710​
711 const hasHeadCommit = (cwd: string) =>
712 execute({
713 operation: "GitVcsDriver.checkpoints.hasHeadCommit",
714 cwd,
715 args: ["rev-parse", "--verify", "HEAD"],
716 allowNonZeroExit: true,
717 }).pipe(Effect.map((result) => result.exitCode === 0));
718​
719 const resolveCheckpointCommit = (cwd: string, checkpointRef: string) =>
720 execute({
721 operation: "GitVcsDriver.checkpoints.resolveCheckpointCommit",
722 cwd,
723 args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`],
724 allowNonZeroExit: true,
725 }).pipe(
726 Effect.map((result) => {
727 if (result.exitCode !== 0) {
728 return null;
729 }
730 const commit = result.stdout.trim();
731 return commit.length > 0 ? commit : null;
732 }),
733 );
734​
735 const resolveGitCommonDir = (cwd: string) =>
736 Effect.gen(function* () {
737 const result = yield* execute({
738 operation: "GitVcsDriver.checkpoints.resolveGitCommonDir",
739 cwd,
740 args: ["rev-parse", "--git-common-dir"],
741 });
742 const gitCommonDir = result.stdout.trim();
743 return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
744 });
745​
746 const checkpoints: VcsDriver.VcsCheckpointOps = {
747 captureCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureCheckpoint")(function* (input) {
748 const operation = "GitVcsDriver.checkpoints.captureCheckpoint";
749 const gitCommonDir = yield* resolveGitCommonDir(input.cwd);
750 const tempIndexPath = path.join(
751 gitCommonDir,
752 `t3-checkpoint-index-${NodeCrypto.randomUUID()}`,
753 );
754 const commitEnv: NodeJS.ProcessEnv = {
755 ...process.env,
756 GIT_INDEX_FILE: tempIndexPath,
757 GIT_AUTHOR_NAME: "T3 Code",
758 GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com",
759 GIT_COMMITTER_NAME: "T3 Code",
760 GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com",
761 };
762​
763 const cleanupTempIndex = fileSystem
764 .remove(tempIndexPath, { force: true })
765 .pipe(Effect.ignore);
766​
767 yield* Effect.gen(function* () {
768 const headExists = yield* hasHeadCommit(input.cwd);
769 if (headExists) {
770 yield* execute({
771 operation,
772 cwd: input.cwd,
773 args: ["read-tree", "HEAD"],
774 env: commitEnv,
775 });
776 }
777​
778 yield* execute({
779 operation,
780 cwd: input.cwd,
781 args: ["add", "-A", "--", "."],
782 env: commitEnv,
783 });
784​
785 const writeTreeResult = yield* execute({
786 operation,
787 cwd: input.cwd,
788 args: ["write-tree"],
789 env: commitEnv,
790 });
791 const treeOid = writeTreeResult.stdout.trim();
792 if (treeOid.length === 0) {
793 return yield* new VcsProcessExitError({
794 operation,
795 command: "git write-tree",
796 cwd: input.cwd,
797 exitCode: 0,
798 detail: "git write-tree returned an empty tree oid.",
799 });
800 }
801​
802 const message = `t3 checkpoint ref=${input.checkpointRef}`;
803 const commitTreeResult = yield* execute({
804 operation,
805 cwd: input.cwd,
806 args: ["commit-tree", treeOid, "-m", message],
807 env: commitEnv,
808 });
809 const commitOid = commitTreeResult.stdout.trim();
810 if (commitOid.length === 0) {
811 return yield* new VcsProcessExitError({
812 operation,
813 command: "git commit-tree",
814 cwd: input.cwd,
815 exitCode: 0,
816 detail: "git commit-tree returned an empty commit oid.",
817 });
818 }
819​
820 yield* execute({
821 operation,
822 cwd: input.cwd,
823 args: ["update-ref", input.checkpointRef, commitOid],
824 });
825 }).pipe(Effect.ensuring(cleanupTempIndex));
826 }),
827​
828 hasCheckpointRef: (input) =>
829 resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
830 Effect.map((commit) => commit !== null),
831 ),
832​
833 restoreCheckpoint: Effect.fn("GitVcsDriver.checkpoints.restoreCheckpoint")(function* (input) {
834 const operation = "GitVcsDriver.checkpoints.restoreCheckpoint";
835​
836 let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
837​
838 if (!commitOid && input.fallbackToHead === true) {
839 commitOid = yield* resolveHeadCommit(input.cwd);
840 }
841​
842 if (!commitOid) {
843 return false;
844 }
845​
846 const tracked = yield* execute({
847 operation,
848 cwd: input.cwd,
849 args: ["ls-files", "--cached", `--with-tree=${commitOid}`, "-z", "--", "."],
850 });
851 // An empty index and checkpoint have nothing for git restore's pathspec to match.
852 if (tracked.stdout.length > 0) {
853 yield* execute({
854 operation,
855 cwd: input.cwd,
856 args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
857 });
858 }
859 // Restoring away the last tracked file can remove a nested workspace directory.
860 yield* fileSystem.makeDirectory(input.cwd, { recursive: true }).pipe(
861 Effect.mapError(
862 (cause) =>
863 new VcsProcessExitError({
864 operation,
865 command: "git restore",
866 cwd: input.cwd,
867 exitCode: 0,
868 detail: `Could not recreate the checkpoint workspace: ${cause.message}`,
869 }),
870 ),
871 );
872 const cleaned = yield* execute({
873 operation,
874 cwd: input.cwd,
875 args: ["clean", "-fd", "--", "."],
876 allowNonZeroExit: true,
877 });
878 if (cleaned.exitCode !== 0) {
879 // Git can remove every child, then fail trying to remove './' itself.
880 const emptiedWorkspace =
881 cleaned.exitCode === 1 &&
882 /^warning: failed to remove \.\/: [^\n]+$/.test(cleaned.stderr.trim()) &&
883 (yield* fileSystem.readDirectory(input.cwd).pipe(
884 Effect.map((entries) => entries.length === 0),
885 Effect.catch(() => Effect.succeed(false)),
886 ));
887 if (!emptiedWorkspace)
888 return yield* new VcsProcessExitError({
889 operation,
890 command: "git clean",
891 cwd: input.cwd,
892 exitCode: cleaned.exitCode,
893 detail: cleaned.stderr.trim() || "Could not clean the checkpoint workspace.",
894 });
895 }
896​
897 const headExists = yield* hasHeadCommit(input.cwd);
898 if (headExists) {
899 yield* execute({
900 operation,
901 cwd: input.cwd,
902 args: ["reset", "--quiet", "--", "."],
903 });
904 }
905​
906 return true;
907 }),
908​
909 diffCheckpoints: Effect.fn("GitVcsDriver.checkpoints.diffCheckpoints")(function* (input) {
910 const operation = "GitVcsDriver.checkpoints.diffCheckpoints";
911 yield* Effect.annotateCurrentSpan({
912 "checkpoint.cwd": input.cwd,
913 "checkpoint.from_ref": input.fromCheckpointRef,
914 "checkpoint.to_ref": input.toCheckpointRef,
915 "checkpoint.ignore_whitespace": input.ignoreWhitespace,
916 "checkpoint.format": input.format ?? "patch",
917 "checkpoint.fallback_from_to_head": input.fallbackFromToHead,
918 });
919​
920 let fromRevision: string = input.fromCheckpointRef;
921 if (input.fallbackFromToHead === true) {
922 const resolvedFromCommit = yield* resolveCheckpointCommit(
923 input.cwd,
924 input.fromCheckpointRef,
925 );
926 if (resolvedFromCommit) {
927 fromRevision = resolvedFromCommit;
928 } else {
929 const headCommit = yield* resolveHeadCommit(input.cwd);
930 if (!headCommit) {
931 return yield* new VcsProcessExitError({
932 operation,
933 command: "git diff",
934 cwd: input.cwd,
935 exitCode: 1,
936 detail: "Checkpoint ref is unavailable for diff operation.",
937 });
938 }
939 fromRevision = headCommit;
940 }
941 }
942​
943 const result = yield* execute({
944 operation,
945 cwd: input.cwd,
946 args: [
947 "diff",
948 ...(input.format === "numstat" ? ["--numstat", "-z"] : ["--patch"]),
949 "--no-color",
950 "--no-ext-diff",
951 "--no-textconv",
952 ...PATCH_RENDER_PREFIX_ARGS,
953 ...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
954 `${fromRevision}^{commit}`,
955 `${input.toCheckpointRef}^{commit}`,
956 ],
957 allowNonZeroExit: true,
958 maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
959 outputMode: input.format === "numstat" ? "error" : "truncate",
960 });
961​
962 if (result.exitCode !== 0) {
963 return yield* new VcsProcessExitError({
964 operation,
965 command: "git diff",
966 cwd: input.cwd,
967 exitCode: result.exitCode,
968 detail: result.stderr.trim() || "Checkpoint ref is unavailable for diff operation.",
969 });
970 }
971​
972 return result.stdout;
973 }),
974​
975 deleteCheckpointRefs: Effect.fn("GitVcsDriver.checkpoints.deleteCheckpointRefs")(
976 function* (input) {
977 yield* Effect.forEach(
978 input.checkpointRefs,
979 (checkpointRef) =>
980 execute({
981 operation: "GitVcsDriver.checkpoints.deleteCheckpointRefs",
982 cwd: input.cwd,
983 args: ["update-ref", "-d", checkpointRef],
984 allowNonZeroExit: true,
985 }),
986 { discard: true },
987 );
988 },
989 ),
990 };
991​
992 return {
993 capabilities,
994 execute,
995 checkpoints,
996 detectRepository,
997 isInsideWorkTree,
998 listWorkspaceFiles,
999 listRemotes,
1000 filterIgnoredPaths,
1001 initRepository,
1002 };
1003});
1004​
1005export const makeVcsDriver = Effect.gen(function* () {
1006 const driver = yield* makeVcsDriverShape();
1007 return VcsDriver.VcsDriver.of(driver);
1008});
1009​
1010export const make = Effect.gen(function* () {
1011 const git = yield* makeGitVcsDriverCore();
1012 return GitVcsDriver.of(git);
1013});
1014​
1015export const vcsLayer = Layer.effect(VcsDriver.VcsDriver, makeVcsDriver);
1016export const layer = Layer.effect(GitVcsDriver, make);