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 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} from "./SourceControlProviderDiscovery.ts";
23
24const decodeLinkSubject = Schema.decodeUnknownEffect(
25 Schema.fromJsonString(
26 Schema.Struct({ title: Schema.String, body: Schema.NullOr(Schema.String) }),
27 ),
28);
29
30function toChangeRequest(summary: GitHubCli.GitHubPullRequestSummary): ChangeRequest {
31 return {
32 provider: "github",
33 number: summary.number,
34 title: summary.title,
35 url: summary.url,
36 baseRefName: summary.baseRefName,
37 headRefName: summary.headRefName,
38 state: summary.state ?? "open",
39 ...(summary.isDraft === true ? { isDraft: true } : {}),
40 closedAt: summary.closedAt ?? null,
41 mergedAt: summary.mergedAt ?? null,
42 updatedAt:
43 summary.updatedAt === undefined
44 ? Option.none()
45 : Option.some(DateTime.makeUnsafe(summary.updatedAt)),
46 ...(summary.isCrossRepository !== undefined
47 ? { isCrossRepository: summary.isCrossRepository }
48 : {}),
49 ...(summary.headRepositoryNameWithOwner !== undefined
50 ? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }
51 : {}),
52 ...(summary.headRepositoryOwnerLogin !== undefined
53 ? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }
54 : {}),
55 };
56}
57
58function parseGitHubAuth(input: SourceControlAuthProbeInput) {
59 const output = combinedAuthOutput(input);
60 const authStatus = parseGitHubAuthStatus(input.stdout);
61 const authenticatedAccount = findAuthenticatedGitHubAccount(authStatus.accounts);
62 const host = authenticatedAccount?.host;
63
64 if (authenticatedAccount) {
65 return providerAuth({
66 status: "authenticated",
67 account: authenticatedAccount.account,
68 host,
69 });
70 }
71
72 const failedAccount = authStatus.accounts.find((entry) => entry.active) ?? authStatus.accounts[0];
73 if (authStatus.parsed) {
74 return providerAuth({
75 status: "unauthenticated",
76 host: failedAccount?.host,
77 detail:
78 failedAccount?.error ??
79 "Run `gh auth login` to authenticate GitHub CLI with an active account.",
80 });
81 }
82
83 // gh gained `auth status --json` in 2.81.0. Older versions reject the flag and exit
84 // non-zero, which reads exactly like a signed-out CLI. Name the real problem instead.
85 if (input.exitCode !== 0 && output.includes("unknown flag: --json")) {
86 return providerAuth({
87 status: "unknown",
88 detail:
89 "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.",
90 });
91 }
92
93 if (input.exitCode !== 0) {
94 return providerAuth({
95 status: "unauthenticated",
96 host,
97 detail: firstSafeAuthLine(output) ?? "Run `gh auth login` to authenticate GitHub CLI.",
98 });
99 }
100
101 return providerAuth({
102 status: "unknown",
103 host,
104 detail: firstSafeAuthLine(output) ?? "GitHub CLI auth status could not be parsed.",
105 });
106}
107
108export const discovery = {
109 type: "cli",
110 kind: "github",
111 label: "GitHub",
112 executable: "gh",
113 versionArgs: ["--version"],
114 authArgs: ["auth", "status", "--json", "hosts"],
115 parseAuth: parseGitHubAuth,
116 installHint:
117 "Install the GitHub command-line tool (`gh`) via https://cli.github.com/ or your package manager (for example `brew install gh`).",
118} satisfies SourceControlCliDiscoverySpec;
119
120export const make = Effect.gen(function* () {
121 const github = yield* GitHubCli.GitHubCli;
122
123 const listChangeRequests: SourceControlProvider.SourceControlProvider["Service"]["listChangeRequests"] =
124 (input) => {
125 if (input.state === "open") {
126 return github
127 .listOpenPullRequests({
128 cwd: input.cwd,
129 headSelector: input.headSelector,
130 ...(input.context === undefined
131 ? {}
132 : { rateLimitHost: new URL(input.context.provider.baseUrl).host }),
133 ...(input.limit !== undefined ? { limit: input.limit } : {}),
134 })
135 .pipe(
136 Effect.map((items) => items.map(toChangeRequest)),
137 Effect.mapError(
138 (error) =>
139 new SourceControlProviderError({
140 provider: "github",
141 operation: "listChangeRequests",
142 command: error.command,
143 cwd: input.cwd,
144 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
145 input.headSelector,
146 ),
147 detail: error.detail,
148 cause: error,
149 }),
150 ),
151 );
152 }
153
154 const stateArg: ChangeRequestState | "all" = input.state;
155 return github
156 .execute({
157 cwd: input.cwd,
158 ...(input.context === undefined
159 ? {}
160 : { rateLimitHost: new URL(input.context.provider.baseUrl).host }),
161 args: [
162 "pr",
163 "list",
164 "--head",
165 input.headSelector,
166 "--state",
167 stateArg,
168 "--limit",
169 String(input.limit ?? 20),
170 "--json",
171 "number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
172 ],
173 })
174 .pipe(
175 Effect.flatMap((result) => {
176 const raw = result.stdout.trim();
177 if (raw.length === 0) {
178 return Effect.succeed([]);
179 }
180 return Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
181 Effect.flatMap((decoded) =>
182 Result.isSuccess(decoded)
183 ? Effect.succeed(
184 decoded.success.map((item) => {
185 const { updatedAt, ...summary } = item;
186 return {
187 ...toChangeRequest({
188 ...summary,
189 ...(Option.isSome(updatedAt)
190 ? { updatedAt: DateTime.formatIso(updatedAt.value) }
191 : {}),
192 }),
193 updatedAt,
194 };
195 }),
196 )
197 : Effect.fail(
198 new GitHubCli.GitHubChangeRequestListDecodeError({
199 command: "gh",
200 cwd: input.cwd,
201 cause: decoded.failure,
202 }),
203 ),
204 ),
205 );
206 }),
207 Effect.mapError(
208 (error) =>
209 new SourceControlProviderError({
210 provider: "github",
211 operation: "listChangeRequests",
212 command: error.command,
213 cwd: input.cwd,
214 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
215 input.headSelector,
216 ),
217 detail: error.detail,
218 cause: error,
219 }),
220 ),
221 );
222 };
223
224 const readLinkSubject = Effect.fn("GitHubSourceControlProvider.readLinkSubject")(function* (
225 input: { readonly cwd: string; readonly url: URL },
226 endpoint: string,
227 ) {
228 const result = yield* github
229 .execute({
230 cwd: input.cwd,
231 args: ["api", "--hostname", input.url.host, endpoint, "--jq", "{title, body}"],
232 env: { GH_PROMPT_DISABLED: "1" },
233 timeoutMs: 3_000,
234 maxOutputBytes: 32_000,
235 })
236 .pipe(
237 Effect.mapError(
238 (cause) =>
239 new SourceControlProviderError({
240 provider: "github",
241 operation: "resolveLink",
242 cwd: input.cwd,
243 detail: "The linked subject could not be read.",
244 cause,
245 }),
246 ),
247 );
248 const subject = yield* decodeLinkSubject(result.stdout).pipe(
249 Effect.mapError(
250 (cause) =>
251 new SourceControlProviderError({
252 provider: "github",
253 operation: "resolveLink.decode",
254 cwd: input.cwd,
255 detail: "The linked subject could not be read.",
256 cause,
257 }),
258 ),
259 );
260 return { title: subject.title, body: subject.body };
261 });
262
263 return SourceControlProvider.SourceControlProvider.of({
264 kind: "github",
265 resolveLink: (input) => {
266 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
267 if (input.url.host !== "github.com") return undefined;
268 const match = /^\/([\w.-]+)\/([\w.-]+)\/(?:pull|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
269 input.url.pathname,
270 );
271 if (!match) return undefined;
272 return readLinkSubject(input, `repos/${match[1]}/${match[2]}/issues/${match[3]}`);
273 },
274 listChangeRequests,
275 getChangeRequest: (input) =>
276 github
277 .getPullRequest({
278 ...input,
279 ...(input.context === undefined
280 ? {}
281 : { rateLimitHost: new URL(input.context.provider.baseUrl).host }),
282 })
283 .pipe(
284 Effect.map(toChangeRequest),
285 Effect.mapError(
286 (error) =>
287 new SourceControlProviderError({
288 provider: "github",
289 operation: "getChangeRequest",
290 command: error.command,
291 cwd: input.cwd,
292 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
293 input.reference,
294 ),
295 detail: error.detail,
296 cause: error,
297 }),
298 ),
299 ),
300 createChangeRequest: (input) =>
301 github
302 .createPullRequest({
303 cwd: input.cwd,
304 baseBranch: input.baseRefName,
305 headSelector: input.headSelector,
306 title: input.title,
307 bodyFile: input.bodyFile,
308 })
309 .pipe(
310 Effect.mapError(
311 (error) =>
312 new SourceControlProviderError({
313 provider: "github",
314 operation: "createChangeRequest",
315 command: error.command,
316 cwd: input.cwd,
317 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
318 input.headSelector,
319 ),
320 detail: error.detail,
321 cause: error,
322 }),
323 ),
324 ),
325 getRepositoryCloneUrls: (input) =>
326 github.getRepositoryCloneUrls(input).pipe(
327 Effect.mapError(
328 (error) =>
329 new SourceControlProviderError({
330 provider: "github",
331 operation: "getRepositoryCloneUrls",
332 command: error.command,
333 cwd: input.cwd,
334 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
335 input.repository,
336 ),
337 detail: error.detail,
338 cause: error,
339 }),
340 ),
341 ),
342 createRepository: (input) =>
343 github.createRepository(input).pipe(
344 Effect.mapError(
345 (error) =>
346 new SourceControlProviderError({
347 provider: "github",
348 operation: "createRepository",
349 command: error.command,
350 cwd: input.cwd,
351 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
352 input.repository,
353 ),
354 detail: error.detail,
355 cause: error,
356 }),
357 ),
358 ),
359 getDefaultBranch: (input) =>
360 github
361 .getDefaultBranch({
362 ...input,
363 ...(input.context === undefined
364 ? {}
365 : { rateLimitHost: new URL(input.context.provider.baseUrl).host }),
366 })
367 .pipe(
368 Effect.mapError(
369 (error) =>
370 new SourceControlProviderError({
371 provider: "github",
372 operation: "getDefaultBranch",
373 command: error.command,
374 cwd: input.cwd,
375 detail: error.detail,
376 cause: error,
377 }),
378 ),
379 ),
380 checkoutChangeRequest: (input) =>
381 github.checkoutPullRequest(input).pipe(
382 Effect.mapError(
383 (error) =>
384 new SourceControlProviderError({
385 provider: "github",
386 operation: "checkoutChangeRequest",
387 command: error.command,
388 cwd: input.cwd,
389 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
390 input.reference,
391 ),
392 detail: error.detail,
393 cause: error,
394 }),
395 ),
396 ),
397 });
398});