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

GitLabSourceControlProvider.ts

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