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

GitHubCli.ts

240 lines7.2 KB

1import { Effect, Layer, Result, Schema, SchemaIssue } from "effect";
2import { TrimmedNonEmptyString } from "@t3tools/contracts";
3​
4import { runProcess } from "../../processRunner";
5import { GitHubCliError } from "@t3tools/contracts";
6import {
7 GitHubCli,
8 type GitHubRepositoryCloneUrls,
9 type GitHubCliShape,
10} from "../Services/GitHubCli.ts";
11import {
12 decodeGitHubPullRequestJson,
13 decodeGitHubPullRequestListJson,
14 formatGitHubJsonDecodeError,
15} from "../githubPullRequests.ts";
16​
17const DEFAULT_TIMEOUT_MS = 30_000;
18​
19function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown): GitHubCliError {
20 if (error instanceof Error) {
21 if (error.message.includes("Command not found: gh")) {
22 return new GitHubCliError({
23 operation,
24 detail: "GitHub CLI (`gh`) is required but not available on PATH.",
25 cause: error,
26 });
27 }
28​
29 const lower = error.message.toLowerCase();
30 if (
31 lower.includes("authentication failed") ||
32 lower.includes("not logged in") ||
33 lower.includes("gh auth login") ||
34 lower.includes("no oauth token")
35 ) {
36 return new GitHubCliError({
37 operation,
38 detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
39 cause: error,
40 });
41 }
42​
43 if (
44 lower.includes("could not resolve to a pullrequest") ||
45 lower.includes("repository.pullrequest") ||
46 lower.includes("no pull requests found for branch") ||
47 lower.includes("pull request not found")
48 ) {
49 return new GitHubCliError({
50 operation,
51 detail: "Pull request not found. Check the PR number or URL and try again.",
52 cause: error,
53 });
54 }
55​
56 return new GitHubCliError({
57 operation,
58 detail: `GitHub CLI command failed: ${error.message}`,
59 cause: error,
60 });
61 }
62​
63 return new GitHubCliError({
64 operation,
65 detail: "GitHub CLI command failed.",
66 cause: error,
67 });
69​
70const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
71 nameWithOwner: TrimmedNonEmptyString,
72 url: TrimmedNonEmptyString,
73 sshUrl: TrimmedNonEmptyString,
74});
75​
76function normalizeRepositoryCloneUrls(
77 raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
78): GitHubRepositoryCloneUrls {
79 return {
80 nameWithOwner: raw.nameWithOwner,
81 url: raw.url,
82 sshUrl: raw.sshUrl,
83 };
85​
86function decodeGitHubJson<S extends Schema.Top>(
87 raw: string,
88 schema: S,
89 operation: "listOpenPullRequests" | "getPullRequest" | "getRepositoryCloneUrls",
90 invalidDetail: string,
91): Effect.Effect<S["Type"], GitHubCliError, S["DecodingServices"]> {
92 return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
93 Effect.mapError(
94 (error) =>
95 new GitHubCliError({
96 operation,
97 detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
98 cause: error,
99 }),
100 ),
101 );
103​
104const makeGitHubCli = Effect.sync(() => {
105 const execute: GitHubCliShape["execute"] = (input) =>
106 Effect.tryPromise({
107 try: () =>
108 runProcess("gh", input.args, {
109 cwd: input.cwd,
110 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
111 }),
112 catch: (error) => normalizeGitHubCliError("execute", error),
113 });
114​
115 const service = {
116 execute,
117 listOpenPullRequests: (input) =>
118 execute({
119 cwd: input.cwd,
120 args: [
121 "pr",
122 "list",
123 "--head",
124 input.headSelector,
125 "--state",
126 "open",
127 "--limit",
128 String(input.limit ?? 1),
129 "--json",
130 "number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
131 ],
132 }).pipe(
133 Effect.map((result) => result.stdout.trim()),
134 Effect.flatMap((raw) =>
135 raw.length === 0
136 ? Effect.succeed([])
137 : Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
138 Effect.flatMap((decoded) => {
139 if (!Result.isSuccess(decoded)) {
140 return Effect.fail(
141 new GitHubCliError({
142 operation: "listOpenPullRequests",
143 detail: `GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
144 cause: decoded.failure,
145 }),
146 );
147 }
148​
149 return Effect.succeed(
150 decoded.success.map(({ updatedAt: _updatedAt, ...summary }) => summary),
151 );
152 }),
153 ),
154 ),
155 ),
156 getPullRequest: (input) =>
157 execute({
158 cwd: input.cwd,
159 args: [
160 "pr",
161 "view",
162 input.reference,
163 "--json",
164 "number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
165 ],
166 }).pipe(
167 Effect.map((result) => result.stdout.trim()),
168 Effect.flatMap((raw) =>
169 Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
170 Effect.flatMap((decoded) => {
171 if (!Result.isSuccess(decoded)) {
172 return Effect.fail(
173 new GitHubCliError({
174 operation: "getPullRequest",
175 detail: `GitHub CLI returned invalid pull request JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
176 cause: decoded.failure,
177 }),
178 );
179 }
180​
181 return Effect.succeed(
182 (({ updatedAt: _updatedAt, ...summary }) => summary)(decoded.success),
183 );
184 }),
185 ),
186 ),
187 ),
188 getRepositoryCloneUrls: (input) =>
189 execute({
190 cwd: input.cwd,
191 args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
192 }).pipe(
193 Effect.map((result) => result.stdout.trim()),
194 Effect.flatMap((raw) =>
195 decodeGitHubJson(
196 raw,
197 RawGitHubRepositoryCloneUrlsSchema,
198 "getRepositoryCloneUrls",
199 "GitHub CLI returned invalid repository JSON.",
200 ),
201 ),
202 Effect.map(normalizeRepositoryCloneUrls),
203 ),
204 createPullRequest: (input) =>
205 execute({
206 cwd: input.cwd,
207 args: [
208 "pr",
209 "create",
210 "--base",
211 input.baseBranch,
212 "--head",
213 input.headSelector,
214 "--title",
215 input.title,
216 "--body-file",
217 input.bodyFile,
218 ],
219 }).pipe(Effect.asVoid),
220 getDefaultBranch: (input) =>
221 execute({
222 cwd: input.cwd,
223 args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
224 }).pipe(
225 Effect.map((value) => {
226 const trimmed = value.stdout.trim();
227 return trimmed.length > 0 ? trimmed : null;
228 }),
229 ),
230 checkoutPullRequest: (input) =>
231 execute({
232 cwd: input.cwd,
233 args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
234 }).pipe(Effect.asVoid),
235 } satisfies GitHubCliShape;
236​
237 return service;
238});
239​
240export const GitHubCliLive = Layer.effect(GitHubCli, makeGitHubCli);