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

GitLabSourceControlProvider.ts

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