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

GitHubSourceControlProvider.ts

196 lines6.6 KB

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