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

GitLabPullRequestCli.ts

1,389 lines50.9 KB

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