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

GitHubCli.ts

680 lines20.6 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 type GitHubAccountSelection,
10 TrimmedNonEmptyString,
11 type SourceControlRepositoryVisibility,
12 type VcsError,
13} from "@t3tools/contracts";
14​
15import * as ServerSettings from "../serverSettings.ts";
16import * as VcsProcess from "../vcs/VcsProcess.ts";
17import * as GitHubCredentials from "./GitHubCredentials.ts";
18import {
19 decodeGitHubPullRequestJson,
20 decodeGitHubPullRequestListJson,
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 GitHubPullRequestNotFoundError extends Schema.TaggedErrorClass<GitHubPullRequestNotFoundError>()(
58 "GitHubPullRequestNotFoundError",
59 gitHubCliFailureFields,
60) {
61 get detail(): string {
62 return "Pull request not found. Check the PR number or URL and try again.";
63 }
64​
65 override get message(): string {
66 return `GitHub CLI failed in execute: ${this.detail}`;
67 }
69​
70export class GitHubCliCommandError extends Schema.TaggedErrorClass<GitHubCliCommandError>()(
71 "GitHubCliCommandError",
72 gitHubCliFailureFields,
73) {
74 get detail(): string {
75 return "GitHub CLI command failed.";
76 }
77​
78 override get message(): string {
79 return `GitHub CLI failed in execute: ${this.detail}`;
80 }
82​
83const gitHubCredentialFields = {
84 command: Schema.Literal("gh"),
85 cwd: Schema.String,
86 host: Schema.String,
87} as const;
88​
89export class GitHubAccountSettingsUnavailableError extends Schema.TaggedErrorClass<GitHubAccountSettingsUnavailableError>()(
90 "GitHubAccountSettingsUnavailableError",
91 {
92 ...gitHubCredentialFields,
93 cause: Schema.Defect(),
94 },
95) {
96 get detail(): string {
97 return `GitHub account settings could not be loaded for ${this.host}.`;
98 }
99​
100 override get message(): string {
101 return `GitHub CLI credential selection failed: ${this.detail}`;
102 }
104​
105export class GitHubAccountSelectionConflictError extends Schema.TaggedErrorClass<GitHubAccountSelectionConflictError>()(
106 "GitHubAccountSelectionConflictError",
107 {
108 ...gitHubCredentialFields,
109 repositories: Schema.Array(Schema.String),
110 },
111) {
112 get detail(): string {
113 return `Repositories on ${this.host} require different GitHub accounts: ${this.repositories.join(", ")}.`;
114 }
115​
116 override get message(): string {
117 return `GitHub CLI credential selection failed: ${this.detail}`;
118 }
120​
121export class GitHubTokenEnvironmentUnavailableError extends Schema.TaggedErrorClass<GitHubTokenEnvironmentUnavailableError>()(
122 "GitHubTokenEnvironmentUnavailableError",
123 {
124 ...gitHubCredentialFields,
125 login: Schema.String,
126 tokenSource: Schema.String,
127 },
128) {
129 get detail(): string {
130 return `GitHub token source ${this.tokenSource} is unavailable for ${this.login} on ${this.host}.`;
131 }
132​
133 override get message(): string {
134 return `GitHub CLI credential selection failed: ${this.detail}`;
135 }
137​
138export class GitHubTokenOutputEmptyError extends Schema.TaggedErrorClass<GitHubTokenOutputEmptyError>()(
139 "GitHubTokenOutputEmptyError",
140 {
141 ...gitHubCredentialFields,
142 login: Schema.String,
143 tokenSource: Schema.String,
144 },
145) {
146 get detail(): string {
147 return `GitHub CLI returned no token for ${this.login} on ${this.host}.`;
148 }
149​
150 override get message(): string {
151 return `GitHub CLI credential selection failed: ${this.detail}`;
152 }
154​
155const gitHubCliDecodeFields = {
156 command: Schema.Literal("gh"),
157 cwd: Schema.String,
158 cause: Schema.Defect(),
159} as const;
160​
161export class GitHubPullRequestListDecodeError extends Schema.TaggedErrorClass<GitHubPullRequestListDecodeError>()(
162 "GitHubPullRequestListDecodeError",
163 gitHubCliDecodeFields,
164) {
165 get detail(): string {
166 return "GitHub CLI returned invalid PR list JSON.";
167 }
168​
169 override get message(): string {
170 return `GitHub CLI failed in listOpenPullRequests: ${this.detail}`;
171 }
173​
174export class GitHubChangeRequestListDecodeError extends Schema.TaggedErrorClass<GitHubChangeRequestListDecodeError>()(
175 "GitHubChangeRequestListDecodeError",
176 gitHubCliDecodeFields,
177) {
178 get detail(): string {
179 return "GitHub CLI returned invalid change request JSON.";
180 }
181​
182 override get message(): string {
183 return `GitHub CLI failed in listChangeRequests: ${this.detail}`;
184 }
186​
187export class GitHubPullRequestDecodeError extends Schema.TaggedErrorClass<GitHubPullRequestDecodeError>()(
188 "GitHubPullRequestDecodeError",
189 gitHubCliDecodeFields,
190) {
191 get detail(): string {
192 return "GitHub CLI returned invalid pull request JSON.";
193 }
194​
195 override get message(): string {
196 return `GitHub CLI failed in getPullRequest: ${this.detail}`;
197 }
199​
200export class GitHubRepositoryDecodeError extends Schema.TaggedErrorClass<GitHubRepositoryDecodeError>()(
201 "GitHubRepositoryDecodeError",
202 gitHubCliDecodeFields,
203) {
204 get detail(): string {
205 return "GitHub CLI returned invalid repository JSON.";
206 }
207​
208 override get message(): string {
209 return `GitHub CLI failed in getRepositoryCloneUrls: ${this.detail}`;
210 }
212​
213export const GitHubCliError = Schema.Union([
214 GitHubCliUnavailableError,
215 GitHubCliAuthenticationError,
216 GitHubPullRequestNotFoundError,
217 GitHubCliCommandError,
218 GitHubAccountSettingsUnavailableError,
219 GitHubAccountSelectionConflictError,
220 GitHubTokenEnvironmentUnavailableError,
221 GitHubTokenOutputEmptyError,
222 GitHubPullRequestListDecodeError,
223 GitHubChangeRequestListDecodeError,
224 GitHubPullRequestDecodeError,
225 GitHubRepositoryDecodeError,
226]);
227export type GitHubCliError = typeof GitHubCliError.Type;
228​
229export const isGitHubCliError = Schema.is(GitHubCliError);
230​
231export function fromVcsError(
232 context: {
233 readonly command: "gh";
234 readonly cwd: string;
235 },
236 error: VcsError,
237): GitHubCliError {
238 if (
239 error._tag === "VcsProcessSpawnError" &&
240 error.cause instanceof PlatformError.PlatformError &&
241 error.cause.reason._tag === "NotFound" &&
242 error.cause.reason.module === "ChildProcess" &&
243 error.cause.reason.method === "spawn"
244 ) {
245 return new GitHubCliUnavailableError({ ...context, cause: error });
246 }
247​
248 if (error._tag === "VcsProcessExitError") {
249 if (error.failureKind === "authentication") {
250 return new GitHubCliAuthenticationError({ ...context, cause: error });
251 }
252 if (error.failureKind === "not-found") {
253 return new GitHubPullRequestNotFoundError({ ...context, cause: error });
254 }
255 }
256​
257 return new GitHubCliCommandError({ ...context, cause: error });
259​
260export interface GitHubPullRequestSummary {
261 readonly number: number;
262 readonly title: string;
263 readonly url: string;
264 readonly baseRefName: string;
265 readonly headRefName: string;
266 readonly state?: "open" | "closed" | "merged";
267 readonly isCrossRepository?: boolean;
268 readonly headRepositoryNameWithOwner?: string | null;
269 readonly headRepositoryOwnerLogin?: string | null;
271​
272export interface GitHubRepositoryCloneUrls {
273 readonly nameWithOwner: string;
274 readonly url: string;
275 readonly sshUrl: string;
277​
278type GitHubAuthTarget = GitHubCredentials.GitHubCredentialTarget;
279​
280const GITHUB_TOKEN_ENV_SOURCES = new Set([
281 "GH_TOKEN",
282 "GITHUB_TOKEN",
283 "GH_ENTERPRISE_TOKEN",
284 "GITHUB_ENTERPRISE_TOKEN",
285]);
286​
287function definedAuthTarget(input: GitHubAuthTarget): GitHubAuthTarget {
288 if (input.repositories === undefined) return {};
289 return {
290 ...(input.host === undefined ? {} : { host: input.host }),
291 repositories: input.repositories,
292 };
294​
295function repositoryAuthTarget(input: {
296 readonly host?: string | undefined;
297 readonly repository: string;
298}): GitHubAuthTarget {
299 return input.host === undefined
300 ? { repositories: [input.repository] }
301 : { host: input.host, repositories: [input.repository] };
303​
304export class GitHubCli extends Context.Service<
305 GitHubCli,
306 {
307 readonly execute: (
308 input: {
309 readonly cwd: string;
310 readonly args: ReadonlyArray<string>;
311 readonly timeoutMs?: number;
312 /** Piped to the child's stdin, for payloads that must never appear in argv. */
313 readonly stdin?: string;
314 readonly maxOutputBytes?: number;
315 } & GitHubAuthTarget,
316 ) => Effect.Effect<VcsProcess.VcsProcessOutput, GitHubCliError>;
317​
318 /** Stable, non-secret identity for the credential that will serve this target. */
319 readonly getBatchKey: (
320 input: GitHubAuthTarget & { readonly cwd: string },
321 ) => Effect.Effect<string, GitHubCliError>;
322​
323 readonly listOpenPullRequests: (
324 input: {
325 readonly cwd: string;
326 readonly headSelector: string;
327 readonly limit?: number;
328 } & GitHubAuthTarget,
329 ) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
330​
331 readonly getPullRequest: (
332 input: {
333 readonly cwd: string;
334 readonly reference: string;
335 } & GitHubAuthTarget,
336 ) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
337​
338 readonly getRepositoryCloneUrls: (
339 input: {
340 readonly cwd: string;
341 readonly repository: string;
342 } & GitHubAuthTarget,
343 ) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
344​
345 readonly createRepository: (
346 input: {
347 readonly cwd: string;
348 readonly repository: string;
349 readonly visibility: SourceControlRepositoryVisibility;
350 } & GitHubAuthTarget,
351 ) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
352​
353 readonly createPullRequest: (
354 input: {
355 readonly cwd: string;
356 readonly baseBranch: string;
357 readonly headSelector: string;
358 readonly title: string;
359 readonly bodyFile: string;
360 } & GitHubAuthTarget,
361 ) => Effect.Effect<void, GitHubCliError>;
362​
363 readonly getDefaultBranch: (
364 input: {
365 readonly cwd: string;
366 } & GitHubAuthTarget,
367 ) => Effect.Effect<string | null, GitHubCliError>;
368​
369 readonly checkoutPullRequest: (
370 input: {
371 readonly cwd: string;
372 readonly reference: string;
373 readonly force?: boolean;
374 } & GitHubAuthTarget,
375 ) => Effect.Effect<void, GitHubCliError>;
376 }
377>()("t3/sourceControl/GitHubCli") {}
378​
379const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
380 nameWithOwner: TrimmedNonEmptyString,
381 url: TrimmedNonEmptyString,
382 sshUrl: TrimmedNonEmptyString,
383});
384const decodeRawGitHubRepositoryCloneUrls = Schema.decodeEffect(
385 Schema.fromJsonString(RawGitHubRepositoryCloneUrlsSchema),
386);
387​
388function normalizeRepositoryCloneUrls(
389 raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
390): GitHubRepositoryCloneUrls {
391 return {
392 nameWithOwner: raw.nameWithOwner,
393 url: raw.url,
394 sshUrl: raw.sshUrl,
395 };
397​
398/**
399 * `gh repo create` prints the canonical URL of the new repository on stdout
400 * (e.g. `https://github.com/owner/repo`). Reading it back here avoids a
401 * follow-up `gh repo view`, which can race GitHub's GraphQL eventual
402 * consistency window and falsely report the just-created repo as missing.
403 */
404function deriveRepositoryCloneUrlsFromCreateOutput(
405 stdout: string,
406 repository: string,
407): GitHubRepositoryCloneUrls {
408 const fallbackHost = "github.com";
409 const match = stdout.match(/https?:\/\/[^\s]+/);
410 if (match) {
411 const cleaned = match[0].replace(/\.git$/, "");
412 try {
413 const parsed = new URL(cleaned);
414 const pathname = parsed.pathname.replace(/^\/+|\/+$/g, "");
415 const segments = pathname.split("/").filter(Boolean);
416 if (segments.length === 2) {
417 const nameWithOwner = `${segments[0]}/${segments[1]}`;
418 return {
419 nameWithOwner,
420 url: `${parsed.origin}/${nameWithOwner}`,
421 sshUrl: `git@${parsed.host}:${nameWithOwner}.git`,
422 };
423 }
424 } catch {
425 // Fall through to the input-derived defaults below.
426 }
427 }
428 return {
429 nameWithOwner: repository,
430 url: `https://${fallbackHost}/${repository}`,
431 sshUrl: `git@${fallbackHost}:${repository}.git`,
432 };
434​
435export const make = Effect.gen(function* () {
436 const vcsProcess = yield* VcsProcess.VcsProcess;
437 const settings = yield* ServerSettings.ServerSettingsService;
438​
439 const credentialRoute = Effect.fn("GitHubCli.credentialRoute")(function* (
440 input: GitHubAuthTarget & { readonly cwd: string },
441 ): Effect.fn.Return<GitHubCredentials.GitHubCredentialRoute, GitHubCliError> {
442 const host = (input.host ?? "github.com").toLowerCase();
443 const current = yield* settings.getSettings.pipe(
444 Effect.mapError(
445 (cause) =>
446 new GitHubAccountSettingsUnavailableError({
447 command: "gh",
448 cwd: input.cwd,
449 host,
450 cause,
451 }),
452 ),
453 );
454 const selected = GitHubCredentials.selectCredentialRoute(current, input);
455 if (Result.isFailure(selected)) {
456 switch (selected.failure._tag) {
457 case "SelectionConflict":
458 return yield* new GitHubAccountSelectionConflictError({
459 command: "gh",
460 cwd: input.cwd,
461 host,
462 repositories: [...selected.failure.repositories],
463 });
464 }
465 }
466 return selected.success;
467 });
468​
469 const tokenFor = Effect.fn("GitHubCli.tokenFor")(function* (input: {
470 readonly host: string;
471 readonly account: GitHubAccountSelection;
472 readonly cwd: string;
473 }) {
474 if (GITHUB_TOKEN_ENV_SOURCES.has(input.account.tokenSource)) {
475 const token = process.env[input.account.tokenSource]?.trim();
476 if (token !== undefined && token.length > 0) return token;
477 return yield* new GitHubTokenEnvironmentUnavailableError({
478 command: "gh",
479 cwd: input.cwd,
480 host: input.host,
481 login: input.account.login,
482 tokenSource: input.account.tokenSource,
483 });
484 }
485​
486 const output = yield* vcsProcess
487 .run({
488 operation: "GitHubCli.authToken",
489 command: "gh",
490 args: ["auth", "token", "--hostname", input.host, "--user", input.account.login],
491 cwd: input.cwd,
492 timeoutMs: DEFAULT_TIMEOUT_MS,
493 })
494 .pipe(Effect.mapError((error) => fromVcsError({ command: "gh", cwd: input.cwd }, error)));
495 const token = output.stdout.trim();
496 if (token.length === 0) {
497 return yield* new GitHubTokenOutputEmptyError({
498 command: "gh",
499 cwd: input.cwd,
500 host: input.host,
501 login: input.account.login,
502 tokenSource: input.account.tokenSource,
503 });
504 }
505 return token;
506 });
507​
508 const run = (input: Parameters<GitHubCli["Service"]["execute"]>[0], env?: NodeJS.ProcessEnv) =>
509 vcsProcess
510 .run({
511 operation: "GitHubCli.execute",
512 command: "gh",
513 args: input.args,
514 cwd: input.cwd,
515 ...(env !== undefined ? { env } : {}),
516 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
517 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
518 ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
519 })
520 .pipe(Effect.mapError((error) => fromVcsError({ command: "gh", cwd: input.cwd }, error)));
521​
522 const execute: GitHubCli["Service"]["execute"] = Effect.fn("GitHubCli.execute")(
523 function* (input) {
524 const route = yield* credentialRoute(input);
525 if (route.account === undefined) return yield* run(input);
526​
527 const token = yield* tokenFor({ host: route.host, account: route.account, cwd: input.cwd });
528 const tokenVariable =
529 route.host === "github.com" || route.host.endsWith(".ghe.com")
530 ? "GH_TOKEN"
531 : "GH_ENTERPRISE_TOKEN";
532 return yield* run(input, { [tokenVariable]: token });
533 },
534 );
535​
536 return GitHubCli.of({
537 execute,
538 getBatchKey: (input) => credentialRoute(input).pipe(Effect.map((route) => route.key)),
539 listOpenPullRequests: (input) =>
540 execute({
541 cwd: input.cwd,
542 ...definedAuthTarget(input),
543 args: [
544 "pr",
545 "list",
546 "--head",
547 input.headSelector,
548 "--state",
549 "open",
550 "--limit",
551 String(input.limit ?? 1),
552 "--json",
553 "number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
554 ],
555 }).pipe(
556 Effect.map((result) => result.stdout.trim()),
557 Effect.flatMap((raw) =>
558 raw.length === 0
559 ? Effect.succeed([])
560 : Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
561 Effect.flatMap((decoded) => {
562 if (!Result.isSuccess(decoded)) {
563 return Effect.fail(
564 new GitHubPullRequestListDecodeError({
565 command: "gh",
566 cwd: input.cwd,
567 cause: decoded.failure,
568 }),
569 );
570 }
571​
572 return Effect.succeed(
573 decoded.success.map(({ updatedAt: _updatedAt, ...summary }) => summary),
574 );
575 }),
576 ),
577 ),
578 ),
579 getPullRequest: (input) =>
580 execute({
581 cwd: input.cwd,
582 ...definedAuthTarget(input),
583 args: [
584 "pr",
585 "view",
586 input.reference,
587 "--json",
588 "number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
589 ],
590 }).pipe(
591 Effect.map((result) => result.stdout.trim()),
592 Effect.flatMap((raw) =>
593 Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
594 Effect.flatMap((decoded) => {
595 if (!Result.isSuccess(decoded)) {
596 return Effect.fail(
597 new GitHubPullRequestDecodeError({
598 command: "gh",
599 cwd: input.cwd,
600 cause: decoded.failure,
601 }),
602 );
603 }
604​
605 return Effect.succeed(
606 (({ updatedAt: _updatedAt, ...summary }) => summary)(decoded.success),
607 );
608 }),
609 ),
610 ),
611 ),
612 getRepositoryCloneUrls: (input) =>
613 execute({
614 cwd: input.cwd,
615 ...repositoryAuthTarget(input),
616 args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
617 }).pipe(
618 Effect.map((result) => result.stdout.trim()),
619 Effect.flatMap((raw) =>
620 decodeRawGitHubRepositoryCloneUrls(raw).pipe(
621 Effect.mapError(
622 (cause) =>
623 new GitHubRepositoryDecodeError({
624 command: "gh",
625 cwd: input.cwd,
626 cause,
627 }),
628 ),
629 ),
630 ),
631 Effect.map(normalizeRepositoryCloneUrls),
632 ),
633 createRepository: (input) =>
634 execute({
635 cwd: input.cwd,
636 ...repositoryAuthTarget(input),
637 args: ["repo", "create", input.repository, `--${input.visibility}`],
638 }).pipe(
639 Effect.map((result) =>
640 deriveRepositoryCloneUrlsFromCreateOutput(result.stdout, input.repository),
641 ),
642 ),
643 createPullRequest: (input) =>
644 execute({
645 cwd: input.cwd,
646 ...definedAuthTarget(input),
647 args: [
648 "pr",
649 "create",
650 "--base",
651 input.baseBranch,
652 "--head",
653 input.headSelector,
654 "--title",
655 input.title,
656 "--body-file",
657 input.bodyFile,
658 ],
659 }).pipe(Effect.asVoid),
660 getDefaultBranch: (input) =>
661 execute({
662 cwd: input.cwd,
663 ...definedAuthTarget(input),
664 args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
665 }).pipe(
666 Effect.map((value) => {
667 const trimmed = value.stdout.trim();
668 return trimmed.length > 0 ? trimmed : null;
669 }),
670 ),
671 checkoutPullRequest: (input) =>
672 execute({
673 cwd: input.cwd,
674 ...definedAuthTarget(input),
675 args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
676 }).pipe(Effect.asVoid),
677 });
678});
679​
680export const layer = Layer.effect(GitHubCli, make);