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