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

GitLabPullRequestCli.ts

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