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

GitHubCli.ts

486 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 updatedAt?: string;
209 readonly isCrossRepository?: boolean;
210 readonly headRepositoryNameWithOwner?: string | null;
211 readonly headRepositoryOwnerLogin?: string | null;
213​
214function pullRequestSummary(input: NormalizedGitHubPullRequestRecord): GitHubPullRequestSummary {
215 const { updatedAt, ...summary } = input;
216 return {
217 ...summary,
218 ...(Option.isSome(updatedAt) ? { updatedAt: DateTime.formatIso(updatedAt.value) } : {}),
219 };
221​
222export interface GitHubRepositoryCloneUrls {
223 readonly nameWithOwner: string;
224 readonly url: string;
225 readonly sshUrl: string;
227​
228export class GitHubCli extends Context.Service<
229 GitHubCli,
230 {
231 readonly execute: (input: {
232 readonly cwd: string;
233 readonly args: ReadonlyArray<string>;
234 readonly timeoutMs?: number;
235 /** Piped to the child's stdin, for payloads that must never appear in argv. */
236 readonly stdin?: string;
237 readonly maxOutputBytes?: number;
238 }) => Effect.Effect<VcsProcess.VcsProcessOutput, GitHubCliError>;
239​
240 readonly listOpenPullRequests: (input: {
241 readonly cwd: string;
242 readonly headSelector: string;
243 readonly limit?: number;
244 }) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
245​
246 readonly getPullRequest: (input: {
247 readonly cwd: string;
248 readonly reference: string;
249 }) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
250​
251 readonly getRepositoryCloneUrls: (input: {
252 readonly cwd: string;
253 readonly repository: string;
254 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
255​
256 readonly createRepository: (input: {
257 readonly cwd: string;
258 readonly repository: string;
259 readonly visibility: SourceControlRepositoryVisibility;
260 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
261​
262 readonly createPullRequest: (input: {
263 readonly cwd: string;
264 readonly baseBranch: string;
265 readonly headSelector: string;
266 readonly title: string;
267 readonly bodyFile: string;
268 }) => Effect.Effect<void, GitHubCliError>;
269​
270 readonly getDefaultBranch: (input: {
271 readonly cwd: string;
272 }) => Effect.Effect<string | null, GitHubCliError>;
273​
274 readonly checkoutPullRequest: (input: {
275 readonly cwd: string;
276 readonly reference: string;
277 readonly force?: boolean;
278 }) => Effect.Effect<void, GitHubCliError>;
279 }
280>()("t3/sourceControl/GitHubCli") {}
281​
282const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
283 nameWithOwner: TrimmedNonEmptyString,
284 url: TrimmedNonEmptyString,
285 sshUrl: TrimmedNonEmptyString,
286});
287const decodeRawGitHubRepositoryCloneUrls = Schema.decodeEffect(
288 Schema.fromJsonString(RawGitHubRepositoryCloneUrlsSchema),
289);
290​
291function normalizeRepositoryCloneUrls(
292 raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
293): GitHubRepositoryCloneUrls {
294 return {
295 nameWithOwner: raw.nameWithOwner,
296 url: raw.url,
297 sshUrl: raw.sshUrl,
298 };
300​
301/**
302 * `gh repo create` prints the canonical URL of the new repository on stdout
303 * (e.g. `https://github.com/owner/repo`). Reading it back here avoids a
304 * follow-up `gh repo view`, which can race GitHub's GraphQL eventual
305 * consistency window and falsely report the just-created repo as missing.
306 */
307function deriveRepositoryCloneUrlsFromCreateOutput(
308 stdout: string,
309 repository: string,
310): GitHubRepositoryCloneUrls {
311 const fallbackHost = "github.com";
312 const match = stdout.match(/https?:\/\/[^\s]+/);
313 if (match) {
314 const cleaned = match[0].replace(/\.git$/, "");
315 try {
316 const parsed = new URL(cleaned);
317 const pathname = parsed.pathname.replace(/^\/+|\/+$/g, "");
318 const segments = pathname.split("/").filter(Boolean);
319 if (segments.length === 2) {
320 const nameWithOwner = `${segments[0]}/${segments[1]}`;
321 return {
322 nameWithOwner,
323 url: `${parsed.origin}/${nameWithOwner}`,
324 sshUrl: `git@${parsed.host}:${nameWithOwner}.git`,
325 };
326 }
327 } catch {
328 // Fall through to the input-derived defaults below.
329 }
330 }
331 return {
332 nameWithOwner: repository,
333 url: `https://${fallbackHost}/${repository}`,
334 sshUrl: `git@${fallbackHost}:${repository}.git`,
335 };
337​
338export const make = Effect.gen(function* () {
339 const process = yield* VcsProcess.VcsProcess;
340​
341 const execute: GitHubCli["Service"]["execute"] = (input) =>
342 process
343 .run({
344 operation: "GitHubCli.execute",
345 command: "gh",
346 args: input.args,
347 cwd: input.cwd,
348 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
349 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
350 ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
351 })
352 .pipe(Effect.mapError((error) => fromVcsError({ command: "gh", cwd: input.cwd }, error)));
353​
354 return GitHubCli.of({
355 execute,
356 listOpenPullRequests: (input) =>
357 execute({
358 cwd: input.cwd,
359 args: [
360 "pr",
361 "list",
362 "--head",
363 input.headSelector,
364 "--state",
365 "open",
366 "--limit",
367 String(input.limit ?? 1),
368 "--json",
369 "number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
370 ],
371 }).pipe(
372 Effect.map((result) => result.stdout.trim()),
373 Effect.flatMap((raw) =>
374 raw.length === 0
375 ? Effect.succeed([])
376 : Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
377 Effect.flatMap((decoded) => {
378 if (!Result.isSuccess(decoded)) {
379 return Effect.fail(
380 new GitHubPullRequestListDecodeError({
381 command: "gh",
382 cwd: input.cwd,
383 cause: decoded.failure,
384 }),
385 );
386 }
387​
388 return Effect.succeed(decoded.success.map(pullRequestSummary));
389 }),
390 ),
391 ),
392 ),
393 getPullRequest: (input) =>
394 execute({
395 cwd: input.cwd,
396 args: [
397 "pr",
398 "view",
399 input.reference,
400 "--json",
401 "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
402 ],
403 }).pipe(
404 Effect.map((result) => result.stdout.trim()),
405 Effect.flatMap((raw) =>
406 Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
407 Effect.flatMap((decoded) => {
408 if (!Result.isSuccess(decoded)) {
409 return Effect.fail(
410 new GitHubPullRequestDecodeError({
411 command: "gh",
412 cwd: input.cwd,
413 cause: decoded.failure,
414 }),
415 );
416 }
417​
418 return Effect.succeed(pullRequestSummary(decoded.success));
419 }),
420 ),
421 ),
422 ),
423 getRepositoryCloneUrls: (input) =>
424 execute({
425 cwd: input.cwd,
426 args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
427 }).pipe(
428 Effect.map((result) => result.stdout.trim()),
429 Effect.flatMap((raw) =>
430 decodeRawGitHubRepositoryCloneUrls(raw).pipe(
431 Effect.mapError(
432 (cause) =>
433 new GitHubRepositoryDecodeError({
434 command: "gh",
435 cwd: input.cwd,
436 cause,
437 }),
438 ),
439 ),
440 ),
441 Effect.map(normalizeRepositoryCloneUrls),
442 ),
443 createRepository: (input) =>
444 execute({
445 cwd: input.cwd,
446 args: ["repo", "create", input.repository, `--${input.visibility}`],
447 }).pipe(
448 Effect.map((result) =>
449 deriveRepositoryCloneUrlsFromCreateOutput(result.stdout, input.repository),
450 ),
451 ),
452 createPullRequest: (input) =>
453 execute({
454 cwd: input.cwd,
455 args: [
456 "pr",
457 "create",
458 "--base",
459 input.baseBranch,
460 "--head",
461 input.headSelector,
462 "--title",
463 input.title,
464 "--body-file",
465 input.bodyFile,
466 ],
467 }).pipe(Effect.asVoid),
468 getDefaultBranch: (input) =>
469 execute({
470 cwd: input.cwd,
471 args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
472 }).pipe(
473 Effect.map((value) => {
474 const trimmed = value.stdout.trim();
475 return trimmed.length > 0 ? trimmed : null;
476 }),
477 ),
478 checkoutPullRequest: (input) =>
479 execute({
480 cwd: input.cwd,
481 args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
482 }).pipe(Effect.asVoid),
483 });
484});
485​
486export const layer = Layer.effect(GitHubCli, make);