Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitHubSourceControlProvider.ts

662 lines22.9 KB

1import * as Schema from "effect/Schema";
2import * as DateTime from "effect/DateTime";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import * as Result from "effect/Result";
6import {
7 SourceControlProviderError,
8 type ChangeRequest,
9 type ChangeRequestState,
10} from "@t3tools/contracts";
11​
12import * as GitHubCli from "./GitHubCli.ts";
13import { findAuthenticatedGitHubAccount, parseGitHubAuthStatus } from "./gitHubAuthStatus.ts";
14import { decodeGitHubPullRequestListJson } from "./gitHubPullRequests.ts";
15import * as SourceControlProvider from "./SourceControlProvider.ts";
16import {
17 combinedAuthOutput,
18 firstSafeAuthLine,
19 providerAuth,
20 type SourceControlAuthProbeInput,
21 type SourceControlCliDiscoverySpec,
22 type SourceControlDiscoveryInstance,
23 type SourceControlUnknownRemoteRefinementInput,
24} from "./SourceControlProviderDiscovery.ts";
25​
26type GitHubProviderKind = "github" | "github-enterprise";
27​
28const decodeLinkSubject = Schema.decodeUnknownEffect(
29 Schema.fromJsonString(
30 Schema.Struct({ title: Schema.String, body: Schema.NullOr(Schema.String) }),
31 ),
32);
33​
34function toChangeRequest(
35 kind: GitHubProviderKind,
36 summary: GitHubCli.GitHubPullRequestSummary,
37): ChangeRequest {
38 return {
39 provider: kind,
40 number: summary.number,
41 title: summary.title,
42 url: summary.url,
43 baseRefName: summary.baseRefName,
44 headRefName: summary.headRefName,
45 state: summary.state ?? "open",
46 ...(summary.isDraft === true ? { isDraft: true } : {}),
47 closedAt: summary.closedAt ?? null,
48 mergedAt: summary.mergedAt ?? null,
49 updatedAt:
50 summary.updatedAt === undefined
51 ? Option.none()
52 : Option.some(DateTime.makeUnsafe(summary.updatedAt)),
53 ...(summary.isCrossRepository !== undefined
54 ? { isCrossRepository: summary.isCrossRepository }
55 : {}),
56 ...(summary.headRepositoryNameWithOwner !== undefined
57 ? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }
58 : {}),
59 ...(summary.headRepositoryOwnerLogin !== undefined
60 ? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }
61 : {}),
62 };
64​
65function parseGitHubAuth(input: SourceControlAuthProbeInput) {
66 const output = combinedAuthOutput(input);
67 const authStatus = parseGitHubAuthStatus(input.stdout);
68 const authenticatedAccount = findAuthenticatedGitHubAccount(authStatus.accounts);
69 const host = authenticatedAccount?.host;
70​
71 if (authenticatedAccount) {
72 return providerAuth({
73 status: "authenticated",
74 account: authenticatedAccount.account,
75 host,
76 });
77 }
78​
79 const failedAccount = authStatus.accounts.find((entry) => entry.active) ?? authStatus.accounts[0];
80 if (authStatus.parsed) {
81 return providerAuth({
82 status: "unauthenticated",
83 host: failedAccount?.host,
84 detail:
85 failedAccount?.error ??
86 "Run `gh auth login` to authenticate GitHub CLI with an active account.",
87 });
88 }
89​
90 // gh gained `auth status --json` in 2.81.0. Older versions reject the flag and exit
91 // non-zero, which reads exactly like a signed-out CLI. Name the real problem instead.
92 if (input.exitCode !== 0 && output.includes("unknown flag: --json")) {
93 return providerAuth({
94 status: "unknown",
95 detail:
96 "GitHub CLI is too old to report sign-in status. Update `gh` to 2.81.0 or newer (for example `brew upgrade gh`) and rescan.",
97 });
98 }
99​
100 if (input.exitCode !== 0) {
101 return providerAuth({
102 status: "unauthenticated",
103 host,
104 detail: firstSafeAuthLine(output) ?? "Run `gh auth login` to authenticate GitHub CLI.",
105 });
106 }
107​
108 return providerAuth({
109 status: "unknown",
110 host,
111 detail: firstSafeAuthLine(output) ?? "GitHub CLI auth status could not be parsed.",
112 });
114​
115function githubComAuth(status: ReturnType<typeof parseGitHubAuthStatus>) {
116 const accounts = status.accounts.filter((account) => account.host === "github.com");
117 const authenticated = findAuthenticatedGitHubAccount(accounts);
118 if (authenticated) {
119 return providerAuth({
120 status: "authenticated",
121 account: authenticated.account,
122 host: "github.com",
123 });
124 }
125 return providerAuth({
126 status: "unauthenticated",
127 host: "github.com",
128 detail:
129 accounts[0]?.error ??
130 "Run `gh auth login` to authenticate GitHub CLI with an active account.",
131 });
133​
134export function expandGitHubInstances(
135 input: SourceControlAuthProbeInput,
136): ReadonlyArray<SourceControlDiscoveryInstance> {
137 const status = parseGitHubAuthStatus(input.stdout);
138 if (!status.parsed) {
139 return [
140 {
141 kind: "github",
142 id: "github",
143 host: "github.com",
144 label: "GitHub",
145 auth: parseGitHubAuth(input),
146 },
147 ];
148 }
149​
150 const enterpriseHosts = [
151 ...new Set(
152 status.accounts.map((account) => account.host).filter((host) => host !== "github.com"),
153 ),
154 ].sort();
155​
156 return [
157 {
158 kind: "github",
159 id: "github",
160 host: "github.com",
161 label: "GitHub",
162 auth: githubComAuth(status),
163 },
164 ...enterpriseHosts.map((host) => {
165 const accounts = status.accounts.filter((account) => account.host === host);
166 const authenticated = findAuthenticatedGitHubAccount(accounts);
167 return {
168 kind: "github-enterprise" as const,
169 id: `github-enterprise:${host}`,
170 host,
171 label: host,
172 auth: authenticated
173 ? providerAuth({ status: "authenticated", account: authenticated.account, host })
174 : providerAuth({
175 status: "unauthenticated",
176 host,
177 detail:
178 accounts[0]?.error ?? `Run \`gh auth login --hostname ${host}\` to authenticate.`,
179 }),
180 };
181 }),
182 ];
184​
185// An `unknown` remote's provider name is the raw host, port included, so both
186// sides have to drop the port before they can be compared.
187function toHostName(host: string): string {
188 try {
189 return new URL(`https://${host}`).hostname.toLowerCase();
190 } catch {
191 return host.replace(/:\d+$/u, "").toLowerCase();
192 }
194​
195export function refineUnknownGitHubRemote(input: SourceControlUnknownRemoteRefinementInput) {
196 const host = toHostName(input.context.provider.name);
197 const authenticated = parseGitHubAuthStatus(input.auth.stdout).accounts.some(
198 (account) => toHostName(account.host) === host && account.authenticated,
199 );
200​
201 if (!authenticated) {
202 return null;
203 }
204​
205 return {
206 kind: "github-enterprise",
207 name: host,
208 baseUrl: input.context.provider.baseUrl,
209 } as const;
211​
212export const discovery = {
213 type: "cli",
214 kind: "github",
215 label: "GitHub",
216 executable: "gh",
217 versionArgs: ["--version"],
218 authArgs: ["auth", "status", "--json", "hosts"],
219 parseAuth: parseGitHubAuth,
220 expandInstances: expandGitHubInstances,
221 refineUnknownRemote: refineUnknownGitHubRemote,
222 installHint:
223 "Install the GitHub command-line tool (`gh`) via https://cli.github.com/ or your package manager (for example `brew install gh`).",
224} satisfies SourceControlCliDiscoverySpec;
225​
226function isBareRepositoryName(repository: string): boolean {
227 return !repository.includes("/");
229​
230const AMBIGUOUS_REPOSITORY_CANDIDATE_LIMIT = 5;
231​
232type RepositorySearchMatch =
233 | { readonly _tag: "match"; readonly fullName: string }
234 | { readonly _tag: "ambiguous"; readonly candidates: ReadonlyArray<string> }
235 | { readonly _tag: "none" };
236​
237// Bare names resolve against the caller's personal namespace on `gh repo
238// view`, which is usually empty on an enterprise host, so they go through
239// search instead. An exact repo-name match wins outright; a sole near match
240// still resolves, since that is the whole point of accepting a bare name.
241// Anything else is a choice between repositories that search ranking is no
242// basis for making, so report the candidates rather than guess.
243function pickRepositorySearchMatch(
244 query: string,
245 results: ReadonlyArray<GitHubCli.GitHubRepositorySearchResult>,
246): RepositorySearchMatch {
247 if (results.length === 0) {
248 return { _tag: "none" };
249 }
250​
251 const normalizedQuery = query.toLowerCase();
252 const exact = results.filter(
253 (result) => result.fullName.split("/").pop()?.toLowerCase() === normalizedQuery,
254 );
255 if (exact.length === 1) {
256 return { _tag: "match", fullName: exact[0]!.fullName };
257 }
258 const candidates = exact.length > 1 ? exact : results;
259 if (candidates.length > 1) {
260 return { _tag: "ambiguous", candidates: candidates.map((result) => result.fullName) };
261 }
262 return { _tag: "match", fullName: candidates[0]!.fullName };
264​
265/**
266 * What a bare name that resolved to nothing, or to more than one repository, tells the reader.
267 * It lives beside the taxonomy that produced it: the failure carries the same structural fields
268 * either way, and only the sentence differs between the two outcomes.
269 */
270function repositorySearchFailureDetail(
271 match: Extract<RepositorySearchMatch, { readonly _tag: "ambiguous" | "none" }>,
272 context: { readonly repository: string; readonly host?: string },
273): string {
274 const repository = SourceControlProvider.transportSafeSourceControlErrorValue(context.repository);
275 const host = context.host
276 ? SourceControlProvider.transportSafeSourceControlErrorValue(context.host)
277 : "the configured host";
278 if (match._tag === "none") {
279 return `No repository named "${repository}" was found on ${host}.`;
280 }
281 const candidates = match.candidates
282 .slice(0, AMBIGUOUS_REPOSITORY_CANDIDATE_LIMIT)
283 .map((candidate) => SourceControlProvider.transportSafeSourceControlErrorValue(candidate))
284 .join(", ");
285 return `More than one repository on ${host} matches "${repository}": ${candidates}. Enter the full owner/repo path.`;
287​
288export const makeProvider = (kind: GitHubProviderKind) =>
289 Effect.gen(function* () {
290 const github = yield* GitHubCli.GitHubCli;
291​
292 // A `gh` call with no host and no repo context falls back to github.com, so
293 // it does not fail — it quietly answers for public GitHub. Only operations
294 // that cannot borrow the host from the surrounding remote need this: an
295 // in-repo `gh repo view owner/repo` resolves its own host and must keep
296 // working without one.
297 const ensureEnterpriseHost = (input: {
298 readonly cwd: string;
299 readonly repository: string;
300 readonly host?: string;
301 readonly operation: string;
302 }): Effect.Effect<void, SourceControlProviderError> =>
303 kind === "github-enterprise" && !input.host
304 ? Effect.fail(
305 new SourceControlProviderError({
306 provider: kind,
307 operation: input.operation,
308 command: "gh",
309 cwd: input.cwd,
310 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
311 input.repository,
312 ),
313 detail: "Choose a GitHub Enterprise host before continuing.",
314 }),
315 )
316 : Effect.void;
317​
318 const resolveRepositoryReference = (input: {
319 readonly cwd: string;
320 readonly repository: string;
321 readonly host?: string;
322 }): Effect.Effect<string, SourceControlProviderError> => {
323 const repository = input.repository.trim();
324 if (kind !== "github-enterprise" || !isBareRepositoryName(repository)) {
325 return Effect.succeed(repository);
326 }
327​
328 // `gh search repos` ignores repo context entirely, so unlike a lookup by
329 // owner/repo this cannot borrow the host from the surrounding remote.
330 return ensureEnterpriseHost({
331 cwd: input.cwd,
332 repository,
333 ...(input.host ? { host: input.host } : {}),
334 operation: "getRepositoryCloneUrls",
335 }).pipe(
336 Effect.andThen(() =>
337 github
338 .searchRepositories({
339 cwd: input.cwd,
340 query: repository,
341 ...(input.host ? { host: input.host } : {}),
342 })
343 .pipe(
344 Effect.mapError(
345 (error) =>
346 new SourceControlProviderError({
347 provider: kind,
348 operation: "getRepositoryCloneUrls",
349 command: error.command,
350 cwd: input.cwd,
351 repository:
352 SourceControlProvider.transportSafeSourceControlErrorValue(repository),
353 detail: error.detail,
354 cause: error,
355 }),
356 ),
357 Effect.flatMap((results) => {
358 const match = pickRepositorySearchMatch(repository, results);
359 if (match._tag === "match") {
360 return Effect.succeed(match.fullName);
361 }
362​
363 return Effect.fail(
364 new SourceControlProviderError({
365 provider: kind,
366 operation: "getRepositoryCloneUrls",
367 command: "gh",
368 cwd: input.cwd,
369 repository:
370 SourceControlProvider.transportSafeSourceControlErrorValue(repository),
371 detail: repositorySearchFailureDetail(match, {
372 repository,
373 ...(input.host ? { host: input.host } : {}),
374 }),
375 }),
376 );
377 }),
378 ),
379 ),
380 );
381 };
382​
383 const listChangeRequests: SourceControlProvider.SourceControlProvider["Service"]["listChangeRequests"] =
384 (input) => {
385 if (input.state === "open") {
386 return github
387 .listOpenPullRequests({
388 cwd: input.cwd,
389 headSelector: input.headSelector,
390 ...(input.limit !== undefined ? { limit: input.limit } : {}),
391 })
392 .pipe(
393 Effect.map((items) => items.map((summary) => toChangeRequest(kind, summary))),
394 Effect.mapError(
395 (error) =>
396 new SourceControlProviderError({
397 provider: kind,
398 operation: "listChangeRequests",
399 command: error.command,
400 cwd: input.cwd,
401 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
402 input.headSelector,
403 ),
404 detail: error.detail,
405 cause: error,
406 }),
407 ),
408 );
409 }
410​
411 const stateArg: ChangeRequestState | "all" = input.state;
412 return github
413 .execute({
414 cwd: input.cwd,
415 args: [
416 "pr",
417 "list",
418 "--head",
419 input.headSelector,
420 "--state",
421 stateArg,
422 "--limit",
423 String(input.limit ?? 20),
424 "--json",
425 "number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
426 ],
427 })
428 .pipe(
429 Effect.flatMap((result) => {
430 const raw = result.stdout.trim();
431 if (raw.length === 0) {
432 return Effect.succeed([]);
433 }
434 return Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
435 Effect.flatMap((decoded) =>
436 Result.isSuccess(decoded)
437 ? Effect.succeed(
438 decoded.success.map((item) => {
439 const { updatedAt, ...summary } = item;
440 return {
441 ...toChangeRequest(kind, {
442 ...summary,
443 ...(Option.isSome(updatedAt)
444 ? { updatedAt: DateTime.formatIso(updatedAt.value) }
445 : {}),
446 }),
447 updatedAt,
448 };
449 }),
450 )
451 : Effect.fail(
452 new GitHubCli.GitHubChangeRequestListDecodeError({
453 command: "gh",
454 cwd: input.cwd,
455 cause: decoded.failure,
456 }),
457 ),
458 ),
459 );
460 }),
461 Effect.mapError(
462 (error) =>
463 new SourceControlProviderError({
464 provider: kind,
465 operation: "listChangeRequests",
466 command: error.command,
467 cwd: input.cwd,
468 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
469 input.headSelector,
470 ),
471 detail: error.detail,
472 cause: error,
473 }),
474 ),
475 );
476 };
477​
478 const readLinkSubject = Effect.fn("GitHubSourceControlProvider.readLinkSubject")(function* (
479 input: { readonly cwd: string; readonly url: URL },
480 endpoint: string,
481 ) {
482 const result = yield* github
483 .execute({
484 cwd: input.cwd,
485 args: ["api", "--hostname", input.url.host, endpoint, "--jq", "{title, body}"],
486 env: { GH_PROMPT_DISABLED: "1" },
487 timeoutMs: 3_000,
488 maxOutputBytes: 32_000,
489 })
490 .pipe(
491 Effect.mapError(
492 (cause) =>
493 new SourceControlProviderError({
494 provider: kind,
495 operation: "resolveLink",
496 cwd: input.cwd,
497 detail: "The linked subject could not be read.",
498 cause,
499 }),
500 ),
501 );
502 const subject = yield* decodeLinkSubject(result.stdout).pipe(
503 Effect.mapError(
504 (cause) =>
505 new SourceControlProviderError({
506 provider: kind,
507 operation: "resolveLink.decode",
508 cwd: input.cwd,
509 detail: "The linked subject could not be read.",
510 cause,
511 }),
512 ),
513 );
514 return { title: subject.title, body: subject.body };
515 });
516​
517 return SourceControlProvider.SourceControlProvider.of({
518 kind,
519 resolveLink: (input) => {
520 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
521 // An Enterprise host is named by whoever wrote the link, so only dotcom is read here.
522 if (input.url.host !== "github.com") return undefined;
523 const match = /^\/([\w.-]+)\/([\w.-]+)\/(?:pull|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
524 input.url.pathname,
525 );
526 if (!match) return undefined;
527 return readLinkSubject(input, `repos/${match[1]}/${match[2]}/issues/${match[3]}`);
528 },
529 listChangeRequests,
530 getChangeRequest: (input) =>
531 github.getPullRequest(input).pipe(
532 Effect.map((summary) => toChangeRequest(kind, summary)),
533 Effect.mapError(
534 (error) =>
535 new SourceControlProviderError({
536 provider: kind,
537 operation: "getChangeRequest",
538 command: error.command,
539 cwd: input.cwd,
540 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
541 input.reference,
542 ),
543 detail: error.detail,
544 cause: error,
545 }),
546 ),
547 ),
548 createChangeRequest: (input) =>
549 github
550 .createPullRequest({
551 cwd: input.cwd,
552 baseBranch: input.baseRefName,
553 headSelector: input.headSelector,
554 title: input.title,
555 bodyFile: input.bodyFile,
556 })
557 .pipe(
558 Effect.mapError(
559 (error) =>
560 new SourceControlProviderError({
561 provider: kind,
562 operation: "createChangeRequest",
563 command: error.command,
564 cwd: input.cwd,
565 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
566 input.headSelector,
567 ),
568 detail: error.detail,
569 cause: error,
570 }),
571 ),
572 ),
573 getRepositoryCloneUrls: (input) =>
574 resolveRepositoryReference(input).pipe(
575 Effect.flatMap((repository) =>
576 github
577 .getRepositoryCloneUrls({
578 cwd: input.cwd,
579 repository,
580 ...(input.host ? { host: input.host } : {}),
581 })
582 .pipe(
583 Effect.mapError(
584 (error) =>
585 new SourceControlProviderError({
586 provider: kind,
587 operation: "getRepositoryCloneUrls",
588 command: error.command,
589 cwd: input.cwd,
590 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
591 input.repository,
592 ),
593 detail: error.detail,
594 cause: error,
595 }),
596 ),
597 ),
598 ),
599 ),
600 createRepository: (input) =>
601 ensureEnterpriseHost({ ...input, operation: "createRepository" }).pipe(
602 Effect.andThen(() =>
603 github
604 .createRepository({
605 cwd: input.cwd,
606 repository: input.repository,
607 visibility: input.visibility,
608 ...(input.host ? { host: input.host } : {}),
609 })
610 .pipe(
611 Effect.mapError(
612 (error) =>
613 new SourceControlProviderError({
614 provider: kind,
615 operation: "createRepository",
616 command: error.command,
617 cwd: input.cwd,
618 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
619 input.repository,
620 ),
621 detail: error.detail,
622 cause: error,
623 }),
624 ),
625 ),
626 ),
627 ),
628 getDefaultBranch: (input) =>
629 github.getDefaultBranch(input).pipe(
630 Effect.mapError(
631 (error) =>
632 new SourceControlProviderError({
633 provider: kind,
634 operation: "getDefaultBranch",
635 command: error.command,
636 cwd: input.cwd,
637 detail: error.detail,
638 cause: error,
639 }),
640 ),
641 ),
642 checkoutChangeRequest: (input) =>
643 github.checkoutPullRequest(input).pipe(
644 Effect.mapError(
645 (error) =>
646 new SourceControlProviderError({
647 provider: kind,
648 operation: "checkoutChangeRequest",
649 command: error.command,
650 cwd: input.cwd,
651 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
652 input.reference,
653 ),
654 detail: error.detail,
655 cause: error,
656 }),
657 ),
658 ),
659 });
660 });
661​
662export const make = makeProvider("github");