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

GitLabSourceControlProvider.ts

367 lines13.1 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: ({ cwd, treeish }) =>
212 GitLabChangeRequestTemplate.detect(cwd, treeish, git.execute),
213 refineRepositoryIdentity,
214 resolveLink: (input) => {
215 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
216 if (input.url.host !== "gitlab.com") return undefined;
217 const match = /^\/(.+)\/-\/(merge_requests|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
218 input.url.pathname,
219 );
220 if (!match) return undefined;
221 return readLinkSubject(
222 input,
223 `projects/${encodeURIComponent(match[1]!)}/${match[2]}/${match[3]}`,
224 );
225 },
226 listChangeRequests: (input) => {
227 const source = SourceControlProvider.sourceControlRefFromInput(input);
228 return gitlab
229 .listMergeRequests({
230 cwd: input.cwd,
231 headSelector: input.headSelector,
232 ...(source ? { source } : {}),
233 state: input.state,
234 ...(input.limit !== undefined ? { limit: input.limit } : {}),
235 })
236 .pipe(
237 Effect.map((items) => items.map(toChangeRequest)),
238 Effect.mapError(
239 (error) =>
240 new SourceControlProviderError({
241 provider: SourceControlProviderKind.make("gitlab"),
242 operation: "listChangeRequests",
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 getChangeRequest: (input) =>
255 gitlab.getMergeRequest(input).pipe(
256 Effect.map(toChangeRequest),
257 Effect.mapError(
258 (error) =>
259 new SourceControlProviderError({
260 provider: SourceControlProviderKind.make("gitlab"),
261 operation: "getChangeRequest",
262 command: error.command,
263 cwd: input.cwd,
264 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
265 input.reference,
266 ),
267 detail: error.detail,
268 cause: error,
269 }),
270 ),
271 ),
272 createChangeRequest: (input) => {
273 const source = SourceControlProvider.sourceControlRefFromInput(input);
274 return gitlab
275 .createMergeRequest({
276 cwd: input.cwd,
277 baseBranch: input.baseRefName,
278 headSelector: input.headSelector,
279 ...(source ? { source } : {}),
280 ...(input.target ? { target: input.target } : {}),
281 title: input.title,
282 bodyFile: input.bodyFile,
283 })
284 .pipe(
285 Effect.mapError(
286 (error) =>
287 new SourceControlProviderError({
288 provider: SourceControlProviderKind.make("gitlab"),
289 operation: "createChangeRequest",
290 command: error.command,
291 cwd: input.cwd,
292 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
293 input.headSelector,
294 ),
295 detail: error.detail,
296 cause: error,
297 }),
298 ),
299 );
300 },
301 getRepositoryCloneUrls: (input) =>
302 gitlab.getRepositoryCloneUrls(input).pipe(
303 Effect.mapError(
304 (error) =>
305 new SourceControlProviderError({
306 provider: SourceControlProviderKind.make("gitlab"),
307 operation: "getRepositoryCloneUrls",
308 command: error.command,
309 cwd: input.cwd,
310 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
311 input.repository,
312 ),
313 detail: error.detail,
314 cause: error,
315 }),
316 ),
317 ),
318 createRepository: (input) =>
319 gitlab.createRepository(input).pipe(
320 Effect.mapError(
321 (error) =>
322 new SourceControlProviderError({
323 provider: SourceControlProviderKind.make("gitlab"),
324 operation: "createRepository",
325 command: error.command,
326 cwd: input.cwd,
327 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
328 input.repository,
329 ),
330 detail: error.detail,
331 cause: error,
332 }),
333 ),
334 ),
335 getDefaultBranch: (input) =>
336 gitlab.getDefaultBranch(input).pipe(
337 Effect.mapError(
338 (error) =>
339 new SourceControlProviderError({
340 provider: SourceControlProviderKind.make("gitlab"),
341 operation: "getDefaultBranch",
342 command: error.command,
343 cwd: input.cwd,
344 detail: error.detail,
345 cause: error,
346 }),
347 ),
348 ),
349 checkoutChangeRequest: (input) =>
350 gitlab.checkoutMergeRequest(input).pipe(
351 Effect.mapError(
352 (error) =>
353 new SourceControlProviderError({
354 provider: SourceControlProviderKind.make("gitlab"),
355 operation: "checkoutChangeRequest",
356 command: error.command,
357 cwd: input.cwd,
358 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
359 input.reference,
360 ),
361 detail: error.detail,
362 cause: error,
363 }),
364 ),
365 ),
366 });
367});