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