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

GitLabSourceControlProvider.ts

319 lines11.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";
6​
7import * as GitLabCli from "./GitLabCli.ts";
8import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
9import {
10 combinedAuthOutput,
11 firstSafeAuthLine,
12 matchFirst,
13 parseCliHost,
14 providerAuth,
15 type SourceControlAuthProbeInput,
16 type SourceControlCliDiscoverySpec,
17 type SourceControlUnknownRemoteRefinementInput,
18} from "@t3tools/source-control-core/server/discovery";
19import { findAuthenticatedGitLabHost, parseGitLabAuthStatusHosts } from "./gitLabAuthStatus.ts";
20​
21const decodeLinkSubject = Schema.decodeUnknownEffect(
22 Schema.fromJsonString(
23 Schema.Struct({ title: Schema.String, description: Schema.NullOr(Schema.String) }),
24 ),
25);
26​
27function toChangeRequest(summary: GitLabCli.GitLabMergeRequestSummary): ChangeRequest {
28 return {
29 provider: SourceControlProviderKind.make("gitlab"),
30 number: summary.number,
31 title: summary.title,
32 url: summary.url,
33 baseRefName: summary.baseRefName,
34 headRefName: summary.headRefName,
35 state: summary.state ?? "open",
36 ...(summary.isDraft === true ? { isDraft: true } : {}),
37 closedAt: summary.closedAt ?? null,
38 mergedAt: summary.mergedAt ?? null,
39 updatedAt: summary.updatedAt ?? Option.none(),
40 ...(summary.isCrossRepository !== undefined
41 ? { isCrossRepository: summary.isCrossRepository }
42 : {}),
43 ...(summary.headRepositoryNameWithOwner !== undefined
44 ? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }
45 : {}),
46 ...(summary.headRepositoryOwnerLogin !== undefined
47 ? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }
48 : {}),
49 };
51​
52function parseGitLabAuth(input: SourceControlAuthProbeInput) {
53 const output = combinedAuthOutput(input);
54 const authenticatedHost = findAuthenticatedGitLabHost(parseGitLabAuthStatusHosts(output));
55 const account =
56 authenticatedHost?.account ??
57 matchFirst(output, [
58 /Logged in to .* as\s+([^\s(]+)/iu,
59 /Logged in to .* account\s+([^\s(]+)/iu,
60 /account:\s*([^\s(]+)/iu,
61 ]);
62 const host = authenticatedHost?.host ?? parseCliHost(output);
63​
64 if (account) {
65 return providerAuth({ status: "authenticated", account, host });
66 }
67​
68 if (input.exitCode !== 0) {
69 return providerAuth({
70 status: "unauthenticated",
71 host,
72 detail: firstSafeAuthLine(output) ?? "Run `glab auth login` to authenticate GitLab CLI.",
73 });
74 }
75​
76 return providerAuth({
77 status: "unknown",
78 host,
79 detail: firstSafeAuthLine(output) ?? "GitLab CLI auth status could not be parsed.",
80 });
82​
83const GITLAB_HOST_NOT_LOGGED_IN_PATTERN =
84 /\bnot (?:been )?authenticated with glab\b|\bno gitlab instances? ha(?:s|ve) been authenticated\b/iu;
85​
86function refineUnknownGitLabRemote(input: SourceControlUnknownRemoteRefinementInput) {
87 const host = input.context.provider.name.toLowerCase();
88 const output = combinedAuthOutput(input.auth);
89 const authenticated = parseGitLabAuthStatusHosts(output).some(
90 (entry) => entry.account !== null && entry.host === host,
91 );
92​
93 if (!authenticated) {
94 return GITLAB_HOST_NOT_LOGGED_IN_PATTERN.test(output) ? null : undefined;
95 }
96​
97 return {
98 kind: SourceControlProviderKind.make("gitlab"),
99 name: "GitLab Self-Hosted",
100 baseUrl: input.context.provider.baseUrl,
101 } as const;
103​
104export const discovery = {
105 type: "cli",
106 kind: SourceControlProviderKind.make("gitlab"),
107 label: "GitLab",
108 executable: "glab",
109 versionArgs: ["--version"],
110 authArgs: ["auth", "status"],
111 // glab matches its configured hosts by exact name, so ask with the remote's own spelling.
112 remoteRefinementArgs: ({ provider, remoteUrl }) => {
113 const at = remoteUrl.toLowerCase().indexOf(provider.name.toLowerCase());
114 const host = at < 0 ? provider.name : remoteUrl.slice(at, at + provider.name.length);
115 return ["auth", "status", "--hostname", host];
116 },
117 parseAuth: parseGitLabAuth,
118 refineUnknownRemote: refineUnknownGitLabRemote,
119 installHint:
120 "Install the GitLab command-line tool (`glab`) from https://gitlab.com/gitlab-org/cli or your package manager (for example `brew install glab`).",
121} satisfies SourceControlCliDiscoverySpec;
122​
123export const make = Effect.gen(function* () {
124 const gitlab = yield* GitLabCli.GitLabCli;
125​
126 const readLinkSubject = Effect.fn("GitLabSourceControlProvider.readLinkSubject")(function* (
127 input: { readonly cwd: string; readonly url: URL },
128 endpoint: string,
129 ) {
130 const result = yield* gitlab
131 .execute({
132 cwd: input.cwd,
133 args: ["api", "--hostname", input.url.host, endpoint],
134 timeoutMs: 3_000,
135 maxOutputBytes: 32_000,
136 })
137 .pipe(
138 Effect.mapError(
139 (cause) =>
140 new SourceControlProviderError({
141 provider: SourceControlProviderKind.make("gitlab"),
142 operation: "resolveLink",
143 cwd: input.cwd,
144 detail: "The linked subject could not be read.",
145 cause,
146 }),
147 ),
148 );
149 const subject = yield* decodeLinkSubject(result.stdout).pipe(
150 Effect.mapError(
151 (cause) =>
152 new SourceControlProviderError({
153 provider: SourceControlProviderKind.make("gitlab"),
154 operation: "resolveLink.decode",
155 cwd: input.cwd,
156 detail: "The linked subject could not be read.",
157 cause,
158 }),
159 ),
160 );
161 return { title: subject.title, body: subject.description };
162 });
163​
164 return SourceControlProvider.SourceControlProvider.of({
165 kind: SourceControlProviderKind.make("gitlab"),
166 resolveLink: (input) => {
167 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
168 if (input.url.host !== "gitlab.com") return undefined;
169 const match = /^\/(.+)\/-\/(merge_requests|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
170 input.url.pathname,
171 );
172 if (!match) return undefined;
173 return readLinkSubject(
174 input,
175 `projects/${encodeURIComponent(match[1]!)}/${match[2]}/${match[3]}`,
176 );
177 },
178 listChangeRequests: (input) => {
179 const source = SourceControlProvider.sourceControlRefFromInput(input);
180 return gitlab
181 .listMergeRequests({
182 cwd: input.cwd,
183 headSelector: input.headSelector,
184 ...(source ? { source } : {}),
185 state: input.state,
186 ...(input.limit !== undefined ? { limit: input.limit } : {}),
187 })
188 .pipe(
189 Effect.map((items) => items.map(toChangeRequest)),
190 Effect.mapError(
191 (error) =>
192 new SourceControlProviderError({
193 provider: SourceControlProviderKind.make("gitlab"),
194 operation: "listChangeRequests",
195 command: error.command,
196 cwd: input.cwd,
197 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
198 input.headSelector,
199 ),
200 detail: error.detail,
201 cause: error,
202 }),
203 ),
204 );
205 },
206 getChangeRequest: (input) =>
207 gitlab.getMergeRequest(input).pipe(
208 Effect.map(toChangeRequest),
209 Effect.mapError(
210 (error) =>
211 new SourceControlProviderError({
212 provider: SourceControlProviderKind.make("gitlab"),
213 operation: "getChangeRequest",
214 command: error.command,
215 cwd: input.cwd,
216 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
217 input.reference,
218 ),
219 detail: error.detail,
220 cause: error,
221 }),
222 ),
223 ),
224 createChangeRequest: (input) => {
225 const source = SourceControlProvider.sourceControlRefFromInput(input);
226 return gitlab
227 .createMergeRequest({
228 cwd: input.cwd,
229 baseBranch: input.baseRefName,
230 headSelector: input.headSelector,
231 ...(source ? { source } : {}),
232 ...(input.target ? { target: input.target } : {}),
233 title: input.title,
234 bodyFile: input.bodyFile,
235 })
236 .pipe(
237 Effect.mapError(
238 (error) =>
239 new SourceControlProviderError({
240 provider: SourceControlProviderKind.make("gitlab"),
241 operation: "createChangeRequest",
242 command: error.command,
243 cwd: input.cwd,
244 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
245 input.headSelector,
246 ),
247 detail: error.detail,
248 cause: error,
249 }),
250 ),
251 );
252 },
253 getRepositoryCloneUrls: (input) =>
254 gitlab.getRepositoryCloneUrls(input).pipe(
255 Effect.mapError(
256 (error) =>
257 new SourceControlProviderError({
258 provider: SourceControlProviderKind.make("gitlab"),
259 operation: "getRepositoryCloneUrls",
260 command: error.command,
261 cwd: input.cwd,
262 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
263 input.repository,
264 ),
265 detail: error.detail,
266 cause: error,
267 }),
268 ),
269 ),
270 createRepository: (input) =>
271 gitlab.createRepository(input).pipe(
272 Effect.mapError(
273 (error) =>
274 new SourceControlProviderError({
275 provider: SourceControlProviderKind.make("gitlab"),
276 operation: "createRepository",
277 command: error.command,
278 cwd: input.cwd,
279 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
280 input.repository,
281 ),
282 detail: error.detail,
283 cause: error,
284 }),
285 ),
286 ),
287 getDefaultBranch: (input) =>
288 gitlab.getDefaultBranch(input).pipe(
289 Effect.mapError(
290 (error) =>
291 new SourceControlProviderError({
292 provider: SourceControlProviderKind.make("gitlab"),
293 operation: "getDefaultBranch",
294 command: error.command,
295 cwd: input.cwd,
296 detail: error.detail,
297 cause: error,
298 }),
299 ),
300 ),
301 checkoutChangeRequest: (input) =>
302 gitlab.checkoutMergeRequest(input).pipe(
303 Effect.mapError(
304 (error) =>
305 new SourceControlProviderError({
306 provider: SourceControlProviderKind.make("gitlab"),
307 operation: "checkoutChangeRequest",
308 command: error.command,
309 cwd: input.cwd,
310 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
311 input.reference,
312 ),
313 detail: error.detail,
314 cause: error,
315 }),
316 ),
317 ),
318 });
319});