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