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

GitLabCli.ts

442 lines13.7 KB

1import { Context, Effect, Layer, Option, Result, Schema, SchemaIssue, type DateTime } from "effect";
2​
3import { TrimmedNonEmptyString, type SourceControlRepositoryVisibility } from "@t3tools/contracts";
4​
5import * as VcsProcess from "../vcs/VcsProcess.ts";
6import * as GitLabMergeRequests from "./gitLabMergeRequests.ts";
7import type * as SourceControlProvider from "./SourceControlProvider.ts";
8​
9const DEFAULT_TIMEOUT_MS = 30_000;
10​
11export class GitLabCliError extends Schema.TaggedErrorClass<GitLabCliError>()("GitLabCliError", {
12 operation: Schema.String,
13 detail: Schema.String,
14 cause: Schema.optional(Schema.Defect),
15}) {
16 override get message(): string {
17 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
18 }
20​
21export interface GitLabMergeRequestSummary {
22 readonly number: number;
23 readonly title: string;
24 readonly url: string;
25 readonly baseRefName: string;
26 readonly headRefName: string;
27 readonly state?: "open" | "closed" | "merged";
28 readonly updatedAt?: Option.Option<DateTime.Utc>;
29 readonly isCrossRepository?: boolean;
30 readonly headRepositoryNameWithOwner?: string | null;
31 readonly headRepositoryOwnerLogin?: string | null;
33​
34export interface GitLabRepositoryCloneUrls {
35 readonly nameWithOwner: string;
36 readonly url: string;
37 readonly sshUrl: string;
39​
40export interface GitLabCliShape {
41 readonly execute: (input: {
42 readonly cwd: string;
43 readonly args: ReadonlyArray<string>;
44 readonly timeoutMs?: number;
45 }) => Effect.Effect<VcsProcess.VcsProcessOutput, GitLabCliError>;
46​
47 readonly listMergeRequests: (input: {
48 readonly cwd: string;
49 readonly headSelector: string;
50 readonly source?: SourceControlProvider.SourceControlRefSelector;
51 readonly state: "open" | "closed" | "merged" | "all";
52 readonly limit?: number;
53 }) => Effect.Effect<ReadonlyArray<GitLabMergeRequestSummary>, GitLabCliError>;
54​
55 readonly getMergeRequest: (input: {
56 readonly cwd: string;
57 readonly reference: string;
58 }) => Effect.Effect<GitLabMergeRequestSummary, GitLabCliError>;
59​
60 readonly getRepositoryCloneUrls: (input: {
61 readonly cwd: string;
62 readonly repository: string;
63 }) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
64​
65 readonly createRepository: (input: {
66 readonly cwd: string;
67 readonly repository: string;
68 readonly visibility: SourceControlRepositoryVisibility;
69 }) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
70​
71 readonly createMergeRequest: (input: {
72 readonly cwd: string;
73 readonly baseBranch: string;
74 readonly headSelector: string;
75 readonly source?: SourceControlProvider.SourceControlRefSelector;
76 readonly target?: SourceControlProvider.SourceControlRefSelector;
77 readonly title: string;
78 readonly bodyFile: string;
79 }) => Effect.Effect<void, GitLabCliError>;
80​
81 readonly getDefaultBranch: (input: {
82 readonly cwd: string;
83 }) => Effect.Effect<string | null, GitLabCliError>;
84​
85 readonly checkoutMergeRequest: (input: {
86 readonly cwd: string;
87 readonly reference: string;
88 readonly force?: boolean;
89 }) => Effect.Effect<void, GitLabCliError>;
91​
92export class GitLabCli extends Context.Service<GitLabCli, GitLabCliShape>()(
93 "t3/source-control/GitLabCli",
94) {}
95​
96function isVcsProcessSpawnError(error: unknown): boolean {
97 return (
98 typeof error === "object" &&
99 error !== null &&
100 "_tag" in error &&
101 error._tag === "VcsProcessSpawnError"
102 );
104​
105function normalizeGitLabCliError(operation: "execute" | "stdout", error: unknown): GitLabCliError {
106 if (error instanceof Error) {
107 if (error.message.includes("Command not found: glab") || isVcsProcessSpawnError(error)) {
108 return new GitLabCliError({
109 operation,
110 detail: "GitLab CLI (`glab`) is required but not available on PATH.",
111 cause: error,
112 });
113 }
114​
115 const lower = error.message.toLowerCase();
116 if (
117 lower.includes("authentication failed") ||
118 lower.includes("not logged in") ||
119 lower.includes("glab auth login") ||
120 lower.includes("token")
121 ) {
122 return new GitLabCliError({
123 operation,
124 detail: "GitLab CLI is not authenticated. Run `glab auth login` and retry.",
125 cause: error,
126 });
127 }
128​
129 if (
130 lower.includes("merge request not found") ||
131 lower.includes("not found") ||
132 lower.includes("404")
133 ) {
134 return new GitLabCliError({
135 operation,
136 detail: "Merge request not found. Check the MR number or URL and try again.",
137 cause: error,
138 });
139 }
140​
141 return new GitLabCliError({
142 operation,
143 detail: `GitLab CLI command failed: ${error.message}`,
144 cause: error,
145 });
146 }
147​
148 return new GitLabCliError({
149 operation,
150 detail: "GitLab CLI command failed.",
151 cause: error,
152 });
154​
155const RawGitLabRepositoryCloneUrlsSchema = Schema.Struct({
156 path_with_namespace: TrimmedNonEmptyString,
157 web_url: TrimmedNonEmptyString,
158 http_url_to_repo: TrimmedNonEmptyString,
159 ssh_url_to_repo: TrimmedNonEmptyString,
160});
161​
162const RawGitLabDefaultBranchSchema = Schema.Struct({
163 default_branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
164});
165​
166const RawGitLabNamespaceSchema = Schema.Struct({
167 id: Schema.Number,
168});
169​
170function normalizeRepositoryCloneUrls(
171 raw: Schema.Schema.Type<typeof RawGitLabRepositoryCloneUrlsSchema>,
172): GitLabRepositoryCloneUrls {
173 return {
174 nameWithOwner: raw.path_with_namespace,
175 url: raw.web_url,
176 sshUrl: raw.ssh_url_to_repo,
177 };
179​
180function decodeGitLabJson<S extends Schema.Top>(
181 raw: string,
182 schema: S,
183 operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
184 invalidDetail: string,
185): Effect.Effect<S["Type"], GitLabCliError, S["DecodingServices"]> {
186 return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
187 Effect.mapError(
188 (error) =>
189 new GitLabCliError({
190 operation,
191 detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
192 cause: error,
193 }),
194 ),
195 );
197​
198function stateArgs(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
199 switch (state) {
200 case "open":
201 return [];
202 case "closed":
203 return ["--closed"];
204 case "merged":
205 return ["--merged"];
206 case "all":
207 return ["--all"];
208 }
210​
211function normalizeHeadSelector(headSelector: string): string {
212 const trimmed = headSelector.trim();
213 const ownerBranch = /^[^:]+:(.+)$/.exec(trimmed);
214 return ownerBranch?.[1]?.trim() || trimmed;
216​
217function sourceRefName(input: {
218 readonly headSelector: string;
219 readonly source?: SourceControlProvider.SourceControlRefSelector;
220}): string {
221 return input.source?.refName ?? normalizeHeadSelector(input.headSelector);
223​
224function sourceProjectIdentifier(
225 source: SourceControlProvider.SourceControlRefSelector | undefined,
226): string | null {
227 return source?.repository ?? source?.owner ?? null;
229​
230function toSummaryWithOptionalUpdatedAt(
231 record: GitLabMergeRequestSummary & {
232 readonly updatedAt: Option.Option<DateTime.Utc>;
233 },
234): GitLabMergeRequestSummary {
235 const { updatedAt, ...summary } = record;
236 return Option.isSome(updatedAt) ? { ...summary, updatedAt } : summary;
238​
239function parseRepositoryPath(repository: string): {
240 readonly namespacePath: string | null;
241 readonly projectPath: string;
242} {
243 const parts = repository
244 .split("/")
245 .map((part) => part.trim())
246 .filter((part) => part.length > 0);
247 const projectPath = parts.at(-1) ?? repository.trim();
248 const namespacePath = parts.length > 1 ? parts.slice(0, -1).join("/") : null;
249 return { namespacePath, projectPath };
251​
252export const make = Effect.fn("makeGitLabCli")(function* () {
253 const process = yield* VcsProcess.VcsProcess;
254​
255 const execute: GitLabCliShape["execute"] = (input) =>
256 process
257 .run({
258 operation: "GitLabCli.execute",
259 command: "glab",
260 args: input.args,
261 cwd: input.cwd,
262 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
263 })
264 .pipe(Effect.mapError((error) => normalizeGitLabCliError("execute", error)));
265​
266 return GitLabCli.of({
267 execute,
268 listMergeRequests: (input) =>
269 execute({
270 cwd: input.cwd,
271 args: [
272 "mr",
273 "list",
274 "--source-branch",
275 sourceRefName(input),
276 ...stateArgs(input.state),
277 "--per-page",
278 String(input.limit ?? 20),
279 "--output",
280 "json",
281 ],
282 }).pipe(
283 Effect.map((result) => result.stdout.trim()),
284 Effect.flatMap((raw) =>
285 raw.length === 0
286 ? Effect.succeed([])
287 : Effect.sync(() => GitLabMergeRequests.decodeGitLabMergeRequestListJson(raw)).pipe(
288 Effect.flatMap((decoded) => {
289 if (!Result.isSuccess(decoded)) {
290 return Effect.fail(
291 new GitLabCliError({
292 operation: "listMergeRequests",
293 detail: `GitLab CLI returned invalid MR list JSON: ${GitLabMergeRequests.formatGitLabJsonDecodeError(decoded.failure)}`,
294 cause: decoded.failure,
295 }),
296 );
297 }
298​
299 return Effect.succeed(decoded.success.map(toSummaryWithOptionalUpdatedAt));
300 }),
301 ),
302 ),
303 ),
304 getMergeRequest: (input) =>
305 execute({
306 cwd: input.cwd,
307 args: ["mr", "view", input.reference, "--output", "json"],
308 }).pipe(
309 Effect.map((result) => result.stdout.trim()),
310 Effect.flatMap((raw) =>
311 Effect.sync(() => GitLabMergeRequests.decodeGitLabMergeRequestJson(raw)).pipe(
312 Effect.flatMap((decoded) => {
313 if (!Result.isSuccess(decoded)) {
314 return Effect.fail(
315 new GitLabCliError({
316 operation: "getMergeRequest",
317 detail: `GitLab CLI returned invalid merge request JSON: ${GitLabMergeRequests.formatGitLabJsonDecodeError(decoded.failure)}`,
318 cause: decoded.failure,
319 }),
320 );
321 }
322​
323 return Effect.succeed(toSummaryWithOptionalUpdatedAt(decoded.success));
324 }),
325 ),
326 ),
327 ),
328 getRepositoryCloneUrls: (input) =>
329 execute({
330 cwd: input.cwd,
331 args: ["api", `projects/${encodeURIComponent(input.repository)}`],
332 }).pipe(
333 Effect.map((result) => result.stdout.trim()),
334 Effect.flatMap((raw) =>
335 decodeGitLabJson(
336 raw,
337 RawGitLabRepositoryCloneUrlsSchema,
338 "getRepositoryCloneUrls",
339 "GitLab CLI returned invalid repository JSON.",
340 ),
341 ),
342 Effect.map(normalizeRepositoryCloneUrls),
343 ),
344 createRepository: (input) => {
345 const { namespacePath, projectPath } = parseRepositoryPath(input.repository);
346 const namespaceId: Effect.Effect<number | null, GitLabCliError> = namespacePath
347 ? execute({
348 cwd: input.cwd,
349 args: ["api", `namespaces/${encodeURIComponent(namespacePath)}`],
350 }).pipe(
351 Effect.map((result) => result.stdout.trim()),
352 Effect.flatMap((raw) =>
353 decodeGitLabJson(
354 raw,
355 RawGitLabNamespaceSchema,
356 "createRepository",
357 "GitLab CLI returned invalid namespace JSON.",
358 ),
359 ),
360 Effect.map((namespace) => namespace.id),
361 )
362 : Effect.succeed(null);
363​
364 return namespaceId.pipe(
365 Effect.flatMap((resolvedNamespaceId) =>
366 execute({
367 cwd: input.cwd,
368 args: [
369 "api",
370 "--method",
371 "POST",
372 "projects",
373 "--raw-field",
374 `path=${projectPath}`,
375 "--raw-field",
376 `name=${projectPath}`,
377 "--raw-field",
378 `visibility=${input.visibility}`,
379 ...(resolvedNamespaceId === null
380 ? []
381 : ["--raw-field", `namespace_id=${resolvedNamespaceId}`]),
382 ],
383 }),
384 ),
385 Effect.map((result) => result.stdout.trim()),
386 Effect.flatMap((raw) =>
387 decodeGitLabJson(
388 raw,
389 RawGitLabRepositoryCloneUrlsSchema,
390 "createRepository",
391 "GitLab CLI returned invalid repository JSON.",
392 ),
393 ),
394 Effect.map(normalizeRepositoryCloneUrls),
395 );
396 },
397 createMergeRequest: (input) => {
398 const sourceProject = sourceProjectIdentifier(input.source);
399 return execute({
400 cwd: input.cwd,
401 args: [
402 "api",
403 "--method",
404 "POST",
405 "projects/:fullpath/merge_requests",
406 "--raw-field",
407 `source_branch=${sourceRefName(input)}`,
408 "--raw-field",
409 `target_branch=${input.target?.refName ?? input.baseBranch}`,
410 ...(sourceProject ? ["--raw-field", `source_project_id=${sourceProject}`] : []),
411 "--raw-field",
412 `title=${input.title}`,
413 "--field",
414 `description=@${input.bodyFile}`,
415 ],
416 }).pipe(Effect.asVoid);
417 },
418 getDefaultBranch: (input) =>
419 execute({
420 cwd: input.cwd,
421 args: ["api", "projects/:fullpath"],
422 }).pipe(
423 Effect.map((result) => result.stdout.trim()),
424 Effect.flatMap((raw) =>
425 decodeGitLabJson(
426 raw,
427 RawGitLabDefaultBranchSchema,
428 "getDefaultBranch",
429 "GitLab CLI returned invalid repository JSON.",
430 ),
431 ),
432 Effect.map((value) => value.default_branch ?? null),
433 ),
434 checkoutMergeRequest: (input) =>
435 execute({
436 cwd: input.cwd,
437 args: ["mr", "checkout", input.reference],
438 }).pipe(Effect.asVoid),
439 });
440});
441​
442export const layer = Layer.effect(GitLabCli, make());