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