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