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

GitLabPullRequestCli.ts

1,153 lines42.3 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Result from "effect/Result";
5import * as Schema from "effect/Schema";
6import type {
7 PullRequestAction,
8 PullRequestComment,
9 PullRequestCommit,
10 PullRequestInvolvement,
11 PullRequestListState,
12 PullRequestMergeCapabilities,
13 PullRequestMergeMethod,
14 PullRequestReviewCommentDraft,
15 PullRequestReviewThread,
16 PullRequestReviewVerdict,
17 PullRequestReviewerCandidateList,
18} from "@t3tools/contracts";
19​
20import * as GitLabCli from "../sourceControl/GitLabCli.ts";
21import {
22 decodeCommitDiffRefsJson,
23 decodeCommitsJson,
24 decodeDiffRefsJson,
25 decodeDiscussionsJson,
26 decodeMergeRequestDetailJson,
27 decodeMergeRequestDiffsJson,
28 decodeMergeRequestListJson,
29 decodeNotesJson,
30 decodeProjectMergeCapabilitiesJson,
31 decodeProjectUsersJson,
32 decodeViewerJson,
33 type GitLabDiffRefs,
34 type GitLabMergeRequestDetail,
35 type GitLabMergeRequestListItem,
36 type GitLabProjectUsers,
37} from "./gitLabMergeRequestJson.ts";
38import type { ProviderListCursor } from "./PullRequestProvider.ts";
39​
40/**
41 * Names the read that produced unusable output, so a failure reports the call it came from
42 * rather than borrowing another operation's message.
43 */
44export class GitLabMergeRequestReadError extends Schema.TaggedErrorClass<GitLabMergeRequestReadError>()(
45 "GitLabMergeRequestReadError",
46 {
47 command: Schema.Literal("glab"),
48 cwd: Schema.String,
49 operation: Schema.String,
50 cause: Schema.Defect(),
51 },
52) {
53 get detail(): string {
54 return `GitLab CLI returned an unreadable ${this.operation} response.`;
55 }
56​
57 override get message(): string {
58 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
59 }
61​
62/** Not a decode failure: glab answered, the account it answered for just has no username. */
63export class GitLabViewerUnavailableError extends Schema.TaggedErrorClass<GitLabViewerUnavailableError>()(
64 "GitLabViewerUnavailableError",
65 {
66 command: Schema.Literal("glab"),
67 cwd: Schema.String,
68 },
69) {
70 get detail(): string {
71 return "GitLab CLI returned no username for the authenticated account.";
72 }
73​
74 override get message(): string {
75 return `GitLab CLI failed in getViewerUsername: ${this.detail}`;
76 }
78​
79/** Not a decode failure: GitLab answered, the merge request just has no revisions to place a
80 * comment against. */
81export class GitLabDiffRefsUnavailableError extends Schema.TaggedErrorClass<GitLabDiffRefsUnavailableError>()(
82 "GitLabDiffRefsUnavailableError",
83 {
84 command: Schema.Literal("glab"),
85 cwd: Schema.String,
86 number: Schema.Int,
87 },
88) {
89 get detail(): string {
90 return "The merge request reported no diff revisions.";
91 }
92​
93 override get message(): string {
94 return `GitLab CLI failed in getDiffRefs: ${this.detail}`;
95 }
97​
98/** Not a decode failure: the reader asked to carry on from a cursor this walk never handed out. */
99export class GitLabDiffCursorError extends Schema.TaggedErrorClass<GitLabDiffCursorError>()(
100 "GitLabDiffCursorError",
101 {
102 command: Schema.Literal("glab"),
103 cwd: Schema.String,
104 },
105) {
106 get detail(): string {
107 return "The diff cursor was not one this merge request handed out.";
108 }
109​
110 override get message(): string {
111 return `GitLab CLI failed in getMergeRequestDiff: ${this.detail}`;
112 }
114​
115/** Not a decode failure: the reader named a commit that is not a sha this project could hold. */
116export class GitLabDiffCommitError extends Schema.TaggedErrorClass<GitLabDiffCommitError>()(
117 "GitLabDiffCommitError",
118 {
119 command: Schema.Literal("glab"),
120 cwd: Schema.String,
121 },
122) {
123 get detail(): string {
124 return "The named commit was not a commit sha.";
125 }
126​
127 override get message(): string {
128 return `GitLab CLI failed in getMergeRequestDiff: ${this.detail}`;
129 }
131​
132/** The commit exists and decoded, but it has no parent to use as the old revision. */
133export class GitLabDiffCommitParentUnavailableError extends Schema.TaggedErrorClass<GitLabDiffCommitParentUnavailableError>()(
134 "GitLabDiffCommitParentUnavailableError",
135 {
136 command: Schema.Literal("glab"),
137 cwd: Schema.String,
138 commit: Schema.String,
139 },
140) {
141 get detail(): string {
142 return `Commit ${this.commit} reported no parent revision.`;
143 }
144​
145 override get message(): string {
146 return `GitLab CLI failed in getMergeRequestDiffFileContents: ${this.detail}`;
147 }
149​
150/** A blob exists, but expanding it would be unsafe or would not produce text. */
151export class GitLabDiffFileContentsUnavailableError extends Schema.TaggedErrorClass<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;
183/** Commit history is read one page deep; the rest of a long history stays on GitLab. */
184const COMMIT_PAGE_SIZE = 100;
185/**
186 * Pages of the conversation to follow before it is reported as truncated. GitLab caps a page at
187 * a hundred, so this is a thousand notes and a thousand discussions — more than any merge
188 * request a person is reading holds, and a walk that ends whatever the host has.
189 */
190const CONVERSATION_PAGES = 10;
191const DIFF_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
192const DIFF_TIMEOUT_MS = 60_000;
193const DIFF_FILE_MAX_OUTPUT_BYTES = 1024 * 1024;
194​
195export interface GitLabMergeRequestListBatch {
196 readonly items: ReadonlyArray<GitLabMergeRequestListItem>;
197 readonly truncated: boolean;
198 /** Raw GitLab rows consumed to produce this page, including malformed rows. */
199 readonly cursorAdvance: number;
201​
202export interface GitLabMergeRequestDiffSlice {
203 readonly patch: string;
204 /** Files in this slice had their hunks withheld, as opposed to there being more slices. */
205 readonly truncated: boolean;
206 /** Where the next slice starts, or null once the patch is whole. */
207 readonly nextCursor: string | null;
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 /** Free text for GitLab's own `search`, which matches title and description. */
225 readonly query?: string | undefined;
226 /** Where to carry on from in GitLab's stable update-ordered row set. */
227 readonly cursor?: ProviderListCursor | undefined;
228 }) => Effect.Effect<GitLabMergeRequestListBatch, GitLabPullRequestCliError>;
229​
230 readonly getMergeRequestDetail: (input: {
231 readonly cwd: string;
232 readonly repository: string;
233 readonly number: number;
234 }) => Effect.Effect<GitLabMergeRequestDetail, GitLabPullRequestCliError>;
235​
236 readonly listNotes: (input: {
237 readonly cwd: string;
238 readonly repository: string;
239 readonly number: number;
240 }) => Effect.Effect<
241 { readonly comments: ReadonlyArray<PullRequestComment>; readonly truncated: boolean },
242 GitLabPullRequestCliError
243 >;
244​
245 readonly listCommits: (input: {
246 readonly cwd: string;
247 readonly repository: string;
248 readonly number: number;
249 }) => Effect.Effect<ReadonlyArray<PullRequestCommit>, GitLabPullRequestCliError>;
250​
251 readonly getMergeRequestDiff: (input: {
252 readonly cwd: string;
253 readonly repository: string;
254 readonly number: number;
255 /** Absent asks for the first slice; anything else is a cursor a slice handed back. */
256 readonly cursor?: string | undefined;
257 /** One commit's own changes, rather than everything the merge request carries. */
258 readonly commit?: string | undefined;
259 }) => Effect.Effect<GitLabMergeRequestDiffSlice, GitLabPullRequestCliError>;
260​
261 readonly getMergeRequestDiffFileContents: (input: {
262 readonly cwd: string;
263 readonly repository: string;
264 readonly number: number;
265 readonly commit?: string | undefined;
266 readonly changeType: "change" | "rename-pure" | "rename-changed" | "new" | "deleted";
267 readonly oldPath: string;
268 readonly newPath: string;
269 }) => Effect.Effect<
270 { readonly oldContents: string; readonly newContents: string },
271 GitLabPullRequestCliError
272 >;
273​
274 readonly getProjectMergeCapabilities: (input: {
275 readonly cwd: string;
276 readonly repository: string;
277 }) => Effect.Effect<PullRequestMergeCapabilities, GitLabPullRequestCliError>;
278​
279 /**
280 * Who this merge request may be sent to, and who it has already been sent to. Two reads at
281 * once, because GitLab keeps the people with access on the project and the reviewers on the
282 * merge request, and neither answers for the other.
283 */
284 readonly listReviewerCandidates: (input: {
285 readonly cwd: string;
286 readonly repository: string;
287 readonly number: number;
288 }) => Effect.Effect<PullRequestReviewerCandidateList, GitLabPullRequestCliError>;
289​
290 readonly setReviewerRequest: (input: {
291 readonly cwd: string;
292 readonly repository: string;
293 readonly number: number;
294 readonly reviewers: ReadonlyArray<{ readonly id: string }>;
295 readonly requested: boolean;
296 }) => Effect.Effect<void, GitLabPullRequestCliError>;
297​
298 readonly runMergeRequestAction: (input: {
299 readonly cwd: string;
300 readonly repository: string;
301 readonly number: number;
302 readonly action: PullRequestAction;
303 readonly mergeMethod?: PullRequestMergeMethod;
304 }) => Effect.Effect<void, GitLabPullRequestCliError>;
305​
306 readonly commentOnMergeRequest: (input: {
307 readonly cwd: string;
308 readonly repository: string;
309 readonly number: number;
310 readonly body: string;
311 }) => Effect.Effect<void, GitLabPullRequestCliError>;
312​
313 readonly listDiscussions: (input: {
314 readonly cwd: string;
315 readonly repository: string;
316 readonly number: number;
317 }) => Effect.Effect<
318 { readonly threads: ReadonlyArray<PullRequestReviewThread>; readonly truncated: boolean },
319 GitLabPullRequestCliError
320 >;
321​
322 readonly submitReview: (input: {
323 readonly cwd: string;
324 readonly repository: string;
325 readonly number: number;
326 readonly verdict: PullRequestReviewVerdict;
327 readonly body: string;
328 readonly comments: ReadonlyArray<PullRequestReviewCommentDraft>;
329 }) => Effect.Effect<void, GitLabPullRequestCliError>;
330​
331 readonly replyToDiscussion: (input: {
332 readonly cwd: string;
333 readonly repository: string;
334 readonly number: number;
335 readonly discussionId: string;
336 readonly body: string;
337 }) => Effect.Effect<void, GitLabPullRequestCliError>;
338​
339 readonly setDiscussionResolution: (input: {
340 readonly cwd: string;
341 readonly repository: string;
342 readonly number: number;
343 readonly discussionId: string;
344 readonly resolved: boolean;
345 }) => Effect.Effect<void, GitLabPullRequestCliError>;
346 }
347>()("t3/pullRequest/GitLabPullRequestCli") {}
348​
349/** The REST API addresses a project by its URL-encoded full path. */
350function projectPath(repository: string): string {
351 return encodeURIComponent(repository.trim());
353​
354function stateParam(state: PullRequestListState): string {
355 // GitLab's `closed` already excludes merged merge requests, so no extra filter is needed,
356 // and it spans every state under `all`.
357 return state === "open" ? "opened" : state;
359​
360function involvementParams(input: {
361 readonly involvement: PullRequestInvolvement;
362 readonly viewer: string;
363}): ReadonlyArray<readonly [string, string]> {
364 switch (input.involvement) {
365 case "authored":
366 return [["author_username", input.viewer]];
367 case "reviewing":
368 return [["reviewer_username", input.viewer]];
369 case "all":
370 return [];
371 }
373​
374/**
375 * The page a diff cursor names, or null for anything this walk cannot have issued. The cursor
376 * arrives from the reader as a string and goes straight into a query, so it is parsed rather
377 * than trusted; the length bound keeps a page number out of exponential notation.
378 */
379function diffCursorPage(cursor: string): number | null {
380 return /^[1-9][0-9]{0,6}$/.test(cursor) ? Number(cursor) : null;
382​
383/**
384 * A commit sha arrives from the reader and goes straight into a request path, so it is checked
385 * rather than trusted: hexadecimal only, from the shortest abbreviation a host prints up to a
386 * whole sha.
387 */
388function isCommitSha(value: string): boolean {
389 return /^[0-9a-f]{7,64}$/i.test(value);
391​
392function searchParams(search: string | undefined): ReadonlyArray<readonly [string, string]> {
393 const trimmed = search?.trim() ?? "";
394 return trimmed.length === 0 ? [] : [["search", trimmed]];
396​
397function query(params: ReadonlyArray<readonly [string, string]>): string {
398 return params.map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&");
400​
401function actionArgs(
402 action: PullRequestAction,
403 mergeMethod: PullRequestMergeMethod | undefined,
404): ReadonlyArray<string> {
405 switch (action) {
406 case "merge":
407 return [
408 "merge",
409 // glab turns on auto-merge whenever a pipeline is running. The button means merge now.
410 "--auto-merge=false",
411 "--yes",
412 ...(mergeMethod === "squash" ? ["--squash"] : []),
413 ...(mergeMethod === "rebase" ? ["--rebase"] : []),
414 ];
415 case "ready":
416 return ["update", "--ready"];
417 case "draft":
418 return ["update", "--draft"];
419 case "close":
420 return ["close"];
421 case "reopen":
422 return ["reopen"];
423 }
425​
426export const make = Effect.gen(function* () {
427 const gitlab = yield* GitLabCli.GitLabCli;
428​
429 const api = (input: {
430 readonly cwd: string;
431 readonly path: string;
432 readonly method?: string;
433 readonly stdin?: string;
434 readonly maxOutputBytes?: number;
435 readonly timeoutMs?: number;
436 }) =>
437 gitlab.execute({
438 cwd: input.cwd,
439 args: [
440 "api",
441 input.path,
442 ...(input.method === undefined ? [] : ["--method", input.method]),
443 // A raw body from stdin: argv is visible in process listings and is echoed back
444 // inside process-runner failure messages. Unlike `gh`, `glab api --input` sends no
445 // Content-Type at all, and GitLab answers a bodyless content type with HTTP 415.
446 ...(input.stdin === undefined
447 ? []
448 : ["--input", "-", "--header", "Content-Type: application/json"]),
449 ],
450 ...(input.stdin === undefined ? {} : { stdin: input.stdin }),
451 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
452 ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),
453 });
454​
455 /**
456 * `per_page` stops at 100, so a larger page is walked one request at a time. The walk is
457 * bounded twice over: it stops on a short page or once the extra row that reveals a next
458 * page has been read, and it never asks for more pages than the caller's page needs. The
459 * second bound is what makes it terminate when every row on a page fails to decode, which
460 * leaves nothing collected but does not mean GitLab has run out of rows.
461 */
462 const listPage = (input: {
463 readonly cwd: string;
464 readonly repository: string;
465 readonly state: PullRequestListState;
466 readonly involvement: PullRequestInvolvement;
467 readonly viewer: string;
468 readonly limit: number;
469 readonly query?: string | undefined;
470 readonly cursor?: ProviderListCursor | undefined;
471 readonly page: number;
472 readonly collected: ReadonlyArray<GitLabMergeRequestListItem>;
473 readonly cursorAdvance: number;
474 }): Effect.Effect<GitLabMergeRequestListBatch, GitLabPullRequestCliError> => {
475 // A continuation uses GitLab's offset pagination. Its timestamp filter is inclusive and has
476 // no tie-breaker, so a page where many rows share the boundary would otherwise return the
477 // same prefix forever. `delivered` is the stable offset the service has already handed over.
478 const delivered = input.cursor?.delivered ?? 0;
479 const perPage = Math.min(input.limit + 1, MAX_PAGE_SIZE);
480 const firstPage = Math.floor(delivered / perPage) + 1;
481 const skipOnFirstPage = input.page === firstPage ? delivered % perPage : 0;
482 // A page made entirely of malformed rows has no item from which the service can build a
483 // continuation. Bound the walk to the raw span this request asked for rather than recursing
484 // forever on a host that keeps returning full unusable pages.
485 const lastPage = Math.floor((delivered + input.limit) / perPage) + 1;
486 return api({
487 cwd: input.cwd,
488 path: `projects/${projectPath(input.repository)}/merge_requests?${query([
489 ["state", stateParam(input.state)],
490 ...involvementParams(input),
491 // The listing is read through `glab api` rather than `glab mr list`, so the search is
492 // the REST API's own `search` parameter — the one `mr list --search` passes on. It
493 // matches title and description, and travels URL-encoded like every other value here,
494 // so no text in it can become a parameter of its own.
495 ...searchParams(input.query),
496 ["order_by", "updated_at"],
497 ["sort", "desc"],
498 ["per_page", String(perPage)],
499 ["page", String(input.page)],
500 ])}`,
501 }).pipe(
502 Effect.flatMap((result) => {
503 const raw = result.stdout.trim();
504 if (raw.length === 0) {
505 return Effect.succeed({
506 items: input.collected,
507 truncated: false,
508 cursorAdvance: input.cursorAdvance,
509 });
510 }
511 const decoded = decodeMergeRequestListJson(raw);
512 if (!Result.isSuccess(decoded)) {
513 return Effect.fail(
514 new GitLabMergeRequestReadError({
515 command: "glab",
516 cwd: input.cwd,
517 operation: "listMergeRequests",
518 cause: decoded.failure,
519 }),
520 );
521 }
522 const pageItems: GitLabMergeRequestListItem[] = [];
523 const pageRawIndexes: number[] = [];
524 for (const [index, item] of decoded.success.items.entries()) {
525 const rawIndex = decoded.success.rawIndexes[index]!;
526 if (rawIndex < skipOnFirstPage) continue;
527 pageItems.push(item);
528 pageRawIndexes.push(rawIndex);
529 }
530 const remaining = input.limit - input.collected.length;
531 const lastItemRawIndex = pageRawIndexes[remaining - 1];
532 if (lastItemRawIndex !== undefined) {
533 const consumed = lastItemRawIndex + 1 - skipOnFirstPage;
534 return Effect.succeed({
535 items: [...input.collected, ...pageItems.slice(0, remaining)],
536 truncated:
537 lastItemRawIndex + 1 < decoded.success.rawCount ||
538 decoded.success.rawCount === perPage,
539 cursorAdvance: input.cursorAdvance + consumed,
540 });
541 }
542 const collected = [...input.collected, ...pageItems];
543 const consumed = Math.max(0, decoded.success.rawCount - skipOnFirstPage);
544 // Counted before decoding, so a skipped malformed row cannot end paging early.
545 const exhausted = decoded.success.rawCount < perPage;
546 if (exhausted) {
547 return Effect.succeed({
548 items: collected,
549 truncated: false,
550 cursorAdvance: input.cursorAdvance + consumed,
551 });
552 }
553 if (input.page >= lastPage) {
554 return Effect.succeed({
555 items: collected,
556 truncated: true,
557 cursorAdvance: input.cursorAdvance + consumed,
558 });
559 }
560 return listPage({
561 ...input,
562 page: input.page + 1,
563 collected,
564 cursorAdvance: input.cursorAdvance + consumed,
565 });
566 }),
567 );
568 };
569​
570 /**
571 * One page of a merge request's files, as a patch that stands on its own. GitLab pages
572 * `/diffs` by offset and has no cursor of its own, so the page number is the cursor; the
573 * caller carries on from it for as long as GitLab keeps handing full pages back.
574 *
575 * A named commit is read from the commit's own diff, which answers in the same shape and pages
576 * the same way.
577 */
578 const diffPage = (input: {
579 readonly cwd: string;
580 readonly repository: string;
581 readonly number: number;
582 readonly page: number;
583 readonly commit?: string | undefined;
584 }): Effect.Effect<GitLabMergeRequestDiffSlice, GitLabPullRequestCliError> =>
585 api({
586 cwd: input.cwd,
587 path: `projects/${projectPath(input.repository)}/${
588 input.commit === undefined
589 ? `merge_requests/${input.number}/diffs`
590 : `repository/commits/${input.commit}/diff`
591 }?${query([
592 ["per_page", String(MAX_PAGE_SIZE)],
593 ["page", String(input.page)],
594 ])}`,
595 maxOutputBytes: DIFF_MAX_OUTPUT_BYTES,
596 timeoutMs: DIFF_TIMEOUT_MS,
597 }).pipe(
598 Effect.flatMap((result) => {
599 // A byte-truncated response is a JSON prefix, so this page cannot be read at all.
600 // Answering with no cursor would call the diff whole while silently dropping this page
601 // and every one after it, so the read fails and says which page could not be had.
602 if (result.stdoutTruncated) {
603 return Effect.fail(
604 new GitLabMergeRequestReadError({
605 command: "glab",
606 cwd: input.cwd,
607 operation: "getMergeRequestDiff",
608 cause: new Error(
609 `Page ${input.page} of the merge request diff was too large to read.`,
610 ),
611 }),
612 );
613 }
614 const decoded = decodeMergeRequestDiffsJson(result.stdout.trim());
615 if (!Result.isSuccess(decoded)) {
616 return Effect.fail(
617 new GitLabMergeRequestReadError({
618 command: "glab",
619 cwd: input.cwd,
620 operation: "getMergeRequestDiff",
621 cause: decoded.failure,
622 }),
623 );
624 }
625 const patch = decoded.success.patch;
626 // Counted before decoding, so a page whose files all failed to decode still moves on
627 // rather than pointing the reader back at the page it just read.
628 const morePages = decoded.success.rawCount >= MAX_PAGE_SIZE;
629 return Effect.succeed({
630 // The slice ends on a newline, so a file GitLab gave a header and no hunks for does
631 // not run into the first line of the next slice.
632 patch: patch.length === 0 ? patch : patch.replace(/\n?$/, "\n"),
633 truncated: decoded.success.truncated,
634 nextCursor: morePages ? String(input.page + 1) : null,
635 });
636 }),
637 );
638​
639 /**
640 * The conversation, a page at a time. GitLab pages by offset and reports no total, so a short
641 * page is the only thing that says it is done — and the raw count decides, not the kept one:
642 * the notes GitLab wrote itself are dropped, and a whole page of them still means there is
643 * more to read.
644 */
645 const notesPage = (input: {
646 readonly cwd: string;
647 readonly repository: string;
648 readonly number: number;
649 readonly page: number;
650 readonly collected: ReadonlyArray<PullRequestComment>;
651 }): Effect.Effect<
652 { readonly comments: ReadonlyArray<PullRequestComment>; readonly truncated: boolean },
653 GitLabPullRequestCliError
654 > =>
655 api({
656 cwd: input.cwd,
657 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/notes?${query(
658 [
659 ["per_page", String(MAX_PAGE_SIZE)],
660 ["page", String(input.page)],
661 ["order_by", "created_at"],
662 ["sort", "asc"],
663 ],
664 )}`,
665 }).pipe(
666 Effect.flatMap((result) => {
667 const decoded = decodeNotesJson(result.stdout.trim());
668 if (!Result.isSuccess(decoded)) {
669 return Effect.fail(
670 new GitLabMergeRequestReadError({
671 command: "glab",
672 cwd: input.cwd,
673 operation: "listNotes",
674 cause: decoded.failure,
675 }),
676 );
677 }
678 const collected = [...input.collected, ...decoded.success.comments];
679 if (decoded.success.rawCount < MAX_PAGE_SIZE) {
680 return Effect.succeed({ comments: collected, truncated: false });
681 }
682 return input.page >= CONVERSATION_PAGES
683 ? Effect.succeed({ comments: collected, truncated: true })
684 : notesPage({ ...input, page: input.page + 1, collected });
685 }),
686 );
687​
688 /** The positioned discussions, walked the same way and stopped by the same bound. */
689 const discussionsPage = (input: {
690 readonly cwd: string;
691 readonly repository: string;
692 readonly number: number;
693 readonly page: number;
694 readonly collected: ReadonlyArray<PullRequestReviewThread>;
695 }): Effect.Effect<
696 { readonly threads: ReadonlyArray<PullRequestReviewThread>; readonly truncated: boolean },
697 GitLabPullRequestCliError
698 > =>
699 api({
700 cwd: input.cwd,
701 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/discussions?${query(
702 [
703 ["per_page", String(MAX_PAGE_SIZE)],
704 ["page", String(input.page)],
705 ],
706 )}`,
707 }).pipe(
708 Effect.flatMap((result) => {
709 const decoded = decodeDiscussionsJson(result.stdout.trim());
710 if (!Result.isSuccess(decoded)) {
711 return Effect.fail(
712 new GitLabMergeRequestReadError({
713 command: "glab",
714 cwd: input.cwd,
715 operation: "listDiscussions",
716 cause: decoded.failure,
717 }),
718 );
719 }
720 const collected = [...input.collected, ...decoded.success.threads];
721 // The raw count again: this endpoint returns the plain notes too, so a full page of
722 // those is not the end of the positioned ones.
723 if (decoded.success.rawCount < MAX_PAGE_SIZE) {
724 return Effect.succeed({ threads: collected, truncated: false });
725 }
726 return input.page >= CONVERSATION_PAGES
727 ? Effect.succeed({ threads: collected, truncated: true })
728 : discussionsPage({ ...input, page: input.page + 1, collected });
729 }),
730 );
731​
732 /**
733 * The revisions a positioned comment is written against. GitLab resolves a comment's line
734 * against these three shas, so a review with line comments cannot be sent without them.
735 */
736 const getDiffRefs = (input: {
737 readonly cwd: string;
738 readonly repository: string;
739 readonly number: number;
740 }): Effect.Effect<GitLabDiffRefs, GitLabPullRequestCliError> =>
741 api({
742 cwd: input.cwd,
743 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`,
744 }).pipe(
745 Effect.flatMap((result): Effect.Effect<GitLabDiffRefs, GitLabPullRequestCliError> => {
746 const decoded = decodeDiffRefsJson(result.stdout.trim());
747 if (!Result.isSuccess(decoded)) {
748 return Effect.fail(
749 new GitLabMergeRequestReadError({
750 command: "glab",
751 cwd: input.cwd,
752 operation: "getDiffRefs",
753 cause: decoded.failure,
754 }),
755 );
756 }
757 // A merge request with no diff refs is a well-formed answer that cannot carry a
758 // positioned comment — a dead end, but not something that failed to be read.
759 return decoded.success === null
760 ? Effect.fail(
761 new GitLabDiffRefsUnavailableError({
762 command: "glab",
763 cwd: input.cwd,
764 number: input.number,
765 }),
766 )
767 : Effect.succeed(decoded.success);
768 }),
769 );
770​
771 const getCommitDiffRefs = (input: {
772 readonly cwd: string;
773 readonly repository: string;
774 readonly commit: string;
775 readonly allowRoot: boolean;
776 }): Effect.Effect<GitLabDiffRefs, GitLabPullRequestCliError> =>
777 api({
778 cwd: input.cwd,
779 path: `projects/${projectPath(input.repository)}/repository/commits/${input.commit}`,
780 }).pipe(
781 Effect.flatMap((result): Effect.Effect<GitLabDiffRefs, GitLabPullRequestCliError> => {
782 const decoded = decodeCommitDiffRefsJson(result.stdout.trim());
783 if (!Result.isSuccess(decoded)) {
784 return Effect.fail(
785 new GitLabMergeRequestReadError({
786 command: "glab",
787 cwd: input.cwd,
788 operation: "getMergeRequestDiffFileContents",
789 cause: decoded.failure,
790 }),
791 );
792 }
793 return decoded.success === null
794 ? input.allowRoot
795 ? Effect.succeed({
796 baseSha: "",
797 headSha: input.commit,
798 startSha: "",
799 })
800 : Effect.fail(
801 new GitLabDiffCommitParentUnavailableError({
802 command: "glab",
803 cwd: input.cwd,
804 commit: input.commit,
805 }),
806 )
807 : Effect.succeed(decoded.success);
808 }),
809 );
810​
811 /**
812 * The merge request itself, which several calls need for different parts of it: the detail for
813 * everything, and the reviewer paths for the ids GitLab writes a reviewer set with.
814 */
815 const mergeRequestDetail = (input: {
816 readonly cwd: string;
817 readonly repository: string;
818 readonly number: number;
819 }): Effect.Effect<GitLabMergeRequestDetail, GitLabPullRequestCliError> =>
820 api({
821 cwd: input.cwd,
822 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`,
823 }).pipe(
824 Effect.flatMap((result) => {
825 const decoded = decodeMergeRequestDetailJson(result.stdout.trim());
826 return Result.isSuccess(decoded)
827 ? Effect.succeed(decoded.success)
828 : Effect.fail(
829 new GitLabMergeRequestReadError({
830 command: "glab",
831 cwd: input.cwd,
832 operation: "getMergeRequestDetail",
833 cause: decoded.failure,
834 }),
835 );
836 }),
837 );
838​
839 /** The people with access to the project, one page deep. */
840 const projectUsers = (input: {
841 readonly cwd: string;
842 readonly repository: string;
843 }): Effect.Effect<GitLabProjectUsers, GitLabPullRequestCliError> =>
844 api({
845 cwd: input.cwd,
846 path: `projects/${projectPath(input.repository)}/users?${query([
847 ["per_page", String(MAX_PAGE_SIZE)],
848 ])}`,
849 }).pipe(
850 Effect.flatMap((result) => {
851 const decoded = decodeProjectUsersJson(result.stdout.trim());
852 return Result.isSuccess(decoded)
853 ? Effect.succeed(decoded.success)
854 : Effect.fail(
855 new GitLabMergeRequestReadError({
856 command: "glab",
857 cwd: input.cwd,
858 operation: "listReviewerCandidates",
859 cause: decoded.failure,
860 }),
861 );
862 }),
863 );
864​
865 return GitLabPullRequestCli.of({
866 getViewerUsername: (input) =>
867 api({ cwd: input.cwd, path: "user" }).pipe(
868 Effect.flatMap((result): Effect.Effect<string, GitLabPullRequestCliError> => {
869 const decoded = decodeViewerJson(result.stdout.trim());
870 if (!Result.isSuccess(decoded)) {
871 return Effect.fail(
872 new GitLabMergeRequestReadError({
873 command: "glab",
874 cwd: input.cwd,
875 operation: "getViewerUsername",
876 cause: decoded.failure,
877 }),
878 );
879 }
880 return decoded.success === null
881 ? Effect.fail(new GitLabViewerUnavailableError({ command: "glab", cwd: input.cwd }))
882 : Effect.succeed(decoded.success);
883 }),
884 ),
885​
886 listMergeRequests: (input) => {
887 const perPage = Math.min(input.limit + 1, MAX_PAGE_SIZE);
888 const page = Math.floor((input.cursor?.delivered ?? 0) / perPage) + 1;
889 return listPage({ ...input, page, collected: [], cursorAdvance: 0 });
890 },
891​
892 getMergeRequestDetail: mergeRequestDetail,
893​
894 listNotes: (input) => notesPage({ ...input, page: 1, collected: [] }),
895​
896 listCommits: (input) =>
897 api({
898 cwd: input.cwd,
899 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/commits?${query(
900 [
901 ["per_page", String(COMMIT_PAGE_SIZE)],
902 ["with_stats", "true"],
903 ],
904 )}`,
905 }).pipe(
906 Effect.flatMap((result) => {
907 const decoded = decodeCommitsJson(result.stdout.trim());
908 return Result.isSuccess(decoded)
909 ? Effect.succeed(decoded.success)
910 : Effect.fail(
911 new GitLabMergeRequestReadError({
912 command: "glab",
913 cwd: input.cwd,
914 operation: "listCommits",
915 cause: decoded.failure,
916 }),
917 );
918 }),
919 ),
920​
921 getMergeRequestDiff: (input) => {
922 if (input.commit !== undefined && !isCommitSha(input.commit)) {
923 return Effect.fail(new GitLabDiffCommitError({ command: "glab", cwd: input.cwd }));
924 }
925 const target = {
926 cwd: input.cwd,
927 repository: input.repository,
928 number: input.number,
929 ...(input.commit === undefined ? {} : { commit: input.commit }),
930 };
931 if (input.cursor === undefined) {
932 return diffPage({ ...target, page: 1 });
933 }
934 const page = diffCursorPage(input.cursor);
935 return page === null
936 ? Effect.fail(new GitLabDiffCursorError({ command: "glab", cwd: input.cwd }))
937 : diffPage({ ...target, page });
938 },
939​
940 getMergeRequestDiffFileContents: (input) =>
941 Effect.gen(function* () {
942 if (input.commit !== undefined && !isCommitSha(input.commit)) {
943 return yield* Effect.fail(new GitLabDiffCommitError({ command: "glab", cwd: input.cwd }));
944 }
945 const refs = yield* input.commit === undefined
946 ? getDiffRefs(input)
947 : getCommitDiffRefs({
948 cwd: input.cwd,
949 repository: input.repository,
950 commit: input.commit,
951 allowRoot: input.changeType === "new",
952 });
953​
954 const readFile = (revision: string, filePath: string) =>
955 api({
956 cwd: input.cwd,
957 path: `projects/${projectPath(input.repository)}/repository/files/${encodeURIComponent(
958 filePath,
959 )}/raw?ref=${encodeURIComponent(revision)}`,
960 maxOutputBytes: DIFF_FILE_MAX_OUTPUT_BYTES,
961 timeoutMs: DIFF_TIMEOUT_MS,
962 }).pipe(
963 Effect.flatMap((result) =>
964 result.stdoutTruncated ||
965 result.stdout.includes("\0") ||
966 result.stdoutInvalidUtf8 === true
967 ? Effect.fail(
968 new GitLabDiffFileContentsUnavailableError({
969 command: "glab",
970 cwd: input.cwd,
971 path: filePath,
972 reason: result.stdoutTruncated ? "oversized" : "binary",
973 }),
974 )
975 : Effect.succeed(result.stdout),
976 ),
977 );
978​
979 const [oldContents, newContents] = yield* Effect.all(
980 [
981 input.changeType === "new" ? Effect.succeed("") : readFile(refs.baseSha, input.oldPath),
982 input.changeType === "deleted"
983 ? Effect.succeed("")
984 : readFile(refs.headSha, input.newPath),
985 ],
986 { concurrency: 2 },
987 );
988 return { oldContents, newContents };
989 }),
990​
991 getProjectMergeCapabilities: (input) =>
992 api({
993 cwd: input.cwd,
994 path: `projects/${projectPath(input.repository)}?license=false`,
995 }).pipe(
996 Effect.flatMap((result) => {
997 const decoded = decodeProjectMergeCapabilitiesJson(result.stdout.trim());
998 return Result.isSuccess(decoded)
999 ? Effect.succeed(decoded.success)
1000 : Effect.fail(
1001 new GitLabMergeRequestReadError({
1002 command: "glab",
1003 cwd: input.cwd,
1004 operation: "getProjectMergeCapabilities",
1005 cause: decoded.failure,
1006 }),
1007 );
1008 }),
1009 ),
1010​
1011 listReviewerCandidates: (input) =>
1012 Effect.all([mergeRequestDetail(input), projectUsers(input)], { concurrency: 2 }).pipe(
1013 Effect.map(([mergeRequest, users]) => {
1014 const author = mergeRequest.author?.login;
1015 const requested = new Set(mergeRequest.reviewRequestLogins);
1016 return {
1017 // The author is dropped rather than shown unusable: GitLab refuses to make the person
1018 // who opened a merge request its reviewer.
1019 candidates: users.candidates.flatMap((candidate) =>
1020 candidate.login === author
1021 ? []
1022 : [{ ...candidate, isRequested: requested.has(candidate.login) }],
1023 ),
1024 truncated: users.rawCount >= MAX_PAGE_SIZE,
1025 };
1026 }),
1027 ),
1028​
1029 setReviewerRequest: (input) =>
1030 mergeRequestDetail(input).pipe(
1031 Effect.flatMap((mergeRequest) => {
1032 // GitLab has no endpoint that adds or removes one reviewer: `reviewer_ids` replaces the
1033 // whole set, so the set that is already there is read first and the change applied to
1034 // it. Asking again for somebody already on it writes the same set back, which is how
1035 // GitLab re-requests a review.
1036 const ids = new Set(mergeRequest.reviewerIds);
1037 for (const reviewer of input.reviewers) {
1038 const id = Number(reviewer.id);
1039 // A candidate GitLab did not name is not an id it would accept, and sending it would
1040 // rewrite the reviewer set around a number nobody chose.
1041 if (!Number.isSafeInteger(id) || id <= 0) continue;
1042 if (input.requested) ids.add(id);
1043 else ids.delete(id);
1045 return api({
1046 cwd: input.cwd,
1047 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`,
1048 method: "PUT",
1049 stdin: JSON.stringify({ reviewer_ids: [...ids] }),
1050 });
1051 }),
1052 Effect.asVoid,
1053 ),
1054​
1055 runMergeRequestAction: (input) => {
1056 const [subcommand, ...flags] = actionArgs(input.action, input.mergeMethod);
1057 return gitlab
1058 .execute({
1059 cwd: input.cwd,
1060 args: ["mr", subcommand!, String(input.number), "--repo", input.repository, ...flags],
1061 })
1062 .pipe(Effect.asVoid);
1063 },
1064​
1065 commentOnMergeRequest: (input) =>
1066 api({
1067 cwd: input.cwd,
1068 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/notes`,
1069 method: "POST",
1070 // A JSON body rather than a `--raw-field`: glab coerces a field that reads as a
1071 // literal `true` or a number, and a comment body is text either way.
1072 stdin: JSON.stringify({ body: input.body }),
1073 }).pipe(Effect.asVoid),
1074​
1075 listDiscussions: (input) => discussionsPage({ ...input, page: 1, collected: [] }),
1076​
1077 submitReview: (input) =>
1078 Effect.gen(function* () {
1079 const project = projectPath(input.repository);
1080 const mergeRequest = `projects/${project}/merge_requests/${input.number}`;
1081 // GitLab has no pending review to attach comments to, so a review is replayed as the
1082 // requests it is made of: the line comments, then the summary, then the verdict. A
1083 // failure part-way therefore leaves what was already posted in place, which is why
1084 // the verdict goes last — a half-sent review is never an approval.
1085 if (input.comments.length > 0) {
1086 const refs = yield* getDiffRefs(input);
1087 yield* Effect.forEach(
1088 input.comments,
1089 (comment) =>
1090 api({
1091 cwd: input.cwd,
1092 path: `${mergeRequest}/discussions`,
1093 method: "POST",
1094 stdin: JSON.stringify({
1095 body: comment.body,
1096 position: {
1097 base_sha: refs.baseSha,
1098 head_sha: refs.headSha,
1099 start_sha: refs.startSha,
1100 position_type: "text",
1101 // Both paths are sent because GitLab resolves a position against both
1102 // sides of the diff. They differ only for a renamed file, which is why the
1103 // draft carries the name the file had before the change.
1104 old_path: comment.oldPath ?? comment.path,
1105 new_path: comment.path,
1106 ...(comment.side === "left"
1107 ? { old_line: comment.line }
1108 : { new_line: comment.line }),
1109 },
1110 }),
1111 }),
1112 { discard: true },
1113 );
1115 if (input.body.trim().length > 0) {
1116 yield* api({
1117 cwd: input.cwd,
1118 path: `${mergeRequest}/notes`,
1119 method: "POST",
1120 // A JSON body rather than a `--raw-field`, for the reason the plain comment gives:
1121 // glab coerces a field that reads as a literal `true` or a number.
1122 // @effect-diagnostics-next-line preferSchemaOverJson:off
1123 stdin: JSON.stringify({ body: input.body }),
1124 });
1126 if (input.verdict === "approve") {
1127 yield* api({ cwd: input.cwd, path: `${mergeRequest}/approve`, method: "POST" });
1129 }),
1130​
1131 replyToDiscussion: (input) =>
1132 api({
1133 cwd: input.cwd,
1134 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/discussions/${encodeURIComponent(
1135 input.discussionId,
1136 )}/notes`,
1137 method: "POST",
1138 stdin: JSON.stringify({ body: input.body }),
1139 }).pipe(Effect.asVoid),
1140​
1141 setDiscussionResolution: (input) =>
1142 api({
1143 cwd: input.cwd,
1144 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/discussions/${encodeURIComponent(
1145 input.discussionId,
1146 )}`,
1147 method: "PUT",
1148 stdin: JSON.stringify({ resolved: input.resolved }),
1149 }).pipe(Effect.asVoid),
1150 });
1151});
1152​
1153export const layer = Layer.effect(GitLabPullRequestCli, make);