Open History to see the last commit
1import { Context, Effect, Layer, Result, Schema, SchemaIssue } from "effect";
2
3import {
4 TrimmedNonEmptyString,
5 type SourceControlRepositoryVisibility,
6 type VcsError,
7} from "@t3tools/contracts";
8
9import { VcsProcess, type VcsProcessOutput } from "../vcs/VcsProcess.ts";
10import {
11 decodeGitHubPullRequestJson,
12 decodeGitHubPullRequestListJson,
13 formatGitHubJsonDecodeError,
14} from "./gitHubPullRequests.ts";
15
16const DEFAULT_TIMEOUT_MS = 30_000;
17
18export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
19 operation: Schema.String,
20 detail: Schema.String,
21 cause: Schema.optional(Schema.Defect),
22}) {
23 override get message(): string {
24 return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
25 }
26}
27
28export interface GitHubPullRequestSummary {
29 readonly number: number;
30 readonly title: string;
31 readonly url: string;
32 readonly baseRefName: string;
33 readonly headRefName: string;
34 readonly state?: "open" | "closed" | "merged";
35 readonly isCrossRepository?: boolean;
36 readonly headRepositoryNameWithOwner?: string | null;
37 readonly headRepositoryOwnerLogin?: string | null;
38}
39
40export interface GitHubRepositoryCloneUrls {
41 readonly nameWithOwner: string;
42 readonly url: string;
43 readonly sshUrl: string;
44}
45
46export interface GitHubCliShape {
47 readonly execute: (input: {
48 readonly cwd: string;
49 readonly args: ReadonlyArray<string>;
50 readonly timeoutMs?: number;
51 }) => Effect.Effect<VcsProcessOutput, GitHubCliError>;
52
53 readonly listOpenPullRequests: (input: {
54 readonly cwd: string;
55 readonly headSelector: string;
56 readonly limit?: number;
57 }) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
58
59 readonly getPullRequest: (input: {
60 readonly cwd: string;
61 readonly reference: string;
62 }) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
63
64 readonly getRepositoryCloneUrls: (input: {
65 readonly cwd: string;
66 readonly repository: string;
67 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
68
69 readonly createRepository: (input: {
70 readonly cwd: string;
71 readonly repository: string;
72 readonly visibility: SourceControlRepositoryVisibility;
73 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
74
75 readonly createPullRequest: (input: {
76 readonly cwd: string;
77 readonly baseBranch: string;
78 readonly headSelector: string;
79 readonly title: string;
80 readonly bodyFile: string;
81 }) => Effect.Effect<void, GitHubCliError>;
82
83 readonly getDefaultBranch: (input: {
84 readonly cwd: string;
85 }) => Effect.Effect<string | null, GitHubCliError>;
86
87 readonly checkoutPullRequest: (input: {
88 readonly cwd: string;
89 readonly reference: string;
90 readonly force?: boolean;
91 }) => Effect.Effect<void, GitHubCliError>;
92}
93
94export class GitHubCli extends Context.Service<GitHubCli, GitHubCliShape>()(
95 "t3/source-control/GitHubCli",
96) {}
97
98function errorText(error: VcsError | unknown): string {
99 if (typeof error === "object" && error !== null) {
100 const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
101 const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
102 const message = "message" in error && typeof error.message === "string" ? error.message : "";
103 return [tag, detail, message].filter(Boolean).join("\n");
104 }
105
106 return String(error);
107}
108
109function normalizeGitHubCliError(
110 operation: "execute" | "stdout",
111 error: VcsError | unknown,
112): GitHubCliError {
113 const text = errorText(error);
114 const lower = text.toLowerCase();
115
116 if (lower.includes("command not found: gh") || lower.includes("enoent")) {
117 return new GitHubCliError({
118 operation,
119 detail: "GitHub CLI (`gh`) is required but not available on PATH.",
120 cause: error,
121 });
122 }
123
124 if (
125 lower.includes("authentication failed") ||
126 lower.includes("not logged in") ||
127 lower.includes("gh auth login") ||
128 lower.includes("no oauth token")
129 ) {
130 return new GitHubCliError({
131 operation,
132 detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
133 cause: error,
134 });
135 }
136
137 if (
138 lower.includes("could not resolve to a pullrequest") ||
139 lower.includes("repository.pullrequest") ||
140 lower.includes("no pull requests found for branch") ||
141 lower.includes("pull request not found")
142 ) {
143 return new GitHubCliError({
144 operation,
145 detail: "Pull request not found. Check the PR number or URL and try again.",
146 cause: error,
147 });
148 }
149
150 return new GitHubCliError({
151 operation,
152 detail: text,
153 cause: error,
154 });
155}
156
157const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
158 nameWithOwner: TrimmedNonEmptyString,
159 url: TrimmedNonEmptyString,
160 sshUrl: TrimmedNonEmptyString,
161});
162
163function normalizeRepositoryCloneUrls(
164 raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
165): GitHubRepositoryCloneUrls {
166 return {
167 nameWithOwner: raw.nameWithOwner,
168 url: raw.url,
169 sshUrl: raw.sshUrl,
170 };
171}
172
173/**
174 * `gh repo create` prints the canonical URL of the new repository on stdout
175 * (e.g. `https://github.com/owner/repo`). Reading it back here avoids a
176 * follow-up `gh repo view`, which can race GitHub's GraphQL eventual
177 * consistency window and falsely report the just-created repo as missing.
178 */
179function deriveRepositoryCloneUrlsFromCreateOutput(
180 stdout: string,
181 repository: string,
182): GitHubRepositoryCloneUrls {
183 const fallbackHost = "github.com";
184 const match = stdout.match(/https?:\/\/[^\s]+/);
185 if (match) {
186 const cleaned = match[0].replace(/\.git$/, "");
187 try {
188 const parsed = new URL(cleaned);
189 const pathname = parsed.pathname.replace(/^\/+|\/+$/g, "");
190 const segments = pathname.split("/").filter(Boolean);
191 if (segments.length === 2) {
192 const nameWithOwner = `${segments[0]}/${segments[1]}`;
193 return {
194 nameWithOwner,
195 url: `${parsed.origin}/${nameWithOwner}`,
196 sshUrl: `git@${parsed.host}:${nameWithOwner}.git`,
197 };
198 }
199 } catch {
200 // Fall through to the input-derived defaults below.
201 }
202 }
203 return {
204 nameWithOwner: repository,
205 url: `https://${fallbackHost}/${repository}`,
206 sshUrl: `git@${fallbackHost}:${repository}.git`,
207 };
208}
209
210function decodeGitHubJson<S extends Schema.Top>(
211 raw: string,
212 schema: S,
213 operation: "listOpenPullRequests" | "getPullRequest" | "getRepositoryCloneUrls",
214 invalidDetail: string,
215): Effect.Effect<S["Type"], GitHubCliError, S["DecodingServices"]> {
216 return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
217 Effect.mapError(
218 (error) =>
219 new GitHubCliError({
220 operation,
221 detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
222 cause: error,
223 }),
224 ),
225 );
226}
227
228export const make = Effect.fn("makeGitHubCli")(function* () {
229 const process = yield* VcsProcess;
230
231 const execute: GitHubCliShape["execute"] = (input) =>
232 process
233 .run({
234 operation: "GitHubCli.execute",
235 command: "gh",
236 args: input.args,
237 cwd: input.cwd,
238 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
239 })
240 .pipe(Effect.mapError((error) => normalizeGitHubCliError("execute", error)));
241
242 return GitHubCli.of({
243 execute,
244 listOpenPullRequests: (input) =>
245 execute({
246 cwd: input.cwd,
247 args: [
248 "pr",
249 "list",
250 "--head",
251 input.headSelector,
252 "--state",
253 "open",
254 "--limit",
255 String(input.limit ?? 1),
256 "--json",
257 "number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
258 ],
259 }).pipe(
260 Effect.map((result) => result.stdout.trim()),
261 Effect.flatMap((raw) =>
262 raw.length === 0
263 ? Effect.succeed([])
264 : Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
265 Effect.flatMap((decoded) => {
266 if (!Result.isSuccess(decoded)) {
267 return Effect.fail(
268 new GitHubCliError({
269 operation: "listOpenPullRequests",
270 detail: `GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
271 cause: decoded.failure,
272 }),
273 );
274 }
275
276 return Effect.succeed(
277 decoded.success.map(({ updatedAt: _updatedAt, ...summary }) => summary),
278 );
279 }),
280 ),
281 ),
282 ),
283 getPullRequest: (input) =>
284 execute({
285 cwd: input.cwd,
286 args: [
287 "pr",
288 "view",
289 input.reference,
290 "--json",
291 "number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
292 ],
293 }).pipe(
294 Effect.map((result) => result.stdout.trim()),
295 Effect.flatMap((raw) =>
296 Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
297 Effect.flatMap((decoded) => {
298 if (!Result.isSuccess(decoded)) {
299 return Effect.fail(
300 new GitHubCliError({
301 operation: "getPullRequest",
302 detail: `GitHub CLI returned invalid pull request JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
303 cause: decoded.failure,
304 }),
305 );
306 }
307
308 return Effect.succeed(
309 (({ updatedAt: _updatedAt, ...summary }) => summary)(decoded.success),
310 );
311 }),
312 ),
313 ),
314 ),
315 getRepositoryCloneUrls: (input) =>
316 execute({
317 cwd: input.cwd,
318 args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
319 }).pipe(
320 Effect.map((result) => result.stdout.trim()),
321 Effect.flatMap((raw) =>
322 decodeGitHubJson(
323 raw,
324 RawGitHubRepositoryCloneUrlsSchema,
325 "getRepositoryCloneUrls",
326 "GitHub CLI returned invalid repository JSON.",
327 ),
328 ),
329 Effect.map(normalizeRepositoryCloneUrls),
330 ),
331 createRepository: (input) =>
332 execute({
333 cwd: input.cwd,
334 args: ["repo", "create", input.repository, `--${input.visibility}`],
335 }).pipe(
336 Effect.map((result) =>
337 deriveRepositoryCloneUrlsFromCreateOutput(result.stdout, input.repository),
338 ),
339 ),
340 createPullRequest: (input) =>
341 execute({
342 cwd: input.cwd,
343 args: [
344 "pr",
345 "create",
346 "--base",
347 input.baseBranch,
348 "--head",
349 input.headSelector,
350 "--title",
351 input.title,
352 "--body-file",
353 input.bodyFile,
354 ],
355 }).pipe(Effect.asVoid),
356 getDefaultBranch: (input) =>
357 execute({
358 cwd: input.cwd,
359 args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
360 }).pipe(
361 Effect.map((value) => {
362 const trimmed = value.stdout.trim();
363 return trimmed.length > 0 ? trimmed : null;
364 }),
365 ),
366 checkoutPullRequest: (input) =>
367 execute({
368 cwd: input.cwd,
369 args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
370 }).pipe(Effect.asVoid),
371 });
372});
373
374export const layer = Layer.effect(GitHubCli, make());