Open History to see the last commit
1import fs from "node:fs";
2import os from "node:os";
3import path from "node:path";
4
5import {
6 gitPullInputSchema,
7 gitPullResultSchema,
8 gitStatusInputSchema,
9 gitStatusResultSchema,
10 type GitCheckoutInput,
11 type GitCreateBranchInput,
12 type GitCreateWorktreeInput,
13 type GitCreateWorktreeResult,
14 type GitInitInput,
15 type GitListBranchesInput,
16 type GitListBranchesResult,
17 type GitPullInput,
18 type GitPullResult,
19 type GitRemoveWorktreeInput,
20 type GitStatusInput,
21 type GitStatusResult,
22} from "@t3tools/contracts";
23import { type ProcessRunResult, runProcess } from "./processRunner";
24
25export interface TerminalCommandInput {
26 command: string;
27 cwd: string;
28 timeoutMs?: number;
29 maxOutputBytes?: number;
30}
31
32export type TerminalCommandResult = ProcessRunResult;
33
34export interface GitStatusDetails extends Omit<GitStatusResult, "openPr"> {
35 upstreamRef: string | null;
36}
37
38export interface GitPreparedCommitContext {
39 stagedSummary: string;
40 stagedPatch: string;
41}
42
43export interface GitPushResult {
44 status: "pushed" | "skipped_up_to_date";
45 branch: string;
46 upstreamBranch?: string | undefined;
47 setUpstream?: boolean | undefined;
48}
49
50export interface GitRangeContext {
51 commitSummary: string;
52 diffSummary: string;
53 diffPatch: string;
54}
55
56interface RunGitOptions {
57 timeoutMs?: number | undefined;
58 allowNonZeroExit?: boolean | undefined;
59}
60
61interface ExecuteGitOptions {
62 timeoutMs?: number | undefined;
63 allowNonZeroExit?: boolean | undefined;
64 fallbackErrorMessage?: string | undefined;
65}
66
67const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
68
69/** Spawn git directly with an argv array — no shell, no quoting needed. */
70function runGit(
71 args: readonly string[],
72 cwd: string,
73 timeoutMs = 30_000,
74): Promise<ProcessRunResult> {
75 return runProcess("git", args, {
76 cwd,
77 timeoutMs,
78 allowNonZeroExit: true,
79 maxBufferBytes: DEFAULT_MAX_OUTPUT_BYTES,
80 outputMode: "truncate",
81 });
82}
83
84function trimStdout(value: string): string {
85 return value.trim();
86}
87
88function parseBranchAb(value: string): { ahead: number; behind: number } {
89 const match = value.match(/^\+(\d+)\s+-(\d+)$/);
90 if (!match) return { ahead: 0, behind: 0 };
91 return {
92 ahead: Number(match[1] ?? "0"),
93 behind: Number(match[2] ?? "0"),
94 };
95}
96
97function parseNumstatEntries(
98 stdout: string,
99): Array<{ path: string; insertions: number; deletions: number }> {
100 const entries: Array<{ path: string; insertions: number; deletions: number }> = [];
101 for (const line of stdout.split(/\r?\n/g)) {
102 if (line.trim().length === 0) continue;
103 const [addedRaw, deletedRaw, ...pathParts] = line.split("\t");
104 const rawPath =
105 pathParts.length > 1 ? (pathParts.at(-1) ?? "").trim() : pathParts.join("\t").trim();
106 if (rawPath.length === 0) continue;
107 const added = Number.parseInt(addedRaw ?? "0", 10);
108 const deleted = Number.parseInt(deletedRaw ?? "0", 10);
109 const renameArrowIndex = rawPath.indexOf(" => ");
110 const normalizedPath =
111 renameArrowIndex >= 0 ? rawPath.slice(renameArrowIndex + " => ".length).trim() : rawPath;
112 entries.push({
113 path: normalizedPath.length > 0 ? normalizedPath : rawPath,
114 insertions: Number.isFinite(added) ? added : 0,
115 deletions: Number.isFinite(deleted) ? deleted : 0,
116 });
117 }
118 return entries;
119}
120
121function parsePorcelainPath(line: string): string | null {
122 if (line.startsWith("? ") || line.startsWith("! ")) {
123 const simple = line.slice(2).trim();
124 return simple.length > 0 ? simple : null;
125 }
126
127 if (!(line.startsWith("1 ") || line.startsWith("2 ") || line.startsWith("u "))) {
128 return null;
129 }
130
131 const tabIndex = line.indexOf("\t");
132 if (tabIndex >= 0) {
133 const fromTab = line.slice(tabIndex + 1);
134 const [path] = fromTab.split("\t");
135 return path?.trim().length ? path.trim() : null;
136 }
137
138 const parts = line.trim().split(/\s+/g);
139 const path = parts.at(-1) ?? "";
140 return path.length > 0 ? path : null;
141}
142
143function commandLabel(args: readonly string[]): string {
144 return `git ${args.join(" ")}`;
145}
146
147function normalizeGitSpawnError(cwd: string, error: unknown): Error {
148 if (!(error instanceof Error)) {
149 return new Error("Failed to run git command.");
150 }
151 if (!fs.existsSync(cwd)) {
152 return new Error(`Working directory does not exist: ${cwd}`);
153 }
154 if (error.message.includes("Command not found: git")) {
155 return new Error("Git is required but not available on PATH.");
156 }
157 return new Error(`Failed to run git command: ${error.message}`);
158}
159
160function normalizeGitExecutionError(args: readonly string[], result: TerminalCommandResult): Error {
161 const stderr = result.stderr.trim();
162 if (stderr.toLowerCase().includes("not a git repository")) {
163 return new Error("Current folder is not a git repository.");
164 }
165 if (result.timedOut) {
166 return new Error(`${commandLabel(args)} timed out.`);
167 }
168 const detail =
169 stderr.length > 0 ? stderr : `code=${result.code ?? "null"}, signal=${result.signal ?? "null"}`;
170 return new Error(`${commandLabel(args)} failed: ${detail}`);
171}
172
173async function runGitOrThrow(
174 cwd: string,
175 args: readonly string[],
176 options: RunGitOptions = {},
177): Promise<TerminalCommandResult> {
178 let result: TerminalCommandResult;
179 try {
180 result = await runGit(args, cwd, options.timeoutMs);
181 } catch (error) {
182 throw normalizeGitSpawnError(cwd, error);
183 }
184
185 if (result.timedOut) {
186 throw normalizeGitExecutionError(args, result);
187 }
188 if (!options.allowNonZeroExit && result.code !== 0) {
189 throw normalizeGitExecutionError(args, result);
190 }
191 return result;
192}
193
194async function executeGit(
195 cwd: string,
196 args: readonly string[],
197 options: ExecuteGitOptions = {},
198): Promise<TerminalCommandResult> {
199 const result = await runGitOrThrow(cwd, args, {
200 timeoutMs: options.timeoutMs,
201 allowNonZeroExit: true,
202 });
203
204 if (options.allowNonZeroExit || result.code === 0) {
205 return result;
206 }
207
208 const stderr = result.stderr.trim();
209 if (stderr.length > 0) {
210 throw new Error(stderr);
211 }
212 if (options.fallbackErrorMessage) {
213 throw new Error(options.fallbackErrorMessage);
214 }
215 throw normalizeGitExecutionError(args, result);
216}
217
218export class GitCoreService {
219 async status(raw: GitStatusInput): Promise<GitStatusResult> {
220 const input = gitStatusInputSchema.parse(raw);
221 const details = await this.statusDetails(input.cwd);
222 return gitStatusResultSchema.parse({
223 branch: details.branch,
224 hasWorkingTreeChanges: details.hasWorkingTreeChanges,
225 workingTree: details.workingTree,
226 hasUpstream: details.hasUpstream,
227 aheadCount: details.aheadCount,
228 behindCount: details.behindCount,
229 openPr: null,
230 });
231 }
232
233 async statusDetails(cwd: string): Promise<GitStatusDetails> {
234 const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([
235 this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),
236 this.gitStdout(cwd, ["diff", "--numstat"]),
237 this.gitStdout(cwd, ["diff", "--cached", "--numstat"]),
238 ]);
239
240 let branch: string | null = null;
241 let upstreamRef: string | null = null;
242 let aheadCount = 0;
243 let behindCount = 0;
244 let hasWorkingTreeChanges = false;
245 const changedFilesWithoutNumstat = new Set<string>();
246
247 for (const line of statusStdout.split(/\r?\n/g)) {
248 if (line.startsWith("# branch.head ")) {
249 const value = line.slice("# branch.head ".length).trim();
250 branch = value.startsWith("(") ? null : value;
251 continue;
252 }
253 if (line.startsWith("# branch.upstream ")) {
254 const value = line.slice("# branch.upstream ".length).trim();
255 upstreamRef = value.length > 0 ? value : null;
256 continue;
257 }
258 if (line.startsWith("# branch.ab ")) {
259 const value = line.slice("# branch.ab ".length).trim();
260 const parsed = parseBranchAb(value);
261 aheadCount = parsed.ahead;
262 behindCount = parsed.behind;
263 continue;
264 }
265 if (line.trim().length > 0 && !line.startsWith("#")) {
266 hasWorkingTreeChanges = true;
267 const pathValue = parsePorcelainPath(line);
268 if (pathValue) changedFilesWithoutNumstat.add(pathValue);
269 }
270 }
271 const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
272 const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
273 const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
274 for (const entry of [...stagedEntries, ...unstagedEntries]) {
275 const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 };
276 existing.insertions += entry.insertions;
277 existing.deletions += entry.deletions;
278 fileStatMap.set(entry.path, existing);
279 }
280
281 let insertions = 0;
282 let deletions = 0;
283 const files = Array.from(fileStatMap.entries())
284 .map(([path, stat]) => {
285 insertions += stat.insertions;
286 deletions += stat.deletions;
287 return { path, insertions: stat.insertions, deletions: stat.deletions };
288 })
289 .toSorted((a, b) => a.path.localeCompare(b.path));
290
291 for (const filePath of changedFilesWithoutNumstat) {
292 if (fileStatMap.has(filePath)) continue;
293 files.push({ path: filePath, insertions: 0, deletions: 0 });
294 }
295 files.sort((a, b) => a.path.localeCompare(b.path));
296
297 return {
298 branch,
299 upstreamRef,
300 hasWorkingTreeChanges,
301 workingTree: {
302 files,
303 insertions,
304 deletions,
305 },
306 hasUpstream: upstreamRef !== null,
307 aheadCount,
308 behindCount,
309 };
310 }
311
312 async prepareCommitContext(cwd: string): Promise<GitPreparedCommitContext | null> {
313 await this.git(cwd, ["add", "-A"]);
314
315 const stagedSummary = await this.gitStdout(cwd, ["diff", "--cached", "--name-status"]);
316 if (trimStdout(stagedSummary).length === 0) {
317 return null;
318 }
319
320 const stagedPatch = await this.gitStdout(cwd, ["diff", "--cached", "--patch", "--minimal"]);
321
322 return {
323 stagedSummary,
324 stagedPatch,
325 };
326 }
327
328 async commit(cwd: string, subject: string, body: string): Promise<{ commitSha: string }> {
329 const args = ["commit", "-m", subject];
330 const trimmedBody = body.trim();
331 if (trimmedBody.length > 0) {
332 args.push("-m", trimmedBody);
333 }
334 await this.git(cwd, args);
335 const commitSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"]));
336 return { commitSha };
337 }
338
339 async pushCurrentBranch(cwd: string, fallbackBranch: string | null): Promise<GitPushResult> {
340 const details = await this.statusDetails(cwd);
341 const branch = details.branch ?? fallbackBranch;
342 if (!branch) {
343 throw new Error("Cannot push from detached HEAD.");
344 }
345
346 if (details.hasUpstream && details.aheadCount === 0 && details.behindCount === 0) {
347 return {
348 status: "skipped_up_to_date",
349 branch,
350 ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
351 };
352 }
353
354 if (!details.hasUpstream) {
355 await this.git(cwd, ["push", "-u", "origin", branch]);
356 return {
357 status: "pushed",
358 branch,
359 upstreamBranch: `origin/${branch}`,
360 setUpstream: true,
361 };
362 }
363
364 await this.git(cwd, ["push"]);
365 return {
366 status: "pushed",
367 branch,
368 ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
369 setUpstream: false,
370 };
371 }
372
373 async pullCurrentBranch(cwd: string): Promise<GitPullResult> {
374 const details = await this.statusDetails(cwd);
375 const branch = details.branch;
376 if (!branch) {
377 throw new Error("Cannot pull from detached HEAD.");
378 }
379 if (!details.hasUpstream) {
380 throw new Error("Current branch has no upstream configured. Push with upstream first.");
381 }
382 const beforeSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
383 await executeGit(cwd, ["pull", "--ff-only"], {
384 timeoutMs: 30_000,
385 fallbackErrorMessage: "git pull failed",
386 });
387 const afterSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
388 const refreshed = await this.statusDetails(cwd);
389 return gitPullResultSchema.parse({
390 status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",
391 branch,
392 ...(refreshed.upstreamRef ? { upstreamBranch: refreshed.upstreamRef } : {}),
393 });
394 }
395
396 async readRangeContext(cwd: string, baseBranch: string): Promise<GitRangeContext> {
397 const range = `${baseBranch}..HEAD`;
398 const [commitSummary, diffSummary, diffPatch] = await Promise.all([
399 this.gitStdout(cwd, ["log", "--oneline", range]),
400 this.gitStdout(cwd, ["diff", "--stat", range]),
401 this.gitStdout(cwd, ["diff", "--patch", "--minimal", range]),
402 ]);
403
404 return {
405 commitSummary,
406 diffSummary,
407 diffPatch,
408 };
409 }
410
411 async readConfigValue(cwd: string, key: string): Promise<string | null> {
412 const stdout = await this.gitStdout(cwd, ["config", "--get", key], true);
413 const value = trimStdout(stdout);
414 return value.length > 0 ? value : null;
415 }
416
417 private async readBranchRecency(cwd: string): Promise<Map<string, number>> {
418 const branchRecency = await executeGit(
419 cwd,
420 ["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
421 {
422 timeoutMs: 15_000,
423 allowNonZeroExit: true,
424 },
425 );
426
427 const branchLastCommit = new Map<string, number>();
428 if (branchRecency.code !== 0) {
429 return branchLastCommit;
430 }
431
432 for (const line of branchRecency.stdout.split("\n")) {
433 if (line.length === 0) {
434 continue;
435 }
436 const [name, lastCommitRaw] = line.split("\t");
437 if (!name) {
438 continue;
439 }
440 const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10);
441 branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0);
442 }
443
444 return branchLastCommit;
445 }
446
447 async listBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
448 const branchRecencyPromise = this.readBranchRecency(input.cwd).catch(
449 () => new Map<string, number>(),
450 );
451 const result = await executeGit(input.cwd, ["branch", "--no-color"], {
452 timeoutMs: 10_000,
453 allowNonZeroExit: true,
454 });
455
456 if (result.code !== 0) {
457 const stderr = result.stderr.trim();
458 if (stderr.toLowerCase().includes("not a git repository")) {
459 return { branches: [], isRepo: false };
460 }
461 throw new Error(stderr || "git branch failed");
462 }
463
464 const [defaultRef, worktreeList, branchLastCommit] = await Promise.all([
465 executeGit(input.cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"], {
466 timeoutMs: 5_000,
467 allowNonZeroExit: true,
468 }),
469 executeGit(input.cwd, ["worktree", "list", "--porcelain"], {
470 timeoutMs: 5_000,
471 allowNonZeroExit: true,
472 }),
473 branchRecencyPromise,
474 ]);
475 const defaultBranch =
476 defaultRef.code === 0
477 ? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
478 : null;
479
480 const worktreeMap = new Map<string, string>();
481 if (worktreeList.code === 0) {
482 let currentPath: string | null = null;
483 for (const line of worktreeList.stdout.split("\n")) {
484 if (line.startsWith("worktree ")) {
485 const candidatePath = line.slice("worktree ".length);
486 currentPath = fs.existsSync(candidatePath) ? candidatePath : null;
487 } else if (line.startsWith("branch refs/heads/") && currentPath) {
488 worktreeMap.set(line.slice("branch refs/heads/".length), currentPath);
489 } else if (line === "") {
490 currentPath = null;
491 }
492 }
493 }
494
495 const branches = result.stdout
496 .split("\n")
497 .map((line) => line.trim())
498 .filter((line) => line.length > 0)
499 .map((line) => {
500 const name = line.replace(/^[*+]\s+/, "");
501 return {
502 name,
503 current: line.startsWith("* "),
504 isDefault: name === defaultBranch,
505 worktreePath: worktreeMap.get(name) ?? null,
506 };
507 })
508 .toSorted((a, b) => {
509 const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
510 const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
511 if (aPriority !== bPriority) return aPriority - bPriority;
512
513 const aLastCommit = branchLastCommit.get(a.name) ?? 0;
514 const bLastCommit = branchLastCommit.get(b.name) ?? 0;
515 if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
516 return a.name.localeCompare(b.name);
517 });
518
519 return { branches, isRepo: true };
520 }
521
522 async createWorktree(input: GitCreateWorktreeInput): Promise<GitCreateWorktreeResult> {
523 const sanitizedBranch = input.newBranch.replace(/\//g, "-");
524 const repoName = path.basename(input.cwd);
525 const worktreePath =
526 input.path ?? path.join(os.homedir(), ".t3", "worktrees", repoName, sanitizedBranch);
527
528 await executeGit(
529 input.cwd,
530 ["worktree", "add", "-b", input.newBranch, worktreePath, input.branch],
531 { fallbackErrorMessage: "git worktree add failed" },
532 );
533
534 return {
535 worktree: {
536 path: worktreePath,
537 branch: input.newBranch,
538 },
539 };
540 }
541
542 async removeWorktree(input: GitRemoveWorktreeInput): Promise<void> {
543 await executeGit(input.cwd, ["worktree", "remove", input.path], {
544 timeoutMs: 15_000,
545 fallbackErrorMessage: "git worktree remove failed",
546 });
547 }
548
549 async createBranch(input: GitCreateBranchInput): Promise<void> {
550 await executeGit(input.cwd, ["branch", input.branch], {
551 timeoutMs: 10_000,
552 fallbackErrorMessage: "git branch create failed",
553 });
554 }
555
556 private async refreshCheckedOutBranchUpstream(cwd: string): Promise<void> {
557 const upstreamRef = trimStdout(
558 await this.gitStdout(
559 cwd,
560 ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"],
561 true,
562 ),
563 );
564 if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") {
565 return;
566 }
567
568 const separatorIndex = upstreamRef.indexOf("/");
569 if (separatorIndex <= 0) {
570 return;
571 }
572 const remoteName = upstreamRef.slice(0, separatorIndex);
573 const upstreamBranch = upstreamRef.slice(separatorIndex + 1);
574 if (remoteName.length === 0) {
575 return;
576 }
577 if (upstreamBranch.length === 0) {
578 return;
579 }
580
581 const refspec = `+refs/heads/${upstreamBranch}:refs/remotes/${upstreamRef}`;
582 await this.git(cwd, ["fetch", "--quiet", "--no-tags", remoteName, refspec], true);
583 }
584
585 async checkoutBranch(input: GitCheckoutInput): Promise<void> {
586 await executeGit(input.cwd, ["checkout", input.branch], {
587 timeoutMs: 10_000,
588 fallbackErrorMessage: "git checkout failed",
589 });
590 // Refresh upstream refs in the background so checkout remains responsive.
591 void this.refreshCheckedOutBranchUpstream(input.cwd).catch(() => undefined);
592 }
593
594 async initRepo(input: GitInitInput): Promise<void> {
595 await executeGit(input.cwd, ["init"], {
596 timeoutMs: 10_000,
597 fallbackErrorMessage: "git init failed",
598 });
599 }
600
601 async git(cwd: string, args: readonly string[], allowNonZeroExit = false): Promise<void> {
602 await executeGit(cwd, args, { allowNonZeroExit });
603 }
604
605 async gitStdout(cwd: string, args: readonly string[], allowNonZeroExit = false): Promise<string> {
606 const result = await executeGit(cwd, args, { allowNonZeroExit });
607 return result.stdout;
608 }
609}
610
611const defaultGitCoreService = new GitCoreService();
612
613export async function runTerminalCommand(
614 input: TerminalCommandInput,
615): Promise<TerminalCommandResult> {
616 const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
617 const shellPath =
618 process.platform === "win32"
619 ? (process.env.ComSpec ?? "cmd.exe")
620 : (process.env.SHELL ?? "/bin/sh");
621
622 const args =
623 process.platform === "win32" ? ["/d", "/s", "/c", input.command] : ["-lc", input.command];
624
625 const result = await runProcess(shellPath, args, {
626 cwd: input.cwd,
627 timeoutMs: input.timeoutMs ?? 30_000,
628 allowNonZeroExit: true,
629 maxBufferBytes: maxOutputBytes,
630 outputMode: "truncate",
631 });
632
633 if (!result.stdoutTruncated && !result.stderrTruncated) {
634 return result;
635 }
636
637 return {
638 ...result,
639 stderr: `${result.stderr}\n[output truncated at ${maxOutputBytes} bytes]`,
640 };
641}
642
643export async function listGitBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
644 return defaultGitCoreService.listBranches(input);
645}
646
647export async function pullGitBranch(raw: GitPullInput): Promise<GitPullResult> {
648 const input = gitPullInputSchema.parse(raw);
649 return defaultGitCoreService.pullCurrentBranch(input.cwd);
650}
651
652export async function createGitWorktree(
653 input: GitCreateWorktreeInput,
654): Promise<GitCreateWorktreeResult> {
655 return defaultGitCoreService.createWorktree(input);
656}
657
658export async function removeGitWorktree(input: GitRemoveWorktreeInput): Promise<void> {
659 await defaultGitCoreService.removeWorktree(input);
660}
661
662export async function createGitBranch(input: GitCreateBranchInput): Promise<void> {
663 await defaultGitCoreService.createBranch(input);
664}
665
666export async function checkoutGitBranch(input: GitCheckoutInput): Promise<void> {
667 await defaultGitCoreService.checkoutBranch(input);
668}
669
670export async function initGitRepo(input: GitInitInput): Promise<void> {
671 await defaultGitCoreService.initRepo(input);
672}