Open History to see the last commit
1import { Effect, Layer } from "effect";
2
3import { runProcess } from "../../processRunner";
4import { GitHubCliError } from "../Errors.ts";
5import { GitHubCli, type GitHubCliShape } from "../Services/GitHubCli.ts";
6
7const DEFAULT_TIMEOUT_MS = 30_000;
8
9function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown): GitHubCliError {
10 if (error instanceof Error) {
11 if (error.message.includes("Command not found: gh")) {
12 return new GitHubCliError({
13 operation,
14 detail: "GitHub CLI (`gh`) is required but not available on PATH.",
15 cause: error,
16 });
17 }
18
19 const lower = error.message.toLowerCase();
20 if (
21 lower.includes("authentication failed") ||
22 lower.includes("not logged in") ||
23 lower.includes("gh auth login") ||
24 lower.includes("no oauth token")
25 ) {
26 return new GitHubCliError({
27 operation,
28 detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
29 cause: error,
30 });
31 }
32
33 return new GitHubCliError({
34 operation,
35 detail: `GitHub CLI command failed: ${error.message}`,
36 cause: error,
37 });
38 }
39
40 return new GitHubCliError({
41 operation,
42 detail: "GitHub CLI command failed.",
43 cause: error,
44 });
45}
46
47function parseOpenPullRequests(raw: string): ReadonlyArray<{
48 number: number;
49 title: string;
50 url: string;
51 baseRefName: string;
52 headRefName: string;
53}> {
54 const trimmed = raw.trim();
55 if (trimmed.length === 0) return [];
56
57 const parsed: unknown = JSON.parse(trimmed);
58 if (!Array.isArray(parsed)) {
59 throw new Error("GitHub CLI returned non-array JSON.");
60 }
61
62 const result: Array<{
63 number: number;
64 title: string;
65 url: string;
66 baseRefName: string;
67 headRefName: string;
68 }> = [];
69 for (const entry of parsed) {
70 if (!entry || typeof entry !== "object") {
71 continue;
72 }
73 const record = entry as Record<string, unknown>;
74 const number = record.number;
75 const title = record.title;
76 const url = record.url;
77 const baseRefName = record.baseRefName;
78 const headRefName = record.headRefName;
79 if (
80 typeof number !== "number" ||
81 !Number.isInteger(number) ||
82 number <= 0 ||
83 typeof title !== "string" ||
84 typeof url !== "string" ||
85 typeof baseRefName !== "string" ||
86 typeof headRefName !== "string"
87 ) {
88 continue;
89 }
90 result.push({
91 number,
92 title,
93 url,
94 baseRefName,
95 headRefName,
96 });
97 }
98
99 return result;
100}
101
102const makeGitHubCli = Effect.sync(() => {
103 const execute: GitHubCliShape["execute"] = (input) =>
104 Effect.tryPromise({
105 try: () =>
106 runProcess("gh", input.args, {
107 cwd: input.cwd,
108 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
109 }),
110 catch: (error) => normalizeGitHubCliError("execute", error),
111 });
112
113 const service = {
114 execute,
115 listOpenPullRequests: (input) =>
116 execute({
117 cwd: input.cwd,
118 args: [
119 "pr",
120 "list",
121 "--head",
122 input.headBranch,
123 "--state",
124 "open",
125 "--limit",
126 String(input.limit ?? 1),
127 "--json",
128 "number,title,url,baseRefName,headRefName",
129 ],
130 }).pipe(
131 Effect.map((result) => result.stdout),
132 Effect.flatMap((raw) =>
133 Effect.try({
134 try: () => parseOpenPullRequests(raw),
135 catch: (error: unknown) =>
136 new GitHubCliError({
137 operation: "listOpenPullRequests",
138 detail:
139 error instanceof Error
140 ? `GitHub CLI returned invalid PR list JSON: ${error.message}`
141 : "GitHub CLI returned invalid PR list JSON.",
142 ...(error !== undefined ? { cause: error } : {}),
143 }),
144 }),
145 ),
146 ),
147 createPullRequest: (input) =>
148 execute({
149 cwd: input.cwd,
150 args: [
151 "pr",
152 "create",
153 "--base",
154 input.baseBranch,
155 "--head",
156 input.headBranch,
157 "--title",
158 input.title,
159 "--body-file",
160 input.bodyFile,
161 ],
162 }).pipe(Effect.asVoid),
163 getDefaultBranch: (input) =>
164 execute({
165 cwd: input.cwd,
166 args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
167 }).pipe(
168 Effect.map((value) => {
169 const trimmed = value.stdout.trim();
170 return trimmed.length > 0 ? trimmed : null;
171 }),
172 ),
173 } satisfies GitHubCliShape;
174
175 return service;
176});
177
178export const GitHubCliLive = Layer.effect(GitHubCli, makeGitHubCli);