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

GitLabPullRequestCli.ts

1,493 lines51.3 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Result from "effect/Result";
5import * as Schema from "effect/Schema";
6import { resolvePullRequestAuthorFilter, VcsProcessExitError } from "@t3tools/contracts";
7import type {
8 PullRequestAction,
9 PullRequestActor,
10 PullRequestComment,
11 PullRequestCommit,
12 PullRequestInvolvement,
13 PullRequestLabel,
14 PullRequestListFilters,
15 PullRequestListState,
16 PullRequestMergeCapabilities,
17 PullRequestMergeMethod,
18 PullRequestReaction,
19 PullRequestReactionContent,
20 PullRequestReviewCommentDraft,
21 PullRequestReviewPosition,
22 PullRequestReviewThread,
23 PullRequestReviewVerdict,
24 PullRequestReviewerCandidateList,
25} from "@t3tools/contracts";
26​
27import * as GitLabCli from "./GitLabCli.ts";
28import {
29 AWARD_EMOJI_GRAPHQL_QUERY,
30 decodeAwardEmojiJson,
31 decodeCommitDiffRefsJson,
32 decodeCommitsJson,
33 decodeDiffRefsJson,
34 decodeDiscussionsJson,
35 decodeMergeRequestDetailJson,
36 decodeMergeRequestDiffsJson,
37 decodeMergeRequestChangesJson,
38 decodeMergeRequestListJson,
39 decodeNotesJson,
40 decodeOwnAwardIdJson,
41 decodeProjectMergeCapabilitiesJson,
42 decodeProjectLabelsJson,
43 decodeProjectUsersJson,
44 decodeRepositoryBlobsJson,
45 decodeViewerJson,
46 gitLabAwardName,
47 REPOSITORY_BLOBS_GRAPHQL_QUERY,
48 type GitLabDiffRefs,
49 type GitLabMergeRequestDetail,
50 type GitLabMergeRequestListItem,
51 type GitLabProjectUsers,
52} from "./gitLabMergeRequestJson.ts";
53import type { ProviderListCursor } from "@t3tools/source-control-core/server/PullRequestProvider";
54​
55export class GitLabMergeRequestReadError extends Schema.TaggedError<GitLabMergeRequestReadError>()(
56 "GitLabMergeRequestReadError",
57 {
58 command: Schema.Literal("glab"),
59 cwd: Schema.String,
60 operation: Schema.String,
61 cause: Schema.Defect(),
62 },
63) {
64 get detail(): string {
65 return `GitLab CLI returned an unreadable ${this.operation} response.`;
66 }
67​
68 override get message(): string {
69 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
70 }
72​
73export class GitLabViewerUnavailableError extends Schema.TaggedError<GitLabViewerUnavailableError>()(
74 "GitLabViewerUnavailableError",
75 {
76 command: Schema.Literal("glab"),
77 cwd: Schema.String,
78 },
79) {
80 get detail(): string {
81 return "GitLab CLI returned no username for the authenticated account.";
82 }
83​
84 override get message(): string {
85 return `GitLab CLI failed in getViewerUsername: ${this.detail}`;
86 }
88​
89export class GitLabDiffRefsUnavailableError extends Schema.TaggedError<GitLabDiffRefsUnavailableError>()(
90 "GitLabDiffRefsUnavailableError",
91 {
92 command: Schema.Literal("glab"),
93 cwd: Schema.String,
94 number: Schema.Int,
95 },
96) {
97 get detail(): string {
98 return "The merge request reported no diff revisions.";
99 }
100​
101 override get message(): string {
102 return `GitLab CLI failed in getDiffRefs: ${this.detail}`;
103 }
105​
106export class GitLabDiffCursorError extends Schema.TaggedError<GitLabDiffCursorError>()(
107 "GitLabDiffCursorError",
108 {
109 command: Schema.Literal("glab"),
110 cwd: Schema.String,
111 },
112) {
113 get detail(): string {
114 return "The diff cursor was not one this merge request handed out.";
115 }
116​
117 override get message(): string {
118 return `GitLab CLI failed in getMergeRequestDiff: ${this.detail}`;
119 }
121​
122export class GitLabDiffCommitError extends Schema.TaggedError<GitLabDiffCommitError>()(
123 "GitLabDiffCommitError",
124 {
125 command: Schema.Literal("glab"),
126 cwd: Schema.String,
127 },
128) {
129 get detail(): string {
130 return "The named commit was not a commit sha.";
131 }
132​
133 override get message(): string {
134 return `GitLab CLI failed in getMergeRequestDiff: ${this.detail}`;
135 }
137​
138export class GitLabDiffCommitParentUnavailableError extends Schema.TaggedError<GitLabDiffCommitParentUnavailableError>()(
139 "GitLabDiffCommitParentUnavailableError",
140 {
141 command: Schema.Literal("glab"),
142 cwd: Schema.String,
143 commit: Schema.String,
144 },
145) {
146 get detail(): string {
147 return `Commit ${this.commit} reported no parent revision.`;
148 }
149​
150 override get message(): string {
151 return `GitLab CLI failed in getMergeRequestDiffFileContents: ${this.detail}`;
152 }
154​
155export class GitLabDiffFileContentsUnavailableError extends Schema.TaggedError<GitLabDiffFileContentsUnavailableError>()(
156 "GitLabDiffFileContentsUnavailableError",
157 {
158 command: Schema.Literal("glab"),
159 cwd: Schema.String,
160 path: Schema.String,
161 reason: Schema.Literals(["oversized", "binary"]),
162 },
163) {
164 get detail(): string {
165 return this.reason === "oversized"
166 ? `The diff file '${this.path}' exceeds the 1 MB expansion limit.`
167 : `The diff file '${this.path}' is binary.`;
168 }
169​
170 override get message(): string {
171 return `GitLab CLI failed in getMergeRequestDiffFileContents: ${this.detail}`;
172 }
174​
175export type GitLabPullRequestCliError =
176 | GitLabCli.GitLabCliError
177 | GitLabMergeRequestReadError
178 | GitLabDiffCursorError
179 | GitLabDiffCommitError
180 | GitLabDiffCommitParentUnavailableError
181 | GitLabDiffFileContentsUnavailableError
182 | GitLabDiffRefsUnavailableError
183 | GitLabViewerUnavailableError;
184​
185/** GitLab's `per_page` limit. */
186const MAX_PAGE_SIZE = 100;
187const COMMIT_PAGE_SIZE = 100;
188/**
189 * GitLab 15.7 through 17.10 answer the merge request `/diffs` endpoint with a 500 for any
190 * `per_page` above 30 (fixed in 17.11), so those pages stay at a size every version accepts.
191 * A commit's own diff endpoint never had that bug and keeps the full page.
192 */
193const MERGE_REQUEST_DIFF_PAGE_SIZE = 30;
194const diffPageSize = (commit: string | undefined) =>
195 commit === undefined ? MERGE_REQUEST_DIFF_PAGE_SIZE : MAX_PAGE_SIZE;
196const CONVERSATION_PAGES = 10;
197const DIFF_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
198const DIFF_TIMEOUT_MS = 60_000;
199const isVcsProcessExitError = Schema.is(VcsProcessExitError);
200const DIFF_FILE_MAX_OUTPUT_BYTES = 1024 * 1024;
201​
202export interface GitLabMergeRequestListBatch {
203 readonly items: ReadonlyArray<GitLabMergeRequestListItem>;
204 readonly truncated: boolean;
205 readonly cursorAdvance: number;
207​
208export interface GitLabMergeRequestDiffSlice {
209 readonly patch: string;
210 readonly truncated: boolean;
211 readonly nextCursor: string | null;
213​
214export class GitLabPullRequestCli extends Context.Service<
215 GitLabPullRequestCli,
216 {
217 readonly getViewerUsername: (input: {
218 readonly cwd: string;
219 }) => Effect.Effect<string, GitLabPullRequestCliError>;
220​
221 readonly listMergeRequests: (input: {
222 readonly cwd: string;
223 readonly repository: string;
224 readonly state: PullRequestListState;
225 readonly involvement: PullRequestInvolvement;
226 readonly viewer: string;
227 readonly limit: number;
228 readonly query?: string | undefined;
229 readonly cursor?: ProviderListCursor | undefined;
230 readonly filters?: PullRequestListFilters | undefined;
231 }) => Effect.Effect<GitLabMergeRequestListBatch, GitLabPullRequestCliError>;
232​
233 readonly getMergeRequestDetail: (input: {
234 readonly cwd: string;
235 readonly repository: string;
236 readonly number: number;
237 }) => Effect.Effect<GitLabMergeRequestDetail, GitLabPullRequestCliError>;
238​
239 readonly listNotes: (input: {
240 readonly cwd: string;
241 readonly repository: string;
242 readonly number: number;
243 }) => Effect.Effect<
244 { readonly comments: ReadonlyArray<PullRequestComment>; readonly truncated: boolean },
245 GitLabPullRequestCliError
246 >;
247​
248 readonly listCommits: (input: {
249 readonly cwd: string;
250 readonly repository: string;
251 readonly number: number;
252 }) => Effect.Effect<ReadonlyArray<PullRequestCommit>, GitLabPullRequestCliError>;
253​
254 readonly getMergeRequestDiff: (input: {
255 readonly cwd: string;
256 readonly repository: string;
257 readonly number: number;
258 readonly cursor?: string | undefined;
259 readonly commit?: string | undefined;
260 }) => Effect.Effect<GitLabMergeRequestDiffSlice, GitLabPullRequestCliError>;
261​
262 readonly getMergeRequestDiffFileContents: (input: {
263 readonly cwd: string;
264 readonly repository: string;
265 readonly number: number;
266 readonly commit?: string | undefined;
267 readonly changeType: "change" | "rename-pure" | "rename-changed" | "new" | "deleted";
268 readonly oldPath: string;
269 readonly newPath: string;
270 }) => Effect.Effect<
271 { readonly oldContents: string; readonly newContents: string },
272 GitLabPullRequestCliError
273 >;
274​
275 readonly getProjectMergeCapabilities: (input: {
276 readonly cwd: string;
277 readonly repository: string;
278 }) => Effect.Effect<PullRequestMergeCapabilities, GitLabPullRequestCliError>;
279​
280 readonly getFileRevisions: (input: {
281 readonly cwd: string;
282 readonly repository: string;
283 readonly number: number;
284 readonly paths: ReadonlyArray<string>;
285 }) => Effect.Effect<ReadonlyMap<string, string>, GitLabPullRequestCliError>;
286​
287 readonly listReviewerCandidates: (input: {
288 readonly cwd: string;
289 readonly repository: string;
290 readonly number: number;
291 }) => Effect.Effect<PullRequestReviewerCandidateList, GitLabPullRequestCliError>;
292​
293 readonly listProjectLabels: (input: {
294 readonly cwd: string;
295 readonly repository: string;
296 readonly search?: string | undefined;
297 }) => Effect.Effect<
298 { readonly items: ReadonlyArray<PullRequestLabel>; readonly truncated: boolean },
299 GitLabPullRequestCliError
300 >;
301​
302 readonly listProjectUsers: (input: {
303 readonly cwd: string;
304 readonly repository: string;
305 readonly search?: string | undefined;
306 }) => Effect.Effect<
307 { readonly items: ReadonlyArray<PullRequestActor>; readonly truncated: boolean },
308 GitLabPullRequestCliError
309 >;
310​
311 readonly setReviewerRequest: (input: {
312 readonly cwd: string;
313 readonly repository: string;
314 readonly number: number;
315 readonly reviewers: ReadonlyArray<{ readonly id: string }>;
316 readonly requested: boolean;
317 }) => Effect.Effect<void, GitLabPullRequestCliError>;
318​
319 readonly runMergeRequestAction: (input: {
320 readonly cwd: string;
321 readonly repository: string;
322 readonly number: number;
323 readonly action: PullRequestAction;
324 readonly mergeMethod?: PullRequestMergeMethod;
325 }) => Effect.Effect<void, GitLabPullRequestCliError>;
326​
327 readonly updateMergeRequest: (input: {
328 readonly cwd: string;
329 readonly repository: string;
330 readonly number: number;
331 readonly title?: string | undefined;
332 readonly description?: string | undefined;
333 }) => Effect.Effect<void, GitLabPullRequestCliError>;
334​
335 readonly commentOnMergeRequest: (input: {
336 readonly cwd: string;
337 readonly repository: string;
338 readonly number: number;
339 readonly body: string;
340 }) => Effect.Effect<void, GitLabPullRequestCliError>;
341​
342 readonly updateNote: (input: {
343 readonly cwd: string;
344 readonly repository: string;
345 readonly number: number;
346 readonly noteId: string;
347 readonly body: string;
348 }) => Effect.Effect<void, GitLabPullRequestCliError>;
349​
350 readonly listDiscussions: (input: {
351 readonly cwd: string;
352 readonly repository: string;
353 readonly number: number;
354 }) => Effect.Effect<
355 { readonly threads: ReadonlyArray<PullRequestReviewThread>; readonly truncated: boolean },
356 GitLabPullRequestCliError
357 >;
358​
359 readonly submitReview: (input: {
360 readonly cwd: string;
361 readonly repository: string;
362 readonly number: number;
363 readonly verdict: PullRequestReviewVerdict;
364 readonly body: string;
365 readonly comments: ReadonlyArray<PullRequestReviewCommentDraft>;
366 }) => Effect.Effect<void, GitLabPullRequestCliError>;
367​
368 readonly replyToDiscussion: (input: {
369 readonly cwd: string;
370 readonly repository: string;
371 readonly number: number;
372 readonly discussionId: string;
373 readonly body: string;
374 }) => Effect.Effect<void, GitLabPullRequestCliError>;
375​
376 readonly setDiscussionResolution: (input: {
377 readonly cwd: string;
378 readonly repository: string;
379 readonly number: number;
380 readonly discussionId: string;
381 readonly resolved: boolean;
382 }) => Effect.Effect<void, GitLabPullRequestCliError>;
383​
384 readonly listReactions: (input: {
385 readonly cwd: string;
386 readonly repository: string;
387 readonly number: number;
388 }) => Effect.Effect<
389 {
390 readonly reactions: ReadonlyArray<PullRequestReaction>;
391 readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>;
392 },
393 GitLabPullRequestCliError
394 >;
395​
396 readonly setReaction: (input: {
397 readonly cwd: string;
398 readonly repository: string;
399 readonly number: number;
400 readonly noteId?: string | undefined;
401 readonly content: PullRequestReactionContent;
402 readonly reacted: boolean;
403 }) => Effect.Effect<void, GitLabPullRequestCliError>;
404 }
405>()("@t3tools/source-control-gitlab/server/GitLabPullRequestCli") {}
406​
407function projectPath(repository: string): string {
408 return encodeURIComponent(repository.trim());
410​
411function gitLabReviewPositionLines(
412 position: PullRequestReviewPosition,
413):
414 | { readonly new_line: number }
415 | { readonly old_line: number }
416 | { readonly old_line: number; readonly new_line: number } {
417 switch (position.kind) {
418 case "added":
419 return { new_line: position.newLine };
420 case "deleted":
421 return { old_line: position.oldLine };
422 case "context":
423 return { old_line: position.oldLine, new_line: position.newLine };
424 }
426​
427function stateParam(state: PullRequestListState): string {
428 return state === "open" ? "opened" : state;
430​
431function involvementParams(input: {
432 readonly involvement: PullRequestInvolvement;
433 readonly viewer: string;
434}): ReadonlyArray<readonly [string, string]> {
435 switch (input.involvement) {
436 case "authored":
437 return [["author_username", input.viewer]];
438 case "reviewing":
439 return [["reviewer_username", input.viewer]];
440 case "all":
441 return [];
442 }
444​
445/**
446 * GitLab's `labels` asks for every label it names, so only groups of one go to it; a group of
447 * alternatives is left for the service to narrow. A comma would split a name in two, and `None`
448 * and `Any` mean "unlabeled" and "labeled" to GitLab rather than labels of those names.
449 */
450function filterParams(input: {
451 readonly filters?: PullRequestListFilters | undefined;
452 readonly involvement: PullRequestInvolvement;
453 readonly viewer: string;
454}): ReadonlyArray<readonly [string, string]> {
455 const filters = input.filters;
456 if (filters === undefined) return [];
457 const listable = (names: ReadonlyArray<string>) =>
458 names.filter((name) => !name.includes(",") && !/^(?:none|any)$/iu.test(name.trim()));
459 const required = listable(
460 (filters.labels ?? []).flatMap((group) => (group.length === 1 ? group : [])),
461 );
462 const excluded = listable(filters.excludedLabels ?? []);
463 return [
464 ...(required.length === 0 ? [] : [["labels", required.join(",")] as const]),
465 ...(excluded.length === 0 ? [] : [["not[labels]", excluded.join(",")] as const]),
466 ...(filters.author === undefined || input.involvement === "authored"
467 ? []
468 : [
469 [
470 "author_username",
471 resolvePullRequestAuthorFilter(filters.author, input.viewer),
472 ] as const,
473 ]),
474 ...(filters.draft === undefined
475 ? []
476 : [["wip", filters.draft === "only" ? "yes" : "no"] as const]),
477 ];
479​
480function diffCursorPage(cursor: string): number | null {
481 return /^[1-9][0-9]{0,6}$/.test(cursor) ? Number(cursor) : null;
483​
484function isCommitSha(value: string): boolean {
485 return /^[0-9a-f]{7,64}$/i.test(value);
487​
488function searchParams(search: string | undefined): ReadonlyArray<readonly [string, string]> {
489 const trimmed = search?.trim() ?? "";
490 return trimmed.length === 0 ? [] : [["search", trimmed]];
492​
493function query(params: ReadonlyArray<readonly [string, string]>): string {
494 return params.map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&");
496​
497function actionArgs(
498 action: PullRequestAction,
499 mergeMethod: PullRequestMergeMethod | undefined,
500): ReadonlyArray<string> {
501 switch (action) {
502 case "merge":
503 return [
504 "merge",
505 // glab defaults to auto-merge during a running pipeline.
506 "--auto-merge=false",
507 "--yes",
508 ...(mergeMethod === "squash" ? ["--squash"] : []),
509 ];
510 case "enable-auto-merge":
511 return [
512 "merge",
513 "--auto-merge=true",
514 "--yes",
515 ...(mergeMethod === "squash" ? ["--squash"] : []),
516 ];
517 case "disable-auto-merge":
518 return [];
519 case "ready":
520 return ["update", "--ready"];
521 case "draft":
522 return ["update", "--draft"];
523 case "close":
524 return ["close"];
525 case "update-branch":
526 return ["rebase"];
527 case "reopen":
528 return ["reopen"];
529 case "revert":
530 case "approve-workflows":
531 case "delete-branch":
532 throw new Error(`GitLab merge request action ${action} is unsupported`);
533 }
535​
536/** @public */
537export const make = Effect.gen(function* () {
538 const gitlab = yield* GitLabCli.GitLabCli;
539​
540 const api = (input: {
541 readonly cwd: string;
542 readonly path: string;
543 readonly method?: string;
544 readonly stdin?: string;
545 readonly maxOutputBytes?: number;
546 readonly timeoutMs?: number;
547 }) =>
548 gitlab.execute({
549 cwd: input.cwd,
550 args: [
551 "api",
552 input.path,
553 ...(input.method === undefined ? [] : ["--method", input.method]),
554 // glab --input keeps payloads out of argv/logs but omits GitLab's required Content-Type.
555 ...(input.stdin === undefined
556 ? []
557 : ["--input", "-", "--header", "Content-Type: application/json"]),
558 ],
559 ...(input.stdin === undefined ? {} : { stdin: input.stdin }),
560 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
561 ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),
562 });
563​
564 const listPage = (input: {
565 readonly cwd: string;
566 readonly repository: string;
567 readonly state: PullRequestListState;
568 readonly involvement: PullRequestInvolvement;
569 readonly viewer: string;
570 readonly limit: number;
571 readonly query?: string | undefined;
572 readonly cursor?: ProviderListCursor | undefined;
573 readonly filters?: PullRequestListFilters | undefined;
574 readonly page: number;
575 readonly collected: ReadonlyArray<GitLabMergeRequestListItem>;
576 readonly cursorAdvance: number;
577 }): Effect.Effect<GitLabMergeRequestListBatch, GitLabPullRequestCliError> => {
578 // GitLab's timestamp filter can repeat equal-time pages forever; use offsets.
579 const delivered = input.cursor?.delivered ?? 0;
580 const perPage = Math.min(input.limit + 1, MAX_PAGE_SIZE);
581 const firstPage = Math.floor(delivered / perPage) + 1;
582 const skipOnFirstPage = input.page === firstPage ? delivered % perPage : 0;
583 // Bound raw pages to stop recursion on entirely malformed results.
584 const lastPage = Math.floor((delivered + input.limit) / perPage) + 1;
585 return api({
586 cwd: input.cwd,
587 path: `projects/${projectPath(input.repository)}/merge_requests?${query([
588 ["state", stateParam(input.state)],
589 ...involvementParams(input),
590 ...searchParams(input.query),
591 ...filterParams(input),
592 ["order_by", "updated_at"],
593 ["sort", "desc"],
594 ["per_page", String(perPage)],
595 ["page", String(input.page)],
596 ])}`,
597 }).pipe(
598 Effect.flatMap((result) => {
599 const raw = result.stdout.trim();
600 if (raw.length === 0) {
601 return Effect.succeed({
602 items: input.collected,
603 truncated: false,
604 cursorAdvance: input.cursorAdvance,
605 });
606 }
607 const decoded = decodeMergeRequestListJson(raw);
608 if (!Result.isSuccess(decoded)) {
609 return Effect.fail(
610 new GitLabMergeRequestReadError({
611 command: "glab",
612 cwd: input.cwd,
613 operation: "listMergeRequests",
614 cause: decoded.failure,
615 }),
616 );
617 }
618 const pageItems: GitLabMergeRequestListItem[] = [];
619 const pageRawIndexes: number[] = [];
620 for (const [index, item] of decoded.success.items.entries()) {
621 const rawIndex = decoded.success.rawIndexes[index]!;
622 if (rawIndex < skipOnFirstPage) continue;
623 pageItems.push(item);
624 pageRawIndexes.push(rawIndex);
625 }
626 const remaining = input.limit - input.collected.length;
627 const lastItemRawIndex = pageRawIndexes[remaining - 1];
628 if (lastItemRawIndex !== undefined) {
629 const consumed = lastItemRawIndex + 1 - skipOnFirstPage;
630 return Effect.succeed({
631 items: [...input.collected, ...pageItems.slice(0, remaining)],
632 truncated:
633 lastItemRawIndex + 1 < decoded.success.rawCount ||
634 decoded.success.rawCount === perPage,
635 cursorAdvance: input.cursorAdvance + consumed,
636 });
637 }
638 const collected = [...input.collected, ...pageItems];
639 const consumed = Math.max(0, decoded.success.rawCount - skipOnFirstPage);
640 // Count malformed rows to avoid ending pagination early.
641 const exhausted = decoded.success.rawCount < perPage;
642 if (exhausted) {
643 return Effect.succeed({
644 items: collected,
645 truncated: false,
646 cursorAdvance: input.cursorAdvance + consumed,
647 });
648 }
649 if (input.page >= lastPage) {
650 return Effect.succeed({
651 items: collected,
652 truncated: true,
653 cursorAdvance: input.cursorAdvance + consumed,
654 });
655 }
656 return listPage({
657 ...input,
658 page: input.page + 1,
659 collected,
660 cursorAdvance: input.cursorAdvance + consumed,
661 });
662 }),
663 );
664 };
665​
666 const diffPage = (input: {
667 readonly cwd: string;
668 readonly repository: string;
669 readonly number: number;
670 readonly page: number;
671 readonly commit?: string | undefined;
672 }): Effect.Effect<GitLabMergeRequestDiffSlice, GitLabPullRequestCliError> =>
673 api({
674 cwd: input.cwd,
675 path: `projects/${projectPath(input.repository)}/${
676 input.commit === undefined
677 ? `merge_requests/${input.number}/diffs`
678 : `repository/commits/${input.commit}/diff`
679 }?${query([
680 ["per_page", String(diffPageSize(input.commit))],
681 ["page", String(input.page)],
682 ])}`,
683 maxOutputBytes: DIFF_MAX_OUTPUT_BYTES,
684 timeoutMs: DIFF_TIMEOUT_MS,
685 }).pipe(
686 Effect.map((result) => ({ result, legacy: false })),
687 Effect.catchTags({
688 GitLabCliCommandError: (error) => {
689 if (
690 input.commit !== undefined ||
691 input.page !== 1 ||
692 !isVcsProcessExitError(error.cause) ||
693 error.cause.failureKind !== "not-found"
694 ) {
695 return Effect.fail(error);
696 }
697 // GitLab before 15.7 has no /diffs endpoint. /changes returns one complete slice.
698 return api({
699 cwd: input.cwd,
700 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/changes?access_raw_diffs=true`,
701 maxOutputBytes: DIFF_MAX_OUTPUT_BYTES,
702 timeoutMs: DIFF_TIMEOUT_MS,
703 }).pipe(Effect.map((result) => ({ result, legacy: true })));
704 },
705 }),
706 Effect.flatMap(({ result, legacy }) => {
707 // Returning no cursor for byte-truncated JSON would lose subsequent pages.
708 if (result.stdoutTruncated) {
709 return Effect.fail(
710 new GitLabMergeRequestReadError({
711 command: "glab",
712 cwd: input.cwd,
713 operation: "getMergeRequestDiff",
714 cause: new Error(
715 `Page ${input.page} of the merge request diff was too large to read.`,
716 ),
717 }),
718 );
719 }
720 const decoded = (legacy ? decodeMergeRequestChangesJson : decodeMergeRequestDiffsJson)(
721 result.stdout.trim(),
722 );
723 if (!Result.isSuccess(decoded)) {
724 return Effect.fail(
725 new GitLabMergeRequestReadError({
726 command: "glab",
727 cwd: input.cwd,
728 operation: "getMergeRequestDiff",
729 cause: decoded.failure,
730 }),
731 );
732 }
733 const patch = decoded.success.patch;
734 // Counted before decoding, so a page whose files all failed to decode still moves on
735 // rather than pointing the reader back at the page it just read.
736 const morePages = !legacy && decoded.success.rawCount >= diffPageSize(input.commit);
737 return Effect.succeed({
738 // Terminate slices so a hunkless header cannot run into the next slice.
739 patch: patch.length === 0 ? patch : patch.replace(/\n?$/, "\n"),
740 truncated: decoded.success.truncated,
741 nextCursor: morePages ? String(input.page + 1) : null,
742 });
743 }),
744 );
745​
746 const notesPage = (input: {
747 readonly cwd: string;
748 readonly repository: string;
749 readonly number: number;
750 readonly page: number;
751 readonly collected: ReadonlyArray<PullRequestComment>;
752 }): Effect.Effect<
753 { readonly comments: ReadonlyArray<PullRequestComment>; readonly truncated: boolean },
754 GitLabPullRequestCliError
755 > =>
756 api({
757 cwd: input.cwd,
758 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/notes?${query(
759 [
760 ["per_page", String(MAX_PAGE_SIZE)],
761 ["page", String(input.page)],
762 ["order_by", "created_at"],
763 ["sort", "asc"],
764 ],
765 )}`,
766 }).pipe(
767 Effect.flatMap((result) => {
768 const decoded = decodeNotesJson(result.stdout.trim());
769 if (!Result.isSuccess(decoded)) {
770 return Effect.fail(
771 new GitLabMergeRequestReadError({
772 command: "glab",
773 cwd: input.cwd,
774 operation: "listNotes",
775 cause: decoded.failure,
776 }),
777 );
778 }
779 const collected = [...input.collected, ...decoded.success.comments];
780 if (decoded.success.rawCount < MAX_PAGE_SIZE) {
781 return Effect.succeed({ comments: collected, truncated: false });
782 }
783 return input.page >= CONVERSATION_PAGES
784 ? Effect.succeed({ comments: collected, truncated: true })
785 : notesPage({ ...input, page: input.page + 1, collected });
786 }),
787 );
788​
789 const discussionsPage = (input: {
790 readonly cwd: string;
791 readonly repository: string;
792 readonly number: number;
793 readonly page: number;
794 readonly collected: ReadonlyArray<PullRequestReviewThread>;
795 }): Effect.Effect<
796 { readonly threads: ReadonlyArray<PullRequestReviewThread>; readonly truncated: boolean },
797 GitLabPullRequestCliError
798 > =>
799 api({
800 cwd: input.cwd,
801 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/discussions?${query(
802 [
803 ["per_page", String(MAX_PAGE_SIZE)],
804 ["page", String(input.page)],
805 ],
806 )}`,
807 }).pipe(
808 Effect.flatMap((result) => {
809 const decoded = decodeDiscussionsJson(result.stdout.trim());
810 if (!Result.isSuccess(decoded)) {
811 return Effect.fail(
812 new GitLabMergeRequestReadError({
813 command: "glab",
814 cwd: input.cwd,
815 operation: "listDiscussions",
816 cause: decoded.failure,
817 }),
818 );
819 }
820 const collected = [...input.collected, ...decoded.success.threads];
821 // Plain notes count toward the page size even when no positioned threads survive decoding.
822 if (decoded.success.rawCount < MAX_PAGE_SIZE) {
823 return Effect.succeed({ threads: collected, truncated: false });
824 }
825 return input.page >= CONVERSATION_PAGES
826 ? Effect.succeed({ threads: collected, truncated: true })
827 : discussionsPage({ ...input, page: input.page + 1, collected });
828 }),
829 );
830​
831 const getDiffRefs = (input: {
832 readonly cwd: string;
833 readonly repository: string;
834 readonly number: number;
835 }): Effect.Effect<GitLabDiffRefs, GitLabPullRequestCliError> =>
836 api({
837 cwd: input.cwd,
838 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`,
839 }).pipe(
840 Effect.flatMap((result): Effect.Effect<GitLabDiffRefs, GitLabPullRequestCliError> => {
841 const decoded = decodeDiffRefsJson(result.stdout.trim());
842 if (!Result.isSuccess(decoded)) {
843 return Effect.fail(
844 new GitLabMergeRequestReadError({
845 command: "glab",
846 cwd: input.cwd,
847 operation: "getDiffRefs",
848 cause: decoded.failure,
849 }),
850 );
851 }
852 return decoded.success === null
853 ? Effect.fail(
854 new GitLabDiffRefsUnavailableError({
855 command: "glab",
856 cwd: input.cwd,
857 number: input.number,
858 }),
859 )
860 : Effect.succeed(decoded.success);
861 }),
862 );
863​
864 const getCommitDiffRefs = (input: {
865 readonly cwd: string;
866 readonly repository: string;
867 readonly commit: string;
868 readonly allowRoot: boolean;
869 }): Effect.Effect<GitLabDiffRefs, GitLabPullRequestCliError> =>
870 api({
871 cwd: input.cwd,
872 path: `projects/${projectPath(input.repository)}/repository/commits/${input.commit}`,
873 }).pipe(
874 Effect.flatMap((result): Effect.Effect<GitLabDiffRefs, GitLabPullRequestCliError> => {
875 const decoded = decodeCommitDiffRefsJson(result.stdout.trim());
876 if (!Result.isSuccess(decoded)) {
877 return Effect.fail(
878 new GitLabMergeRequestReadError({
879 command: "glab",
880 cwd: input.cwd,
881 operation: "getMergeRequestDiffFileContents",
882 cause: decoded.failure,
883 }),
884 );
885 }
886 return decoded.success === null
887 ? input.allowRoot
888 ? Effect.succeed({
889 baseSha: "",
890 headSha: input.commit,
891 startSha: "",
892 })
893 : Effect.fail(
894 new GitLabDiffCommitParentUnavailableError({
895 command: "glab",
896 cwd: input.cwd,
897 commit: input.commit,
898 }),
899 )
900 : Effect.succeed(decoded.success);
901 }),
902 );
903​
904 const mergeRequestDetail = (input: {
905 readonly cwd: string;
906 readonly repository: string;
907 readonly number: number;
908 }): Effect.Effect<GitLabMergeRequestDetail, GitLabPullRequestCliError> =>
909 api({
910 cwd: input.cwd,
911 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}?${query([
912 ["include_diverged_commits_count", "true"],
913 ])}`,
914 }).pipe(
915 Effect.flatMap((result) => {
916 const decoded = decodeMergeRequestDetailJson(result.stdout.trim());
917 return Result.isSuccess(decoded)
918 ? Effect.succeed(decoded.success)
919 : Effect.fail(
920 new GitLabMergeRequestReadError({
921 command: "glab",
922 cwd: input.cwd,
923 operation: "getMergeRequestDetail",
924 cause: decoded.failure,
925 }),
926 );
927 }),
928 );
929​
930 const projectUsers = (input: {
931 readonly cwd: string;
932 readonly repository: string;
933 readonly search?: string | undefined;
934 }): Effect.Effect<GitLabProjectUsers, GitLabPullRequestCliError> =>
935 api({
936 cwd: input.cwd,
937 path: `projects/${projectPath(input.repository)}/users?${query([
938 ["per_page", String(MAX_PAGE_SIZE)],
939 ...searchParams(input.search),
940 ])}`,
941 }).pipe(
942 Effect.flatMap((result) => {
943 const decoded = decodeProjectUsersJson(result.stdout.trim());
944 return Result.isSuccess(decoded)
945 ? Effect.succeed(decoded.success)
946 : Effect.fail(
947 new GitLabMergeRequestReadError({
948 command: "glab",
949 cwd: input.cwd,
950 operation: "listReviewerCandidates",
951 cause: decoded.failure,
952 }),
953 );
954 }),
955 );
956​
957 const awardSubjectPath = (input: {
958 readonly repository: string;
959 readonly number: number;
960 readonly noteId?: string | undefined;
961 }) => {
962 const mergeRequest = `projects/${projectPath(input.repository)}/merge_requests/${input.number}`;
963 return input.noteId === undefined
964 ? `${mergeRequest}/award_emoji`
965 : `${mergeRequest}/notes/${encodeURIComponent(input.noteId)}/award_emoji`;
966 };
967​
968 const awardsPage = (input: {
969 readonly cwd: string;
970 readonly repository: string;
971 readonly number: number;
972 readonly cursor: string | null;
973 readonly page: number;
974 readonly collected: {
975 readonly reactions: ReadonlyArray<PullRequestReaction>;
976 readonly reactionsByNoteId: Map<string, ReadonlyArray<PullRequestReaction>>;
977 } | null;
978 }): Effect.Effect<
979 {
980 readonly reactions: ReadonlyArray<PullRequestReaction>;
981 readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>;
982 },
983 GitLabPullRequestCliError
984 > =>
985 api({
986 cwd: input.cwd,
987 path: "graphql",
988 method: "POST",
989 stdin: JSON.stringify({
990 query: AWARD_EMOJI_GRAPHQL_QUERY,
991 variables: {
992 fullPath: input.repository,
993 iid: String(input.number),
994 cursor: input.cursor,
995 },
996 }),
997 }).pipe(
998 Effect.flatMap((result) => {
999 const decoded = decodeAwardEmojiJson(result.stdout.trim());
1000 if (!Result.isSuccess(decoded)) {
1001 return Effect.fail(
1002 new GitLabMergeRequestReadError({
1003 command: "glab",
1004 cwd: input.cwd,
1005 operation: "listReactions",
1006 cause: decoded.failure,
1007 }),
1008 );
1010 const collected = input.collected ?? {
1011 reactions: decoded.success.reactions,
1012 reactionsByNoteId: new Map<string, ReadonlyArray<PullRequestReaction>>(),
1013 };
1014 for (const [id, reactions] of decoded.success.reactionsByNoteId)
1015 collected.reactionsByNoteId.set(id, reactions);
1016 return decoded.success.nextCursor === null || input.page >= CONVERSATION_PAGES
1017 ? Effect.succeed(collected)
1018 : awardsPage({
1019 ...input,
1020 cursor: decoded.success.nextCursor,
1021 page: input.page + 1,
1022 collected,
1023 });
1024 }),
1025 );
1026​
1027 // GitLab charges by path count and returns one connection page; respect both limits.
1028 const BLOB_PATHS_PER_REQUEST = 100;
1029​
1030 const blobsAt = (input: {
1031 readonly cwd: string;
1032 readonly repository: string;
1033 readonly ref: string;
1034 readonly paths: ReadonlyArray<string>;
1035 }): Effect.Effect<ReadonlyMap<string, string> | null, GitLabPullRequestCliError> =>
1036 api({
1037 cwd: input.cwd,
1038 path: "graphql",
1039 method: "POST",
1040 stdin: JSON.stringify({
1041 query: REPOSITORY_BLOBS_GRAPHQL_QUERY,
1042 variables: { fullPath: input.repository, ref: input.ref, paths: input.paths },
1043 }),
1044 }).pipe(
1045 Effect.flatMap(
1046 (result): Effect.Effect<ReadonlyMap<string, string> | null, GitLabPullRequestCliError> => {
1047 const decoded = decodeRepositoryBlobsJson(result.stdout.trim());
1048 return Result.isSuccess(decoded)
1049 ? Effect.succeed(decoded.success)
1050 : Effect.fail(
1051 new GitLabMergeRequestReadError({
1052 command: "glab",
1053 cwd: input.cwd,
1054 operation: "getFileRevisions",
1055 cause: decoded.failure,
1056 }),
1057 );
1058 },
1059 ),
1060 );
1061​
1062 const fileRevisions = (input: {
1063 readonly cwd: string;
1064 readonly repository: string;
1065 readonly number: number;
1066 readonly paths: ReadonlyArray<string>;
1067 }): Effect.Effect<ReadonlyMap<string, string>, GitLabPullRequestCliError> =>
1068 input.paths.length === 0
1069 ? Effect.succeed(new Map())
1070 : getDiffRefs(input).pipe(
1071 Effect.flatMap((refs) => {
1072 const batches: Array<ReadonlyArray<string>> = [];
1073 for (let at = 0; at < input.paths.length; at += BLOB_PATHS_PER_REQUEST) {
1074 batches.push(input.paths.slice(at, at + BLOB_PATHS_PER_REQUEST));
1076 return Effect.forEach(
1077 batches,
1078 (paths) =>
1079 blobsAt({ ...input, ref: refs.headSha, paths }).pipe(
1080 Effect.map((page) => ({ paths, page })),
1081 ),
1082 { concurrency: 2 },
1083 ).pipe(
1084 Effect.map((pages) => {
1085 const revisions = new Map<string, string>();
1086 for (const { paths, page } of pages) {
1087 // Unanswered paths are unknown; omit them to preserve viewed marks.
1088 if (page === null) continue;
1089 for (const [path, oid] of page) revisions.set(path, oid);
1090 for (const path of paths) {
1091 if (!revisions.has(path)) revisions.set(path, "");
1094 return revisions as ReadonlyMap<string, string>;
1095 }),
1096 );
1097 }),
1098 );
1099​
1100 const viewerUsername = (input: { readonly cwd: string }) =>
1101 api({ cwd: input.cwd, path: "user" }).pipe(
1102 Effect.flatMap((result): Effect.Effect<string, GitLabPullRequestCliError> => {
1103 const decoded = decodeViewerJson(result.stdout.trim());
1104 if (!Result.isSuccess(decoded)) {
1105 return Effect.fail(
1106 new GitLabMergeRequestReadError({
1107 command: "glab",
1108 cwd: input.cwd,
1109 operation: "getViewerUsername",
1110 cause: decoded.failure,
1111 }),
1112 );
1114 return decoded.success === null
1115 ? Effect.fail(new GitLabViewerUnavailableError({ command: "glab", cwd: input.cwd }))
1116 : Effect.succeed(decoded.success);
1117 }),
1118 );
1119​
1120 return GitLabPullRequestCli.of({
1121 getViewerUsername: viewerUsername,
1122​
1123 listMergeRequests: (input) => {
1124 const perPage = Math.min(input.limit + 1, MAX_PAGE_SIZE);
1125 const page = Math.floor((input.cursor?.delivered ?? 0) / perPage) + 1;
1126 return listPage({ ...input, page, collected: [], cursorAdvance: 0 });
1127 },
1128​
1129 getMergeRequestDetail: mergeRequestDetail,
1130​
1131 listNotes: (input) => notesPage({ ...input, page: 1, collected: [] }),
1132​
1133 listReactions: (input) => awardsPage({ ...input, cursor: null, page: 1, collected: null }),
1134​
1135 getFileRevisions: fileRevisions,
1136​
1137 setReaction: Effect.fn("GitLabPullRequestCli.setReaction")(function* (input) {
1138 const subject = awardSubjectPath(input);
1139 if (input.reacted) {
1140 yield* api({
1141 cwd: input.cwd,
1142 path: `${subject}?${query([["name", gitLabAwardName(input.content)]])}`,
1143 method: "POST",
1144 });
1145 return;
1147 // GitLab deletes an award by its id and takes no emoji name there, so the reader's own
1148 // award of that name is looked up first.
1149 const viewer = yield* viewerUsername({ cwd: input.cwd });
1150 const listed = yield* api({ cwd: input.cwd, path: subject });
1151 const own = decodeOwnAwardIdJson(listed.stdout.trim(), {
1152 content: input.content,
1153 viewer,
1154 });
1155 if (!Result.isSuccess(own)) {
1156 return yield* new GitLabMergeRequestReadError({
1157 command: "glab",
1158 cwd: input.cwd,
1159 operation: "setReaction",
1160 cause: own.failure,
1161 });
1163 if (own.success === null) return;
1164 yield* api({
1165 cwd: input.cwd,
1166 path: `${subject}/${own.success}`,
1167 method: "DELETE",
1168 });
1169 }),
1170​
1171 listCommits: (input) =>
1172 api({
1173 cwd: input.cwd,
1174 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/commits?${query(
1176 ["per_page", String(COMMIT_PAGE_SIZE)],
1177 ["with_stats", "true"],
1178 ],
1179 )}`,
1180 }).pipe(
1181 Effect.flatMap((result) => {
1182 const decoded = decodeCommitsJson(result.stdout.trim());
1183 return Result.isSuccess(decoded)
1184 ? Effect.succeed(decoded.success)
1185 : Effect.fail(
1186 new GitLabMergeRequestReadError({
1187 command: "glab",
1188 cwd: input.cwd,
1189 operation: "listCommits",
1190 cause: decoded.failure,
1191 }),
1192 );
1193 }),
1194 ),
1195​
1196 getMergeRequestDiff: (input) => {
1197 if (input.commit !== undefined && !isCommitSha(input.commit)) {
1198 return Effect.fail(new GitLabDiffCommitError({ command: "glab", cwd: input.cwd }));
1200 const target = {
1201 cwd: input.cwd,
1202 repository: input.repository,
1203 number: input.number,
1204 ...(input.commit === undefined ? {} : { commit: input.commit }),
1205 };
1206 if (input.cursor === undefined) {
1207 return diffPage({ ...target, page: 1 });
1209 const page = diffCursorPage(input.cursor);
1210 return page === null
1211 ? Effect.fail(new GitLabDiffCursorError({ command: "glab", cwd: input.cwd }))
1212 : diffPage({ ...target, page });
1213 },
1214​
1215 getMergeRequestDiffFileContents: Effect.fn(
1216 "GitLabPullRequestCli.getMergeRequestDiffFileContents",
1217 )(function* (input) {
1218 if (input.commit !== undefined && !isCommitSha(input.commit)) {
1219 return yield* new GitLabDiffCommitError({ command: "glab", cwd: input.cwd });
1221 const refs = yield* input.commit === undefined
1222 ? getDiffRefs(input)
1223 : getCommitDiffRefs({
1224 cwd: input.cwd,
1225 repository: input.repository,
1226 commit: input.commit,
1227 allowRoot: input.changeType === "new",
1228 });
1229​
1230 const readFile = (revision: string, filePath: string) =>
1231 api({
1232 cwd: input.cwd,
1233 path: `projects/${projectPath(input.repository)}/repository/files/${encodeURIComponent(
1234 filePath,
1235 )}/raw?ref=${encodeURIComponent(revision)}`,
1236 maxOutputBytes: DIFF_FILE_MAX_OUTPUT_BYTES,
1237 timeoutMs: DIFF_TIMEOUT_MS,
1238 }).pipe(
1239 Effect.flatMap((result) =>
1240 result.stdoutTruncated ||
1241 result.stdout.includes("\0") ||
1242 result.stdoutInvalidUtf8 === true
1243 ? Effect.fail(
1244 new GitLabDiffFileContentsUnavailableError({
1245 command: "glab",
1246 cwd: input.cwd,
1247 path: filePath,
1248 reason: result.stdoutTruncated ? "oversized" : "binary",
1249 }),
1251 : Effect.succeed(result.stdout),
1252 ),
1253 );
1254​
1255 const [oldContents, newContents] = yield* Effect.all(
1257 input.changeType === "new" ? Effect.succeed("") : readFile(refs.baseSha, input.oldPath),
1258 input.changeType === "deleted"
1259 ? Effect.succeed("")
1260 : readFile(refs.headSha, input.newPath),
1261 ],
1262 { concurrency: 2 },
1263 );
1264 return { oldContents, newContents };
1265 }),
1266​
1267 getProjectMergeCapabilities: (input) =>
1268 api({
1269 cwd: input.cwd,
1270 path: `projects/${projectPath(input.repository)}?license=false`,
1271 }).pipe(
1272 Effect.flatMap((result) => {
1273 const decoded = decodeProjectMergeCapabilitiesJson(result.stdout.trim());
1274 return Result.isSuccess(decoded)
1275 ? Effect.succeed(decoded.success)
1276 : Effect.fail(
1277 new GitLabMergeRequestReadError({
1278 command: "glab",
1279 cwd: input.cwd,
1280 operation: "getProjectMergeCapabilities",
1281 cause: decoded.failure,
1282 }),
1283 );
1284 }),
1285 ),
1286​
1287 listProjectLabels: (input) =>
1288 api({
1289 cwd: input.cwd,
1290 path: `projects/${projectPath(input.repository)}/labels?${query([
1291 ["per_page", String(MAX_PAGE_SIZE)],
1292 ...searchParams(input.search),
1293 ])}`,
1294 }).pipe(
1295 Effect.flatMap((result) => {
1296 const decoded = decodeProjectLabelsJson(result.stdout.trim());
1297 return Result.isSuccess(decoded)
1298 ? Effect.succeed({
1299 items: decoded.success.labels,
1300 truncated: decoded.success.rawCount >= MAX_PAGE_SIZE,
1301 })
1302 : Effect.fail(
1303 new GitLabMergeRequestReadError({
1304 command: "glab",
1305 cwd: input.cwd,
1306 operation: "listProjectLabels",
1307 cause: decoded.failure,
1308 }),
1309 );
1310 }),
1311 ),
1312​
1313 listProjectUsers: (input) =>
1314 projectUsers(input).pipe(
1315 Effect.map(({ candidates, rawCount }) => ({
1316 items: candidates.map(({ login, name, avatarUrl }) => ({ login, name, avatarUrl })),
1317 truncated: rawCount >= MAX_PAGE_SIZE,
1318 })),
1319 ),
1320​
1321 listReviewerCandidates: (input) =>
1322 Effect.all([mergeRequestDetail(input), projectUsers(input)], { concurrency: 2 }).pipe(
1323 Effect.map(([mergeRequest, users]) => {
1324 const author = mergeRequest.author?.login;
1325 const requested = new Set(mergeRequest.reviewRequestLogins);
1326 return {
1327 // GitLab forbids requesting a review from the MR author.
1328 candidates: users.candidates.flatMap((candidate) =>
1329 candidate.login === author
1330 ? []
1331 : [{ ...candidate, isRequested: requested.has(candidate.login) }],
1332 ),
1333 truncated: users.rawCount >= MAX_PAGE_SIZE,
1334 };
1335 }),
1336 ),
1337​
1338 setReviewerRequest: (input) =>
1339 mergeRequestDetail(input).pipe(
1340 Effect.flatMap((mergeRequest) => {
1341 // GitLab replaces reviewer_ids wholesale.
1342 const ids = new Set(mergeRequest.reviewerIds);
1343 for (const reviewer of input.reviewers) {
1344 const id = Number(reviewer.id);
1345 if (!Number.isSafeInteger(id) || id <= 0) continue;
1346 if (input.requested) ids.add(id);
1347 else ids.delete(id);
1349 return api({
1350 cwd: input.cwd,
1351 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`,
1352 method: "PUT",
1353 stdin: JSON.stringify({ reviewer_ids: [...ids] }),
1354 });
1355 }),
1356 Effect.asVoid,
1357 ),
1358​
1359 runMergeRequestAction: Effect.fn("GitLabPullRequestCli.runMergeRequestAction")(
1360 function* (input) {
1361 // `glab mr merge` arms auto-merge and never disarms it, so the one direction the CLI has
1362 // no flag for is asked of GitLab directly through the same `api` passthrough the rest of
1363 // this module writes with.
1364 if (input.action === "disable-auto-merge") {
1365 return yield* api({
1366 cwd: input.cwd,
1367 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/cancel_merge_when_pipeline_succeeds`,
1368 method: "POST",
1369 }).pipe(Effect.asVoid);
1371 const executeMr = (subcommand: string, ...flags: ReadonlyArray<string>) =>
1372 gitlab.execute({
1373 cwd: input.cwd,
1374 args: ["mr", subcommand, String(input.number), "--repo", input.repository, ...flags],
1375 });
1376 const [subcommand, ...flags] = actionArgs(input.action, input.mergeMethod);
1377 if (input.action === "merge" || input.action === "enable-auto-merge") {
1378 if (input.mergeMethod === "rebase") {
1379 // A rebase changes the source SHA, so wait for it before reading the merge guard.
1380 yield* executeMr("rebase");
1382 const refs = yield* getDiffRefs(input);
1383 flags.push("--sha", refs.headSha);
1385 yield* executeMr(subcommand!, ...flags);
1386 },
1387 ),
1388​
1389 updateMergeRequest: (input) =>
1390 api({
1391 cwd: input.cwd,
1392 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`,
1393 method: "PUT",
1394 // Omitted fields remain unchanged; empty values clear them.
1395 stdin: JSON.stringify({
1396 ...(input.title === undefined ? {} : { title: input.title }),
1397 ...(input.description === undefined ? {} : { description: input.description }),
1398 }),
1399 }).pipe(Effect.asVoid),
1400​
1401 commentOnMergeRequest: (input) =>
1402 api({
1403 cwd: input.cwd,
1404 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/notes`,
1405 method: "POST",
1406 // JSON avoids glab's coercion of numeric/boolean comment bodies.
1407 stdin: JSON.stringify({ body: input.body }),
1408 }).pipe(Effect.asVoid),
1409​
1410 updateNote: (input) =>
1411 api({
1412 cwd: input.cwd,
1413 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/notes/${encodeURIComponent(
1414 input.noteId,
1415 )}`,
1416 method: "PUT",
1417 stdin: JSON.stringify({ body: input.body }),
1418 }).pipe(Effect.asVoid),
1419​
1420 listDiscussions: (input) => discussionsPage({ ...input, page: 1, collected: [] }),
1421​
1422 submitReview: Effect.fn("GitLabPullRequestCli.submitReview")(function* (input) {
1423 const project = projectPath(input.repository);
1424 const mergeRequest = `projects/${project}/merge_requests/${input.number}`;
1425 // GitLab has no pending review to attach comments to, so a review is replayed as the
1426 // requests it is made of: the line comments, then the summary, then the verdict. A
1427 // failure part-way therefore leaves what was already posted in place, which is why
1428 // the verdict goes last — a half-sent review is never an approval.
1429 if (input.comments.length > 0) {
1430 const refs = yield* getDiffRefs(input);
1431 yield* Effect.forEach(
1432 input.comments,
1433 (comment) =>
1434 api({
1435 cwd: input.cwd,
1436 path: `${mergeRequest}/discussions`,
1437 method: "POST",
1438 stdin: JSON.stringify({
1439 body: comment.body,
1440 position: {
1441 base_sha: refs.baseSha,
1442 head_sha: refs.headSha,
1443 start_sha: refs.startSha,
1444 position_type: "text",
1445 // Both paths are sent because GitLab resolves a position against both
1446 // sides of the diff. They differ only for a renamed file, which is why the
1447 // draft carries the name the file had before the change.
1448 old_path: comment.oldPath ?? comment.path,
1449 new_path: comment.path,
1450 ...gitLabReviewPositionLines(comment.position),
1451 },
1452 }),
1453 }),
1454 { discard: true },
1455 );
1457 if (input.body.trim().length > 0) {
1458 yield* api({
1459 cwd: input.cwd,
1460 path: `${mergeRequest}/notes`,
1461 method: "POST",
1462 // @effect-diagnostics-next-line preferSchemaOverJson:off
1463 stdin: JSON.stringify({ body: input.body }),
1464 });
1466 if (input.verdict === "approve") {
1467 yield* api({ cwd: input.cwd, path: `${mergeRequest}/approve`, method: "POST" });
1469 }),
1470​
1471 replyToDiscussion: (input) =>
1472 api({
1473 cwd: input.cwd,
1474 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/discussions/${encodeURIComponent(
1475 input.discussionId,
1476 )}/notes`,
1477 method: "POST",
1478 stdin: JSON.stringify({ body: input.body }),
1479 }).pipe(Effect.asVoid),
1480​
1481 setDiscussionResolution: (input) =>
1482 api({
1483 cwd: input.cwd,
1484 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/discussions/${encodeURIComponent(
1485 input.discussionId,
1486 )}`,
1487 method: "PUT",
1488 stdin: JSON.stringify({ resolved: input.resolved }),
1489 }).pipe(Effect.asVoid),
1490 });
1491});
1492​
1493export const layer = Layer.effect(GitLabPullRequestCli, make);