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

GitManager.ts

321 lines9.4 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​
19function gitManagerError(operation: string, detail: string, cause?: unknown): GitManagerError {
20 return new GitManagerError({
21 operation,
22 detail,
23 ...(cause !== undefined ? { cause } : {}),
24 });
26​
27function limitContext(value: string, maxChars: number): string {
28 if (value.length <= maxChars) return value;
29 return `${value.slice(0, maxChars)}\n\n[truncated]`;
31​
32function sanitizeCommitMessage(generated: { subject: string; body: string }): {
33 subject: string;
34 body: string;
35} {
36 const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
37 const subject = rawSubject.replace(/[.]+$/g, "").trim();
38 const safeSubject = subject.length > 0 ? subject.slice(0, 72).trimEnd() : "Update project files";
39 return {
40 subject: safeSubject,
41 body: generated.body.trim(),
42 };
44​
45function parseCustomCommitMessage(raw: string): { subject: string; body: string } | null {
46 const normalized = raw.replace(/\r\n/g, "\n").trim();
47 if (normalized.length === 0) {
48 return null;
49 }
50​
51 const [firstLine, ...rest] = normalized.split("\n");
52 const subject = firstLine?.trim() ?? "";
53 if (subject.length === 0) {
54 return null;
55 }
56​
57 return {
58 subject,
59 body: rest.join("\n").trim(),
60 };
62​
63function extractBranchFromRef(ref: string): string {
64 const normalized = ref.trim();
65​
66 if (normalized.startsWith("refs/remotes/")) {
67 const withoutPrefix = normalized.slice("refs/remotes/".length);
68 const firstSlash = withoutPrefix.indexOf("/");
69 if (firstSlash === -1) {
70 return withoutPrefix.trim();
71 }
72 return withoutPrefix.slice(firstSlash + 1).trim();
73 }
74​
75 const firstSlash = normalized.indexOf("/");
76 if (firstSlash === -1) {
77 return normalized;
78 }
79 return normalized.slice(firstSlash + 1).trim();
81​
82function toStatusOpenPr(pr: OpenPrInfo): {
83 number: number;
84 title: string;
85 url: string;
86 baseBranch: string;
87 headBranch: string;
88} {
89 return {
90 number: pr.number,
91 title: pr.title,
92 url: pr.url,
93 baseBranch: pr.baseRefName,
94 headBranch: pr.headRefName,
95 };
97​
98export const makeGitManager = Effect.gen(function* () {
99 const gitCore = yield* GitCore;
100 const gitHubCli = yield* GitHubCli;
101 const textGeneration = yield* TextGeneration;
102 const fileSystem = yield* FileSystem.FileSystem;
103 const path = yield* Path.Path;
104​
105 const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
106​
107 const findOpenPr = (cwd: string, branch: string) =>
108 gitHubCli
109 .listOpenPullRequests({
110 cwd,
111 headBranch: branch,
112 limit: 1,
113 })
114 .pipe(
115 Effect.map((prs) => {
116 const [first] = prs;
117 if (!first) {
118 return null;
119 }
120 return {
121 number: first.number,
122 title: first.title,
123 url: first.url,
124 baseRefName: first.baseRefName,
125 headRefName: first.headRefName,
126 } satisfies OpenPrInfo;
127 }),
128 );
129​
130 const resolveBaseBranch = (cwd: string, branch: string, upstreamRef: string | null) =>
131 Effect.gen(function* () {
132 const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
133 if (configured) return configured;
134​
135 if (upstreamRef) {
136 const upstreamBranch = extractBranchFromRef(upstreamRef);
137 if (upstreamBranch.length > 0 && upstreamBranch !== branch) {
138 return upstreamBranch;
139 }
140 }
141​
142 const defaultFromGh = yield* gitHubCli
143 .getDefaultBranch({ cwd })
144 .pipe(Effect.catch(() => Effect.succeed(null)));
145 if (defaultFromGh) {
146 return defaultFromGh;
147 }
148​
149 return "main";
150 });
151​
152 const runCommitStep = (cwd: string, branch: string | null, commitMessage?: string) =>
153 Effect.gen(function* () {
154 const context = yield* gitCore.prepareCommitContext(cwd);
155 if (!context) {
156 return { status: "skipped_no_changes" as const };
157 }
158​
159 let generated = parseCustomCommitMessage(commitMessage ?? "");
160 if (!generated) {
161 generated = yield* textGeneration
162 .generateCommitMessage({
163 cwd,
164 branch,
165 stagedSummary: limitContext(context.stagedSummary, 8_000),
166 stagedPatch: limitContext(context.stagedPatch, 50_000),
167 })
168 .pipe(Effect.map((result) => sanitizeCommitMessage(result)));
169 }
170​
171 const { commitSha } = yield* gitCore.commit(cwd, generated.subject, generated.body);
172 return {
173 status: "created" as const,
174 commitSha,
175 subject: generated.subject,
176 };
177 });
178​
179 const runPrStep = (cwd: string, fallbackBranch: string | null) =>
180 Effect.gen(function* () {
181 const details = yield* gitCore.statusDetails(cwd);
182 const branch = details.branch ?? fallbackBranch;
183 if (!branch) {
184 return yield* gitManagerError(
185 "runPrStep",
186 "Cannot create a pull request from detached HEAD.",
187 );
188 }
189 if (!details.hasUpstream) {
190 return yield* gitManagerError(
191 "runPrStep",
192 "Current branch has not been pushed. Push before creating a PR.",
193 );
194 }
195​
196 const existing = yield* findOpenPr(cwd, branch);
197 if (existing) {
198 return {
199 status: "opened_existing" as const,
200 url: existing.url,
201 number: existing.number,
202 baseBranch: existing.baseRefName,
203 headBranch: existing.headRefName,
204 title: existing.title,
205 };
206 }
207​
208 const baseBranch = yield* resolveBaseBranch(cwd, branch, details.upstreamRef);
209 const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch);
210​
211 const generated = yield* textGeneration.generatePrContent({
212 cwd,
213 baseBranch,
214 headBranch: branch,
215 commitSummary: limitContext(rangeContext.commitSummary, 20_000),
216 diffSummary: limitContext(rangeContext.diffSummary, 20_000),
217 diffPatch: limitContext(rangeContext.diffPatch, 60_000),
218 });
219​
220 const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
221 yield* fileSystem
222 .writeFileString(bodyFile, generated.body)
223 .pipe(
224 Effect.mapError((cause) =>
225 gitManagerError("runPrStep", "Failed to write pull request body temp file.", cause),
226 ),
227 );
228 yield* gitHubCli
229 .createPullRequest({
230 cwd,
231 baseBranch,
232 headBranch: branch,
233 title: generated.title,
234 bodyFile,
235 })
236 .pipe(Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.catch(() => Effect.void))));
237​
238 const created = yield* findOpenPr(cwd, branch);
239 if (!created) {
240 return {
241 status: "created" as const,
242 baseBranch,
243 headBranch: branch,
244 title: generated.title,
245 };
246 }
247​
248 return {
249 status: "created" as const,
250 url: created.url,
251 number: created.number,
252 baseBranch: created.baseRefName,
253 headBranch: created.headRefName,
254 title: created.title,
255 };
256 });
257​
258 const status: GitManagerShape["status"] = Effect.fnUntraced(function* (input) {
259 const details = yield* gitCore.statusDetails(input.cwd);
260​
261 const openPr =
262 details.branch && details.hasUpstream
263 ? yield* findOpenPr(input.cwd, details.branch).pipe(
264 Effect.map((pr) => (pr ? toStatusOpenPr(pr) : null)),
265 Effect.catch(() => Effect.succeed(null)),
266 )
267 : null;
268​
269 return {
270 branch: details.branch,
271 hasWorkingTreeChanges: details.hasWorkingTreeChanges,
272 workingTree: details.workingTree,
273 hasUpstream: details.hasUpstream,
274 aheadCount: details.aheadCount,
275 behindCount: details.behindCount,
276 openPr,
277 };
278 });
279​
280 const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(
281 function* (input) {
282 const wantsPush = input.action !== "commit";
283 const wantsPr = input.action === "commit_push_pr";
284​
285 const initialStatus = yield* gitCore.statusDetails(input.cwd);
286 if (wantsPush && !initialStatus.branch) {
287 return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
288 }
289 if (wantsPr && !initialStatus.branch) {
290 return yield* gitManagerError(
291 "runStackedAction",
292 "Cannot create a pull request from detached HEAD.",
293 );
294 }
295​
296 const commit = yield* runCommitStep(input.cwd, initialStatus.branch, input.commitMessage);
297​
298 const push = wantsPush
299 ? yield* gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
300 : { status: "skipped_not_requested" as const };
301​
302 const pr = wantsPr
303 ? yield* runPrStep(input.cwd, initialStatus.branch)
304 : { status: "skipped_not_requested" as const };
305​
306 return {
307 action: input.action,
308 commit,
309 push,
310 pr,
311 };
312 },
313 );
314​
315 return {
316 status,
317 runStackedAction,
318 } satisfies GitManagerShape;
319});
320​
321export const GitManagerLive = Layer.effect(GitManager, makeGitManager);