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