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