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

GitHubSourceControlProvider.ts

215 lines7.3 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 * as Schema from "effect/Schema";
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 * as GitHubPullRequests from "./gitHubPullRequests.ts";
15import * as SourceControlProvider from "./SourceControlProvider.ts";
16import * as SourceControlProviderDiscovery from "./SourceControlProviderDiscovery.ts";
17const isSourceControlProviderError = Schema.is(SourceControlProviderError);
18​
19function providerError(
20 operation: string,
21 cause: GitHubCli.GitHubCliError,
22): SourceControlProviderError {
23 return new SourceControlProviderError({
24 provider: "github",
25 operation,
26 detail: cause.detail,
27 cause,
28 });
30​
31function toChangeRequest(summary: GitHubCli.GitHubPullRequestSummary): ChangeRequest {
32 return {
33 provider: "github",
34 number: summary.number,
35 title: summary.title,
36 url: summary.url,
37 baseRefName: summary.baseRefName,
38 headRefName: summary.headRefName,
39 state: summary.state ?? "open",
40 updatedAt: Option.none(),
41 ...(summary.isCrossRepository !== undefined
42 ? { isCrossRepository: summary.isCrossRepository }
43 : {}),
44 ...(summary.headRepositoryNameWithOwner !== undefined
45 ? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }
46 : {}),
47 ...(summary.headRepositoryOwnerLogin !== undefined
48 ? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }
49 : {}),
50 };
52​
53function parseGitHubAuth(input: SourceControlProviderDiscovery.SourceControlAuthProbeInput) {
54 const output = SourceControlProviderDiscovery.combinedAuthOutput(input);
55 const authStatus = parseGitHubAuthStatus(input.stdout);
56 const authenticatedAccount = findAuthenticatedGitHubAccount(authStatus.accounts);
57 const host = authenticatedAccount?.host;
58​
59 if (authenticatedAccount) {
60 return SourceControlProviderDiscovery.providerAuth({
61 status: "authenticated",
62 account: authenticatedAccount.account,
63 host,
64 });
65 }
66​
67 const failedAccount = authStatus.accounts.find((entry) => entry.active) ?? authStatus.accounts[0];
68 if (authStatus.parsed) {
69 return SourceControlProviderDiscovery.providerAuth({
70 status: "unauthenticated",
71 host: failedAccount?.host,
72 detail:
73 failedAccount?.error ??
74 "Run `gh auth login` to authenticate GitHub CLI with an active account.",
75 });
76 }
77​
78 if (input.exitCode !== 0) {
79 return SourceControlProviderDiscovery.providerAuth({
80 status: "unauthenticated",
81 host,
82 detail:
83 SourceControlProviderDiscovery.firstSafeAuthLine(output) ??
84 "Run `gh auth login` to authenticate GitHub CLI.",
85 });
86 }
87​
88 return SourceControlProviderDiscovery.providerAuth({
89 status: "unknown",
90 host,
91 detail:
92 SourceControlProviderDiscovery.firstSafeAuthLine(output) ??
93 "GitHub CLI auth status could not be parsed.",
94 });
96​
97export const discovery = {
98 type: "cli",
99 kind: "github",
100 label: "GitHub",
101 executable: "gh",
102 versionArgs: ["--version"],
103 authArgs: ["auth", "status", "--json", "hosts"],
104 parseAuth: parseGitHubAuth,
105 installHint:
106 "Install the GitHub command-line tool (`gh`) via https://cli.github.com/ or your package manager (for example `brew install gh`).",
107} satisfies SourceControlProviderDiscovery.SourceControlCliDiscoverySpec;
108​
109export const make = Effect.fn("makeGitHubSourceControlProvider")(function* () {
110 const github = yield* GitHubCli.GitHubCli;
111​
112 const listChangeRequests: SourceControlProvider.SourceControlProviderShape["listChangeRequests"] =
113 (input) => {
114 if (input.state === "open") {
115 return github
116 .listOpenPullRequests({
117 cwd: input.cwd,
118 headSelector: input.headSelector,
119 ...(input.limit !== undefined ? { limit: input.limit } : {}),
120 })
121 .pipe(
122 Effect.map((items) => items.map(toChangeRequest)),
123 Effect.mapError((error) => providerError("listChangeRequests", error)),
124 );
125 }
126​
127 const stateArg: ChangeRequestState | "all" = input.state;
128 return github
129 .execute({
130 cwd: input.cwd,
131 args: [
132 "pr",
133 "list",
134 "--head",
135 input.headSelector,
136 "--state",
137 stateArg,
138 "--limit",
139 String(input.limit ?? 20),
140 "--json",
141 "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
142 ],
143 })
144 .pipe(
145 Effect.flatMap((result) => {
146 const raw = result.stdout.trim();
147 if (raw.length === 0) {
148 return Effect.succeed([]);
149 }
150 return Effect.sync(() => GitHubPullRequests.decodeGitHubPullRequestListJson(raw)).pipe(
151 Effect.flatMap((decoded) =>
152 Result.isSuccess(decoded)
153 ? Effect.succeed(
154 decoded.success.map((item) => ({
155 ...toChangeRequest(item),
156 updatedAt: item.updatedAt,
157 })),
158 )
159 : Effect.fail(
160 new SourceControlProviderError({
161 provider: "github",
162 operation: "listChangeRequests",
163 detail: "GitHub CLI returned invalid change request JSON.",
164 cause: decoded.failure,
165 }),
166 ),
167 ),
168 );
169 }),
170 Effect.mapError((error) =>
171 isSourceControlProviderError(error)
172 ? error
173 : providerError("listChangeRequests", error),
174 ),
175 );
176 };
177​
178 return SourceControlProvider.SourceControlProvider.of({
179 kind: "github",
180 listChangeRequests,
181 getChangeRequest: (input) =>
182 github.getPullRequest(input).pipe(
183 Effect.map(toChangeRequest),
184 Effect.mapError((error) => providerError("getChangeRequest", error)),
185 ),
186 createChangeRequest: (input) =>
187 github
188 .createPullRequest({
189 cwd: input.cwd,
190 baseBranch: input.baseRefName,
191 headSelector: input.headSelector,
192 title: input.title,
193 bodyFile: input.bodyFile,
194 })
195 .pipe(Effect.mapError((error) => providerError("createChangeRequest", error))),
196 getRepositoryCloneUrls: (input) =>
197 github
198 .getRepositoryCloneUrls(input)
199 .pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
200 createRepository: (input) =>
201 github
202 .createRepository(input)
203 .pipe(Effect.mapError((error) => providerError("createRepository", error))),
204 getDefaultBranch: (input) =>
205 github
206 .getDefaultBranch(input)
207 .pipe(Effect.mapError((error) => providerError("getDefaultBranch", error))),
208 checkoutChangeRequest: (input) =>
209 github
210 .checkoutPullRequest(input)
211 .pipe(Effect.mapError((error) => providerError("checkoutChangeRequest", error))),
212 });
213});
214​
215export const layer = Layer.effect(SourceControlProvider.SourceControlProvider, make());