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

GitLabCli.ts

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