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

GitVcsDriver.ts

1,347 lines44.6 KB

1import * as NodeBuffer from "node:buffer";
2​
3import * as Context from "effect/Context";
4import * as Crypto from "effect/Crypto";
5import * as DateTime from "effect/DateTime";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import { ChildProcessSpawner } from "effect/process";
12​
13import {
14 GitCommandError,
15 VcsProcessExitError,
16 type VcsSwitchRefInput,
17 type VcsSwitchRefResult,
18 type VcsCreateRefInput,
19 type VcsCreateRefResult,
20 type VcsCreateWorktreeInput,
21 type VcsCreateWorktreeResult,
22 type ReviewDiffPreviewInput,
23 type ReviewDiffPreviewResult,
24 type ReviewDiffFileContentsInput,
25 type ReviewDiffFileContentsResult,
26 type VcsInitInput,
27 type VcsListRefsInput,
28 type VcsListRefsResult,
29 type VcsPullResult,
30 type VcsRemoveWorktreeInput,
31 type VcsStatusInput,
32 type VcsStatusResult,
33 type WorktreeSubmodules,
34} from "@t3tools/contracts";
35import * as HostProcess from "@t3tools/shared/HostProcess";
36import {
37 makeGitVcsDriverCore,
38 PATCH_RENDER_PREFIX_ARGS,
39 splitNullSeparatedGitStdoutPaths,
40} from "./GitVcsDriverCore.ts";
41import * as VcsDriver from "./VcsDriver.ts";
42import * as VcsProcess from "./VcsProcess.ts";
43​
44export interface ExecuteGitInput {
45 readonly operation: string;
46 readonly cwd: string;
47 readonly args: ReadonlyArray<string>;
48 readonly stdin?: string;
49 readonly env?: NodeJS.ProcessEnv;
50 readonly allowNonZeroExit?: boolean;
51 readonly timeoutMs?: number | null;
52 readonly maxOutputBytes?: number;
53 readonly appendTruncationMarker?: boolean;
54 /**
55 * With `appendTruncationMarker`, keep invoking the line callbacks after the
56 * buffered copy is full. For long-running commands whose output is only
57 * consumed through `progress`.
58 */
59 readonly keepLineCallbacksAfterTruncation?: boolean;
60 readonly progress?: ExecuteGitProgress;
62​
63export interface ExecuteGitResult {
64 readonly exitCode: ChildProcessSpawner.ExitCode;
65 readonly stdout: string;
66 readonly stderr: string;
67 readonly stdoutTruncated: boolean;
68 readonly stderrTruncated: boolean;
70​
71export interface GitStatusDetails {
72 isRepo: boolean;
73 sourceControlProvider?: VcsStatusResult["sourceControlProvider"];
74 hasOriginRemote: boolean;
75 isDefaultBranch: boolean;
76 branch: string | null;
77 upstreamRef: string | null;
78 hasWorkingTreeChanges: boolean;
79 workingTree: VcsStatusResult["workingTree"];
80 branchChanges?: VcsStatusResult["branchChanges"];
81 hasUpstream: boolean;
82 aheadCount: number;
83 behindCount: number;
84 aheadOfDefaultCount: number;
86​
87export interface GitLocalStatusOptions {
88 readonly includeDivergence?: boolean;
89 readonly includeBranchChanges?: boolean;
91​
92export interface GitRemoteStatusDetails {
93 isRepo: boolean;
94 defaultBranch: string | null;
95 isDefaultBranch: boolean;
96 branch: string | null;
97 upstreamRef: string | null;
98 hasUpstream: boolean;
99 aheadCount: number;
100 behindCount: number;
101 aheadOfDefaultCount: number;
103​
104export interface GitPreparedCommitContext {
105 stagedSummary: string;
106 stagedPatch: string;
108​
109export interface ExecuteGitProgress {
110 readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;
111 readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;
112 readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
113 readonly onHookFinished?: (input: {
114 hookName: string;
115 exitCode: number | null;
116 durationMs: number | null;
117 }) => Effect.Effect<void, never>;
119​
120export interface CreateWorktreeProgress {
121 /**
122 * Git refuses an existing path, so a path reported here belongs to this call and is safe to
123 * remove on cancel.
124 */
125 readonly onWorktreeClaimed?: (path: string) => Effect.Effect<void, never>;
126 readonly onCheckoutProgress?: (input: {
127 percent: number;
128 completed: number;
129 total: number;
130 }) => Effect.Effect<void, never>;
131 readonly onSubmodulesStarted?: () => Effect.Effect<void, never>;
132 readonly onSubmodulesDisabled?: (input: {
133 source: "settings" | "t3.json";
134 }) => Effect.Effect<void, never>;
135 readonly onSubmoduleLine?: (line: string) => Effect.Effect<void, never>;
136 readonly onSubmodulesFinished?: (input: {
137 ok: boolean;
138 detail: string | null;
139 }) => Effect.Effect<void, never>;
141​
142export interface CreateWorktreeOptions {
143 readonly progress?: CreateWorktreeProgress;
144 /**
145 * Null (or omitted, for callers without settings access) defers to the
146 * checkout's own t3.json.
147 */
148 readonly submodules?: WorktreeSubmodules | null;
149 readonly worktreesDirectory?: string;
151​
152export interface GitCommitProgress {
153 readonly onOutputLine?: (input: {
154 stream: "stdout" | "stderr";
155 text: string;
156 }) => Effect.Effect<void, never>;
157 readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
158 readonly onHookFinished?: (input: {
159 hookName: string;
160 exitCode: number | null;
161 durationMs: number | null;
162 }) => Effect.Effect<void, never>;
164​
165export interface GitCommitOptions {
166 readonly timeoutMs?: number;
167 readonly progress?: GitCommitProgress;
168 readonly stage?: { readonly filePaths?: readonly string[] };
170​
171export interface GitDeleteLocalBranchInput {
172 readonly cwd: string;
173 readonly refName: string;
174 readonly force?: boolean;
176​
177export interface GitPushResult {
178 status: "pushed" | "skipped_up_to_date";
179 branch: string;
180 upstreamBranch?: string | undefined;
181 setUpstream?: boolean | undefined;
183​
184export interface GitRangeContext {
185 commitSummary: string;
186 diffSummary: string;
187 diffPatch: string;
189​
190export interface GitRenameBranchInput {
191 exactName?: boolean;
192 cwd: string;
193 oldBranch: string;
194 newBranch: string;
196​
197export interface GitRenameBranchResult {
198 branch: string;
200​
201export interface GitFetchPullRequestBranchInput {
202 cwd: string;
203 prNumber: number;
204 branch: string;
206​
207export interface GitFetchPullRequestHeadCommitInput {
208 cwd: string;
209 prNumber: number;
211​
212export interface GitResolveCommitInput {
213 cwd: string;
214 revision: string;
216​
217export interface GitResolveCommitResult {
218 commitSha: string;
220​
221export interface GitRefreshCheckedOutBranchInput {
222 cwd: string;
223 targetCommit: string;
224 /**
225 * Commit the checkout is allowed to be hard-reset away from: the upstream commit read before
226 * the fetch. HEAD sitting there means the checkout holds no work of its own.
227 */
228 resetWhenHeadCommit?: string | null | undefined;
230​
231export interface GitRefreshCheckedOutBranchResult {
232 headCommit: string;
233 moved: boolean;
234 onTarget: boolean;
236​
237export interface GitEnsureRemoteInput {
238 cwd: string;
239 preferredName: string;
240 url: string;
242​
243export interface GitFetchRemoteBranchInput {
244 cwd: string;
245 remoteName: string;
246 remoteBranch: string;
247 localBranch: string;
249​
250export interface GitFetchRemoteTrackingBranchInput {
251 cwd: string;
252 remoteName: string;
253 remoteBranch: string;
255​
256export interface GitFetchRemoteInput {
257 cwd: string;
258 remoteName: string;
259 refName?: string;
261​
262export interface GitRemoteExistsInput {
263 cwd: string;
264 remoteName: string;
266​
267export interface GitRemoteBranchExistsInput extends GitRemoteExistsInput {
268 refName: string;
270​
271export interface GitResolveRemoteTrackingCommitInput {
272 cwd: string;
273 refName: string;
274 fallbackRemoteName: string;
276​
277export interface GitResolveRemoteTrackingCommitResult {
278 commitSha: string;
279 remoteRefName: string;
281​
282export interface GitFetchWorktreeBaseCommitInput {
283 cwd: string;
284 refName: string;
286​
287export interface GitSetBranchUpstreamInput {
288 cwd: string;
289 branch: string;
290 remoteName: string;
291 remoteBranch: string;
293​
294export interface GitRemoteStatusOptions {
295 readonly refreshUpstream?: boolean;
297​
298export class GitVcsDriver extends Context.Service<
299 GitVcsDriver,
300 {
301 readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
302 readonly status: (input: VcsStatusInput) => Effect.Effect<VcsStatusResult, GitCommandError>;
303 readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
304 readonly statusDetailsLocal: (
305 cwd: string,
306 options?: GitLocalStatusOptions,
307 ) => Effect.Effect<GitStatusDetails, GitCommandError>;
308 readonly statusDetailsRemote: (
309 cwd: string,
310 options?: GitRemoteStatusOptions,
311 ) => Effect.Effect<GitRemoteStatusDetails, GitCommandError>;
312 readonly prepareCommitContext: (
313 cwd: string,
314 filePaths?: readonly string[],
315 options?: { readonly includePatch?: boolean },
316 ) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
317 readonly commit: (
318 cwd: string,
319 subject: string,
320 body: string,
321 options?: GitCommitOptions,
322 ) => Effect.Effect<{ commitSha: string }, GitCommandError>;
323 readonly pushCurrentBranch: (
324 cwd: string,
325 fallbackBranch: string | null,
326 options?: { readonly remoteName?: string | null },
327 ) => Effect.Effect<GitPushResult, GitCommandError>;
328 readonly readRangeContext: (
329 cwd: string,
330 baseRef: string,
331 ) => Effect.Effect<GitRangeContext, GitCommandError>;
332 readonly getReviewDiffPreview: (
333 input: ReviewDiffPreviewInput,
334 ) => Effect.Effect<ReviewDiffPreviewResult, GitCommandError>;
335 readonly getReviewDiffFileContents: (
336 input: ReviewDiffFileContentsInput,
337 ) => Effect.Effect<ReviewDiffFileContentsResult, GitCommandError>;
338 readonly readConfigValue: (
339 cwd: string,
340 key: string,
341 ) => Effect.Effect<string | null, GitCommandError>;
342 readonly resolveBranchName: (
343 cwd: string,
344 refName: string,
345 ) => Effect.Effect<string | null, GitCommandError>;
346 readonly listRefs: (
347 input: VcsListRefsInput,
348 ) => Effect.Effect<VcsListRefsResult, GitCommandError>;
349 readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
350 readonly createWorktree: (
351 input: VcsCreateWorktreeInput,
352 options?: CreateWorktreeOptions,
353 ) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
354 readonly fetchPullRequestBranch: (
355 input: GitFetchPullRequestBranchInput,
356 ) => Effect.Effect<void, GitCommandError>;
357 readonly fetchPullRequestHeadCommit: (
358 input: GitFetchPullRequestHeadCommitInput,
359 ) => Effect.Effect<GitResolveCommitResult, GitCommandError>;
360 readonly resolveCommit: (
361 input: GitResolveCommitInput,
362 ) => Effect.Effect<GitResolveCommitResult, GitCommandError>;
363 readonly refreshCheckedOutBranch: (
364 input: GitRefreshCheckedOutBranchInput,
365 ) => Effect.Effect<GitRefreshCheckedOutBranchResult, GitCommandError>;
366 readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
367 readonly resolvePrimaryRemoteName: (cwd: string) => Effect.Effect<string, GitCommandError>;
368 readonly resolveDefaultBranchName: (
369 cwd: string,
370 remoteName: string,
371 ) => Effect.Effect<string | null, GitCommandError>;
372 readonly fetchRemote: (input: GitFetchRemoteInput) => Effect.Effect<void, GitCommandError>;
373 readonly remoteExists: (input: GitRemoteExistsInput) => Effect.Effect<boolean, GitCommandError>;
374 readonly remoteBranchExists: (
375 input: GitRemoteBranchExistsInput,
376 ) => Effect.Effect<boolean, GitCommandError>;
377 readonly resolveRemoteTrackingCommit: (
378 input: GitResolveRemoteTrackingCommitInput,
379 ) => Effect.Effect<GitResolveRemoteTrackingCommitResult, GitCommandError>;
380 readonly resolveWorktreeBaseRemote: (
381 input: GitFetchWorktreeBaseCommitInput,
382 ) => Effect.Effect<{ remoteName: string; branchName: string } | null, GitCommandError>;
383 /** Fetches the configured upstream, explicit remote ref, or origin; null uses the local base. */
384 readonly fetchWorktreeBaseCommit: (
385 input: GitFetchWorktreeBaseCommitInput,
386 ) => Effect.Effect<GitResolveRemoteTrackingCommitResult | null, GitCommandError>;
387 readonly fetchRemoteBranch: (
388 input: GitFetchRemoteBranchInput,
389 ) => Effect.Effect<void, GitCommandError>;
390 readonly fetchRemoteTrackingBranch: (
391 input: GitFetchRemoteTrackingBranchInput,
392 ) => Effect.Effect<void, GitCommandError>;
393 readonly setBranchUpstream: (
394 input: GitSetBranchUpstreamInput,
395 ) => Effect.Effect<void, GitCommandError>;
396 readonly removeWorktree: (
397 input: VcsRemoveWorktreeInput,
398 ) => Effect.Effect<void, GitCommandError>;
399 readonly pruneWorktrees: (input: {
400 readonly cwd: string;
401 }) => Effect.Effect<void, GitCommandError>;
402 readonly listWorktreePaths: (cwd: string) => Effect.Effect<string[], GitCommandError>;
403 readonly deleteLocalBranch: (
404 input: GitDeleteLocalBranchInput,
405 ) => Effect.Effect<void, GitCommandError>;
406 readonly renameBranch: (
407 input: GitRenameBranchInput,
408 ) => Effect.Effect<GitRenameBranchResult, GitCommandError>;
409 readonly createRef: (
410 input: VcsCreateRefInput,
411 ) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
412 readonly switchRef: (
413 input: VcsSwitchRefInput,
414 ) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
415 readonly initRepo: (input: VcsInitInput) => Effect.Effect<void, GitCommandError>;
416 readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
417 }
418>()("t3/vcs/GitVcsDriver") {}
419​
420const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
421const CHECKPOINT_RECOVERY_MAX_CANDIDATES = 64;
422const CHECKPOINT_RECOVERY_TIMEOUT = "5 seconds";
423const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
424const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
425const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [
426 "-c",
427 "core.fsmonitor=false",
428 "-c",
429 "core.untrackedCache=false",
430] as const;
431​
432const nowFreshness = Effect.fn("GitVcsDriver.nowFreshness")(function* () {
433 const now = yield* DateTime.now;
434 return {
435 source: "live-local" as const,
436 observedAt: now,
437 expiresAt: Option.none(),
438 };
439});
440​
441function chunkPathsForGitCheckIgnore(relativePaths: ReadonlyArray<string>): string[][] {
442 const chunks: string[][] = [];
443 let chunk: string[] = [];
444 let chunkBytes = 0;
445​
446 for (const relativePath of relativePaths) {
447 const relativePathBytes = Buffer.byteLength(relativePath) + 1;
448 if (chunk.length > 0 && chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
449 chunks.push(chunk);
450 chunk = [];
451 chunkBytes = 0;
452 }
453​
454 chunk.push(relativePath);
455 chunkBytes += relativePathBytes;
456​
457 if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
458 chunks.push(chunk);
459 chunk = [];
460 chunkBytes = 0;
461 }
462 }
463​
464 if (chunk.length > 0) {
465 chunks.push(chunk);
466 }
467​
468 return chunks;
470​
471function parseGitRemoteVerboseOutput(
472 output: string,
473): Map<string, { url?: string; pushUrl?: string }> {
474 const remotes = new Map<string, { url?: string; pushUrl?: string }>();
475 for (const line of output.split("\n")) {
476 const trimmed = line.trim();
477 if (trimmed.length === 0) {
478 continue;
479 }
480​
481 // Partial clones append the promisor filter, e.g. `(fetch) [blob:none]`.
482 const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)(?:\s+\[[^\]]+\])?$/.exec(trimmed);
483 if (!match) {
484 continue;
485 }
486​
487 const name = match[1];
488 const url = match[2];
489 const direction = match[3];
490 if (!name || !url || !direction) {
491 continue;
492 }
493 const remote = remotes.get(name) ?? {};
494 if (direction === "fetch") {
495 remote.url = url;
496 } else {
497 remote.pushUrl = url;
498 }
499 remotes.set(name, remote);
500 }
501 return remotes;
503​
504const gitCommand = (
505 process: VcsProcess.VcsProcess["Service"],
506 operation: string,
507 cwd: string,
508 args: ReadonlyArray<string>,
509 options?: {
510 readonly stdin?: string;
511 readonly env?: NodeJS.ProcessEnv;
512 readonly allowNonZeroExit?: boolean;
513 readonly timeoutMs?: number;
514 readonly maxOutputBytes?: number;
515 readonly outputMode?: VcsProcess.VcsProcessInput["outputMode"];
516 readonly appendTruncationMarker?: boolean;
517 },
518) =>
519 process.run({
520 operation,
521 command: "git",
522 args: ["-C", cwd, ...args],
523 cwd,
524 spawnCwd: globalThis.process.cwd(),
525 ...(options?.stdin !== undefined ? { stdin: options.stdin } : {}),
526 ...(options?.env !== undefined ? { env: options.env } : {}),
527 ...(options?.allowNonZeroExit !== undefined
528 ? { allowNonZeroExit: options.allowNonZeroExit }
529 : {}),
530 ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
531 ...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
532 ...(options?.outputMode !== undefined ? { outputMode: options.outputMode } : {}),
533 ...(options?.appendTruncationMarker !== undefined
534 ? { appendTruncationMarker: options.appendTruncationMarker }
535 : {}),
536 });
537​
538export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* () {
539 const fileSystem = yield* FileSystem.FileSystem;
540 const path = yield* Path.Path;
541 const vcsProcess = yield* VcsProcess.VcsProcess;
542 const crypto = yield* Crypto.Crypto;
543 const capabilities = {
544 kind: "git" as const,
545 supportsWorktrees: true,
546 supportsBookmarks: false,
547 supportsAtomicSnapshot: false,
548 supportsPushDefaultRemote: true,
549 ignoreClassifier: "native" as const,
550 };
551​
552 const isInsideWorkTree: VcsDriver.VcsDriver["Service"]["isInsideWorkTree"] = (cwd) =>
553 gitCommand(
554 vcsProcess,
555 "GitVcsDriver.isInsideWorkTree",
556 cwd,
557 ["rev-parse", "--is-inside-work-tree"],
558 {
559 allowNonZeroExit: true,
560 timeoutMs: 5_000,
561 maxOutputBytes: 4_096,
562 },
563 ).pipe(Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"));
564​
565 const execute: VcsDriver.VcsDriver["Service"]["execute"] = (input) =>
566 gitCommand(vcsProcess, input.operation, input.cwd, input.args, {
567 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
568 ...(input.env !== undefined ? { env: input.env } : {}),
569 ...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}),
570 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
571 ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
572 ...(input.outputMode !== undefined ? { outputMode: input.outputMode } : {}),
573 ...(input.appendTruncationMarker !== undefined
574 ? { appendTruncationMarker: input.appendTruncationMarker }
575 : {}),
576 });
577​
578 const detectRepository: VcsDriver.VcsDriver["Service"]["detectRepository"] = Effect.fn(
579 "detectRepository",
580 )(function* (cwd) {
581 if (!(yield* isInsideWorkTree(cwd))) {
582 return null;
583 }
584​
585 const root = yield* gitCommand(vcsProcess, "GitVcsDriver.detectRepository.root", cwd, [
586 "rev-parse",
587 "--show-toplevel",
588 ]);
589 const gitCommonDir = yield* gitCommand(
590 vcsProcess,
591 "GitVcsDriver.detectRepository.commonDir",
592 cwd,
593 ["rev-parse", "--git-common-dir"],
594 ).pipe(Effect.orElseSucceed(() => null));
595​
596 return {
597 kind: "git" as const,
598 rootPath: root.stdout.trim(),
599 metadataPath: gitCommonDir?.stdout.trim() || null,
600 freshness: yield* nowFreshness(),
601 };
602 });
603​
604 const listWorkspaceFiles: VcsDriver.VcsDriver["Service"]["listWorkspaceFiles"] = (cwd) =>
605 gitCommand(
606 vcsProcess,
607 "GitVcsDriver.listWorkspaceFiles",
608 cwd,
609 [
610 ...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
611 "ls-files",
612 "--cached",
613 "--others",
614 "--exclude-standard",
615 "-z",
616 ],
617 {
618 allowNonZeroExit: true,
619 timeoutMs: 20_000,
620 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
621 appendTruncationMarker: true,
622 },
623 ).pipe(
624 Effect.flatMap((result) =>
625 result.exitCode === 0
626 ? Effect.gen(function* () {
627 const freshness = yield* nowFreshness();
628 return {
629 paths: splitNullSeparatedGitStdoutPaths(result),
630 truncated: result.stdoutTruncated,
631 freshness,
632 };
633 })
634 : Effect.fail(
635 new VcsProcessExitError({
636 operation: "GitVcsDriver.listWorkspaceFiles",
637 command: "git ls-files",
638 cwd,
639 exitCode: result.exitCode,
640 detail: result.stderr.trim() || "git ls-files failed",
641 }),
642 ),
643 ),
644 );
645​
646 const listRemotes: VcsDriver.VcsDriver["Service"]["listRemotes"] = Effect.fn("listRemotes")(
647 function* (cwd) {
648 const result = yield* gitCommand(
649 vcsProcess,
650 "GitVcsDriver.listRemotes",
651 cwd,
652 ["remote", "-v"],
653 {
654 allowNonZeroExit: true,
655 timeoutMs: 5_000,
656 maxOutputBytes: 64 * 1024,
657 },
658 );
659​
660 if (result.exitCode !== 0) {
661 return yield* new VcsProcessExitError({
662 operation: "GitVcsDriver.listRemotes",
663 command: "git remote -v",
664 cwd,
665 exitCode: result.exitCode,
666 detail: result.stderr.trim() || "git remote -v failed",
667 });
668 }
669​
670 const parsed = parseGitRemoteVerboseOutput(result.stdout);
671 const remotes = Array.from(parsed.entries()).flatMap(([name, remote]) => {
672 if (!remote.url) {
673 return [];
674 }
675 return [
676 {
677 name,
678 url: remote.url,
679 pushUrl: remote.pushUrl ? Option.some(remote.pushUrl) : Option.none(),
680 isPrimary: name === "origin",
681 },
682 ];
683 });
684​
685 return {
686 remotes,
687 freshness: yield* nowFreshness(),
688 };
689 },
690 );
691​
692 const filterIgnoredPaths: VcsDriver.VcsDriver["Service"]["filterIgnoredPaths"] = Effect.fn(
693 "filterIgnoredPaths",
694 )(function* (cwd, relativePaths) {
695 if (relativePaths.length === 0) {
696 return relativePaths;
697 }
698​
699 const ignoredPaths = new Set<string>();
700 const chunks = chunkPathsForGitCheckIgnore(relativePaths);
701​
702 for (const chunk of chunks) {
703 const result = yield* gitCommand(
704 vcsProcess,
705 "GitVcsDriver.filterIgnoredPaths",
706 cwd,
707 [...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
708 {
709 stdin: `${chunk.join("\0")}\0`,
710 allowNonZeroExit: true,
711 timeoutMs: 20_000,
712 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
713 appendTruncationMarker: true,
714 },
715 );
716​
717 if (result.exitCode !== 0 && result.exitCode !== 1) {
718 return yield* new VcsProcessExitError({
719 operation: "GitVcsDriver.filterIgnoredPaths",
720 command: "git check-ignore",
721 cwd,
722 exitCode: result.exitCode,
723 detail: result.stderr.trim() || "git check-ignore failed",
724 });
725 }
726​
727 for (const ignoredPath of splitNullSeparatedGitStdoutPaths(result)) {
728 ignoredPaths.add(ignoredPath);
729 }
730 }
731​
732 if (ignoredPaths.size === 0) {
733 return relativePaths;
734 }
735​
736 return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
737 });
738​
739 const initRepository: VcsDriver.VcsDriver["Service"]["initRepository"] = (input) =>
740 gitCommand(vcsProcess, "GitVcsDriver.initRepository", input.cwd, ["init"], {
741 timeoutMs: 10_000,
742 maxOutputBytes: 64 * 1024,
743 }).pipe(Effect.asVoid);
744​
745 const resolveHeadCommit = (cwd: string) =>
746 execute({
747 operation: "GitVcsDriver.checkpoints.resolveHeadCommit",
748 cwd,
749 args: ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
750 allowNonZeroExit: true,
751 }).pipe(
752 Effect.map((result) => {
753 if (result.exitCode !== 0) {
754 return null;
755 }
756 const commit = result.stdout.trim();
757 return commit.length > 0 ? commit : null;
758 }),
759 );
760​
761 const hasHeadCommit = (cwd: string, env?: NodeJS.ProcessEnv) =>
762 execute({
763 operation: "GitVcsDriver.checkpoints.hasHeadCommit",
764 cwd,
765 args: ["rev-parse", "--verify", "HEAD"],
766 allowNonZeroExit: true,
767 ...(env !== undefined ? { env } : {}),
768 }).pipe(Effect.map((result) => result.exitCode === 0));
769​
770 const resolveCheckpointCommit = (cwd: string, checkpointRef: string) =>
771 execute({
772 operation: "GitVcsDriver.checkpoints.resolveCheckpointCommit",
773 cwd,
774 args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`],
775 allowNonZeroExit: true,
776 }).pipe(
777 Effect.map((result) => {
778 if (result.exitCode !== 0) {
779 return null;
780 }
781 const commit = result.stdout.trim();
782 return commit.length > 0 ? commit : null;
783 }),
784 );
785​
786 const resolveGitCommonDir = (cwd: string) =>
787 Effect.gen(function* () {
788 const result = yield* execute({
789 operation: "GitVcsDriver.checkpoints.resolveGitCommonDir",
790 cwd,
791 args: ["rev-parse", "--git-common-dir"],
792 });
793 const gitCommonDir = result.stdout.trim();
794 return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
795 });
796​
797 // Git renames loose objects and refs into place without fsync by default, so
798 // an unclean restart can leave 0-byte files under refs/t3/** that break every
799 // later fetch and push. Checkpoint writes flush before they are published;
800 // macOS defaults to writeout-only, which does not reach the disk either.
801 // On macOS, VcsProcess retries unsupported full flushes with plain fsync.
802 const durableWrite = [
803 "-c",
804 "core.fsync=objects,reference",
805 "-c",
806 "core.fsyncMethod=fsync",
807 ] as const;
808​
809 // Checkpoints must handle existing paths beyond Windows MAX_PATH, even when
810 // core.longpaths is disabled in the user's Git configuration.
811 const longPaths = (yield* HostProcess.Platform) === "win32" ? ["-c", "core.longpaths=true"] : [];
812​
813 const checkpoints: VcsDriver.VcsCheckpointOps = {
814 captureCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureCheckpoint")(function* (input) {
815 const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION;
816 // core.splitIndex governs every index Git writes, so an unguarded write to the
817 // scratch index can expire the sharedindex.* the real .git/index still uses.
818 const indexConfig = [
819 "-c",
820 "core.fsmonitor=false",
821 "-c",
822 "sparse.expectFilesOutsideOfPatterns=false",
823 "-c",
824 "core.splitIndex=false",
825 "-c",
826 "splitIndex.sharedIndexExpire=never",
827 ];
828 const gitCommonDir = yield* resolveGitCommonDir(input.cwd);
829 const indexId = yield* crypto.randomUUIDv4().pipe(Effect.orDie);
830 const tempIndexPath = path.join(gitCommonDir, `t3-checkpoint-index-${indexId}`);
831 const commitEnv: NodeJS.ProcessEnv = {
832 ...process.env,
833 GIT_INDEX_FILE: tempIndexPath,
834 GIT_AUTHOR_NAME: "T3 Code",
835 GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com",
836 GIT_COMMITTER_NAME: "T3 Code",
837 GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com",
838 };
839​
840 const cleanupTempIndex = Effect.forEach(
841 [tempIndexPath, `${tempIndexPath}.lock`],
842 (indexFile) => fileSystem.remove(indexFile, { force: true }).pipe(Effect.ignore),
843 { discard: true },
844 );
845​
846 yield* Effect.gen(function* () {
847 const headExists = yield* hasHeadCommit(input.cwd);
848 const sparseConfig = yield* execute({
849 operation,
850 cwd: input.cwd,
851 args: ["config", "--bool", "core.sparseCheckout"],
852 allowNonZeroExit: true,
853 });
854 let sparseCheckout = sparseConfig.stdout.trim() === "true";
855 if (sparseCheckout) {
856 const help = yield* execute({
857 operation,
858 cwd: input.cwd,
859 args: ["add", "-h"],
860 allowNonZeroExit: true,
861 });
862 sparseCheckout = /--(?:\[no-\])?sparse\b/.test(`${help.stdout}${help.stderr}`);
863 }
864 if (headExists) {
865 const reusedIndex = yield* Effect.gen(function* () {
866 const indexPath = yield* execute({
867 operation,
868 cwd: input.cwd,
869 args: ["rev-parse", "--path-format=absolute", "--git-path", "index"],
870 });
871 const { mtime } = yield* fileSystem.stat(indexPath.stdout.trim());
872 if (Option.isNone(mtime)) return false;
873 // Stay below the source timestamp even if Date rounded up, preserving Git's racy check.
874 const indexTime = Math.floor((mtime.value.getTime() - 1) / 1000);
875 if (indexTime <= 0) return false;
876 yield* fileSystem.copyFile(indexPath.stdout.trim(), tempIndexPath);
877 yield* execute({
878 operation,
879 cwd: input.cwd,
880 args: [...indexConfig, "read-tree", "--reset", "HEAD"],
881 env: commitEnv,
882 });
883 // read-tree can rewrite the index, so restore its racy timestamp afterward.
884 yield* fileSystem.utimes(tempIndexPath, indexTime, indexTime);
885 let specialFlags = false;
886 let recordStart = true;
887 let skipped = false;
888 let skippedRecord: number[] = [];
889 const skippedPaths: string[] = [];
890 yield* vcsProcess.run({
891 operation,
892 command: "git",
893 cwd: input.cwd,
894 args: [...indexConfig, "ls-files", "--full-name", "--sparse", "-v", "-z"],
895 env: commitEnv,
896 maxOutputBytes: 4_096,
897 outputMode: "truncate",
898 onStdoutChunk: (chunk) => {
899 for (const byte of chunk) {
900 if (recordStart) skipped = byte === 83;
901 if (skipped && sparseCheckout) {
902 if (byte !== 0) skippedRecord.push(byte);
903 else {
904 if (skippedRecord.at(-1) !== 47) {
905 const name = Buffer.from(skippedRecord).subarray(2);
906 if (!NodeBuffer.isUtf8(name)) specialFlags = true;
907 else skippedPaths.push(name.toString("utf8"));
908 }
909 skippedRecord = [];
910 }
911 }
912 if (
913 recordStart &&
914 ((byte >= 97 && byte <= 122) || (!sparseCheckout && byte === 83))
915 ) {
916 specialFlags = true;
917 }
918 recordStart = byte === 0;
919 }
920 },
921 });
922 if (skippedPaths.length > 0 && !specialFlags) {
923 const selected = yield* execute({
924 operation,
925 cwd: input.cwd,
926 args: [...indexConfig, "sparse-checkout", "check-rules", "-z"],
927 stdin: skippedPaths.join("\0") + "\0",
928 env: commitEnv,
929 maxOutputBytes: 1,
930 outputMode: "truncate",
931 });
932 specialFlags = selected.stdout.length > 0 || selected.stdoutTruncated;
933 }
934 // Sparse Git clears skip-worktree for present files. Manual flags still need a reset.
935 return !specialFlags;
936 }).pipe(Effect.orElseSucceed(() => false));
937 if (!reusedIndex) {
938 if (sparseCheckout) {
939 const cone = yield* execute({
940 operation,
941 cwd: input.cwd,
942 args: ["config", "--bool", "core.sparseCheckoutCone"],
943 allowNonZeroExit: true,
944 });
945 // Rebuilding a non-cone index loses exclusions; do not publish false deletions.
946 if (cone.stdout.trim() !== "true") {
947 return yield* new VcsProcessExitError({
948 operation,
949 command: "git read-tree",
950 cwd: input.cwd,
951 exitCode: 1,
952 detail: "Cannot rebuild a checkpoint index for non-cone sparse checkout.",
953 });
954 }
955 }
956 yield* cleanupTempIndex;
957 yield* execute({
958 operation,
959 cwd: input.cwd,
960 args: sparseCheckout
961 ? [...indexConfig, "-c", "index.sparse=true", "read-tree", "--reset", "HEAD"]
962 : [...indexConfig, "read-tree", "HEAD"],
963 env: commitEnv,
964 });
965 }
966 }
967​
968 const stageFiles = (exclusions: ReadonlyArray<string>) =>
969 execute({
970 operation,
971 cwd: input.cwd,
972 args: [
973 ...indexConfig,
974 ...durableWrite,
975 ...longPaths,
976 "add",
977 ...(sparseCheckout ? ["--sparse"] : []),
978 "-A",
979 "--",
980 ".",
981 ...exclusions,
982 ],
983 env: commitEnv,
984 });
985 yield* stageFiles([]).pipe(
986 Effect.catchTags({
987 VcsProcessExitError: (error) =>
988 Effect.gen(function* () {
989 // Git cannot stage an embedded repository until it has a commit. Discover these
990 // only after staging fails so ordinary checkpoints do not need another file scan.
991 const untracked = yield* execute({
992 operation,
993 cwd: input.cwd,
994 args: [
995 ...longPaths,
996 "ls-files",
997 "--others",
998 "--exclude-standard",
999 "-z",
1000 "--",
1001 ".",
1002 ],
1003 env: commitEnv,
1004 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
1005 });
1006 if (untracked.stdoutTruncated) return yield* error;
1007 const candidates = splitNullSeparatedGitStdoutPaths(untracked).filter((entry) =>
1008 entry.endsWith("/"),
1009 );
1010 if (candidates.length > CHECKPOINT_RECOVERY_MAX_CANDIDATES) return yield* error;
1011 const nestedRepoEnv: NodeJS.ProcessEnv = {
1012 ...process.env,
1013 GIT_DIR: undefined,
1014 GIT_WORK_TREE: undefined,
1015 GIT_COMMON_DIR: undefined,
1016 GIT_INDEX_FILE: undefined,
1017 GIT_OBJECT_DIRECTORY: undefined,
1018 GIT_ALTERNATE_OBJECT_DIRECTORIES: undefined,
1019 };
1020 const exclusions: Array<string> = [];
1021 for (const entry of candidates) {
1022 const nestedCwd = path.join(input.cwd, entry);
1023 if (
1024 (yield* fileSystem
1025 .exists(path.join(nestedCwd, ".git"))
1026 .pipe(Effect.mapError(() => error))) &&
1027 !(yield* hasHeadCommit(nestedCwd, nestedRepoEnv))
1028 ) {
1029 exclusions.push(`:(exclude,literal)${entry}`);
1032 if (exclusions.length === 0) return yield* error;
1033 return yield* stageFiles(exclusions);
1034 }).pipe(
1035 Effect.timeoutOrElse({
1036 duration: CHECKPOINT_RECOVERY_TIMEOUT,
1037 orElse: () => Effect.fail(error),
1038 }),
1039 ),
1040 }),
1041 );
1042​
1043 const writeTreeResult = yield* execute({
1044 operation,
1045 cwd: input.cwd,
1046 args: [...indexConfig, ...durableWrite, "write-tree"],
1047 env: commitEnv,
1048 });
1049 const treeOid = writeTreeResult.stdout.trim();
1050 if (treeOid.length === 0) {
1051 return yield* new VcsProcessExitError({
1052 operation,
1053 command: "git write-tree",
1054 cwd: input.cwd,
1055 exitCode: 0,
1056 detail: "git write-tree returned an empty tree oid.",
1057 });
1059​
1060 const message = `t3 checkpoint ref=${input.checkpointRef}`;
1061 // HEAD is the parent so listAuthoredPaths can see how HEAD moved between checkpoints.
1062 const commitTreeResult = yield* execute({
1063 operation,
1064 cwd: input.cwd,
1065 args: [
1066 ...durableWrite,
1067 "commit-tree",
1068 treeOid,
1069 ...(headExists ? ["-p", "HEAD"] : []),
1070 "-m",
1071 message,
1072 ],
1073 env: commitEnv,
1074 });
1075 const commitOid = commitTreeResult.stdout.trim();
1076 if (commitOid.length === 0) {
1077 return yield* new VcsProcessExitError({
1078 operation,
1079 command: "git commit-tree",
1080 cwd: input.cwd,
1081 exitCode: 0,
1082 detail: "git commit-tree returned an empty commit oid.",
1083 });
1085​
1086 yield* execute({
1087 operation,
1088 cwd: input.cwd,
1089 args: [...durableWrite, "update-ref", input.checkpointRef, commitOid],
1090 });
1091 }).pipe(Effect.ensuring(cleanupTempIndex));
1092 }),
1093​
1094 hasCheckpointRef: (input) =>
1095 resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
1096 Effect.map((commit) => commit !== null),
1097 ),
1098​
1099 restoreCheckpoint: Effect.fn("GitVcsDriver.checkpoints.restoreCheckpoint")(function* (input) {
1100 const operation = "GitVcsDriver.checkpoints.restoreCheckpoint";
1101​
1102 let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
1103​
1104 if (!commitOid && input.fallbackToHead === true) {
1105 commitOid = yield* resolveHeadCommit(input.cwd);
1107​
1108 if (!commitOid) {
1109 return false;
1111​
1112 const tracked = yield* execute({
1113 operation,
1114 cwd: input.cwd,
1115 args: ["ls-files", "--cached", `--with-tree=${commitOid}`, "-z", "--", "."],
1116 });
1117 // An empty index and checkpoint have nothing for git restore's pathspec to match.
1118 if (tracked.stdout.length > 0) {
1119 yield* execute({
1120 operation,
1121 cwd: input.cwd,
1122 args: [
1123 ...longPaths,
1124 "restore",
1125 "--source",
1126 commitOid,
1127 "--worktree",
1128 "--staged",
1129 "--",
1130 ".",
1131 ],
1132 });
1134 // Restoring away the last tracked file can remove a nested workspace directory.
1135 const recreateWorkspace = fileSystem.makeDirectory(input.cwd, { recursive: true }).pipe(
1136 Effect.mapError(
1137 (cause) =>
1138 new VcsProcessExitError({
1139 operation,
1140 command: "git restore",
1141 cwd: input.cwd,
1142 exitCode: 0,
1143 detail: `Could not recreate the checkpoint workspace: ${cause.message}`,
1144 }),
1145 ),
1146 );
1147 yield* recreateWorkspace;
1148 const cleaned = yield* execute({
1149 operation,
1150 cwd: input.cwd,
1151 args: [...longPaths, "clean", "-fd", "--", "."],
1152 allowNonZeroExit: true,
1153 });
1154 if (cleaned.exitCode !== 0) {
1155 // Git can remove every child, then fail trying to remove './' itself.
1156 const emptiedWorkspace =
1157 cleaned.exitCode === 1 &&
1158 /^warning: failed to remove \.\/: [^\n]+$/.test(cleaned.stderr.trim()) &&
1159 (yield* fileSystem.readDirectory(input.cwd).pipe(
1160 Effect.map((entries) => entries.length === 0),
1161 Effect.orElseSucceed(() => false),
1162 ));
1163 if (!emptiedWorkspace)
1164 return yield* new VcsProcessExitError({
1165 operation,
1166 command: "git clean",
1167 cwd: input.cwd,
1168 exitCode: cleaned.exitCode,
1169 detail: cleaned.stderr.trim() || "Could not clean the checkpoint workspace.",
1170 });
1172 // On Windows the same clean can remove './' and exit 0.
1173 yield* recreateWorkspace;
1174​
1175 const headExists = yield* hasHeadCommit(input.cwd);
1176 if (headExists) {
1177 yield* execute({
1178 operation,
1179 cwd: input.cwd,
1180 args: [...longPaths, "reset", "--quiet", "--", "."],
1181 });
1183​
1184 return true;
1185 }),
1186​
1187 diffCheckpoints: Effect.fn("GitVcsDriver.checkpoints.diffCheckpoints")(function* (input) {
1188 const operation = "GitVcsDriver.checkpoints.diffCheckpoints";
1189 if (input.filePaths?.length === 0) return "";
1190 yield* Effect.annotateCurrentSpan({
1191 "checkpoint.cwd": input.cwd,
1192 "checkpoint.from_ref": input.fromCheckpointRef,
1193 "checkpoint.to_ref": input.toCheckpointRef,
1194 "checkpoint.ignore_whitespace": input.ignoreWhitespace,
1195 "checkpoint.format": input.format ?? "patch",
1196 "checkpoint.fallback_from_to_head": input.fallbackFromToHead,
1197 });
1198​
1199 let fromRevision: string = input.fromCheckpointRef;
1200 if (input.fallbackFromToHead === true) {
1201 const resolvedFromCommit = yield* resolveCheckpointCommit(
1202 input.cwd,
1203 input.fromCheckpointRef,
1204 );
1205 if (resolvedFromCommit) {
1206 fromRevision = resolvedFromCommit;
1207 } else {
1208 const headCommit = yield* resolveHeadCommit(input.cwd);
1209 if (!headCommit) {
1210 return yield* new VcsProcessExitError({
1211 operation,
1212 command: "git diff",
1213 cwd: input.cwd,
1214 exitCode: 1,
1215 detail: "Checkpoint ref is unavailable for diff operation.",
1216 });
1218 fromRevision = headCommit;
1221​
1222 const result = yield* execute({
1223 operation,
1224 cwd: input.cwd,
1225 args: [
1226 "diff",
1227 ...(input.format === "numstat" ? ["--numstat", "-z"] : ["--patch"]),
1228 "--no-color",
1229 "--no-ext-diff",
1230 "--no-textconv",
1231 ...PATCH_RENDER_PREFIX_ARGS,
1232 ...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
1233 `${fromRevision}^{commit}`,
1234 `${input.toCheckpointRef}^{commit}`,
1235 // Paths are repository-relative, while cwd can be a subdirectory.
1236 ...(input.filePaths
1237 ? ["--", ...input.filePaths.map((file) => `:(top,literal)${file}`)]
1238 : []),
1239 ],
1240 allowNonZeroExit: true,
1241 maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
1242 outputMode: input.format === "numstat" ? "error" : "truncate",
1243 });
1244​
1245 if (result.exitCode !== 0) {
1246 return yield* new VcsProcessExitError({
1247 operation,
1248 command: "git diff",
1249 cwd: input.cwd,
1250 exitCode: result.exitCode,
1251 detail: result.stderr.trim() || "Checkpoint ref is unavailable for diff operation.",
1252 });
1254​
1255 return result.stdout;
1256 }),
1257​
1258 listAuthoredPaths: Effect.fn("GitVcsDriver.checkpoints.listAuthoredPaths")(function* (input) {
1259 const operation = "GitVcsDriver.checkpoints.listAuthoredPaths";
1260 const heads = yield* execute({
1261 operation,
1262 cwd: input.cwd,
1263 args: [
1264 "log",
1265 "--no-walk=unsorted",
1266 "--format=%P %ct",
1267 `${input.fromCheckpointRef}^{commit}`,
1268 `${input.toCheckpointRef}^{commit}`,
1269 ],
1270 });
1271 const [fromLine = "", toLine = ""] = heads.stdout.trimEnd().split("\n");
1272 const [startHead = "", capturedAt = ""] = fromLine.split(" ");
1273 const [endHead = ""] = toLine.split(" ");
1274 if (startHead === "" || endHead === "" || startHead === endHead) {
1275 return null;
1277​
1278 const listPaths = (args: ReadonlyArray<string>) =>
1279 execute({
1280 operation,
1281 cwd: input.cwd,
1282 args: [...args, "--name-only", "-z", "--no-renames", "--no-ext-diff"],
1283 maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
1284 outputMode: "error",
1285 }).pipe(Effect.map((result) => result.stdout.split("\0")));
1286 // Remerge diff lists a merge's paths only where the result differs from Git's
1287 // automatic merge, so a merge keeps its conflict fixes and drops clean upstream changes.
1288 const pathLists = yield* Effect.all(
1290 listPaths(["diff", startHead, `${input.fromCheckpointRef}^{commit}`]),
1291 listPaths(["diff", endHead, `${input.toCheckpointRef}^{commit}`]),
1292 listPaths(["log", "--format=", "--diff-merges=remerge", `${endHead}..${startHead}`]),
1293 listPaths([
1294 "log",
1295 "--format=",
1296 "--diff-merges=remerge",
1297 `--since=@${capturedAt}`,
1298 `${startHead}..${endHead}`,
1299 ]),
1300 ],
1301 { concurrency: "unbounded" },
1302 );
1303 return new Set(pathLists.flat().filter((path) => path.length > 0));
1304 }),
1305​
1306 deleteCheckpointRefs: Effect.fn("GitVcsDriver.checkpoints.deleteCheckpointRefs")(
1307 function* (input) {
1308 yield* Effect.forEach(
1309 input.checkpointRefs,
1310 (checkpointRef) =>
1311 execute({
1312 operation: "GitVcsDriver.checkpoints.deleteCheckpointRefs",
1313 cwd: input.cwd,
1314 args: ["update-ref", "-d", checkpointRef],
1315 allowNonZeroExit: true,
1316 }),
1317 { discard: true },
1318 );
1319 },
1320 ),
1321 };
1322​
1323 return {
1324 capabilities,
1325 execute,
1326 checkpoints,
1327 detectRepository,
1328 isInsideWorkTree,
1329 listWorkspaceFiles,
1330 listRemotes,
1331 filterIgnoredPaths,
1332 initRepository,
1333 };
1334});
1335​
1336export const makeVcsDriver = Effect.gen(function* () {
1337 const driver = yield* makeVcsDriverShape();
1338 return VcsDriver.VcsDriver.of(driver);
1339});
1340​
1341export const make = Effect.gen(function* () {
1342 const git = yield* makeGitVcsDriverCore();
1343 return GitVcsDriver.of(git);
1344});
1345​
1346export const layerVcs = Layer.effect(VcsDriver.VcsDriver, makeVcsDriver);
1347export const layer = Layer.effect(GitVcsDriver, make);