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

gitLabMergeRequestJson.ts

698 lines25.5 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 PullRequestReviewThread,
15 PullRequestReviewerCandidate,
16 PullRequestState,
17} from "@t3tools/contracts";
18import { TrimmedNonEmptyString } from "@t3tools/contracts";
19import { decodeJsonResult } from "@t3tools/shared/schemaJson";
20​
21/**
22 * GitLab's REST enums are decoded as plain strings and normalized here: a GitLab release that
23 * adds a pipeline status or a merge status must not fail the whole payload.
24 */
25const RawUserSchema = Schema.Struct({
26 /**
27 * GitLab writes a merge request's reviewers as numeric ids and takes no usernames there, so the
28 * id is carried alongside the handle rather than looked up again when a review is asked for.
29 */
30 id: Schema.optional(Schema.Int),
31 username: Schema.String,
32 name: Schema.optional(Schema.NullOr(Schema.String)),
33 avatar_url: Schema.optional(Schema.NullOr(Schema.String)),
34});
35​
36const RawPipelineSchema = Schema.Struct({
37 status: Schema.optional(Schema.NullOr(Schema.String)),
38 web_url: Schema.optional(Schema.NullOr(Schema.String)),
39 source: Schema.optional(Schema.NullOr(Schema.String)),
40});
41​
42const RawMergeRequestSchema = Schema.Struct({
43 iid: Schema.Int,
44 title: Schema.String,
45 web_url: Schema.String,
46 description: Schema.optional(Schema.NullOr(Schema.String)),
47 author: Schema.optional(Schema.NullOr(RawUserSchema)),
48 source_branch: Schema.String,
49 target_branch: Schema.String,
50 state: Schema.optional(Schema.NullOr(Schema.String)),
51 draft: Schema.optional(Schema.Boolean),
52 work_in_progress: Schema.optional(Schema.Boolean),
53 merge_status: Schema.optional(Schema.NullOr(Schema.String)),
54 has_conflicts: Schema.optional(Schema.NullOr(Schema.Boolean)),
55 created_at: Schema.String,
56 updated_at: Schema.String,
57 merged_at: Schema.optional(Schema.NullOr(Schema.String)),
58 closed_at: Schema.optional(Schema.NullOr(Schema.String)),
59 reviewers: Schema.optional(Schema.NullOr(Schema.Array(RawUserSchema))),
60 labels: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))),
61 // A string, and "1000+" past GitLab's counting limit, so it is parsed rather than decoded.
62 changes_count: Schema.optional(Schema.NullOr(Schema.String)),
63 head_pipeline: Schema.optional(Schema.NullOr(RawPipelineSchema)),
64 /**
65 * What the requesting account may do, which only the single-merge-request endpoint carries.
66 * GitLab answers `can_merge` for this viewer against this merge request, so it already accounts
67 * for the role, the approval rules and a protected target branch — none of which a project's
68 * access level on its own would tell apart.
69 */
70 user: Schema.optional(
71 Schema.NullOr(Schema.Struct({ can_merge: Schema.optional(Schema.Boolean) })),
72 ),
73});
74​
75const RawNoteSchema = Schema.Struct({
76 id: Schema.Int,
77 body: Schema.optional(Schema.NullOr(Schema.String)),
78 author: Schema.optional(Schema.NullOr(RawUserSchema)),
79 created_at: Schema.String,
80 /** True for notes GitLab writes itself ("assigned to…"), which are events, not comments. */
81 system: Schema.optional(Schema.Boolean),
82 type: Schema.optional(Schema.NullOr(Schema.String)),
83 position: Schema.optional(
84 Schema.NullOr(
85 Schema.Struct({
86 new_path: Schema.optional(Schema.NullOr(Schema.String)),
87 old_path: Schema.optional(Schema.NullOr(Schema.String)),
88 }),
89 ),
90 ),
91});
92​
93/**
94 * A discussion note carrying its place in the diff, which is the shape the whole thread view
95 * is built from. `resolved` lives on the note rather than on the discussion: GitLab calls a
96 * discussion resolved once every resolvable note in it is.
97 */
98const RawDiscussionNoteSchema = Schema.Struct({
99 id: Schema.Int,
100 body: Schema.optional(Schema.NullOr(Schema.String)),
101 author: Schema.optional(Schema.NullOr(RawUserSchema)),
102 created_at: Schema.String,
103 system: Schema.optional(Schema.Boolean),
104 resolvable: Schema.optional(Schema.Boolean),
105 resolved: Schema.optional(Schema.NullOr(Schema.Boolean)),
106 position: Schema.optional(
107 Schema.NullOr(
108 Schema.Struct({
109 position_type: Schema.optional(Schema.NullOr(Schema.String)),
110 new_path: Schema.optional(Schema.NullOr(Schema.String)),
111 old_path: Schema.optional(Schema.NullOr(Schema.String)),
112 new_line: Schema.optional(Schema.NullOr(Schema.Int)),
113 old_line: Schema.optional(Schema.NullOr(Schema.Int)),
114 }),
115 ),
116 ),
117});
118​
119const RawDiscussionSchema = Schema.Struct({
120 id: Schema.String,
121 notes: Schema.optional(Schema.NullOr(Schema.Array(RawDiscussionNoteSchema))),
122});
123​
124const RawDiffRefsSchema = Schema.Struct({
125 diff_refs: Schema.optional(
126 Schema.NullOr(
127 Schema.Struct({
128 base_sha: Schema.String,
129 head_sha: Schema.String,
130 start_sha: Schema.String,
131 }),
132 ),
133 ),
134});
135​
136const RawCommitSchema = Schema.Struct({
137 id: TrimmedNonEmptyString,
138 title: Schema.optional(Schema.NullOr(Schema.String)),
139 committed_date: Schema.optional(Schema.NullOr(Schema.String)),
140 created_at: Schema.optional(Schema.NullOr(Schema.String)),
141 parent_ids: Schema.optional(Schema.Array(Schema.String)),
142 author_name: Schema.optional(Schema.NullOr(Schema.String)),
143 author_email: Schema.optional(Schema.NullOr(Schema.String)),
144 stats: Schema.optional(
145 Schema.NullOr(
146 Schema.Struct({
147 additions: Schema.optional(Schema.Int),
148 deletions: Schema.optional(Schema.Int),
149 }),
150 ),
151 ),
152});
153​
154const RawDiffSchema = Schema.Struct({
155 old_path: Schema.String,
156 new_path: Schema.String,
157 a_mode: Schema.optional(Schema.NullOr(Schema.String)),
158 b_mode: Schema.optional(Schema.NullOr(Schema.String)),
159 new_file: Schema.optional(Schema.Boolean),
160 renamed_file: Schema.optional(Schema.Boolean),
161 deleted_file: Schema.optional(Schema.Boolean),
162 diff: Schema.optional(Schema.NullOr(Schema.String)),
163 /** GitLab omits the hunks for a file it considers too large to inline. */
164 too_large: Schema.optional(Schema.NullOr(Schema.Boolean)),
165 /** And for one it collapsed, which withholds them the same way. */
166 collapsed: Schema.optional(Schema.NullOr(Schema.Boolean)),
167});
168​
169const RawViewerSchema = Schema.Struct({
170 username: Schema.optional(Schema.NullOr(Schema.String)),
171});
172​
173/** A GitLab project settles on one merge strategy plus an optional squash. */
174const RawProjectMergeSettingsSchema = Schema.Struct({
175 merge_method: Schema.optional(Schema.NullOr(Schema.String)),
176 squash_option: Schema.optional(Schema.NullOr(Schema.String)),
177});
178​
179export interface GitLabMergeRequestListItem {
180 readonly number: number;
181 readonly title: string;
182 readonly url: string;
183 readonly author: PullRequestActor | null;
184 readonly headBranch: string;
185 readonly baseBranch: string;
186 readonly state: PullRequestState;
187 readonly isDraft: boolean;
188 readonly mergeability: PullRequestMergeability;
189 /**
190 * GitLab reports neither added nor removed lines on a merge request, so both stay zero and
191 * the surface omits the stat. The Code tab counts them from the patch it already fetched.
192 */
193 readonly additions: number;
194 readonly deletions: number;
195 readonly createdAt: string;
196 readonly updatedAt: string;
197 readonly reviewRequestLogins: ReadonlyArray<string>;
198 readonly labels: ReadonlyArray<PullRequestLabel>;
200​
201export interface GitLabMergeRequestDetail extends GitLabMergeRequestListItem {
202 readonly body: string;
203 readonly changedFiles: number;
204 readonly mergedAt: string | null;
205 readonly closedAt: string | null;
206 readonly reviewers: ReadonlyArray<PullRequestActor>;
207 readonly checks: ReadonlyArray<PullRequestCheck>;
208 /** False only where GitLab said so; an answer without the field leaves merging permitted. */
209 readonly viewerCanMerge: boolean;
210 /** The reviewers as GitLab addresses them, which is what writing the set back takes. */
211 readonly reviewerIds: ReadonlyArray<number>;
213​
214function trimmed(value: string | null | undefined): string | null {
215 const text = value?.trim() ?? "";
216 return text.length > 0 ? text : null;
218​
219function toActor(raw: Schema.Schema.Type<typeof RawUserSchema> | null | undefined) {
220 const login = trimmed(raw?.username);
221 return login === null
222 ? null
223 : { login, name: trimmed(raw?.name), avatarUrl: trimmed(raw?.avatar_url) };
225​
226function toState(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): PullRequestState {
227 if (trimmed(raw.merged_at) !== null) return "merged";
228 switch (raw.state?.trim().toLowerCase()) {
229 case "merged":
230 return "merged";
231 case "closed":
232 return "closed";
233 default:
234 // `locked` is an open merge request whose discussion is locked.
235 return "open";
236 }
238​
239function toMergeability(
240 raw: Schema.Schema.Type<typeof RawMergeRequestSchema>,
241): PullRequestMergeability {
242 if (raw.has_conflicts === true) return "conflicting";
243 switch (raw.merge_status?.trim().toLowerCase()) {
244 case "can_be_merged":
245 return "mergeable";
246 case "cannot_be_merged":
247 return "conflicting";
248 default:
249 // `unchecked` and `checking` mean GitLab has not finished the merge check yet.
250 return "unknown";
251 }
253​
254function toLabels(raw: ReadonlyArray<string> | null | undefined): ReadonlyArray<PullRequestLabel> {
255 // GitLab returns label names only, so there is no colour to carry.
256 return (raw ?? []).flatMap((label) => {
257 const name = trimmed(label);
258 return name === null ? [] : [{ name, color: null }];
259 });
261​
262/**
263 * "3" for a counted change set, "1000+" once GitLab gives up counting. The leading number is
264 * the floor either way, which reads better than dropping an uncounted change set to nothing.
265 */
266function toChangedFiles(value: string | null | undefined): number {
267 const parsed = Number.parseInt(value?.trim() ?? "", 10);
268 return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
270​
271function toPipelineStatus(value: string | null | undefined): PullRequestCheckStatus {
272 switch (value?.trim().toLowerCase()) {
273 case "success":
274 return "success";
275 case "failed":
276 return "failure";
277 case "canceled":
278 case "cancelling":
279 return "cancelled";
280 case "skipped":
281 return "skipped";
282 // A pipeline waiting on a person is not progress, and it is not a failure either.
283 case "manual":
284 case "scheduled":
285 return "neutral";
286 default:
287 return "pending";
288 }
290​
291/**
292 * GitLab has no per-job check list on a merge request, so its pipeline is reported as the one
293 * check. The jobs behind it stay one click away through the pipeline URL.
294 */
295function toChecks(
296 raw: Schema.Schema.Type<typeof RawMergeRequestSchema>,
297): ReadonlyArray<PullRequestCheck> {
298 const pipeline = raw.head_pipeline;
299 if (!pipeline) return [];
300 return [
301 {
302 name: "Pipeline",
303 status: toPipelineStatus(pipeline.status),
304 description: trimmed(pipeline.source),
305 url: trimmed(pipeline.web_url),
306 },
307 ];
309​
310function toListItem(
311 raw: Schema.Schema.Type<typeof RawMergeRequestSchema>,
312): GitLabMergeRequestListItem {
313 return {
314 number: raw.iid,
315 title: raw.title,
316 url: raw.web_url,
317 author: toActor(raw.author),
318 headBranch: raw.source_branch,
319 baseBranch: raw.target_branch,
320 state: toState(raw),
321 isDraft: raw.draft ?? raw.work_in_progress ?? false,
322 mergeability: toMergeability(raw),
323 additions: 0,
324 deletions: 0,
325 createdAt: raw.created_at,
326 updatedAt: raw.updated_at,
327 reviewRequestLogins: (raw.reviewers ?? []).flatMap((reviewer) => {
328 const login = trimmed(reviewer.username);
329 return login === null ? [] : [login];
330 }),
331 labels: toLabels(raw.labels),
332 };
334​
335function toDetail(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): GitLabMergeRequestDetail {
336 const listItem = toListItem(raw);
337 return {
338 ...listItem,
339 body: raw.description ?? "",
340 changedFiles: toChangedFiles(raw.changes_count),
341 mergedAt: trimmed(raw.merged_at),
342 closedAt: trimmed(raw.closed_at),
343 // Built from the reviewers themselves rather than from their logins, so the avatars survive.
344 reviewers: (raw.reviewers ?? []).flatMap((reviewer) => {
345 const actor = toActor(reviewer);
346 return actor === null ? [] : [actor];
347 }),
348 checks: toChecks(raw),
349 viewerCanMerge: raw.user?.can_merge !== false,
350 reviewerIds: (raw.reviewers ?? []).flatMap((reviewer) =>
351 reviewer.id === undefined ? [] : [reviewer.id],
352 ),
353 };
355​
356const decodeUnknownList = decodeJsonResult(Schema.Array(Schema.Unknown));
357const decodeMergeRequestEntry = Schema.decodeUnknownExit(RawMergeRequestSchema);
358const decodeMergeRequest = decodeJsonResult(RawMergeRequestSchema);
359const decodeNoteEntry = Schema.decodeUnknownExit(RawNoteSchema);
360const decodeUserEntry = Schema.decodeUnknownExit(RawUserSchema);
361const decodeCommitEntry = Schema.decodeUnknownExit(RawCommitSchema);
362const decodeCommit = decodeJsonResult(RawCommitSchema);
363const decodeDiffEntry = Schema.decodeUnknownExit(RawDiffSchema);
364const decodeDiscussionEntry = Schema.decodeUnknownExit(RawDiscussionSchema);
365const decodeDiffRefs = decodeJsonResult(RawDiffRefsSchema);
366const decodeViewer = decodeJsonResult(RawViewerSchema);
367const decodeProjectMergeSettings = decodeJsonResult(RawProjectMergeSettingsSchema);
368​
369type DecodeFailure = Cause.Cause<Schema.SchemaError>;
370​
371export interface GitLabProjectUsers {
372 readonly candidates: ReadonlyArray<PullRequestReviewerCandidate>;
373 /** Rows GitLab returned, counted before decoding, so a skipped row cannot hide a next page. */
374 readonly rawCount: number;
376​
377export interface GitLabMergeRequestListBatch {
378 readonly items: ReadonlyArray<GitLabMergeRequestListItem>;
379 /** Zero-based positions of the decoded items in GitLab's raw page. */
380 readonly rawIndexes: ReadonlyArray<number>;
381 /** Rows GitLab returned, counted before decoding, so a skipped row cannot hide a next page. */
382 readonly rawCount: number;
384​
385/** Malformed entries are skipped rather than failing the batch: one unexpected merge request
386 * must not blank the whole list. */
387export function decodeMergeRequestListJson(
388 raw: string,
389): Result.Result<GitLabMergeRequestListBatch, DecodeFailure> {
390 const decoded = decodeUnknownList(raw);
391 if (!Result.isSuccess(decoded)) {
392 return Result.fail(decoded.failure);
393 }
394 const items: GitLabMergeRequestListItem[] = [];
395 const rawIndexes: number[] = [];
396 for (const [rawIndex, entry] of decoded.success.entries()) {
397 const item = decodeMergeRequestEntry(entry);
398 if (Exit.isSuccess(item)) {
399 items.push(toListItem(item.value));
400 rawIndexes.push(rawIndex);
401 }
402 }
403 return Result.succeed({ items, rawIndexes, rawCount: decoded.success.length });
405​
406export function decodeMergeRequestDetailJson(
407 raw: string,
408): Result.Result<GitLabMergeRequestDetail, DecodeFailure> {
409 const decoded = decodeMergeRequest(raw);
410 return Result.isSuccess(decoded)
411 ? Result.succeed(toDetail(decoded.success))
412 : Result.fail(decoded.failure);
414​
415export function decodeViewerJson(raw: string): Result.Result<string | null, DecodeFailure> {
416 const decoded = decodeViewer(raw);
417 return Result.isSuccess(decoded)
418 ? Result.succeed(trimmed(decoded.success.username))
419 : Result.fail(decoded.failure);
421​
422/**
423 * The people with access to the project, which `GET /projects/:id/users` answers with — the same
424 * list GitLab's own reviewer field is filled from, including the members a group above the project
425 * lends it. A malformed row is skipped rather than failing the menu it belongs to.
426 *
427 * Nobody is marked requested here: who has been asked lives on the merge request, and only the
428 * caller holds both.
429 */
430export function decodeProjectUsersJson(
431 raw: string,
432): Result.Result<GitLabProjectUsers, DecodeFailure> {
433 const decoded = decodeUnknownList(raw);
434 if (!Result.isSuccess(decoded)) {
435 return Result.fail(decoded.failure);
436 }
437 const candidates: PullRequestReviewerCandidate[] = [];
438 for (const entry of decoded.success) {
439 const user = decodeUserEntry(entry);
440 if (Exit.isFailure(user) || user.value.id === undefined) continue;
441 const actor = toActor(user.value);
442 if (actor === null) continue;
443 candidates.push({
444 ...actor,
445 id: String(user.value.id),
446 kind: "user",
447 isRequested: false,
448 });
449 }
450 return Result.succeed({ candidates, rawCount: decoded.success.length });
452​
453/**
454 * GitLab settles the strategy per project rather than offering all three per merge request:
455 * `merge_method` picks one of merge commit, semi-linear or fast-forward, and squashing is a
456 * separate switch. An unrecognized setting offers nothing rather than offering a strategy the
457 * project forbids.
458 */
459export function decodeProjectMergeCapabilitiesJson(
460 raw: string,
461): Result.Result<PullRequestMergeCapabilities, DecodeFailure> {
462 const decoded = decodeProjectMergeSettings(raw);
463 if (!Result.isSuccess(decoded)) {
464 return Result.fail(decoded.failure);
465 }
466 const mergeMethod = decoded.success.merge_method?.trim().toLowerCase();
467 const squashOption = decoded.success.squash_option?.trim().toLowerCase();
468 return Result.succeed({
469 merge: mergeMethod === "merge",
470 // Both semi-linear and fast-forward histories are reached by rebasing onto the target.
471 rebase: mergeMethod === "rebase_merge" || mergeMethod === "ff",
472 // Only GitLab's own enabling values. An absent or unrecognized setting offers nothing,
473 // rather than offering a squash the project may forbid.
474 squash:
475 squashOption === "always" || squashOption === "default_on" || squashOption === "default_off",
476 });
478​
479/**
480 * Comments only. System notes are GitLab's own activity feed entries, and a `DiffNote` is the
481 * root of a line-level discussion, which is what the review-comment kind means.
482 *
483 * The raw note count comes back alongside, because dropping notes hides whether the page was
484 * full: a caller cannot tell "no more notes" from "a page of activity entries" without it.
485 */
486/** The three revisions a positioned comment is written against. */
487export interface GitLabDiffRefs {
488 readonly baseSha: string;
489 readonly headSha: string;
490 readonly startSha: string;
492​
493export interface GitLabDiscussions {
494 readonly threads: ReadonlyArray<PullRequestReviewThread>;
495 /** Discussions GitLab returned, counted before decoding, so a skipped one still counts. */
496 readonly rawCount: number;
498​
499/**
500 * Positioned discussions only. GitLab returns the merge request's whole conversation here,
501 * including the plain notes the timeline already shows, and only a positioned one belongs
502 * against a line of the diff.
503 */
504export function decodeDiscussionsJson(
505 raw: string,
506): Result.Result<GitLabDiscussions, DecodeFailure> {
507 const decoded = decodeUnknownList(raw);
508 if (!Result.isSuccess(decoded)) {
509 return Result.fail(decoded.failure);
510 }
511 const threads: PullRequestReviewThread[] = [];
512 for (const entry of decoded.success) {
513 const discussion = decodeDiscussionEntry(entry);
514 if (!Exit.isSuccess(discussion)) continue;
515 const notes = (discussion.value.notes ?? []).filter((note) => note.system !== true);
516 const root = notes[0];
517 const position = root?.position;
518 if (root === undefined || !position || position.position_type !== "text") continue;
519 // A comment on an added or context line carries `new_line`; one on a removed line carries
520 // only `old_line`, and belongs against the file as it was.
521 const side = position.new_line === null || position.new_line === undefined ? "left" : "right";
522 const path = trimmed(side === "left" ? position.old_path : position.new_path);
523 const line = side === "left" ? position.old_line : position.new_line;
524 if (path === null) continue;
525 threads.push({
526 id: discussion.value.id,
527 path,
528 line: typeof line === "number" && line > 0 ? line : null,
529 side,
530 isResolved: root.resolved === true,
531 // GitLab reports no equivalent of "written against a line that has since moved", so a
532 // thread the diff cannot place is worked out from the diff itself rather than claimed
533 // here.
534 isOutdated: false,
535 comments: notes.map((note) => ({
536 id: String(note.id),
537 author: toActor(note.author),
538 body: note.body ?? "",
539 createdAt: note.created_at,
540 url: null,
541 })),
542 });
543 }
544 return Result.succeed({ threads, rawCount: decoded.success.length });
546​
547export function decodeDiffRefsJson(
548 raw: string,
549): Result.Result<GitLabDiffRefs | null, DecodeFailure> {
550 const decoded = decodeDiffRefs(raw);
551 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
552 const refs = decoded.success.diff_refs;
553 return Result.succeed(
554 refs ? { baseSha: refs.base_sha, headSha: refs.head_sha, startSha: refs.start_sha } : null,
555 );
557​
558export function decodeNotesJson(
559 raw: string,
560): Result.Result<
561 { readonly comments: ReadonlyArray<PullRequestComment>; readonly rawCount: number },
562 DecodeFailure
563> {
564 const decoded = decodeUnknownList(raw);
565 if (!Result.isSuccess(decoded)) {
566 return Result.fail(decoded.failure);
567 }
568 const comments: PullRequestComment[] = [];
569 for (const entry of decoded.success) {
570 const note = decodeNoteEntry(entry);
571 if (Exit.isFailure(note)) continue;
572 const value = note.value;
573 if (value.system === true) continue;
574 const body = value.body ?? "";
575 if (body.trim().length === 0) continue;
576 const isDiffNote = value.type?.trim() === "DiffNote";
577 comments.push({
578 id: String(value.id),
579 kind: isDiffNote ? "review-comment" : "issue-comment",
580 author: toActor(value.author),
581 body,
582 createdAt: value.created_at,
583 url: null,
584 path: trimmed(value.position?.new_path) ?? trimmed(value.position?.old_path),
585 reviewState: null,
586 });
587 }
588 return Result.succeed({ comments, rawCount: decoded.success.length });
590​
591export function decodeCommitsJson(
592 raw: string,
593): Result.Result<ReadonlyArray<PullRequestCommit>, DecodeFailure> {
594 const decoded = decodeUnknownList(raw);
595 if (!Result.isSuccess(decoded)) {
596 return Result.fail(decoded.failure);
597 }
598 const commits: PullRequestCommit[] = [];
599 for (const entry of decoded.success) {
600 const commit = decodeCommitEntry(entry);
601 if (Exit.isFailure(commit)) continue;
602 const committedDate = trimmed(commit.value.committed_date) ?? trimmed(commit.value.created_at);
603 if (committedDate === null) continue;
604 commits.push({
605 oid: commit.value.id,
606 messageHeadline: commit.value.title ?? "",
607 committedDate,
608 ...(commit.value.stats === null || commit.value.stats === undefined
609 ? {}
610 : {
611 additions: Math.max(0, commit.value.stats.additions ?? 0),
612 deletions: Math.max(0, commit.value.stats.deletions ?? 0),
613 }),
614 authors: (() => {
615 const login = trimmed(commit.value.author_name) ?? trimmed(commit.value.author_email);
616 return login === null
617 ? []
618 : [{ login, name: trimmed(commit.value.author_name), avatarUrl: null }];
619 })(),
620 });
621 }
622 // GitLab lists a merge request's commits newest first; the timeline reads oldest first.
623 return Result.succeed(commits.toReversed());
625​
626/** The exact comparison GitLab uses for a commit-scoped diff. */
627export function decodeCommitDiffRefsJson(
628 raw: string,
629): Result.Result<GitLabDiffRefs | null, DecodeFailure> {
630 const decoded = decodeCommit(raw);
631 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
632 const baseSha = trimmed(decoded.success.parent_ids?.[0]);
633 const headSha = trimmed(decoded.success.id);
634 return Result.succeed(
635 baseSha === null || headSha === null ? null : { baseSha, headSha, startSha: baseSha },
636 );
638​
639function diffHeaderPaths(raw: Schema.Schema.Type<typeof RawDiffSchema>): {
640 readonly from: string;
641 readonly to: string;
642} {
643 return {
644 from: raw.new_file === true ? "/dev/null" : `a/${raw.old_path}`,
645 to: raw.deleted_file === true ? "/dev/null" : `b/${raw.new_path}`,
646 };
648​
649export interface GitLabMergeRequestPatch {
650 readonly patch: string;
651 /** At least one file's hunks were withheld by GitLab as too large to inline. */
652 readonly truncated: boolean;
653 /** Files GitLab returned, counted before decoding, so the caller can page. */
654 readonly rawCount: number;
656​
657/**
658 * GitLab returns hunks per file with no `diff --git` header, so the unified patch every diff
659 * viewer expects is assembled here. This decodes one page; walking pages is the caller's job,
660 * which is why the raw file count comes back with the patch.
661 */
662export function decodeMergeRequestDiffsJson(
663 raw: string,
664): Result.Result<GitLabMergeRequestPatch, DecodeFailure> {
665 const decoded = decodeUnknownList(raw);
666 if (!Result.isSuccess(decoded)) {
667 return Result.fail(decoded.failure);
668 }
669 const sections: string[] = [];
670 let truncated = false;
671 for (const entry of decoded.success) {
672 const file = decodeDiffEntry(entry);
673 if (Exit.isFailure(file)) continue;
674 const value = file.value;
675 const hunks = value.diff ?? "";
676 if (hunks.length === 0) {
677 // A file GitLab declined to inline still belongs in the file list, header only.
678 truncated = truncated || value.too_large === true || value.collapsed === true;
679 }
680 const { from, to } = diffHeaderPaths(value);
681 const header = [
682 `diff --git a/${value.old_path} b/${value.new_path}`,
683 ...(value.new_file === true ? [`new file mode ${value.b_mode ?? "100644"}`] : []),
684 ...(value.deleted_file === true ? [`deleted file mode ${value.a_mode ?? "100644"}`] : []),
685 ...(value.renamed_file === true
686 ? [`rename from ${value.old_path}`, `rename to ${value.new_path}`]
687 : []),
688 `--- ${from}`,
689 `+++ ${to}`,
690 ].join("\n");
691 sections.push(hunks.length === 0 ? header : `${header}\n${hunks.replace(/\n?$/, "\n")}`);
692 }
693 return Result.succeed({
694 patch: sections.join("\n"),
695 truncated,
696 rawCount: decoded.success.length,
697 });