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 "@v12/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 }) => Effect.Effect<VcsProcess.VcsProcessOutput, GitHubCliError>;
207
208 readonly listOpenPullRequests: (input: {
209 readonly cwd: string;
210 readonly headSelector: string;
211 readonly limit?: number;
212 }) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
213
214 readonly getPullRequest: (input: {
215 readonly cwd: string;
216 readonly reference: string;
217 }) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
218
219 readonly getRepositoryCloneUrls: (input: {
220 readonly cwd: string;
221 readonly repository: string;
222 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
223
224 readonly createRepository: (input: {
225 readonly cwd: string;
226 readonly repository: string;
227 readonly visibility: SourceControlRepositoryVisibility;
228 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
229
230 readonly createPullRequest: (input: {
231 readonly cwd: string;
232 readonly baseBranch: string;
233 readonly headSelector: string;
234 readonly title: string;
235 readonly bodyFile: string;
236 }) => Effect.Effect<void, GitHubCliError>;
237
238 readonly getDefaultBranch: (input: {
239 readonly cwd: string;
240 }) => Effect.Effect<string | null, GitHubCliError>;
241
242 readonly checkoutPullRequest: (input: {
243 readonly cwd: string;
244 readonly reference: string;
245 readonly force?: boolean;
246 }) => Effect.Effect<void, GitHubCliError>;
247 }
248>()("v12/sourceControl/GitHubCli") {}
249
250const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
251 nameWithOwner: TrimmedNonEmptyString,
252 url: TrimmedNonEmptyString,
253 sshUrl: TrimmedNonEmptyString,
254});
255const decodeRawGitHubRepositoryCloneUrls = Schema.decodeEffect(
256 Schema.fromJsonString(RawGitHubRepositoryCloneUrlsSchema),
257);
258
259function normalizeRepositoryCloneUrls(
260 raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
261): GitHubRepositoryCloneUrls {
262 return {
263 nameWithOwner: raw.nameWithOwner,
264 url: raw.url,
265 sshUrl: raw.sshUrl,
266 };
267}
268
269/**
270 * `gh repo create` prints the canonical URL of the new repository on stdout
271 * (e.g. `https://github.com/owner/repo`). Reading it back here avoids a
272 * follow-up `gh repo view`, which can race GitHub's GraphQL eventual
273 * consistency window and falsely report the just-created repo as missing.
274 */
275function deriveRepositoryCloneUrlsFromCreateOutput(
276 stdout: string,
277 repository: string,
278): GitHubRepositoryCloneUrls {
279 const fallbackHost = "github.com";
280 const match = stdout.match(/https?:\/\/[^\s]+/);
281 if (match) {
282 const cleaned = match[0].replace(/\.git$/, "");
283 try {
284 const parsed = new URL(cleaned);
285 const pathname = parsed.pathname.replace(/^\/+|\/+$/g, "");
286 const segments = pathname.split("/").filter(Boolean);
287 if (segments.length === 2) {
288 const nameWithOwner = `${segments[0]}/${segments[1]}`;
289 return {
290 nameWithOwner,
291 url: `${parsed.origin}/${nameWithOwner}`,
292 sshUrl: `git@${parsed.host}:${nameWithOwner}.git`,
293 };
294 }
295 } catch {
296 // Fall through to the input-derived defaults below.
297 }
298 }
299 return {
300 nameWithOwner: repository,
301 url: `https://${fallbackHost}/${repository}`,
302 sshUrl: `git@${fallbackHost}:${repository}.git`,
303 };
304}
305
306export const make = Effect.gen(function* () {
307 const process = yield* VcsProcess.VcsProcess;
308
309 const execute: GitHubCli["Service"]["execute"] = (input) =>
310 process
311 .run({
312 operation: "GitHubCli.execute",
313 command: "gh",
314 args: input.args,
315 cwd: input.cwd,
316 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
317 })
318 .pipe(Effect.mapError((error) => fromVcsError({ command: "gh", cwd: input.cwd }, error)));
319
320 return GitHubCli.of({
321 execute,
322 listOpenPullRequests: (input) =>
323 execute({
324 cwd: input.cwd,
325 args: [
326 "pr",
327 "list",
328 "--head",
329 input.headSelector,
330 "--state",
331 "open",
332 "--limit",
333 String(input.limit ?? 1),
334 "--json",
335 "number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
336 ],
337 }).pipe(
338 Effect.map((result) => result.stdout.trim()),
339 Effect.flatMap((raw) =>
340 raw.length === 0
341 ? Effect.succeed([])
342 : Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
343 Effect.flatMap((decoded) => {
344 if (!Result.isSuccess(decoded)) {
345 return Effect.fail(
346 new GitHubPullRequestListDecodeError({
347 command: "gh",
348 cwd: input.cwd,
349 cause: decoded.failure,
350 }),
351 );
352 }
353
354 return Effect.succeed(
355 decoded.success.map(({ updatedAt: _updatedAt, ...summary }) => summary),
356 );
357 }),
358 ),
359 ),
360 ),
361 getPullRequest: (input) =>
362 execute({
363 cwd: input.cwd,
364 args: [
365 "pr",
366 "view",
367 input.reference,
368 "--json",
369 "number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
370 ],
371 }).pipe(
372 Effect.map((result) => result.stdout.trim()),
373 Effect.flatMap((raw) =>
374 Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
375 Effect.flatMap((decoded) => {
376 if (!Result.isSuccess(decoded)) {
377 return Effect.fail(
378 new GitHubPullRequestDecodeError({
379 command: "gh",
380 cwd: input.cwd,
381 cause: decoded.failure,
382 }),
383 );
384 }
385
386 return Effect.succeed(
387 (({ updatedAt: _updatedAt, ...summary }) => summary)(decoded.success),
388 );
389 }),
390 ),
391 ),
392 ),
393 getRepositoryCloneUrls: (input) =>
394 execute({
395 cwd: input.cwd,
396 args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
397 }).pipe(
398 Effect.map((result) => result.stdout.trim()),
399 Effect.flatMap((raw) =>
400 decodeRawGitHubRepositoryCloneUrls(raw).pipe(
401 Effect.mapError(
402 (cause) =>
403 new GitHubRepositoryDecodeError({
404 command: "gh",
405 cwd: input.cwd,
406 cause,
407 }),
408 ),
409 ),
410 ),
411 Effect.map(normalizeRepositoryCloneUrls),
412 ),
413 createRepository: (input) =>
414 execute({
415 cwd: input.cwd,
416 args: ["repo", "create", input.repository, `--${input.visibility}`],
417 }).pipe(
418 Effect.map((result) =>
419 deriveRepositoryCloneUrlsFromCreateOutput(result.stdout, input.repository),
420 ),
421 ),
422 createPullRequest: (input) =>
423 execute({
424 cwd: input.cwd,
425 args: [
426 "pr",
427 "create",
428 "--base",
429 input.baseBranch,
430 "--head",
431 input.headSelector,
432 "--title",
433 input.title,
434 "--body-file",
435 input.bodyFile,
436 ],
437 }).pipe(Effect.asVoid),
438 getDefaultBranch: (input) =>
439 execute({
440 cwd: input.cwd,
441 args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
442 }).pipe(
443 Effect.map((value) => {
444 const trimmed = value.stdout.trim();
445 return trimmed.length > 0 ? trimmed : null;
446 }),
447 ),
448 checkoutPullRequest: (input) =>
449 execute({
450 cwd: input.cwd,
451 args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
452 }).pipe(Effect.asVoid),
453 });
454});
455
456export const layer = Layer.effect(GitHubCli, make);