Repository navigation
Expand file tree
/
Copy pathGitLabPullRequestCli.ts
More file actions
1517 lines (1424 loc) · 52.6 KB
/
Copy pathGitLabPullRequestCli.ts
File metadata and controls
1517 lines (1424 loc) · 52.6 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 { isCommitSha } from "@t3tools/source-control-core/server/pullRequestUtils";
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 { resolvePullRequestAuthorFilter, VcsProcessExitError } from "@t3tools/contracts";
import type {
PullRequestAction,
PullRequestActor,
PullRequestComment,
PullRequestCommit,
PullRequestInvolvement,
PullRequestLabel,
PullRequestListFilters,
PullRequestListState,
PullRequestMergeCapabilities,
PullRequestMergeMethod,
PullRequestReaction,
PullRequestReactionContent,
PullRequestReviewCommentDraft,
PullRequestReviewPosition,
PullRequestReviewThread,
PullRequestReviewVerdict,
PullRequestReviewerCandidateList,
} from "@t3tools/contracts";
import * as GitLabCli from "./GitLabCli.ts";
import {
AWARD_EMOJI_GRAPHQL_QUERY,
decodeAwardEmojiJson,
decodeCommitDiffRefsJson,
decodeCommitsJson,
decodeDiffRefsJson,
decodeDiscussionsJson,
decodeMergeRequestDetailJson,
decodeMergeRequestDiffsJson,
decodeMergeRequestChangesJson,
decodeMergeRequestListJson,
decodeNotesJson,
decodeOwnAwardIdJson,
decodeProjectMergeCapabilitiesJson,
decodeProjectLabelsJson,
decodeProjectUsersJson,
decodeRepositoryBlobsJson,
decodeViewerJson,
gitLabAwardName,
REPOSITORY_BLOBS_GRAPHQL_QUERY,
type GitLabDiffRefs,
type GitLabMergeRequestDetail,
type GitLabMergeRequestListItem,
type GitLabProjectUsers,
} from "./gitLabMergeRequestJson.ts";
import type { ProviderListCursor } from "@t3tools/source-control-core/server/PullRequestProvider";
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}`;
}
}
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}`;
}
}
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}`;
}
}
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}`;
}
}
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}`;
}
}
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}`;
}
}
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 `per_page` limit. */
const MAX_PAGE_SIZE = 100;
const COMMIT_PAGE_SIZE = 100;
/**
* GitLab 15.7 through 17.10 answer the merge request `/diffs` endpoint with a 500 for any
* `per_page` above 30 (fixed in 17.11), so those pages stay at a size every version accepts.
* A commit's own diff endpoint never had that bug and keeps the full page.
*/
const MERGE_REQUEST_DIFF_PAGE_SIZE = 30;
const diffPageSize = (commit: string | undefined) =>
commit === undefined ? MERGE_REQUEST_DIFF_PAGE_SIZE : MAX_PAGE_SIZE;
const CONVERSATION_PAGES = 10;
const DIFF_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
const DIFF_TIMEOUT_MS = 60_000;
const isVcsProcessExitError = Schema.is(VcsProcessExitError);
const DIFF_FILE_MAX_OUTPUT_BYTES = 1024 * 1024;
export interface GitLabMergeRequestListBatch {
readonly items: ReadonlyArray<GitLabMergeRequestListItem>;
readonly truncated: boolean;
readonly cursorAdvance: number;
}
export interface GitLabMergeRequestDiffSlice {
readonly patch: string;
readonly truncated: boolean;
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;
readonly query?: string | undefined;
readonly cursor?: ProviderListCursor | undefined;
readonly filters?: PullRequestListFilters | 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;
readonly cursor?: string | undefined;
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>;
readonly getFileRevisions: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly paths: ReadonlyArray<string>;
}) => Effect.Effect<ReadonlyMap<string, string>, GitLabPullRequestCliError>;
readonly listReviewerCandidates: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
}) => Effect.Effect<PullRequestReviewerCandidateList, GitLabPullRequestCliError>;
readonly listProjectLabels: (input: {
readonly cwd: string;
readonly repository: string;
readonly search?: string | undefined;
}) => Effect.Effect<
{ readonly items: ReadonlyArray<PullRequestLabel>; readonly truncated: boolean },
GitLabPullRequestCliError
>;
readonly listProjectUsers: (input: {
readonly cwd: string;
readonly repository: string;
readonly search?: string | undefined;
}) => Effect.Effect<
{ readonly items: ReadonlyArray<PullRequestActor>; readonly truncated: boolean },
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>;
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>;
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
>;
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>;
}
>()("@t3tools/source-control-gitlab/server/GitLabPullRequestCli") {}
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 {
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 [];
}
}
/**
* GitLab's `labels` asks for every label it names, so only groups of one go to it; a group of
* alternatives is left for the service to narrow. A comma would split a name in two, and `None`
* and `Any` mean "unlabeled" and "labeled" to GitLab rather than labels of those names.
*/
function filterParams(input: {
readonly filters?: PullRequestListFilters | undefined;
readonly involvement: PullRequestInvolvement;
readonly viewer: string;
}): ReadonlyArray<readonly [string, string]> {
const filters = input.filters;
if (filters === undefined) return [];
const listable = (names: ReadonlyArray<string>) =>
names.filter((name) => !name.includes(",") && !/^(?:none|any)$/iu.test(name.trim()));
const required = listable(
(filters.labels ?? []).flatMap((group) => (group.length === 1 ? group : [])),
);
const excluded = listable(filters.excludedLabels ?? []);
return [
...(required.length === 0 ? [] : [["labels", required.join(",")] as const]),
...(excluded.length === 0 ? [] : [["not[labels]", excluded.join(",")] as const]),
...(filters.author === undefined || input.involvement === "authored"
? []
: [
[
"author_username",
resolvePullRequestAuthorFilter(filters.author, input.viewer),
] as const,
]),
...(filters.draft === undefined
? []
: [["wip", filters.draft === "only" ? "yes" : "no"] as const]),
];
}
function diffCursorPage(cursor: string): number | null {
return /^[1-9][0-9]{0,6}$/.test(cursor) ? Number(cursor) : null;
}
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 defaults to auto-merge during a running pipeline.
"--auto-merge=false",
"--yes",
...(mergeMethod === "squash" ? ["--squash"] : []),
];
case "enable-auto-merge":
return [
"merge",
"--auto-merge=true",
"--yes",
...(mergeMethod === "squash" ? ["--squash"] : []),
];
case "disable-auto-merge":
return [];
case "ready":
return ["update", "--ready"];
case "draft":
return ["update", "--draft"];
case "close":
return ["close"];
case "update-branch":
return ["rebase"];
case "reopen":
return ["reopen"];
case "revert":
case "approve-workflows":
case "delete-branch":
throw new Error(`GitLab merge request action ${action} is unsupported`);
}
}
/** @public */
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]),
// glab --input keeps payloads out of argv/logs but omits GitLab's required Content-Type.
...(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 }),
});
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 filters?: PullRequestListFilters | undefined;
readonly page: number;
readonly collected: ReadonlyArray<GitLabMergeRequestListItem>;
readonly cursorAdvance: number;
}): Effect.Effect<GitLabMergeRequestListBatch, GitLabPullRequestCliError> => {
// GitLab's timestamp filter can repeat equal-time pages forever; use offsets.
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;
// Bound raw pages to stop recursion on entirely malformed results.
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),
...searchParams(input.query),
...filterParams(input),
["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);
// Count malformed rows to avoid ending pagination 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,
});
}),
);
};
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(diffPageSize(input.commit))],
["page", String(input.page)],
])}`,
maxOutputBytes: DIFF_MAX_OUTPUT_BYTES,
timeoutMs: DIFF_TIMEOUT_MS,
}).pipe(
Effect.map((result) => ({ result, legacy: false })),
Effect.catchTags({
GitLabCliCommandError: (error) => {
if (
input.commit !== undefined ||
input.page !== 1 ||
!isVcsProcessExitError(error.cause) ||
error.cause.failureKind !== "not-found"
) {
return Effect.fail(error);
}
// GitLab before 15.7 has no /diffs endpoint. /changes returns one complete slice.
return api({
cwd: input.cwd,
path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/changes?access_raw_diffs=true`,
maxOutputBytes: DIFF_MAX_OUTPUT_BYTES,
timeoutMs: DIFF_TIMEOUT_MS,
}).pipe(Effect.map((result) => ({ result, legacy: true })));
},
}),
Effect.flatMap(({ result, legacy }) => {
// Returning no cursor for byte-truncated JSON would lose subsequent pages.
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 = (legacy ? decodeMergeRequestChangesJson : 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 = !legacy && decoded.success.rawCount >= diffPageSize(input.commit);
return Effect.succeed({
// Terminate slices so a hunkless header cannot run into the next slice.
patch: patch.length === 0 ? patch : patch.replace(/\n?$/, "\n"),
truncated: decoded.success.truncated,
nextCursor: morePages ? String(input.page + 1) : null,
});
}),
);
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 });
}),
);
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];
// Plain notes count toward the page size even when no positioned threads survive decoding.
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 });
}),
);
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,
}),
);
}
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);
}),
);
const mergeRequestDetail = (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
}): Effect.Effect<GitLabMergeRequestDetail, GitLabPullRequestCliError> =>
api({
cwd: input.cwd,
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,
}),
);
}),
);
const projectUsers = (input: {
readonly cwd: string;
readonly repository: string;
readonly search?: string | undefined;
}): Effect.Effect<GitLabProjectUsers, GitLabPullRequestCliError> =>
api({
cwd: input.cwd,
path: `projects/${projectPath(input.repository)}/users?${query([
["per_page", String(MAX_PAGE_SIZE)],
...searchParams(input.search),
])}`,
}).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,
}),
);
}),
);
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`;
};
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>>;
} | null;
}): Effect.Effect<
{
readonly reactions: ReadonlyArray<PullRequestReaction>;
readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>;
},
GitLabPullRequestCliError
> =>
api({
cwd: input.cwd,
path: "graphql",
method: "POST",
stdin: JSON.stringify({
query: AWARD_EMOJI_GRAPHQL_QUERY,
variables: {
fullPath: input.repository,
iid: String(input.number),
cursor: input.cursor,
},
}),
}).pipe(
Effect.flatMap((result) => {
const decoded = decodeAwardEmojiJson(result.stdout.trim());
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabMergeRequestReadError({
command: "glab",