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

GitHubSourceControlProvider.ts

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