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

GitLabSourceControlProvider.ts

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