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