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