Open History to see the last commit
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 DEFAULT_SERVER_SETTINGS,
8 SourceControlProviderError,
9 type ChangeRequest,
10 type GitHubSettings,
11 type SourceControlProviderDiscoveryItem,
12} from "@t3tools/contracts";
13
14import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
15
16import * as ServerSettings from "../serverSettings.ts";
17import * as GitHubApi from "./GitHubApi.ts";
18import * as GitHubCli from "./GitHubCli.ts";
19import {
20 effectiveGitHubAccount,
21 findAuthenticatedGitHubAccount,
22 parseGitHubAuthStatus,
23 type GitHubAuthStatusAccount,
24} from "./gitHubAuthStatus.ts";
25import * as SourceControlProvider from "./SourceControlProvider.ts";
26import {
27 combinedAuthOutput,
28 firstSafeAuthLine,
29 probeSourceControlProvider,
30 providerAuth,
31 type SourceControlAuthProbeInput,
32 type SourceControlCliDiscoverySpec,
33 type SourceControlManagedCliDiscoverySpec,
34} from "./SourceControlProviderDiscovery.ts";
35import * as VcsProcess from "../vcs/VcsProcess.ts";
36
37const decodeLinkSubject = Schema.decodeUnknownEffect(
38 Schema.fromJsonString(
39 Schema.Struct({ title: Schema.String, body: Schema.optional(Schema.NullOr(Schema.String)) }),
40 ),
41);
42
43function toChangeRequest(summary: GitHubCli.GitHubPullRequestSummary): ChangeRequest {
44 return {
45 provider: "github",
46 number: summary.number,
47 title: summary.title,
48 url: summary.url,
49 baseRefName: summary.baseRefName,
50 headRefName: summary.headRefName,
51 ...(summary.headSha !== undefined ? { headSha: summary.headSha } : {}),
52 state: summary.state ?? "open",
53 ...(summary.isDraft === true ? { isDraft: true } : {}),
54 closedAt: summary.closedAt ?? null,
55 mergedAt: summary.mergedAt ?? null,
56 updatedAt:
57 summary.updatedAt === undefined
58 ? Option.none()
59 : Option.some(DateTime.makeUnsafe(summary.updatedAt)),
60 ...(summary.isCrossRepository !== undefined
61 ? { isCrossRepository: summary.isCrossRepository }
62 : {}),
63 ...(summary.headRepositoryNameWithOwner !== undefined
64 ? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }
65 : {}),
66 ...(summary.headRepositoryOwnerLogin !== undefined
67 ? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }
68 : {}),
69 };
70}
71
72function authAccounts(accounts: ReadonlyArray<GitHubAuthStatusAccount>) {
73 return accounts.map((entry) => ({
74 host: entry.host,
75 account: entry.account,
76 active: entry.active,
77 authenticated: entry.authenticated,
78 ...(entry.error === null ? {} : { error: entry.error }),
79 ...(entry.environmentVariable === null
80 ? {}
81 : { environmentVariable: entry.environmentVariable }),
82 }));
83}
84
85/**
86 * Reads `gh auth status --json hosts`. The headline account is the one GitHub requests will
87 * use: Settings can pin a login per host or turn a host off, and an environment token beats both.
88 */
89export function parseGitHubAuth(
90 input: SourceControlAuthProbeInput,
91 settings: GitHubSettings = DEFAULT_SERVER_SETTINGS.github,
92) {
93 const output = combinedAuthOutput(input);
94 const authStatus = parseGitHubAuthStatus(input.stdout);
95 const hosts = [...new Set(authStatus.accounts.map((entry) => entry.host))];
96 const fallback = findAuthenticatedGitHubAccount(authStatus.accounts);
97 // Lead with the host gh would pick, unless Settings turned it off.
98 const orderedHosts = fallback
99 ? [fallback.host, ...hosts.filter((host) => host !== fallback.host)]
100 : hosts;
101 const chosen = orderedHosts
102 .map((host) => effectiveGitHubAccount(host, authStatus.accounts, settings))
103 .find((entry) => entry !== undefined);
104 const accounts = authStatus.parsed ? { accounts: authAccounts(authStatus.accounts) } : {};
105
106 if (chosen) {
107 return {
108 ...providerAuth({
109 status: "authenticated",
110 account: chosen.account,
111 host: chosen.host,
112 detail:
113 chosen.environmentVariable === null
114 ? undefined
115 : `Using ${chosen.environmentVariable} from the server environment; it overrides the account chosen in Settings.`,
116 }),
117 ...accounts,
118 };
119 }
120
121 if (fallback) {
122 return {
123 ...providerAuth({
124 status: "unauthenticated",
125 host: fallback.host,
126 detail: "Every GitHub host gh is signed in to is turned off in Settings → Source Control.",
127 }),
128 ...accounts,
129 };
130 }
131
132 const failedAccount = authStatus.accounts.find((entry) => entry.active) ?? authStatus.accounts[0];
133 if (authStatus.parsed) {
134 return {
135 ...providerAuth({
136 status: "unauthenticated",
137 host: failedAccount?.host,
138 detail:
139 failedAccount?.error ??
140 "Run `gh auth login` to authenticate GitHub CLI with an active account.",
141 }),
142 ...accounts,
143 };
144 }
145
146 // gh gained `auth status --json` in 2.81.0. Older versions reject the flag and exit
147 // non-zero, which reads exactly like a signed-out CLI. Name the real problem instead.
148 if (input.exitCode !== 0 && output.includes("unknown flag: --json")) {
149 return providerAuth({
150 status: "unknown",
151 detail:
152 "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.",
153 });
154 }
155
156 if (input.exitCode !== 0) {
157 return providerAuth({
158 status: "unauthenticated",
159 detail: firstSafeAuthLine(output) ?? "Run `gh auth login` to authenticate GitHub CLI.",
160 });
161 }
162
163 return providerAuth({
164 status: "unknown",
165 detail: firstSafeAuthLine(output) ?? "GitHub CLI auth status could not be parsed.",
166 });
167}
168
169export const discovery = {
170 type: "cli",
171 kind: "github",
172 label: "GitHub",
173 executable: "gh",
174 versionArgs: ["--version"],
175 authArgs: ["auth", "status", "--json", "hosts"],
176 parseAuth: parseGitHubAuth,
177 installHint:
178 "Install the GitHub command-line tool (`gh`) via https://cli.github.com/ or your package manager (for example `brew install gh`).",
179} satisfies SourceControlCliDiscoverySpec;
180
181const decodeViewer = Schema.decodeUnknownOption(
182 Schema.fromJsonString(Schema.Struct({ login: Schema.String })),
183);
184
185/** The environment variable gh would take a github.com token from, if one is set. */
186function environmentTokenVariable(environment: NodeJS.ProcessEnv): string | null {
187 return ["GH_TOKEN", "GITHUB_TOKEN"].find((name) => environment[name]?.trim()) ?? null;
188}
189
190/**
191 * GitHub is usable with a token saved in Settings, one from the environment, or `gh` to hand one
192 * over. Reads the
193 * GitHub settings on every probe, so a saved account choice shows on rescan. An environment
194 * token is checked against the API, since `gh auth status` may not know it.
195 */
196export const makeDiscovery = Effect.gen(function* () {
197 const api = yield* GitHubApi.GitHubApi;
198 const process = yield* VcsProcess.VcsProcess;
199 const environment = yield* HostProcessEnvironment;
200 const serverSettings = yield* ServerSettings.ServerSettingsService;
201
202 return {
203 type: "managed-cli",
204 kind: discovery.kind,
205 label: discovery.label,
206 installHint: discovery.installHint,
207 probe: Effect.fn("GitHubSourceControlProvider.discovery")(function* (cwd: string) {
208 const settings = yield* serverSettings.getSettings.pipe(
209 Effect.map((current) => current.github),
210 Effect.orElseSucceed(() => DEFAULT_SERVER_SETTINGS.github),
211 );
212 const cli = yield* probeSourceControlProvider({
213 cwd,
214 process,
215 spec: { ...discovery, parseAuth: (input) => parseGitHubAuth(input, settings) },
216 });
217 // A token saved in Settings wins over the environment, which wins over gh.
218 const savedToken = (settings.tokens["github.com"] ?? "").trim() !== "";
219 const variable = environmentTokenVariable(environment);
220 const tokenSource = savedToken ? "the token saved in Settings" : variable;
221 // A host turned off in Settings stays off even with a token.
222 if (tokenSource === null || settings.hosts["github.com"]?.enabled === false) return cli;
223 const viewer = yield* api
224 .rest({ host: "github.com", operation: "discovery", path: "user" })
225 .pipe(Effect.result);
226 const login = Result.isSuccess(viewer)
227 ? Option.getOrUndefined(decodeViewer(viewer.success.body))?.login
228 : undefined;
229 // The per-host logins stay, so the account picker still lists every host gh knows.
230 const accounts = cli.auth.accounts === undefined ? {} : { accounts: cli.auth.accounts };
231 return {
232 ...cli,
233 status: "available" as const,
234 auth: {
235 ...(login !== undefined
236 ? providerAuth({
237 status: "authenticated",
238 account: login,
239 host: "github.com",
240 detail: savedToken
241 ? "Using the token saved in Settings; it overrides GH_TOKEN and the gh login."
242 : `Using ${variable} from the server environment; it overrides the account chosen in Settings.`,
243 })
244 : Result.isFailure(viewer) && viewer.failure._tag !== "GitHubApiAuthenticationError"
245 ? // Only a refusal says the token is bad; a network error or a pause says nothing.
246 providerAuth({
247 status: "unknown",
248 host: "github.com",
249 detail: `Could not check ${savedToken ? tokenSource : `the token in ${tokenSource}`}: ${viewer.failure.message}`,
250 })
251 : providerAuth({
252 status: "unauthenticated",
253 host: "github.com",
254 detail: savedToken
255 ? "GitHub refused the token saved in Settings. Replace or remove it in Settings → Source Control."
256 : `GitHub refused the token in ${tokenSource}. Replace it, or unset it to use \`gh auth login\`.`,
257 })),
258 ...accounts,
259 },
260 } satisfies SourceControlProviderDiscoveryItem;
261 }),
262 refineUnknownRemote: () => Effect.succeed(null),
263 } satisfies SourceControlManagedCliDiscoverySpec;
264});
265
266export const make = Effect.gen(function* () {
267 const github = yield* GitHubCli.GitHubCli;
268 const api = yield* GitHubApi.GitHubApi;
269
270 const listChangeRequests: SourceControlProvider.SourceControlProvider["Service"]["listChangeRequests"] =
271 (input) => {
272 if (input.state === "open") {
273 return github
274 .listOpenPullRequests({
275 cwd: input.cwd,
276 headSelector: input.headSelector,
277 ...(input.context === undefined
278 ? {}
279 : { rateLimitHost: new URL(input.context.provider.baseUrl).host }),
280 ...(input.limit !== undefined ? { limit: input.limit } : {}),
281 })
282 .pipe(
283 Effect.map((items) => items.map(toChangeRequest)),
284 Effect.mapError(
285 (error) =>
286 new SourceControlProviderError({
287 provider: "github",
288 operation: "listChangeRequests",
289 command: error.command,
290 cwd: input.cwd,
291 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
292 input.headSelector,
293 ),
294 detail: error.message,
295 cause: error,
296 }),
297 ),
298 );
299 }
300
301 return github
302 .listPullRequestsByHead({
303 cwd: input.cwd,
304 headSelector: input.headSelector,
305 state: input.state,
306 limit: input.limit ?? 20,
307 ...(input.context === undefined
308 ? {}
309 : { rateLimitHost: new URL(input.context.provider.baseUrl).host }),
310 })
311 .pipe(
312 Effect.map((items) =>
313 items.map(({ updatedAt, ...summary }) => ({
314 ...toChangeRequest({
315 ...summary,
316 ...(Option.isSome(updatedAt)
317 ? { updatedAt: DateTime.formatIso(updatedAt.value) }
318 : {}),
319 }),
320 updatedAt,
321 })),
322 ),
323 Effect.mapError(
324 (error) =>
325 new SourceControlProviderError({
326 provider: "github",
327 operation: "listChangeRequests",
328 command: error.command,
329 cwd: input.cwd,
330 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
331 input.headSelector,
332 ),
333 detail: error.message,
334 cause: error,
335 }),
336 ),
337 );
338 };
339
340 const readLinkSubject = Effect.fn("GitHubSourceControlProvider.readLinkSubject")(function* (
341 input: { readonly cwd: string; readonly url: URL },
342 endpoint: string,
343 ) {
344 const result = yield* api
345 .rest({
346 host: input.url.host,
347 operation: "resolveLink",
348 path: endpoint,
349 maxResponseBytes: 1_000_000,
350 })
351 .pipe(
352 Effect.timeout("3 seconds"),
353 Effect.mapError(
354 (cause) =>
355 new SourceControlProviderError({
356 provider: "github",
357 operation: "resolveLink",
358 cwd: input.cwd,
359 detail: "The linked subject could not be read.",
360 cause,
361 }),
362 ),
363 );
364 const subject = yield* decodeLinkSubject(result.body).pipe(
365 Effect.mapError(
366 (cause) =>
367 new SourceControlProviderError({
368 provider: "github",
369 operation: "resolveLink.decode",
370 cwd: input.cwd,
371 detail: "The linked subject could not be read.",
372 cause,
373 }),
374 ),
375 );
376 return { title: subject.title, body: subject.body ?? null };
377 });
378
379 return SourceControlProvider.SourceControlProvider.of({
380 kind: "github",
381 resolveLink: (input) => {
382 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
383 if (input.url.host !== "github.com") return undefined;
384 const match = /^\/([\w.-]+)\/([\w.-]+)\/(?:pull|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
385 input.url.pathname,
386 );
387 if (!match) return undefined;
388 return readLinkSubject(input, `repos/${match[1]}/${match[2]}/issues/${match[3]}`);
389 },
390 listChangeRequests,
391 getChangeRequest: (input) =>
392 github
393 .getPullRequest({
394 ...input,
395 ...(input.context === undefined
396 ? {}
397 : { rateLimitHost: new URL(input.context.provider.baseUrl).host }),
398 })
399 .pipe(
400 Effect.map(toChangeRequest),
401 Effect.mapError(
402 (error) =>
403 new SourceControlProviderError({
404 provider: "github",
405 operation: "getChangeRequest",
406 command: error.command,
407 cwd: input.cwd,
408 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
409 input.reference,
410 ),
411 detail: error.message,
412 cause: error,
413 }),
414 ),
415 ),
416 createChangeRequest: (input) =>
417 github
418 .createPullRequest({
419 cwd: input.cwd,
420 baseBranch: input.baseRefName,
421 headSelector: input.headSelector,
422 title: input.title,
423 bodyFile: input.bodyFile,
424 })
425 .pipe(
426 Effect.mapError(
427 (error) =>
428 new SourceControlProviderError({
429 provider: "github",
430 operation: "createChangeRequest",
431 command: error.command,
432 cwd: input.cwd,
433 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
434 input.headSelector,
435 ),
436 detail: error.message,
437 cause: error,
438 }),
439 ),
440 ),
441 getRepositoryCloneUrls: (input) =>
442 github.getRepositoryCloneUrls(input).pipe(
443 Effect.mapError(
444 (error) =>
445 new SourceControlProviderError({
446 provider: "github",
447 operation: "getRepositoryCloneUrls",
448 command: error.command,
449 cwd: input.cwd,
450 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
451 input.repository,
452 ),
453 detail: error.message,
454 cause: error,
455 }),
456 ),
457 ),
458 createRepository: (input) =>
459 github.createRepository(input).pipe(
460 Effect.mapError(
461 (error) =>
462 new SourceControlProviderError({
463 provider: "github",
464 operation: "createRepository",
465 command: error.command,
466 cwd: input.cwd,
467 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
468 input.repository,
469 ),
470 detail: error.message,
471 cause: error,
472 }),
473 ),
474 ),
475 getDefaultBranch: (input) =>
476 github
477 .getDefaultBranch({
478 ...input,
479 ...(input.context === undefined
480 ? {}
481 : { rateLimitHost: new URL(input.context.provider.baseUrl).host }),
482 })
483 .pipe(
484 Effect.mapError(
485 (error) =>
486 new SourceControlProviderError({
487 provider: "github",
488 operation: "getDefaultBranch",
489 command: error.command,
490 cwd: input.cwd,
491 detail: error.message,
492 cause: error,
493 }),
494 ),
495 ),
496 checkoutChangeRequest: (input) =>
497 github.checkoutPullRequest(input).pipe(
498 Effect.mapError(
499 (error) =>
500 new SourceControlProviderError({
501 provider: "github",
502 operation: "checkoutChangeRequest",
503 command: error.command,
504 cwd: input.cwd,
505 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
506 input.reference,
507 ),
508 detail: error.message,
509 cause: error,
510 }),
511 ),
512 ),
513 });
514});