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

GitHubSourceControlProvider.ts

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