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

GitLabCli.ts

757 lines24.2 KB

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