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