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

GitLabSourceControlProvider.ts

359 lines12.5 KB

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