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