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