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