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

GitManager.ts

425 lines12.3 KB

1import { randomUUID } from "node:crypto";
2​
3import { Effect, FileSystem, Layer, Path } from "effect";
4​
5import { GitManagerError } from "../Errors.ts";
6import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
7import { GitCore } from "../Services/GitCore.ts";
8import { GitHubCli } from "../Services/GitHubCli.ts";
9import { TextGeneration } from "../Services/TextGeneration.ts";
10​
11interface OpenPrInfo {
12 number: number;
13 title: string;
14 url: string;
15 baseRefName: string;
16 headRefName: string;
18​
19interface PullRequestInfo extends OpenPrInfo {
20 state: "open" | "closed" | "merged";
21 updatedAt: string | null;
23​
24function parsePullRequestList(raw: unknown): PullRequestInfo[] {
25 if (!Array.isArray(raw)) return [];
26​
27 const parsed: PullRequestInfo[] = [];
28 for (const entry of raw) {
29 if (!entry || typeof entry !== "object") continue;
30 const record = entry as Record<string, unknown>;
31 const number = record.number;
32 const title = record.title;
33 const url = record.url;
34 const baseRefName = record.baseRefName;
35 const headRefName = record.headRefName;
36 const state = record.state;
37 const mergedAt = record.mergedAt;
38 const updatedAt = record.updatedAt;
39 if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
40 continue;
41 }
42 if (
43 typeof title !== "string" ||
44 typeof url !== "string" ||
45 typeof baseRefName !== "string" ||
46 typeof headRefName !== "string"
47 ) {
48 continue;
49 }
50​
51 let normalizedState: "open" | "closed" | "merged";
52 if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
53 normalizedState = "merged";
54 } else if (state === "OPEN" || state === undefined || state === null) {
55 normalizedState = "open";
56 } else if (state === "CLOSED") {
57 normalizedState = "closed";
58 } else {
59 continue;
60 }
61​
62 parsed.push({
63 number,
64 title,
65 url,
66 baseRefName,
67 headRefName,
68 state: normalizedState,
69 updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null,
70 });
71 }
72 return parsed;
74​
75function gitManagerError(operation: string, detail: string, cause?: unknown): GitManagerError {
76 return new GitManagerError({
77 operation,
78 detail,
79 ...(cause !== undefined ? { cause } : {}),
80 });
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(generated: { subject: string; body: string }): {
89 subject: string;
90 body: string;
91} {
92 const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
93 const subject = rawSubject.replace(/[.]+$/g, "").trim();
94 const safeSubject = subject.length > 0 ? subject.slice(0, 72).trimEnd() : "Update project files";
95 return {
96 subject: safeSubject,
97 body: generated.body.trim(),
98 };
100​
101function parseCustomCommitMessage(raw: string): { subject: string; body: string } | null {
102 const normalized = raw.replace(/\r\n/g, "\n").trim();
103 if (normalized.length === 0) {
104 return null;
105 }
106​
107 const [firstLine, ...rest] = normalized.split("\n");
108 const subject = firstLine?.trim() ?? "";
109 if (subject.length === 0) {
110 return null;
111 }
112​
113 return {
114 subject,
115 body: rest.join("\n").trim(),
116 };
118​
119function extractBranchFromRef(ref: string): string {
120 const normalized = ref.trim();
121​
122 if (normalized.startsWith("refs/remotes/")) {
123 const withoutPrefix = normalized.slice("refs/remotes/".length);
124 const firstSlash = withoutPrefix.indexOf("/");
125 if (firstSlash === -1) {
126 return withoutPrefix.trim();
127 }
128 return withoutPrefix.slice(firstSlash + 1).trim();
129 }
130​
131 const firstSlash = normalized.indexOf("/");
132 if (firstSlash === -1) {
133 return normalized;
134 }
135 return normalized.slice(firstSlash + 1).trim();
137​
138function toStatusPr(pr: PullRequestInfo): {
139 number: number;
140 title: string;
141 url: string;
142 baseBranch: string;
143 headBranch: string;
144 state: "open" | "closed" | "merged";
145} {
146 return {
147 number: pr.number,
148 title: pr.title,
149 url: pr.url,
150 baseBranch: pr.baseRefName,
151 headBranch: pr.headRefName,
152 state: pr.state,
153 };
155​
156export const makeGitManager = Effect.gen(function* () {
157 const gitCore = yield* GitCore;
158 const gitHubCli = yield* GitHubCli;
159 const textGeneration = yield* TextGeneration;
160 const fileSystem = yield* FileSystem.FileSystem;
161 const path = yield* Path.Path;
162​
163 const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
164​
165 const findOpenPr = (cwd: string, branch: string) =>
166 gitHubCli
167 .listOpenPullRequests({
168 cwd,
169 headBranch: branch,
170 limit: 1,
171 })
172 .pipe(
173 Effect.map((prs) => {
174 const [first] = prs;
175 if (!first) {
176 return null;
177 }
178 return {
179 number: first.number,
180 title: first.title,
181 url: first.url,
182 baseRefName: first.baseRefName,
183 headRefName: first.headRefName,
184 state: "open",
185 updatedAt: null,
186 } satisfies PullRequestInfo;
187 }),
188 );
189​
190 const findLatestPr = (cwd: string, branch: string) =>
191 Effect.gen(function* () {
192 const stdout = yield* gitHubCli
193 .execute({
194 cwd,
195 args: [
196 "pr",
197 "list",
198 "--head",
199 branch,
200 "--state",
201 "all",
202 "--limit",
203 "20",
204 "--json",
205 "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt",
206 ],
207 })
208 .pipe(Effect.map((result) => result.stdout));
209​
210 const raw = stdout.trim();
211 if (raw.length === 0) {
212 return null;
213 }
214​
215 const parsedJson = yield* Effect.try({
216 try: () => JSON.parse(raw) as unknown,
217 catch: (cause) =>
218 gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
219 });
220​
221 const parsed = parsePullRequestList(parsedJson).toSorted((a, b) => {
222 const left = a.updatedAt ? Date.parse(a.updatedAt) : 0;
223 const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;
224 return right - left;
225 });
226​
227 const latestOpenPr = parsed.find((pr) => pr.state === "open");
228 if (latestOpenPr) {
229 return latestOpenPr;
230 }
231 return parsed[0] ?? null;
232 });
233​
234 const resolveBaseBranch = (cwd: string, branch: string, upstreamRef: string | null) =>
235 Effect.gen(function* () {
236 const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
237 if (configured) return configured;
238​
239 if (upstreamRef) {
240 const upstreamBranch = extractBranchFromRef(upstreamRef);
241 if (upstreamBranch.length > 0 && upstreamBranch !== branch) {
242 return upstreamBranch;
243 }
244 }
245​
246 const defaultFromGh = yield* gitHubCli
247 .getDefaultBranch({ cwd })
248 .pipe(Effect.catch(() => Effect.succeed(null)));
249 if (defaultFromGh) {
250 return defaultFromGh;
251 }
252​
253 return "main";
254 });
255​
256 const runCommitStep = (cwd: string, branch: string | null, commitMessage?: string) =>
257 Effect.gen(function* () {
258 const context = yield* gitCore.prepareCommitContext(cwd);
259 if (!context) {
260 return { status: "skipped_no_changes" as const };
261 }
262​
263 let generated = parseCustomCommitMessage(commitMessage ?? "");
264 if (!generated) {
265 generated = yield* textGeneration
266 .generateCommitMessage({
267 cwd,
268 branch,
269 stagedSummary: limitContext(context.stagedSummary, 8_000),
270 stagedPatch: limitContext(context.stagedPatch, 50_000),
271 })
272 .pipe(Effect.map((result) => sanitizeCommitMessage(result)));
273 }
274​
275 const { commitSha } = yield* gitCore.commit(cwd, generated.subject, generated.body);
276 return {
277 status: "created" as const,
278 commitSha,
279 subject: generated.subject,
280 };
281 });
282​
283 const runPrStep = (cwd: string, fallbackBranch: string | null) =>
284 Effect.gen(function* () {
285 const details = yield* gitCore.statusDetails(cwd);
286 const branch = details.branch ?? fallbackBranch;
287 if (!branch) {
288 return yield* gitManagerError(
289 "runPrStep",
290 "Cannot create a pull request from detached HEAD.",
291 );
292 }
293 if (!details.hasUpstream) {
294 return yield* gitManagerError(
295 "runPrStep",
296 "Current branch has not been pushed. Push before creating a PR.",
297 );
298 }
299​
300 const existing = yield* findOpenPr(cwd, branch);
301 if (existing) {
302 return {
303 status: "opened_existing" as const,
304 url: existing.url,
305 number: existing.number,
306 baseBranch: existing.baseRefName,
307 headBranch: existing.headRefName,
308 title: existing.title,
309 };
310 }
311​
312 const baseBranch = yield* resolveBaseBranch(cwd, branch, details.upstreamRef);
313 const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch);
314​
315 const generated = yield* textGeneration.generatePrContent({
316 cwd,
317 baseBranch,
318 headBranch: branch,
319 commitSummary: limitContext(rangeContext.commitSummary, 20_000),
320 diffSummary: limitContext(rangeContext.diffSummary, 20_000),
321 diffPatch: limitContext(rangeContext.diffPatch, 60_000),
322 });
323​
324 const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
325 yield* fileSystem
326 .writeFileString(bodyFile, generated.body)
327 .pipe(
328 Effect.mapError((cause) =>
329 gitManagerError("runPrStep", "Failed to write pull request body temp file.", cause),
330 ),
331 );
332 yield* gitHubCli
333 .createPullRequest({
334 cwd,
335 baseBranch,
336 headBranch: branch,
337 title: generated.title,
338 bodyFile,
339 })
340 .pipe(Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.catch(() => Effect.void))));
341​
342 const created = yield* findOpenPr(cwd, branch);
343 if (!created) {
344 return {
345 status: "created" as const,
346 baseBranch,
347 headBranch: branch,
348 title: generated.title,
349 };
350 }
351​
352 return {
353 status: "created" as const,
354 url: created.url,
355 number: created.number,
356 baseBranch: created.baseRefName,
357 headBranch: created.headRefName,
358 title: created.title,
359 };
360 });
361​
362 const status: GitManagerShape["status"] = Effect.fnUntraced(function* (input) {
363 const details = yield* gitCore.statusDetails(input.cwd);
364​
365 const pr =
366 details.branch !== null
367 ? yield* findLatestPr(input.cwd, details.branch).pipe(
368 Effect.map((latest) => (latest ? toStatusPr(latest) : null)),
369 Effect.catch(() => Effect.succeed(null)),
370 )
371 : null;
372​
373 return {
374 branch: details.branch,
375 hasWorkingTreeChanges: details.hasWorkingTreeChanges,
376 workingTree: details.workingTree,
377 hasUpstream: details.hasUpstream,
378 aheadCount: details.aheadCount,
379 behindCount: details.behindCount,
380 pr,
381 };
382 });
383​
384 const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(
385 function* (input) {
386 const wantsPush = input.action !== "commit";
387 const wantsPr = input.action === "commit_push_pr";
388​
389 const initialStatus = yield* gitCore.statusDetails(input.cwd);
390 if (wantsPush && !initialStatus.branch) {
391 return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
392 }
393 if (wantsPr && !initialStatus.branch) {
394 return yield* gitManagerError(
395 "runStackedAction",
396 "Cannot create a pull request from detached HEAD.",
397 );
398 }
399​
400 const commit = yield* runCommitStep(input.cwd, initialStatus.branch, input.commitMessage);
401​
402 const push = wantsPush
403 ? yield* gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
404 : { status: "skipped_not_requested" as const };
405​
406 const pr = wantsPr
407 ? yield* runPrStep(input.cwd, initialStatus.branch)
408 : { status: "skipped_not_requested" as const };
409​
410 return {
411 action: input.action,
412 commit,
413 push,
414 pr,
415 };
416 },
417 );
418​
419 return {
420 status,
421 runStackedAction,
422 } satisfies GitManagerShape;
423});
424​
425export const GitManagerLive = Layer.effect(GitManager, makeGitManager);