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

gitManager.ts

467 lines12.8 KB

1import { randomUUID } from "node:crypto";
2import fs from "node:fs/promises";
3import os from "node:os";
4import path from "node:path";
5​
6import {
7 gitRunStackedActionInputSchema,
8 gitRunStackedActionResultSchema,
9 gitStatusInputSchema,
10 type GitRunStackedActionInput,
11 type GitRunStackedActionResult,
12 type GitStatusInput,
13 type GitStatusResult,
14} from "@t3tools/contracts";
15​
16import type {
17 CommitMessageGenerationResult,
18 PrContentGenerationResult,
19 TextGenerationService,
20} from "./coreServices";
21import { CodexTextGenerator } from "./codexTextGenerator";
22import { GitCoreService } from "./git";
23import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";
24​
25const GH_CLI_TIMEOUT_MS = 30_000;
26​
27interface GitManagerDeps {
28 runProcess?: (
29 command: string,
30 args: readonly string[],
31 options?: ProcessRunOptions,
32 ) => Promise<ProcessRunResult>;
33 textGenerator?: TextGenerationService;
34 gitCore?: GitCoreService;
36​
37interface OpenPrInfo {
38 number: number;
39 title: string;
40 url: string;
41 baseRefName: string;
42 headRefName: string;
44​
45function parseOpenPrList(raw: unknown): OpenPrInfo[] {
46 if (!Array.isArray(raw)) return [];
47​
48 const parsed: OpenPrInfo[] = [];
49 for (const entry of raw) {
50 if (!entry || typeof entry !== "object") continue;
51 const record = entry as Record<string, unknown>;
52 const number = record.number;
53 const title = record.title;
54 const url = record.url;
55 const baseRefName = record.baseRefName;
56 const headRefName = record.headRefName;
57 if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
58 continue;
59 }
60 if (
61 typeof title !== "string" ||
62 typeof url !== "string" ||
63 typeof baseRefName !== "string" ||
64 typeof headRefName !== "string"
65 ) {
66 continue;
67 }
68 parsed.push({
69 number,
70 title,
71 url,
72 baseRefName,
73 headRefName,
74 });
75 }
76 return parsed;
78​
79function trimStdout(value: string): string {
80 return value.trim();
82​
83function limitContext(value: string, maxChars: number): string {
84 if (value.length <= maxChars) return value;
85 return `${value.slice(0, maxChars)}\n\n[truncated]`;
87​
88function sanitizeCommitMessage(
89 generated: CommitMessageGenerationResult,
90): CommitMessageGenerationResult {
91 const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
92 const subject = rawSubject.replace(/[.]+$/g, "").trim();
93 const safeSubject = subject.length > 0 ? subject.slice(0, 72).trimEnd() : "Update project files";
94 return {
95 subject: safeSubject,
96 body: generated.body.trim(),
97 };
99​
100function parseCustomCommitMessage(raw: string): CommitMessageGenerationResult | null {
101 const normalized = raw.replace(/\r\n/g, "\n").trim();
102 if (normalized.length === 0) {
103 return null;
104 }
105​
106 const [firstLine, ...rest] = normalized.split("\n");
107 const subject = firstLine?.trim() ?? "";
108 if (subject.length === 0) {
109 return null;
110 }
111​
112 return {
113 subject,
114 body: rest.join("\n").trim(),
115 };
117​
118function extractBranchFromRef(ref: string): string {
119 const normalized = ref.trim();
120​
121 if (normalized.startsWith("refs/remotes/")) {
122 const withoutPrefix = normalized.slice("refs/remotes/".length);
123 const firstSlash = withoutPrefix.indexOf("/");
124 if (firstSlash === -1) {
125 return withoutPrefix.trim();
126 }
127 return withoutPrefix.slice(firstSlash + 1).trim();
128 }
129​
130 const firstSlash = normalized.indexOf("/");
131 if (firstSlash === -1) {
132 return normalized;
133 }
134 return normalized.slice(firstSlash + 1).trim();
136​
137function asCommandNotFound(command: string, error: unknown): Error | undefined {
138 if (!(error instanceof Error)) return undefined;
139 if (!error.message.includes(`Command not found: ${command}`)) return undefined;
140 if (command === "gh") {
141 return new Error("GitHub CLI (`gh`) is required but not available on PATH.");
142 }
143 if (command === "codex") {
144 return new Error("Codex CLI (`codex`) is required but not available on PATH.");
145 }
146 return new Error(`${command} is required but not available on PATH.`);
148​
149function normalizeGitHubAuthError(error: unknown): Error | undefined {
150 if (!(error instanceof Error)) return undefined;
151 const lower = error.message.toLowerCase();
152 if (
153 lower.includes("authentication failed") ||
154 lower.includes("not logged in") ||
155 lower.includes("gh auth login") ||
156 lower.includes("no oauth token")
157 ) {
158 return new Error("GitHub CLI is not authenticated. Run `gh auth login` and retry.");
159 }
160 return undefined;
162​
163function toStatusOpenPr(pr: OpenPrInfo): {
164 number: number;
165 title: string;
166 url: string;
167 baseBranch: string;
168 headBranch: string;
169} {
170 return {
171 number: pr.number,
172 title: pr.title,
173 url: pr.url,
174 baseBranch: pr.baseRefName,
175 headBranch: pr.headRefName,
176 };
178​
179export class GitManager {
180 private readonly run: NonNullable<GitManagerDeps["runProcess"]>;
181 private readonly textGenerator: TextGenerationService;
182 private readonly gitCore: GitCoreService;
183​
184 constructor(deps: GitManagerDeps = {}) {
185 this.run = deps.runProcess ?? runProcess;
186 this.textGenerator = deps.textGenerator ?? new CodexTextGenerator();
187 this.gitCore = deps.gitCore ?? new GitCoreService();
188 }
189​
190 async status(raw: GitStatusInput): Promise<GitStatusResult> {
191 const input = gitStatusInputSchema.parse(raw);
192 const details = await this.gitCore.statusDetails(input.cwd);
193​
194 let openPr: ReturnType<typeof toStatusOpenPr> | null = null;
195 if (details.branch && details.hasUpstream) {
196 try {
197 const existing = await this.findOpenPr(input.cwd, details.branch);
198 if (existing) {
199 openPr = toStatusOpenPr(existing);
200 }
201 } catch {
202 // PR lookup is best-effort for status rendering.
203 }
204 }
205​
206 return {
207 branch: details.branch,
208 hasWorkingTreeChanges: details.hasWorkingTreeChanges,
209 workingTree: details.workingTree,
210 hasUpstream: details.hasUpstream,
211 aheadCount: details.aheadCount,
212 behindCount: details.behindCount,
213 openPr,
214 };
215 }
216​
217 async runStackedAction(raw: GitRunStackedActionInput): Promise<GitRunStackedActionResult> {
218 const input = gitRunStackedActionInputSchema.parse(raw);
219 const wantsPush = input.action !== "commit";
220 const wantsPr = input.action === "commit_push_pr";
221​
222 const initialStatus = await this.gitCore.statusDetails(input.cwd);
223 if (wantsPush && !initialStatus.branch) {
224 throw new Error("Cannot push from detached HEAD.");
225 }
226 if (wantsPr && !initialStatus.branch) {
227 throw new Error("Cannot create a pull request from detached HEAD.");
228 }
229​
230 const commit = await this.runCommitStep(input.cwd, initialStatus.branch, input.commitMessage);
231​
232 const push = wantsPush
233 ? await this.gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
234 : { status: "skipped_not_requested" as const };
235​
236 const pr = wantsPr
237 ? await this.runPrStep(input.cwd, initialStatus.branch)
238 : { status: "skipped_not_requested" as const };
239​
240 return gitRunStackedActionResultSchema.parse({
241 action: input.action,
242 commit,
243 push,
244 pr,
245 });
246 }
247​
248 private async runCommitStep(
249 cwd: string,
250 branch: string | null,
251 commitMessage?: string,
252 ): Promise<{
253 status: "created" | "skipped_no_changes";
254 commitSha?: string | undefined;
255 subject?: string | undefined;
256 }> {
257 const context = await this.gitCore.prepareCommitContext(cwd);
258 if (!context) {
259 return { status: "skipped_no_changes" };
260 }
261​
262 let generated: CommitMessageGenerationResult | null = parseCustomCommitMessage(
263 commitMessage ?? "",
264 );
265​
266 if (!generated) {
267 try {
268 generated = sanitizeCommitMessage(
269 await this.textGenerator.generateCommitMessage({
270 cwd,
271 branch,
272 stagedSummary: limitContext(context.stagedSummary, 8_000),
273 stagedPatch: limitContext(context.stagedPatch, 50_000),
274 }),
275 );
276 } catch (error) {
277 throw asCommandNotFound("codex", error) ?? error;
278 }
279 }
280​
281 const { commitSha } = await this.gitCore.commit(cwd, generated.subject, generated.body);
282 return {
283 status: "created",
284 commitSha,
285 subject: generated.subject,
286 };
287 }
288​
289 private async runPrStep(
290 cwd: string,
291 fallbackBranch: string | null,
292 ): Promise<{
293 status: "created" | "opened_existing" | "skipped_not_requested";
294 url?: string | undefined;
295 number?: number | undefined;
296 baseBranch?: string | undefined;
297 headBranch?: string | undefined;
298 title?: string | undefined;
299 }> {
300 const details = await this.gitCore.statusDetails(cwd);
301 const branch = details.branch ?? fallbackBranch;
302 if (!branch) {
303 throw new Error("Cannot create a pull request from detached HEAD.");
304 }
305 if (!details.hasUpstream) {
306 throw new Error("Current branch has not been pushed. Push before creating a PR.");
307 }
308​
309 const existing = await this.findOpenPr(cwd, branch);
310 if (existing) {
311 return {
312 status: "opened_existing",
313 url: existing.url,
314 number: existing.number,
315 baseBranch: existing.baseRefName,
316 headBranch: existing.headRefName,
317 title: existing.title,
318 };
319 }
320​
321 const baseBranch = await this.resolveBaseBranch(cwd, branch, details.upstreamRef);
322 const rangeContext = await this.gitCore.readRangeContext(cwd, baseBranch);
323​
324 let generated: PrContentGenerationResult;
325 try {
326 generated = await this.textGenerator.generatePrContent({
327 cwd,
328 baseBranch,
329 headBranch: branch,
330 commitSummary: limitContext(rangeContext.commitSummary, 20_000),
331 diffSummary: limitContext(rangeContext.diffSummary, 20_000),
332 diffPatch: limitContext(rangeContext.diffPatch, 60_000),
333 });
334 } catch (error) {
335 throw asCommandNotFound("codex", error) ?? error;
336 }
337​
338 const bodyFile = path.join(os.tmpdir(), `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
339 await fs.writeFile(bodyFile, generated.body, "utf8");
340​
341 try {
342 await this.runGh(cwd, [
343 "pr",
344 "create",
345 "--base",
346 baseBranch,
347 "--head",
348 branch,
349 "--title",
350 generated.title,
351 "--body-file",
352 bodyFile,
353 ]);
354 } finally {
355 try {
356 await fs.unlink(bodyFile);
357 } catch {
358 // Best-effort cleanup.
359 }
360 }
361​
362 const created = await this.findOpenPr(cwd, branch);
363​
364 if (!created) {
365 return {
366 status: "created",
367 baseBranch,
368 headBranch: branch,
369 title: generated.title,
370 };
371 }
372​
373 return {
374 status: "created",
375 url: created.url,
376 number: created.number,
377 baseBranch: created.baseRefName,
378 headBranch: created.headRefName,
379 title: created.title,
380 };
381 }
382​
383 private async findOpenPr(cwd: string, branch: string): Promise<OpenPrInfo | null> {
384 const stdout = await this.runGhStdout(cwd, [
385 "pr",
386 "list",
387 "--head",
388 branch,
389 "--state",
390 "open",
391 "--limit",
392 "1",
393 "--json",
394 "number,title,url,baseRefName,headRefName",
395 ]);
396​
397 const raw = trimStdout(stdout);
398 if (raw.length === 0) return null;
399​
400 let parsedJson: unknown;
401 try {
402 parsedJson = JSON.parse(raw);
403 } catch {
404 throw new Error("GitHub CLI returned invalid PR list JSON.");
405 }
406​
407 const parsed = parseOpenPrList(parsedJson);
408 return parsed[0] ?? null;
409 }
410​
411 private async resolveBaseBranch(
412 cwd: string,
413 branch: string,
414 upstreamRef: string | null,
415 ): Promise<string> {
416 const configured = await this.gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
417 if (configured) return configured;
418​
419 if (upstreamRef) {
420 const upstreamBranch = extractBranchFromRef(upstreamRef);
421 if (upstreamBranch.length > 0 && upstreamBranch !== branch) {
422 return upstreamBranch;
423 }
424 }
425​
426 try {
427 const ghDefault = await this.runGhStdout(cwd, [
428 "repo",
429 "view",
430 "--json",
431 "defaultBranchRef",
432 "--jq",
433 ".defaultBranchRef.name",
434 ]);
435 const defaultBranch = trimStdout(ghDefault);
436 if (defaultBranch.length > 0) return defaultBranch;
437 } catch {
438 // Fall through to deterministic fallback.
439 }
440​
441 return "main";
442 }
443​
444 private async runGh(cwd: string, args: readonly string[]): Promise<void> {
445 await this.runGhCommand(cwd, args);
446 }
447​
448 private async runGhStdout(cwd: string, args: readonly string[]): Promise<string> {
449 const result = await this.runGhCommand(cwd, args);
450 return result.stdout;
451 }
452​
453 private async runGhCommand(cwd: string, args: readonly string[]): Promise<ProcessRunResult> {
454 try {
455 return await this.run("gh", args, {
456 cwd,
457 timeoutMs: GH_CLI_TIMEOUT_MS,
458 });
459 } catch (error) {
460 throw (
461 asCommandNotFound("gh", error) ??
462 normalizeGitHubAuthError(error) ??
463 (error instanceof Error ? error : new Error("GitHub CLI command failed."))
464 );
465 }
466 }