Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Exit from "effect/Exit";
3import * as Result from "effect/Result";
4import * as Schema from "effect/Schema";
5import type {
6 PullRequestActor,
7 PullRequestCheck,
8 PullRequestCheckStatus,
9 PullRequestComment,
10 PullRequestCommit,
11 PullRequestLabel,
12 PullRequestMergeability,
13 PullRequestMergeCapabilities,
14 PullRequestReaction,
15 PullRequestReactionContent,
16 PullRequestReviewThread,
17 PullRequestReviewerCandidate,
18 PullRequestState,
19} from "@t3tools/contracts";
20import { TrimmedNonEmptyString } from "@t3tools/contracts";
21import { decodeJsonResult } from "@t3tools/shared/schemaJson";
22
23/**
24 * GitLab's REST enums are decoded as plain strings and normalized here: a GitLab release that
25 * adds a pipeline status or a merge status must not fail the whole payload.
26 */
27const RawUserSchema = Schema.Struct({
28 /**
29 * GitLab writes a merge request's reviewers as numeric ids and takes no usernames there, so the
30 * id is carried alongside the handle rather than looked up again when a review is asked for.
31 */
32 id: Schema.optional(Schema.Int),
33 username: Schema.String,
34 name: Schema.optional(Schema.NullOr(Schema.String)),
35 avatar_url: Schema.optional(Schema.NullOr(Schema.String)),
36});
37
38const RawPipelineSchema = Schema.Struct({
39 status: Schema.optional(Schema.NullOr(Schema.String)),
40 web_url: Schema.optional(Schema.NullOr(Schema.String)),
41 source: Schema.optional(Schema.NullOr(Schema.String)),
42});
43
44const RawMergeRequestSchema = Schema.Struct({
45 iid: Schema.Int,
46 title: Schema.String,
47 web_url: Schema.String,
48 description: Schema.optional(Schema.NullOr(Schema.String)),
49 author: Schema.optional(Schema.NullOr(RawUserSchema)),
50 source_branch: Schema.String,
51 target_branch: Schema.String,
52 state: Schema.optional(Schema.NullOr(Schema.String)),
53 draft: Schema.optional(Schema.Boolean),
54 work_in_progress: Schema.optional(Schema.Boolean),
55 merge_status: Schema.optional(Schema.NullOr(Schema.String)),
56 has_conflicts: Schema.optional(Schema.NullOr(Schema.Boolean)),
57 created_at: Schema.String,
58 updated_at: Schema.String,
59 merged_at: Schema.optional(Schema.NullOr(Schema.String)),
60 closed_at: Schema.optional(Schema.NullOr(Schema.String)),
61 reviewers: Schema.optional(Schema.NullOr(Schema.Array(RawUserSchema))),
62 labels: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))),
63 // A string, and "1000+" past GitLab's counting limit, so it is parsed rather than decoded.
64 changes_count: Schema.optional(Schema.NullOr(Schema.String)),
65 head_pipeline: Schema.optional(Schema.NullOr(RawPipelineSchema)),
66 /**
67 * What the requesting account may do, which only the single-merge-request endpoint carries.
68 * GitLab answers `can_merge` for this viewer against this merge request, so it already accounts
69 * for the role, the approval rules and a protected target branch — none of which a project's
70 * access level on its own would tell apart.
71 */
72 user: Schema.optional(
73 Schema.NullOr(Schema.Struct({ can_merge: Schema.optional(Schema.Boolean) })),
74 ),
75 /**
76 * Whether GitLab is holding this merge request to merge it once its pipeline goes green.
77 * `merge_when_pipeline_succeeds` is the field every version answers with; newer ones also
78 * carry `auto_merge_enabled`, which is the same fact under the name GitLab settled on, so
79 * either one saying yes is a yes.
80 */
81 merge_when_pipeline_succeeds: Schema.optional(Schema.NullOr(Schema.Boolean)),
82 auto_merge_enabled: Schema.optional(Schema.NullOr(Schema.Boolean)),
83 /**
84 * How far the target branch has moved on since this one left it, which is the same number
85 * GitLab's own "out of date" wording counts. It costs a walk of the two branches, so GitLab
86 * withholds it unless `include_diverged_commits_count` asks for it, and answers it only for a
87 * single merge request — a list never carries it, however it is asked for.
88 */
89 diverged_commits_count: Schema.optional(Schema.NullOr(Schema.Int)),
90});
91
92const RawNoteSchema = Schema.Struct({
93 id: Schema.Int,
94 body: Schema.optional(Schema.NullOr(Schema.String)),
95 author: Schema.optional(Schema.NullOr(RawUserSchema)),
96 created_at: Schema.String,
97 /** True for notes GitLab writes itself ("assigned to…"), which are events, not comments. */
98 system: Schema.optional(Schema.Boolean),
99 type: Schema.optional(Schema.NullOr(Schema.String)),
100 position: Schema.optional(
101 Schema.NullOr(
102 Schema.Struct({
103 new_path: Schema.optional(Schema.NullOr(Schema.String)),
104 old_path: Schema.optional(Schema.NullOr(Schema.String)),
105 }),
106 ),
107 ),
108});
109
110/**
111 * A discussion note carrying its place in the diff, which is the shape the whole thread view
112 * is built from. `resolved` lives on the note rather than on the discussion: GitLab calls a
113 * discussion resolved once every resolvable note in it is.
114 */
115const RawDiscussionNoteSchema = Schema.Struct({
116 id: Schema.Int,
117 body: Schema.optional(Schema.NullOr(Schema.String)),
118 author: Schema.optional(Schema.NullOr(RawUserSchema)),
119 created_at: Schema.String,
120 system: Schema.optional(Schema.Boolean),
121 resolvable: Schema.optional(Schema.Boolean),
122 resolved: Schema.optional(Schema.NullOr(Schema.Boolean)),
123 position: Schema.optional(
124 Schema.NullOr(
125 Schema.Struct({
126 position_type: Schema.optional(Schema.NullOr(Schema.String)),
127 new_path: Schema.optional(Schema.NullOr(Schema.String)),
128 old_path: Schema.optional(Schema.NullOr(Schema.String)),
129 new_line: Schema.optional(Schema.NullOr(Schema.Int)),
130 old_line: Schema.optional(Schema.NullOr(Schema.Int)),
131 }),
132 ),
133 ),
134});
135
136const RawDiscussionSchema = Schema.Struct({
137 id: Schema.String,
138 notes: Schema.optional(Schema.NullOr(Schema.Array(RawDiscussionNoteSchema))),
139});
140
141const RawDiffRefsSchema = Schema.Struct({
142 diff_refs: Schema.optional(
143 Schema.NullOr(
144 Schema.Struct({
145 base_sha: Schema.String,
146 head_sha: Schema.String,
147 start_sha: Schema.String,
148 }),
149 ),
150 ),
151});
152
153const RawCommitSchema = Schema.Struct({
154 id: TrimmedNonEmptyString,
155 title: Schema.optional(Schema.NullOr(Schema.String)),
156 committed_date: Schema.optional(Schema.NullOr(Schema.String)),
157 created_at: Schema.optional(Schema.NullOr(Schema.String)),
158 parent_ids: Schema.optional(Schema.Array(Schema.String)),
159 author_name: Schema.optional(Schema.NullOr(Schema.String)),
160 author_email: Schema.optional(Schema.NullOr(Schema.String)),
161 stats: Schema.optional(
162 Schema.NullOr(
163 Schema.Struct({
164 additions: Schema.optional(Schema.Int),
165 deletions: Schema.optional(Schema.Int),
166 }),
167 ),
168 ),
169});
170
171const RawDiffSchema = Schema.Struct({
172 old_path: Schema.String,
173 new_path: Schema.String,
174 a_mode: Schema.optional(Schema.NullOr(Schema.String)),
175 b_mode: Schema.optional(Schema.NullOr(Schema.String)),
176 new_file: Schema.optional(Schema.Boolean),
177 renamed_file: Schema.optional(Schema.Boolean),
178 deleted_file: Schema.optional(Schema.Boolean),
179 diff: Schema.optional(Schema.NullOr(Schema.String)),
180 /** GitLab omits the hunks for a file it considers too large to inline. */
181 too_large: Schema.optional(Schema.NullOr(Schema.Boolean)),
182 /** And for one it collapsed, which withholds them the same way. */
183 collapsed: Schema.optional(Schema.NullOr(Schema.Boolean)),
184});
185
186const RawViewerSchema = Schema.Struct({
187 username: Schema.optional(Schema.NullOr(Schema.String)),
188});
189
190/** A GitLab project settles on one merge strategy plus an optional squash. */
191const RawProjectMergeSettingsSchema = Schema.Struct({
192 merge_method: Schema.optional(Schema.NullOr(Schema.String)),
193 squash_option: Schema.optional(Schema.NullOr(Schema.String)),
194});
195
196export interface GitLabMergeRequestListItem {
197 readonly number: number;
198 readonly title: string;
199 readonly url: string;
200 readonly author: PullRequestActor | null;
201 readonly headBranch: string;
202 readonly baseBranch: string;
203 readonly state: PullRequestState;
204 readonly isDraft: boolean;
205 readonly mergeability: PullRequestMergeability;
206 /**
207 * GitLab reports neither added nor removed lines on a merge request, so both stay zero and
208 * the surface omits the stat. The Code tab counts them from the patch it already fetched.
209 */
210 readonly additions: number;
211 readonly deletions: number;
212 readonly createdAt: string;
213 readonly updatedAt: string;
214 readonly reviewRequestLogins: ReadonlyArray<string>;
215 readonly labels: ReadonlyArray<PullRequestLabel>;
216}
217
218export interface GitLabMergeRequestDetail extends GitLabMergeRequestListItem {
219 readonly body: string;
220 readonly changedFiles: number;
221 readonly mergedAt: string | null;
222 readonly closedAt: string | null;
223 readonly reviewers: ReadonlyArray<PullRequestActor>;
224 readonly checks: ReadonlyArray<PullRequestCheck>;
225 /** False only where GitLab said so; an answer without the field leaves merging permitted. */
226 readonly viewerCanMerge: boolean;
227 /** The reviewers as GitLab addresses them, which is what writing the set back takes. */
228 readonly reviewerIds: ReadonlyArray<number>;
229 /** Absent where GitLab named neither auto-merge field, which is not the same as off. */
230 readonly autoMergeEnabled?: boolean;
231 /**
232 * Absent where GitLab did not count, which is not the same as a branch that has nothing behind
233 * it: an install too old to answer must not be read as saying the branch is current.
234 */
235 readonly divergedCommits?: number;
236}
237
238function trimmed(value: string | null | undefined): string | null {
239 const text = value?.trim() ?? "";
240 return text.length > 0 ? text : null;
241}
242
243function toActor(raw: Schema.Schema.Type<typeof RawUserSchema> | null | undefined) {
244 const login = trimmed(raw?.username);
245 return login === null
246 ? null
247 : { login, name: trimmed(raw?.name), avatarUrl: trimmed(raw?.avatar_url) };
248}
249
250function toState(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): PullRequestState {
251 if (trimmed(raw.merged_at) !== null) return "merged";
252 switch (raw.state?.trim().toLowerCase()) {
253 case "merged":
254 return "merged";
255 case "closed":
256 return "closed";
257 default:
258 // `locked` is an open merge request whose discussion is locked.
259 return "open";
260 }
261}
262
263function toMergeability(
264 raw: Schema.Schema.Type<typeof RawMergeRequestSchema>,
265): PullRequestMergeability {
266 if (raw.has_conflicts === true) return "conflicting";
267 switch (raw.merge_status?.trim().toLowerCase()) {
268 case "can_be_merged":
269 return "mergeable";
270 case "cannot_be_merged":
271 return "conflicting";
272 default:
273 // `unchecked` and `checking` mean GitLab has not finished the merge check yet.
274 return "unknown";
275 }
276}
277
278function toLabels(raw: ReadonlyArray<string> | null | undefined): ReadonlyArray<PullRequestLabel> {
279 // GitLab returns label names only, so there is no colour to carry.
280 return (raw ?? []).flatMap((label) => {
281 const name = trimmed(label);
282 return name === null ? [] : [{ name, color: null }];
283 });
284}
285
286/**
287 * "3" for a counted change set, "1000+" once GitLab gives up counting. The leading number is
288 * the floor either way, which reads better than dropping an uncounted change set to nothing.
289 */
290function toChangedFiles(value: string | null | undefined): number {
291 const parsed = Number.parseInt(value?.trim() ?? "", 10);
292 return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
293}
294
295function toPipelineStatus(value: string | null | undefined): PullRequestCheckStatus {
296 switch (value?.trim().toLowerCase()) {
297 case "success":
298 return "success";
299 case "failed":
300 return "failure";
301 case "canceled":
302 case "cancelling":
303 return "cancelled";
304 case "skipped":
305 return "skipped";
306 // A pipeline waiting on a person is not progress, and it is not a failure either.
307 case "manual":
308 case "scheduled":
309 return "neutral";
310 default:
311 return "pending";
312 }
313}
314
315/**
316 * GitLab has no per-job check list on a merge request, so its pipeline is reported as the one
317 * check. The jobs behind it stay one click away through the pipeline URL.
318 */
319function toChecks(
320 raw: Schema.Schema.Type<typeof RawMergeRequestSchema>,
321): ReadonlyArray<PullRequestCheck> {
322 const pipeline = raw.head_pipeline;
323 if (!pipeline) return [];
324 return [
325 {
326 name: "Pipeline",
327 status: toPipelineStatus(pipeline.status),
328 description: trimmed(pipeline.source),
329 url: trimmed(pipeline.web_url),
330 },
331 ];
332}
333
334function toListItem(
335 raw: Schema.Schema.Type<typeof RawMergeRequestSchema>,
336): GitLabMergeRequestListItem {
337 return {
338 number: raw.iid,
339 title: raw.title,
340 url: raw.web_url,
341 author: toActor(raw.author),
342 headBranch: raw.source_branch,
343 baseBranch: raw.target_branch,
344 state: toState(raw),
345 isDraft: raw.draft ?? raw.work_in_progress ?? false,
346 mergeability: toMergeability(raw),
347 additions: 0,
348 deletions: 0,
349 createdAt: raw.created_at,
350 updatedAt: raw.updated_at,
351 reviewRequestLogins: (raw.reviewers ?? []).flatMap((reviewer) => {
352 const login = trimmed(reviewer.username);
353 return login === null ? [] : [login];
354 }),
355 labels: toLabels(raw.labels),
356 };
357}
358
359function toDetail(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): GitLabMergeRequestDetail {
360 const listItem = toListItem(raw);
361 const autoMerge =
362 raw.merge_when_pipeline_succeeds == null && raw.auto_merge_enabled == null
363 ? undefined
364 : raw.merge_when_pipeline_succeeds === true || raw.auto_merge_enabled === true;
365 return {
366 ...listItem,
367 body: raw.description ?? "",
368 changedFiles: toChangedFiles(raw.changes_count),
369 mergedAt: trimmed(raw.merged_at),
370 closedAt: trimmed(raw.closed_at),
371 // Built from the reviewers themselves rather than from their logins, so the avatars survive.
372 reviewers: (raw.reviewers ?? []).flatMap((reviewer) => {
373 const actor = toActor(reviewer);
374 return actor === null ? [] : [actor];
375 }),
376 checks: toChecks(raw),
377 viewerCanMerge: raw.user?.can_merge !== false,
378 reviewerIds: (raw.reviewers ?? []).flatMap((reviewer) =>
379 reviewer.id === undefined ? [] : [reviewer.id],
380 ),
381 ...(autoMerge === undefined ? {} : { autoMergeEnabled: autoMerge }),
382 ...(raw.diverged_commits_count == null ? {} : { divergedCommits: raw.diverged_commits_count }),
383 };
384}
385
386const decodeUnknownList = decodeJsonResult(Schema.Array(Schema.Unknown));
387const decodeMergeRequestEntry = Schema.decodeUnknownExit(RawMergeRequestSchema);
388const decodeMergeRequest = decodeJsonResult(RawMergeRequestSchema);
389const decodeNoteEntry = Schema.decodeUnknownExit(RawNoteSchema);
390const decodeUserEntry = Schema.decodeUnknownExit(RawUserSchema);
391const decodeCommitEntry = Schema.decodeUnknownExit(RawCommitSchema);
392const decodeCommit = decodeJsonResult(RawCommitSchema);
393const decodeDiffEntry = Schema.decodeUnknownExit(RawDiffSchema);
394const decodeDiscussionEntry = Schema.decodeUnknownExit(RawDiscussionSchema);
395const decodeDiffRefs = decodeJsonResult(RawDiffRefsSchema);
396const decodeViewer = decodeJsonResult(RawViewerSchema);
397const decodeProjectMergeSettings = decodeJsonResult(RawProjectMergeSettingsSchema);
398
399type DecodeFailure = Cause.Cause<Schema.SchemaError>;
400
401export interface GitLabProjectUsers {
402 readonly candidates: ReadonlyArray<PullRequestReviewerCandidate>;
403 /** Rows GitLab returned, counted before decoding, so a skipped row cannot hide a next page. */
404 readonly rawCount: number;
405}
406
407export interface GitLabMergeRequestListBatch {
408 readonly items: ReadonlyArray<GitLabMergeRequestListItem>;
409 /** Zero-based positions of the decoded items in GitLab's raw page. */
410 readonly rawIndexes: ReadonlyArray<number>;
411 /** Rows GitLab returned, counted before decoding, so a skipped row cannot hide a next page. */
412 readonly rawCount: number;
413}
414
415/** Malformed entries are skipped rather than failing the batch: one unexpected merge request
416 * must not blank the whole list. */
417export function decodeMergeRequestListJson(
418 raw: string,
419): Result.Result<GitLabMergeRequestListBatch, DecodeFailure> {
420 const decoded = decodeUnknownList(raw);
421 if (!Result.isSuccess(decoded)) {
422 return Result.fail(decoded.failure);
423 }
424 const items: GitLabMergeRequestListItem[] = [];
425 const rawIndexes: number[] = [];
426 for (const [rawIndex, entry] of decoded.success.entries()) {
427 const item = decodeMergeRequestEntry(entry);
428 if (Exit.isSuccess(item)) {
429 items.push(toListItem(item.value));
430 rawIndexes.push(rawIndex);
431 }
432 }
433 return Result.succeed({ items, rawIndexes, rawCount: decoded.success.length });
434}
435
436export function decodeMergeRequestDetailJson(
437 raw: string,
438): Result.Result<GitLabMergeRequestDetail, DecodeFailure> {
439 const decoded = decodeMergeRequest(raw);
440 return Result.isSuccess(decoded)
441 ? Result.succeed(toDetail(decoded.success))
442 : Result.fail(decoded.failure);
443}
444
445export function decodeViewerJson(raw: string): Result.Result<string | null, DecodeFailure> {
446 const decoded = decodeViewer(raw);
447 return Result.isSuccess(decoded)
448 ? Result.succeed(trimmed(decoded.success.username))
449 : Result.fail(decoded.failure);
450}
451
452/**
453 * The people with access to the project, which `GET /projects/:id/users` answers with — the same
454 * list GitLab's own reviewer field is filled from, including the members a group above the project
455 * lends it. A malformed row is skipped rather than failing the menu it belongs to.
456 *
457 * Nobody is marked requested here: who has been asked lives on the merge request, and only the
458 * caller holds both.
459 */
460export function decodeProjectUsersJson(
461 raw: string,
462): Result.Result<GitLabProjectUsers, DecodeFailure> {
463 const decoded = decodeUnknownList(raw);
464 if (!Result.isSuccess(decoded)) {
465 return Result.fail(decoded.failure);
466 }
467 const candidates: PullRequestReviewerCandidate[] = [];
468 for (const entry of decoded.success) {
469 const user = decodeUserEntry(entry);
470 if (Exit.isFailure(user) || user.value.id === undefined) continue;
471 const actor = toActor(user.value);
472 if (actor === null) continue;
473 candidates.push({
474 ...actor,
475 id: String(user.value.id),
476 kind: "user",
477 isRequested: false,
478 });
479 }
480 return Result.succeed({ candidates, rawCount: decoded.success.length });
481}
482
483/**
484 * GitLab settles the strategy per project rather than offering all three per merge request:
485 * `merge_method` picks one of merge commit, semi-linear or fast-forward, and squashing is a
486 * separate switch. An unrecognized setting offers nothing rather than offering a strategy the
487 * project forbids.
488 */
489export function decodeProjectMergeCapabilitiesJson(
490 raw: string,
491): Result.Result<PullRequestMergeCapabilities, DecodeFailure> {
492 const decoded = decodeProjectMergeSettings(raw);
493 if (!Result.isSuccess(decoded)) {
494 return Result.fail(decoded.failure);
495 }
496 const mergeMethod = decoded.success.merge_method?.trim().toLowerCase();
497 const squashOption = decoded.success.squash_option?.trim().toLowerCase();
498 return Result.succeed({
499 merge: mergeMethod === "merge",
500 // Both semi-linear and fast-forward histories are reached by rebasing onto the target.
501 rebase: mergeMethod === "rebase_merge" || mergeMethod === "ff",
502 // Only GitLab's own enabling values. An absent or unrecognized setting offers nothing,
503 // rather than offering a squash the project may forbid.
504 squash:
505 squashOption === "always" || squashOption === "default_on" || squashOption === "default_off",
506 });
507}
508
509/**
510 * Comments only. System notes are GitLab's own activity feed entries, and a `DiffNote` is the
511 * root of a line-level discussion, which is what the review-comment kind means.
512 *
513 * The raw note count comes back alongside, because dropping notes hides whether the page was
514 * full: a caller cannot tell "no more notes" from "a page of activity entries" without it.
515 */
516/** The three revisions a positioned comment is written against. */
517export interface GitLabDiffRefs {
518 readonly baseSha: string;
519 readonly headSha: string;
520 readonly startSha: string;
521}
522
523export interface GitLabDiscussions {
524 readonly threads: ReadonlyArray<PullRequestReviewThread>;
525 /** Discussions GitLab returned, counted before decoding, so a skipped one still counts. */
526 readonly rawCount: number;
527}
528
529/**
530 * Positioned discussions only. GitLab returns the merge request's whole conversation here,
531 * including the plain notes the timeline already shows, and only a positioned one belongs
532 * against a line of the diff.
533 */
534export function decodeDiscussionsJson(
535 raw: string,
536): Result.Result<GitLabDiscussions, DecodeFailure> {
537 const decoded = decodeUnknownList(raw);
538 if (!Result.isSuccess(decoded)) {
539 return Result.fail(decoded.failure);
540 }
541 const threads: PullRequestReviewThread[] = [];
542 for (const entry of decoded.success) {
543 const discussion = decodeDiscussionEntry(entry);
544 if (!Exit.isSuccess(discussion)) continue;
545 const notes = (discussion.value.notes ?? []).filter((note) => note.system !== true);
546 const root = notes[0];
547 const position = root?.position;
548 if (root === undefined || !position || position.position_type !== "text") continue;
549 // A comment on an added or context line carries `new_line`; one on a removed line carries
550 // only `old_line`, and belongs against the file as it was.
551 const side = position.new_line === null || position.new_line === undefined ? "left" : "right";
552 const path = trimmed(side === "left" ? position.old_path : position.new_path);
553 const line = side === "left" ? position.old_line : position.new_line;
554 if (path === null) continue;
555 threads.push({
556 id: discussion.value.id,
557 path,
558 line: typeof line === "number" && line > 0 ? line : null,
559 side,
560 isResolved: root.resolved === true,
561 // GitLab reports no equivalent of "written against a line that has since moved", so a
562 // thread the diff cannot place is worked out from the diff itself rather than claimed
563 // here.
564 isOutdated: false,
565 comments: notes.map((note) => ({
566 id: String(note.id),
567 author: toActor(note.author),
568 body: note.body ?? "",
569 createdAt: note.created_at,
570 url: null,
571 })),
572 });
573 }
574 return Result.succeed({ threads, rawCount: decoded.success.length });
575}
576
577export function decodeDiffRefsJson(
578 raw: string,
579): Result.Result<GitLabDiffRefs | null, DecodeFailure> {
580 const decoded = decodeDiffRefs(raw);
581 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
582 const refs = decoded.success.diff_refs;
583 return Result.succeed(
584 refs ? { baseSha: refs.base_sha, headSha: refs.head_sha, startSha: refs.start_sha } : null,
585 );
586}
587
588export function decodeNotesJson(
589 raw: string,
590): Result.Result<
591 { readonly comments: ReadonlyArray<PullRequestComment>; readonly rawCount: number },
592 DecodeFailure
593> {
594 const decoded = decodeUnknownList(raw);
595 if (!Result.isSuccess(decoded)) {
596 return Result.fail(decoded.failure);
597 }
598 const comments: PullRequestComment[] = [];
599 for (const entry of decoded.success) {
600 const note = decodeNoteEntry(entry);
601 if (Exit.isFailure(note)) continue;
602 const value = note.value;
603 if (value.system === true) continue;
604 const body = value.body ?? "";
605 if (body.trim().length === 0) continue;
606 const isDiffNote = value.type?.trim() === "DiffNote";
607 comments.push({
608 id: String(value.id),
609 kind: isDiffNote ? "review-comment" : "issue-comment",
610 author: toActor(value.author),
611 body,
612 createdAt: value.created_at,
613 url: null,
614 path: trimmed(value.position?.new_path) ?? trimmed(value.position?.old_path),
615 reviewState: null,
616 });
617 }
618 return Result.succeed({ comments, rawCount: decoded.success.length });
619}
620
621export function decodeCommitsJson(
622 raw: string,
623): Result.Result<ReadonlyArray<PullRequestCommit>, DecodeFailure> {
624 const decoded = decodeUnknownList(raw);
625 if (!Result.isSuccess(decoded)) {
626 return Result.fail(decoded.failure);
627 }
628 const commits: PullRequestCommit[] = [];
629 for (const entry of decoded.success) {
630 const commit = decodeCommitEntry(entry);
631 if (Exit.isFailure(commit)) continue;
632 const committedDate = trimmed(commit.value.committed_date) ?? trimmed(commit.value.created_at);
633 if (committedDate === null) continue;
634 commits.push({
635 oid: commit.value.id,
636 messageHeadline: commit.value.title ?? "",
637 committedDate,
638 ...(commit.value.stats === null || commit.value.stats === undefined
639 ? {}
640 : {
641 additions: Math.max(0, commit.value.stats.additions ?? 0),
642 deletions: Math.max(0, commit.value.stats.deletions ?? 0),
643 }),
644 authors: (() => {
645 const login = trimmed(commit.value.author_name) ?? trimmed(commit.value.author_email);
646 return login === null
647 ? []
648 : [{ login, name: trimmed(commit.value.author_name), avatarUrl: null }];
649 })(),
650 });
651 }
652 // GitLab lists a merge request's commits newest first; the timeline reads oldest first.
653 return Result.succeed(commits.toReversed());
654}
655
656/** The exact comparison GitLab uses for a commit-scoped diff. */
657export function decodeCommitDiffRefsJson(
658 raw: string,
659): Result.Result<GitLabDiffRefs | null, DecodeFailure> {
660 const decoded = decodeCommit(raw);
661 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
662 const baseSha = trimmed(decoded.success.parent_ids?.[0]);
663 const headSha = trimmed(decoded.success.id);
664 return Result.succeed(
665 baseSha === null || headSha === null ? null : { baseSha, headSha, startSha: baseSha },
666 );
667}
668
669function diffHeaderPaths(raw: Schema.Schema.Type<typeof RawDiffSchema>): {
670 readonly from: string;
671 readonly to: string;
672} {
673 return {
674 from: raw.new_file === true ? "/dev/null" : `a/${raw.old_path}`,
675 to: raw.deleted_file === true ? "/dev/null" : `b/${raw.new_path}`,
676 };
677}
678
679export interface GitLabMergeRequestPatch {
680 readonly patch: string;
681 /** At least one file's hunks were withheld by GitLab as too large to inline. */
682 readonly truncated: boolean;
683 /** Files GitLab returned, counted before decoding, so the caller can page. */
684 readonly rawCount: number;
685}
686
687/**
688 * GitLab returns hunks per file with no `diff --git` header, so the unified patch every diff
689 * viewer expects is assembled here. This decodes one page; walking pages is the caller's job,
690 * which is why the raw file count comes back with the patch.
691 */
692export function decodeMergeRequestDiffsJson(
693 raw: string,
694): Result.Result<GitLabMergeRequestPatch, DecodeFailure> {
695 const decoded = decodeUnknownList(raw);
696 if (!Result.isSuccess(decoded)) {
697 return Result.fail(decoded.failure);
698 }
699 const sections: string[] = [];
700 let truncated = false;
701 for (const entry of decoded.success) {
702 const file = decodeDiffEntry(entry);
703 if (Exit.isFailure(file)) continue;
704 const value = file.value;
705 const hunks = value.diff ?? "";
706 if (hunks.length === 0) {
707 // A file GitLab declined to inline still belongs in the file list, header only.
708 truncated = truncated || value.too_large === true || value.collapsed === true;
709 }
710 const { from, to } = diffHeaderPaths(value);
711 const header = [
712 `diff --git a/${value.old_path} b/${value.new_path}`,
713 ...(value.new_file === true ? [`new file mode ${value.b_mode ?? "100644"}`] : []),
714 ...(value.deleted_file === true ? [`deleted file mode ${value.a_mode ?? "100644"}`] : []),
715 ...(value.renamed_file === true
716 ? [`rename from ${value.old_path}`, `rename to ${value.new_path}`]
717 : []),
718 `--- ${from}`,
719 `+++ ${to}`,
720 ].join("\n");
721 sections.push(hunks.length === 0 ? header : `${header}\n${hunks.replace(/\n?$/, "\n")}`);
722 }
723 return Result.succeed({
724 patch: sections.join("\n"),
725 truncated,
726 rawCount: decoded.success.length,
727 });
728}
729
730/** GitLab's award names for the eight reactions the contract carries. */
731const GITLAB_AWARD_BY_CONTENT: Readonly<Record<PullRequestReactionContent, string>> = {
732 "thumbs-up": "thumbsup",
733 "thumbs-down": "thumbsdown",
734 laugh: "laughing",
735 hooray: "tada",
736 confused: "confused",
737 heart: "heart",
738 rocket: "rocket",
739 eyes: "eyes",
740};
741
742const CONTENT_BY_GITLAB_AWARD: Readonly<Record<string, PullRequestReactionContent>> =
743 Object.fromEntries(
744 Object.entries(GITLAB_AWARD_BY_CONTENT).map(([content, name]) => [name, content]),
745 ) as Readonly<Record<string, PullRequestReactionContent>>;
746
747export function gitLabAwardName(content: PullRequestReactionContent): string {
748 return GITLAB_AWARD_BY_CONTENT[content];
749}
750
751/**
752 * Awards on the merge request and on every note of it, in one read. The REST notes endpoint the
753 * conversation comes from carries no award at all, and asking per note would be a request each.
754 *
755 * `currentUser` rides along because GitLab names who awarded but never says whether that is the
756 * reader — so the comparison is made here rather than paid for with a request of its own.
757 */
758export const AWARD_EMOJI_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!, $cursor: String) {
759 currentUser { username }
760 project(fullPath: $fullPath) {
761 mergeRequest(iid: $iid) {
762 awardEmoji { nodes { name user { username } } }
763 notes(first: 100, after: $cursor) {
764 pageInfo { hasNextPage endCursor }
765 nodes { id awardEmoji { nodes { name user { username } } } }
766 }
767 }
768 }
769}`;
770
771const RawAwardEmojiNodesSchema = Schema.optional(
772 Schema.NullOr(
773 Schema.Struct({
774 nodes: Schema.optional(
775 Schema.NullOr(
776 Schema.Array(
777 Schema.NullOr(
778 Schema.Struct({
779 name: Schema.optional(Schema.NullOr(Schema.String)),
780 user: Schema.optional(
781 Schema.NullOr(
782 Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) }),
783 ),
784 ),
785 }),
786 ),
787 ),
788 ),
789 ),
790 }),
791 ),
792);
793
794const RawAwardEmojiPageSchema = Schema.Struct({
795 data: Schema.Struct({
796 currentUser: Schema.optional(
797 Schema.NullOr(Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) })),
798 ),
799 project: Schema.NullOr(
800 Schema.Struct({
801 mergeRequest: Schema.NullOr(
802 Schema.Struct({
803 awardEmoji: RawAwardEmojiNodesSchema,
804 notes: Schema.optional(
805 Schema.NullOr(
806 Schema.Struct({
807 pageInfo: Schema.optional(
808 Schema.Struct({
809 hasNextPage: Schema.optional(Schema.Boolean),
810 endCursor: Schema.optional(Schema.NullOr(Schema.String)),
811 }),
812 ),
813 nodes: Schema.Array(
814 Schema.NullOr(
815 Schema.Struct({
816 id: Schema.optional(Schema.NullOr(Schema.String)),
817 awardEmoji: RawAwardEmojiNodesSchema,
818 }),
819 ),
820 ),
821 }),
822 ),
823 ),
824 }),
825 ),
826 }),
827 ),
828 }),
829});
830
831const decodeAwardEmojiPage = decodeJsonResult(RawAwardEmojiPageSchema);
832
833/**
834 * The awards on one subject, grouped the way a reaction pill is drawn. The viewer's own username
835 * is left out of `actors` — the page names them "You" instead, and leaving it in would name them
836 * twice — but `count` still counts them along with everyone else.
837 */
838function toReactions(
839 nodes: Schema.Schema.Type<typeof RawAwardEmojiNodesSchema>,
840 viewer: string | null,
841): ReadonlyArray<PullRequestReaction> {
842 const normalizedViewer = viewer?.toLowerCase() ?? null;
843 const groups = new Map<
844 PullRequestReactionContent,
845 { count: number; actors: string[]; viewer: boolean }
846 >();
847 for (const node of nodes?.nodes ?? []) {
848 // An award outside the eight is left out rather than shown under a name the picker has no
849 // way to take back: GitLab accepts any emoji, and the other hosts accept none of them.
850 const content = CONTENT_BY_GITLAB_AWARD[trimmed(node?.name)?.toLowerCase() ?? ""];
851 if (content === undefined) continue;
852 const username = trimmed(node?.user?.username);
853 if (username === null) continue;
854 const group = groups.get(content) ?? { count: 0, actors: [], viewer: false };
855 group.count++;
856 if (normalizedViewer !== null && username.toLowerCase() === normalizedViewer) {
857 group.viewer = true;
858 } else {
859 group.actors.push(username);
860 }
861 groups.set(content, group);
862 }
863 return [...groups].flatMap(([content, group]) =>
864 group.count === 0
865 ? []
866 : [{ content, count: group.count, actors: group.actors, viewerHasReacted: group.viewer }],
867 );
868}
869
870/** `gid://gitlab/DiffNote/42` is note 42, which is the id the REST conversation carries. */
871function noteIdOf(gid: string | null | undefined): string | null {
872 const id = trimmed(gid)?.split("/").at(-1);
873 return id !== undefined && /^\d+$/.test(id) ? id : null;
874}
875
876export interface GitLabAwardEmojiPage {
877 /** The merge request's own awards, which are the ones on its description. */
878 readonly reactions: ReadonlyArray<PullRequestReaction>;
879 readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>;
880 readonly nextCursor: string | null;
881}
882
883export function decodeAwardEmojiJson(
884 raw: string,
885): Result.Result<GitLabAwardEmojiPage, DecodeFailure> {
886 const decoded = decodeAwardEmojiPage(raw);
887 if (!Result.isSuccess(decoded)) {
888 return Result.fail(decoded.failure);
889 }
890 const data = decoded.success.data;
891 const viewer = trimmed(data.currentUser?.username);
892 const mergeRequest = data.project?.mergeRequest;
893 const reactionsByNoteId = new Map<string, ReadonlyArray<PullRequestReaction>>();
894 for (const node of mergeRequest?.notes?.nodes ?? []) {
895 const id = noteIdOf(node?.id);
896 if (id === null) continue;
897 const reactions = toReactions(node?.awardEmoji, viewer);
898 if (reactions.length > 0) reactionsByNoteId.set(id, reactions);
899 }
900 const pageInfo = mergeRequest?.notes?.pageInfo;
901 return Result.succeed({
902 reactions: toReactions(mergeRequest?.awardEmoji, viewer),
903 reactionsByNoteId,
904 nextCursor: pageInfo?.hasNextPage === true ? (trimmed(pageInfo.endCursor) ?? null) : null,
905 });
906}
907
908const RawAwardSchema = Schema.Struct({
909 id: Schema.Int,
910 name: Schema.optional(Schema.NullOr(Schema.String)),
911 user: Schema.optional(
912 Schema.NullOr(Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) })),
913 ),
914});
915
916const decodeAward = Schema.decodeUnknownExit(RawAwardSchema);
917
918/**
919 * The reader's own award of one name on a subject, which is what taking a reaction back is
920 * addressed by: GitLab deletes an award by its id and has no way to name one by its emoji.
921 */
922export function decodeOwnAwardIdJson(
923 raw: string,
924 input: { readonly content: PullRequestReactionContent; readonly viewer: string },
925): Result.Result<number | null, DecodeFailure> {
926 const decoded = decodeUnknownList(raw);
927 if (!Result.isSuccess(decoded)) {
928 return Result.fail(decoded.failure);
929 }
930 const name = gitLabAwardName(input.content);
931 for (const entry of decoded.success) {
932 const award = decodeAward(entry);
933 if (Exit.isFailure(award)) continue;
934 const value = award.value;
935 if (trimmed(value.name)?.toLowerCase() !== name) continue;
936 if (trimmed(value.user?.username) !== input.viewer) continue;
937 return Result.succeed(value.id);
938 }
939 return Result.succeed(null);
940}