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 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 }
67}
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 }
84}
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 }
103}
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 }
120}
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 }
137}
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 }
155}
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 }
176}
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;
207}
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;
215}
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());
402}
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 }
418}
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;
424}
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 }
438}
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;
447}
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);
456}
457
458function searchParams(search: string | undefined): ReadonlyArray<readonly [string, string]> {
459 const trimmed = search?.trim() ?? "";
460 return trimmed.length === 0 ? [] : [["search", trimmed]];
461}
462
463function query(params: ReadonlyArray<readonly [string, string]>): string {
464 return params.map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&");
465}
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 // Never reached: this host does not declare the action, so the service refuses it first.
508 case "revert":
509 case "approve-workflows":
510 throw new Error(`GitLab merge request action ${action} is unsupported`);
511 }
512}
513
514export const make = Effect.gen(function* () {
515 const gitlab = yield* GitLabCli.GitLabCli;
516
517 const api = (input: {
518 readonly cwd: string;
519 readonly path: string;
520 readonly method?: string;
521 readonly stdin?: string;
522 readonly maxOutputBytes?: number;
523 readonly timeoutMs?: number;
524 }) =>
525 gitlab.execute({
526 cwd: input.cwd,
527 args: [
528 "api",
529 input.path,
530 ...(input.method === undefined ? [] : ["--method", input.method]),
531 // A raw body from stdin: argv is visible in process listings and is echoed back
532 // inside process-runner failure messages. Unlike `gh`, `glab api --input` sends no
533 // Content-Type at all, and GitLab answers a bodyless content type with HTTP 415.
534 ...(input.stdin === undefined
535 ? []
536 : ["--input", "-", "--header", "Content-Type: application/json"]),
537 ],
538 ...(input.stdin === undefined ? {} : { stdin: input.stdin }),
539 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
540 ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),
541 });
542
543 /**
544 * `per_page` stops at 100, so a larger page is walked one request at a time. The walk is
545 * bounded twice over: it stops on a short page or once the extra row that reveals a next
546 * page has been read, and it never asks for more pages than the caller's page needs. The
547 * second bound is what makes it terminate when every row on a page fails to decode, which
548 * leaves nothing collected but does not mean GitLab has run out of rows.
549 */
550 const listPage = (input: {
551 readonly cwd: string;
552 readonly repository: string;
553 readonly state: PullRequestListState;
554 readonly involvement: PullRequestInvolvement;
555 readonly viewer: string;
556 readonly limit: number;
557 readonly query?: string | undefined;
558 readonly cursor?: ProviderListCursor | undefined;
559 readonly page: number;
560 readonly collected: ReadonlyArray<GitLabMergeRequestListItem>;
561 readonly cursorAdvance: number;
562 }): Effect.Effect<GitLabMergeRequestListBatch, GitLabPullRequestCliError> => {
563 // A continuation uses GitLab's offset pagination. Its timestamp filter is inclusive and has
564 // no tie-breaker, so a page where many rows share the boundary would otherwise return the
565 // same prefix forever. `delivered` is the stable offset the service has already handed over.
566 const delivered = input.cursor?.delivered ?? 0;
567 const perPage = Math.min(input.limit + 1, MAX_PAGE_SIZE);
568 const firstPage = Math.floor(delivered / perPage) + 1;
569 const skipOnFirstPage = input.page === firstPage ? delivered % perPage : 0;
570 // A page made entirely of malformed rows has no item from which the service can build a
571 // continuation. Bound the walk to the raw span this request asked for rather than recursing
572 // forever on a host that keeps returning full unusable pages.
573 const lastPage = Math.floor((delivered + input.limit) / perPage) + 1;
574 return api({
575 cwd: input.cwd,
576 path: `projects/${projectPath(input.repository)}/merge_requests?${query([
577 ["state", stateParam(input.state)],
578 ...involvementParams(input),
579 // The listing is read through `glab api` rather than `glab mr list`, so the search is
580 // the REST API's own `search` parameter — the one `mr list --search` passes on. It
581 // matches title and description, and travels URL-encoded like every other value here,
582 // so no text in it can become a parameter of its own.
583 ...searchParams(input.query),
584 ["order_by", "updated_at"],
585 ["sort", "desc"],
586 ["per_page", String(perPage)],
587 ["page", String(input.page)],
588 ])}`,
589 }).pipe(
590 Effect.flatMap((result) => {
591 const raw = result.stdout.trim();
592 if (raw.length === 0) {
593 return Effect.succeed({
594 items: input.collected,
595 truncated: false,
596 cursorAdvance: input.cursorAdvance,
597 });
598 }
599 const decoded = decodeMergeRequestListJson(raw);
600 if (!Result.isSuccess(decoded)) {
601 return Effect.fail(
602 new GitLabMergeRequestReadError({
603 command: "glab",
604 cwd: input.cwd,
605 operation: "listMergeRequests",
606 cause: decoded.failure,
607 }),
608 );
609 }
610 const pageItems: GitLabMergeRequestListItem[] = [];
611 const pageRawIndexes: number[] = [];
612 for (const [index, item] of decoded.success.items.entries()) {
613 const rawIndex = decoded.success.rawIndexes[index]!;
614 if (rawIndex < skipOnFirstPage) continue;
615 pageItems.push(item);
616 pageRawIndexes.push(rawIndex);
617 }
618 const remaining = input.limit - input.collected.length;
619 const lastItemRawIndex = pageRawIndexes[remaining - 1];
620 if (lastItemRawIndex !== undefined) {
621 const consumed = lastItemRawIndex + 1 - skipOnFirstPage;
622 return Effect.succeed({
623 items: [...input.collected, ...pageItems.slice(0, remaining)],
624 truncated:
625 lastItemRawIndex + 1 < decoded.success.rawCount ||
626 decoded.success.rawCount === perPage,
627 cursorAdvance: input.cursorAdvance + consumed,
628 });
629 }
630 const collected = [...input.collected, ...pageItems];
631 const consumed = Math.max(0, decoded.success.rawCount - skipOnFirstPage);
632 // Counted before decoding, so a skipped malformed row cannot end paging early.
633 const exhausted = decoded.success.rawCount < perPage;
634 if (exhausted) {
635 return Effect.succeed({
636 items: collected,
637 truncated: false,
638 cursorAdvance: input.cursorAdvance + consumed,
639 });
640 }
641 if (input.page >= lastPage) {
642 return Effect.succeed({
643 items: collected,
644 truncated: true,
645 cursorAdvance: input.cursorAdvance + consumed,
646 });
647 }
648 return listPage({
649 ...input,
650 page: input.page + 1,
651 collected,
652 cursorAdvance: input.cursorAdvance + consumed,
653 });
654 }),
655 );
656 };
657
658 /**
659 * One page of a merge request's files, as a patch that stands on its own. GitLab pages
660 * `/diffs` by offset and has no cursor of its own, so the page number is the cursor; the
661 * caller carries on from it for as long as GitLab keeps handing full pages back.
662 *
663 * A named commit is read from the commit's own diff, which answers in the same shape and pages
664 * the same way.
665 */
666 const diffPage = (input: {
667 readonly cwd: string;
668 readonly repository: string;
669 readonly number: number;
670 readonly page: number;
671 readonly commit?: string | undefined;
672 }): Effect.Effect<GitLabMergeRequestDiffSlice, GitLabPullRequestCliError> =>
673 api({
674 cwd: input.cwd,
675 path: `projects/${projectPath(input.repository)}/${
676 input.commit === undefined
677 ? `merge_requests/${input.number}/diffs`
678 : `repository/commits/${input.commit}/diff`
679 }?${query([
680 ["per_page", String(MAX_PAGE_SIZE)],
681 ["page", String(input.page)],
682 ])}`,
683 maxOutputBytes: DIFF_MAX_OUTPUT_BYTES,
684 timeoutMs: DIFF_TIMEOUT_MS,
685 }).pipe(
686 Effect.flatMap((result) => {
687 // A byte-truncated response is a JSON prefix, so this page cannot be read at all.
688 // Answering with no cursor would call the diff whole while silently dropping this page
689 // and every one after it, so the read fails and says which page could not be had.
690 if (result.stdoutTruncated) {
691 return Effect.fail(
692 new GitLabMergeRequestReadError({
693 command: "glab",
694 cwd: input.cwd,
695 operation: "getMergeRequestDiff",
696 cause: new Error(
697 `Page ${input.page} of the merge request diff was too large to read.`,
698 ),
699 }),
700 );
701 }
702 const decoded = decodeMergeRequestDiffsJson(result.stdout.trim());
703 if (!Result.isSuccess(decoded)) {
704 return Effect.fail(
705 new GitLabMergeRequestReadError({
706 command: "glab",
707 cwd: input.cwd,
708 operation: "getMergeRequestDiff",
709 cause: decoded.failure,
710 }),
711 );
712 }
713 const patch = decoded.success.patch;
714 // Counted before decoding, so a page whose files all failed to decode still moves on
715 // rather than pointing the reader back at the page it just read.
716 const morePages = decoded.success.rawCount >= MAX_PAGE_SIZE;
717 return Effect.succeed({
718 // The slice ends on a newline, so a file GitLab gave a header and no hunks for does
719 // not run into the first line of the next slice.
720 patch: patch.length === 0 ? patch : patch.replace(/\n?$/, "\n"),
721 truncated: decoded.success.truncated,
722 nextCursor: morePages ? String(input.page + 1) : null,
723 });
724 }),
725 );
726
727 /**
728 * The conversation, a page at a time. GitLab pages by offset and reports no total, so a short
729 * page is the only thing that says it is done — and the raw count decides, not the kept one:
730 * the notes GitLab wrote itself are dropped, and a whole page of them still means there is
731 * more to read.
732 */
733 const notesPage = (input: {
734 readonly cwd: string;
735 readonly repository: string;
736 readonly number: number;
737 readonly page: number;
738 readonly collected: ReadonlyArray<PullRequestComment>;
739 }): Effect.Effect<
740 { readonly comments: ReadonlyArray<PullRequestComment>; readonly truncated: boolean },
741 GitLabPullRequestCliError
742 > =>
743 api({
744 cwd: input.cwd,
745 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/notes?${query(
746 [
747 ["per_page", String(MAX_PAGE_SIZE)],
748 ["page", String(input.page)],
749 ["order_by", "created_at"],
750 ["sort", "asc"],
751 ],
752 )}`,
753 }).pipe(
754 Effect.flatMap((result) => {
755 const decoded = decodeNotesJson(result.stdout.trim());
756 if (!Result.isSuccess(decoded)) {
757 return Effect.fail(
758 new GitLabMergeRequestReadError({
759 command: "glab",
760 cwd: input.cwd,
761 operation: "listNotes",
762 cause: decoded.failure,
763 }),
764 );
765 }
766 const collected = [...input.collected, ...decoded.success.comments];
767 if (decoded.success.rawCount < MAX_PAGE_SIZE) {
768 return Effect.succeed({ comments: collected, truncated: false });
769 }
770 return input.page >= CONVERSATION_PAGES
771 ? Effect.succeed({ comments: collected, truncated: true })
772 : notesPage({ ...input, page: input.page + 1, collected });
773 }),
774 );
775
776 /** The positioned discussions, walked the same way and stopped by the same bound. */
777 const discussionsPage = (input: {
778 readonly cwd: string;
779 readonly repository: string;
780 readonly number: number;
781 readonly page: number;
782 readonly collected: ReadonlyArray<PullRequestReviewThread>;
783 }): Effect.Effect<
784 { readonly threads: ReadonlyArray<PullRequestReviewThread>; readonly truncated: boolean },
785 GitLabPullRequestCliError
786 > =>
787 api({
788 cwd: input.cwd,
789 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/discussions?${query(
790 [
791 ["per_page", String(MAX_PAGE_SIZE)],
792 ["page", String(input.page)],
793 ],
794 )}`,
795 }).pipe(
796 Effect.flatMap((result) => {
797 const decoded = decodeDiscussionsJson(result.stdout.trim());
798 if (!Result.isSuccess(decoded)) {
799 return Effect.fail(
800 new GitLabMergeRequestReadError({
801 command: "glab",
802 cwd: input.cwd,
803 operation: "listDiscussions",
804 cause: decoded.failure,
805 }),
806 );
807 }
808 const collected = [...input.collected, ...decoded.success.threads];
809 // The raw count again: this endpoint returns the plain notes too, so a full page of
810 // those is not the end of the positioned ones.
811 if (decoded.success.rawCount < MAX_PAGE_SIZE) {
812 return Effect.succeed({ threads: collected, truncated: false });
813 }
814 return input.page >= CONVERSATION_PAGES
815 ? Effect.succeed({ threads: collected, truncated: true })
816 : discussionsPage({ ...input, page: input.page + 1, collected });
817 }),
818 );
819
820 /**
821 * The revisions a positioned comment is written against. GitLab resolves a comment's line
822 * against these three shas, so a review with line comments cannot be sent without them.
823 */
824 const getDiffRefs = (input: {
825 readonly cwd: string;
826 readonly repository: string;
827 readonly number: number;
828 }): Effect.Effect<GitLabDiffRefs, GitLabPullRequestCliError> =>
829 api({
830 cwd: input.cwd,
831 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`,
832 }).pipe(
833 Effect.flatMap((result): Effect.Effect<GitLabDiffRefs, GitLabPullRequestCliError> => {
834 const decoded = decodeDiffRefsJson(result.stdout.trim());
835 if (!Result.isSuccess(decoded)) {
836 return Effect.fail(
837 new GitLabMergeRequestReadError({
838 command: "glab",
839 cwd: input.cwd,
840 operation: "getDiffRefs",
841 cause: decoded.failure,
842 }),
843 );
844 }
845 // A merge request with no diff refs is a well-formed answer that cannot carry a
846 // positioned comment — a dead end, but not something that failed to be read.
847 return decoded.success === null
848 ? Effect.fail(
849 new GitLabDiffRefsUnavailableError({
850 command: "glab",
851 cwd: input.cwd,
852 number: input.number,
853 }),
854 )
855 : Effect.succeed(decoded.success);
856 }),
857 );
858
859 const getCommitDiffRefs = (input: {
860 readonly cwd: string;
861 readonly repository: string;
862 readonly commit: string;
863 readonly allowRoot: boolean;
864 }): Effect.Effect<GitLabDiffRefs, GitLabPullRequestCliError> =>
865 api({
866 cwd: input.cwd,
867 path: `projects/${projectPath(input.repository)}/repository/commits/${input.commit}`,
868 }).pipe(
869 Effect.flatMap((result): Effect.Effect<GitLabDiffRefs, GitLabPullRequestCliError> => {
870 const decoded = decodeCommitDiffRefsJson(result.stdout.trim());
871 if (!Result.isSuccess(decoded)) {
872 return Effect.fail(
873 new GitLabMergeRequestReadError({
874 command: "glab",
875 cwd: input.cwd,
876 operation: "getMergeRequestDiffFileContents",
877 cause: decoded.failure,
878 }),
879 );
880 }
881 return decoded.success === null
882 ? input.allowRoot
883 ? Effect.succeed({
884 baseSha: "",
885 headSha: input.commit,
886 startSha: "",
887 })
888 : Effect.fail(
889 new GitLabDiffCommitParentUnavailableError({
890 command: "glab",
891 cwd: input.cwd,
892 commit: input.commit,
893 }),
894 )
895 : Effect.succeed(decoded.success);
896 }),
897 );
898
899 /**
900 * The merge request itself, which several calls need for different parts of it: the detail for
901 * everything, and the reviewer paths for the ids GitLab writes a reviewer set with.
902 */
903 const mergeRequestDetail = (input: {
904 readonly cwd: string;
905 readonly repository: string;
906 readonly number: number;
907 }): Effect.Effect<GitLabMergeRequestDetail, GitLabPullRequestCliError> =>
908 api({
909 cwd: input.cwd,
910 // How far behind the target branch this one is comes only when asked for by name, and it
911 // is asked for here rather than on a second read because it is the same merge request.
912 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}?${query([
913 ["include_diverged_commits_count", "true"],
914 ])}`,
915 }).pipe(
916 Effect.flatMap((result) => {
917 const decoded = decodeMergeRequestDetailJson(result.stdout.trim());
918 return Result.isSuccess(decoded)
919 ? Effect.succeed(decoded.success)
920 : Effect.fail(
921 new GitLabMergeRequestReadError({
922 command: "glab",
923 cwd: input.cwd,
924 operation: "getMergeRequestDetail",
925 cause: decoded.failure,
926 }),
927 );
928 }),
929 );
930
931 /** The people with access to the project, one page deep. */
932 const projectUsers = (input: {
933 readonly cwd: string;
934 readonly repository: string;
935 }): Effect.Effect<GitLabProjectUsers, GitLabPullRequestCliError> =>
936 api({
937 cwd: input.cwd,
938 path: `projects/${projectPath(input.repository)}/users?${query([
939 ["per_page", String(MAX_PAGE_SIZE)],
940 ])}`,
941 }).pipe(
942 Effect.flatMap((result) => {
943 const decoded = decodeProjectUsersJson(result.stdout.trim());
944 return Result.isSuccess(decoded)
945 ? Effect.succeed(decoded.success)
946 : Effect.fail(
947 new GitLabMergeRequestReadError({
948 command: "glab",
949 cwd: input.cwd,
950 operation: "listReviewerCandidates",
951 cause: decoded.failure,
952 }),
953 );
954 }),
955 );
956
957 /** Where an award is written: a note of the merge request, or the merge request itself. */
958 const awardSubjectPath = (input: {
959 readonly repository: string;
960 readonly number: number;
961 readonly noteId?: string | undefined;
962 }) => {
963 const mergeRequest = `projects/${projectPath(input.repository)}/merge_requests/${input.number}`;
964 return input.noteId === undefined
965 ? `${mergeRequest}/award_emoji`
966 : `${mergeRequest}/notes/${encodeURIComponent(input.noteId)}/award_emoji`;
967 };
968
969 /**
970 * The awards on the merge request and its notes, a page of notes at a time. Bounded by the same
971 * count as the conversation itself: awards past the notes that were read belong to notes the
972 * page is not showing.
973 */
974 const awardsPage = (input: {
975 readonly cwd: string;
976 readonly repository: string;
977 readonly number: number;
978 readonly cursor: string | null;
979 readonly page: number;
980 readonly collected: {
981 readonly reactions: ReadonlyArray<PullRequestReaction>;
982 readonly reactionsByNoteId: Map<string, ReadonlyArray<PullRequestReaction>>;
983 } | null;
984 }): Effect.Effect<
985 {
986 readonly reactions: ReadonlyArray<PullRequestReaction>;
987 readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>;
988 },
989 GitLabPullRequestCliError
990 > =>
991 api({
992 cwd: input.cwd,
993 path: "graphql",
994 method: "POST",
995 stdin: JSON.stringify({
996 query: AWARD_EMOJI_GRAPHQL_QUERY,
997 variables: {
998 fullPath: input.repository,
999 iid: String(input.number),
1000 cursor: input.cursor,
1001 },
1002 }),
1003 }).pipe(
1004 Effect.flatMap((result) => {
1005 const decoded = decodeAwardEmojiJson(result.stdout.trim());
1006 if (!Result.isSuccess(decoded)) {
1007 return Effect.fail(
1008 new GitLabMergeRequestReadError({
1009 command: "glab",
1010 cwd: input.cwd,
1011 operation: "listReactions",
1012 cause: decoded.failure,
1013 }),
1014 );
1015 }
1016 const collected = input.collected ?? {
1017 reactions: decoded.success.reactions,
1018 reactionsByNoteId: new Map<string, ReadonlyArray<PullRequestReaction>>(),
1019 };
1020 for (const [id, reactions] of decoded.success.reactionsByNoteId)
1021 collected.reactionsByNoteId.set(id, reactions);
1022 return decoded.success.nextCursor === null || input.page >= CONVERSATION_PAGES
1023 ? Effect.succeed(collected)
1024 : awardsPage({
1025 ...input,
1026 cursor: decoded.success.nextCursor,
1027 page: input.page + 1,
1028 collected,
1029 });
1030 }),
1031 );
1032
1033 const viewerUsername = (input: { readonly cwd: string }) =>
1034 api({ cwd: input.cwd, path: "user" }).pipe(
1035 Effect.flatMap((result): Effect.Effect<string, GitLabPullRequestCliError> => {
1036 const decoded = decodeViewerJson(result.stdout.trim());
1037 if (!Result.isSuccess(decoded)) {
1038 return Effect.fail(
1039 new GitLabMergeRequestReadError({
1040 command: "glab",
1041 cwd: input.cwd,
1042 operation: "getViewerUsername",
1043 cause: decoded.failure,
1044 }),
1045 );
1046 }
1047 return decoded.success === null
1048 ? Effect.fail(new GitLabViewerUnavailableError({ command: "glab", cwd: input.cwd }))
1049 : Effect.succeed(decoded.success);
1050 }),
1051 );
1052
1053 return GitLabPullRequestCli.of({
1054 getViewerUsername: viewerUsername,
1055
1056 listMergeRequests: (input) => {
1057 const perPage = Math.min(input.limit + 1, MAX_PAGE_SIZE);
1058 const page = Math.floor((input.cursor?.delivered ?? 0) / perPage) + 1;
1059 return listPage({ ...input, page, collected: [], cursorAdvance: 0 });
1060 },
1061
1062 getMergeRequestDetail: mergeRequestDetail,
1063
1064 listNotes: (input) => notesPage({ ...input, page: 1, collected: [] }),
1065
1066 listReactions: (input) => awardsPage({ ...input, cursor: null, page: 1, collected: null }),
1067
1068 setReaction: (input) =>
1069 Effect.gen(function* () {
1070 const subject = awardSubjectPath(input);
1071 if (input.reacted) {
1072 yield* api({
1073 cwd: input.cwd,
1074 path: `${subject}?${query([["name", gitLabAwardName(input.content)]])}`,
1075 method: "POST",
1076 });
1077 return;
1078 }
1079 // GitLab deletes an award by its id and takes no emoji name there, so the reader's own
1080 // award of that name is looked up first. Nothing to delete is success: the reaction the
1081 // caller asked to take back is already gone.
1082 const viewer = yield* viewerUsername({ cwd: input.cwd });
1083 const listed = yield* api({ cwd: input.cwd, path: subject });
1084 const own = decodeOwnAwardIdJson(listed.stdout.trim(), {
1085 content: input.content,
1086 viewer,
1087 });
1088 if (!Result.isSuccess(own)) {
1089 return yield* new GitLabMergeRequestReadError({
1090 command: "glab",
1091 cwd: input.cwd,
1092 operation: "setReaction",
1093 cause: own.failure,
1094 });
1095 }
1096 if (own.success === null) return;
1097 yield* api({
1098 cwd: input.cwd,
1099 path: `${subject}/${own.success}`,
1100 method: "DELETE",
1101 });
1102 }),
1103
1104 listCommits: (input) =>
1105 api({
1106 cwd: input.cwd,
1107 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/commits?${query(
1108 [
1109 ["per_page", String(COMMIT_PAGE_SIZE)],
1110 ["with_stats", "true"],
1111 ],
1112 )}`,
1113 }).pipe(
1114 Effect.flatMap((result) => {
1115 const decoded = decodeCommitsJson(result.stdout.trim());
1116 return Result.isSuccess(decoded)
1117 ? Effect.succeed(decoded.success)
1118 : Effect.fail(
1119 new GitLabMergeRequestReadError({
1120 command: "glab",
1121 cwd: input.cwd,
1122 operation: "listCommits",
1123 cause: decoded.failure,
1124 }),
1125 );
1126 }),
1127 ),
1128
1129 getMergeRequestDiff: (input) => {
1130 if (input.commit !== undefined && !isCommitSha(input.commit)) {
1131 return Effect.fail(new GitLabDiffCommitError({ command: "glab", cwd: input.cwd }));
1132 }
1133 const target = {
1134 cwd: input.cwd,
1135 repository: input.repository,
1136 number: input.number,
1137 ...(input.commit === undefined ? {} : { commit: input.commit }),
1138 };
1139 if (input.cursor === undefined) {
1140 return diffPage({ ...target, page: 1 });
1141 }
1142 const page = diffCursorPage(input.cursor);
1143 return page === null
1144 ? Effect.fail(new GitLabDiffCursorError({ command: "glab", cwd: input.cwd }))
1145 : diffPage({ ...target, page });
1146 },
1147
1148 getMergeRequestDiffFileContents: (input) =>
1149 Effect.gen(function* () {
1150 if (input.commit !== undefined && !isCommitSha(input.commit)) {
1151 return yield* Effect.fail(new GitLabDiffCommitError({ command: "glab", cwd: input.cwd }));
1152 }
1153 const refs = yield* input.commit === undefined
1154 ? getDiffRefs(input)
1155 : getCommitDiffRefs({
1156 cwd: input.cwd,
1157 repository: input.repository,
1158 commit: input.commit,
1159 allowRoot: input.changeType === "new",
1160 });
1161
1162 const readFile = (revision: string, filePath: string) =>
1163 api({
1164 cwd: input.cwd,
1165 path: `projects/${projectPath(input.repository)}/repository/files/${encodeURIComponent(
1166 filePath,
1167 )}/raw?ref=${encodeURIComponent(revision)}`,
1168 maxOutputBytes: DIFF_FILE_MAX_OUTPUT_BYTES,
1169 timeoutMs: DIFF_TIMEOUT_MS,
1170 }).pipe(
1171 Effect.flatMap((result) =>
1172 result.stdoutTruncated ||
1173 result.stdout.includes("\0") ||
1174 result.stdoutInvalidUtf8 === true
1175 ? Effect.fail(
1176 new GitLabDiffFileContentsUnavailableError({
1177 command: "glab",
1178 cwd: input.cwd,
1179 path: filePath,
1180 reason: result.stdoutTruncated ? "oversized" : "binary",
1181 }),
1182 )
1183 : Effect.succeed(result.stdout),
1184 ),
1185 );
1186
1187 const [oldContents, newContents] = yield* Effect.all(
1188 [
1189 input.changeType === "new" ? Effect.succeed("") : readFile(refs.baseSha, input.oldPath),
1190 input.changeType === "deleted"
1191 ? Effect.succeed("")
1192 : readFile(refs.headSha, input.newPath),
1193 ],
1194 { concurrency: 2 },
1195 );
1196 return { oldContents, newContents };
1197 }),
1198
1199 getProjectMergeCapabilities: (input) =>
1200 api({
1201 cwd: input.cwd,
1202 path: `projects/${projectPath(input.repository)}?license=false`,
1203 }).pipe(
1204 Effect.flatMap((result) => {
1205 const decoded = decodeProjectMergeCapabilitiesJson(result.stdout.trim());
1206 return Result.isSuccess(decoded)
1207 ? Effect.succeed(decoded.success)
1208 : Effect.fail(
1209 new GitLabMergeRequestReadError({
1210 command: "glab",
1211 cwd: input.cwd,
1212 operation: "getProjectMergeCapabilities",
1213 cause: decoded.failure,
1214 }),
1215 );
1216 }),
1217 ),
1218
1219 listReviewerCandidates: (input) =>
1220 Effect.all([mergeRequestDetail(input), projectUsers(input)], { concurrency: 2 }).pipe(
1221 Effect.map(([mergeRequest, users]) => {
1222 const author = mergeRequest.author?.login;
1223 const requested = new Set(mergeRequest.reviewRequestLogins);
1224 return {
1225 // The author is dropped rather than shown unusable: GitLab refuses to make the person
1226 // who opened a merge request its reviewer.
1227 candidates: users.candidates.flatMap((candidate) =>
1228 candidate.login === author
1229 ? []
1230 : [{ ...candidate, isRequested: requested.has(candidate.login) }],
1231 ),
1232 truncated: users.rawCount >= MAX_PAGE_SIZE,
1233 };
1234 }),
1235 ),
1236
1237 setReviewerRequest: (input) =>
1238 mergeRequestDetail(input).pipe(
1239 Effect.flatMap((mergeRequest) => {
1240 // GitLab has no endpoint that adds or removes one reviewer: `reviewer_ids` replaces the
1241 // whole set, so the set that is already there is read first and the change applied to
1242 // it. Asking again for somebody already on it writes the same set back, which is how
1243 // GitLab re-requests a review.
1244 const ids = new Set(mergeRequest.reviewerIds);
1245 for (const reviewer of input.reviewers) {
1246 const id = Number(reviewer.id);
1247 // A candidate GitLab did not name is not an id it would accept, and sending it would
1248 // rewrite the reviewer set around a number nobody chose.
1249 if (!Number.isSafeInteger(id) || id <= 0) continue;
1250 if (input.requested) ids.add(id);
1251 else ids.delete(id);
1252 }
1253 return api({
1254 cwd: input.cwd,
1255 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`,
1256 method: "PUT",
1257 stdin: JSON.stringify({ reviewer_ids: [...ids] }),
1258 });
1259 }),
1260 Effect.asVoid,
1261 ),
1262
1263 runMergeRequestAction: (input) => {
1264 // `glab mr merge` arms auto-merge and never disarms it, so the one direction the CLI has
1265 // no flag for is asked of GitLab directly through the same `api` passthrough the rest of
1266 // this module writes with.
1267 if (input.action === "disable-auto-merge") {
1268 return api({
1269 cwd: input.cwd,
1270 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/cancel_merge_when_pipeline_succeeds`,
1271 method: "POST",
1272 }).pipe(Effect.asVoid);
1273 }
1274 const [subcommand, ...flags] = actionArgs(input.action, input.mergeMethod);
1275 return gitlab
1276 .execute({
1277 cwd: input.cwd,
1278 args: ["mr", subcommand!, String(input.number), "--repo", input.repository, ...flags],
1279 })
1280 .pipe(Effect.asVoid);
1281 },
1282
1283 updateMergeRequest: (input) =>
1284 api({
1285 cwd: input.cwd,
1286 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`,
1287 method: "PUT",
1288 // Only the fields the caller asked to change: GitLab leaves out what it is not sent, and
1289 // clears what it is sent empty — so a title corrected on its own must carry no
1290 // description at all.
1291 stdin: JSON.stringify({
1292 ...(input.title === undefined ? {} : { title: input.title }),
1293 ...(input.description === undefined ? {} : { description: input.description }),
1294 }),
1295 }).pipe(Effect.asVoid),
1296
1297 commentOnMergeRequest: (input) =>
1298 api({
1299 cwd: input.cwd,
1300 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/notes`,
1301 method: "POST",
1302 // A JSON body rather than a `--raw-field`: glab coerces a field that reads as a
1303 // literal `true` or a number, and a comment body is text either way.
1304 stdin: JSON.stringify({ body: input.body }),
1305 }).pipe(Effect.asVoid),
1306
1307 updateNote: (input) =>
1308 api({
1309 cwd: input.cwd,
1310 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/notes/${encodeURIComponent(
1311 input.noteId,
1312 )}`,
1313 method: "PUT",
1314 stdin: JSON.stringify({ body: input.body }),
1315 }).pipe(Effect.asVoid),
1316
1317 listDiscussions: (input) => discussionsPage({ ...input, page: 1, collected: [] }),
1318
1319 submitReview: (input) =>
1320 Effect.gen(function* () {
1321 const project = projectPath(input.repository);
1322 const mergeRequest = `projects/${project}/merge_requests/${input.number}`;
1323 // GitLab has no pending review to attach comments to, so a review is replayed as the
1324 // requests it is made of: the line comments, then the summary, then the verdict. A
1325 // failure part-way therefore leaves what was already posted in place, which is why
1326 // the verdict goes last — a half-sent review is never an approval.
1327 if (input.comments.length > 0) {
1328 const refs = yield* getDiffRefs(input);
1329 yield* Effect.forEach(
1330 input.comments,
1331 (comment) =>
1332 api({
1333 cwd: input.cwd,
1334 path: `${mergeRequest}/discussions`,
1335 method: "POST",
1336 stdin: JSON.stringify({
1337 body: comment.body,
1338 position: {
1339 base_sha: refs.baseSha,
1340 head_sha: refs.headSha,
1341 start_sha: refs.startSha,
1342 position_type: "text",
1343 // Both paths are sent because GitLab resolves a position against both
1344 // sides of the diff. They differ only for a renamed file, which is why the
1345 // draft carries the name the file had before the change.
1346 old_path: comment.oldPath ?? comment.path,
1347 new_path: comment.path,
1348 ...gitLabReviewPositionLines(comment.position),
1349 },
1350 }),
1351 }),
1352 { discard: true },
1353 );
1354 }
1355 if (input.body.trim().length > 0) {
1356 yield* api({
1357 cwd: input.cwd,
1358 path: `${mergeRequest}/notes`,
1359 method: "POST",
1360 // A JSON body rather than a `--raw-field`, for the reason the plain comment gives:
1361 // glab coerces a field that reads as a literal `true` or a number.
1362 // @effect-diagnostics-next-line preferSchemaOverJson:off
1363 stdin: JSON.stringify({ body: input.body }),
1364 });
1365 }
1366 if (input.verdict === "approve") {
1367 yield* api({ cwd: input.cwd, path: `${mergeRequest}/approve`, method: "POST" });
1368 }
1369 }),
1370
1371 replyToDiscussion: (input) =>
1372 api({
1373 cwd: input.cwd,
1374 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/discussions/${encodeURIComponent(
1375 input.discussionId,
1376 )}/notes`,
1377 method: "POST",
1378 stdin: JSON.stringify({ body: input.body }),
1379 }).pipe(Effect.asVoid),
1380
1381 setDiscussionResolution: (input) =>
1382 api({
1383 cwd: input.cwd,
1384 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/discussions/${encodeURIComponent(
1385 input.discussionId,
1386 )}`,
1387 method: "PUT",
1388 stdin: JSON.stringify({ resolved: input.resolved }),
1389 }).pipe(Effect.asVoid),
1390 });
1391});
1392
1393export const layer = Layer.effect(GitLabPullRequestCli, make);