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

GitHubSourceControlProvider.ts

323 lines10.5 KB

1import * as DateTime from "effect/DateTime";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
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​
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 updatedAt:
34 summary.updatedAt === undefined
35 ? Option.none()
36 : Option.some(DateTime.makeUnsafe(summary.updatedAt)),
37 ...(summary.isCrossRepository !== undefined
38 ? { isCrossRepository: summary.isCrossRepository }
39 : {}),
40 ...(summary.headRepositoryNameWithOwner !== undefined
41 ? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }
42 : {}),
43 ...(summary.headRepositoryOwnerLogin !== undefined
44 ? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }
45 : {}),
46 };
48​
49function parseGitHubAuth(input: SourceControlAuthProbeInput) {
50 const output = combinedAuthOutput(input);
51 const authStatus = parseGitHubAuthStatus(input.stdout);
52 const authenticatedAccount = findAuthenticatedGitHubAccount(authStatus.accounts);
53 const host = authenticatedAccount?.host;
54​
55 if (authenticatedAccount) {
56 return providerAuth({
57 status: "authenticated",
58 account: authenticatedAccount.account,
59 host,
60 });
61 }
62​
63 const failedAccount = authStatus.accounts.find((entry) => entry.active) ?? authStatus.accounts[0];
64 if (authStatus.parsed) {
65 return providerAuth({
66 status: "unauthenticated",
67 host: failedAccount?.host,
68 detail:
69 failedAccount?.error ??
70 "Run `gh auth login` to authenticate GitHub CLI with an active account.",
71 });
72 }
73​
74 // gh gained `auth status --json` in 2.81.0. Older versions reject the flag and exit
75 // non-zero, which reads exactly like a signed-out CLI. Name the real problem instead.
76 if (input.exitCode !== 0 && output.includes("unknown flag: --json")) {
77 return providerAuth({
78 status: "unknown",
79 detail:
80 "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.",
81 });
82 }
83​
84 if (input.exitCode !== 0) {
85 return providerAuth({
86 status: "unauthenticated",
87 host,
88 detail: firstSafeAuthLine(output) ?? "Run `gh auth login` to authenticate GitHub CLI.",
89 });
90 }
91​
92 return providerAuth({
93 status: "unknown",
94 host,
95 detail: firstSafeAuthLine(output) ?? "GitHub CLI auth status could not be parsed.",
96 });
98​
99export const discovery = {
100 type: "cli",
101 kind: "github",
102 label: "GitHub",
103 executable: "gh",
104 versionArgs: ["--version"],
105 authArgs: ["auth", "status", "--json", "hosts"],
106 parseAuth: parseGitHubAuth,
107 installHint:
108 "Install the GitHub command-line tool (`gh`) via https://cli.github.com/ or your package manager (for example `brew install gh`).",
109} satisfies SourceControlCliDiscoverySpec;
110​
111export const make = Effect.gen(function* () {
112 const github = yield* GitHubCli.GitHubCli;
113​
114 const listChangeRequests: SourceControlProvider.SourceControlProvider["Service"]["listChangeRequests"] =
115 (input) => {
116 if (input.state === "open") {
117 return github
118 .listOpenPullRequests({
119 cwd: input.cwd,
120 headSelector: input.headSelector,
121 ...(input.limit !== undefined ? { limit: input.limit } : {}),
122 })
123 .pipe(
124 Effect.map((items) => items.map(toChangeRequest)),
125 Effect.mapError(
126 (error) =>
127 new SourceControlProviderError({
128 provider: "github",
129 operation: "listChangeRequests",
130 command: error.command,
131 cwd: input.cwd,
132 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
133 input.headSelector,
134 ),
135 detail: error.detail,
136 cause: error,
137 }),
138 ),
139 );
140 }
141​
142 const stateArg: ChangeRequestState | "all" = input.state;
143 return github
144 .execute({
145 cwd: input.cwd,
146 args: [
147 "pr",
148 "list",
149 "--head",
150 input.headSelector,
151 "--state",
152 stateArg,
153 "--limit",
154 String(input.limit ?? 20),
155 "--json",
156 "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
157 ],
158 })
159 .pipe(
160 Effect.flatMap((result) => {
161 const raw = result.stdout.trim();
162 if (raw.length === 0) {
163 return Effect.succeed([]);
164 }
165 return Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
166 Effect.flatMap((decoded) =>
167 Result.isSuccess(decoded)
168 ? Effect.succeed(
169 decoded.success.map((item) => {
170 const { updatedAt, ...summary } = item;
171 return {
172 ...toChangeRequest({
173 ...summary,
174 ...(Option.isSome(updatedAt)
175 ? { updatedAt: DateTime.formatIso(updatedAt.value) }
176 : {}),
177 }),
178 updatedAt,
179 };
180 }),
181 )
182 : Effect.fail(
183 new GitHubCli.GitHubChangeRequestListDecodeError({
184 command: "gh",
185 cwd: input.cwd,
186 cause: decoded.failure,
187 }),
188 ),
189 ),
190 );
191 }),
192 Effect.mapError(
193 (error) =>
194 new SourceControlProviderError({
195 provider: "github",
196 operation: "listChangeRequests",
197 command: error.command,
198 cwd: input.cwd,
199 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
200 input.headSelector,
201 ),
202 detail: error.detail,
203 cause: error,
204 }),
205 ),
206 );
207 };
208​
209 return SourceControlProvider.SourceControlProvider.of({
210 kind: "github",
211 listChangeRequests,
212 getChangeRequest: (input) =>
213 github.getPullRequest(input).pipe(
214 Effect.map(toChangeRequest),
215 Effect.mapError(
216 (error) =>
217 new SourceControlProviderError({
218 provider: "github",
219 operation: "getChangeRequest",
220 command: error.command,
221 cwd: input.cwd,
222 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
223 input.reference,
224 ),
225 detail: error.detail,
226 cause: error,
227 }),
228 ),
229 ),
230 createChangeRequest: (input) =>
231 github
232 .createPullRequest({
233 cwd: input.cwd,
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.getRepositoryCloneUrls(input).pipe(
257 Effect.mapError(
258 (error) =>
259 new SourceControlProviderError({
260 provider: "github",
261 operation: "getRepositoryCloneUrls",
262 command: error.command,
263 cwd: input.cwd,
264 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
265 input.repository,
266 ),
267 detail: error.detail,
268 cause: error,
269 }),
270 ),
271 ),
272 createRepository: (input) =>
273 github.createRepository(input).pipe(
274 Effect.mapError(
275 (error) =>
276 new SourceControlProviderError({
277 provider: "github",
278 operation: "createRepository",
279 command: error.command,
280 cwd: input.cwd,
281 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
282 input.repository,
283 ),
284 detail: error.detail,
285 cause: error,
286 }),
287 ),
288 ),
289 getDefaultBranch: (input) =>
290 github.getDefaultBranch(input).pipe(
291 Effect.mapError(
292 (error) =>
293 new SourceControlProviderError({
294 provider: "github",
295 operation: "getDefaultBranch",
296 command: error.command,
297 cwd: input.cwd,
298 detail: error.detail,
299 cause: error,
300 }),
301 ),
302 ),
303 checkoutChangeRequest: (input) =>
304 github.checkoutPullRequest(input).pipe(
305 Effect.mapError(
306 (error) =>
307 new SourceControlProviderError({
308 provider: "github",
309 operation: "checkoutChangeRequest",
310 command: error.command,
311 cwd: input.cwd,
312 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
313 input.reference,
314 ),
315 detail: error.detail,
316 cause: error,
317 }),
318 ),
319 ),
320 });
321});
322​
323export const layer = Layer.effect(SourceControlProvider.SourceControlProvider, make);