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

GitHubSourceControlProvider.ts

311 lines10.0 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";
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 // gh gained `auth status --json` in 2.81.0. Older versions reject the flag and exit
71 // non-zero, which reads exactly like a signed-out CLI. Name the real problem instead.
72 if (input.exitCode !== 0 && output.includes("unknown flag: --json")) {
73 return providerAuth({
74 status: "unknown",
75 detail:
76 "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.",
77 });
78 }
79​
80 if (input.exitCode !== 0) {
81 return providerAuth({
82 status: "unauthenticated",
83 host,
84 detail: firstSafeAuthLine(output) ?? "Run `gh auth login` to authenticate GitHub CLI.",
85 });
86 }
87​
88 return providerAuth({
89 status: "unknown",
90 host,
91 detail: firstSafeAuthLine(output) ?? "GitHub CLI auth status could not be parsed.",
92 });
94​
95export const discovery = {
96 type: "cli",
97 kind: "github",
98 label: "GitHub",
99 executable: "gh",
100 versionArgs: ["--version"],
101 authArgs: ["auth", "status", "--json", "hosts"],
102 parseAuth: parseGitHubAuth,
103 installHint:
104 "Install the GitHub command-line tool (`gh`) via https://cli.github.com/ or your package manager (for example `brew install gh`).",
105} satisfies SourceControlCliDiscoverySpec;
106​
107export const make = Effect.gen(function* () {
108 const github = yield* GitHubCli.GitHubCli;
109​
110 const listChangeRequests: SourceControlProvider.SourceControlProvider["Service"]["listChangeRequests"] =
111 (input) => {
112 if (input.state === "open") {
113 return github
114 .listOpenPullRequests({
115 cwd: input.cwd,
116 headSelector: input.headSelector,
117 ...(input.limit !== undefined ? { limit: input.limit } : {}),
118 })
119 .pipe(
120 Effect.map((items) => items.map(toChangeRequest)),
121 Effect.mapError(
122 (error) =>
123 new SourceControlProviderError({
124 provider: "github",
125 operation: "listChangeRequests",
126 command: error.command,
127 cwd: input.cwd,
128 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
129 input.headSelector,
130 ),
131 detail: error.detail,
132 cause: error,
133 }),
134 ),
135 );
136 }
137​
138 const stateArg: ChangeRequestState | "all" = input.state;
139 return github
140 .execute({
141 cwd: input.cwd,
142 args: [
143 "pr",
144 "list",
145 "--head",
146 input.headSelector,
147 "--state",
148 stateArg,
149 "--limit",
150 String(input.limit ?? 20),
151 "--json",
152 "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
153 ],
154 })
155 .pipe(
156 Effect.flatMap((result) => {
157 const raw = result.stdout.trim();
158 if (raw.length === 0) {
159 return Effect.succeed([]);
160 }
161 return Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
162 Effect.flatMap((decoded) =>
163 Result.isSuccess(decoded)
164 ? Effect.succeed(
165 decoded.success.map((item) => ({
166 ...toChangeRequest(item),
167 updatedAt: item.updatedAt,
168 })),
169 )
170 : Effect.fail(
171 new GitHubCli.GitHubChangeRequestListDecodeError({
172 command: "gh",
173 cwd: input.cwd,
174 cause: decoded.failure,
175 }),
176 ),
177 ),
178 );
179 }),
180 Effect.mapError(
181 (error) =>
182 new SourceControlProviderError({
183 provider: "github",
184 operation: "listChangeRequests",
185 command: error.command,
186 cwd: input.cwd,
187 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
188 input.headSelector,
189 ),
190 detail: error.detail,
191 cause: error,
192 }),
193 ),
194 );
195 };
196​
197 return SourceControlProvider.SourceControlProvider.of({
198 kind: "github",
199 listChangeRequests,
200 getChangeRequest: (input) =>
201 github.getPullRequest(input).pipe(
202 Effect.map(toChangeRequest),
203 Effect.mapError(
204 (error) =>
205 new SourceControlProviderError({
206 provider: "github",
207 operation: "getChangeRequest",
208 command: error.command,
209 cwd: input.cwd,
210 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
211 input.reference,
212 ),
213 detail: error.detail,
214 cause: error,
215 }),
216 ),
217 ),
218 createChangeRequest: (input) =>
219 github
220 .createPullRequest({
221 cwd: input.cwd,
222 baseBranch: input.baseRefName,
223 headSelector: input.headSelector,
224 title: input.title,
225 bodyFile: input.bodyFile,
226 })
227 .pipe(
228 Effect.mapError(
229 (error) =>
230 new SourceControlProviderError({
231 provider: "github",
232 operation: "createChangeRequest",
233 command: error.command,
234 cwd: input.cwd,
235 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
236 input.headSelector,
237 ),
238 detail: error.detail,
239 cause: error,
240 }),
241 ),
242 ),
243 getRepositoryCloneUrls: (input) =>
244 github.getRepositoryCloneUrls(input).pipe(
245 Effect.mapError(
246 (error) =>
247 new SourceControlProviderError({
248 provider: "github",
249 operation: "getRepositoryCloneUrls",
250 command: error.command,
251 cwd: input.cwd,
252 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
253 input.repository,
254 ),
255 detail: error.detail,
256 cause: error,
257 }),
258 ),
259 ),
260 createRepository: (input) =>
261 github.createRepository(input).pipe(
262 Effect.mapError(
263 (error) =>
264 new SourceControlProviderError({
265 provider: "github",
266 operation: "createRepository",
267 command: error.command,
268 cwd: input.cwd,
269 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
270 input.repository,
271 ),
272 detail: error.detail,
273 cause: error,
274 }),
275 ),
276 ),
277 getDefaultBranch: (input) =>
278 github.getDefaultBranch(input).pipe(
279 Effect.mapError(
280 (error) =>
281 new SourceControlProviderError({
282 provider: "github",
283 operation: "getDefaultBranch",
284 command: error.command,
285 cwd: input.cwd,
286 detail: error.detail,
287 cause: error,
288 }),
289 ),
290 ),
291 checkoutChangeRequest: (input) =>
292 github.checkoutPullRequest(input).pipe(
293 Effect.mapError(
294 (error) =>
295 new SourceControlProviderError({
296 provider: "github",
297 operation: "checkoutChangeRequest",
298 command: error.command,
299 cwd: input.cwd,
300 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
301 input.reference,
302 ),
303 detail: error.detail,
304 cause: error,
305 }),
306 ),
307 ),
308 });
309});
310​
311export const layer = Layer.effect(SourceControlProvider.SourceControlProvider, make);