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