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

GitHubCli.ts

478 lines14.3 KB

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