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

GitManager.ts

1,064 lines33.5 KB

1import { randomUUID } from "node:crypto";
2import { realpathSync } from "node:fs";
3​
4import { Effect, FileSystem, Layer, Path } from "effect";
5import {
6 resolveAutoFeatureBranchName,
7 sanitizeBranchFragment,
8 sanitizeFeatureBranchName,
9} from "@t3tools/shared/git";
10​
11import { GitManagerError } from "../Errors.ts";
12import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
13import { GitCore } from "../Services/GitCore.ts";
14import { GitHubCli } from "../Services/GitHubCli.ts";
15import { TextGeneration } from "../Services/TextGeneration.ts";
16​
17interface OpenPrInfo {
18 number: number;
19 title: string;
20 url: string;
21 baseRefName: string;
22 headRefName: string;
24​
25interface PullRequestInfo extends OpenPrInfo {
26 state: "open" | "closed" | "merged";
27 updatedAt: string | null;
29​
30interface ResolvedPullRequest {
31 number: number;
32 title: string;
33 url: string;
34 baseBranch: string;
35 headBranch: string;
36 state: "open" | "closed" | "merged";
38​
39interface PullRequestHeadRemoteInfo {
40 isCrossRepository?: boolean;
41 headRepositoryNameWithOwner?: string | null;
42 headRepositoryOwnerLogin?: string | null;
44​
45interface BranchHeadContext {
46 localBranch: string;
47 headBranch: string;
48 headSelectors: ReadonlyArray<string>;
49 preferredHeadSelector: string;
50 remoteName: string | null;
51 headRepositoryNameWithOwner: string | null;
52 headRepositoryOwnerLogin: string | null;
53 isCrossRepository: boolean;
55​
56function parseRepositoryNameFromPullRequestUrl(url: string): string | null {
57 const trimmed = url.trim();
58 const match = /^https:\/\/github\.com\/[^/]+\/([^/]+)\/pull\/\d+(?:\/.*)?$/i.exec(trimmed);
59 const repositoryName = match?.[1]?.trim() ?? "";
60 return repositoryName.length > 0 ? repositoryName : null;
62​
63function resolveHeadRepositoryNameWithOwner(
64 pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
65): string | null {
66 const explicitRepository = pullRequest.headRepositoryNameWithOwner?.trim() ?? "";
67 if (explicitRepository.length > 0) {
68 return explicitRepository;
69 }
70​
71 if (!pullRequest.isCrossRepository) {
72 return null;
73 }
74​
75 const ownerLogin = pullRequest.headRepositoryOwnerLogin?.trim() ?? "";
76 const repositoryName = parseRepositoryNameFromPullRequestUrl(pullRequest.url);
77 if (ownerLogin.length === 0 || !repositoryName) {
78 return null;
79 }
80​
81 return `${ownerLogin}/${repositoryName}`;
83​
84function resolvePullRequestWorktreeLocalBranchName(
85 pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
86): string {
87 if (!pullRequest.isCrossRepository) {
88 return pullRequest.headBranch;
89 }
90​
91 const sanitizedHeadBranch = sanitizeBranchFragment(pullRequest.headBranch).trim();
92 const suffix = sanitizedHeadBranch.length > 0 ? sanitizedHeadBranch : "head";
93 return `t3code/pr-${pullRequest.number}/${suffix}`;
95​
96function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {
97 const trimmed = url?.trim() ?? "";
98 if (trimmed.length === 0) {
99 return null;
100 }
101​
102 const match =
103 /^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(
104 trimmed,
105 );
106 const repositoryNameWithOwner = match?.[1]?.trim() ?? "";
107 return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;
109​
110function parseRepositoryOwnerLogin(nameWithOwner: string | null): string | null {
111 const trimmed = nameWithOwner?.trim() ?? "";
112 if (trimmed.length === 0) {
113 return null;
114 }
115 const [ownerLogin] = trimmed.split("/");
116 const normalizedOwnerLogin = ownerLogin?.trim() ?? "";
117 return normalizedOwnerLogin.length > 0 ? normalizedOwnerLogin : null;
119​
120function parsePullRequestList(raw: unknown): PullRequestInfo[] {
121 if (!Array.isArray(raw)) return [];
122​
123 const parsed: PullRequestInfo[] = [];
124 for (const entry of raw) {
125 if (!entry || typeof entry !== "object") continue;
126 const record = entry as Record<string, unknown>;
127 const number = record.number;
128 const title = record.title;
129 const url = record.url;
130 const baseRefName = record.baseRefName;
131 const headRefName = record.headRefName;
132 const state = record.state;
133 const mergedAt = record.mergedAt;
134 const updatedAt = record.updatedAt;
135 if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
136 continue;
137 }
138 if (
139 typeof title !== "string" ||
140 typeof url !== "string" ||
141 typeof baseRefName !== "string" ||
142 typeof headRefName !== "string"
143 ) {
144 continue;
145 }
146​
147 let normalizedState: "open" | "closed" | "merged";
148 if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
149 normalizedState = "merged";
150 } else if (state === "OPEN" || state === undefined || state === null) {
151 normalizedState = "open";
152 } else if (state === "CLOSED") {
153 normalizedState = "closed";
154 } else {
155 continue;
156 }
157​
158 parsed.push({
159 number,
160 title,
161 url,
162 baseRefName,
163 headRefName,
164 state: normalizedState,
165 updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null,
166 });
167 }
168 return parsed;
170​
171function gitManagerError(operation: string, detail: string, cause?: unknown): GitManagerError {
172 return new GitManagerError({
173 operation,
174 detail,
175 ...(cause !== undefined ? { cause } : {}),
176 });
178​
179function limitContext(value: string, maxChars: number): string {
180 if (value.length <= maxChars) return value;
181 return `${value.slice(0, maxChars)}\n\n[truncated]`;
183​
184function sanitizeCommitMessage(generated: {
185 subject: string;
186 body: string;
187 branch?: string | undefined;
188}): {
189 subject: string;
190 body: string;
191 branch?: string | undefined;
192} {
193 const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
194 const subject = rawSubject.replace(/[.]+$/g, "").trim();
195 const safeSubject = subject.length > 0 ? subject.slice(0, 72).trimEnd() : "Update project files";
196 return {
197 subject: safeSubject,
198 body: generated.body.trim(),
199 ...(generated.branch !== undefined ? { branch: generated.branch } : {}),
200 };
202​
203interface CommitAndBranchSuggestion {
204 subject: string;
205 body: string;
206 branch?: string | undefined;
207 commitMessage: string;
209​
210function formatCommitMessage(subject: string, body: string): string {
211 const trimmedBody = body.trim();
212 if (trimmedBody.length === 0) {
213 return subject;
214 }
215 return `${subject}\n\n${trimmedBody}`;
217​
218function parseCustomCommitMessage(raw: string): { subject: string; body: string } | null {
219 const normalized = raw.replace(/\r\n/g, "\n").trim();
220 if (normalized.length === 0) {
221 return null;
222 }
223​
224 const [firstLine, ...rest] = normalized.split("\n");
225 const subject = firstLine?.trim() ?? "";
226 if (subject.length === 0) {
227 return null;
228 }
229​
230 return {
231 subject,
232 body: rest.join("\n").trim(),
233 };
235​
236function extractBranchFromRef(ref: string): string {
237 const normalized = ref.trim();
238​
239 if (normalized.startsWith("refs/remotes/")) {
240 const withoutPrefix = normalized.slice("refs/remotes/".length);
241 const firstSlash = withoutPrefix.indexOf("/");
242 if (firstSlash === -1) {
243 return withoutPrefix.trim();
244 }
245 return withoutPrefix.slice(firstSlash + 1).trim();
246 }
247​
248 const firstSlash = normalized.indexOf("/");
249 if (firstSlash === -1) {
250 return normalized;
251 }
252 return normalized.slice(firstSlash + 1).trim();
254​
255function appendUnique(values: string[], next: string | null | undefined): void {
256 const trimmed = next?.trim() ?? "";
257 if (trimmed.length === 0 || values.includes(trimmed)) {
258 return;
259 }
260 values.push(trimmed);
262​
263function toStatusPr(pr: PullRequestInfo): {
264 number: number;
265 title: string;
266 url: string;
267 baseBranch: string;
268 headBranch: string;
269 state: "open" | "closed" | "merged";
270} {
271 return {
272 number: pr.number,
273 title: pr.title,
274 url: pr.url,
275 baseBranch: pr.baseRefName,
276 headBranch: pr.headRefName,
277 state: pr.state,
278 };
280​
281function normalizePullRequestReference(reference: string): string {
282 const trimmed = reference.trim();
283 const hashNumber = /^#(\d+)$/.exec(trimmed);
284 return hashNumber?.[1] ?? trimmed;
286​
287function canonicalizeExistingPath(value: string): string {
288 try {
289 return realpathSync.native(value);
290 } catch {
291 return value;
292 }
294​
295function toResolvedPullRequest(pr: {
296 number: number;
297 title: string;
298 url: string;
299 baseRefName: string;
300 headRefName: string;
301 state?: "open" | "closed" | "merged";
302}): ResolvedPullRequest {
303 return {
304 number: pr.number,
305 title: pr.title,
306 url: pr.url,
307 baseBranch: pr.baseRefName,
308 headBranch: pr.headRefName,
309 state: pr.state ?? "open",
310 };
312​
313function shouldPreferSshRemote(url: string | null): boolean {
314 if (!url) return false;
315 const trimmed = url.trim();
316 return trimmed.startsWith("git@") || trimmed.startsWith("ssh://");
318​
319function toPullRequestHeadRemoteInfo(pr: {
320 isCrossRepository?: boolean;
321 headRepositoryNameWithOwner?: string | null;
322 headRepositoryOwnerLogin?: string | null;
323}): PullRequestHeadRemoteInfo {
324 return {
325 ...(pr.isCrossRepository !== undefined ? { isCrossRepository: pr.isCrossRepository } : {}),
326 ...(pr.headRepositoryNameWithOwner !== undefined
327 ? { headRepositoryNameWithOwner: pr.headRepositoryNameWithOwner }
328 : {}),
329 ...(pr.headRepositoryOwnerLogin !== undefined
330 ? { headRepositoryOwnerLogin: pr.headRepositoryOwnerLogin }
331 : {}),
332 };
334​
335export const makeGitManager = Effect.gen(function* () {
336 const gitCore = yield* GitCore;
337 const gitHubCli = yield* GitHubCli;
338 const textGeneration = yield* TextGeneration;
339​
340 const configurePullRequestHeadUpstream = (
341 cwd: string,
342 pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
343 localBranch = pullRequest.headBranch,
344 ) =>
345 Effect.gen(function* () {
346 const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? "";
347 if (repositoryNameWithOwner.length === 0) {
348 return;
349 }
350​
351 const cloneUrls = yield* gitHubCli.getRepositoryCloneUrls({
352 cwd,
353 repository: repositoryNameWithOwner,
354 });
355 const originRemoteUrl = yield* gitCore.readConfigValue(cwd, "remote.origin.url");
356 const remoteUrl = shouldPreferSshRemote(originRemoteUrl) ? cloneUrls.sshUrl : cloneUrls.url;
357 const preferredRemoteName =
358 pullRequest.headRepositoryOwnerLogin?.trim() ||
359 repositoryNameWithOwner.split("/")[0]?.trim() ||
360 "fork";
361 const remoteName = yield* gitCore.ensureRemote({
362 cwd,
363 preferredName: preferredRemoteName,
364 url: remoteUrl,
365 });
366​
367 yield* gitCore.setBranchUpstream({
368 cwd,
369 branch: localBranch,
370 remoteName,
371 remoteBranch: pullRequest.headBranch,
372 });
373 }).pipe(
374 Effect.catch((error) =>
375 Effect.logWarning(
376 `GitManager.configurePullRequestHeadUpstream: failed to configure upstream for ${localBranch} -> ${pullRequest.headBranch} in ${cwd}: ${error.message}`,
377 ).pipe(Effect.asVoid),
378 ),
379 );
380​
381 const materializePullRequestHeadBranch = (
382 cwd: string,
383 pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
384 localBranch = pullRequest.headBranch,
385 ) =>
386 Effect.gen(function* () {
387 const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? "";
388​
389 if (repositoryNameWithOwner.length === 0) {
390 yield* gitCore.fetchPullRequestBranch({
391 cwd,
392 prNumber: pullRequest.number,
393 branch: localBranch,
394 });
395 return;
396 }
397​
398 const cloneUrls = yield* gitHubCli.getRepositoryCloneUrls({
399 cwd,
400 repository: repositoryNameWithOwner,
401 });
402 const originRemoteUrl = yield* gitCore.readConfigValue(cwd, "remote.origin.url");
403 const remoteUrl = shouldPreferSshRemote(originRemoteUrl) ? cloneUrls.sshUrl : cloneUrls.url;
404 const preferredRemoteName =
405 pullRequest.headRepositoryOwnerLogin?.trim() ||
406 repositoryNameWithOwner.split("/")[0]?.trim() ||
407 "fork";
408 const remoteName = yield* gitCore.ensureRemote({
409 cwd,
410 preferredName: preferredRemoteName,
411 url: remoteUrl,
412 });
413​
414 yield* gitCore.fetchRemoteBranch({
415 cwd,
416 remoteName,
417 remoteBranch: pullRequest.headBranch,
418 localBranch,
419 });
420 yield* gitCore.setBranchUpstream({
421 cwd,
422 branch: localBranch,
423 remoteName,
424 remoteBranch: pullRequest.headBranch,
425 });
426 }).pipe(
427 Effect.catch(() =>
428 gitCore.fetchPullRequestBranch({
429 cwd,
430 prNumber: pullRequest.number,
431 branch: localBranch,
432 }),
433 ),
434 );
435 const fileSystem = yield* FileSystem.FileSystem;
436 const path = yield* Path.Path;
437​
438 const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
439​
440 const readConfigValueNullable = (cwd: string, key: string) =>
441 gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
442​
443 const resolveRemoteRepositoryContext = (cwd: string, remoteName: string | null) =>
444 Effect.gen(function* () {
445 if (!remoteName) {
446 return {
447 repositoryNameWithOwner: null,
448 ownerLogin: null,
449 };
450 }
451​
452 const remoteUrl = yield* readConfigValueNullable(cwd, `remote.${remoteName}.url`);
453 const repositoryNameWithOwner = parseGitHubRepositoryNameWithOwnerFromRemoteUrl(remoteUrl);
454 return {
455 repositoryNameWithOwner,
456 ownerLogin: parseRepositoryOwnerLogin(repositoryNameWithOwner),
457 };
458 });
459​
460 const resolveBranchHeadContext = (
461 cwd: string,
462 details: { branch: string; upstreamRef: string | null },
463 ) =>
464 Effect.gen(function* () {
465 const remoteName = yield* readConfigValueNullable(cwd, `branch.${details.branch}.remote`);
466 const headBranchFromUpstream = details.upstreamRef
467 ? extractBranchFromRef(details.upstreamRef)
468 : "";
469 const headBranch =
470 headBranchFromUpstream.length > 0 ? headBranchFromUpstream : details.branch;
471​
472 const [remoteRepository, originRepository] = yield* Effect.all(
473 [
474 resolveRemoteRepositoryContext(cwd, remoteName),
475 resolveRemoteRepositoryContext(cwd, "origin"),
476 ],
477 { concurrency: "unbounded" },
478 );
479​
480 const isCrossRepository =
481 remoteRepository.repositoryNameWithOwner !== null &&
482 originRepository.repositoryNameWithOwner !== null
483 ? remoteRepository.repositoryNameWithOwner.toLowerCase() !==
484 originRepository.repositoryNameWithOwner.toLowerCase()
485 : remoteName !== null &&
486 remoteName !== "origin" &&
487 remoteRepository.repositoryNameWithOwner !== null;
488​
489 const ownerHeadSelector =
490 remoteRepository.ownerLogin && headBranch.length > 0
491 ? `${remoteRepository.ownerLogin}:${headBranch}`
492 : null;
493 const remoteAliasHeadSelector =
494 remoteName && headBranch.length > 0 ? `${remoteName}:${headBranch}` : null;
495 const shouldProbeRemoteOwnedSelectors =
496 isCrossRepository || (remoteName !== null && remoteName !== "origin");
497​
498 const headSelectors: string[] = [];
499 if (isCrossRepository && shouldProbeRemoteOwnedSelectors) {
500 appendUnique(headSelectors, ownerHeadSelector);
501 appendUnique(
502 headSelectors,
503 remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null,
504 );
505 }
506 appendUnique(headSelectors, details.branch);
507 appendUnique(headSelectors, headBranch !== details.branch ? headBranch : null);
508 if (!isCrossRepository && shouldProbeRemoteOwnedSelectors) {
509 appendUnique(headSelectors, ownerHeadSelector);
510 appendUnique(
511 headSelectors,
512 remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null,
513 );
514 }
515​
516 return {
517 localBranch: details.branch,
518 headBranch,
519 headSelectors,
520 preferredHeadSelector:
521 ownerHeadSelector && isCrossRepository ? ownerHeadSelector : headBranch,
522 remoteName,
523 headRepositoryNameWithOwner: remoteRepository.repositoryNameWithOwner,
524 headRepositoryOwnerLogin: remoteRepository.ownerLogin,
525 isCrossRepository,
526 } satisfies BranchHeadContext;
527 });
528​
529 const findOpenPr = (cwd: string, headSelectors: ReadonlyArray<string>) =>
530 Effect.gen(function* () {
531 for (const headSelector of headSelectors) {
532 const pullRequests = yield* gitHubCli.listOpenPullRequests({
533 cwd,
534 headSelector,
535 limit: 1,
536 });
537​
538 const [firstPullRequest] = pullRequests;
539 if (firstPullRequest) {
540 return {
541 number: firstPullRequest.number,
542 title: firstPullRequest.title,
543 url: firstPullRequest.url,
544 baseRefName: firstPullRequest.baseRefName,
545 headRefName: firstPullRequest.headRefName,
546 state: "open",
547 updatedAt: null,
548 } satisfies PullRequestInfo;
549 }
550 }
551​
552 return null;
553 });
554​
555 const findLatestPr = (cwd: string, details: { branch: string; upstreamRef: string | null }) =>
556 Effect.gen(function* () {
557 const headContext = yield* resolveBranchHeadContext(cwd, details);
558 const parsedByNumber = new Map<number, PullRequestInfo>();
559​
560 for (const headSelector of headContext.headSelectors) {
561 const stdout = yield* gitHubCli
562 .execute({
563 cwd,
564 args: [
565 "pr",
566 "list",
567 "--head",
568 headSelector,
569 "--state",
570 "all",
571 "--limit",
572 "20",
573 "--json",
574 "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt",
575 ],
576 })
577 .pipe(Effect.map((result) => result.stdout));
578​
579 const raw = stdout.trim();
580 if (raw.length === 0) {
581 continue;
582 }
583​
584 const parsedJson = yield* Effect.try({
585 try: () => JSON.parse(raw) as unknown,
586 catch: (cause) =>
587 gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
588 });
589​
590 for (const pr of parsePullRequestList(parsedJson)) {
591 parsedByNumber.set(pr.number, pr);
592 }
593 }
594​
595 const parsed = Array.from(parsedByNumber.values()).toSorted((a, b) => {
596 const left = a.updatedAt ? Date.parse(a.updatedAt) : 0;
597 const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;
598 return right - left;
599 });
600​
601 const latestOpenPr = parsed.find((pr) => pr.state === "open");
602 if (latestOpenPr) {
603 return latestOpenPr;
604 }
605 return parsed[0] ?? null;
606 });
607​
608 const resolveBaseBranch = (
609 cwd: string,
610 branch: string,
611 upstreamRef: string | null,
612 headContext: Pick<BranchHeadContext, "isCrossRepository">,
613 ) =>
614 Effect.gen(function* () {
615 const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
616 if (configured) return configured;
617​
618 if (upstreamRef && !headContext.isCrossRepository) {
619 const upstreamBranch = extractBranchFromRef(upstreamRef);
620 if (upstreamBranch.length > 0 && upstreamBranch !== branch) {
621 return upstreamBranch;
622 }
623 }
624​
625 const defaultFromGh = yield* gitHubCli
626 .getDefaultBranch({ cwd })
627 .pipe(Effect.catch(() => Effect.succeed(null)));
628 if (defaultFromGh) {
629 return defaultFromGh;
630 }
631​
632 return "main";
633 });
634​
635 const resolveCommitAndBranchSuggestion = (input: {
636 cwd: string;
637 branch: string | null;
638 commitMessage?: string;
639 /** When true, also produce a semantic feature branch name. */
640 includeBranch?: boolean;
641 }) =>
642 Effect.gen(function* () {
643 const context = yield* gitCore.prepareCommitContext(input.cwd);
644 if (!context) {
645 return null;
646 }
647​
648 const customCommit = parseCustomCommitMessage(input.commitMessage ?? "");
649 if (customCommit) {
650 return {
651 subject: customCommit.subject,
652 body: customCommit.body,
653 ...(input.includeBranch
654 ? { branch: sanitizeFeatureBranchName(customCommit.subject) }
655 : {}),
656 commitMessage: formatCommitMessage(customCommit.subject, customCommit.body),
657 };
658 }
659​
660 const generated = yield* textGeneration
661 .generateCommitMessage({
662 cwd: input.cwd,
663 branch: input.branch,
664 stagedSummary: limitContext(context.stagedSummary, 8_000),
665 stagedPatch: limitContext(context.stagedPatch, 50_000),
666 ...(input.includeBranch ? { includeBranch: true } : {}),
667 })
668 .pipe(Effect.map((result) => sanitizeCommitMessage(result)));
669​
670 return {
671 subject: generated.subject,
672 body: generated.body,
673 ...(generated.branch !== undefined ? { branch: generated.branch } : {}),
674 commitMessage: formatCommitMessage(generated.subject, generated.body),
675 };
676 });
677​
678 const runCommitStep = (
679 cwd: string,
680 branch: string | null,
681 commitMessage?: string,
682 preResolvedSuggestion?: CommitAndBranchSuggestion,
683 ) =>
684 Effect.gen(function* () {
685 const suggestion =
686 preResolvedSuggestion ??
687 (yield* resolveCommitAndBranchSuggestion({
688 cwd,
689 branch,
690 ...(commitMessage ? { commitMessage } : {}),
691 }));
692 if (!suggestion) {
693 return { status: "skipped_no_changes" as const };
694 }
695​
696 const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body);
697 return {
698 status: "created" as const,
699 commitSha,
700 subject: suggestion.subject,
701 };
702 });
703​
704 const runPrStep = (cwd: string, fallbackBranch: string | null) =>
705 Effect.gen(function* () {
706 const details = yield* gitCore.statusDetails(cwd);
707 const branch = details.branch ?? fallbackBranch;
708 if (!branch) {
709 return yield* gitManagerError(
710 "runPrStep",
711 "Cannot create a pull request from detached HEAD.",
712 );
713 }
714 if (!details.hasUpstream) {
715 return yield* gitManagerError(
716 "runPrStep",
717 "Current branch has not been pushed. Push before creating a PR.",
718 );
719 }
720​
721 const headContext = yield* resolveBranchHeadContext(cwd, {
722 branch,
723 upstreamRef: details.upstreamRef,
724 });
725​
726 const existing = yield* findOpenPr(cwd, headContext.headSelectors);
727 if (existing) {
728 return {
729 status: "opened_existing" as const,
730 url: existing.url,
731 number: existing.number,
732 baseBranch: existing.baseRefName,
733 headBranch: existing.headRefName,
734 title: existing.title,
735 };
736 }
737​
738 const baseBranch = yield* resolveBaseBranch(cwd, branch, details.upstreamRef, headContext);
739 const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch);
740​
741 const generated = yield* textGeneration.generatePrContent({
742 cwd,
743 baseBranch,
744 headBranch: headContext.headBranch,
745 commitSummary: limitContext(rangeContext.commitSummary, 20_000),
746 diffSummary: limitContext(rangeContext.diffSummary, 20_000),
747 diffPatch: limitContext(rangeContext.diffPatch, 60_000),
748 });
749​
750 const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
751 yield* fileSystem
752 .writeFileString(bodyFile, generated.body)
753 .pipe(
754 Effect.mapError((cause) =>
755 gitManagerError("runPrStep", "Failed to write pull request body temp file.", cause),
756 ),
757 );
758 yield* gitHubCli
759 .createPullRequest({
760 cwd,
761 baseBranch,
762 headSelector: headContext.preferredHeadSelector,
763 title: generated.title,
764 bodyFile,
765 })
766 .pipe(Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.catch(() => Effect.void))));
767​
768 const created = yield* findOpenPr(cwd, headContext.headSelectors);
769 if (!created) {
770 return {
771 status: "created" as const,
772 baseBranch,
773 headBranch: headContext.headBranch,
774 title: generated.title,
775 };
776 }
777​
778 return {
779 status: "created" as const,
780 url: created.url,
781 number: created.number,
782 baseBranch: created.baseRefName,
783 headBranch: created.headRefName,
784 title: created.title,
785 };
786 });
787​
788 const status: GitManagerShape["status"] = Effect.fnUntraced(function* (input) {
789 const details = yield* gitCore.statusDetails(input.cwd);
790​
791 const pr =
792 details.branch !== null
793 ? yield* findLatestPr(input.cwd, {
794 branch: details.branch,
795 upstreamRef: details.upstreamRef,
796 }).pipe(
797 Effect.map((latest) => (latest ? toStatusPr(latest) : null)),
798 Effect.catch(() => Effect.succeed(null)),
799 )
800 : null;
801​
802 return {
803 branch: details.branch,
804 hasWorkingTreeChanges: details.hasWorkingTreeChanges,
805 workingTree: details.workingTree,
806 hasUpstream: details.hasUpstream,
807 aheadCount: details.aheadCount,
808 behindCount: details.behindCount,
809 pr,
810 };
811 });
812​
813 const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fnUntraced(
814 function* (input) {
815 const pullRequest = yield* gitHubCli
816 .getPullRequest({
817 cwd: input.cwd,
818 reference: normalizePullRequestReference(input.reference),
819 })
820 .pipe(Effect.map((resolved) => toResolvedPullRequest(resolved)));
821​
822 return { pullRequest };
823 },
824 );
825​
826 const preparePullRequestThread: GitManagerShape["preparePullRequestThread"] = Effect.fnUntraced(
827 function* (input) {
828 const normalizedReference = normalizePullRequestReference(input.reference);
829 const rootWorktreePath = canonicalizeExistingPath(input.cwd);
830 const pullRequestSummary = yield* gitHubCli.getPullRequest({
831 cwd: input.cwd,
832 reference: normalizedReference,
833 });
834 const pullRequest = toResolvedPullRequest(pullRequestSummary);
835​
836 if (input.mode === "local") {
837 yield* gitHubCli.checkoutPullRequest({
838 cwd: input.cwd,
839 reference: normalizedReference,
840 force: true,
841 });
842 const details = yield* gitCore.statusDetails(input.cwd);
843 yield* configurePullRequestHeadUpstream(
844 input.cwd,
845 {
846 ...pullRequest,
847 ...toPullRequestHeadRemoteInfo(pullRequestSummary),
848 },
849 details.branch ?? pullRequest.headBranch,
850 );
851 return {
852 pullRequest,
853 branch: details.branch ?? pullRequest.headBranch,
854 worktreePath: null,
855 };
856 }
857​
858 const ensureExistingWorktreeUpstream = (worktreePath: string) =>
859 Effect.gen(function* () {
860 const details = yield* gitCore.statusDetails(worktreePath);
861 yield* configurePullRequestHeadUpstream(
862 worktreePath,
863 {
864 ...pullRequest,
865 ...toPullRequestHeadRemoteInfo(pullRequestSummary),
866 },
867 details.branch ?? pullRequest.headBranch,
868 );
869 });
870​
871 const pullRequestWithRemoteInfo = {
872 ...pullRequest,
873 ...toPullRequestHeadRemoteInfo(pullRequestSummary),
874 } as const;
875 const localPullRequestBranch =
876 resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo);
877​
878 const findLocalHeadBranch = (cwd: string) =>
879 gitCore.listBranches({ cwd }).pipe(
880 Effect.map((result) => {
881 const localBranch = result.branches.find(
882 (branch) => !branch.isRemote && branch.name === localPullRequestBranch,
883 );
884 if (localBranch) {
885 return localBranch;
886 }
887 if (localPullRequestBranch === pullRequest.headBranch) {
888 return null;
889 }
890 return (
891 result.branches.find(
892 (branch) =>
893 !branch.isRemote &&
894 branch.name === pullRequest.headBranch &&
895 branch.worktreePath !== null &&
896 canonicalizeExistingPath(branch.worktreePath) !== rootWorktreePath,
897 ) ?? null
898 );
899 }),
900 );
901​
902 const existingBranchBeforeFetch = yield* findLocalHeadBranch(input.cwd);
903 const existingBranchBeforeFetchPath = existingBranchBeforeFetch?.worktreePath
904 ? canonicalizeExistingPath(existingBranchBeforeFetch.worktreePath)
905 : null;
906 if (
907 existingBranchBeforeFetch?.worktreePath &&
908 existingBranchBeforeFetchPath !== rootWorktreePath
909 ) {
910 yield* ensureExistingWorktreeUpstream(existingBranchBeforeFetch.worktreePath);
911 return {
912 pullRequest,
913 branch: localPullRequestBranch,
914 worktreePath: existingBranchBeforeFetch.worktreePath,
915 };
916 }
917 if (existingBranchBeforeFetchPath === rootWorktreePath) {
918 return yield* gitManagerError(
919 "preparePullRequestThread",
920 "This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.",
921 );
922 }
923​
924 yield* materializePullRequestHeadBranch(
925 input.cwd,
926 pullRequestWithRemoteInfo,
927 localPullRequestBranch,
928 );
929​
930 const existingBranchAfterFetch = yield* findLocalHeadBranch(input.cwd);
931 const existingBranchAfterFetchPath = existingBranchAfterFetch?.worktreePath
932 ? canonicalizeExistingPath(existingBranchAfterFetch.worktreePath)
933 : null;
934 if (
935 existingBranchAfterFetch?.worktreePath &&
936 existingBranchAfterFetchPath !== rootWorktreePath
937 ) {
938 yield* ensureExistingWorktreeUpstream(existingBranchAfterFetch.worktreePath);
939 return {
940 pullRequest,
941 branch: localPullRequestBranch,
942 worktreePath: existingBranchAfterFetch.worktreePath,
943 };
944 }
945 if (existingBranchAfterFetchPath === rootWorktreePath) {
946 return yield* gitManagerError(
947 "preparePullRequestThread",
948 "This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.",
949 );
950 }
951​
952 const worktree = yield* gitCore.createWorktree({
953 cwd: input.cwd,
954 branch: localPullRequestBranch,
955 path: null,
956 });
957 yield* ensureExistingWorktreeUpstream(worktree.worktree.path);
958​
959 return {
960 pullRequest,
961 branch: worktree.worktree.branch,
962 worktreePath: worktree.worktree.path,
963 };
964 },
965 );
966​
967 const runFeatureBranchStep = (cwd: string, branch: string | null, commitMessage?: string) =>
968 Effect.gen(function* () {
969 const suggestion = yield* resolveCommitAndBranchSuggestion({
970 cwd,
971 branch,
972 ...(commitMessage ? { commitMessage } : {}),
973 includeBranch: true,
974 });
975 if (!suggestion) {
976 return yield* gitManagerError(
977 "runFeatureBranchStep",
978 "Cannot create a feature branch because there are no changes to commit.",
979 );
980 }
981​
982 const preferredBranch = suggestion.branch ?? sanitizeFeatureBranchName(suggestion.subject);
983 const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd);
984 const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch);
985​
986 yield* gitCore.createBranch({ cwd, branch: resolvedBranch });
987 yield* Effect.scoped(gitCore.checkoutBranch({ cwd, branch: resolvedBranch }));
988​
989 return {
990 branchStep: { status: "created" as const, name: resolvedBranch },
991 resolvedCommitMessage: suggestion.commitMessage,
992 resolvedCommitSuggestion: suggestion,
993 };
994 });
995​
996 const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(
997 function* (input) {
998 const wantsPush = input.action !== "commit";
999 const wantsPr = input.action === "commit_push_pr";
1000​
1001 const initialStatus = yield* gitCore.statusDetails(input.cwd);
1002 if (!input.featureBranch && wantsPush && !initialStatus.branch) {
1003 return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
1005 if (!input.featureBranch && wantsPr && !initialStatus.branch) {
1006 return yield* gitManagerError(
1007 "runStackedAction",
1008 "Cannot create a pull request from detached HEAD.",
1009 );
1011​
1012 let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
1013 let commitMessageForStep = input.commitMessage;
1014 let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
1015​
1016 if (input.featureBranch) {
1017 const result = yield* runFeatureBranchStep(
1018 input.cwd,
1019 initialStatus.branch,
1020 input.commitMessage,
1021 );
1022 branchStep = result.branchStep;
1023 commitMessageForStep = result.resolvedCommitMessage;
1024 preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
1025 } else {
1026 branchStep = { status: "skipped_not_requested" as const };
1028​
1029 const currentBranch = branchStep.name ?? initialStatus.branch;
1030​
1031 const commit = yield* runCommitStep(
1032 input.cwd,
1033 currentBranch,
1034 commitMessageForStep,
1035 preResolvedCommitSuggestion,
1036 );
1037​
1038 const push = wantsPush
1039 ? yield* gitCore.pushCurrentBranch(input.cwd, currentBranch)
1040 : { status: "skipped_not_requested" as const };
1041​
1042 const pr = wantsPr
1043 ? yield* runPrStep(input.cwd, currentBranch)
1044 : { status: "skipped_not_requested" as const };
1045​
1046 return {
1047 action: input.action,
1048 branch: branchStep,
1049 commit,
1050 push,
1051 pr,
1052 };
1053 },
1054 );
1055​
1056 return {
1057 status,
1058 resolvePullRequest,
1059 preparePullRequestThread,
1060 runStackedAction,
1061 } satisfies GitManagerShape;
1062});
1063​
1064export const GitManagerLive = Layer.effect(GitManager, makeGitManager);