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

GitHubSourceControlProvider.ts

301 lines9.6 KB

1import * as Effect from "effect/Effect";
2import * as Layer from "effect/Layer";
3import * as Option from "effect/Option";
4import * as Result from "effect/Result";
5import {
6 SourceControlProviderError,
7 type ChangeRequest,
8 type ChangeRequestState,
9} from "@v12/contracts";
10​
11import * as GitHubCli from "./GitHubCli.ts";
12import { findAuthenticatedGitHubAccount, parseGitHubAuthStatus } from "./gitHubAuthStatus.ts";
13import { decodeGitHubPullRequestListJson } from "./gitHubPullRequests.ts";
14import * as SourceControlProvider from "./SourceControlProvider.ts";
15import {
16 combinedAuthOutput,
17 firstSafeAuthLine,
18 providerAuth,
19 type SourceControlAuthProbeInput,
20 type SourceControlCliDiscoverySpec,
21} from "./SourceControlProviderDiscovery.ts";
22​
23function toChangeRequest(summary: GitHubCli.GitHubPullRequestSummary): ChangeRequest {
24 return {
25 provider: "github",
26 number: summary.number,
27 title: summary.title,
28 url: summary.url,
29 baseRefName: summary.baseRefName,
30 headRefName: summary.headRefName,
31 state: summary.state ?? "open",
32 updatedAt: Option.none(),
33 ...(summary.isCrossRepository !== undefined
34 ? { isCrossRepository: summary.isCrossRepository }
35 : {}),
36 ...(summary.headRepositoryNameWithOwner !== undefined
37 ? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }
38 : {}),
39 ...(summary.headRepositoryOwnerLogin !== undefined
40 ? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }
41 : {}),
42 };
44​
45function parseGitHubAuth(input: SourceControlAuthProbeInput) {
46 const output = combinedAuthOutput(input);
47 const authStatus = parseGitHubAuthStatus(input.stdout);
48 const authenticatedAccount = findAuthenticatedGitHubAccount(authStatus.accounts);
49 const host = authenticatedAccount?.host;
50​
51 if (authenticatedAccount) {
52 return providerAuth({
53 status: "authenticated",
54 account: authenticatedAccount.account,
55 host,
56 });
57 }
58​
59 const failedAccount = authStatus.accounts.find((entry) => entry.active) ?? authStatus.accounts[0];
60 if (authStatus.parsed) {
61 return providerAuth({
62 status: "unauthenticated",
63 host: failedAccount?.host,
64 detail:
65 failedAccount?.error ??
66 "Run `gh auth login` to authenticate GitHub CLI with an active account.",
67 });
68 }
69​
70 if (input.exitCode !== 0) {
71 return providerAuth({
72 status: "unauthenticated",
73 host,
74 detail: firstSafeAuthLine(output) ?? "Run `gh auth login` to authenticate GitHub CLI.",
75 });
76 }
77​
78 return providerAuth({
79 status: "unknown",
80 host,
81 detail: firstSafeAuthLine(output) ?? "GitHub CLI auth status could not be parsed.",
82 });
84​
85export const discovery = {
86 type: "cli",
87 kind: "github",
88 label: "GitHub",
89 executable: "gh",
90 versionArgs: ["--version"],
91 authArgs: ["auth", "status", "--json", "hosts"],
92 parseAuth: parseGitHubAuth,
93 installHint:
94 "Install the GitHub command-line tool (`gh`) via https://cli.github.com/ or your package manager (for example `brew install gh`).",
95} satisfies SourceControlCliDiscoverySpec;
96​
97export const make = Effect.gen(function* () {
98 const github = yield* GitHubCli.GitHubCli;
99​
100 const listChangeRequests: SourceControlProvider.SourceControlProvider["Service"]["listChangeRequests"] =
101 (input) => {
102 if (input.state === "open") {
103 return github
104 .listOpenPullRequests({
105 cwd: input.cwd,
106 headSelector: input.headSelector,
107 ...(input.limit !== undefined ? { limit: input.limit } : {}),
108 })
109 .pipe(
110 Effect.map((items) => items.map(toChangeRequest)),
111 Effect.mapError(
112 (error) =>
113 new SourceControlProviderError({
114 provider: "github",
115 operation: "listChangeRequests",
116 command: error.command,
117 cwd: input.cwd,
118 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
119 input.headSelector,
120 ),
121 detail: error.detail,
122 cause: error,
123 }),
124 ),
125 );
126 }
127​
128 const stateArg: ChangeRequestState | "all" = input.state;
129 return github
130 .execute({
131 cwd: input.cwd,
132 args: [
133 "pr",
134 "list",
135 "--head",
136 input.headSelector,
137 "--state",
138 stateArg,
139 "--limit",
140 String(input.limit ?? 20),
141 "--json",
142 "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
143 ],
144 })
145 .pipe(
146 Effect.flatMap((result) => {
147 const raw = result.stdout.trim();
148 if (raw.length === 0) {
149 return Effect.succeed([]);
150 }
151 return Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
152 Effect.flatMap((decoded) =>
153 Result.isSuccess(decoded)
154 ? Effect.succeed(
155 decoded.success.map((item) => ({
156 ...toChangeRequest(item),
157 updatedAt: item.updatedAt,
158 })),
159 )
160 : Effect.fail(
161 new GitHubCli.GitHubChangeRequestListDecodeError({
162 command: "gh",
163 cwd: input.cwd,
164 cause: decoded.failure,
165 }),
166 ),
167 ),
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 return SourceControlProvider.SourceControlProvider.of({
188 kind: "github",
189 listChangeRequests,
190 getChangeRequest: (input) =>
191 github.getPullRequest(input).pipe(
192 Effect.map(toChangeRequest),
193 Effect.mapError(
194 (error) =>
195 new SourceControlProviderError({
196 provider: "github",
197 operation: "getChangeRequest",
198 command: error.command,
199 cwd: input.cwd,
200 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
201 input.reference,
202 ),
203 detail: error.detail,
204 cause: error,
205 }),
206 ),
207 ),
208 createChangeRequest: (input) =>
209 github
210 .createPullRequest({
211 cwd: input.cwd,
212 baseBranch: input.baseRefName,
213 headSelector: input.headSelector,
214 title: input.title,
215 bodyFile: input.bodyFile,
216 })
217 .pipe(
218 Effect.mapError(
219 (error) =>
220 new SourceControlProviderError({
221 provider: "github",
222 operation: "createChangeRequest",
223 command: error.command,
224 cwd: input.cwd,
225 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
226 input.headSelector,
227 ),
228 detail: error.detail,
229 cause: error,
230 }),
231 ),
232 ),
233 getRepositoryCloneUrls: (input) =>
234 github.getRepositoryCloneUrls(input).pipe(
235 Effect.mapError(
236 (error) =>
237 new SourceControlProviderError({
238 provider: "github",
239 operation: "getRepositoryCloneUrls",
240 command: error.command,
241 cwd: input.cwd,
242 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
243 input.repository,
244 ),
245 detail: error.detail,
246 cause: error,
247 }),
248 ),
249 ),
250 createRepository: (input) =>
251 github.createRepository(input).pipe(
252 Effect.mapError(
253 (error) =>
254 new SourceControlProviderError({
255 provider: "github",
256 operation: "createRepository",
257 command: error.command,
258 cwd: input.cwd,
259 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
260 input.repository,
261 ),
262 detail: error.detail,
263 cause: error,
264 }),
265 ),
266 ),
267 getDefaultBranch: (input) =>
268 github.getDefaultBranch(input).pipe(
269 Effect.mapError(
270 (error) =>
271 new SourceControlProviderError({
272 provider: "github",
273 operation: "getDefaultBranch",
274 command: error.command,
275 cwd: input.cwd,
276 detail: error.detail,
277 cause: error,
278 }),
279 ),
280 ),
281 checkoutChangeRequest: (input) =>
282 github.checkoutPullRequest(input).pipe(
283 Effect.mapError(
284 (error) =>
285 new SourceControlProviderError({
286 provider: "github",
287 operation: "checkoutChangeRequest",
288 command: error.command,
289 cwd: input.cwd,
290 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
291 input.reference,
292 ),
293 detail: error.detail,
294 cause: error,
295 }),
296 ),
297 ),
298 });
299});
300​
301export const layer = Layer.effect(SourceControlProvider.SourceControlProvider, make);