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

GitHubSourceControlProvider.ts

329 lines10.7 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 "@t3tools/contracts";
10import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
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​
24function authTarget(context: SourceControlProvider.SourceControlProviderContext | undefined) {
25 if (context === undefined) return {};
26 const [host, ...path] = normalizeGitRemoteUrl(context.remoteUrl).split("/");
27 return host && path.length >= 2 ? { host, repositories: [path.join("/")] } : {};
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 updatedAt: Option.none(),
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 githubAccounts: authStatus.accounts.flatMap((account) =>
64 account.authenticated && account.tokenSource !== null
65 ? [
66 {
67 host: account.host,
68 login: account.account,
69 tokenSource: account.tokenSource,
70 active: account.active,
71 },
72 ]
73 : [],
74 ),
75 });
76 }
77​
78 const failedAccount = authStatus.accounts.find((entry) => entry.active) ?? authStatus.accounts[0];
79 if (authStatus.parsed) {
80 return providerAuth({
81 status: "unauthenticated",
82 host: failedAccount?.host,
83 detail:
84 failedAccount?.error ??
85 "Run `gh auth login` to authenticate GitHub CLI with an active account.",
86 });
87 }
88​
89 if (input.exitCode !== 0) {
90 return providerAuth({
91 status: "unauthenticated",
92 host,
93 detail: firstSafeAuthLine(output) ?? "Run `gh auth login` to authenticate GitHub CLI.",
94 });
95 }
96​
97 return providerAuth({
98 status: "unknown",
99 host,
100 detail: firstSafeAuthLine(output) ?? "GitHub CLI auth status could not be parsed.",
101 });
103​
104export const discovery = {
105 type: "cli",
106 kind: "github",
107 label: "GitHub",
108 executable: "gh",
109 versionArgs: ["--version"],
110 authArgs: ["auth", "status", "--json", "hosts"],
111 parseAuth: parseGitHubAuth,
112 installHint:
113 "Install the GitHub command-line tool (`gh`) via https://cli.github.com/ or your package manager (for example `brew install gh`).",
114} satisfies SourceControlCliDiscoverySpec;
115​
116export const make = Effect.gen(function* () {
117 const github = yield* GitHubCli.GitHubCli;
118​
119 const listChangeRequests: SourceControlProvider.SourceControlProvider["Service"]["listChangeRequests"] =
120 (input) => {
121 if (input.state === "open") {
122 return github
123 .listOpenPullRequests({
124 cwd: input.cwd,
125 ...authTarget(input.context),
126 headSelector: input.headSelector,
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 const stateArg: ChangeRequestState | "all" = input.state;
149 return github
150 .execute({
151 cwd: input.cwd,
152 ...authTarget(input.context),
153 args: [
154 "pr",
155 "list",
156 "--head",
157 input.headSelector,
158 "--state",
159 stateArg,
160 "--limit",
161 String(input.limit ?? 20),
162 "--json",
163 "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
164 ],
165 })
166 .pipe(
167 Effect.flatMap((result) => {
168 const raw = result.stdout.trim();
169 if (raw.length === 0) {
170 return Effect.succeed([]);
171 }
172 return Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
173 Effect.flatMap((decoded) =>
174 Result.isSuccess(decoded)
175 ? Effect.succeed(
176 decoded.success.map((item) => ({
177 ...toChangeRequest(item),
178 updatedAt: item.updatedAt,
179 })),
180 )
181 : Effect.fail(
182 new GitHubCli.GitHubChangeRequestListDecodeError({
183 command: "gh",
184 cwd: input.cwd,
185 cause: decoded.failure,
186 }),
187 ),
188 ),
189 );
190 }),
191 Effect.mapError(
192 (error) =>
193 new SourceControlProviderError({
194 provider: "github",
195 operation: "listChangeRequests",
196 command: error.command,
197 cwd: input.cwd,
198 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
199 input.headSelector,
200 ),
201 detail: error.detail,
202 cause: error,
203 }),
204 ),
205 );
206 };
207​
208 return SourceControlProvider.SourceControlProvider.of({
209 kind: "github",
210 listChangeRequests,
211 getChangeRequest: (input) =>
212 github.getPullRequest({ ...input, ...authTarget(input.context) }).pipe(
213 Effect.map(toChangeRequest),
214 Effect.mapError(
215 (error) =>
216 new SourceControlProviderError({
217 provider: "github",
218 operation: "getChangeRequest",
219 command: error.command,
220 cwd: input.cwd,
221 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
222 input.reference,
223 ),
224 detail: error.detail,
225 cause: error,
226 }),
227 ),
228 ),
229 createChangeRequest: (input) =>
230 github
231 .createPullRequest({
232 cwd: input.cwd,
233 ...authTarget(input.context),
234 baseBranch: input.baseRefName,
235 headSelector: input.headSelector,
236 title: input.title,
237 bodyFile: input.bodyFile,
238 })
239 .pipe(
240 Effect.mapError(
241 (error) =>
242 new SourceControlProviderError({
243 provider: "github",
244 operation: "createChangeRequest",
245 command: error.command,
246 cwd: input.cwd,
247 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
248 input.headSelector,
249 ),
250 detail: error.detail,
251 cause: error,
252 }),
253 ),
254 ),
255 getRepositoryCloneUrls: (input) =>
256 github
257 .getRepositoryCloneUrls({
258 ...input,
259 ...authTarget(input.context),
260 repository: input.repository,
261 })
262 .pipe(
263 Effect.mapError(
264 (error) =>
265 new SourceControlProviderError({
266 provider: "github",
267 operation: "getRepositoryCloneUrls",
268 command: error.command,
269 cwd: input.cwd,
270 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
271 input.repository,
272 ),
273 detail: error.detail,
274 cause: error,
275 }),
276 ),
277 ),
278 createRepository: (input) =>
279 github.createRepository(input).pipe(
280 Effect.mapError(
281 (error) =>
282 new SourceControlProviderError({
283 provider: "github",
284 operation: "createRepository",
285 command: error.command,
286 cwd: input.cwd,
287 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
288 input.repository,
289 ),
290 detail: error.detail,
291 cause: error,
292 }),
293 ),
294 ),
295 getDefaultBranch: (input) =>
296 github.getDefaultBranch({ ...input, ...authTarget(input.context) }).pipe(
297 Effect.mapError(
298 (error) =>
299 new SourceControlProviderError({
300 provider: "github",
301 operation: "getDefaultBranch",
302 command: error.command,
303 cwd: input.cwd,
304 detail: error.detail,
305 cause: error,
306 }),
307 ),
308 ),
309 checkoutChangeRequest: (input) =>
310 github.checkoutPullRequest({ ...input, ...authTarget(input.context) }).pipe(
311 Effect.mapError(
312 (error) =>
313 new SourceControlProviderError({
314 provider: "github",
315 operation: "checkoutChangeRequest",
316 command: error.command,
317 cwd: input.cwd,
318 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
319 input.reference,
320 ),
321 detail: error.detail,
322 cause: error,
323 }),
324 ),
325 ),
326 });
327});
328​
329export const layer = Layer.effect(SourceControlProvider.SourceControlProvider, make);