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

GitHubCli.ts

370 lines11.3 KB

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