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

GitLabSourceControlProvider.ts

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