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