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

GitHubSourceControlProvider.ts

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