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

GitHubCli.ts

552 lines17.4 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 const GitHubCliError = Schema.Union([
190 GitHubCliUnavailableError,
191 GitHubCliAuthenticationError,
192 GitHubCliRateLimitError,
193 GitHubPullRequestNotFoundError,
194 GitHubCliCommandError,
195 GitHubPullRequestListDecodeError,
196 GitHubChangeRequestListDecodeError,
197 GitHubPullRequestDecodeError,
198 GitHubRepositoryDecodeError,
199]);
200export type GitHubCliError = typeof GitHubCliError.Type;
201​
202export const isGitHubCliError = Schema.is(GitHubCliError);
203​
204export function fromVcsError(
205 context: {
206 readonly command: "gh";
207 readonly cwd: string;
208 },
209 error: VcsError,
210): GitHubCliError {
211 if (
212 error._tag === "VcsProcessSpawnError" &&
213 error.cause instanceof PlatformError.PlatformError &&
214 error.cause.reason._tag === "NotFound" &&
215 error.cause.reason.module === "ChildProcess" &&
216 error.cause.reason.method === "spawn"
217 ) {
218 return new GitHubCliUnavailableError({ ...context, cause: error });
219 }
220​
221 if (error._tag === "VcsProcessExitError") {
222 if (error.failureKind === "authentication") {
223 return new GitHubCliAuthenticationError({ ...context, cause: error });
224 }
225 if (error.failureKind === "rate-limited") {
226 return new GitHubCliRateLimitError({ ...context, cause: error });
227 }
228 if (error.failureKind === "not-found") {
229 return new GitHubPullRequestNotFoundError({ ...context, cause: error });
230 }
231 }
232​
233 return new GitHubCliCommandError({ ...context, cause: error });
235​
236export interface GitHubPullRequestSummary {
237 readonly number: number;
238 readonly title: string;
239 readonly url: string;
240 readonly baseRefName: string;
241 readonly headRefName: string;
242 readonly state?: "open" | "closed" | "merged";
243 readonly isDraft?: boolean;
244 readonly closedAt?: string | null;
245 readonly mergedAt?: string | null;
246 readonly updatedAt?: string;
247 readonly isCrossRepository?: boolean;
248 readonly headRepositoryNameWithOwner?: string | null;
249 readonly headRepositoryOwnerLogin?: string | null;
250 readonly headRefOid?: string | null;
252​
253function pullRequestSummary(input: NormalizedGitHubPullRequestRecord): GitHubPullRequestSummary {
254 const { updatedAt, ...summary } = input;
255 return {
256 ...summary,
257 ...(Option.isSome(updatedAt) ? { updatedAt: DateTime.formatIso(updatedAt.value) } : {}),
258 };
260​
261export interface GitHubRepositoryCloneUrls {
262 readonly nameWithOwner: string;
263 readonly url: string;
264 readonly sshUrl: string;
266​
267export class GitHubCli extends Context.Service<
268 GitHubCli,
269 {
270 readonly execute: (input: {
271 readonly cwd: string;
272 readonly args: ReadonlyArray<string>;
273 readonly timeoutMs?: number;
274 /** Piped to the child's stdin, for payloads that must never appear in argv. */
275 readonly stdin?: string;
276 readonly env?: NodeJS.ProcessEnv;
277 readonly maxOutputBytes?: number;
278 }) => Effect.Effect<VcsProcess.VcsProcessOutput, GitHubCliError>;
279​
280 readonly listOpenPullRequests: (input: {
281 readonly cwd: string;
282 readonly headSelector: string;
283 readonly limit?: number;
284 }) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
285​
286 readonly getPullRequest: (input: {
287 readonly cwd: string;
288 readonly reference: string;
289 }) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
290​
291 readonly getRepositoryCloneUrls: (input: {
292 readonly cwd: string;
293 readonly repository: string;
294 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
295​
296 readonly createRepository: (input: {
297 readonly cwd: string;
298 readonly repository: string;
299 readonly visibility: SourceControlRepositoryVisibility;
300 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
301​
302 readonly createPullRequest: (input: {
303 readonly cwd: string;
304 readonly baseBranch: string;
305 readonly headSelector: string;
306 readonly title: string;
307 readonly bodyFile: string;
308 }) => Effect.Effect<void, GitHubCliError>;
309​
310 readonly getDefaultBranch: (input: {
311 readonly cwd: string;
312 }) => Effect.Effect<string | null, GitHubCliError>;
313​
314 readonly checkoutPullRequest: (input: {
315 readonly cwd: string;
316 readonly reference: string;
317 readonly force?: boolean;
318 }) => Effect.Effect<void, GitHubCliError>;
319 }
320>()("t3/sourceControl/GitHubCli") {}
321​
322const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
323 nameWithOwner: TrimmedNonEmptyString,
324 url: TrimmedNonEmptyString,
325 sshUrl: TrimmedNonEmptyString,
326});
327const decodeRawGitHubRepositoryCloneUrls = Schema.decodeEffect(
328 Schema.fromJsonString(RawGitHubRepositoryCloneUrlsSchema),
329);
330​
331function normalizeRepositoryCloneUrls(
332 raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
333): GitHubRepositoryCloneUrls {
334 return {
335 nameWithOwner: raw.nameWithOwner,
336 url: raw.url,
337 sshUrl: raw.sshUrl,
338 };
340​
341/**
342 * `gh repo create` prints the canonical URL of the new repository on stdout
343 * (e.g. `https://github.com/owner/repo`). Reading it back here avoids a
344 * follow-up `gh repo view`, which can race GitHub's GraphQL eventual
345 * consistency window and falsely report the just-created repo as missing.
346 */
347function deriveRepositoryCloneUrlsFromCreateOutput(
348 stdout: string,
349 repository: string,
350): GitHubRepositoryCloneUrls {
351 const fallbackHost = "github.com";
352 const match = stdout.match(/https?:\/\/[^\s]+/);
353 if (match) {
354 const cleaned = match[0].replace(/\.git$/, "");
355 try {
356 const parsed = new URL(cleaned);
357 const pathname = parsed.pathname.replace(/^\/+|\/+$/g, "");
358 const segments = pathname.split("/").filter(Boolean);
359 if (segments.length === 2) {
360 const nameWithOwner = `${segments[0]}/${segments[1]}`;
361 return {
362 nameWithOwner,
363 url: `${parsed.origin}/${nameWithOwner}`,
364 sshUrl: `git@${parsed.host}:${nameWithOwner}.git`,
365 };
366 }
367 } catch {
368 // Fall through to the input-derived defaults below.
369 }
370 }
371 return {
372 nameWithOwner: repository,
373 url: `https://${fallbackHost}/${repository}`,
374 sshUrl: `git@${fallbackHost}:${repository}.git`,
375 };
377​
378/** @public Service construction is part of the canonical Effect module API. */
379export const make = Effect.gen(function* () {
380 const process = yield* VcsProcess.VcsProcess;
381​
382 const execute: GitHubCli["Service"]["execute"] = Effect.fn("GitHubCli.execute")(
383 function* (input) {
384 const credential = yield* PinnedGitHubCredential;
385 if (credential !== null && !targetsVerifiedHost(input.args, credential.host)) {
386 return yield* new GitHubCliCommandError({
387 command: "gh",
388 cwd: input.cwd,
389 cause: new Error("The GitHub command does not target the verified credential's host."),
390 });
391 }
392 const token = credential === null ? undefined : Redacted.value(credential.token);
393 const env =
394 credential === null
395 ? input.env
396 : {
397 ...input.env,
398 GH_HOST: credential.host,
399 GH_TOKEN: token,
400 GITHUB_TOKEN: token,
401 GH_ENTERPRISE_TOKEN: token,
402 GITHUB_ENTERPRISE_TOKEN: token,
403 GH_DEBUG: "",
404 };
405 return yield* process
406 .run({
407 operation: "GitHubCli.execute",
408 command: "gh",
409 args: input.args,
410 cwd: input.cwd,
411 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
412 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
413 ...(env !== undefined ? { env } : {}),
414 ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
415 })
416 .pipe(Effect.mapError((error) => fromVcsError({ command: "gh", cwd: input.cwd }, error)));
417 },
418 );
419​
420 return GitHubCli.of({
421 execute,
422 listOpenPullRequests: (input) =>
423 execute({
424 cwd: input.cwd,
425 args: [
426 "pr",
427 "list",
428 "--head",
429 input.headSelector,
430 "--state",
431 "open",
432 "--limit",
433 String(input.limit ?? 1),
434 "--json",
435 "number,title,url,baseRefName,headRefName,headRefOid,state,isDraft,mergedAt,closedAt,isCrossRepository,headRepository,headRepositoryOwner",
436 ],
437 }).pipe(
438 Effect.map((result) => result.stdout.trim()),
439 Effect.flatMap((raw) =>
440 raw.length === 0
441 ? Effect.succeed([])
442 : Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
443 Effect.flatMap((decoded) => {
444 if (!Result.isSuccess(decoded)) {
445 return Effect.fail(
446 new GitHubPullRequestListDecodeError({
447 command: "gh",
448 cwd: input.cwd,
449 cause: decoded.failure,
450 }),
451 );
452 }
453​
454 return Effect.succeed(decoded.success.map(pullRequestSummary));
455 }),
456 ),
457 ),
458 ),
459 getPullRequest: (input) =>
460 execute({
461 cwd: input.cwd,
462 args: [
463 "pr",
464 "view",
465 input.reference,
466 "--json",
467 "number,title,url,baseRefName,headRefName,headRefOid,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
468 ],
469 }).pipe(
470 Effect.map((result) => result.stdout.trim()),
471 Effect.flatMap((raw) =>
472 Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
473 Effect.flatMap((decoded) => {
474 if (!Result.isSuccess(decoded)) {
475 return Effect.fail(
476 new GitHubPullRequestDecodeError({
477 command: "gh",
478 cwd: input.cwd,
479 cause: decoded.failure,
480 }),
481 );
482 }
483​
484 return Effect.succeed(pullRequestSummary(decoded.success));
485 }),
486 ),
487 ),
488 ),
489 getRepositoryCloneUrls: (input) =>
490 execute({
491 cwd: input.cwd,
492 args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
493 }).pipe(
494 Effect.map((result) => result.stdout.trim()),
495 Effect.flatMap((raw) =>
496 decodeRawGitHubRepositoryCloneUrls(raw).pipe(
497 Effect.mapError(
498 (cause) =>
499 new GitHubRepositoryDecodeError({
500 command: "gh",
501 cwd: input.cwd,
502 cause,
503 }),
504 ),
505 ),
506 ),
507 Effect.map(normalizeRepositoryCloneUrls),
508 ),
509 createRepository: (input) =>
510 execute({
511 cwd: input.cwd,
512 args: ["repo", "create", input.repository, `--${input.visibility}`],
513 }).pipe(
514 Effect.map((result) =>
515 deriveRepositoryCloneUrlsFromCreateOutput(result.stdout, input.repository),
516 ),
517 ),
518 createPullRequest: (input) =>
519 execute({
520 cwd: input.cwd,
521 args: [
522 "pr",
523 "create",
524 "--base",
525 input.baseBranch,
526 "--head",
527 input.headSelector,
528 "--title",
529 input.title,
530 "--body-file",
531 input.bodyFile,
532 ],
533 }).pipe(Effect.asVoid),
534 getDefaultBranch: (input) =>
535 execute({
536 cwd: input.cwd,
537 args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
538 }).pipe(
539 Effect.map((value) => {
540 const trimmed = value.stdout.trim();
541 return trimmed.length > 0 ? trimmed : null;
542 }),
543 ),
544 checkoutPullRequest: (input) =>
545 execute({
546 cwd: input.cwd,
547 args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
548 }).pipe(Effect.asVoid),
549 });
550});
551​
552export const layer = Layer.effect(GitHubCli, make);