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

GitLabSourceControlProvider.ts

365 lines13.0 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 { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";
7​
8import * as GitLabCli from "./GitLabCli.ts";
9import * as GitLabChangeRequestTemplate from "./gitLabChangeRequestTemplate.ts";
10import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
11import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
12import {
13 combinedAuthOutput,
14 firstSafeAuthLine,
15 matchFirst,
16 parseCliHost,
17 providerAuth,
18 type SourceControlAuthProbeInput,
19 type SourceControlCliDiscoverySpec,
20 type SourceControlUnknownRemoteRefinementInput,
21} from "@t3tools/source-control-core/server/discovery";
22import { findAuthenticatedGitLabHost, parseGitLabAuthStatusHosts } from "./gitLabAuthStatus.ts";
23​
24const decodeLinkSubject = Schema.decodeUnknownEffect(
25 Schema.fromJsonString(
26 Schema.Struct({ title: Schema.String, description: Schema.NullOr(Schema.String) }),
27 ),
28);
29​
30function toChangeRequest(summary: GitLabCli.GitLabMergeRequestSummary): ChangeRequest {
31 return {
32 provider: SourceControlProviderKind.make("gitlab"),
33 number: summary.number,
34 title: summary.title,
35 url: summary.url,
36 baseRefName: summary.baseRefName,
37 headRefName: summary.headRefName,
38 ...(summary.headSha !== undefined ? { headSha: summary.headSha } : {}),
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 };
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 });
86​
87const GITLAB_HOST_NOT_LOGGED_IN_PATTERN =
88 /\bnot (?:been )?authenticated with glab\b|\bno gitlab instances? ha(?:s|ve) been authenticated\b/iu;
89​
90function refineUnknownGitLabRemote(input: SourceControlUnknownRemoteRefinementInput) {
91 const host = input.context.provider.name.toLowerCase();
92 const output = combinedAuthOutput(input.auth);
93 const authenticated = parseGitLabAuthStatusHosts(output).some(
94 (entry) => entry.account !== null && entry.host === host,
95 );
96​
97 if (!authenticated) {
98 return GITLAB_HOST_NOT_LOGGED_IN_PATTERN.test(output) ? null : undefined;
99 }
100​
101 return {
102 kind: SourceControlProviderKind.make("gitlab"),
103 name: "GitLab Self-Hosted",
104 baseUrl: input.context.provider.baseUrl,
105 } as const;
107​
108function unknownRemoteProvider(remoteUrl: string) {
109 // The shared detector does not recognize userless SCP remotes.
110 const scpHost = /^([^@:/\\\s]{2,}):\/?[^/\s]+(?:\/[^/\s]+)+$/u.exec(remoteUrl.trim())?.[1];
111 const provider = detectSourceControlProviderFromRemoteUrl(
112 scpHost ? `ssh://${scpHost}` : remoteUrl,
113 );
114 return provider?.kind === "unknown" ? provider : null;
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 matches its configured hosts by exact name, so ask with the remote's own 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: ({ cwd, treeish }) =>
210 GitLabChangeRequestTemplate.detect(cwd, treeish, git.execute),
211 refineRepositoryIdentity,
212 resolveLink: (input) => {
213 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
214 if (input.url.host !== "gitlab.com") return undefined;
215 const match = /^\/(.+)\/-\/(merge_requests|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
216 input.url.pathname,
217 );
218 if (!match) return undefined;
219 return readLinkSubject(
220 input,
221 `projects/${encodeURIComponent(match[1]!)}/${match[2]}/${match[3]}`,
222 );
223 },
224 listChangeRequests: (input) => {
225 const source = SourceControlProvider.sourceControlRefFromInput(input);
226 return gitlab
227 .listMergeRequests({
228 cwd: input.cwd,
229 headSelector: input.headSelector,
230 ...(source ? { source } : {}),
231 state: input.state,
232 ...(input.limit !== undefined ? { limit: input.limit } : {}),
233 })
234 .pipe(
235 Effect.map((items) => items.map(toChangeRequest)),
236 Effect.mapError(
237 (error) =>
238 new SourceControlProviderError({
239 provider: SourceControlProviderKind.make("gitlab"),
240 operation: "listChangeRequests",
241 command: error.command,
242 cwd: input.cwd,
243 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
244 input.headSelector,
245 ),
246 detail: error.detail,
247 cause: error,
248 }),
249 ),
250 );
251 },
252 getChangeRequest: (input) =>
253 gitlab.getMergeRequest(input).pipe(
254 Effect.map(toChangeRequest),
255 Effect.mapError(
256 (error) =>
257 new SourceControlProviderError({
258 provider: SourceControlProviderKind.make("gitlab"),
259 operation: "getChangeRequest",
260 command: error.command,
261 cwd: input.cwd,
262 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
263 input.reference,
264 ),
265 detail: error.detail,
266 cause: error,
267 }),
268 ),
269 ),
270 createChangeRequest: (input) => {
271 const source = SourceControlProvider.sourceControlRefFromInput(input);
272 return gitlab
273 .createMergeRequest({
274 cwd: input.cwd,
275 baseBranch: input.baseRefName,
276 headSelector: input.headSelector,
277 ...(source ? { source } : {}),
278 ...(input.target ? { target: input.target } : {}),
279 title: input.title,
280 bodyFile: input.bodyFile,
281 })
282 .pipe(
283 Effect.mapError(
284 (error) =>
285 new SourceControlProviderError({
286 provider: SourceControlProviderKind.make("gitlab"),
287 operation: "createChangeRequest",
288 command: error.command,
289 cwd: input.cwd,
290 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
291 input.headSelector,
292 ),
293 detail: error.detail,
294 cause: error,
295 }),
296 ),
297 );
298 },
299 getRepositoryCloneUrls: (input) =>
300 gitlab.getRepositoryCloneUrls(input).pipe(
301 Effect.mapError(
302 (error) =>
303 new SourceControlProviderError({
304 provider: SourceControlProviderKind.make("gitlab"),
305 operation: "getRepositoryCloneUrls",
306 command: error.command,
307 cwd: input.cwd,
308 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
309 input.repository,
310 ),
311 detail: error.detail,
312 cause: error,
313 }),
314 ),
315 ),
316 createRepository: (input) =>
317 gitlab.createRepository(input).pipe(
318 Effect.mapError(
319 (error) =>
320 new SourceControlProviderError({
321 provider: SourceControlProviderKind.make("gitlab"),
322 operation: "createRepository",
323 command: error.command,
324 cwd: input.cwd,
325 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
326 input.repository,
327 ),
328 detail: error.detail,
329 cause: error,
330 }),
331 ),
332 ),
333 getDefaultBranch: (input) =>
334 gitlab.getDefaultBranch(input).pipe(
335 Effect.mapError(
336 (error) =>
337 new SourceControlProviderError({
338 provider: SourceControlProviderKind.make("gitlab"),
339 operation: "getDefaultBranch",
340 command: error.command,
341 cwd: input.cwd,
342 detail: error.detail,
343 cause: error,
344 }),
345 ),
346 ),
347 checkoutChangeRequest: (input) =>
348 gitlab.checkoutMergeRequest(input).pipe(
349 Effect.mapError(
350 (error) =>
351 new SourceControlProviderError({
352 provider: SourceControlProviderKind.make("gitlab"),
353 operation: "checkoutChangeRequest",
354 command: error.command,
355 cwd: input.cwd,
356 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
357 input.reference,
358 ),
359 detail: error.detail,
360 cause: error,
361 }),
362 ),
363 ),
364 });
365});