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

GitHubCli.ts

629 lines19.9 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 Redacted from "effect/Redacted";
8import * as Result from "effect/Result";
9import * as Schema from "effect/Schema";
10​
11import {
12 TrimmedNonEmptyString,
13 type SourceControlRepositoryVisibility,
14 type VcsError,
15} from "@t3tools/contracts";
16​
17import * as VcsProcess from "../vcs/VcsProcess.ts";
18import {
19 decodeGitHubPullRequestJson,
20 decodeGitHubPullRequestListJson,
21 type NormalizedGitHubPullRequestRecord,
22} from "./gitHubPullRequests.ts";
23​
24const DEFAULT_TIMEOUT_MS = 30_000;
25​
26/** Server-local credential scope; never put its value in RPC payloads or cache keys. */
27export const PinnedGitHubCredential = Context.Reference<{
28 readonly host: string;
29 readonly token: Redacted.Redacted<string>;
30 readonly credentialFingerprint: string;
31} | null>("t3/sourceControl/PinnedGitHubCredential", { defaultValue: () => null });
32​
33function targetsVerifiedHost(args: ReadonlyArray<string>, host: string): boolean {
34 const hosts: Array<string | null> = [];
35 const repositoryHost = (repository: string | undefined) => {
36 if (repository === undefined) return null;
37 if (/^https?:\/\//i.test(repository)) {
38 try {
39 return new URL(repository).host.toLowerCase();
40 } catch {
41 return null;
42 }
43 }
44 const parts = repository.split("/");
45 return parts.length === 3 ? parts[0]!.toLowerCase() : null;
46 };
47 if (args[0] === "repo" && args[1] === "view") hosts.push(repositoryHost(args[2]));
48 for (let index = 0; index < args.length; index++) {
49 const arg = args[index]!;
50 if (arg === "--hostname") hosts.push(args[++index]?.toLowerCase() ?? null);
51 else if (arg.startsWith("--hostname=")) hosts.push(arg.slice(11).toLowerCase());
52 else if (arg === "--repo" || arg === "-R") hosts.push(repositoryHost(args[++index]));
53 else if (arg.startsWith("--repo=")) hosts.push(repositoryHost(arg.slice(7)));
54 else if (arg.startsWith("-R")) hosts.push(repositoryHost(arg.slice(2)));
55 else if (/^https?:\/\//i.test(arg)) hosts.push(repositoryHost(arg));
56 }
57 return hosts.length > 0 && hosts.every((target) => target === host);
59​
60const gitHubCliFailureFields = {
61 command: Schema.Literal("gh"),
62 cwd: Schema.String,
63 cause: Schema.Defect(),
64} as const;
65​
66export class GitHubCliUnavailableError extends Schema.TaggedError<GitHubCliUnavailableError>()(
67 "GitHubCliUnavailableError",
68 gitHubCliFailureFields,
69) {
70 get detail(): string {
71 return "GitHub CLI (`gh`) is required but not available on PATH.";
72 }
73​
74 override get message(): string {
75 return `GitHub CLI failed in execute: ${this.detail}`;
76 }
78​
79export class GitHubCliAuthenticationError extends Schema.TaggedError<GitHubCliAuthenticationError>()(
80 "GitHubCliAuthenticationError",
81 gitHubCliFailureFields,
82) {
83 get detail(): string {
84 return "GitHub CLI is not authenticated. Run `gh auth login` and retry.";
85 }
86​
87 override get message(): string {
88 return `GitHub CLI failed in execute: ${this.detail}`;
89 }
91​
92export class GitHubCliRateLimitError extends Schema.TaggedError<GitHubCliRateLimitError>()(
93 "GitHubCliRateLimitError",
94 gitHubCliFailureFields,
95) {
96 get detail(): string {
97 return "GitHub API rate limit exceeded. Run `gh api rate_limit` to inspect the quota and reset time.";
98 }
99​
100 override get message(): string {
101 return `GitHub CLI failed in execute: ${this.detail}`;
102 }
104​
105export class GitHubPullRequestNotFoundError extends Schema.TaggedError<GitHubPullRequestNotFoundError>()(
106 "GitHubPullRequestNotFoundError",
107 gitHubCliFailureFields,
108) {
109 get detail(): string {
110 return "Pull request not found. Check the PR number or URL and try again.";
111 }
112​
113 override get message(): string {
114 return `GitHub CLI failed in execute: ${this.detail}`;
115 }
117​
118export class GitHubCliCommandError extends Schema.TaggedError<GitHubCliCommandError>()(
119 "GitHubCliCommandError",
120 gitHubCliFailureFields,
121) {
122 get detail(): string {
123 return "GitHub CLI command failed.";
124 }
125​
126 override get message(): string {
127 return `GitHub CLI failed in execute: ${this.detail}`;
128 }
130​
131const gitHubCliDecodeFields = {
132 command: Schema.Literal("gh"),
133 cwd: Schema.String,
134 cause: Schema.Defect(),
135} as const;
136​
137export class GitHubPullRequestListDecodeError extends Schema.TaggedError<GitHubPullRequestListDecodeError>()(
138 "GitHubPullRequestListDecodeError",
139 gitHubCliDecodeFields,
140) {
141 get detail(): string {
142 return "GitHub CLI returned invalid PR list JSON.";
143 }
144​
145 override get message(): string {
146 return `GitHub CLI failed in listOpenPullRequests: ${this.detail}`;
147 }
149​
150export class GitHubChangeRequestListDecodeError extends Schema.TaggedError<GitHubChangeRequestListDecodeError>()(
151 "GitHubChangeRequestListDecodeError",
152 gitHubCliDecodeFields,
153) {
154 get detail(): string {
155 return "GitHub CLI returned invalid change request JSON.";
156 }
157​
158 override get message(): string {
159 return `GitHub CLI failed in listChangeRequests: ${this.detail}`;
160 }
162​
163export class GitHubPullRequestDecodeError extends Schema.TaggedError<GitHubPullRequestDecodeError>()(
164 "GitHubPullRequestDecodeError",
165 gitHubCliDecodeFields,
166) {
167 get detail(): string {
168 return "GitHub CLI returned invalid pull request JSON.";
169 }
170​
171 override get message(): string {
172 return `GitHub CLI failed in getPullRequest: ${this.detail}`;
173 }
175​
176export class GitHubRepositoryDecodeError extends Schema.TaggedError<GitHubRepositoryDecodeError>()(
177 "GitHubRepositoryDecodeError",
178 gitHubCliDecodeFields,
179) {
180 get detail(): string {
181 return "GitHub CLI returned invalid repository JSON.";
182 }
183​
184 override get message(): string {
185 return `GitHub CLI failed in getRepositoryCloneUrls: ${this.detail}`;
186 }
188​
189export class GitHubRepositorySearchDecodeError extends Schema.TaggedError<GitHubRepositorySearchDecodeError>()(
190 "GitHubRepositorySearchDecodeError",
191 gitHubCliDecodeFields,
192) {
193 get detail(): string {
194 return "GitHub CLI returned invalid repository search JSON.";
195 }
196​
197 override get message(): string {
198 return `GitHub CLI failed in searchRepositories: ${this.detail}`;
199 }
201​
202export const GitHubCliError = Schema.Union([
203 GitHubCliUnavailableError,
204 GitHubCliAuthenticationError,
205 GitHubCliRateLimitError,
206 GitHubPullRequestNotFoundError,
207 GitHubCliCommandError,
208 GitHubPullRequestListDecodeError,
209 GitHubChangeRequestListDecodeError,
210 GitHubPullRequestDecodeError,
211 GitHubRepositoryDecodeError,
212 GitHubRepositorySearchDecodeError,
213]);
214export type GitHubCliError = typeof GitHubCliError.Type;
215​
216export const isGitHubCliError = Schema.is(GitHubCliError);
217​
218export function fromVcsError(
219 context: {
220 readonly command: "gh";
221 readonly cwd: string;
222 },
223 error: VcsError,
224): GitHubCliError {
225 if (
226 error._tag === "VcsProcessSpawnError" &&
227 error.cause instanceof PlatformError.PlatformError &&
228 error.cause.reason._tag === "NotFound" &&
229 error.cause.reason.module === "ChildProcess" &&
230 error.cause.reason.method === "spawn"
231 ) {
232 return new GitHubCliUnavailableError({ ...context, cause: error });
233 }
234​
235 if (error._tag === "VcsProcessExitError") {
236 if (error.failureKind === "authentication") {
237 return new GitHubCliAuthenticationError({ ...context, cause: error });
238 }
239 if (error.failureKind === "rate-limited") {
240 return new GitHubCliRateLimitError({ ...context, cause: error });
241 }
242 if (error.failureKind === "not-found") {
243 return new GitHubPullRequestNotFoundError({ ...context, cause: error });
244 }
245 }
246​
247 return new GitHubCliCommandError({ ...context, cause: error });
249​
250export interface GitHubPullRequestSummary {
251 readonly number: number;
252 readonly title: string;
253 readonly url: string;
254 readonly baseRefName: string;
255 readonly headRefName: string;
256 readonly state?: "open" | "closed" | "merged";
257 readonly isDraft?: boolean;
258 readonly closedAt?: string | null;
259 readonly mergedAt?: string | null;
260 readonly updatedAt?: string;
261 readonly isCrossRepository?: boolean;
262 readonly headRepositoryNameWithOwner?: string | null;
263 readonly headRepositoryOwnerLogin?: string | null;
265​
266function pullRequestSummary(input: NormalizedGitHubPullRequestRecord): GitHubPullRequestSummary {
267 const { updatedAt, ...summary } = input;
268 return {
269 ...summary,
270 ...(Option.isSome(updatedAt) ? { updatedAt: DateTime.formatIso(updatedAt.value) } : {}),
271 };
273​
274export interface GitHubRepositoryCloneUrls {
275 readonly nameWithOwner: string;
276 readonly url: string;
277 readonly sshUrl: string;
279​
280export interface GitHubRepositorySearchResult {
281 readonly fullName: string;
283​
284export class GitHubCli extends Context.Service<
285 GitHubCli,
286 {
287 readonly execute: (input: {
288 readonly cwd: string;
289 readonly args: ReadonlyArray<string>;
290 readonly timeoutMs?: number;
291 readonly host?: string;
292 /** Piped to the child's stdin, for payloads that must never appear in argv. */
293 readonly stdin?: string;
294 readonly env?: NodeJS.ProcessEnv;
295 readonly maxOutputBytes?: number;
296 }) => Effect.Effect<VcsProcess.VcsProcessOutput, GitHubCliError>;
297​
298 readonly listOpenPullRequests: (input: {
299 readonly cwd: string;
300 readonly headSelector: string;
301 readonly limit?: number;
302 }) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
303​
304 readonly getPullRequest: (input: {
305 readonly cwd: string;
306 readonly reference: string;
307 }) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
308​
309 readonly getRepositoryCloneUrls: (input: {
310 readonly cwd: string;
311 readonly repository: string;
312 readonly host?: string;
313 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
314​
315 readonly searchRepositories: (input: {
316 readonly cwd: string;
317 readonly query: string;
318 readonly host?: string;
319 readonly limit?: number;
320 }) => Effect.Effect<ReadonlyArray<GitHubRepositorySearchResult>, GitHubCliError>;
321​
322 readonly createRepository: (input: {
323 readonly cwd: string;
324 readonly repository: string;
325 readonly visibility: SourceControlRepositoryVisibility;
326 readonly host?: string;
327 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
328​
329 readonly createPullRequest: (input: {
330 readonly cwd: string;
331 readonly baseBranch: string;
332 readonly headSelector: string;
333 readonly title: string;
334 readonly bodyFile: string;
335 }) => Effect.Effect<void, GitHubCliError>;
336​
337 readonly getDefaultBranch: (input: {
338 readonly cwd: string;
339 }) => Effect.Effect<string | null, GitHubCliError>;
340​
341 readonly checkoutPullRequest: (input: {
342 readonly cwd: string;
343 readonly reference: string;
344 readonly force?: boolean;
345 }) => Effect.Effect<void, GitHubCliError>;
346 }
347>()("t3/sourceControl/GitHubCli") {}
348​
349const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
350 nameWithOwner: TrimmedNonEmptyString,
351 url: TrimmedNonEmptyString,
352 sshUrl: TrimmedNonEmptyString,
353});
354const decodeRawGitHubRepositoryCloneUrls = Schema.decodeEffect(
355 Schema.fromJsonString(RawGitHubRepositoryCloneUrlsSchema),
356);
357​
358const RawGitHubRepositorySearchResultsSchema = Schema.Array(
359 Schema.Struct({
360 fullName: TrimmedNonEmptyString,
361 }),
362);
363const decodeRawGitHubRepositorySearchResults = Schema.decodeEffect(
364 Schema.fromJsonString(RawGitHubRepositorySearchResultsSchema),
365);
366​
367function normalizeRepositoryCloneUrls(
368 raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
369): GitHubRepositoryCloneUrls {
370 return {
371 nameWithOwner: raw.nameWithOwner,
372 url: raw.url,
373 sshUrl: raw.sshUrl,
374 };
376​
377/**
378 * `gh repo create` prints the canonical URL of the new repository on stdout
379 * (e.g. `https://github.com/owner/repo`). Reading it back here avoids a
380 * follow-up `gh repo view`, which can race GitHub's GraphQL eventual
381 * consistency window and falsely report the just-created repo as missing.
382 */
383function deriveRepositoryCloneUrlsFromCreateOutput(
384 stdout: string,
385 repository: string,
386 host: string = "github.com",
387): GitHubRepositoryCloneUrls {
388 const match = stdout.match(/https?:\/\/[^\s]+/);
389 if (match) {
390 const cleaned = match[0].replace(/\.git$/, "");
391 try {
392 const parsed = new URL(cleaned);
393 const pathname = parsed.pathname.replace(/^\/+|\/+$/g, "");
394 const segments = pathname.split("/").filter(Boolean);
395 if (segments.length === 2) {
396 const nameWithOwner = `${segments[0]}/${segments[1]}`;
397 return {
398 nameWithOwner,
399 url: `${parsed.origin}/${nameWithOwner}`,
400 sshUrl: `git@${parsed.host}:${nameWithOwner}.git`,
401 };
402 }
403 } catch {
404 // Fall through to the input-derived defaults below.
405 }
406 }
407 return {
408 nameWithOwner: repository,
409 url: `https://${host}/${repository}`,
410 sshUrl: `git@${host}:${repository}.git`,
411 };
413​
414/** @public Service construction is part of the canonical Effect module API. */
415export const make = Effect.gen(function* () {
416 const process = yield* VcsProcess.VcsProcess;
417​
418 const execute: GitHubCli["Service"]["execute"] = Effect.fn("GitHubCli.execute")(
419 function* (input) {
420 const credential = yield* PinnedGitHubCredential;
421 if (credential !== null && !targetsVerifiedHost(input.args, credential.host)) {
422 return yield* new GitHubCliCommandError({
423 command: "gh",
424 cwd: input.cwd,
425 cause: new Error("The GitHub command does not target the verified credential's host."),
426 });
427 }
428 const token = credential === null ? undefined : Redacted.value(credential.token);
429 // `extendEnv` follows `env` down in the runner, so the host environment is merged in and
430 // these are the overrides alone. A pinned credential names its own host and outranks the
431 // caller's, since the command has already been checked against it.
432 const env =
433 credential === null
434 ? input.host
435 ? { ...input.env, GH_HOST: input.host }
436 : input.env
437 : {
438 ...input.env,
439 GH_HOST: credential.host,
440 GH_TOKEN: token,
441 GITHUB_TOKEN: token,
442 GH_ENTERPRISE_TOKEN: token,
443 GITHUB_ENTERPRISE_TOKEN: token,
444 GH_DEBUG: "",
445 };
446 return yield* process
447 .run({
448 operation: "GitHubCli.execute",
449 command: "gh",
450 args: input.args,
451 cwd: input.cwd,
452 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
453 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
454 ...(env !== undefined ? { env } : {}),
455 ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
456 })
457 .pipe(Effect.mapError((error) => fromVcsError({ command: "gh", cwd: input.cwd }, error)));
458 },
459 );
460​
461 return GitHubCli.of({
462 execute,
463 listOpenPullRequests: (input) =>
464 execute({
465 cwd: input.cwd,
466 args: [
467 "pr",
468 "list",
469 "--head",
470 input.headSelector,
471 "--state",
472 "open",
473 "--limit",
474 String(input.limit ?? 1),
475 "--json",
476 "number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,isCrossRepository,headRepository,headRepositoryOwner",
477 ],
478 }).pipe(
479 Effect.map((result) => result.stdout.trim()),
480 Effect.flatMap((raw) =>
481 raw.length === 0
482 ? Effect.succeed([])
483 : Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
484 Effect.flatMap((decoded) => {
485 if (!Result.isSuccess(decoded)) {
486 return Effect.fail(
487 new GitHubPullRequestListDecodeError({
488 command: "gh",
489 cwd: input.cwd,
490 cause: decoded.failure,
491 }),
492 );
493 }
494​
495 return Effect.succeed(decoded.success.map(pullRequestSummary));
496 }),
497 ),
498 ),
499 ),
500 getPullRequest: (input) =>
501 execute({
502 cwd: input.cwd,
503 args: [
504 "pr",
505 "view",
506 input.reference,
507 "--json",
508 "number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
509 ],
510 }).pipe(
511 Effect.map((result) => result.stdout.trim()),
512 Effect.flatMap((raw) =>
513 Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
514 Effect.flatMap((decoded) => {
515 if (!Result.isSuccess(decoded)) {
516 return Effect.fail(
517 new GitHubPullRequestDecodeError({
518 command: "gh",
519 cwd: input.cwd,
520 cause: decoded.failure,
521 }),
522 );
523 }
524​
525 return Effect.succeed(pullRequestSummary(decoded.success));
526 }),
527 ),
528 ),
529 ),
530 getRepositoryCloneUrls: (input) =>
531 execute({
532 cwd: input.cwd,
533 args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
534 ...(input.host ? { host: input.host } : {}),
535 }).pipe(
536 Effect.map((result) => result.stdout.trim()),
537 Effect.flatMap((raw) =>
538 decodeRawGitHubRepositoryCloneUrls(raw).pipe(
539 Effect.mapError(
540 (cause) =>
541 new GitHubRepositoryDecodeError({
542 command: "gh",
543 cwd: input.cwd,
544 cause,
545 }),
546 ),
547 ),
548 ),
549 Effect.map(normalizeRepositoryCloneUrls),
550 ),
551 searchRepositories: (input) =>
552 execute({
553 cwd: input.cwd,
554 args: [
555 "search",
556 "repos",
557 input.query,
558 // Unscoped, GitHub also scores description and readme hits, and the caller reads the
559 // results as repository names: a description match can resolve as the sole near match.
560 "--match",
561 "name",
562 "--limit",
563 String(input.limit ?? 20),
564 "--json",
565 "fullName",
566 ],
567 ...(input.host ? { host: input.host } : {}),
568 }).pipe(
569 Effect.map((result) => result.stdout.trim()),
570 Effect.flatMap((raw) =>
571 raw.length === 0
572 ? Effect.succeed([])
573 : decodeRawGitHubRepositorySearchResults(raw).pipe(
574 Effect.mapError(
575 (cause) =>
576 new GitHubRepositorySearchDecodeError({
577 command: "gh",
578 cwd: input.cwd,
579 cause,
580 }),
581 ),
582 ),
583 ),
584 ),
585 createRepository: (input) =>
586 execute({
587 cwd: input.cwd,
588 args: ["repo", "create", input.repository, `--${input.visibility}`],
589 ...(input.host ? { host: input.host } : {}),
590 }).pipe(
591 Effect.map((result) =>
592 deriveRepositoryCloneUrlsFromCreateOutput(result.stdout, input.repository, input.host),
593 ),
594 ),
595 createPullRequest: (input) =>
596 execute({
597 cwd: input.cwd,
598 args: [
599 "pr",
600 "create",
601 "--base",
602 input.baseBranch,
603 "--head",
604 input.headSelector,
605 "--title",
606 input.title,
607 "--body-file",
608 input.bodyFile,
609 ],
610 }).pipe(Effect.asVoid),
611 getDefaultBranch: (input) =>
612 execute({
613 cwd: input.cwd,
614 args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
615 }).pipe(
616 Effect.map((value) => {
617 const trimmed = value.stdout.trim();
618 return trimmed.length > 0 ? trimmed : null;
619 }),
620 ),
621 checkoutPullRequest: (input) =>
622 execute({
623 cwd: input.cwd,
624 args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
625 }).pipe(Effect.asVoid),
626 });
627});
628​
629export const layer = Layer.effect(GitHubCli, make);