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 {
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 };
57}
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 });
88}
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;
109}
110
111/** The caller refines only an identity no host recognised, so its remote is on an unknown host. */
112function unknownRemoteProvider(remoteUrl: string) {
113 const remote = parseGitRemoteHost(remoteUrl);
114 return remote === null ? null : unknownHostProvider(remote);
115}
116
117// A glab login confirms a self-hosted GitLab whose hostname does not identify its provider.
118const refineRepositoryIdentity: NonNullable<
119 SourceControlProvider.SourceControlProvider["Service"]["refineRepositoryIdentity"]
120> = Effect.fn("GitLabSourceControlProvider.refineRepositoryIdentity")(function* ({
121 identity,
122 resolveContext,
123}) {
124 if (!identity.rootPath || (identity.provider !== undefined && identity.provider !== "unknown"))
125 return identity;
126 const provider = unknownRemoteProvider(identity.locator.remoteUrl);
127 if (!provider) return identity;
128 const context = yield* resolveContext({
129 cwd: identity.rootPath,
130 context: {
131 provider,
132 remoteName: identity.locator.remoteName,
133 remoteUrl: identity.locator.remoteUrl,
134 },
135 });
136 return context?.provider.kind === "gitlab"
137 ? { ...identity, provider: SourceControlProviderKind.make("gitlab") }
138 : identity;
139});
140
141export const discovery = {
142 type: "cli",
143 kind: SourceControlProviderKind.make("gitlab"),
144 label: "GitLab",
145 executable: "glab",
146 versionArgs: ["--version"],
147 // Without --all, glab 1.79+ checks only the current host unless that is gitlab.com; older
148 // glab lists every host and rejects --all. --all waits on every host, so ask it only after
149 // the current host reports signed out.
150 authArgs: ["auth", "status"],
151 // A probe that names no host covers every host glab has a login for, so it runs without the
152 // environment token; the default host is asked with it last, by name.
153 authRetryArgs: (environment) => [
154 ["auth", "status", "--all"],
155 ...(GitLabCli.hasEnvironmentToken(environment)
156 ? [["auth", "status", "--hostname", GitLabCli.defaultHost(environment)]]
157 : []),
158 ],
159 probeEnv: (args, environment) => {
160 const named = args.indexOf("--hostname");
161 return named !== -1 &&
162 GitLabCli.hostOf(args[named + 1] ?? "") === GitLabCli.defaultHost(environment)
163 ? {}
164 : GitLabCli.WITHOUT_ENVIRONMENT_TOKEN;
165 },
166 // glab host matching requires the remote's exact spelling.
167 remoteRefinementArgs: ({ provider, remoteUrl }) => {
168 const authority = /^[a-z][a-z0-9+.-]*:\/\/([^/]+)/iu.exec(remoteUrl.trim())?.[1];
169 const remoteHost = authority
170 ? authority.slice(authority.lastIndexOf("@") + 1)
171 : remoteUrl.trim().replace(/^[^@:/]+@/u, "");
172 const host = remoteHost.toLowerCase().startsWith(provider.name.toLowerCase())
173 ? remoteHost.slice(0, provider.name.length)
174 : provider.name;
175 return ["auth", "status", "--hostname", host];
176 },
177 parseAuth: parseGitLabAuth,
178 refineUnknownRemote: refineUnknownGitLabRemote,
179 installHint:
180 "Install the GitLab command-line tool (`glab`) from https://gitlab.com/gitlab-org/cli or your package manager (for example `brew install glab`).",
181} satisfies SourceControlCliDiscoverySpec;
182
183export const make = Effect.gen(function* () {
184 const gitlab = yield* GitLabCli.GitLabCli;
185 const { git } = yield* SourceControlHost.SourceControlHost;
186
187 const readLinkSubject = Effect.fn("GitLabSourceControlProvider.readLinkSubject")(function* (
188 input: { readonly cwd: string; readonly url: URL },
189 endpoint: string,
190 ) {
191 const result = yield* gitlab
192 .execute({
193 cwd: input.cwd,
194 callerNamedHost: input.url.host,
195 args: ["api", "--hostname", input.url.host, endpoint],
196 timeoutMs: 3_000,
197 maxOutputBytes: 32_000,
198 })
199 .pipe(
200 Effect.mapError(
201 (cause) =>
202 new SourceControlProviderError({
203 provider: SourceControlProviderKind.make("gitlab"),
204 operation: "resolveLink",
205 cwd: input.cwd,
206 detail: "The linked subject could not be read.",
207 cause,
208 }),
209 ),
210 );
211 const subject = yield* decodeLinkSubject(result.stdout).pipe(
212 Effect.mapError(
213 (cause) =>
214 new SourceControlProviderError({
215 provider: SourceControlProviderKind.make("gitlab"),
216 operation: "resolveLink.decode",
217 cwd: input.cwd,
218 detail: "The linked subject could not be read.",
219 cause,
220 }),
221 ),
222 );
223 return { title: subject.title, body: subject.description };
224 });
225
226 return SourceControlProvider.SourceControlProvider.of({
227 kind: SourceControlProviderKind.make("gitlab"),
228 // GitLab lists fork merge requests by source branch with no owner filter, so read a full page
229 // once per branch. The first selector wins: GitManager puts `owner:branch` first for a fork
230 // head, which tells the list to name fork source projects.
231 headBranchProbe: ({ headSelectors }) => {
232 const byBranch = new Map<string, string>();
233 for (const selector of headSelectors) {
234 const branch = SourceControlProvider.sourceBranch({ headSelector: selector });
235 if (!byBranch.has(branch)) byBranch.set(branch, selector);
236 }
237 return { headSelectors: [...byBranch.values()], limit: 100 };
238 },
239 readChangeRequestTemplate: Effect.fn("GitLabSourceControlProvider.readChangeRequestTemplate")(
240 function ({ cwd, treeish }) {
241 return GitLabChangeRequestTemplate.detect(cwd, treeish, git.execute);
242 },
243 ),
244 refineRepositoryIdentity,
245 resolveLink: (input) => {
246 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
247 if (input.url.host !== "gitlab.com") return undefined;
248 const match = /^\/(.+)\/-\/(merge_requests|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
249 input.url.pathname,
250 );
251 if (!match) return undefined;
252 return readLinkSubject(
253 input,
254 `projects/${encodeURIComponent(match[1]!)}/${match[2]}/${match[3]}`,
255 );
256 },
257 listChangeRequests: Effect.fn("GitLabSourceControlProvider.listChangeRequests")(
258 function (input) {
259 const source = SourceControlProvider.sourceControlRefFromInput(input);
260 return gitlab
261 .listMergeRequests({
262 cwd: input.cwd,
263 headSelector: input.headSelector,
264 ...(source ? { source } : {}),
265 state: input.state,
266 ...(input.limit !== undefined ? { limit: input.limit } : {}),
267 })
268 .pipe(
269 Effect.map((items) => items.map(toChangeRequest)),
270 Effect.mapError(
271 (error) =>
272 new SourceControlProviderError({
273 provider: SourceControlProviderKind.make("gitlab"),
274 operation: "listChangeRequests",
275 command: error.command,
276 cwd: input.cwd,
277 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
278 input.headSelector,
279 ),
280 detail: error.detail,
281 cause: error,
282 }),
283 ),
284 );
285 },
286 ),
287 getChangeRequest: Effect.fn("GitLabSourceControlProvider.getChangeRequest")(function (input) {
288 return gitlab.getMergeRequest(input).pipe(
289 Effect.map(toChangeRequest),
290 Effect.mapError(
291 (error) =>
292 new SourceControlProviderError({
293 provider: SourceControlProviderKind.make("gitlab"),
294 operation: "getChangeRequest",
295 command: error.command,
296 cwd: input.cwd,
297 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
298 input.reference,
299 ),
300 detail: error.detail,
301 cause: error,
302 }),
303 ),
304 );
305 }),
306 createsDraftChangeRequests: true,
307 createChangeRequest: Effect.fn("GitLabSourceControlProvider.createChangeRequest")(
308 function (input) {
309 const source = SourceControlProvider.sourceControlRefFromInput(input);
310 return gitlab
311 .createMergeRequest({
312 cwd: input.cwd,
313 baseBranch: input.baseRefName,
314 headSelector: input.headSelector,
315 ...(source ? { source } : {}),
316 ...(input.target ? { target: input.target } : {}),
317 title: input.title,
318 bodyFile: input.bodyFile,
319 ...(input.draft === true ? { draft: true } : {}),
320 })
321 .pipe(
322 Effect.mapError(
323 (error) =>
324 new SourceControlProviderError({
325 provider: SourceControlProviderKind.make("gitlab"),
326 operation: "createChangeRequest",
327 command: error.command,
328 cwd: input.cwd,
329 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
330 input.headSelector,
331 ),
332 detail: error.detail,
333 cause: error,
334 }),
335 ),
336 );
337 },
338 ),
339 getRepositoryCloneUrls: Effect.fn("GitLabSourceControlProvider.getRepositoryCloneUrls")(
340 function (input) {
341 return gitlab.getRepositoryCloneUrls(input).pipe(
342 Effect.mapError(
343 (error) =>
344 new SourceControlProviderError({
345 provider: SourceControlProviderKind.make("gitlab"),
346 operation: "getRepositoryCloneUrls",
347 command: error.command,
348 cwd: input.cwd,
349 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
350 input.repository,
351 ),
352 detail: error.detail,
353 cause: error,
354 }),
355 ),
356 );
357 },
358 ),
359 createRepository: Effect.fn("GitLabSourceControlProvider.createRepository")(function (input) {
360 return gitlab.createRepository(input).pipe(
361 Effect.mapError(
362 (error) =>
363 new SourceControlProviderError({
364 provider: SourceControlProviderKind.make("gitlab"),
365 operation: "createRepository",
366 command: error.command,
367 cwd: input.cwd,
368 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
369 input.repository,
370 ),
371 detail: error.detail,
372 cause: error,
373 }),
374 ),
375 );
376 }),
377 getDefaultBranch: Effect.fn("GitLabSourceControlProvider.getDefaultBranch")(function (input) {
378 return gitlab.getDefaultBranch(input).pipe(
379 Effect.mapError(
380 (error) =>
381 new SourceControlProviderError({
382 provider: SourceControlProviderKind.make("gitlab"),
383 operation: "getDefaultBranch",
384 command: error.command,
385 cwd: input.cwd,
386 detail: error.detail,
387 cause: error,
388 }),
389 ),
390 );
391 }),
392 checkoutChangeRequest: Effect.fn("GitLabSourceControlProvider.checkoutChangeRequest")(
393 function (input) {
394 return gitlab.checkoutMergeRequest(input).pipe(
395 Effect.mapError(
396 (error) =>
397 new SourceControlProviderError({
398 provider: SourceControlProviderKind.make("gitlab"),
399 operation: "checkoutChangeRequest",
400 command: error.command,
401 cwd: input.cwd,
402 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
403 input.reference,
404 ),
405 detail: error.detail,
406 cause: error,
407 }),
408 ),
409 );
410 },
411 ),
412 });
413});