Repository navigation
Expand file tree
/
Copy pathGitLabPullRequestCli.ts
More file actions
1495 lines (1406 loc) · 55.3 KB
/
Copy pathGitLabPullRequestCli.ts
File metadata and controls
1495 lines (1406 loc) · 55.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import type {
PullRequestAction,
PullRequestComment,
PullRequestCommit,
PullRequestInvolvement,
PullRequestListState,
PullRequestMergeCapabilities,
PullRequestMergeMethod,
PullRequestReaction,
PullRequestReactionContent,
PullRequestReviewCommentDraft,
PullRequestReviewPosition,
PullRequestReviewThread,
PullRequestReviewVerdict,
PullRequestReviewerCandidateList,
} from "@t3tools/contracts";
import * as GitLabCli from "../sourceControl/GitLabCli.ts";
import {
AWARD_EMOJI_GRAPHQL_QUERY,
decodeAwardEmojiJson,
decodeCommitDiffRefsJson,
decodeCommitsJson,
decodeDiffRefsJson,
decodeDiscussionsJson,
decodeMergeRequestDetailJson,
decodeMergeRequestDiffsJson,
decodeMergeRequestListJson,
decodeNotesJson,
decodeOwnAwardIdJson,
decodeProjectMergeCapabilitiesJson,
decodeProjectUsersJson,
decodeRepositoryBlobsJson,
decodeViewerJson,
gitLabAwardName,
REPOSITORY_BLOBS_GRAPHQL_QUERY,
type GitLabDiffRefs,
type GitLabMergeRequestDetail,
type GitLabMergeRequestListItem,
type GitLabProjectUsers,
} from "./gitLabMergeRequestJson.ts";
import type { ProviderListCursor } from "./PullRequestProvider.ts";
/**
* Names the read that produced unusable output, so a failure reports the call it came from
* rather than borrowing another operation's message.
*/
export class GitLabMergeRequestReadError extends Schema.TaggedError<GitLabMergeRequestReadError>()(
"GitLabMergeRequestReadError",
{
command: Schema.Literal("glab"),
cwd: Schema.String,
operation: Schema.String,
cause: Schema.Defect(),
},
) {
get detail(): string {
return `GitLab CLI returned an unreadable ${this.operation} response.`;
}
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
}
/** Not a decode failure: glab answered, the account it answered for just has no username. */
export class GitLabViewerUnavailableError extends Schema.TaggedError<GitLabViewerUnavailableError>()(
"GitLabViewerUnavailableError",
{
command: Schema.Literal("glab"),
cwd: Schema.String,
},
) {
get detail(): string {
return "GitLab CLI returned no username for the authenticated account.";
}
override get message(): string {
return `GitLab CLI failed in getViewerUsername: ${this.detail}`;
}
}
/** Not a decode failure: GitLab answered, the merge request just has no revisions to place a
* comment against. */
export class GitLabDiffRefsUnavailableError extends Schema.TaggedError<GitLabDiffRefsUnavailableError>()(
"GitLabDiffRefsUnavailableError",
{
command: Schema.Literal("glab"),
cwd: Schema.String,
number: Schema.Int,
},
) {
get detail(): string {
return "The merge request reported no diff revisions.";
}
override get message(): string {
return `GitLab CLI failed in getDiffRefs: ${this.detail}`;
}
}
/** Not a decode failure: the reader asked to carry on from a cursor this walk never handed out. */
export class GitLabDiffCursorError extends Schema.TaggedError<GitLabDiffCursorError>()(
"GitLabDiffCursorError",
{
command: Schema.Literal("glab"),
cwd: Schema.String,
},
) {
get detail(): string {
return "The diff cursor was not one this merge request handed out.";
}
override get message(): string {
return `GitLab CLI failed in getMergeRequestDiff: ${this.detail}`;
}
}
/** Not a decode failure: the reader named a commit that is not a sha this project could hold. */
export class GitLabDiffCommitError extends Schema.TaggedError<GitLabDiffCommitError>()(
"GitLabDiffCommitError",
{
command: Schema.Literal("glab"),
cwd: Schema.String,
},
) {
get detail(): string {
return "The named commit was not a commit sha.";
}
override get message(): string {
return `GitLab CLI failed in getMergeRequestDiff: ${this.detail}`;
}
}
/** The commit exists and decoded, but it has no parent to use as the old revision. */
export class GitLabDiffCommitParentUnavailableError extends Schema.TaggedError<GitLabDiffCommitParentUnavailableError>()(
"GitLabDiffCommitParentUnavailableError",
{
command: Schema.Literal("glab"),
cwd: Schema.String,
commit: Schema.String,
},
) {
get detail(): string {
return `Commit ${this.commit} reported no parent revision.`;
}
override get message(): string {
return `GitLab CLI failed in getMergeRequestDiffFileContents: ${this.detail}`;
}
}
/** A blob exists, but expanding it would be unsafe or would not produce text. */
export class GitLabDiffFileContentsUnavailableError extends Schema.TaggedError<GitLabDiffFileContentsUnavailableError>()(
"GitLabDiffFileContentsUnavailableError",
{
command: Schema.Literal("glab"),
cwd: Schema.String,
path: Schema.String,
reason: Schema.Literals(["oversized", "binary"]),
},
) {
get detail(): string {
return this.reason === "oversized"
? `The diff file '${this.path}' exceeds the 1 MB expansion limit.`
: `The diff file '${this.path}' is binary.`;
}
override get message(): string {
return `GitLab CLI failed in getMergeRequestDiffFileContents: ${this.detail}`;
}
}
export type GitLabPullRequestCliError =
| GitLabCli.GitLabCliError
| GitLabMergeRequestReadError
| GitLabDiffCursorError
| GitLabDiffCommitError
| GitLabDiffCommitParentUnavailableError
| GitLabDiffFileContentsUnavailableError
| GitLabDiffRefsUnavailableError
| GitLabViewerUnavailableError;
/** GitLab's own ceiling on `per_page`, so a larger page has to be walked. */
const MAX_PAGE_SIZE = 100;
/** Commit history is read one page deep; the rest of a long history stays on GitLab. */
const COMMIT_PAGE_SIZE = 100;
/**
* Pages of the conversation to follow before it is reported as truncated. GitLab caps a page at
* a hundred, so this is a thousand notes and a thousand discussions — more than any merge
* request a person is reading holds, and a walk that ends whatever the host has.
*/
const CONVERSATION_PAGES = 10;
const DIFF_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
const DIFF_TIMEOUT_MS = 60_000;
const DIFF_FILE_MAX_OUTPUT_BYTES = 1024 * 1024;
export interface GitLabMergeRequestListBatch {
readonly items: ReadonlyArray<GitLabMergeRequestListItem>;
readonly truncated: boolean;
/** Raw GitLab rows consumed to produce this page, including malformed rows. */
readonly cursorAdvance: number;
}
export interface GitLabMergeRequestDiffSlice {
readonly patch: string;
/** Files in this slice had their hunks withheld, as opposed to there being more slices. */
readonly truncated: boolean;
/** Where the next slice starts, or null once the patch is whole. */
readonly nextCursor: string | null;
}
export class GitLabPullRequestCli extends Context.Service<
GitLabPullRequestCli,
{
readonly getViewerUsername: (input: {
readonly cwd: string;
}) => Effect.Effect<string, GitLabPullRequestCliError>;
readonly listMergeRequests: (input: {
readonly cwd: string;
readonly repository: string;
readonly state: PullRequestListState;
readonly involvement: PullRequestInvolvement;
readonly viewer: string;
readonly limit: number;
/** Free text for GitLab's own `search`, which matches title and description. */
readonly query?: string | undefined;
/** Where to carry on from in GitLab's stable update-ordered row set. */
readonly cursor?: ProviderListCursor | undefined;
}) => Effect.Effect<GitLabMergeRequestListBatch, GitLabPullRequestCliError>;
readonly getMergeRequestDetail: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
}) => Effect.Effect<GitLabMergeRequestDetail, GitLabPullRequestCliError>;
readonly listNotes: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
}) => Effect.Effect<
{ readonly comments: ReadonlyArray<PullRequestComment>; readonly truncated: boolean },
GitLabPullRequestCliError
>;
readonly listCommits: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
}) => Effect.Effect<ReadonlyArray<PullRequestCommit>, GitLabPullRequestCliError>;
readonly getMergeRequestDiff: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
/** Absent asks for the first slice; anything else is a cursor a slice handed back. */
readonly cursor?: string | undefined;
/** One commit's own changes, rather than everything the merge request carries. */
readonly commit?: string | undefined;
}) => Effect.Effect<GitLabMergeRequestDiffSlice, GitLabPullRequestCliError>;
readonly getMergeRequestDiffFileContents: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly commit?: string | undefined;
readonly changeType: "change" | "rename-pure" | "rename-changed" | "new" | "deleted";
readonly oldPath: string;
readonly newPath: string;
}) => Effect.Effect<
{ readonly oldContents: string; readonly newContents: string },
GitLabPullRequestCliError
>;
readonly getProjectMergeCapabilities: (input: {
readonly cwd: string;
readonly repository: string;
}) => Effect.Effect<PullRequestMergeCapabilities, GitLabPullRequestCliError>;
/**
* What the merge request's head has of each of these paths, as blob ids.
*
* The head sha comes from the merge request's own diff refs, so the answer is the version a
* reader is looking at rather than whatever the source branch has moved on to. A path the
* head does not have is answered as the empty revision, since the batch it was asked in was
* looked at; a batch GitLab did not answer for is left out instead.
*/
readonly getFileRevisions: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly paths: ReadonlyArray<string>;
}) => Effect.Effect<ReadonlyMap<string, string>, GitLabPullRequestCliError>;
/**
* Who this merge request may be sent to, and who it has already been sent to. Two reads at
* once, because GitLab keeps the people with access on the project and the reviewers on the
* merge request, and neither answers for the other.
*/
readonly listReviewerCandidates: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
}) => Effect.Effect<PullRequestReviewerCandidateList, GitLabPullRequestCliError>;
readonly setReviewerRequest: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly reviewers: ReadonlyArray<{ readonly id: string }>;
readonly requested: boolean;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
readonly runMergeRequestAction: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly action: PullRequestAction;
readonly mergeMethod?: PullRequestMergeMethod;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
/** Whichever of the two is given is sent. GitLab calls a merge request's body its description. */
readonly updateMergeRequest: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly title?: string | undefined;
readonly description?: string | undefined;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
readonly commentOnMergeRequest: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly body: string;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
readonly updateNote: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly noteId: string;
readonly body: string;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
readonly listDiscussions: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
}) => Effect.Effect<
{ readonly threads: ReadonlyArray<PullRequestReviewThread>; readonly truncated: boolean },
GitLabPullRequestCliError
>;
readonly submitReview: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly verdict: PullRequestReviewVerdict;
readonly body: string;
readonly comments: ReadonlyArray<PullRequestReviewCommentDraft>;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
readonly replyToDiscussion: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly discussionId: string;
readonly body: string;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
readonly setDiscussionResolution: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly discussionId: string;
readonly resolved: boolean;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
/** The awards on the merge request and on every note of it, keyed by the note's REST id. */
readonly listReactions: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
}) => Effect.Effect<
{
readonly reactions: ReadonlyArray<PullRequestReaction>;
readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>;
},
GitLabPullRequestCliError
>;
/**
* Awards an emoji, or takes the award back. `noteId` is a note of the merge request; absent
* awards the merge request itself, which is where its description's reactions live.
*/
readonly setReaction: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly noteId?: string | undefined;
readonly content: PullRequestReactionContent;
readonly reacted: boolean;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
}
>()("t3/pullRequest/GitLabPullRequestCli") {}
/** The REST API addresses a project by its URL-encoded full path. */
function projectPath(repository: string): string {
return encodeURIComponent(repository.trim());
}
function gitLabReviewPositionLines(
position: PullRequestReviewPosition,
):
| { readonly new_line: number }
| { readonly old_line: number }
| { readonly old_line: number; readonly new_line: number } {
switch (position.kind) {
case "added":
return { new_line: position.newLine };
case "deleted":
return { old_line: position.oldLine };
case "context":
return { old_line: position.oldLine, new_line: position.newLine };
}
}
function stateParam(state: PullRequestListState): string {
// GitLab's `closed` already excludes merged merge requests, so no extra filter is needed,
// and it spans every state under `all`.
return state === "open" ? "opened" : state;
}
function involvementParams(input: {
readonly involvement: PullRequestInvolvement;
readonly viewer: string;
}): ReadonlyArray<readonly [string, string]> {
switch (input.involvement) {
case "authored":
return [["author_username", input.viewer]];
case "reviewing":
return [["reviewer_username", input.viewer]];
case "all":
return [];
}
}
/**
* The page a diff cursor names, or null for anything this walk cannot have issued. The cursor
* arrives from the reader as a string and goes straight into a query, so it is parsed rather
* than trusted; the length bound keeps a page number out of exponential notation.
*/
function diffCursorPage(cursor: string): number | null {
return /^[1-9][0-9]{0,6}$/.test(cursor) ? Number(cursor) : null;
}
/**
* A commit sha arrives from the reader and goes straight into a request path, so it is checked
* rather than trusted: hexadecimal only, from the shortest abbreviation a host prints up to a
* whole sha.
*/
function isCommitSha(value: string): boolean {
return /^[0-9a-f]{7,64}$/i.test(value);
}
function searchParams(search: string | undefined): ReadonlyArray<readonly [string, string]> {
const trimmed = search?.trim() ?? "";
return trimmed.length === 0 ? [] : [["search", trimmed]];
}
function query(params: ReadonlyArray<readonly [string, string]>): string {
return params.map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&");
}
function actionArgs(
action: PullRequestAction,
mergeMethod: PullRequestMergeMethod | undefined,
): ReadonlyArray<string> {
switch (action) {
case "merge":
return [
"merge",
// glab turns on auto-merge whenever a pipeline is running. The button means merge now.
"--auto-merge=false",
"--yes",
...(mergeMethod === "squash" ? ["--squash"] : []),
...(mergeMethod === "rebase" ? ["--rebase"] : []),
];
// The same command with the flag the other way up: here the wait is the whole point, so
// glab is told to arm the merge rather than talked out of it.
case "enable-auto-merge":
return [
"merge",
"--auto-merge=true",
"--yes",
...(mergeMethod === "squash" ? ["--squash"] : []),
...(mergeMethod === "rebase" ? ["--rebase"] : []),
];
// Never reached: taking the arming back has no `glab mr` command, so it goes to the API.
case "disable-auto-merge":
return [];
case "ready":
return ["update", "--ready"];
case "draft":
return ["update", "--draft"];
case "close":
return ["close"];
// A rebase, because GitLab has no other way to move a branch onto its target: there is no
// merge-the-target-in equivalent of GitHub's update button, which is why this host declares
// `rebase` alone and never has to read the method it was handed.
case "update-branch":
return ["rebase"];
case "reopen":
return ["reopen"];
// Never reached: this host does not declare the action, so the service refuses it first.
case "revert":
case "approve-workflows":
throw new Error(`GitLab merge request action ${action} is unsupported`);
}
}
/** @public Service construction is part of the canonical Effect module API. */
export const make = Effect.gen(function* () {
const gitlab = yield* GitLabCli.GitLabCli;
const api = (input: {
readonly cwd: string;
readonly path: string;
readonly method?: string;
readonly stdin?: string;
readonly maxOutputBytes?: number;
readonly timeoutMs?: number;
}) =>
gitlab.execute({
cwd: input.cwd,
args: [
"api",
input.path,
...(input.method === undefined ? [] : ["--method", input.method]),
// A raw body from stdin: argv is visible in process listings and is echoed back
// inside process-runner failure messages. Unlike `gh`, `glab api --input` sends no
// Content-Type at all, and GitLab answers a bodyless content type with HTTP 415.
...(input.stdin === undefined
? []
: ["--input", "-", "--header", "Content-Type: application/json"]),
],
...(input.stdin === undefined ? {} : { stdin: input.stdin }),
...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),
});
/**
* `per_page` stops at 100, so a larger page is walked one request at a time. The walk is
* bounded twice over: it stops on a short page or once the extra row that reveals a next
* page has been read, and it never asks for more pages than the caller's page needs. The
* second bound is what makes it terminate when every row on a page fails to decode, which
* leaves nothing collected but does not mean GitLab has run out of rows.
*/
const listPage = (input: {
readonly cwd: string;
readonly repository: string;
readonly state: PullRequestListState;
readonly involvement: PullRequestInvolvement;
readonly viewer: string;
readonly limit: number;
readonly query?: string | undefined;
readonly cursor?: ProviderListCursor | undefined;
readonly page: number;
readonly collected: ReadonlyArray<GitLabMergeRequestListItem>;
readonly cursorAdvance: number;
}): Effect.Effect<GitLabMergeRequestListBatch, GitLabPullRequestCliError> => {
// A continuation uses GitLab's offset pagination. Its timestamp filter is inclusive and has
// no tie-breaker, so a page where many rows share the boundary would otherwise return the
// same prefix forever. `delivered` is the stable offset the service has already handed over.
const delivered = input.cursor?.delivered ?? 0;
const perPage = Math.min(input.limit + 1, MAX_PAGE_SIZE);
const firstPage = Math.floor(delivered / perPage) + 1;
const skipOnFirstPage = input.page === firstPage ? delivered % perPage : 0;
// A page made entirely of malformed rows has no item from which the service can build a
// continuation. Bound the walk to the raw span this request asked for rather than recursing
// forever on a host that keeps returning full unusable pages.
const lastPage = Math.floor((delivered + input.limit) / perPage) + 1;
return api({
cwd: input.cwd,
path: `projects/${projectPath(input.repository)}/merge_requests?${query([
["state", stateParam(input.state)],
...involvementParams(input),
// The listing is read through `glab api` rather than `glab mr list`, so the search is
// the REST API's own `search` parameter — the one `mr list --search` passes on. It
// matches title and description, and travels URL-encoded like every other value here,
// so no text in it can become a parameter of its own.
...searchParams(input.query),
["order_by", "updated_at"],
["sort", "desc"],
["per_page", String(perPage)],
["page", String(input.page)],
])}`,
}).pipe(
Effect.flatMap((result) => {
const raw = result.stdout.trim();
if (raw.length === 0) {
return Effect.succeed({
items: input.collected,
truncated: false,
cursorAdvance: input.cursorAdvance,
});
}
const decoded = decodeMergeRequestListJson(raw);
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabMergeRequestReadError({
command: "glab",
cwd: input.cwd,
operation: "listMergeRequests",
cause: decoded.failure,
}),
);
}
const pageItems: GitLabMergeRequestListItem[] = [];
const pageRawIndexes: number[] = [];
for (const [index, item] of decoded.success.items.entries()) {
const rawIndex = decoded.success.rawIndexes[index]!;
if (rawIndex < skipOnFirstPage) continue;
pageItems.push(item);
pageRawIndexes.push(rawIndex);
}
const remaining = input.limit - input.collected.length;
const lastItemRawIndex = pageRawIndexes[remaining - 1];
if (lastItemRawIndex !== undefined) {
const consumed = lastItemRawIndex + 1 - skipOnFirstPage;
return Effect.succeed({
items: [...input.collected, ...pageItems.slice(0, remaining)],
truncated:
lastItemRawIndex + 1 < decoded.success.rawCount ||
decoded.success.rawCount === perPage,
cursorAdvance: input.cursorAdvance + consumed,
});
}
const collected = [...input.collected, ...pageItems];
const consumed = Math.max(0, decoded.success.rawCount - skipOnFirstPage);
// Counted before decoding, so a skipped malformed row cannot end paging early.
const exhausted = decoded.success.rawCount < perPage;
if (exhausted) {
return Effect.succeed({
items: collected,
truncated: false,
cursorAdvance: input.cursorAdvance + consumed,
});
}
if (input.page >= lastPage) {
return Effect.succeed({
items: collected,
truncated: true,
cursorAdvance: input.cursorAdvance + consumed,
});
}
return listPage({
...input,
page: input.page + 1,
collected,
cursorAdvance: input.cursorAdvance + consumed,
});
}),
);
};
/**
* One page of a merge request's files, as a patch that stands on its own. GitLab pages
* `/diffs` by offset and has no cursor of its own, so the page number is the cursor; the
* caller carries on from it for as long as GitLab keeps handing full pages back.
*
* A named commit is read from the commit's own diff, which answers in the same shape and pages
* the same way.
*/
const diffPage = (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly page: number;
readonly commit?: string | undefined;
}): Effect.Effect<GitLabMergeRequestDiffSlice, GitLabPullRequestCliError> =>
api({
cwd: input.cwd,
path: `projects/${projectPath(input.repository)}/${
input.commit === undefined
? `merge_requests/${input.number}/diffs`
: `repository/commits/${input.commit}/diff`
}?${query([
["per_page", String(MAX_PAGE_SIZE)],
["page", String(input.page)],
])}`,
maxOutputBytes: DIFF_MAX_OUTPUT_BYTES,
timeoutMs: DIFF_TIMEOUT_MS,
}).pipe(
Effect.flatMap((result) => {
// A byte-truncated response is a JSON prefix, so this page cannot be read at all.
// Answering with no cursor would call the diff whole while silently dropping this page
// and every one after it, so the read fails and says which page could not be had.
if (result.stdoutTruncated) {
return Effect.fail(
new GitLabMergeRequestReadError({
command: "glab",
cwd: input.cwd,
operation: "getMergeRequestDiff",
cause: new Error(
`Page ${input.page} of the merge request diff was too large to read.`,
),
}),
);
}
const decoded = decodeMergeRequestDiffsJson(result.stdout.trim());
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabMergeRequestReadError({
command: "glab",
cwd: input.cwd,
operation: "getMergeRequestDiff",
cause: decoded.failure,
}),
);
}
const patch = decoded.success.patch;
// Counted before decoding, so a page whose files all failed to decode still moves on
// rather than pointing the reader back at the page it just read.
const morePages = decoded.success.rawCount >= MAX_PAGE_SIZE;
return Effect.succeed({
// The slice ends on a newline, so a file GitLab gave a header and no hunks for does
// not run into the first line of the next slice.
patch: patch.length === 0 ? patch : patch.replace(/\n?$/, "\n"),
truncated: decoded.success.truncated,
nextCursor: morePages ? String(input.page + 1) : null,
});
}),
);
/**
* The conversation, a page at a time. GitLab pages by offset and reports no total, so a short
* page is the only thing that says it is done — and the raw count decides, not the kept one:
* the notes GitLab wrote itself are dropped, and a whole page of them still means there is
* more to read.
*/
const notesPage = (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly page: number;
readonly collected: ReadonlyArray<PullRequestComment>;
}): Effect.Effect<
{ readonly comments: ReadonlyArray<PullRequestComment>; readonly truncated: boolean },
GitLabPullRequestCliError
> =>
api({
cwd: input.cwd,
path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/notes?${query(
[
["per_page", String(MAX_PAGE_SIZE)],
["page", String(input.page)],
["order_by", "created_at"],
["sort", "asc"],
],
)}`,
}).pipe(
Effect.flatMap((result) => {
const decoded = decodeNotesJson(result.stdout.trim());
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabMergeRequestReadError({
command: "glab",
cwd: input.cwd,
operation: "listNotes",
cause: decoded.failure,
}),
);
}
const collected = [...input.collected, ...decoded.success.comments];
if (decoded.success.rawCount < MAX_PAGE_SIZE) {
return Effect.succeed({ comments: collected, truncated: false });
}
return input.page >= CONVERSATION_PAGES
? Effect.succeed({ comments: collected, truncated: true })
: notesPage({ ...input, page: input.page + 1, collected });
}),
);
/** The positioned discussions, walked the same way and stopped by the same bound. */
const discussionsPage = (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly page: number;
readonly collected: ReadonlyArray<PullRequestReviewThread>;
}): Effect.Effect<
{ readonly threads: ReadonlyArray<PullRequestReviewThread>; readonly truncated: boolean },
GitLabPullRequestCliError
> =>
api({
cwd: input.cwd,
path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/discussions?${query(
[
["per_page", String(MAX_PAGE_SIZE)],
["page", String(input.page)],
],
)}`,
}).pipe(
Effect.flatMap((result) => {
const decoded = decodeDiscussionsJson(result.stdout.trim());
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabMergeRequestReadError({
command: "glab",
cwd: input.cwd,
operation: "listDiscussions",
cause: decoded.failure,
}),
);
}
const collected = [...input.collected, ...decoded.success.threads];
// The raw count again: this endpoint returns the plain notes too, so a full page of
// those is not the end of the positioned ones.
if (decoded.success.rawCount < MAX_PAGE_SIZE) {
return Effect.succeed({ threads: collected, truncated: false });
}
return input.page >= CONVERSATION_PAGES
? Effect.succeed({ threads: collected, truncated: true })
: discussionsPage({ ...input, page: input.page + 1, collected });
}),
);
/**
* The revisions a positioned comment is written against. GitLab resolves a comment's line
* against these three shas, so a review with line comments cannot be sent without them.
*/
const getDiffRefs = (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
}): Effect.Effect<GitLabDiffRefs, GitLabPullRequestCliError> =>
api({
cwd: input.cwd,
path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`,
}).pipe(
Effect.flatMap((result): Effect.Effect<GitLabDiffRefs, GitLabPullRequestCliError> => {
const decoded = decodeDiffRefsJson(result.stdout.trim());
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabMergeRequestReadError({
command: "glab",
cwd: input.cwd,
operation: "getDiffRefs",
cause: decoded.failure,
}),
);
}
// A merge request with no diff refs is a well-formed answer that cannot carry a
// positioned comment — a dead end, but not something that failed to be read.
return decoded.success === null
? Effect.fail(
new GitLabDiffRefsUnavailableError({
command: "glab",
cwd: input.cwd,
number: input.number,
}),
)
: Effect.succeed(decoded.success);
}),
);
const getCommitDiffRefs = (input: {
readonly cwd: string;
readonly repository: string;
readonly commit: string;
readonly allowRoot: boolean;
}): Effect.Effect<GitLabDiffRefs, GitLabPullRequestCliError> =>
api({
cwd: input.cwd,
path: `projects/${projectPath(input.repository)}/repository/commits/${input.commit}`,
}).pipe(
Effect.flatMap((result): Effect.Effect<GitLabDiffRefs, GitLabPullRequestCliError> => {
const decoded = decodeCommitDiffRefsJson(result.stdout.trim());
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabMergeRequestReadError({
command: "glab",
cwd: input.cwd,
operation: "getMergeRequestDiffFileContents",
cause: decoded.failure,
}),
);
}
return decoded.success === null
? input.allowRoot
? Effect.succeed({
baseSha: "",
headSha: input.commit,
startSha: "",
})
: Effect.fail(
new GitLabDiffCommitParentUnavailableError({
command: "glab",
cwd: input.cwd,
commit: input.commit,
}),
)
: Effect.succeed(decoded.success);
}),
);
/**
* The merge request itself, which several calls need for different parts of it: the detail for
* everything, and the reviewer paths for the ids GitLab writes a reviewer set with.
*/
const mergeRequestDetail = (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
}): Effect.Effect<GitLabMergeRequestDetail, GitLabPullRequestCliError> =>
api({
cwd: input.cwd,
// How far behind the target branch this one is comes only when asked for by name, and it
// is asked for here rather than on a second read because it is the same merge request.
path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}?${query([
["include_diverged_commits_count", "true"],
])}`,
}).pipe(
Effect.flatMap((result) => {
const decoded = decodeMergeRequestDetailJson(result.stdout.trim());
return Result.isSuccess(decoded)
? Effect.succeed(decoded.success)
: Effect.fail(
new GitLabMergeRequestReadError({
command: "glab",
cwd: input.cwd,
operation: "getMergeRequestDetail",
cause: decoded.failure,
}),
);
}),
);
/** The people with access to the project, one page deep. */
const projectUsers = (input: {
readonly cwd: string;
readonly repository: string;
}): Effect.Effect<GitLabProjectUsers, GitLabPullRequestCliError> =>
api({
cwd: input.cwd,
path: `projects/${projectPath(input.repository)}/users?${query([
["per_page", String(MAX_PAGE_SIZE)],
])}`,
}).pipe(
Effect.flatMap((result) => {
const decoded = decodeProjectUsersJson(result.stdout.trim());
return Result.isSuccess(decoded)
? Effect.succeed(decoded.success)
: Effect.fail(
new GitLabMergeRequestReadError({
command: "glab",
cwd: input.cwd,
operation: "listReviewerCandidates",
cause: decoded.failure,
}),
);
}),
);
/** Where an award is written: a note of the merge request, or the merge request itself. */
const awardSubjectPath = (input: {
readonly repository: string;
readonly number: number;
readonly noteId?: string | undefined;
}) => {
const mergeRequest = `projects/${projectPath(input.repository)}/merge_requests/${input.number}`;
return input.noteId === undefined
? `${mergeRequest}/award_emoji`
: `${mergeRequest}/notes/${encodeURIComponent(input.noteId)}/award_emoji`;
};
/**
* The awards on the merge request and its notes, a page of notes at a time. Bounded by the same
* count as the conversation itself: awards past the notes that were read belong to notes the
* page is not showing.
*/
const awardsPage = (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly cursor: string | null;
readonly page: number;
readonly collected: {
readonly reactions: ReadonlyArray<PullRequestReaction>;
readonly reactionsByNoteId: Map<string, ReadonlyArray<PullRequestReaction>>;