Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitLabCli.ts

677 lines21.3 KB

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