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

gitLabMergeRequestJson.ts

949 lines35.2 KB

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