Open History to see the last commit
1import { Context, DateTime, Effect, Layer, Option } from "effect";
2import { ChildProcessSpawner } from "effect/unstable/process";
3
4import {
5 GitCommandError,
6 VcsProcessExitError,
7 type VcsSwitchRefInput,
8 type VcsSwitchRefResult,
9 type VcsCreateRefInput,
10 type VcsCreateRefResult,
11 type VcsCreateWorktreeInput,
12 type VcsCreateWorktreeResult,
13 type VcsInitInput,
14 type VcsListRefsInput,
15 type VcsListRefsResult,
16 type VcsPullResult,
17 type VcsRemoveWorktreeInput,
18 type VcsStatusInput,
19 type VcsStatusResult,
20} from "@t3tools/contracts";
21import * as GitVcsDriverCore from "./GitVcsDriverCore.ts";
22import * as VcsDriver from "./VcsDriver.ts";
23import * as VcsProcess from "./VcsProcess.ts";
24
25export interface ExecuteGitInput {
26 readonly operation: string;
27 readonly cwd: string;
28 readonly args: ReadonlyArray<string>;
29 readonly stdin?: string;
30 readonly env?: NodeJS.ProcessEnv;
31 readonly allowNonZeroExit?: boolean;
32 readonly timeoutMs?: number;
33 readonly maxOutputBytes?: number;
34 readonly truncateOutputAtMaxBytes?: boolean;
35 readonly progress?: ExecuteGitProgress;
36}
37
38export interface ExecuteGitResult {
39 readonly exitCode: ChildProcessSpawner.ExitCode;
40 readonly stdout: string;
41 readonly stderr: string;
42 readonly stdoutTruncated: boolean;
43 readonly stderrTruncated: boolean;
44}
45
46export interface GitStatusDetails {
47 isRepo: boolean;
48 sourceControlProvider?: VcsStatusResult["sourceControlProvider"];
49 hasOriginRemote: boolean;
50 isDefaultBranch: boolean;
51 branch: string | null;
52 upstreamRef: string | null;
53 hasWorkingTreeChanges: boolean;
54 workingTree: VcsStatusResult["workingTree"];
55 hasUpstream: boolean;
56 aheadCount: number;
57 behindCount: number;
58 aheadOfDefaultCount: number;
59}
60
61export interface GitPreparedCommitContext {
62 stagedSummary: string;
63 stagedPatch: string;
64}
65
66export interface ExecuteGitProgress {
67 readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;
68 readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;
69 readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
70 readonly onHookFinished?: (input: {
71 hookName: string;
72 exitCode: number | null;
73 durationMs: number | null;
74 }) => Effect.Effect<void, never>;
75}
76
77export interface GitCommitProgress {
78 readonly onOutputLine?: (input: {
79 stream: "stdout" | "stderr";
80 text: string;
81 }) => Effect.Effect<void, never>;
82 readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
83 readonly onHookFinished?: (input: {
84 hookName: string;
85 exitCode: number | null;
86 durationMs: number | null;
87 }) => Effect.Effect<void, never>;
88}
89
90export interface GitCommitOptions {
91 readonly timeoutMs?: number;
92 readonly progress?: GitCommitProgress;
93}
94
95export interface GitPushResult {
96 status: "pushed" | "skipped_up_to_date";
97 branch: string;
98 upstreamBranch?: string | undefined;
99 setUpstream?: boolean | undefined;
100}
101
102export interface GitRangeContext {
103 commitSummary: string;
104 diffSummary: string;
105 diffPatch: string;
106}
107
108export interface GitRenameBranchInput {
109 cwd: string;
110 oldBranch: string;
111 newBranch: string;
112}
113
114export interface GitRenameBranchResult {
115 branch: string;
116}
117
118export interface GitFetchPullRequestBranchInput {
119 cwd: string;
120 prNumber: number;
121 branch: string;
122}
123
124export interface GitEnsureRemoteInput {
125 cwd: string;
126 preferredName: string;
127 url: string;
128}
129
130export interface GitFetchRemoteBranchInput {
131 cwd: string;
132 remoteName: string;
133 remoteBranch: string;
134 localBranch: string;
135}
136
137export interface GitFetchRemoteTrackingBranchInput {
138 cwd: string;
139 remoteName: string;
140 remoteBranch: string;
141}
142
143export interface GitSetBranchUpstreamInput {
144 cwd: string;
145 branch: string;
146 remoteName: string;
147 remoteBranch: string;
148}
149
150export interface GitVcsDriverShape {
151 readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
152 readonly status: (input: VcsStatusInput) => Effect.Effect<VcsStatusResult, GitCommandError>;
153 readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
154 readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
155 readonly prepareCommitContext: (
156 cwd: string,
157 filePaths?: readonly string[],
158 ) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
159 readonly commit: (
160 cwd: string,
161 subject: string,
162 body: string,
163 options?: GitCommitOptions,
164 ) => Effect.Effect<{ commitSha: string }, GitCommandError>;
165 readonly pushCurrentBranch: (
166 cwd: string,
167 fallbackBranch: string | null,
168 options?: { readonly remoteName?: string | null },
169 ) => Effect.Effect<GitPushResult, GitCommandError>;
170 readonly readRangeContext: (
171 cwd: string,
172 baseRef: string,
173 ) => Effect.Effect<GitRangeContext, GitCommandError>;
174 readonly readConfigValue: (
175 cwd: string,
176 key: string,
177 ) => Effect.Effect<string | null, GitCommandError>;
178 readonly listRefs: (input: VcsListRefsInput) => Effect.Effect<VcsListRefsResult, GitCommandError>;
179 readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
180 readonly createWorktree: (
181 input: VcsCreateWorktreeInput,
182 ) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
183 readonly fetchPullRequestBranch: (
184 input: GitFetchPullRequestBranchInput,
185 ) => Effect.Effect<void, GitCommandError>;
186 readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
187 readonly resolvePrimaryRemoteName: (cwd: string) => Effect.Effect<string, GitCommandError>;
188 readonly fetchRemoteBranch: (
189 input: GitFetchRemoteBranchInput,
190 ) => Effect.Effect<void, GitCommandError>;
191 readonly fetchRemoteTrackingBranch: (
192 input: GitFetchRemoteTrackingBranchInput,
193 ) => Effect.Effect<void, GitCommandError>;
194 readonly setBranchUpstream: (
195 input: GitSetBranchUpstreamInput,
196 ) => Effect.Effect<void, GitCommandError>;
197 readonly removeWorktree: (input: VcsRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
198 readonly renameBranch: (
199 input: GitRenameBranchInput,
200 ) => Effect.Effect<GitRenameBranchResult, GitCommandError>;
201 readonly createRef: (
202 input: VcsCreateRefInput,
203 ) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
204 readonly switchRef: (
205 input: VcsSwitchRefInput,
206 ) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
207 readonly initRepo: (input: VcsInitInput) => Effect.Effect<void, GitCommandError>;
208 readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
209}
210
211export class GitVcsDriver extends Context.Service<GitVcsDriver, GitVcsDriverShape>()(
212 "t3/vcs/GitVcsDriver",
213) {}
214
215const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
216const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
217const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [
218 "-c",
219 "core.fsmonitor=false",
220 "-c",
221 "core.untrackedCache=false",
222] as const;
223
224const nowFreshness = Effect.fn("GitVcsDriver.nowFreshness")(function* () {
225 const now = yield* DateTime.now;
226 return {
227 source: "live-local" as const,
228 observedAt: now,
229 expiresAt: Option.none(),
230 };
231});
232
233function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
234 const parts = input.split("\0");
235 if (parts.length === 0) return [];
236
237 if (truncated && parts[parts.length - 1]?.length) {
238 parts.pop();
239 }
240
241 return parts.filter((value) => value.length > 0);
242}
243
244function chunkPathsForGitCheckIgnore(relativePaths: ReadonlyArray<string>): string[][] {
245 const chunks: string[][] = [];
246 let chunk: string[] = [];
247 let chunkBytes = 0;
248
249 for (const relativePath of relativePaths) {
250 const relativePathBytes = Buffer.byteLength(relativePath) + 1;
251 if (chunk.length > 0 && chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
252 chunks.push(chunk);
253 chunk = [];
254 chunkBytes = 0;
255 }
256
257 chunk.push(relativePath);
258 chunkBytes += relativePathBytes;
259
260 if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
261 chunks.push(chunk);
262 chunk = [];
263 chunkBytes = 0;
264 }
265 }
266
267 if (chunk.length > 0) {
268 chunks.push(chunk);
269 }
270
271 return chunks;
272}
273
274function parseGitRemoteVerboseOutput(
275 output: string,
276): Map<string, { url?: string; pushUrl?: string }> {
277 const remotes = new Map<string, { url?: string; pushUrl?: string }>();
278 for (const line of output.split("\n")) {
279 const trimmed = line.trim();
280 if (trimmed.length === 0) {
281 continue;
282 }
283
284 const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed);
285 if (!match) {
286 continue;
287 }
288
289 const name = match[1];
290 const url = match[2];
291 const direction = match[3];
292 if (!name || !url || !direction) {
293 continue;
294 }
295 const remote = remotes.get(name) ?? {};
296 if (direction === "fetch") {
297 remote.url = url;
298 } else {
299 remote.pushUrl = url;
300 }
301 remotes.set(name, remote);
302 }
303 return remotes;
304}
305
306const gitCommand = (
307 process: VcsProcess.VcsProcessShape,
308 operation: string,
309 cwd: string,
310 args: ReadonlyArray<string>,
311 options?: {
312 readonly stdin?: string;
313 readonly env?: NodeJS.ProcessEnv;
314 readonly allowNonZeroExit?: boolean;
315 readonly timeoutMs?: number;
316 readonly maxOutputBytes?: number;
317 readonly truncateOutputAtMaxBytes?: boolean;
318 },
319) =>
320 process.run({
321 operation,
322 command: "git",
323 args,
324 cwd,
325 ...(options?.stdin !== undefined ? { stdin: options.stdin } : {}),
326 ...(options?.env !== undefined ? { env: options.env } : {}),
327 ...(options?.allowNonZeroExit !== undefined
328 ? { allowNonZeroExit: options.allowNonZeroExit }
329 : {}),
330 ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
331 ...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
332 ...(options?.truncateOutputAtMaxBytes !== undefined
333 ? { truncateOutputAtMaxBytes: options.truncateOutputAtMaxBytes }
334 : {}),
335 });
336
337export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* () {
338 const process = yield* VcsProcess.VcsProcess;
339 const capabilities = {
340 kind: "git" as const,
341 supportsWorktrees: true,
342 supportsBookmarks: false,
343 supportsAtomicSnapshot: false,
344 supportsPushDefaultRemote: true,
345 ignoreClassifier: "native" as const,
346 };
347
348 const isInsideWorkTree: VcsDriver.VcsDriverShape["isInsideWorkTree"] = (cwd) =>
349 gitCommand(
350 process,
351 "GitVcsDriver.isInsideWorkTree",
352 cwd,
353 ["rev-parse", "--is-inside-work-tree"],
354 {
355 allowNonZeroExit: true,
356 timeoutMs: 5_000,
357 maxOutputBytes: 4_096,
358 },
359 ).pipe(Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"));
360
361 const execute: VcsDriver.VcsDriverShape["execute"] = (input) =>
362 gitCommand(process, input.operation, input.cwd, input.args, {
363 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
364 ...(input.env !== undefined ? { env: input.env } : {}),
365 ...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}),
366 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
367 ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
368 ...(input.truncateOutputAtMaxBytes !== undefined
369 ? { truncateOutputAtMaxBytes: input.truncateOutputAtMaxBytes }
370 : {}),
371 });
372
373 const detectRepository: VcsDriver.VcsDriverShape["detectRepository"] = Effect.fn(
374 "detectRepository",
375 )(function* (cwd) {
376 if (!(yield* isInsideWorkTree(cwd))) {
377 return null;
378 }
379
380 const root = yield* gitCommand(process, "GitVcsDriver.detectRepository.root", cwd, [
381 "rev-parse",
382 "--show-toplevel",
383 ]);
384 const gitCommonDir = yield* gitCommand(
385 process,
386 "GitVcsDriver.detectRepository.commonDir",
387 cwd,
388 ["rev-parse", "--git-common-dir"],
389 ).pipe(Effect.catch(() => Effect.succeed(null)));
390
391 return {
392 kind: "git" as const,
393 rootPath: root.stdout.trim(),
394 metadataPath: gitCommonDir?.stdout.trim() || null,
395 freshness: yield* nowFreshness(),
396 };
397 });
398
399 const listWorkspaceFiles: VcsDriver.VcsDriverShape["listWorkspaceFiles"] = (cwd) =>
400 gitCommand(
401 process,
402 "GitVcsDriver.listWorkspaceFiles",
403 cwd,
404 [
405 ...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
406 "ls-files",
407 "--cached",
408 "--others",
409 "--exclude-standard",
410 "-z",
411 ],
412 {
413 allowNonZeroExit: true,
414 timeoutMs: 20_000,
415 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
416 truncateOutputAtMaxBytes: true,
417 },
418 ).pipe(
419 Effect.flatMap((result) =>
420 result.exitCode === 0
421 ? Effect.gen(function* () {
422 const freshness = yield* nowFreshness();
423 return {
424 paths: splitNullSeparatedPaths(result.stdout, result.stdoutTruncated),
425 truncated: result.stdoutTruncated,
426 freshness,
427 };
428 })
429 : Effect.fail(
430 new VcsProcessExitError({
431 operation: "GitVcsDriver.listWorkspaceFiles",
432 command: "git ls-files",
433 cwd,
434 exitCode: result.exitCode,
435 detail: result.stderr.trim() || "git ls-files failed",
436 }),
437 ),
438 ),
439 );
440
441 const listRemotes: VcsDriver.VcsDriverShape["listRemotes"] = Effect.fn("listRemotes")(
442 function* (cwd) {
443 const result = yield* gitCommand(process, "GitVcsDriver.listRemotes", cwd, ["remote", "-v"], {
444 allowNonZeroExit: true,
445 timeoutMs: 5_000,
446 maxOutputBytes: 64 * 1024,
447 });
448
449 if (result.exitCode !== 0) {
450 return yield* new VcsProcessExitError({
451 operation: "GitVcsDriver.listRemotes",
452 command: "git remote -v",
453 cwd,
454 exitCode: result.exitCode,
455 detail: result.stderr.trim() || "git remote -v failed",
456 });
457 }
458
459 const parsed = parseGitRemoteVerboseOutput(result.stdout);
460 const remotes = Array.from(parsed.entries()).flatMap(([name, remote]) => {
461 if (!remote.url) {
462 return [];
463 }
464 return [
465 {
466 name,
467 url: remote.url,
468 pushUrl: remote.pushUrl ? Option.some(remote.pushUrl) : Option.none(),
469 isPrimary: name === "origin",
470 },
471 ];
472 });
473
474 return {
475 remotes,
476 freshness: yield* nowFreshness(),
477 };
478 },
479 );
480
481 const filterIgnoredPaths: VcsDriver.VcsDriverShape["filterIgnoredPaths"] = Effect.fn(
482 "filterIgnoredPaths",
483 )(function* (cwd, relativePaths) {
484 if (relativePaths.length === 0) {
485 return relativePaths;
486 }
487
488 const ignoredPaths = new Set<string>();
489 const chunks = chunkPathsForGitCheckIgnore(relativePaths);
490
491 for (const chunk of chunks) {
492 const result = yield* gitCommand(
493 process,
494 "GitVcsDriver.filterIgnoredPaths",
495 cwd,
496 [...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
497 {
498 stdin: `${chunk.join("\0")}\0`,
499 allowNonZeroExit: true,
500 timeoutMs: 20_000,
501 maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
502 truncateOutputAtMaxBytes: true,
503 },
504 );
505
506 if (result.exitCode !== 0 && result.exitCode !== 1) {
507 return yield* new VcsProcessExitError({
508 operation: "GitVcsDriver.filterIgnoredPaths",
509 command: "git check-ignore",
510 cwd,
511 exitCode: result.exitCode,
512 detail: result.stderr.trim() || "git check-ignore failed",
513 });
514 }
515
516 for (const ignoredPath of splitNullSeparatedPaths(result.stdout, result.stdoutTruncated)) {
517 ignoredPaths.add(ignoredPath);
518 }
519 }
520
521 if (ignoredPaths.size === 0) {
522 return relativePaths;
523 }
524
525 return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
526 });
527
528 const initRepository: VcsDriver.VcsDriverShape["initRepository"] = (input) =>
529 gitCommand(process, "GitVcsDriver.initRepository", input.cwd, ["init"], {
530 timeoutMs: 10_000,
531 maxOutputBytes: 64 * 1024,
532 }).pipe(Effect.asVoid);
533
534 return VcsDriver.VcsDriver.of({
535 capabilities,
536 execute,
537 detectRepository,
538 isInsideWorkTree,
539 listWorkspaceFiles,
540 listRemotes,
541 filterIgnoredPaths,
542 initRepository,
543 });
544});
545
546export const makeVcsDriver = Effect.fn("makeGitVcsDriver")(function* () {
547 const driver = yield* makeVcsDriverShape();
548 return VcsDriver.VcsDriver.of(driver);
549});
550
551export const make = Effect.fn("makeGitVcsDriverService")(function* () {
552 const git = yield* GitVcsDriverCore.makeGitVcsDriverCore();
553 return GitVcsDriver.of(git);
554});
555
556export const vcsLayer = Layer.effect(VcsDriver.VcsDriver, makeVcsDriver());
557export const layer = Layer.effect(GitVcsDriver, make());