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

GitHubCli.ts

487 lines14.6 KB

1import * as Context from "effect/Context";
2import * as DateTime from "effect/DateTime";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as PlatformError from "effect/PlatformError";
7import * as Result from "effect/Result";
8import * as Schema from "effect/Schema";
9​
10import {
11 TrimmedNonEmptyString,
12 type SourceControlRepositoryVisibility,
13 type VcsError,
14} from "@t3tools/contracts";
15​
16import * as VcsProcess from "../vcs/VcsProcess.ts";
17import {
18 decodeGitHubPullRequestJson,
19 decodeGitHubPullRequestListJson,
20 type NormalizedGitHubPullRequestRecord,
21} from "./gitHubPullRequests.ts";
22​
23const DEFAULT_TIMEOUT_MS = 30_000;
24​
25const gitHubCliFailureFields = {
26 command: Schema.Literal("gh"),
27 cwd: Schema.String,
28 cause: Schema.Defect(),
29} as const;
30​
31export class GitHubCliUnavailableError extends Schema.TaggedErrorClass<GitHubCliUnavailableError>()(
32 "GitHubCliUnavailableError",
33 gitHubCliFailureFields,
34) {
35 get detail(): string {
36 return "GitHub CLI (`gh`) is required but not available on PATH.";
37 }
38​
39 override get message(): string {
40 return `GitHub CLI failed in execute: ${this.detail}`;
41 }
43​
44export class GitHubCliAuthenticationError extends Schema.TaggedErrorClass<GitHubCliAuthenticationError>()(
45 "GitHubCliAuthenticationError",
46 gitHubCliFailureFields,
47) {
48 get detail(): string {
49 return "GitHub CLI is not authenticated. Run `gh auth login` and retry.";
50 }
51​
52 override get message(): string {
53 return `GitHub CLI failed in execute: ${this.detail}`;
54 }
56​
57export class GitHubCliRateLimitError extends Schema.TaggedErrorClass<GitHubCliRateLimitError>()(
58 "GitHubCliRateLimitError",
59 gitHubCliFailureFields,
60) {
61 get detail(): string {
62 return "GitHub API rate limit exceeded. Run `gh api rate_limit` to inspect the quota and reset time.";
63 }
64​
65 override get message(): string {
66 return `GitHub CLI failed in execute: ${this.detail}`;
67 }
69​
70export class GitHubPullRequestNotFoundError extends Schema.TaggedErrorClass<GitHubPullRequestNotFoundError>()(
71 "GitHubPullRequestNotFoundError",
72 gitHubCliFailureFields,
73) {
74 get detail(): string {
75 return "Pull request not found. Check the PR number or URL and try again.";
76 }
77​
78 override get message(): string {
79 return `GitHub CLI failed in execute: ${this.detail}`;
80 }
82​
83export class GitHubCliCommandError extends Schema.TaggedErrorClass<GitHubCliCommandError>()(
84 "GitHubCliCommandError",
85 gitHubCliFailureFields,
86) {
87 get detail(): string {
88 return "GitHub CLI command failed.";
89 }
90​
91 override get message(): string {
92 return `GitHub CLI failed in execute: ${this.detail}`;
93 }
95​
96const gitHubCliDecodeFields = {
97 command: Schema.Literal("gh"),
98 cwd: Schema.String,
99 cause: Schema.Defect(),
100} as const;
101​
102export class GitHubPullRequestListDecodeError extends Schema.TaggedErrorClass<GitHubPullRequestListDecodeError>()(
103 "GitHubPullRequestListDecodeError",
104 gitHubCliDecodeFields,
105) {
106 get detail(): string {
107 return "GitHub CLI returned invalid PR list JSON.";
108 }
109​
110 override get message(): string {
111 return `GitHub CLI failed in listOpenPullRequests: ${this.detail}`;
112 }
114​
115export class GitHubChangeRequestListDecodeError extends Schema.TaggedErrorClass<GitHubChangeRequestListDecodeError>()(
116 "GitHubChangeRequestListDecodeError",
117 gitHubCliDecodeFields,
118) {
119 get detail(): string {
120 return "GitHub CLI returned invalid change request JSON.";
121 }
122​
123 override get message(): string {
124 return `GitHub CLI failed in listChangeRequests: ${this.detail}`;
125 }
127​
128export class GitHubPullRequestDecodeError extends Schema.TaggedErrorClass<GitHubPullRequestDecodeError>()(
129 "GitHubPullRequestDecodeError",
130 gitHubCliDecodeFields,
131) {
132 get detail(): string {
133 return "GitHub CLI returned invalid pull request JSON.";
134 }
135​
136 override get message(): string {
137 return `GitHub CLI failed in getPullRequest: ${this.detail}`;
138 }
140​
141export class GitHubRepositoryDecodeError extends Schema.TaggedErrorClass<GitHubRepositoryDecodeError>()(
142 "GitHubRepositoryDecodeError",
143 gitHubCliDecodeFields,
144) {
145 get detail(): string {
146 return "GitHub CLI returned invalid repository JSON.";
147 }
148​
149 override get message(): string {
150 return `GitHub CLI failed in getRepositoryCloneUrls: ${this.detail}`;
151 }
153​
154export const GitHubCliError = Schema.Union([
155 GitHubCliUnavailableError,
156 GitHubCliAuthenticationError,
157 GitHubCliRateLimitError,
158 GitHubPullRequestNotFoundError,
159 GitHubCliCommandError,
160 GitHubPullRequestListDecodeError,
161 GitHubChangeRequestListDecodeError,
162 GitHubPullRequestDecodeError,
163 GitHubRepositoryDecodeError,
164]);
165export type GitHubCliError = typeof GitHubCliError.Type;
166​
167export const isGitHubCliError = Schema.is(GitHubCliError);
168​
169export function fromVcsError(
170 context: {
171 readonly command: "gh";
172 readonly cwd: string;
173 },
174 error: VcsError,
175): GitHubCliError {
176 if (
177 error._tag === "VcsProcessSpawnError" &&
178 error.cause instanceof PlatformError.PlatformError &&
179 error.cause.reason._tag === "NotFound" &&
180 error.cause.reason.module === "ChildProcess" &&
181 error.cause.reason.method === "spawn"
182 ) {
183 return new GitHubCliUnavailableError({ ...context, cause: error });
184 }
185​
186 if (error._tag === "VcsProcessExitError") {
187 if (error.failureKind === "authentication") {
188 return new GitHubCliAuthenticationError({ ...context, cause: error });
189 }
190 if (error.failureKind === "rate-limited") {
191 return new GitHubCliRateLimitError({ ...context, cause: error });
192 }
193 if (error.failureKind === "not-found") {
194 return new GitHubPullRequestNotFoundError({ ...context, cause: error });
195 }
196 }
197​
198 return new GitHubCliCommandError({ ...context, cause: error });
200​
201export interface GitHubPullRequestSummary {
202 readonly number: number;
203 readonly title: string;
204 readonly url: string;
205 readonly baseRefName: string;
206 readonly headRefName: string;
207 readonly state?: "open" | "closed" | "merged";
208 readonly isDraft?: boolean;
209 readonly updatedAt?: string;
210 readonly isCrossRepository?: boolean;
211 readonly headRepositoryNameWithOwner?: string | null;
212 readonly headRepositoryOwnerLogin?: string | null;
214​
215function pullRequestSummary(input: NormalizedGitHubPullRequestRecord): GitHubPullRequestSummary {
216 const { updatedAt, ...summary } = input;
217 return {
218 ...summary,
219 ...(Option.isSome(updatedAt) ? { updatedAt: DateTime.formatIso(updatedAt.value) } : {}),
220 };
222​
223export interface GitHubRepositoryCloneUrls {
224 readonly nameWithOwner: string;
225 readonly url: string;
226 readonly sshUrl: string;
228​
229export class GitHubCli extends Context.Service<
230 GitHubCli,
231 {
232 readonly execute: (input: {
233 readonly cwd: string;
234 readonly args: ReadonlyArray<string>;
235 readonly timeoutMs?: number;
236 /** Piped to the child's stdin, for payloads that must never appear in argv. */
237 readonly stdin?: string;
238 readonly maxOutputBytes?: number;
239 }) => Effect.Effect<VcsProcess.VcsProcessOutput, GitHubCliError>;
240​
241 readonly listOpenPullRequests: (input: {
242 readonly cwd: string;
243 readonly headSelector: string;
244 readonly limit?: number;
245 }) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
246​
247 readonly getPullRequest: (input: {
248 readonly cwd: string;
249 readonly reference: string;
250 }) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
251​
252 readonly getRepositoryCloneUrls: (input: {
253 readonly cwd: string;
254 readonly repository: string;
255 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
256​
257 readonly createRepository: (input: {
258 readonly cwd: string;
259 readonly repository: string;
260 readonly visibility: SourceControlRepositoryVisibility;
261 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
262​
263 readonly createPullRequest: (input: {
264 readonly cwd: string;
265 readonly baseBranch: string;
266 readonly headSelector: string;
267 readonly title: string;
268 readonly bodyFile: string;
269 }) => Effect.Effect<void, GitHubCliError>;
270​
271 readonly getDefaultBranch: (input: {
272 readonly cwd: string;
273 }) => Effect.Effect<string | null, GitHubCliError>;
274​
275 readonly checkoutPullRequest: (input: {
276 readonly cwd: string;
277 readonly reference: string;
278 readonly force?: boolean;
279 }) => Effect.Effect<void, GitHubCliError>;
280 }
281>()("t3/sourceControl/GitHubCli") {}
282​
283const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
284 nameWithOwner: TrimmedNonEmptyString,
285 url: TrimmedNonEmptyString,
286 sshUrl: TrimmedNonEmptyString,
287});
288const decodeRawGitHubRepositoryCloneUrls = Schema.decodeEffect(
289 Schema.fromJsonString(RawGitHubRepositoryCloneUrlsSchema),
290);
291​
292function normalizeRepositoryCloneUrls(
293 raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
294): GitHubRepositoryCloneUrls {
295 return {
296 nameWithOwner: raw.nameWithOwner,
297 url: raw.url,
298 sshUrl: raw.sshUrl,
299 };
301​
302/**
303 * `gh repo create` prints the canonical URL of the new repository on stdout
304 * (e.g. `https://github.com/owner/repo`). Reading it back here avoids a
305 * follow-up `gh repo view`, which can race GitHub's GraphQL eventual
306 * consistency window and falsely report the just-created repo as missing.
307 */
308function deriveRepositoryCloneUrlsFromCreateOutput(
309 stdout: string,
310 repository: string,
311): GitHubRepositoryCloneUrls {
312 const fallbackHost = "github.com";
313 const match = stdout.match(/https?:\/\/[^\s]+/);
314 if (match) {
315 const cleaned = match[0].replace(/\.git$/, "");
316 try {
317 const parsed = new URL(cleaned);
318 const pathname = parsed.pathname.replace(/^\/+|\/+$/g, "");
319 const segments = pathname.split("/").filter(Boolean);
320 if (segments.length === 2) {
321 const nameWithOwner = `${segments[0]}/${segments[1]}`;
322 return {
323 nameWithOwner,
324 url: `${parsed.origin}/${nameWithOwner}`,
325 sshUrl: `git@${parsed.host}:${nameWithOwner}.git`,
326 };
327 }
328 } catch {
329 // Fall through to the input-derived defaults below.
330 }
331 }
332 return {
333 nameWithOwner: repository,
334 url: `https://${fallbackHost}/${repository}`,
335 sshUrl: `git@${fallbackHost}:${repository}.git`,
336 };
338​
339export const make = Effect.gen(function* () {
340 const process = yield* VcsProcess.VcsProcess;
341​
342 const execute: GitHubCli["Service"]["execute"] = (input) =>
343 process
344 .run({
345 operation: "GitHubCli.execute",
346 command: "gh",
347 args: input.args,
348 cwd: input.cwd,
349 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
350 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
351 ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
352 })
353 .pipe(Effect.mapError((error) => fromVcsError({ command: "gh", cwd: input.cwd }, error)));
354​
355 return GitHubCli.of({
356 execute,
357 listOpenPullRequests: (input) =>
358 execute({
359 cwd: input.cwd,
360 args: [
361 "pr",
362 "list",
363 "--head",
364 input.headSelector,
365 "--state",
366 "open",
367 "--limit",
368 String(input.limit ?? 1),
369 "--json",
370 "number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
371 ],
372 }).pipe(
373 Effect.map((result) => result.stdout.trim()),
374 Effect.flatMap((raw) =>
375 raw.length === 0
376 ? Effect.succeed([])
377 : Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
378 Effect.flatMap((decoded) => {
379 if (!Result.isSuccess(decoded)) {
380 return Effect.fail(
381 new GitHubPullRequestListDecodeError({
382 command: "gh",
383 cwd: input.cwd,
384 cause: decoded.failure,
385 }),
386 );
387 }
388​
389 return Effect.succeed(decoded.success.map(pullRequestSummary));
390 }),
391 ),
392 ),
393 ),
394 getPullRequest: (input) =>
395 execute({
396 cwd: input.cwd,
397 args: [
398 "pr",
399 "view",
400 input.reference,
401 "--json",
402 "number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
403 ],
404 }).pipe(
405 Effect.map((result) => result.stdout.trim()),
406 Effect.flatMap((raw) =>
407 Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
408 Effect.flatMap((decoded) => {
409 if (!Result.isSuccess(decoded)) {
410 return Effect.fail(
411 new GitHubPullRequestDecodeError({
412 command: "gh",
413 cwd: input.cwd,
414 cause: decoded.failure,
415 }),
416 );
417 }
418​
419 return Effect.succeed(pullRequestSummary(decoded.success));
420 }),
421 ),
422 ),
423 ),
424 getRepositoryCloneUrls: (input) =>
425 execute({
426 cwd: input.cwd,
427 args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
428 }).pipe(
429 Effect.map((result) => result.stdout.trim()),
430 Effect.flatMap((raw) =>
431 decodeRawGitHubRepositoryCloneUrls(raw).pipe(
432 Effect.mapError(
433 (cause) =>
434 new GitHubRepositoryDecodeError({
435 command: "gh",
436 cwd: input.cwd,
437 cause,
438 }),
439 ),
440 ),
441 ),
442 Effect.map(normalizeRepositoryCloneUrls),
443 ),
444 createRepository: (input) =>
445 execute({
446 cwd: input.cwd,
447 args: ["repo", "create", input.repository, `--${input.visibility}`],
448 }).pipe(
449 Effect.map((result) =>
450 deriveRepositoryCloneUrlsFromCreateOutput(result.stdout, input.repository),
451 ),
452 ),
453 createPullRequest: (input) =>
454 execute({
455 cwd: input.cwd,
456 args: [
457 "pr",
458 "create",
459 "--base",
460 input.baseBranch,
461 "--head",
462 input.headSelector,
463 "--title",
464 input.title,
465 "--body-file",
466 input.bodyFile,
467 ],
468 }).pipe(Effect.asVoid),
469 getDefaultBranch: (input) =>
470 execute({
471 cwd: input.cwd,
472 args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
473 }).pipe(
474 Effect.map((value) => {
475 const trimmed = value.stdout.trim();
476 return trimmed.length > 0 ? trimmed : null;
477 }),
478 ),
479 checkoutPullRequest: (input) =>
480 execute({
481 cwd: input.cwd,
482 args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
483 }).pipe(Effect.asVoid),
484 });
485});
486​
487export const layer = Layer.effect(GitHubCli, make);