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