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 VcsCheckpointStorageError: (cause) => new GitLabCliCommandError({ ...context, cause }),
158 VcsUnsupportedOperationError: (cause) => new GitLabCliCommandError({ ...context, cause }),
159 });
160 }
161}
162
163export class GitLabMergeRequestListDecodeError extends Schema.TaggedError<GitLabMergeRequestListDecodeError>()(
164 "GitLabMergeRequestListDecodeError",
165 {
166 ...gitLabCliDecodeErrorContext,
167 operation: Schema.Literal("listMergeRequests"),
168 },
169) {
170 get detail(): string {
171 return "GitLab CLI returned invalid MR list JSON.";
172 }
173
174 override get message(): string {
175 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
176 }
177}
178
179export class GitLabMergeRequestDecodeError extends Schema.TaggedError<GitLabMergeRequestDecodeError>()(
180 "GitLabMergeRequestDecodeError",
181 {
182 ...gitLabCliDecodeErrorContext,
183 operation: Schema.Literal("getMergeRequest"),
184 reference: Schema.String,
185 },
186) {
187 get detail(): string {
188 return "GitLab CLI returned invalid merge request JSON.";
189 }
190
191 override get message(): string {
192 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
193 }
194}
195
196export class GitLabRepositoryDecodeError extends Schema.TaggedError<GitLabRepositoryDecodeError>()(
197 "GitLabRepositoryDecodeError",
198 {
199 ...gitLabCliDecodeErrorContext,
200 operation: Schema.Literals([
201 "getRepositoryCloneUrls",
202 "createRepository",
203 "getDefaultBranch",
204 "createMergeRequest",
205 ]),
206 repository: Schema.optional(Schema.String),
207 },
208) {
209 get detail(): string {
210 return "GitLab CLI returned invalid repository JSON.";
211 }
212
213 override get message(): string {
214 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
215 }
216}
217
218export class GitLabNamespaceDecodeError extends Schema.TaggedError<GitLabNamespaceDecodeError>()(
219 "GitLabNamespaceDecodeError",
220 {
221 ...gitLabCliDecodeErrorContext,
222 operation: Schema.Literal("createRepository"),
223 namespacePath: Schema.String,
224 },
225) {
226 get detail(): string {
227 return "GitLab CLI returned invalid namespace JSON.";
228 }
229
230 override get message(): string {
231 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
232 }
233}
234
235export const GitLabCliError = Schema.Union([
236 GitLabCliUnavailableError,
237 GitLabCliAuthenticationError,
238 GitLabCliRateLimitError,
239 GitLabMergeRequestNotFoundError,
240 GitLabCliCommandError,
241 GitLabMergeRequestListDecodeError,
242 GitLabMergeRequestDecodeError,
243 GitLabRepositoryDecodeError,
244 GitLabNamespaceDecodeError,
245]);
246export type GitLabCliError = typeof GitLabCliError.Type;
247
248export interface GitLabMergeRequestSummary {
249 readonly number: number;
250 readonly title: string;
251 readonly url: string;
252 readonly baseRefName: string;
253 readonly headRefName: string;
254 readonly headSha?: string;
255 readonly state?: "open" | "closed" | "merged";
256 readonly isDraft?: boolean;
257 readonly closedAt?: string | null;
258 readonly mergedAt?: string | null;
259 readonly updatedAt?: Option.Option<DateTime.Utc>;
260 readonly isCrossRepository?: boolean;
261 readonly headRepositoryNameWithOwner?: string | null;
262 readonly headRepositoryOwnerLogin?: string | null;
263}
264
265export interface GitLabRepositoryCloneUrls {
266 readonly nameWithOwner: string;
267 readonly url: string;
268 readonly sshUrl: string;
269}
270
271export class GitLabCli extends Context.Service<
272 GitLabCli,
273 {
274 readonly execute: (input: {
275 readonly cwd: string;
276 readonly host?: string | undefined;
277 readonly args: ReadonlyArray<string>;
278 readonly timeoutMs?: number;
279 /** Keeps sensitive payloads out of argv. */
280 readonly stdin?: string;
281 readonly maxOutputBytes?: number;
282 }) => Effect.Effect<SourceControlHost.SourceControlProcessOutput, GitLabCliError>;
283
284 readonly listMergeRequests: (input: {
285 readonly cwd: string;
286 readonly headSelector: string;
287 readonly source?: SourceControlProvider.SourceControlRefSelector;
288 readonly state: "open" | "closed" | "merged" | "all";
289 readonly limit?: number;
290 }) => Effect.Effect<ReadonlyArray<GitLabMergeRequestSummary>, GitLabCliError>;
291
292 readonly getMergeRequest: (input: {
293 readonly cwd: string;
294 readonly reference: string;
295 }) => Effect.Effect<GitLabMergeRequestSummary, GitLabCliError>;
296
297 readonly getRepositoryCloneUrls: (input: {
298 readonly cwd: string;
299 readonly repository: string;
300 }) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
301
302 readonly createRepository: (input: {
303 readonly cwd: string;
304 readonly repository: string;
305 readonly visibility: SourceControlRepositoryVisibility;
306 }) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
307
308 readonly createMergeRequest: (input: {
309 readonly cwd: string;
310 readonly baseBranch: string;
311 readonly headSelector: string;
312 readonly source?: SourceControlProvider.SourceControlRefSelector;
313 readonly target?: SourceControlProvider.SourceControlRefSelector;
314 readonly title: string;
315 readonly bodyFile: string;
316 }) => Effect.Effect<void, GitLabCliError>;
317
318 readonly getDefaultBranch: (input: {
319 readonly cwd: string;
320 }) => Effect.Effect<string | null, GitLabCliError>;
321
322 readonly checkoutMergeRequest: (input: {
323 readonly cwd: string;
324 readonly reference: string;
325 readonly force?: boolean;
326 }) => Effect.Effect<void, GitLabCliError>;
327 }
328>()("@t3tools/source-control-gitlab/server/GitLabCli") {}
329
330const RawGitLabRepositoryCloneUrlsSchema = Schema.Struct({
331 path_with_namespace: TrimmedNonEmptyString,
332 web_url: TrimmedNonEmptyString,
333 http_url_to_repo: TrimmedNonEmptyString,
334 ssh_url_to_repo: TrimmedNonEmptyString,
335});
336
337const RawGitLabDefaultBranchSchema = Schema.Struct({
338 default_branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
339});
340
341const decodeGitLabMergeRequestProject = Schema.decodeEffect(
342 Schema.fromJsonString(Schema.Struct({ id: Schema.Number, path: TrimmedNonEmptyString })),
343);
344
345const RawGitLabNamespaceSchema = Schema.Struct({
346 id: Schema.Number,
347});
348
349const decodeGitLabRepositoryCloneUrls = Schema.decodeEffect(
350 Schema.fromJsonString(RawGitLabRepositoryCloneUrlsSchema),
351);
352const decodeGitLabDefaultBranch = Schema.decodeEffect(
353 Schema.fromJsonString(RawGitLabDefaultBranchSchema),
354);
355const decodeGitLabNamespace = Schema.decodeEffect(Schema.fromJsonString(RawGitLabNamespaceSchema));
356
357function normalizeRepositoryCloneUrls(
358 raw: Schema.Schema.Type<typeof RawGitLabRepositoryCloneUrlsSchema>,
359): GitLabRepositoryCloneUrls {
360 return {
361 nameWithOwner: raw.path_with_namespace,
362 url: raw.web_url,
363 sshUrl: raw.ssh_url_to_repo,
364 };
365}
366
367function stateArgs(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
368 switch (state) {
369 case "open":
370 return [];
371 case "closed":
372 return ["--closed"];
373 case "merged":
374 return ["--merged"];
375 case "all":
376 return ["--all"];
377 }
378}
379
380function normalizeHeadSelector(headSelector: string): string {
381 const trimmed = headSelector.trim();
382 const ownerBranch = /^[^:]+:(.+)$/.exec(trimmed);
383 return ownerBranch?.[1]?.trim() || trimmed;
384}
385
386function sourceRefName(input: {
387 readonly headSelector: string;
388 readonly source?: SourceControlProvider.SourceControlRefSelector;
389}): string {
390 return input.source?.refName ?? normalizeHeadSelector(input.headSelector);
391}
392
393function toSummaryWithOptionalUpdatedAt(
394 record: GitLabMergeRequestSummary & {
395 readonly updatedAt: Option.Option<DateTime.Utc>;
396 },
397): GitLabMergeRequestSummary {
398 const { updatedAt, ...summary } = record;
399 return Option.isSome(updatedAt) ? { ...summary, updatedAt } : summary;
400}
401
402function parseRepositoryPath(repository: string): {
403 readonly namespacePath: string | null;
404 readonly projectPath: string;
405} {
406 const parts: Array<string> = [];
407 for (const part of repository.split("/")) {
408 const trimmed = part.trim();
409 if (trimmed.length > 0) {
410 parts.push(trimmed);
411 }
412 }
413 const projectPath = parts.at(-1) ?? repository.trim();
414 const namespacePath = parts.length > 1 ? parts.slice(0, -1).join("/") : null;
415 return { namespacePath, projectPath };
416}
417
418// glab prints a missing project or merge request as a bare 404, and an expired
419// OAuth login as an `invalid_grant` refresh failure without suggesting `glab auth login`.
420const classifyGlabFailure = (stderr: string): VcsProcessExitFailureKind | null => {
421 const normalized = stderr.toLowerCase();
422 if (normalized.includes("glab auth login") || normalized.includes("invalid_grant")) {
423 return "authentication";
424 }
425
426 if (normalized.includes("not found") || normalized.includes("404")) {
427 return "not-found";
428 }
429
430 return null;
431};
432
433/** @public */
434export const make = Effect.gen(function* () {
435 const { process } = yield* SourceControlHost.SourceControlHost;
436
437 const run = (
438 input: Parameters<GitLabCli["Service"]["execute"]>[0],
439 mapError: (error: VcsError) => GitLabCliError,
440 ) =>
441 process
442 .run({
443 operation: "GitLabCli.execute",
444 command: "glab",
445 args: input.args,
446 cwd: input.cwd,
447 // glab may otherwise prefer a different checkout remote.
448 ...(input.host === undefined ? {} : { env: { GITLAB_HOST: input.host } }),
449 classifyFailure: classifyGlabFailure,
450 notFoundDetail: "Merge request not found.",
451 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
452 ...(input.stdin === undefined ? {} : { stdin: input.stdin }),
453 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
454 })
455 .pipe(Effect.mapError(mapError));
456
457 const execute: GitLabCli["Service"]["execute"] = (input) =>
458 run(input, (error) =>
459 GitLabCliCommandError.fromVcsError(
460 { operation: "execute", command: "glab", cwd: input.cwd },
461 error,
462 ),
463 );
464
465 const executeMergeRequest = (input: {
466 readonly cwd: string;
467 readonly reference: string;
468 readonly args: ReadonlyArray<string>;
469 }) =>
470 run(input, (error) =>
471 GitLabMergeRequestNotFoundError.fromVcsError(
472 {
473 operation: "execute",
474 command: "glab",
475 cwd: input.cwd,
476 reference: input.reference,
477 },
478 error,
479 ),
480 );
481
482 return GitLabCli.of({
483 execute,
484 listMergeRequests: Effect.fn("GitLabCli.listMergeRequests")(function (input) {
485 return execute({
486 cwd: input.cwd,
487 args: [
488 "mr",
489 "list",
490 "--source-branch",
491 sourceRefName(input),
492 ...stateArgs(input.state),
493 "--per-page",
494 String(input.limit ?? 20),
495 "--output",
496 "json",
497 ],
498 }).pipe(
499 Effect.map((result) => result.stdout.trim()),
500 Effect.flatMap((raw) =>
501 raw.length === 0
502 ? Effect.succeed([])
503 : Effect.sync(() => decodeGitLabMergeRequestListJson(raw)).pipe(
504 Effect.flatMap((decoded) => {
505 if (!Result.isSuccess(decoded)) {
506 return Effect.fail(
507 new GitLabMergeRequestListDecodeError({
508 operation: "listMergeRequests",
509 command: "glab",
510 cwd: input.cwd,
511 cause: decoded.failure,
512 }),
513 );
514 }
515
516 return Effect.succeed(decoded.success.map(toSummaryWithOptionalUpdatedAt));
517 }),
518 ),
519 ),
520 );
521 }),
522 getMergeRequest: Effect.fn("GitLabCli.getMergeRequest")(function (input) {
523 return executeMergeRequest({
524 cwd: input.cwd,
525 reference: input.reference,
526 args: ["mr", "view", "--output", "json", "--", input.reference],
527 }).pipe(
528 Effect.map((result) => result.stdout.trim()),
529 Effect.flatMap((raw) =>
530 Effect.sync(() => decodeGitLabMergeRequestJson(raw)).pipe(
531 Effect.flatMap((decoded) => {
532 if (!Result.isSuccess(decoded)) {
533 return Effect.fail(
534 new GitLabMergeRequestDecodeError({
535 operation: "getMergeRequest",
536 command: "glab",
537 cwd: input.cwd,
538 reference: input.reference,
539 cause: decoded.failure,
540 }),
541 );
542 }
543
544 return Effect.succeed(toSummaryWithOptionalUpdatedAt(decoded.success));
545 }),
546 ),
547 ),
548 );
549 }),
550 getRepositoryCloneUrls: Effect.fn("GitLabCli.getRepositoryCloneUrls")(function (input) {
551 return execute({
552 cwd: input.cwd,
553 args: ["api", `projects/${encodeURIComponent(input.repository)}`],
554 }).pipe(
555 Effect.map((result) => result.stdout.trim()),
556 Effect.flatMap((raw) =>
557 decodeGitLabRepositoryCloneUrls(raw).pipe(
558 Effect.mapError(
559 (cause) =>
560 new GitLabRepositoryDecodeError({
561 operation: "getRepositoryCloneUrls",
562 command: "glab",
563 cwd: input.cwd,
564 repository: input.repository,
565 cause,
566 }),
567 ),
568 ),
569 ),
570 Effect.map(normalizeRepositoryCloneUrls),
571 );
572 }),
573 createRepository: Effect.fn("GitLabCli.createRepository")(function (input) {
574 const { namespacePath, projectPath } = parseRepositoryPath(input.repository);
575 const namespaceId: Effect.Effect<number | null, GitLabCliError> = namespacePath
576 ? execute({
577 cwd: input.cwd,
578 args: ["api", `namespaces/${encodeURIComponent(namespacePath)}`],
579 }).pipe(
580 Effect.map((result) => result.stdout.trim()),
581 Effect.flatMap((raw) =>
582 decodeGitLabNamespace(raw).pipe(
583 Effect.mapError(
584 (cause) =>
585 new GitLabNamespaceDecodeError({
586 operation: "createRepository",
587 command: "glab",
588 cwd: input.cwd,
589 namespacePath,
590 cause,
591 }),
592 ),
593 ),
594 ),
595 Effect.map((namespace) => namespace.id),
596 )
597 : Effect.succeed(null);
598
599 return namespaceId.pipe(
600 Effect.flatMap((resolvedNamespaceId) =>
601 execute({
602 cwd: input.cwd,
603 args: [
604 "api",
605 "--method",
606 "POST",
607 "projects",
608 "--raw-field",
609 `path=${projectPath}`,
610 "--raw-field",
611 `name=${projectPath}`,
612 "--raw-field",
613 `visibility=${input.visibility}`,
614 ...(resolvedNamespaceId === null
615 ? []
616 : ["--raw-field", `namespace_id=${resolvedNamespaceId}`]),
617 ],
618 }),
619 ),
620 Effect.map((result) => result.stdout.trim()),
621 Effect.flatMap((raw) =>
622 decodeGitLabRepositoryCloneUrls(raw).pipe(
623 Effect.mapError(
624 (cause) =>
625 new GitLabRepositoryDecodeError({
626 operation: "createRepository",
627 command: "glab",
628 cwd: input.cwd,
629 repository: input.repository,
630 cause,
631 }),
632 ),
633 ),
634 ),
635 Effect.map(normalizeRepositoryCloneUrls),
636 );
637 }),
638 createMergeRequest: Effect.fn("GitLabCli.createMergeRequest")(function* (input) {
639 let project = ":fullpath";
640 let targetProjectId: number | undefined;
641 if (input.source?.repository || input.source?.owner) {
642 const result = yield* execute({ cwd: input.cwd, args: ["api", "projects/:fullpath"] });
643 const targetProject = yield* decodeGitLabMergeRequestProject(result.stdout).pipe(
644 Effect.mapError(
645 (cause) =>
646 new GitLabRepositoryDecodeError({
647 operation: "createMergeRequest",
648 command: "glab",
649 cwd: input.cwd,
650 cause,
651 }),
652 ),
653 );
654 project = encodeURIComponent(
655 input.source.repository ?? `${input.source.owner}/${targetProject.path}`,
656 );
657 targetProjectId = targetProject.id;
658 }
659 yield* execute({
660 cwd: input.cwd,
661 args: [
662 "api",
663 "--method",
664 "POST",
665 `projects/${project}/merge_requests`,
666 "--raw-field",
667 `source_branch=${sourceRefName(input)}`,
668 "--raw-field",
669 `target_branch=${input.target?.refName ?? input.baseBranch}`,
670 ...(targetProjectId === undefined
671 ? []
672 : ["--raw-field", `target_project_id=${targetProjectId}`]),
673 "--raw-field",
674 `title=${input.title}`,
675 "--field",
676 `description=@${input.bodyFile}`,
677 ],
678 });
679 }),
680 getDefaultBranch: Effect.fn("GitLabCli.getDefaultBranch")(function (input) {
681 return execute({
682 cwd: input.cwd,
683 args: ["api", "projects/:fullpath"],
684 }).pipe(
685 Effect.map((result) => result.stdout.trim()),
686 Effect.flatMap((raw) =>
687 decodeGitLabDefaultBranch(raw).pipe(
688 Effect.mapError(
689 (cause) =>
690 new GitLabRepositoryDecodeError({
691 operation: "getDefaultBranch",
692 command: "glab",
693 cwd: input.cwd,
694 cause,
695 }),
696 ),
697 ),
698 ),
699 Effect.map((value) => value.default_branch ?? null),
700 );
701 }),
702 checkoutMergeRequest: Effect.fn("GitLabCli.checkoutMergeRequest")(function (input) {
703 return executeMergeRequest({
704 cwd: input.cwd,
705 reference: input.reference,
706 args: ["mr", "checkout", "--", input.reference],
707 }).pipe(Effect.asVoid);
708 }),
709 });
710});
711
712export const layer = Layer.effect(GitLabCli, make);