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/source-control/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 = repository
251 .split("/")
252 .map((part) => part.trim())
253 .filter((part) => part.length > 0);
254 const projectPath = parts.at(-1) ?? repository.trim();
255 const namespacePath = parts.length > 1 ? parts.slice(0, -1).join("/") : null;
256 return { namespacePath, projectPath };
257}
258
259export const make = Effect.fn("makeGitLabCli")(function* () {
260 const process = yield* VcsProcess.VcsProcess;
261
262 const execute: GitLabCliShape["execute"] = (input) =>
263 process
264 .run({
265 operation: "GitLabCli.execute",
266 command: "glab",
267 args: input.args,
268 cwd: input.cwd,
269 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
270 })
271 .pipe(Effect.mapError((error) => normalizeGitLabCliError("execute", error)));
272
273 return GitLabCli.of({
274 execute,
275 listMergeRequests: (input) =>
276 execute({
277 cwd: input.cwd,
278 args: [
279 "mr",
280 "list",
281 "--source-branch",
282 sourceRefName(input),
283 ...stateArgs(input.state),
284 "--per-page",
285 String(input.limit ?? 20),
286 "--output",
287 "json",
288 ],
289 }).pipe(
290 Effect.map((result) => result.stdout.trim()),
291 Effect.flatMap((raw) =>
292 raw.length === 0
293 ? Effect.succeed([])
294 : Effect.sync(() => GitLabMergeRequests.decodeGitLabMergeRequestListJson(raw)).pipe(
295 Effect.flatMap((decoded) => {
296 if (!Result.isSuccess(decoded)) {
297 return Effect.fail(
298 new GitLabCliError({
299 operation: "listMergeRequests",
300 detail: `GitLab CLI returned invalid MR list JSON: ${GitLabMergeRequests.formatGitLabJsonDecodeError(decoded.failure)}`,
301 cause: decoded.failure,
302 }),
303 );
304 }
305
306 return Effect.succeed(decoded.success.map(toSummaryWithOptionalUpdatedAt));
307 }),
308 ),
309 ),
310 ),
311 getMergeRequest: (input) =>
312 execute({
313 cwd: input.cwd,
314 args: ["mr", "view", input.reference, "--output", "json"],
315 }).pipe(
316 Effect.map((result) => result.stdout.trim()),
317 Effect.flatMap((raw) =>
318 Effect.sync(() => GitLabMergeRequests.decodeGitLabMergeRequestJson(raw)).pipe(
319 Effect.flatMap((decoded) => {
320 if (!Result.isSuccess(decoded)) {
321 return Effect.fail(
322 new GitLabCliError({
323 operation: "getMergeRequest",
324 detail: `GitLab CLI returned invalid merge request JSON: ${GitLabMergeRequests.formatGitLabJsonDecodeError(decoded.failure)}`,
325 cause: decoded.failure,
326 }),
327 );
328 }
329
330 return Effect.succeed(toSummaryWithOptionalUpdatedAt(decoded.success));
331 }),
332 ),
333 ),
334 ),
335 getRepositoryCloneUrls: (input) =>
336 execute({
337 cwd: input.cwd,
338 args: ["api", `projects/${encodeURIComponent(input.repository)}`],
339 }).pipe(
340 Effect.map((result) => result.stdout.trim()),
341 Effect.flatMap((raw) =>
342 decodeGitLabJson(
343 raw,
344 RawGitLabRepositoryCloneUrlsSchema,
345 "getRepositoryCloneUrls",
346 "GitLab CLI returned invalid repository JSON.",
347 ),
348 ),
349 Effect.map(normalizeRepositoryCloneUrls),
350 ),
351 createRepository: (input) => {
352 const { namespacePath, projectPath } = parseRepositoryPath(input.repository);
353 const namespaceId: Effect.Effect<number | null, GitLabCliError> = namespacePath
354 ? execute({
355 cwd: input.cwd,
356 args: ["api", `namespaces/${encodeURIComponent(namespacePath)}`],
357 }).pipe(
358 Effect.map((result) => result.stdout.trim()),
359 Effect.flatMap((raw) =>
360 decodeGitLabJson(
361 raw,
362 RawGitLabNamespaceSchema,
363 "createRepository",
364 "GitLab CLI returned invalid namespace JSON.",
365 ),
366 ),
367 Effect.map((namespace) => namespace.id),
368 )
369 : Effect.succeed(null);
370
371 return namespaceId.pipe(
372 Effect.flatMap((resolvedNamespaceId) =>
373 execute({
374 cwd: input.cwd,
375 args: [
376 "api",
377 "--method",
378 "POST",
379 "projects",
380 "--raw-field",
381 `path=${projectPath}`,
382 "--raw-field",
383 `name=${projectPath}`,
384 "--raw-field",
385 `visibility=${input.visibility}`,
386 ...(resolvedNamespaceId === null
387 ? []
388 : ["--raw-field", `namespace_id=${resolvedNamespaceId}`]),
389 ],
390 }),
391 ),
392 Effect.map((result) => result.stdout.trim()),
393 Effect.flatMap((raw) =>
394 decodeGitLabJson(
395 raw,
396 RawGitLabRepositoryCloneUrlsSchema,
397 "createRepository",
398 "GitLab CLI returned invalid repository JSON.",
399 ),
400 ),
401 Effect.map(normalizeRepositoryCloneUrls),
402 );
403 },
404 createMergeRequest: (input) => {
405 const sourceProject = sourceProjectIdentifier(input.source);
406 return execute({
407 cwd: input.cwd,
408 args: [
409 "api",
410 "--method",
411 "POST",
412 "projects/:fullpath/merge_requests",
413 "--raw-field",
414 `source_branch=${sourceRefName(input)}`,
415 "--raw-field",
416 `target_branch=${input.target?.refName ?? input.baseBranch}`,
417 ...(sourceProject ? ["--raw-field", `source_project_id=${sourceProject}`] : []),
418 "--raw-field",
419 `title=${input.title}`,
420 "--field",
421 `description=@${input.bodyFile}`,
422 ],
423 }).pipe(Effect.asVoid);
424 },
425 getDefaultBranch: (input) =>
426 execute({
427 cwd: input.cwd,
428 args: ["api", "projects/:fullpath"],
429 }).pipe(
430 Effect.map((result) => result.stdout.trim()),
431 Effect.flatMap((raw) =>
432 decodeGitLabJson(
433 raw,
434 RawGitLabDefaultBranchSchema,
435 "getDefaultBranch",
436 "GitLab CLI returned invalid repository JSON.",
437 ),
438 ),
439 Effect.map((value) => value.default_branch ?? null),
440 ),
441 checkoutMergeRequest: (input) =>
442 execute({
443 cwd: input.cwd,
444 args: ["mr", "checkout", input.reference],
445 }).pipe(Effect.asVoid),
446 });
447});
448
449export const layer = Layer.effect(GitLabCli, make());