Open History to see the last commit
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 TrimmedNonEmptyString,
10 type SourceControlRepositoryVisibility,
11 type VcsError,
12} from "@t3tools/contracts";
13
14import * as VcsProcess from "../vcs/VcsProcess.ts";
15import {
16 decodeGitHubPullRequestJson,
17 decodeGitHubPullRequestListJson,
18} from "./gitHubPullRequests.ts";
19
20const DEFAULT_TIMEOUT_MS = 30_000;
21
22const gitHubCliFailureFields = {
23 command: Schema.Literal("gh"),
24 cwd: Schema.String,
25 cause: Schema.Defect(),
26} as const;
27
28export class GitHubCliUnavailableError extends Schema.TaggedErrorClass<GitHubCliUnavailableError>()(
29 "GitHubCliUnavailableError",
30 gitHubCliFailureFields,
31) {
32 get detail(): string {
33 return "GitHub CLI (`gh`) is required but not available on PATH.";
34 }
35
36 override get message(): string {
37 return `GitHub CLI failed in execute: ${this.detail}`;
38 }
39}
40
41export class GitHubCliAuthenticationError extends Schema.TaggedErrorClass<GitHubCliAuthenticationError>()(
42 "GitHubCliAuthenticationError",
43 gitHubCliFailureFields,
44) {
45 get detail(): string {
46 return "GitHub CLI is not authenticated. Run `gh auth login` and retry.";
47 }
48
49 override get message(): string {
50 return `GitHub CLI failed in execute: ${this.detail}`;
51 }
52}
53
54export class GitHubPullRequestNotFoundError extends Schema.TaggedErrorClass<GitHubPullRequestNotFoundError>()(
55 "GitHubPullRequestNotFoundError",
56 gitHubCliFailureFields,
57) {
58 get detail(): string {
59 return "Pull request not found. Check the PR number or URL and try again.";
60 }
61
62 override get message(): string {
63 return `GitHub CLI failed in execute: ${this.detail}`;
64 }
65}
66
67export class GitHubCliCommandError extends Schema.TaggedErrorClass<GitHubCliCommandError>()(
68 "GitHubCliCommandError",
69 gitHubCliFailureFields,
70) {
71 get detail(): string {
72 return "GitHub CLI command failed.";
73 }
74
75 override get message(): string {
76 return `GitHub CLI failed in execute: ${this.detail}`;
77 }
78}
79
80const gitHubCliDecodeFields = {
81 command: Schema.Literal("gh"),
82 cwd: Schema.String,
83 cause: Schema.Defect(),
84} as const;
85
86export class GitHubPullRequestListDecodeError extends Schema.TaggedErrorClass<GitHubPullRequestListDecodeError>()(
87 "GitHubPullRequestListDecodeError",
88 gitHubCliDecodeFields,
89) {
90 get detail(): string {
91 return "GitHub CLI returned invalid PR list JSON.";
92 }
93
94 override get message(): string {
95 return `GitHub CLI failed in listOpenPullRequests: ${this.detail}`;
96 }
97}
98
99export class GitHubChangeRequestListDecodeError extends Schema.TaggedErrorClass<GitHubChangeRequestListDecodeError>()(
100 "GitHubChangeRequestListDecodeError",
101 gitHubCliDecodeFields,
102) {
103 get detail(): string {
104 return "GitHub CLI returned invalid change request JSON.";
105 }
106
107 override get message(): string {
108 return `GitHub CLI failed in listChangeRequests: ${this.detail}`;
109 }
110}
111
112export class GitHubPullRequestDecodeError extends Schema.TaggedErrorClass<GitHubPullRequestDecodeError>()(
113 "GitHubPullRequestDecodeError",
114 gitHubCliDecodeFields,
115) {
116 get detail(): string {
117 return "GitHub CLI returned invalid pull request JSON.";
118 }
119
120 override get message(): string {
121 return `GitHub CLI failed in getPullRequest: ${this.detail}`;
122 }
123}
124
125export class GitHubRepositoryDecodeError extends Schema.TaggedErrorClass<GitHubRepositoryDecodeError>()(
126 "GitHubRepositoryDecodeError",
127 gitHubCliDecodeFields,
128) {
129 get detail(): string {
130 return "GitHub CLI returned invalid repository JSON.";
131 }
132
133 override get message(): string {
134 return `GitHub CLI failed in getRepositoryCloneUrls: ${this.detail}`;
135 }
136}
137
138export const GitHubCliError = Schema.Union([
139 GitHubCliUnavailableError,
140 GitHubCliAuthenticationError,
141 GitHubPullRequestNotFoundError,
142 GitHubCliCommandError,
143 GitHubPullRequestListDecodeError,
144 GitHubChangeRequestListDecodeError,
145 GitHubPullRequestDecodeError,
146 GitHubRepositoryDecodeError,
147]);
148export type GitHubCliError = typeof GitHubCliError.Type;
149
150export const isGitHubCliError = Schema.is(GitHubCliError);
151
152export function fromVcsError(
153 context: {
154 readonly command: "gh";
155 readonly cwd: string;
156 },
157 error: VcsError,
158): GitHubCliError {
159 if (
160 error._tag === "VcsProcessSpawnError" &&
161 error.cause instanceof PlatformError.PlatformError &&
162 error.cause.reason._tag === "NotFound" &&
163 error.cause.reason.module === "ChildProcess" &&
164 error.cause.reason.method === "spawn"
165 ) {
166 return new GitHubCliUnavailableError({ ...context, cause: error });
167 }
168
169 if (error._tag === "VcsProcessExitError") {
170 if (error.failureKind === "authentication") {
171 return new GitHubCliAuthenticationError({ ...context, cause: error });
172 }
173 if (error.failureKind === "not-found") {
174 return new GitHubPullRequestNotFoundError({ ...context, cause: error });
175 }
176 }
177
178 return new GitHubCliCommandError({ ...context, cause: error });
179}
180
181export interface GitHubPullRequestSummary {
182 readonly number: number;
183 readonly title: string;
184 readonly url: string;
185 readonly baseRefName: string;
186 readonly headRefName: string;
187 readonly state?: "open" | "closed" | "merged";
188 readonly isCrossRepository?: boolean;
189 readonly headRepositoryNameWithOwner?: string | null;
190 readonly headRepositoryOwnerLogin?: string | null;
191}
192
193export interface GitHubRepositoryCloneUrls {
194 readonly nameWithOwner: string;
195 readonly url: string;
196 readonly sshUrl: string;
197}
198
199export class GitHubCli extends Context.Service<
200 GitHubCli,
201 {
202 readonly execute: (input: {
203 readonly cwd: string;
204 readonly args: ReadonlyArray<string>;
205 readonly timeoutMs?: number;
206 /** Piped to the child's stdin, for payloads that must never appear in argv. */
207 readonly stdin?: string;
208 readonly maxOutputBytes?: number;
209 }) => Effect.Effect<VcsProcess.VcsProcessOutput, GitHubCliError>;
210
211 readonly listOpenPullRequests: (input: {
212 readonly cwd: string;
213 readonly headSelector: string;
214 readonly limit?: number;
215 }) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
216
217 readonly getPullRequest: (input: {
218 readonly cwd: string;
219 readonly reference: string;
220 }) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
221
222 readonly getRepositoryCloneUrls: (input: {
223 readonly cwd: string;
224 readonly repository: string;
225 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
226
227 readonly createRepository: (input: {
228 readonly cwd: string;
229 readonly repository: string;
230 readonly visibility: SourceControlRepositoryVisibility;
231 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
232
233 readonly createPullRequest: (input: {
234 readonly cwd: string;
235 readonly baseBranch: string;
236 readonly headSelector: string;
237 readonly title: string;
238 readonly bodyFile: string;
239 }) => Effect.Effect<void, GitHubCliError>;
240
241 readonly getDefaultBranch: (input: {
242 readonly cwd: string;
243 }) => Effect.Effect<string | null, GitHubCliError>;
244
245 readonly checkoutPullRequest: (input: {
246 readonly cwd: string;
247 readonly reference: string;
248 readonly force?: boolean;
249 }) => Effect.Effect<void, GitHubCliError>;
250 }
251>()("t3/sourceControl/GitHubCli") {}
252
253const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
254 nameWithOwner: TrimmedNonEmptyString,
255 url: TrimmedNonEmptyString,
256 sshUrl: TrimmedNonEmptyString,
257});
258const decodeRawGitHubRepositoryCloneUrls = Schema.decodeEffect(
259 Schema.fromJsonString(RawGitHubRepositoryCloneUrlsSchema),
260);
261
262function normalizeRepositoryCloneUrls(
263 raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
264): GitHubRepositoryCloneUrls {
265 return {
266 nameWithOwner: raw.nameWithOwner,
267 url: raw.url,
268 sshUrl: raw.sshUrl,
269 };
270}
271
272/**
273 * `gh repo create` prints the canonical URL of the new repository on stdout
274 * (e.g. `https://github.com/owner/repo`). Reading it back here avoids a
275 * follow-up `gh repo view`, which can race GitHub's GraphQL eventual
276 * consistency window and falsely report the just-created repo as missing.
277 */
278function deriveRepositoryCloneUrlsFromCreateOutput(
279 stdout: string,
280 repository: string,
281): GitHubRepositoryCloneUrls {
282 const fallbackHost = "github.com";
283 const match = stdout.match(/https?:\/\/[^\s]+/);
284 if (match) {
285 const cleaned = match[0].replace(/\.git$/, "");
286 try {
287 const parsed = new URL(cleaned);
288 const pathname = parsed.pathname.replace(/^\/+|\/+$/g, "");
289 const segments = pathname.split("/").filter(Boolean);
290 if (segments.length === 2) {
291 const nameWithOwner = `${segments[0]}/${segments[1]}`;
292 return {
293 nameWithOwner,
294 url: `${parsed.origin}/${nameWithOwner}`,
295 sshUrl: `git@${parsed.host}:${nameWithOwner}.git`,
296 };
297 }
298 } catch {
299 // Fall through to the input-derived defaults below.
300 }
301 }
302 return {
303 nameWithOwner: repository,
304 url: `https://${fallbackHost}/${repository}`,
305 sshUrl: `git@${fallbackHost}:${repository}.git`,
306 };
307}
308
309export const make = Effect.gen(function* () {
310 const process = yield* VcsProcess.VcsProcess;
311
312 const execute: GitHubCli["Service"]["execute"] = (input) =>
313 process
314 .run({
315 operation: "GitHubCli.execute",
316 command: "gh",
317 args: input.args,
318 cwd: input.cwd,
319 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
320 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
321 ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
322 })
323 .pipe(Effect.mapError((error) => fromVcsError({ command: "gh", cwd: input.cwd }, error)));
324
325 return GitHubCli.of({
326 execute,
327 listOpenPullRequests: (input) =>
328 execute({
329 cwd: input.cwd,
330 args: [
331 "pr",
332 "list",
333 "--head",
334 input.headSelector,
335 "--state",
336 "open",
337 "--limit",
338 String(input.limit ?? 1),
339 "--json",
340 "number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
341 ],
342 }).pipe(
343 Effect.map((result) => result.stdout.trim()),
344 Effect.flatMap((raw) =>
345 raw.length === 0
346 ? Effect.succeed([])
347 : Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
348 Effect.flatMap((decoded) => {
349 if (!Result.isSuccess(decoded)) {
350 return Effect.fail(
351 new GitHubPullRequestListDecodeError({
352 command: "gh",
353 cwd: input.cwd,
354 cause: decoded.failure,
355 }),
356 );
357 }
358
359 return Effect.succeed(
360 decoded.success.map(({ updatedAt: _updatedAt, ...summary }) => summary),
361 );
362 }),
363 ),
364 ),
365 ),
366 getPullRequest: (input) =>
367 execute({
368 cwd: input.cwd,
369 args: [
370 "pr",
371 "view",
372 input.reference,
373 "--json",
374 "number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
375 ],
376 }).pipe(
377 Effect.map((result) => result.stdout.trim()),
378 Effect.flatMap((raw) =>
379 Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
380 Effect.flatMap((decoded) => {
381 if (!Result.isSuccess(decoded)) {
382 return Effect.fail(
383 new GitHubPullRequestDecodeError({
384 command: "gh",
385 cwd: input.cwd,
386 cause: decoded.failure,
387 }),
388 );
389 }
390
391 return Effect.succeed(
392 (({ updatedAt: _updatedAt, ...summary }) => summary)(decoded.success),
393 );
394 }),
395 ),
396 ),
397 ),
398 getRepositoryCloneUrls: (input) =>
399 execute({
400 cwd: input.cwd,
401 args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
402 }).pipe(
403 Effect.map((result) => result.stdout.trim()),
404 Effect.flatMap((raw) =>
405 decodeRawGitHubRepositoryCloneUrls(raw).pipe(
406 Effect.mapError(
407 (cause) =>
408 new GitHubRepositoryDecodeError({
409 command: "gh",
410 cwd: input.cwd,
411 cause,
412 }),
413 ),
414 ),
415 ),
416 Effect.map(normalizeRepositoryCloneUrls),
417 ),
418 createRepository: (input) =>
419 execute({
420 cwd: input.cwd,
421 args: ["repo", "create", input.repository, `--${input.visibility}`],
422 }).pipe(
423 Effect.map((result) =>
424 deriveRepositoryCloneUrlsFromCreateOutput(result.stdout, input.repository),
425 ),
426 ),
427 createPullRequest: (input) =>
428 execute({
429 cwd: input.cwd,
430 args: [
431 "pr",
432 "create",
433 "--base",
434 input.baseBranch,
435 "--head",
436 input.headSelector,
437 "--title",
438 input.title,
439 "--body-file",
440 input.bodyFile,
441 ],
442 }).pipe(Effect.asVoid),
443 getDefaultBranch: (input) =>
444 execute({
445 cwd: input.cwd,
446 args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
447 }).pipe(
448 Effect.map((value) => {
449 const trimmed = value.stdout.trim();
450 return trimmed.length > 0 ? trimmed : null;
451 }),
452 ),
453 checkoutPullRequest: (input) =>
454 execute({
455 cwd: input.cwd,
456 args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
457 }).pipe(Effect.asVoid),
458 });
459});
460
461export const layer = Layer.effect(GitHubCli, make);