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

GitLabCli.ts

791 lines25.2 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Exit from "effect/Exit";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Match from "effect/Match";
7import * as Option from "effect/Option";
8import * as Result from "effect/Result";
9import * as Schema from "effect/Schema";
10import type * as DateTime from "effect/DateTime";
11​
12import {
13 TrimmedNonEmptyString,
14 type SourceControlRepositoryVisibility,
15 type VcsError,
16 type VcsProcessExitFailureKind,
17} from "@t3tools/contracts";
18​
19import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
20import {
21 decodeGitLabMergeRequestJson,
22 decodeGitLabMergeRequestListJson,
23} from "./gitLabMergeRequests.ts";
24import type * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
25​
26const DEFAULT_TIMEOUT_MS = 30_000;
27// GitLab allows ~1M-character descriptions; glab's JSON escaping (`\u003c`) can grow one sixfold.
28const MERGE_REQUEST_LIST_MAX_BYTES = 8_000_000;
29const decodeJsonArray = Schema.decodeUnknownExit(
30 Schema.fromJsonString(Schema.Array(Schema.Unknown)),
31);
32​
33const gitLabCliExecutionErrorContext = {
34 operation: Schema.Literal("execute"),
35 command: Schema.Literal("glab"),
36 cwd: Schema.String,
37 cause: Schema.Defect(),
38};
39​
40const gitLabCliDecodeErrorContext = {
41 command: Schema.Literal("glab"),
42 cwd: Schema.String,
43 cause: Schema.Defect(),
44};
45​
46export class GitLabCliUnavailableError extends Schema.TaggedError<GitLabCliUnavailableError>()(
47 "GitLabCliUnavailableError",
48 gitLabCliExecutionErrorContext,
49) {
50 get detail(): string {
51 return "GitLab CLI (`glab`) is required but not available on PATH.";
52 }
53​
54 override get message(): string {
55 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
56 }
58​
59export class GitLabCliAuthenticationError extends Schema.TaggedError<GitLabCliAuthenticationError>()(
60 "GitLabCliAuthenticationError",
61 gitLabCliExecutionErrorContext,
62) {
63 get detail(): string {
64 return "GitLab CLI is not authenticated. Run `glab auth login` and retry.";
65 }
66​
67 override get message(): string {
68 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
69 }
71​
72export class GitLabCliRateLimitError extends Schema.TaggedError<GitLabCliRateLimitError>()(
73 "GitLabCliRateLimitError",
74 gitLabCliExecutionErrorContext,
75) {
76 get detail(): string {
77 return "GitLab API rate limit exceeded.";
78 }
79​
80 override get message(): string {
81 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
82 }
84​
85export class GitLabMergeRequestNotFoundError extends Schema.TaggedError<GitLabMergeRequestNotFoundError>()(
86 "GitLabMergeRequestNotFoundError",
87 {
88 ...gitLabCliExecutionErrorContext,
89 reference: Schema.String,
90 },
91) {
92 get detail(): string {
93 return `Merge request ${this.reference} was not found. Check the MR number or URL and try again.`;
94 }
95​
96 override get message(): string {
97 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
98 }
99​
100 static fromVcsError(
101 context: {
102 readonly operation: "execute";
103 readonly command: "glab";
104 readonly cwd: string;
105 readonly reference: string;
106 },
107 error: VcsError,
108 ): GitLabCliError {
109 if (error._tag === "VcsProcessExitError" && error.failureKind === "not-found") {
110 return new GitLabMergeRequestNotFoundError({ ...context, cause: error });
111 }
112​
113 return GitLabCliCommandError.fromVcsError(
114 {
115 operation: context.operation,
116 command: context.command,
117 cwd: context.cwd,
118 },
119 error,
120 );
121 }
123​
124export class GitLabCliCommandError extends Schema.TaggedError<GitLabCliCommandError>()(
125 "GitLabCliCommandError",
126 gitLabCliExecutionErrorContext,
127) {
128 get detail(): string {
129 return "GitLab CLI command failed.";
130 }
131​
132 override get message(): string {
133 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
134 }
135​
136 static fromVcsError(
137 context: {
138 readonly operation: "execute";
139 readonly command: "glab";
140 readonly cwd: string;
141 },
142 error: VcsError,
143 ): GitLabCliError {
144 return Match.valueTags(error, {
145 VcsProcessSpawnError: (cause) => new GitLabCliUnavailableError({ ...context, cause }),
146 VcsProcessExitError: (cause) => {
147 switch (cause.failureKind) {
148 case "authentication":
149 return new GitLabCliAuthenticationError({ ...context, cause });
150 case "rate-limited":
151 return new GitLabCliRateLimitError({ ...context, cause });
152 case "not-found":
153 case "command-failed":
154 case undefined:
155 return new GitLabCliCommandError({ ...context, cause });
156 }
157 },
158 VcsProcessTimeoutError: (cause) => new GitLabCliCommandError({ ...context, cause }),
159 VcsProcessStdinWriteError: (cause) => new GitLabCliCommandError({ ...context, cause }),
160 VcsProcessOutputReadError: (cause) => new GitLabCliCommandError({ ...context, cause }),
161 VcsProcessOutputLimitError: (cause) => new GitLabCliCommandError({ ...context, cause }),
162 VcsProcessMissingExitCodeError: (cause) => new GitLabCliCommandError({ ...context, cause }),
163 VcsRepositoryDetectionError: (cause) => new GitLabCliCommandError({ ...context, cause }),
164 VcsCheckpointStorageError: (cause) => new GitLabCliCommandError({ ...context, cause }),
165 VcsUnsupportedOperationError: (cause) => new GitLabCliCommandError({ ...context, cause }),
166 });
167 }
169​
170export class GitLabMergeRequestListDecodeError extends Schema.TaggedError<GitLabMergeRequestListDecodeError>()(
171 "GitLabMergeRequestListDecodeError",
172 {
173 ...gitLabCliDecodeErrorContext,
174 operation: Schema.Literal("listMergeRequests"),
175 },
176) {
177 get detail(): string {
178 return "GitLab CLI returned invalid MR list JSON.";
179 }
180​
181 override get message(): string {
182 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
183 }
185​
186export class GitLabMergeRequestDecodeError extends Schema.TaggedError<GitLabMergeRequestDecodeError>()(
187 "GitLabMergeRequestDecodeError",
188 {
189 ...gitLabCliDecodeErrorContext,
190 operation: Schema.Literal("getMergeRequest"),
191 reference: Schema.String,
192 },
193) {
194 get detail(): string {
195 return "GitLab CLI returned invalid merge request JSON.";
196 }
197​
198 override get message(): string {
199 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
200 }
202​
203export class GitLabRepositoryDecodeError extends Schema.TaggedError<GitLabRepositoryDecodeError>()(
204 "GitLabRepositoryDecodeError",
205 {
206 ...gitLabCliDecodeErrorContext,
207 operation: Schema.Literals([
208 "getRepositoryCloneUrls",
209 "createRepository",
210 "getDefaultBranch",
211 "createMergeRequest",
212 ]),
213 repository: Schema.optional(Schema.String),
214 },
215) {
216 get detail(): string {
217 return "GitLab CLI returned invalid repository JSON.";
218 }
219​
220 override get message(): string {
221 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
222 }
224​
225export class GitLabNamespaceDecodeError extends Schema.TaggedError<GitLabNamespaceDecodeError>()(
226 "GitLabNamespaceDecodeError",
227 {
228 ...gitLabCliDecodeErrorContext,
229 operation: Schema.Literal("createRepository"),
230 namespacePath: Schema.String,
231 },
232) {
233 get detail(): string {
234 return "GitLab CLI returned invalid namespace JSON.";
235 }
236​
237 override get message(): string {
238 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
239 }
241​
242export class GitLabMergeRequestBodyReadError extends Schema.TaggedError<GitLabMergeRequestBodyReadError>()(
243 "GitLabMergeRequestBodyReadError",
244 {
245 operation: Schema.Literal("createMergeRequest"),
246 command: Schema.Literal("glab"),
247 cwd: Schema.String,
248 cause: Schema.Defect(),
249 },
250) {
251 get detail(): string {
252 return "The merge request description could not be read.";
253 }
254​
255 override get message(): string {
256 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
257 }
259​
260export const GitLabCliError = Schema.Union([
261 GitLabCliUnavailableError,
262 GitLabCliAuthenticationError,
263 GitLabCliRateLimitError,
264 GitLabMergeRequestNotFoundError,
265 GitLabCliCommandError,
266 GitLabMergeRequestListDecodeError,
267 GitLabMergeRequestDecodeError,
268 GitLabRepositoryDecodeError,
269 GitLabNamespaceDecodeError,
270 GitLabMergeRequestBodyReadError,
271]);
272export type GitLabCliError = typeof GitLabCliError.Type;
273​
274export interface GitLabMergeRequestSummary {
275 readonly number: number;
276 readonly title: string;
277 readonly url: string;
278 readonly baseRefName: string;
279 readonly headRefName: string;
280 readonly headSha?: string;
281 readonly state?: "open" | "closed" | "merged";
282 readonly isDraft?: boolean;
283 readonly closedAt?: string | null;
284 readonly mergedAt?: string | null;
285 readonly updatedAt?: Option.Option<DateTime.Utc>;
286 readonly isCrossRepository?: boolean;
287 readonly headRepositoryNameWithOwner?: string | null;
288 readonly headRepositoryOwnerLogin?: string | null;
290​
291export interface GitLabRepositoryCloneUrls {
292 readonly nameWithOwner: string;
293 readonly url: string;
294 readonly sshUrl: string;
296​
297export class GitLabCli extends Context.Service<
298 GitLabCli,
299 {
300 readonly execute: (input: {
301 readonly cwd: string;
302 readonly host?: string | undefined;
303 readonly args: ReadonlyArray<string>;
304 readonly timeoutMs?: number;
305 /** Keeps sensitive payloads out of argv. */
306 readonly stdin?: string;
307 readonly maxOutputBytes?: number;
308 }) => Effect.Effect<SourceControlHost.SourceControlProcessOutput, GitLabCliError>;
309​
310 readonly listMergeRequests: (input: {
311 readonly cwd: string;
312 readonly headSelector: string;
313 readonly source?: SourceControlProvider.SourceControlRefSelector;
314 readonly state: "open" | "closed" | "merged" | "all";
315 readonly limit?: number;
316 }) => Effect.Effect<ReadonlyArray<GitLabMergeRequestSummary>, GitLabCliError>;
317​
318 readonly getMergeRequest: (input: {
319 readonly cwd: string;
320 readonly reference: string;
321 }) => Effect.Effect<GitLabMergeRequestSummary, GitLabCliError>;
322​
323 readonly getRepositoryCloneUrls: (input: {
324 readonly cwd: string;
325 readonly repository: string;
326 }) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
327​
328 readonly createRepository: (input: {
329 readonly cwd: string;
330 readonly repository: string;
331 readonly visibility: SourceControlRepositoryVisibility;
332 }) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
333​
334 readonly createMergeRequest: (input: {
335 readonly cwd: string;
336 readonly baseBranch: string;
337 readonly headSelector: string;
338 readonly source?: SourceControlProvider.SourceControlRefSelector;
339 readonly target?: SourceControlProvider.SourceControlRefSelector;
340 readonly title: string;
341 readonly bodyFile: string;
342 }) => Effect.Effect<void, GitLabCliError>;
343​
344 readonly getDefaultBranch: (input: {
345 readonly cwd: string;
346 }) => Effect.Effect<string | null, GitLabCliError>;
347​
348 readonly checkoutMergeRequest: (input: {
349 readonly cwd: string;
350 readonly reference: string;
351 readonly force?: boolean;
352 }) => Effect.Effect<void, GitLabCliError>;
353 }
354>()("@t3tools/source-control-gitlab/server/GitLabCli") {}
355​
356const RawGitLabRepositoryCloneUrlsSchema = Schema.Struct({
357 path_with_namespace: TrimmedNonEmptyString,
358 web_url: TrimmedNonEmptyString,
359 http_url_to_repo: TrimmedNonEmptyString,
360 ssh_url_to_repo: TrimmedNonEmptyString,
361});
362​
363const RawGitLabDefaultBranchSchema = Schema.Struct({
364 default_branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
365});
366​
367const decodeGitLabMergeRequestProject = Schema.decodeEffect(
368 Schema.fromJsonString(Schema.Struct({ id: Schema.Number, path: TrimmedNonEmptyString })),
369);
370​
371const RawGitLabNamespaceSchema = Schema.Struct({
372 id: Schema.Number,
373});
374​
375const decodeGitLabRepositoryCloneUrls = Schema.decodeEffect(
376 Schema.fromJsonString(RawGitLabRepositoryCloneUrlsSchema),
377);
378const decodeGitLabDefaultBranch = Schema.decodeEffect(
379 Schema.fromJsonString(RawGitLabDefaultBranchSchema),
380);
381const decodeGitLabNamespace = Schema.decodeEffect(Schema.fromJsonString(RawGitLabNamespaceSchema));
382​
383function normalizeRepositoryCloneUrls(
384 raw: Schema.Schema.Type<typeof RawGitLabRepositoryCloneUrlsSchema>,
385): GitLabRepositoryCloneUrls {
386 return {
387 nameWithOwner: raw.path_with_namespace,
388 url: raw.web_url,
389 sshUrl: raw.ssh_url_to_repo,
390 };
392​
393function stateArgs(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
394 switch (state) {
395 case "open":
396 return [];
397 case "closed":
398 return ["--closed"];
399 case "merged":
400 return ["--merged"];
401 case "all":
402 return ["--all"];
403 }
405​
406function normalizeHeadSelector(headSelector: string): string {
407 const trimmed = headSelector.trim();
408 const ownerBranch = /^[^:]+:(.+)$/.exec(trimmed);
409 return ownerBranch?.[1]?.trim() || trimmed;
411​
412function sourceRefName(input: {
413 readonly headSelector: string;
414 readonly source?: SourceControlProvider.SourceControlRefSelector;
415}): string {
416 return input.source?.refName ?? normalizeHeadSelector(input.headSelector);
418​
419function toSummaryWithOptionalUpdatedAt(
420 record: GitLabMergeRequestSummary & {
421 readonly updatedAt: Option.Option<DateTime.Utc>;
422 },
423): GitLabMergeRequestSummary {
424 const { updatedAt, ...summary } = record;
425 return Option.isSome(updatedAt) ? { ...summary, updatedAt } : summary;
427​
428function parseRepositoryPath(repository: string): {
429 readonly namespacePath: string | null;
430 readonly projectPath: string;
431} {
432 const parts: Array<string> = [];
433 for (const part of repository.split("/")) {
434 const trimmed = part.trim();
435 if (trimmed.length > 0) {
436 parts.push(trimmed);
437 }
438 }
439 const projectPath = parts.at(-1) ?? repository.trim();
440 const namespacePath = parts.length > 1 ? parts.slice(0, -1).join("/") : null;
441 return { namespacePath, projectPath };
443​
444function parseRepositoryLookup(repository: string): {
445 readonly host: string | null;
446 readonly projectPath: string;
447} {
448 const trimmed = repository.trim();
449 if (!/^https?:\/\//i.test(trimmed)) return { host: null, projectPath: repository };
450 try {
451 const url = new URL(trimmed);
452 const projectPath = decodeURIComponent(url.pathname)
453 .replace(/\/-(?:\/.*)?$/, "")
454 .replace(/^\/+|\/+$/g, "")
455 .replace(/\.git$/, "");
456 return projectPath.length === 0
457 ? { host: null, projectPath: repository }
458 : { host: url.host, projectPath };
459 } catch {
460 return { host: null, projectPath: repository };
461 }
463​
464// glab prints a missing project or merge request as a bare 404, and an expired
465// OAuth login as an `invalid_grant` refresh failure without suggesting `glab auth login`.
466const classifyGlabFailure = (stderr: string): VcsProcessExitFailureKind | null => {
467 const normalized = stderr.toLowerCase();
468 if (normalized.includes("glab auth login") || normalized.includes("invalid_grant")) {
469 return "authentication";
470 }
471​
472 if (normalized.includes("not found") || normalized.includes("404")) {
473 return "not-found";
474 }
475​
476 return null;
477};
478​
479/** @public */
480export const make = Effect.gen(function* () {
481 const { process } = yield* SourceControlHost.SourceControlHost;
482 const fileSystem = yield* FileSystem.FileSystem;
483​
484 const run = (
485 input: Parameters<GitLabCli["Service"]["execute"]>[0],
486 mapError: (error: VcsError) => GitLabCliError,
487 ) =>
488 process
489 .run({
490 operation: "GitLabCli.execute",
491 command: "glab",
492 args: input.args,
493 cwd: input.cwd,
494 // glab may otherwise prefer a different checkout remote.
495 ...(input.host === undefined ? {} : { env: { GITLAB_HOST: input.host } }),
496 classifyFailure: classifyGlabFailure,
497 notFoundDetail: "Merge request not found.",
498 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
499 ...(input.stdin === undefined ? {} : { stdin: input.stdin }),
500 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
501 })
502 .pipe(Effect.mapError(mapError));
503​
504 const execute: GitLabCli["Service"]["execute"] = (input) =>
505 run(input, (error) =>
506 GitLabCliCommandError.fromVcsError(
507 { operation: "execute", command: "glab", cwd: input.cwd },
508 error,
509 ),
510 );
511​
512 const executeMergeRequest = (input: {
513 readonly cwd: string;
514 readonly reference: string;
515 readonly args: ReadonlyArray<string>;
516 }) =>
517 run(input, (error) =>
518 GitLabMergeRequestNotFoundError.fromVcsError(
519 {
520 operation: "execute",
521 command: "glab",
522 cwd: input.cwd,
523 reference: input.reference,
524 },
525 error,
526 ),
527 );
528​
529 return GitLabCli.of({
530 execute,
531 listMergeRequests: Effect.fn("GitLabCli.listMergeRequests")(function* (input) {
532 const limit = input.limit ?? 20;
533 let pageSize = limit;
534 let page = 1;
535 const items: GitLabMergeRequestSummary[] = [];
536 while (items.length < limit) {
537 const result = yield* execute({
538 cwd: input.cwd,
539 args: [
540 "mr",
541 "list",
542 "--source-branch",
543 sourceRefName(input),
544 ...stateArgs(input.state),
545 "--per-page",
546 String(pageSize),
547 ...(page > 1 ? ["--page", String(page)] : []),
548 "--output",
549 "json",
550 ],
551 maxOutputBytes: MERGE_REQUEST_LIST_MAX_BYTES,
552 });
553 if (result.stdoutTruncated && pageSize > 1) {
554 pageSize = Math.max(1, Math.floor(pageSize / 2));
555 page = 1;
556 items.length = 0;
557 continue;
558 }
559 const raw = result.stdout.trim();
560 if (raw.length === 0) break;
561 const decoded = decodeGitLabMergeRequestListJson(raw);
562 if (result.stdoutTruncated || !Result.isSuccess(decoded)) {
563 return yield* new GitLabMergeRequestListDecodeError({
564 operation: "listMergeRequests",
565 command: "glab",
566 cwd: input.cwd,
567 cause: Result.isFailure(decoded) ? decoded.failure : "MR list output was truncated",
568 });
569 }
570 items.push(...decoded.success.map(toSummaryWithOptionalUpdatedAt));
571 // Count raw entries: the decoder drops invalid ones, which would end paging early.
572 const entries = decodeJsonArray(raw);
573 if (
574 page * pageSize >= limit ||
575 (Exit.isSuccess(entries) && entries.value.length < pageSize)
576 ) {
577 break;
578 }
579 page += 1;
580 }
581 return items.slice(0, limit);
582 }),
583 getMergeRequest: Effect.fn("GitLabCli.getMergeRequest")(function (input) {
584 return executeMergeRequest({
585 cwd: input.cwd,
586 reference: input.reference,
587 args: ["mr", "view", "--output", "json", "--", input.reference],
588 }).pipe(
589 Effect.map((result) => result.stdout.trim()),
590 Effect.flatMap((raw) =>
591 Effect.sync(() => decodeGitLabMergeRequestJson(raw)).pipe(
592 Effect.flatMap((decoded) => {
593 if (!Result.isSuccess(decoded)) {
594 return Effect.fail(
595 new GitLabMergeRequestDecodeError({
596 operation: "getMergeRequest",
597 command: "glab",
598 cwd: input.cwd,
599 reference: input.reference,
600 cause: decoded.failure,
601 }),
602 );
603 }
604​
605 return Effect.succeed(toSummaryWithOptionalUpdatedAt(decoded.success));
606 }),
607 ),
608 ),
609 );
610 }),
611 getRepositoryCloneUrls: Effect.fn("GitLabCli.getRepositoryCloneUrls")(function (input) {
612 const { host, projectPath } = parseRepositoryLookup(input.repository);
613 return execute({
614 cwd: input.cwd,
615 args: [
616 "api",
617 ...(host === null ? [] : ["--hostname", host]),
618 `projects/${encodeURIComponent(projectPath)}`,
619 ],
620 }).pipe(
621 Effect.map((result) => result.stdout.trim()),
622 Effect.flatMap((raw) =>
623 decodeGitLabRepositoryCloneUrls(raw).pipe(
624 Effect.mapError(
625 (cause) =>
626 new GitLabRepositoryDecodeError({
627 operation: "getRepositoryCloneUrls",
628 command: "glab",
629 cwd: input.cwd,
630 repository: input.repository,
631 cause,
632 }),
633 ),
634 ),
635 ),
636 Effect.map(normalizeRepositoryCloneUrls),
637 );
638 }),
639 createRepository: Effect.fn("GitLabCli.createRepository")(function (input) {
640 const { namespacePath, projectPath } = parseRepositoryPath(input.repository);
641 const namespaceId: Effect.Effect<number | null, GitLabCliError> = namespacePath
642 ? execute({
643 cwd: input.cwd,
644 args: ["api", `namespaces/${encodeURIComponent(namespacePath)}`],
645 }).pipe(
646 Effect.map((result) => result.stdout.trim()),
647 Effect.flatMap((raw) =>
648 decodeGitLabNamespace(raw).pipe(
649 Effect.mapError(
650 (cause) =>
651 new GitLabNamespaceDecodeError({
652 operation: "createRepository",
653 command: "glab",
654 cwd: input.cwd,
655 namespacePath,
656 cause,
657 }),
658 ),
659 ),
660 ),
661 Effect.map((namespace) => namespace.id),
662 )
663 : Effect.succeed(null);
664​
665 return namespaceId.pipe(
666 Effect.flatMap((resolvedNamespaceId) =>
667 execute({
668 cwd: input.cwd,
669 args: [
670 "api",
671 "--method",
672 "POST",
673 "projects",
674 "--raw-field",
675 `path=${projectPath}`,
676 "--raw-field",
677 `name=${projectPath}`,
678 "--raw-field",
679 `visibility=${input.visibility}`,
680 ...(resolvedNamespaceId === null
681 ? []
682 : ["--raw-field", `namespace_id=${resolvedNamespaceId}`]),
683 ],
684 }),
685 ),
686 Effect.map((result) => result.stdout.trim()),
687 Effect.flatMap((raw) =>
688 decodeGitLabRepositoryCloneUrls(raw).pipe(
689 Effect.mapError(
690 (cause) =>
691 new GitLabRepositoryDecodeError({
692 operation: "createRepository",
693 command: "glab",
694 cwd: input.cwd,
695 repository: input.repository,
696 cause,
697 }),
698 ),
699 ),
700 ),
701 Effect.map(normalizeRepositoryCloneUrls),
702 );
703 }),
704 createMergeRequest: Effect.fn("GitLabCli.createMergeRequest")(function* (input) {
705 // A confined glab (Snap) has a private /tmp, so it cannot open the server's body file.
706 const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
707 Effect.mapError(
708 (cause) =>
709 new GitLabMergeRequestBodyReadError({
710 operation: "createMergeRequest",
711 command: "glab",
712 cwd: input.cwd,
713 cause,
714 }),
715 ),
716 );
717 let project = ":fullpath";
718 let targetProjectId: number | undefined;
719 if (input.source?.repository || input.source?.owner) {
720 const result = yield* execute({ cwd: input.cwd, args: ["api", "projects/:fullpath"] });
721 const targetProject = yield* decodeGitLabMergeRequestProject(result.stdout).pipe(
722 Effect.mapError(
723 (cause) =>
724 new GitLabRepositoryDecodeError({
725 operation: "createMergeRequest",
726 command: "glab",
727 cwd: input.cwd,
728 cause,
729 }),
730 ),
731 );
732 project = encodeURIComponent(
733 input.source.repository ?? `${input.source.owner}/${targetProject.path}`,
734 );
735 targetProjectId = targetProject.id;
736 }
737 yield* execute({
738 cwd: input.cwd,
739 args: [
740 "api",
741 "--method",
742 "POST",
743 `projects/${project}/merge_requests`,
744 "--raw-field",
745 `source_branch=${sourceRefName(input)}`,
746 "--raw-field",
747 `target_branch=${input.target?.refName ?? input.baseBranch}`,
748 ...(targetProjectId === undefined
749 ? []
750 : ["--raw-field", `target_project_id=${targetProjectId}`]),
751 "--raw-field",
752 `title=${input.title}`,
753 "--field",
754 "description=@-",
755 ],
756 stdin: description,
757 });
758 }),
759 getDefaultBranch: Effect.fn("GitLabCli.getDefaultBranch")(function (input) {
760 return execute({
761 cwd: input.cwd,
762 args: ["api", "projects/:fullpath"],
763 }).pipe(
764 Effect.map((result) => result.stdout.trim()),
765 Effect.flatMap((raw) =>
766 decodeGitLabDefaultBranch(raw).pipe(
767 Effect.mapError(
768 (cause) =>
769 new GitLabRepositoryDecodeError({
770 operation: "getDefaultBranch",
771 command: "glab",
772 cwd: input.cwd,
773 cause,
774 }),
775 ),
776 ),
777 ),
778 Effect.map((value) => value.default_branch ?? null),
779 );
780 }),
781 checkoutMergeRequest: Effect.fn("GitLabCli.checkoutMergeRequest")(function (input) {
782 return executeMergeRequest({
783 cwd: input.cwd,
784 reference: input.reference,
785 args: ["mr", "checkout", "--", input.reference],
786 }).pipe(Effect.asVoid);
787 }),
788 });
789});
790​
791export const layer = Layer.effect(GitLabCli, make);