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