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

GitHubCli.ts

375 lines11.5 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Result from "effect/Result";
5import * as Schema from "effect/Schema";
6import * as SchemaIssue from "effect/SchemaIssue";
7​
8import {
9 TrimmedNonEmptyString,
10 type SourceControlRepositoryVisibility,
11 type VcsError,
12} from "@t3tools/contracts";
13​
14import * as VcsProcess from "../vcs/VcsProcess.ts";
15import * as GitHubPullRequests from "./gitHubPullRequests.ts";
16​
17const DEFAULT_TIMEOUT_MS = 30_000;
18​
19export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
20 operation: Schema.String,
21 detail: Schema.String,
22 cause: Schema.optional(Schema.Defect()),
23}) {
24 override get message(): string {
25 return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
26 }
28​
29export interface GitHubPullRequestSummary {
30 readonly number: number;
31 readonly title: string;
32 readonly url: string;
33 readonly baseRefName: string;
34 readonly headRefName: string;
35 readonly state?: "open" | "closed" | "merged";
36 readonly isCrossRepository?: boolean;
37 readonly headRepositoryNameWithOwner?: string | null;
38 readonly headRepositoryOwnerLogin?: string | null;
40​
41export interface GitHubRepositoryCloneUrls {
42 readonly nameWithOwner: string;
43 readonly url: string;
44 readonly sshUrl: string;
46​
47export interface GitHubCliShape {
48 readonly execute: (input: {
49 readonly cwd: string;
50 readonly args: ReadonlyArray<string>;
51 readonly timeoutMs?: number;
52 }) => Effect.Effect<VcsProcess.VcsProcessOutput, GitHubCliError>;
53​
54 readonly listOpenPullRequests: (input: {
55 readonly cwd: string;
56 readonly headSelector: string;
57 readonly limit?: number;
58 }) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
59​
60 readonly getPullRequest: (input: {
61 readonly cwd: string;
62 readonly reference: string;
63 }) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
64​
65 readonly getRepositoryCloneUrls: (input: {
66 readonly cwd: string;
67 readonly repository: string;
68 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
69​
70 readonly createRepository: (input: {
71 readonly cwd: string;
72 readonly repository: string;
73 readonly visibility: SourceControlRepositoryVisibility;
74 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
75​
76 readonly createPullRequest: (input: {
77 readonly cwd: string;
78 readonly baseBranch: string;
79 readonly headSelector: string;
80 readonly title: string;
81 readonly bodyFile: string;
82 }) => Effect.Effect<void, GitHubCliError>;
83​
84 readonly getDefaultBranch: (input: {
85 readonly cwd: string;
86 }) => Effect.Effect<string | null, GitHubCliError>;
87​
88 readonly checkoutPullRequest: (input: {
89 readonly cwd: string;
90 readonly reference: string;
91 readonly force?: boolean;
92 }) => Effect.Effect<void, GitHubCliError>;
94​
95export class GitHubCli extends Context.Service<GitHubCli, GitHubCliShape>()(
96 "t3/sourceControl/GitHubCli",
97) {}
98​
99function errorText(error: VcsError | unknown): string {
100 if (typeof error === "object" && error !== null) {
101 const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
102 const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
103 const message = "message" in error && typeof error.message === "string" ? error.message : "";
104 return [tag, detail, message].filter(Boolean).join("\n");
105 }
106​
107 return String(error);
109​
110function normalizeGitHubCliError(
111 operation: "execute" | "stdout",
112 error: VcsError | unknown,
113): GitHubCliError {
114 const text = errorText(error);
115 const lower = text.toLowerCase();
116​
117 if (lower.includes("command not found: gh") || lower.includes("enoent")) {
118 return new GitHubCliError({
119 operation,
120 detail: "GitHub CLI (`gh`) is required but not available on PATH.",
121 cause: error,
122 });
123 }
124​
125 if (
126 lower.includes("authentication failed") ||
127 lower.includes("not logged in") ||
128 lower.includes("gh auth login") ||
129 lower.includes("no oauth token")
130 ) {
131 return new GitHubCliError({
132 operation,
133 detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
134 cause: error,
135 });
136 }
137​
138 if (
139 lower.includes("could not resolve to a pullrequest") ||
140 lower.includes("repository.pullrequest") ||
141 lower.includes("no pull requests found for branch") ||
142 lower.includes("pull request not found")
143 ) {
144 return new GitHubCliError({
145 operation,
146 detail: "Pull request not found. Check the PR number or URL and try again.",
147 cause: error,
148 });
149 }
150​
151 return new GitHubCliError({
152 operation,
153 detail: text,
154 cause: error,
155 });
157​
158const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
159 nameWithOwner: TrimmedNonEmptyString,
160 url: TrimmedNonEmptyString,
161 sshUrl: TrimmedNonEmptyString,
162});
163​
164function normalizeRepositoryCloneUrls(
165 raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
166): GitHubRepositoryCloneUrls {
167 return {
168 nameWithOwner: raw.nameWithOwner,
169 url: raw.url,
170 sshUrl: raw.sshUrl,
171 };
173​
174/**
175 * `gh repo create` prints the canonical URL of the new repository on stdout
176 * (e.g. `https://github.com/owner/repo`). Reading it back here avoids a
177 * follow-up `gh repo view`, which can race GitHub's GraphQL eventual
178 * consistency window and falsely report the just-created repo as missing.
179 */
180function deriveRepositoryCloneUrlsFromCreateOutput(
181 stdout: string,
182 repository: string,
183): GitHubRepositoryCloneUrls {
184 const fallbackHost = "github.com";
185 const match = stdout.match(/https?:\/\/[^\s]+/);
186 if (match) {
187 const cleaned = match[0].replace(/\.git$/, "");
188 try {
189 const parsed = new URL(cleaned);
190 const pathname = parsed.pathname.replace(/^\/+|\/+$/g, "");
191 const segments = pathname.split("/").filter(Boolean);
192 if (segments.length === 2) {
193 const nameWithOwner = `${segments[0]}/${segments[1]}`;
194 return {
195 nameWithOwner,
196 url: `${parsed.origin}/${nameWithOwner}`,
197 sshUrl: `git@${parsed.host}:${nameWithOwner}.git`,
198 };
199 }
200 } catch {
201 // Fall through to the input-derived defaults below.
202 }
203 }
204 return {
205 nameWithOwner: repository,
206 url: `https://${fallbackHost}/${repository}`,
207 sshUrl: `git@${fallbackHost}:${repository}.git`,
208 };
210​
211function decodeGitHubJson<S extends Schema.Top>(
212 raw: string,
213 schema: S,
214 operation: "listOpenPullRequests" | "getPullRequest" | "getRepositoryCloneUrls",
215 invalidDetail: string,
216): Effect.Effect<S["Type"], GitHubCliError, S["DecodingServices"]> {
217 return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
218 Effect.mapError(
219 (error) =>
220 new GitHubCliError({
221 operation,
222 detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
223 cause: error,
224 }),
225 ),
226 );
228​
229export const make = Effect.fn("makeGitHubCli")(function* () {
230 const process = yield* VcsProcess.VcsProcess;
231​
232 const execute: GitHubCliShape["execute"] = (input) =>
233 process
234 .run({
235 operation: "GitHubCli.execute",
236 command: "gh",
237 args: input.args,
238 cwd: input.cwd,
239 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
240 })
241 .pipe(Effect.mapError((error) => normalizeGitHubCliError("execute", error)));
242​
243 return GitHubCli.of({
244 execute,
245 listOpenPullRequests: (input) =>
246 execute({
247 cwd: input.cwd,
248 args: [
249 "pr",
250 "list",
251 "--head",
252 input.headSelector,
253 "--state",
254 "open",
255 "--limit",
256 String(input.limit ?? 1),
257 "--json",
258 "number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
259 ],
260 }).pipe(
261 Effect.map((result) => result.stdout.trim()),
262 Effect.flatMap((raw) =>
263 raw.length === 0
264 ? Effect.succeed([])
265 : Effect.sync(() => GitHubPullRequests.decodeGitHubPullRequestListJson(raw)).pipe(
266 Effect.flatMap((decoded) => {
267 if (!Result.isSuccess(decoded)) {
268 return Effect.fail(
269 new GitHubCliError({
270 operation: "listOpenPullRequests",
271 detail: `GitHub CLI returned invalid PR list JSON: ${GitHubPullRequests.formatGitHubJsonDecodeError(decoded.failure)}`,
272 cause: decoded.failure,
273 }),
274 );
275 }
276​
277 return Effect.succeed(
278 decoded.success.map(({ updatedAt: _updatedAt, ...summary }) => summary),
279 );
280 }),
281 ),
282 ),
283 ),
284 getPullRequest: (input) =>
285 execute({
286 cwd: input.cwd,
287 args: [
288 "pr",
289 "view",
290 input.reference,
291 "--json",
292 "number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
293 ],
294 }).pipe(
295 Effect.map((result) => result.stdout.trim()),
296 Effect.flatMap((raw) =>
297 Effect.sync(() => GitHubPullRequests.decodeGitHubPullRequestJson(raw)).pipe(
298 Effect.flatMap((decoded) => {
299 if (!Result.isSuccess(decoded)) {
300 return Effect.fail(
301 new GitHubCliError({
302 operation: "getPullRequest",
303 detail: `GitHub CLI returned invalid pull request JSON: ${GitHubPullRequests.formatGitHubJsonDecodeError(decoded.failure)}`,
304 cause: decoded.failure,
305 }),
306 );
307 }
308​
309 return Effect.succeed(
310 (({ updatedAt: _updatedAt, ...summary }) => summary)(decoded.success),
311 );
312 }),
313 ),
314 ),
315 ),
316 getRepositoryCloneUrls: (input) =>
317 execute({
318 cwd: input.cwd,
319 args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
320 }).pipe(
321 Effect.map((result) => result.stdout.trim()),
322 Effect.flatMap((raw) =>
323 decodeGitHubJson(
324 raw,
325 RawGitHubRepositoryCloneUrlsSchema,
326 "getRepositoryCloneUrls",
327 "GitHub CLI returned invalid repository JSON.",
328 ),
329 ),
330 Effect.map(normalizeRepositoryCloneUrls),
331 ),
332 createRepository: (input) =>
333 execute({
334 cwd: input.cwd,
335 args: ["repo", "create", input.repository, `--${input.visibility}`],
336 }).pipe(
337 Effect.map((result) =>
338 deriveRepositoryCloneUrlsFromCreateOutput(result.stdout, input.repository),
339 ),
340 ),
341 createPullRequest: (input) =>
342 execute({
343 cwd: input.cwd,
344 args: [
345 "pr",
346 "create",
347 "--base",
348 input.baseBranch,
349 "--head",
350 input.headSelector,
351 "--title",
352 input.title,
353 "--body-file",
354 input.bodyFile,
355 ],
356 }).pipe(Effect.asVoid),
357 getDefaultBranch: (input) =>
358 execute({
359 cwd: input.cwd,
360 args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
361 }).pipe(
362 Effect.map((value) => {
363 const trimmed = value.stdout.trim();
364 return trimmed.length > 0 ? trimmed : null;
365 }),
366 ),
367 checkoutPullRequest: (input) =>
368 execute({
369 cwd: input.cwd,
370 args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
371 }).pipe(Effect.asVoid),
372 });
373});
374​
375export const layer = Layer.effect(GitHubCli, make());