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