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 VcsProcess from "../vcs/VcsProcess.ts";
17import {
18 decodeGitLabMergeRequestJson,
19 decodeGitLabMergeRequestListJson,
20} from "./gitLabMergeRequests.ts";
21import type * as SourceControlProvider from "./SourceControlProvider.ts";
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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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;
240export const isGitLabCliError = Schema.is(GitLabCliError);
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 state?: "open" | "closed" | "merged";
249 readonly updatedAt?: Option.Option<DateTime.Utc>;
250 readonly isCrossRepository?: boolean;
251 readonly headRepositoryNameWithOwner?: string | null;
252 readonly headRepositoryOwnerLogin?: string | null;
253}
254
255export interface GitLabRepositoryCloneUrls {
256 readonly nameWithOwner: string;
257 readonly url: string;
258 readonly sshUrl: string;
259}
260
261export class GitLabCli extends Context.Service<
262 GitLabCli,
263 {
264 readonly execute: (input: {
265 readonly cwd: string;
266 readonly args: ReadonlyArray<string>;
267 readonly timeoutMs?: number;
268 /** Piped to the child's stdin, for payloads that must never appear in argv. */
269 readonly stdin?: string;
270 readonly maxOutputBytes?: number;
271 }) => Effect.Effect<VcsProcess.VcsProcessOutput, GitLabCliError>;
272
273 readonly listMergeRequests: (input: {
274 readonly cwd: string;
275 readonly headSelector: string;
276 readonly source?: SourceControlProvider.SourceControlRefSelector;
277 readonly state: "open" | "closed" | "merged" | "all";
278 readonly limit?: number;
279 }) => Effect.Effect<ReadonlyArray<GitLabMergeRequestSummary>, GitLabCliError>;
280
281 readonly getMergeRequest: (input: {
282 readonly cwd: string;
283 readonly reference: string;
284 }) => Effect.Effect<GitLabMergeRequestSummary, GitLabCliError>;
285
286 readonly getRepositoryCloneUrls: (input: {
287 readonly cwd: string;
288 readonly repository: string;
289 }) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
290
291 readonly createRepository: (input: {
292 readonly cwd: string;
293 readonly repository: string;
294 readonly visibility: SourceControlRepositoryVisibility;
295 }) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
296
297 readonly createMergeRequest: (input: {
298 readonly cwd: string;
299 readonly baseBranch: string;
300 readonly headSelector: string;
301 readonly source?: SourceControlProvider.SourceControlRefSelector;
302 readonly target?: SourceControlProvider.SourceControlRefSelector;
303 readonly title: string;
304 readonly bodyFile: string;
305 }) => Effect.Effect<void, GitLabCliError>;
306
307 readonly getDefaultBranch: (input: {
308 readonly cwd: string;
309 }) => Effect.Effect<string | null, GitLabCliError>;
310
311 readonly checkoutMergeRequest: (input: {
312 readonly cwd: string;
313 readonly reference: string;
314 readonly force?: boolean;
315 }) => Effect.Effect<void, GitLabCliError>;
316 }
317>()("t3/sourceControl/GitLabCli") {}
318
319const RawGitLabRepositoryCloneUrlsSchema = Schema.Struct({
320 path_with_namespace: TrimmedNonEmptyString,
321 web_url: TrimmedNonEmptyString,
322 http_url_to_repo: TrimmedNonEmptyString,
323 ssh_url_to_repo: TrimmedNonEmptyString,
324});
325
326const RawGitLabDefaultBranchSchema = Schema.Struct({
327 default_branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
328});
329
330const RawGitLabNamespaceSchema = Schema.Struct({
331 id: Schema.Number,
332});
333
334const decodeGitLabRepositoryCloneUrls = Schema.decodeEffect(
335 Schema.fromJsonString(RawGitLabRepositoryCloneUrlsSchema),
336);
337const decodeGitLabDefaultBranch = Schema.decodeEffect(
338 Schema.fromJsonString(RawGitLabDefaultBranchSchema),
339);
340const decodeGitLabNamespace = Schema.decodeEffect(Schema.fromJsonString(RawGitLabNamespaceSchema));
341
342function normalizeRepositoryCloneUrls(
343 raw: Schema.Schema.Type<typeof RawGitLabRepositoryCloneUrlsSchema>,
344): GitLabRepositoryCloneUrls {
345 return {
346 nameWithOwner: raw.path_with_namespace,
347 url: raw.web_url,
348 sshUrl: raw.ssh_url_to_repo,
349 };
350}
351
352function stateArgs(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
353 switch (state) {
354 case "open":
355 return [];
356 case "closed":
357 return ["--closed"];
358 case "merged":
359 return ["--merged"];
360 case "all":
361 return ["--all"];
362 }
363}
364
365function normalizeHeadSelector(headSelector: string): string {
366 const trimmed = headSelector.trim();
367 const ownerBranch = /^[^:]+:(.+)$/.exec(trimmed);
368 return ownerBranch?.[1]?.trim() || trimmed;
369}
370
371function sourceRefName(input: {
372 readonly headSelector: string;
373 readonly source?: SourceControlProvider.SourceControlRefSelector;
374}): string {
375 return input.source?.refName ?? normalizeHeadSelector(input.headSelector);
376}
377
378function sourceProjectIdentifier(
379 source: SourceControlProvider.SourceControlRefSelector | undefined,
380): string | null {
381 return source?.repository ?? source?.owner ?? null;
382}
383
384function toSummaryWithOptionalUpdatedAt(
385 record: GitLabMergeRequestSummary & {
386 readonly updatedAt: Option.Option<DateTime.Utc>;
387 },
388): GitLabMergeRequestSummary {
389 const { updatedAt, ...summary } = record;
390 return Option.isSome(updatedAt) ? { ...summary, updatedAt } : summary;
391}
392
393function parseRepositoryPath(repository: string): {
394 readonly namespacePath: string | null;
395 readonly projectPath: string;
396} {
397 const parts: Array<string> = [];
398 for (const part of repository.split("/")) {
399 const trimmed = part.trim();
400 if (trimmed.length > 0) {
401 parts.push(trimmed);
402 }
403 }
404 const projectPath = parts.at(-1) ?? repository.trim();
405 const namespacePath = parts.length > 1 ? parts.slice(0, -1).join("/") : null;
406 return { namespacePath, projectPath };
407}
408
409export const make = Effect.gen(function* () {
410 const process = yield* VcsProcess.VcsProcess;
411
412 const run = (
413 input: Parameters<GitLabCli["Service"]["execute"]>[0],
414 mapError: (error: VcsError) => GitLabCliError,
415 ) =>
416 process
417 .run({
418 operation: "GitLabCli.execute",
419 command: "glab",
420 args: input.args,
421 cwd: input.cwd,
422 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
423 ...(input.stdin === undefined ? {} : { stdin: input.stdin }),
424 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
425 })
426 .pipe(Effect.mapError(mapError));
427
428 const execute: GitLabCli["Service"]["execute"] = (input) =>
429 run(input, (error) =>
430 GitLabCliCommandError.fromVcsError(
431 { operation: "execute", command: "glab", cwd: input.cwd },
432 error,
433 ),
434 );
435
436 const executeMergeRequest = (input: {
437 readonly cwd: string;
438 readonly reference: string;
439 readonly args: ReadonlyArray<string>;
440 }) =>
441 run(input, (error) =>
442 GitLabMergeRequestNotFoundError.fromVcsError(
443 {
444 operation: "execute",
445 command: "glab",
446 cwd: input.cwd,
447 reference: input.reference,
448 },
449 error,
450 ),
451 );
452
453 return GitLabCli.of({
454 execute,
455 listMergeRequests: (input) =>
456 execute({
457 cwd: input.cwd,
458 args: [
459 "mr",
460 "list",
461 "--source-branch",
462 sourceRefName(input),
463 ...stateArgs(input.state),
464 "--per-page",
465 String(input.limit ?? 20),
466 "--output",
467 "json",
468 ],
469 }).pipe(
470 Effect.map((result) => result.stdout.trim()),
471 Effect.flatMap((raw) =>
472 raw.length === 0
473 ? Effect.succeed([])
474 : Effect.sync(() => decodeGitLabMergeRequestListJson(raw)).pipe(
475 Effect.flatMap((decoded) => {
476 if (!Result.isSuccess(decoded)) {
477 return Effect.fail(
478 new GitLabMergeRequestListDecodeError({
479 operation: "listMergeRequests",
480 command: "glab",
481 cwd: input.cwd,
482 cause: decoded.failure,
483 }),
484 );
485 }
486
487 return Effect.succeed(decoded.success.map(toSummaryWithOptionalUpdatedAt));
488 }),
489 ),
490 ),
491 ),
492 getMergeRequest: (input) =>
493 executeMergeRequest({
494 cwd: input.cwd,
495 reference: input.reference,
496 args: ["mr", "view", input.reference, "--output", "json"],
497 }).pipe(
498 Effect.map((result) => result.stdout.trim()),
499 Effect.flatMap((raw) =>
500 Effect.sync(() => decodeGitLabMergeRequestJson(raw)).pipe(
501 Effect.flatMap((decoded) => {
502 if (!Result.isSuccess(decoded)) {
503 return Effect.fail(
504 new GitLabMergeRequestDecodeError({
505 operation: "getMergeRequest",
506 command: "glab",
507 cwd: input.cwd,
508 reference: input.reference,
509 cause: decoded.failure,
510 }),
511 );
512 }
513
514 return Effect.succeed(toSummaryWithOptionalUpdatedAt(decoded.success));
515 }),
516 ),
517 ),
518 ),
519 getRepositoryCloneUrls: (input) =>
520 execute({
521 cwd: input.cwd,
522 args: ["api", `projects/${encodeURIComponent(input.repository)}`],
523 }).pipe(
524 Effect.map((result) => result.stdout.trim()),
525 Effect.flatMap((raw) =>
526 decodeGitLabRepositoryCloneUrls(raw).pipe(
527 Effect.mapError(
528 (cause) =>
529 new GitLabRepositoryDecodeError({
530 operation: "getRepositoryCloneUrls",
531 command: "glab",
532 cwd: input.cwd,
533 repository: input.repository,
534 cause,
535 }),
536 ),
537 ),
538 ),
539 Effect.map(normalizeRepositoryCloneUrls),
540 ),
541 createRepository: (input) => {
542 const { namespacePath, projectPath } = parseRepositoryPath(input.repository);
543 const namespaceId: Effect.Effect<number | null, GitLabCliError> = namespacePath
544 ? execute({
545 cwd: input.cwd,
546 args: ["api", `namespaces/${encodeURIComponent(namespacePath)}`],
547 }).pipe(
548 Effect.map((result) => result.stdout.trim()),
549 Effect.flatMap((raw) =>
550 decodeGitLabNamespace(raw).pipe(
551 Effect.mapError(
552 (cause) =>
553 new GitLabNamespaceDecodeError({
554 operation: "createRepository",
555 command: "glab",
556 cwd: input.cwd,
557 namespacePath,
558 cause,
559 }),
560 ),
561 ),
562 ),
563 Effect.map((namespace) => namespace.id),
564 )
565 : Effect.succeed(null);
566
567 return namespaceId.pipe(
568 Effect.flatMap((resolvedNamespaceId) =>
569 execute({
570 cwd: input.cwd,
571 args: [
572 "api",
573 "--method",
574 "POST",
575 "projects",
576 "--raw-field",
577 `path=${projectPath}`,
578 "--raw-field",
579 `name=${projectPath}`,
580 "--raw-field",
581 `visibility=${input.visibility}`,
582 ...(resolvedNamespaceId === null
583 ? []
584 : ["--raw-field", `namespace_id=${resolvedNamespaceId}`]),
585 ],
586 }),
587 ),
588 Effect.map((result) => result.stdout.trim()),
589 Effect.flatMap((raw) =>
590 decodeGitLabRepositoryCloneUrls(raw).pipe(
591 Effect.mapError(
592 (cause) =>
593 new GitLabRepositoryDecodeError({
594 operation: "createRepository",
595 command: "glab",
596 cwd: input.cwd,
597 repository: input.repository,
598 cause,
599 }),
600 ),
601 ),
602 ),
603 Effect.map(normalizeRepositoryCloneUrls),
604 );
605 },
606 createMergeRequest: (input) => {
607 const sourceProject = sourceProjectIdentifier(input.source);
608 return execute({
609 cwd: input.cwd,
610 args: [
611 "api",
612 "--method",
613 "POST",
614 "projects/:fullpath/merge_requests",
615 "--raw-field",
616 `source_branch=${sourceRefName(input)}`,
617 "--raw-field",
618 `target_branch=${input.target?.refName ?? input.baseBranch}`,
619 ...(sourceProject ? ["--raw-field", `source_project_id=${sourceProject}`] : []),
620 "--raw-field",
621 `title=${input.title}`,
622 "--field",
623 `description=@${input.bodyFile}`,
624 ],
625 }).pipe(Effect.asVoid);
626 },
627 getDefaultBranch: (input) =>
628 execute({
629 cwd: input.cwd,
630 args: ["api", "projects/:fullpath"],
631 }).pipe(
632 Effect.map((result) => result.stdout.trim()),
633 Effect.flatMap((raw) =>
634 decodeGitLabDefaultBranch(raw).pipe(
635 Effect.mapError(
636 (cause) =>
637 new GitLabRepositoryDecodeError({
638 operation: "getDefaultBranch",
639 command: "glab",
640 cwd: input.cwd,
641 cause,
642 }),
643 ),
644 ),
645 ),
646 Effect.map((value) => value.default_branch ?? null),
647 ),
648 checkoutMergeRequest: (input) =>
649 executeMergeRequest({
650 cwd: input.cwd,
651 reference: input.reference,
652 args: ["mr", "checkout", input.reference],
653 }).pipe(Effect.asVoid),
654 });
655});
656
657export const layer = Layer.effect(GitLabCli, make);