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

GitLabCli.ts

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