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

GitLabSourceControlProvider.ts

308 lines9.9 KB

1import * as Schema from "effect/Schema";
2import * as Effect from "effect/Effect";
3import * as Option from "effect/Option";
4import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
5​
6import * as GitLabCli from "./GitLabCli.ts";
7import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
8import {
9 combinedAuthOutput,
10 firstSafeAuthLine,
11 matchFirst,
12 parseCliHost,
13 providerAuth,
14 type SourceControlAuthProbeInput,
15 type SourceControlCliDiscoverySpec,
16 type SourceControlUnknownRemoteRefinementInput,
17} from "@t3tools/source-control-core/server/discovery";
18import { findAuthenticatedGitLabHost, parseGitLabAuthStatusHosts } from "./gitLabAuthStatus.ts";
19​
20const decodeLinkSubject = Schema.decodeUnknownEffect(
21 Schema.fromJsonString(
22 Schema.Struct({ title: Schema.String, description: Schema.NullOr(Schema.String) }),
23 ),
24);
25​
26function toChangeRequest(summary: GitLabCli.GitLabMergeRequestSummary): ChangeRequest {
27 return {
28 provider: "gitlab",
29 number: summary.number,
30 title: summary.title,
31 url: summary.url,
32 baseRefName: summary.baseRefName,
33 headRefName: summary.headRefName,
34 state: summary.state ?? "open",
35 ...(summary.isDraft === true ? { isDraft: true } : {}),
36 closedAt: summary.closedAt ?? null,
37 mergedAt: summary.mergedAt ?? null,
38 updatedAt: summary.updatedAt ?? Option.none(),
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 };
50​
51function parseGitLabAuth(input: SourceControlAuthProbeInput) {
52 const output = combinedAuthOutput(input);
53 const authenticatedHost = findAuthenticatedGitLabHost(parseGitLabAuthStatusHosts(output));
54 const account =
55 authenticatedHost?.account ??
56 matchFirst(output, [
57 /Logged in to .* as\s+([^\s(]+)/iu,
58 /Logged in to .* account\s+([^\s(]+)/iu,
59 /account:\s*([^\s(]+)/iu,
60 ]);
61 const host = authenticatedHost?.host ?? parseCliHost(output);
62​
63 if (account) {
64 return providerAuth({ status: "authenticated", account, host });
65 }
66​
67 if (input.exitCode !== 0) {
68 return providerAuth({
69 status: "unauthenticated",
70 host,
71 detail: firstSafeAuthLine(output) ?? "Run `glab auth login` to authenticate GitLab CLI.",
72 });
73 }
74​
75 return providerAuth({
76 status: "unknown",
77 host,
78 detail: firstSafeAuthLine(output) ?? "GitLab CLI auth status could not be parsed.",
79 });
81​
82function refineUnknownGitLabRemote(input: SourceControlUnknownRemoteRefinementInput) {
83 const host = input.context.provider.name.toLowerCase();
84 const authenticated = parseGitLabAuthStatusHosts(combinedAuthOutput(input.auth)).some(
85 (entry) => entry.account !== null && entry.host === host,
86 );
87​
88 if (!authenticated) {
89 return null;
90 }
91​
92 return {
93 kind: "gitlab",
94 name: "GitLab Self-Hosted",
95 baseUrl: input.context.provider.baseUrl,
96 } as const;
98​
99export const discovery = {
100 type: "cli",
101 kind: "gitlab",
102 label: "GitLab",
103 executable: "glab",
104 versionArgs: ["--version"],
105 authArgs: ["auth", "status"],
106 parseAuth: parseGitLabAuth,
107 refineUnknownRemote: refineUnknownGitLabRemote,
108 installHint:
109 "Install the GitLab command-line tool (`glab`) from https://gitlab.com/gitlab-org/cli or your package manager (for example `brew install glab`).",
110} satisfies SourceControlCliDiscoverySpec;
111​
112export const make = Effect.gen(function* () {
113 const gitlab = yield* GitLabCli.GitLabCli;
114​
115 const readLinkSubject = Effect.fn("GitLabSourceControlProvider.readLinkSubject")(function* (
116 input: { readonly cwd: string; readonly url: URL },
117 endpoint: string,
118 ) {
119 const result = yield* gitlab
120 .execute({
121 cwd: input.cwd,
122 args: ["api", "--hostname", input.url.host, endpoint],
123 timeoutMs: 3_000,
124 maxOutputBytes: 32_000,
125 })
126 .pipe(
127 Effect.mapError(
128 (cause) =>
129 new SourceControlProviderError({
130 provider: "gitlab",
131 operation: "resolveLink",
132 cwd: input.cwd,
133 detail: "The linked subject could not be read.",
134 cause,
135 }),
136 ),
137 );
138 const subject = yield* decodeLinkSubject(result.stdout).pipe(
139 Effect.mapError(
140 (cause) =>
141 new SourceControlProviderError({
142 provider: "gitlab",
143 operation: "resolveLink.decode",
144 cwd: input.cwd,
145 detail: "The linked subject could not be read.",
146 cause,
147 }),
148 ),
149 );
150 return { title: subject.title, body: subject.description };
151 });
152​
153 return SourceControlProvider.SourceControlProvider.of({
154 kind: "gitlab",
155 resolveLink: (input) => {
156 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
157 if (input.url.host !== "gitlab.com") return undefined;
158 const match = /^\/(.+)\/-\/(merge_requests|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
159 input.url.pathname,
160 );
161 if (!match) return undefined;
162 return readLinkSubject(
163 input,
164 `projects/${encodeURIComponent(match[1]!)}/${match[2]}/${match[3]}`,
165 );
166 },
167 listChangeRequests: (input) => {
168 const source = SourceControlProvider.sourceControlRefFromInput(input);
169 return gitlab
170 .listMergeRequests({
171 cwd: input.cwd,
172 headSelector: input.headSelector,
173 ...(source ? { source } : {}),
174 state: input.state,
175 ...(input.limit !== undefined ? { limit: input.limit } : {}),
176 })
177 .pipe(
178 Effect.map((items) => items.map(toChangeRequest)),
179 Effect.mapError(
180 (error) =>
181 new SourceControlProviderError({
182 provider: "gitlab",
183 operation: "listChangeRequests",
184 command: error.command,
185 cwd: input.cwd,
186 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
187 input.headSelector,
188 ),
189 detail: error.detail,
190 cause: error,
191 }),
192 ),
193 );
194 },
195 getChangeRequest: (input) =>
196 gitlab.getMergeRequest(input).pipe(
197 Effect.map(toChangeRequest),
198 Effect.mapError(
199 (error) =>
200 new SourceControlProviderError({
201 provider: "gitlab",
202 operation: "getChangeRequest",
203 command: error.command,
204 cwd: input.cwd,
205 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
206 input.reference,
207 ),
208 detail: error.detail,
209 cause: error,
210 }),
211 ),
212 ),
213 createChangeRequest: (input) => {
214 const source = SourceControlProvider.sourceControlRefFromInput(input);
215 return gitlab
216 .createMergeRequest({
217 cwd: input.cwd,
218 baseBranch: input.baseRefName,
219 headSelector: input.headSelector,
220 ...(source ? { source } : {}),
221 ...(input.target ? { target: input.target } : {}),
222 title: input.title,
223 bodyFile: input.bodyFile,
224 })
225 .pipe(
226 Effect.mapError(
227 (error) =>
228 new SourceControlProviderError({
229 provider: "gitlab",
230 operation: "createChangeRequest",
231 command: error.command,
232 cwd: input.cwd,
233 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
234 input.headSelector,
235 ),
236 detail: error.detail,
237 cause: error,
238 }),
239 ),
240 );
241 },
242 getRepositoryCloneUrls: (input) =>
243 gitlab.getRepositoryCloneUrls(input).pipe(
244 Effect.mapError(
245 (error) =>
246 new SourceControlProviderError({
247 provider: "gitlab",
248 operation: "getRepositoryCloneUrls",
249 command: error.command,
250 cwd: input.cwd,
251 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
252 input.repository,
253 ),
254 detail: error.detail,
255 cause: error,
256 }),
257 ),
258 ),
259 createRepository: (input) =>
260 gitlab.createRepository(input).pipe(
261 Effect.mapError(
262 (error) =>
263 new SourceControlProviderError({
264 provider: "gitlab",
265 operation: "createRepository",
266 command: error.command,
267 cwd: input.cwd,
268 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
269 input.repository,
270 ),
271 detail: error.detail,
272 cause: error,
273 }),
274 ),
275 ),
276 getDefaultBranch: (input) =>
277 gitlab.getDefaultBranch(input).pipe(
278 Effect.mapError(
279 (error) =>
280 new SourceControlProviderError({
281 provider: "gitlab",
282 operation: "getDefaultBranch",
283 command: error.command,
284 cwd: input.cwd,
285 detail: error.detail,
286 cause: error,
287 }),
288 ),
289 ),
290 checkoutChangeRequest: (input) =>
291 gitlab.checkoutMergeRequest(input).pipe(
292 Effect.mapError(
293 (error) =>
294 new SourceControlProviderError({
295 provider: "gitlab",
296 operation: "checkoutChangeRequest",
297 command: error.command,
298 cwd: input.cwd,
299 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
300 input.reference,
301 ),
302 detail: error.detail,
303 cause: error,
304 }),
305 ),
306 ),
307 });
308});