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