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