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

GitLabPullRequestCli.ts

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