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 Match from "effect/Match";
5import * as Option from "effect/Option";
6import * as Result from "effect/Result";
7import * as Schema from "effect/Schema";
8import type * as DateTime from "effect/DateTime";
9
10import {
11 TrimmedNonEmptyString,
12 type SourceControlRepositoryVisibility,
13 type VcsError,
14 type VcsProcessExitFailureKind,
15} from "@t3tools/contracts";
16
17import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
18import {
19 decodeGitLabMergeRequestJson,
20 decodeGitLabMergeRequestListJson,
21} from "./gitLabMergeRequests.ts";
22import type * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
23
24const DEFAULT_TIMEOUT_MS = 30_000;
25
26const gitLabCliExecutionErrorContext = {
27 operation: Schema.Literal("execute"),
28 command: Schema.Literal("glab"),
29 cwd: Schema.String,
30 cause: Schema.Defect(),
31};
32
33const gitLabCliDecodeErrorContext = {
34 command: Schema.Literal("glab"),
35 cwd: Schema.String,
36 cause: Schema.Defect(),
37};
38
39export class GitLabCliUnavailableError extends Schema.TaggedError<GitLabCliUnavailableError>()(
40 "GitLabCliUnavailableError",
41 gitLabCliExecutionErrorContext,
42) {
43 get detail(): string {
44 return "GitLab CLI (`glab`) is required but not available on PATH.";
45 }
46
47 override get message(): string {
48 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
49 }
50}
51
52export class GitLabCliAuthenticationError extends Schema.TaggedError<GitLabCliAuthenticationError>()(
53 "GitLabCliAuthenticationError",
54 gitLabCliExecutionErrorContext,
55) {
56 get detail(): string {
57 return "GitLab CLI is not authenticated. Run `glab auth login` and retry.";
58 }
59
60 override get message(): string {
61 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
62 }
63}
64
65export class GitLabCliRateLimitError extends Schema.TaggedError<GitLabCliRateLimitError>()(
66 "GitLabCliRateLimitError",
67 gitLabCliExecutionErrorContext,
68) {
69 get detail(): string {
70 return "GitLab API rate limit exceeded.";
71 }
72
73 override get message(): string {
74 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
75 }
76}
77
78export class GitLabMergeRequestNotFoundError extends Schema.TaggedError<GitLabMergeRequestNotFoundError>()(
79 "GitLabMergeRequestNotFoundError",
80 {
81 ...gitLabCliExecutionErrorContext,
82 reference: Schema.String,
83 },
84) {
85 get detail(): string {
86 return `Merge request ${this.reference} was not found. Check the MR number or URL and try again.`;
87 }
88
89 override get message(): string {
90 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
91 }
92
93 static fromVcsError(
94 context: {
95 readonly operation: "execute";
96 readonly command: "glab";
97 readonly cwd: string;
98 readonly reference: string;
99 },
100 error: VcsError,
101 ): GitLabCliError {
102 if (error._tag === "VcsProcessExitError" && error.failureKind === "not-found") {
103 return new GitLabMergeRequestNotFoundError({ ...context, cause: error });
104 }
105
106 return GitLabCliCommandError.fromVcsError(
107 {
108 operation: context.operation,
109 command: context.command,
110 cwd: context.cwd,
111 },
112 error,
113 );
114 }
115}
116
117export class GitLabCliCommandError extends Schema.TaggedError<GitLabCliCommandError>()(
118 "GitLabCliCommandError",
119 gitLabCliExecutionErrorContext,
120) {
121 get detail(): string {
122 return "GitLab CLI command failed.";
123 }
124
125 override get message(): string {
126 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
127 }
128
129 static fromVcsError(
130 context: {
131 readonly operation: "execute";
132 readonly command: "glab";
133 readonly cwd: string;
134 },
135 error: VcsError,
136 ): GitLabCliError {
137 return Match.valueTags(error, {
138 VcsProcessSpawnError: (cause) => new GitLabCliUnavailableError({ ...context, cause }),
139 VcsProcessExitError: (cause) => {
140 switch (cause.failureKind) {
141 case "authentication":
142 return new GitLabCliAuthenticationError({ ...context, cause });
143 case "rate-limited":
144 return new GitLabCliRateLimitError({ ...context, cause });
145 case "not-found":
146 case "command-failed":
147 case undefined:
148 return new GitLabCliCommandError({ ...context, cause });
149 }
150 },
151 VcsProcessTimeoutError: (cause) => new GitLabCliCommandError({ ...context, cause }),
152 VcsProcessStdinWriteError: (cause) => new GitLabCliCommandError({ ...context, cause }),
153 VcsProcessOutputReadError: (cause) => new GitLabCliCommandError({ ...context, cause }),
154 VcsProcessOutputLimitError: (cause) => new GitLabCliCommandError({ ...context, cause }),
155 VcsProcessMissingExitCodeError: (cause) => new GitLabCliCommandError({ ...context, cause }),
156 VcsRepositoryDetectionError: (cause) => new GitLabCliCommandError({ ...context, cause }),
157 VcsUnsupportedOperationError: (cause) => new GitLabCliCommandError({ ...context, cause }),
158 });
159 }
160}
161
162export class GitLabMergeRequestListDecodeError extends Schema.TaggedError<GitLabMergeRequestListDecodeError>()(
163 "GitLabMergeRequestListDecodeError",
164 {
165 ...gitLabCliDecodeErrorContext,
166 operation: Schema.Literal("listMergeRequests"),
167 },
168) {
169 get detail(): string {
170 return "GitLab CLI returned invalid MR list JSON.";
171 }
172
173 override get message(): string {
174 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
175 }
176}
177
178export class GitLabMergeRequestDecodeError extends Schema.TaggedError<GitLabMergeRequestDecodeError>()(
179 "GitLabMergeRequestDecodeError",
180 {
181 ...gitLabCliDecodeErrorContext,
182 operation: Schema.Literal("getMergeRequest"),
183 reference: Schema.String,
184 },
185) {
186 get detail(): string {
187 return "GitLab CLI returned invalid merge request JSON.";
188 }
189
190 override get message(): string {
191 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
192 }
193}
194
195export class GitLabRepositoryDecodeError extends Schema.TaggedError<GitLabRepositoryDecodeError>()(
196 "GitLabRepositoryDecodeError",
197 {
198 ...gitLabCliDecodeErrorContext,
199 operation: Schema.Literals(["getRepositoryCloneUrls", "createRepository", "getDefaultBranch"]),
200 repository: Schema.optional(Schema.String),
201 },
202) {
203 get detail(): string {
204 return "GitLab CLI returned invalid repository JSON.";
205 }
206
207 override get message(): string {
208 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
209 }
210}
211
212export class GitLabNamespaceDecodeError extends Schema.TaggedError<GitLabNamespaceDecodeError>()(
213 "GitLabNamespaceDecodeError",
214 {
215 ...gitLabCliDecodeErrorContext,
216 operation: Schema.Literal("createRepository"),
217 namespacePath: Schema.String,
218 },
219) {
220 get detail(): string {
221 return "GitLab CLI returned invalid namespace JSON.";
222 }
223
224 override get message(): string {
225 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
226 }
227}
228
229export const GitLabCliError = Schema.Union([
230 GitLabCliUnavailableError,
231 GitLabCliAuthenticationError,
232 GitLabCliRateLimitError,
233 GitLabMergeRequestNotFoundError,
234 GitLabCliCommandError,
235 GitLabMergeRequestListDecodeError,
236 GitLabMergeRequestDecodeError,
237 GitLabRepositoryDecodeError,
238 GitLabNamespaceDecodeError,
239]);
240export type GitLabCliError = typeof GitLabCliError.Type;
241
242export interface GitLabMergeRequestSummary {
243 readonly number: number;
244 readonly title: string;
245 readonly url: string;
246 readonly baseRefName: string;
247 readonly headRefName: string;
248 readonly headSha?: string;
249 readonly state?: "open" | "closed" | "merged";
250 readonly isDraft?: boolean;
251 readonly closedAt?: string | null;
252 readonly mergedAt?: string | null;
253 readonly updatedAt?: Option.Option<DateTime.Utc>;
254 readonly isCrossRepository?: boolean;
255 readonly headRepositoryNameWithOwner?: string | null;
256 readonly headRepositoryOwnerLogin?: string | null;
257}
258
259export interface GitLabRepositoryCloneUrls {
260 readonly nameWithOwner: string;
261 readonly url: string;
262 readonly sshUrl: string;
263}
264
265export class GitLabCli extends Context.Service<
266 GitLabCli,
267 {
268 readonly execute: (input: {
269 readonly cwd: string;
270 readonly host?: string | undefined;
271 readonly args: ReadonlyArray<string>;
272 readonly timeoutMs?: number;
273 /** Keeps sensitive payloads out of argv. */
274 readonly stdin?: string;
275 readonly maxOutputBytes?: number;
276 }) => Effect.Effect<SourceControlHost.SourceControlProcessOutput, GitLabCliError>;
277
278 readonly listMergeRequests: (input: {
279 readonly cwd: string;
280 readonly headSelector: string;
281 readonly source?: SourceControlProvider.SourceControlRefSelector;
282 readonly state: "open" | "closed" | "merged" | "all";
283 readonly limit?: number;
284 }) => Effect.Effect<ReadonlyArray<GitLabMergeRequestSummary>, GitLabCliError>;
285
286 readonly getMergeRequest: (input: {
287 readonly cwd: string;
288 readonly reference: string;
289 }) => Effect.Effect<GitLabMergeRequestSummary, GitLabCliError>;
290
291 readonly getRepositoryCloneUrls: (input: {
292 readonly cwd: string;
293 readonly repository: string;
294 }) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
295
296 readonly createRepository: (input: {
297 readonly cwd: string;
298 readonly repository: string;
299 readonly visibility: SourceControlRepositoryVisibility;
300 }) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
301
302 readonly createMergeRequest: (input: {
303 readonly cwd: string;
304 readonly baseBranch: string;
305 readonly headSelector: string;
306 readonly source?: SourceControlProvider.SourceControlRefSelector;
307 readonly target?: SourceControlProvider.SourceControlRefSelector;
308 readonly title: string;
309 readonly bodyFile: string;
310 }) => Effect.Effect<void, GitLabCliError>;
311
312 readonly getDefaultBranch: (input: {
313 readonly cwd: string;
314 }) => Effect.Effect<string | null, GitLabCliError>;
315
316 readonly checkoutMergeRequest: (input: {
317 readonly cwd: string;
318 readonly reference: string;
319 readonly force?: boolean;
320 }) => Effect.Effect<void, GitLabCliError>;
321 }
322>()("@t3tools/source-control-gitlab/server/GitLabCli") {}
323
324const RawGitLabRepositoryCloneUrlsSchema = Schema.Struct({
325 path_with_namespace: TrimmedNonEmptyString,
326 web_url: TrimmedNonEmptyString,
327 http_url_to_repo: TrimmedNonEmptyString,
328 ssh_url_to_repo: TrimmedNonEmptyString,
329});
330
331const RawGitLabDefaultBranchSchema = Schema.Struct({
332 default_branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
333});
334
335const RawGitLabNamespaceSchema = Schema.Struct({
336 id: Schema.Number,
337});
338
339const decodeGitLabRepositoryCloneUrls = Schema.decodeEffect(
340 Schema.fromJsonString(RawGitLabRepositoryCloneUrlsSchema),
341);
342const decodeGitLabDefaultBranch = Schema.decodeEffect(
343 Schema.fromJsonString(RawGitLabDefaultBranchSchema),
344);
345const decodeGitLabNamespace = Schema.decodeEffect(Schema.fromJsonString(RawGitLabNamespaceSchema));
346
347function normalizeRepositoryCloneUrls(
348 raw: Schema.Schema.Type<typeof RawGitLabRepositoryCloneUrlsSchema>,
349): GitLabRepositoryCloneUrls {
350 return {
351 nameWithOwner: raw.path_with_namespace,
352 url: raw.web_url,
353 sshUrl: raw.ssh_url_to_repo,
354 };
355}
356
357function stateArgs(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
358 switch (state) {
359 case "open":
360 return [];
361 case "closed":
362 return ["--closed"];
363 case "merged":
364 return ["--merged"];
365 case "all":
366 return ["--all"];
367 }
368}
369
370function normalizeHeadSelector(headSelector: string): string {
371 const trimmed = headSelector.trim();
372 const ownerBranch = /^[^:]+:(.+)$/.exec(trimmed);
373 return ownerBranch?.[1]?.trim() || trimmed;
374}
375
376function sourceRefName(input: {
377 readonly headSelector: string;
378 readonly source?: SourceControlProvider.SourceControlRefSelector;
379}): string {
380 return input.source?.refName ?? normalizeHeadSelector(input.headSelector);
381}
382
383function sourceProjectIdentifier(
384 source: SourceControlProvider.SourceControlRefSelector | undefined,
385): string | null {
386 return source?.repository ?? source?.owner ?? null;
387}
388
389function toSummaryWithOptionalUpdatedAt(
390 record: GitLabMergeRequestSummary & {
391 readonly updatedAt: Option.Option<DateTime.Utc>;
392 },
393): GitLabMergeRequestSummary {
394 const { updatedAt, ...summary } = record;
395 return Option.isSome(updatedAt) ? { ...summary, updatedAt } : summary;
396}
397
398function parseRepositoryPath(repository: string): {
399 readonly namespacePath: string | null;
400 readonly projectPath: string;
401} {
402 const parts: Array<string> = [];
403 for (const part of repository.split("/")) {
404 const trimmed = part.trim();
405 if (trimmed.length > 0) {
406 parts.push(trimmed);
407 }
408 }
409 const projectPath = parts.at(-1) ?? repository.trim();
410 const namespacePath = parts.length > 1 ? parts.slice(0, -1).join("/") : null;
411 return { namespacePath, projectPath };
412}
413
414// glab prints a missing project or merge request as a bare 404.
415const classifyGlabFailure = (stderr: string): VcsProcessExitFailureKind | null => {
416 const normalized = stderr.toLowerCase();
417 if (normalized.includes("glab auth login")) return "authentication";
418 if (normalized.includes("not found") || normalized.includes("404")) return "not-found";
419 return null;
420};
421
422/** @public */
423export const make = Effect.gen(function* () {
424 const { process } = yield* SourceControlHost.SourceControlHost;
425
426 const run = (
427 input: Parameters<GitLabCli["Service"]["execute"]>[0],
428 mapError: (error: VcsError) => GitLabCliError,
429 ) =>
430 process
431 .run({
432 operation: "GitLabCli.execute",
433 command: "glab",
434 args: input.args,
435 cwd: input.cwd,
436 // glab may otherwise prefer a different checkout remote.
437 ...(input.host === undefined ? {} : { env: { GITLAB_HOST: input.host } }),
438 classifyFailure: classifyGlabFailure,
439 notFoundDetail: "Merge request not found.",
440 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
441 ...(input.stdin === undefined ? {} : { stdin: input.stdin }),
442 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
443 })
444 .pipe(Effect.mapError(mapError));
445
446 const execute: GitLabCli["Service"]["execute"] = (input) =>
447 run(input, (error) =>
448 GitLabCliCommandError.fromVcsError(
449 { operation: "execute", command: "glab", cwd: input.cwd },
450 error,
451 ),
452 );
453
454 const executeMergeRequest = (input: {
455 readonly cwd: string;
456 readonly reference: string;
457 readonly args: ReadonlyArray<string>;
458 }) =>
459 run(input, (error) =>
460 GitLabMergeRequestNotFoundError.fromVcsError(
461 {
462 operation: "execute",
463 command: "glab",
464 cwd: input.cwd,
465 reference: input.reference,
466 },
467 error,
468 ),
469 );
470
471 return GitLabCli.of({
472 execute,
473 listMergeRequests: Effect.fn("GitLabCli.listMergeRequests")(function (input) {
474 return execute({
475 cwd: input.cwd,
476 args: [
477 "mr",
478 "list",
479 "--source-branch",
480 sourceRefName(input),
481 ...stateArgs(input.state),
482 "--per-page",
483 String(input.limit ?? 20),
484 "--output",
485 "json",
486 ],
487 }).pipe(
488 Effect.map((result) => result.stdout.trim()),
489 Effect.flatMap((raw) =>
490 raw.length === 0
491 ? Effect.succeed([])
492 : Effect.sync(() => decodeGitLabMergeRequestListJson(raw)).pipe(
493 Effect.flatMap((decoded) => {
494 if (!Result.isSuccess(decoded)) {
495 return Effect.fail(
496 new GitLabMergeRequestListDecodeError({
497 operation: "listMergeRequests",
498 command: "glab",
499 cwd: input.cwd,
500 cause: decoded.failure,
501 }),
502 );
503 }
504
505 return Effect.succeed(decoded.success.map(toSummaryWithOptionalUpdatedAt));
506 }),
507 ),
508 ),
509 );
510 }),
511 getMergeRequest: Effect.fn("GitLabCli.getMergeRequest")(function (input) {
512 return executeMergeRequest({
513 cwd: input.cwd,
514 reference: input.reference,
515 args: ["mr", "view", "--output", "json", "--", input.reference],
516 }).pipe(
517 Effect.map((result) => result.stdout.trim()),
518 Effect.flatMap((raw) =>
519 Effect.sync(() => decodeGitLabMergeRequestJson(raw)).pipe(
520 Effect.flatMap((decoded) => {
521 if (!Result.isSuccess(decoded)) {
522 return Effect.fail(
523 new GitLabMergeRequestDecodeError({
524 operation: "getMergeRequest",
525 command: "glab",
526 cwd: input.cwd,
527 reference: input.reference,
528 cause: decoded.failure,
529 }),
530 );
531 }
532
533 return Effect.succeed(toSummaryWithOptionalUpdatedAt(decoded.success));
534 }),
535 ),
536 ),
537 );
538 }),
539 getRepositoryCloneUrls: Effect.fn("GitLabCli.getRepositoryCloneUrls")(function (input) {
540 return execute({
541 cwd: input.cwd,
542 args: ["api", `projects/${encodeURIComponent(input.repository)}`],
543 }).pipe(
544 Effect.map((result) => result.stdout.trim()),
545 Effect.flatMap((raw) =>
546 decodeGitLabRepositoryCloneUrls(raw).pipe(
547 Effect.mapError(
548 (cause) =>
549 new GitLabRepositoryDecodeError({
550 operation: "getRepositoryCloneUrls",
551 command: "glab",
552 cwd: input.cwd,
553 repository: input.repository,
554 cause,
555 }),
556 ),
557 ),
558 ),
559 Effect.map(normalizeRepositoryCloneUrls),
560 );
561 }),
562 createRepository: Effect.fn("GitLabCli.createRepository")(function (input) {
563 const { namespacePath, projectPath } = parseRepositoryPath(input.repository);
564 const namespaceId: Effect.Effect<number | null, GitLabCliError> = namespacePath
565 ? execute({
566 cwd: input.cwd,
567 args: ["api", `namespaces/${encodeURIComponent(namespacePath)}`],
568 }).pipe(
569 Effect.map((result) => result.stdout.trim()),
570 Effect.flatMap((raw) =>
571 decodeGitLabNamespace(raw).pipe(
572 Effect.mapError(
573 (cause) =>
574 new GitLabNamespaceDecodeError({
575 operation: "createRepository",
576 command: "glab",
577 cwd: input.cwd,
578 namespacePath,
579 cause,
580 }),
581 ),
582 ),
583 ),
584 Effect.map((namespace) => namespace.id),
585 )
586 : Effect.succeed(null);
587
588 return namespaceId.pipe(
589 Effect.flatMap((resolvedNamespaceId) =>
590 execute({
591 cwd: input.cwd,
592 args: [
593 "api",
594 "--method",
595 "POST",
596 "projects",
597 "--raw-field",
598 `path=${projectPath}`,
599 "--raw-field",
600 `name=${projectPath}`,
601 "--raw-field",
602 `visibility=${input.visibility}`,
603 ...(resolvedNamespaceId === null
604 ? []
605 : ["--raw-field", `namespace_id=${resolvedNamespaceId}`]),
606 ],
607 }),
608 ),
609 Effect.map((result) => result.stdout.trim()),
610 Effect.flatMap((raw) =>
611 decodeGitLabRepositoryCloneUrls(raw).pipe(
612 Effect.mapError(
613 (cause) =>
614 new GitLabRepositoryDecodeError({
615 operation: "createRepository",
616 command: "glab",
617 cwd: input.cwd,
618 repository: input.repository,
619 cause,
620 }),
621 ),
622 ),
623 ),
624 Effect.map(normalizeRepositoryCloneUrls),
625 );
626 }),
627 createMergeRequest: Effect.fn("GitLabCli.createMergeRequest")(function (input) {
628 const sourceProject = sourceProjectIdentifier(input.source);
629 return execute({
630 cwd: input.cwd,
631 args: [
632 "api",
633 "--method",
634 "POST",
635 "projects/:fullpath/merge_requests",
636 "--raw-field",
637 `source_branch=${sourceRefName(input)}`,
638 "--raw-field",
639 `target_branch=${input.target?.refName ?? input.baseBranch}`,
640 ...(sourceProject ? ["--raw-field", `source_project_id=${sourceProject}`] : []),
641 "--raw-field",
642 `title=${input.title}`,
643 "--field",
644 `description=@${input.bodyFile}`,
645 ],
646 }).pipe(Effect.asVoid);
647 }),
648 getDefaultBranch: Effect.fn("GitLabCli.getDefaultBranch")(function (input) {
649 return execute({
650 cwd: input.cwd,
651 args: ["api", "projects/:fullpath"],
652 }).pipe(
653 Effect.map((result) => result.stdout.trim()),
654 Effect.flatMap((raw) =>
655 decodeGitLabDefaultBranch(raw).pipe(
656 Effect.mapError(
657 (cause) =>
658 new GitLabRepositoryDecodeError({
659 operation: "getDefaultBranch",
660 command: "glab",
661 cwd: input.cwd,
662 cause,
663 }),
664 ),
665 ),
666 ),
667 Effect.map((value) => value.default_branch ?? null),
668 );
669 }),
670 checkoutMergeRequest: Effect.fn("GitLabCli.checkoutMergeRequest")(function (input) {
671 return executeMergeRequest({
672 cwd: input.cwd,
673 reference: input.reference,
674 args: ["mr", "checkout", "--", input.reference],
675 }).pipe(Effect.asVoid);
676 }),
677 });
678});
679
680export const layer = Layer.effect(GitLabCli, make);