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.limit !== undefined ? { limit: input.limit } : {}),
131 })
132 .pipe(
133 Effect.map((items) => items.map(toChangeRequest)),
134 Effect.mapError(
135 (error) =>
136 new SourceControlProviderError({
137 provider: "github",
138 operation: "listChangeRequests",
139 command: error.command,
140 cwd: input.cwd,
141 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
142 input.headSelector,
143 ),
144 detail: error.detail,
145 cause: error,
146 }),
147 ),
148 );
149 }
150
151 const stateArg: ChangeRequestState | "all" = input.state;
152 return github
153 .execute({
154 cwd: input.cwd,
155 args: [
156 "pr",
157 "list",
158 "--head",
159 input.headSelector,
160 "--state",
161 stateArg,
162 "--limit",
163 String(input.limit ?? 20),
164 "--json",
165 "number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
166 ],
167 })
168 .pipe(
169 Effect.flatMap((result) => {
170 const raw = result.stdout.trim();
171 if (raw.length === 0) {
172 return Effect.succeed([]);
173 }
174 return Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
175 Effect.flatMap((decoded) =>
176 Result.isSuccess(decoded)
177 ? Effect.succeed(
178 decoded.success.map((item) => {
179 const { updatedAt, ...summary } = item;
180 return {
181 ...toChangeRequest({
182 ...summary,
183 ...(Option.isSome(updatedAt)
184 ? { updatedAt: DateTime.formatIso(updatedAt.value) }
185 : {}),
186 }),
187 updatedAt,
188 };
189 }),
190 )
191 : Effect.fail(
192 new GitHubCli.GitHubChangeRequestListDecodeError({
193 command: "gh",
194 cwd: input.cwd,
195 cause: decoded.failure,
196 }),
197 ),
198 ),
199 );
200 }),
201 Effect.mapError(
202 (error) =>
203 new SourceControlProviderError({
204 provider: "github",
205 operation: "listChangeRequests",
206 command: error.command,
207 cwd: input.cwd,
208 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
209 input.headSelector,
210 ),
211 detail: error.detail,
212 cause: error,
213 }),
214 ),
215 );
216 };
217
218 const readLinkSubject = Effect.fn("GitHubSourceControlProvider.readLinkSubject")(function* (
219 input: { readonly cwd: string; readonly url: URL },
220 endpoint: string,
221 ) {
222 const result = yield* github
223 .execute({
224 cwd: input.cwd,
225 args: ["api", "--hostname", input.url.host, endpoint, "--jq", "{title, body}"],
226 env: { GH_PROMPT_DISABLED: "1" },
227 timeoutMs: 3_000,
228 maxOutputBytes: 32_000,
229 })
230 .pipe(
231 Effect.mapError(
232 (cause) =>
233 new SourceControlProviderError({
234 provider: "github",
235 operation: "resolveLink",
236 cwd: input.cwd,
237 detail: "The linked subject could not be read.",
238 cause,
239 }),
240 ),
241 );
242 const subject = yield* decodeLinkSubject(result.stdout).pipe(
243 Effect.mapError(
244 (cause) =>
245 new SourceControlProviderError({
246 provider: "github",
247 operation: "resolveLink.decode",
248 cwd: input.cwd,
249 detail: "The linked subject could not be read.",
250 cause,
251 }),
252 ),
253 );
254 return { title: subject.title, body: subject.body };
255 });
256
257 return SourceControlProvider.SourceControlProvider.of({
258 kind: "github",
259 resolveLink: (input) => {
260 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
261 if (input.url.host !== "github.com") return undefined;
262 const match = /^\/([\w.-]+)\/([\w.-]+)\/(?:pull|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
263 input.url.pathname,
264 );
265 if (!match) return undefined;
266 return readLinkSubject(input, `repos/${match[1]}/${match[2]}/issues/${match[3]}`);
267 },
268 listChangeRequests,
269 getChangeRequest: (input) =>
270 github.getPullRequest(input).pipe(
271 Effect.map(toChangeRequest),
272 Effect.mapError(
273 (error) =>
274 new SourceControlProviderError({
275 provider: "github",
276 operation: "getChangeRequest",
277 command: error.command,
278 cwd: input.cwd,
279 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
280 input.reference,
281 ),
282 detail: error.detail,
283 cause: error,
284 }),
285 ),
286 ),
287 createChangeRequest: (input) =>
288 github
289 .createPullRequest({
290 cwd: input.cwd,
291 baseBranch: input.baseRefName,
292 headSelector: input.headSelector,
293 title: input.title,
294 bodyFile: input.bodyFile,
295 })
296 .pipe(
297 Effect.mapError(
298 (error) =>
299 new SourceControlProviderError({
300 provider: "github",
301 operation: "createChangeRequest",
302 command: error.command,
303 cwd: input.cwd,
304 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
305 input.headSelector,
306 ),
307 detail: error.detail,
308 cause: error,
309 }),
310 ),
311 ),
312 getRepositoryCloneUrls: (input) =>
313 github.getRepositoryCloneUrls(input).pipe(
314 Effect.mapError(
315 (error) =>
316 new SourceControlProviderError({
317 provider: "github",
318 operation: "getRepositoryCloneUrls",
319 command: error.command,
320 cwd: input.cwd,
321 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
322 input.repository,
323 ),
324 detail: error.detail,
325 cause: error,
326 }),
327 ),
328 ),
329 createRepository: (input) =>
330 github.createRepository(input).pipe(
331 Effect.mapError(
332 (error) =>
333 new SourceControlProviderError({
334 provider: "github",
335 operation: "createRepository",
336 command: error.command,
337 cwd: input.cwd,
338 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
339 input.repository,
340 ),
341 detail: error.detail,
342 cause: error,
343 }),
344 ),
345 ),
346 getDefaultBranch: (input) =>
347 github.getDefaultBranch(input).pipe(
348 Effect.mapError(
349 (error) =>
350 new SourceControlProviderError({
351 provider: "github",
352 operation: "getDefaultBranch",
353 command: error.command,
354 cwd: input.cwd,
355 detail: error.detail,
356 cause: error,
357 }),
358 ),
359 ),
360 checkoutChangeRequest: (input) =>
361 github.checkoutPullRequest(input).pipe(
362 Effect.mapError(
363 (error) =>
364 new SourceControlProviderError({
365 provider: "github",
366 operation: "checkoutChangeRequest",
367 command: error.command,
368 cwd: input.cwd,
369 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
370 input.reference,
371 ),
372 detail: error.detail,
373 cause: error,
374 }),
375 ),
376 ),
377 });
378});