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

gitLabMergeRequestJson.ts

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