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