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

gitLabMergeRequestJson.ts

959 lines32.8 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 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 sha: Schema.optional(Schema.NullOr(Schema.String)),
51 state: Schema.optional(Schema.NullOr(Schema.String)),
52 draft: Schema.optional(Schema.Boolean),
53 work_in_progress: Schema.optional(Schema.Boolean),
54 merge_status: Schema.optional(Schema.NullOr(Schema.String)),
55 has_conflicts: Schema.optional(Schema.NullOr(Schema.Boolean)),
56 created_at: Schema.String,
57 updated_at: Schema.String,
58 merged_at: Schema.optional(Schema.NullOr(Schema.String)),
59 closed_at: Schema.optional(Schema.NullOr(Schema.String)),
60 reviewers: Schema.optional(Schema.NullOr(Schema.Array(RawUserSchema))),
61 assignees: Schema.optional(Schema.NullOr(Schema.Array(RawUserSchema))),
62 labels: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))),
63 // A string, and "1000+" past GitLab's counting limit, so it is parsed rather than decoded.
64 changes_count: Schema.optional(Schema.NullOr(Schema.String)),
65 head_pipeline: Schema.optional(Schema.NullOr(RawPipelineSchema)),
66 user: Schema.optional(
67 Schema.NullOr(Schema.Struct({ can_merge: Schema.optional(Schema.Boolean) })),
68 ),
69 merge_when_pipeline_succeeds: Schema.optional(Schema.NullOr(Schema.Boolean)),
70 auto_merge_enabled: Schema.optional(Schema.NullOr(Schema.Boolean)),
71 squash_on_merge: Schema.optional(Schema.NullOr(Schema.Boolean)),
72 squash: Schema.optional(Schema.NullOr(Schema.Boolean)),
73 /**
74 * It costs a walk of the two branches, so GitLab withholds it unless
75 * `include_diverged_commits_count` asks for it, and answers it only for a single merge
76 * request — a list never carries it, however it is asked for.
77 */
78 diverged_commits_count: Schema.optional(Schema.NullOr(Schema.Int)),
79});
80​
81const RawNoteSchema = Schema.Struct({
82 id: Schema.Int,
83 body: Schema.optional(Schema.NullOr(Schema.String)),
84 author: Schema.optional(Schema.NullOr(RawUserSchema)),
85 created_at: Schema.String,
86 system: Schema.optional(Schema.Boolean),
87 type: Schema.optional(Schema.NullOr(Schema.String)),
88 position: Schema.optional(
89 Schema.NullOr(
90 Schema.Struct({
91 new_path: Schema.optional(Schema.NullOr(Schema.String)),
92 old_path: Schema.optional(Schema.NullOr(Schema.String)),
93 }),
94 ),
95 ),
96});
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 too_large: Schema.optional(Schema.NullOr(Schema.Boolean)),
164 collapsed: Schema.optional(Schema.NullOr(Schema.Boolean)),
165});
166​
167const RawViewerSchema = Schema.Struct({
168 username: Schema.optional(Schema.NullOr(Schema.String)),
169});
170​
171const RawProjectMergeSettingsSchema = Schema.Struct({
172 merge_method: Schema.optional(Schema.NullOr(Schema.String)),
173 squash_option: Schema.optional(Schema.NullOr(Schema.String)),
174});
175​
176export interface GitLabMergeRequestListItem {
177 readonly number: number;
178 readonly title: string;
179 readonly url: string;
180 readonly author: PullRequestActor | null;
181 readonly headBranch: string;
182 readonly baseBranch: string;
183 readonly state: PullRequestState;
184 readonly isDraft: boolean;
185 readonly mergeability: PullRequestMergeability;
186 readonly additions: number;
187 readonly deletions: number;
188 readonly createdAt: string;
189 readonly updatedAt: string;
190 readonly reviewRequestLogins: ReadonlyArray<string>;
191 readonly labels: ReadonlyArray<PullRequestLabel>;
192 readonly assignees?: ReadonlyArray<PullRequestActor>;
194​
195export interface GitLabMergeRequestDetail extends GitLabMergeRequestListItem {
196 readonly body: string;
197 readonly changedFiles: number;
198 readonly mergedAt: string | null;
199 readonly closedAt: string | null;
200 readonly reviewers: ReadonlyArray<PullRequestActor>;
201 readonly checks: ReadonlyArray<PullRequestCheck>;
202 readonly viewerCanMerge: boolean;
203 readonly reviewerIds: ReadonlyArray<number>;
204 /** Every assignee id, even one without a username to show, since writes replace the set. */
205 readonly assigneeIds: ReadonlyArray<number>;
206 /** The candidate list leads with these, since one page of project users need not reach them. */
207 readonly assigneeUsers: ReadonlyArray<PullRequestActor & { readonly id: number }>;
208 readonly autoMergeEnabled?: boolean;
209 readonly autoMergeMethod?: PullRequestMergeMethod;
210 /**
211 * Absent where GitLab did not count, which is not the same as a branch that has nothing behind
212 * it: an install too old to answer must not be read as saying the branch is current.
213 */
214 readonly divergedCommits?: number;
215 readonly headSha?: string;
217​
218function trimmed(value: string | null | undefined): string | null {
219 const text = value?.trim() ?? "";
220 return text.length > 0 ? text : null;
222​
223function toActor(raw: Schema.Schema.Type<typeof RawUserSchema> | null | undefined) {
224 const login = trimmed(raw?.username);
225 return login === null
226 ? null
227 : { login, name: trimmed(raw?.name), avatarUrl: trimmed(raw?.avatar_url) };
229​
230function toState(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): PullRequestState {
231 if (trimmed(raw.merged_at) !== null) return "merged";
232 switch (raw.state?.trim().toLowerCase()) {
233 case "merged":
234 return "merged";
235 case "closed":
236 return "closed";
237 default:
238 return "open";
239 }
241​
242function toMergeability(
243 raw: Schema.Schema.Type<typeof RawMergeRequestSchema>,
244): PullRequestMergeability {
245 if (raw.has_conflicts === true) return "conflicting";
246 switch (raw.merge_status?.trim().toLowerCase()) {
247 case "can_be_merged":
248 return "mergeable";
249 case "cannot_be_merged":
250 return "conflicting";
251 default:
252 return "unknown";
253 }
255​
256function toLabels(raw: ReadonlyArray<string> | null | undefined): ReadonlyArray<PullRequestLabel> {
257 return (raw ?? []).flatMap((label) => {
258 const name = trimmed(label);
259 return name === null ? [] : [{ name, color: null }];
260 });
262​
263function toChangedFiles(value: string | null | undefined): number {
264 const parsed = Number.parseInt(value?.trim() ?? "", 10);
265 return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
267​
268function toPipelineStatus(value: string | null | undefined): PullRequestCheckStatus {
269 switch (value?.trim().toLowerCase()) {
270 case "success":
271 return "success";
272 case "failed":
273 return "failure";
274 case "canceled":
275 case "cancelling":
276 return "cancelled";
277 case "skipped":
278 return "skipped";
279 case "manual":
280 case "scheduled":
281 return "neutral";
282 default:
283 return "pending";
284 }
286​
287function toChecks(
288 raw: Schema.Schema.Type<typeof RawMergeRequestSchema>,
289): ReadonlyArray<PullRequestCheck> {
290 const pipeline = raw.head_pipeline;
291 if (!pipeline) return [];
292 return [
293 {
294 name: "Pipeline",
295 status: toPipelineStatus(pipeline.status),
296 description: trimmed(pipeline.source),
297 url: trimmed(pipeline.web_url),
298 },
299 ];
301​
302function toListItem(
303 raw: Schema.Schema.Type<typeof RawMergeRequestSchema>,
304): GitLabMergeRequestListItem {
305 return {
306 number: raw.iid,
307 title: raw.title,
308 url: raw.web_url,
309 author: toActor(raw.author),
310 headBranch: raw.source_branch,
311 baseBranch: raw.target_branch,
312 state: toState(raw),
313 isDraft: raw.draft ?? raw.work_in_progress ?? false,
314 mergeability: toMergeability(raw),
315 additions: 0,
316 deletions: 0,
317 createdAt: raw.created_at,
318 updatedAt: raw.updated_at,
319 reviewRequestLogins: (raw.reviewers ?? []).flatMap((reviewer) => {
320 const login = trimmed(reviewer.username);
321 return login === null ? [] : [login];
322 }),
323 labels: toLabels(raw.labels),
324 assignees: (raw.assignees ?? []).flatMap((assignee) => {
325 const actor = toActor(assignee);
326 return actor === null ? [] : [actor];
327 }),
328 };
330​
331function toDetail(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): GitLabMergeRequestDetail {
332 const listItem = toListItem(raw);
333 const headSha = trimmed(raw.sha);
334 const autoMerge =
335 raw.merge_when_pipeline_succeeds == null && raw.auto_merge_enabled == null
336 ? undefined
337 : raw.merge_when_pipeline_succeeds === true || raw.auto_merge_enabled === true;
338 return {
339 ...listItem,
340 body: raw.description ?? "",
341 changedFiles: toChangedFiles(raw.changes_count),
342 mergedAt: trimmed(raw.merged_at),
343 closedAt: trimmed(raw.closed_at),
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 assigneeIds: (raw.assignees ?? []).flatMap((assignee) =>
354 assignee.id === undefined ? [] : [assignee.id],
355 ),
356 assigneeUsers: (raw.assignees ?? []).flatMap((assignee) => {
357 const actor = toActor(assignee);
358 return actor === null || assignee.id === undefined ? [] : [{ ...actor, id: assignee.id }];
359 }),
360 ...(autoMerge === undefined ? {} : { autoMergeEnabled: autoMerge }),
361 ...(autoMerge === true && raw.squash_on_merge === true
362 ? { autoMergeMethod: "squash" as const }
363 : {}),
364 ...(raw.diverged_commits_count == null ? {} : { divergedCommits: raw.diverged_commits_count }),
365 ...(headSha === null ? {} : { headSha }),
366 };
368​
369const decodeUnknownList = decodeJsonResult(Schema.Array(Schema.Unknown));
370const decodeMergeRequestEntry = Schema.decodeUnknownExit(RawMergeRequestSchema);
371const decodeMergeRequest = decodeJsonResult(RawMergeRequestSchema);
372const decodeNoteEntry = Schema.decodeUnknownExit(RawNoteSchema);
373const decodeUserEntry = Schema.decodeUnknownExit(RawUserSchema);
374const decodeCommitEntry = Schema.decodeUnknownExit(RawCommitSchema);
375const decodeCommit = decodeJsonResult(RawCommitSchema);
376const decodeMergeRequestChanges = decodeJsonResult(
377 Schema.Struct({
378 changes: Schema.Array(Schema.Unknown),
379 overflow: Schema.optional(Schema.Boolean),
380 changes_count: Schema.optional(Schema.NullOr(Schema.String)),
381 }),
382);
383const decodeDiffEntry = Schema.decodeUnknownExit(RawDiffSchema);
384const decodeDiscussionEntry = Schema.decodeUnknownExit(RawDiscussionSchema);
385const decodeDiffRefs = decodeJsonResult(RawDiffRefsSchema);
386const decodeViewer = decodeJsonResult(RawViewerSchema);
387const decodeProjectMergeSettings = decodeJsonResult(RawProjectMergeSettingsSchema);
388​
389type DecodeFailure = Cause.Cause<Schema.SchemaError>;
390​
391export interface GitLabProjectUsers {
392 readonly candidates: ReadonlyArray<PullRequestReviewerCandidate>;
393 /** Rows GitLab returned, counted before decoding, so a skipped row cannot hide a next page. */
394 readonly rawCount: number;
396​
397export interface GitLabMergeRequestListBatch {
398 readonly items: ReadonlyArray<GitLabMergeRequestListItem>;
399 readonly rawIndexes: ReadonlyArray<number>;
400 readonly rawCount: number;
402​
403export function decodeMergeRequestListJson(
404 raw: string,
405): Result.Result<GitLabMergeRequestListBatch, DecodeFailure> {
406 const decoded = decodeUnknownList(raw);
407 if (!Result.isSuccess(decoded)) {
408 return Result.fail(decoded.failure);
409 }
410 const items: GitLabMergeRequestListItem[] = [];
411 const rawIndexes: number[] = [];
412 for (const [rawIndex, entry] of decoded.success.entries()) {
413 const item = decodeMergeRequestEntry(entry);
414 if (Exit.isSuccess(item)) {
415 items.push(toListItem(item.value));
416 rawIndexes.push(rawIndex);
417 }
418 }
419 return Result.succeed({ items, rawIndexes, rawCount: decoded.success.length });
421​
422export function decodeMergeRequestDetailJson(
423 raw: string,
424): Result.Result<GitLabMergeRequestDetail, DecodeFailure> {
425 const decoded = decodeMergeRequest(raw);
426 return Result.isSuccess(decoded)
427 ? Result.succeed(toDetail(decoded.success))
428 : Result.fail(decoded.failure);
430​
431export function decodeViewerJson(raw: string): Result.Result<string | null, DecodeFailure> {
432 const decoded = decodeViewer(raw);
433 return Result.isSuccess(decoded)
434 ? Result.succeed(trimmed(decoded.success.username))
435 : Result.fail(decoded.failure);
437​
438export function decodeProjectUsersJson(
439 raw: string,
440): Result.Result<GitLabProjectUsers, DecodeFailure> {
441 const decoded = decodeUnknownList(raw);
442 if (!Result.isSuccess(decoded)) {
443 return Result.fail(decoded.failure);
444 }
445 const candidates: PullRequestReviewerCandidate[] = [];
446 for (const entry of decoded.success) {
447 const user = decodeUserEntry(entry);
448 if (Exit.isFailure(user) || user.value.id === undefined) continue;
449 const actor = toActor(user.value);
450 if (actor === null) continue;
451 candidates.push({
452 ...actor,
453 id: String(user.value.id),
454 kind: "user",
455 isRequested: false,
456 });
457 }
458 return Result.succeed({ candidates, rawCount: decoded.success.length });
460​
461export function decodeProjectMergeCapabilitiesJson(
462 raw: string,
463): Result.Result<PullRequestMergeCapabilities, DecodeFailure> {
464 const decoded = decodeProjectMergeSettings(raw);
465 if (!Result.isSuccess(decoded)) {
466 return Result.fail(decoded.failure);
467 }
468 const mergeMethod = decoded.success.merge_method?.trim().toLowerCase();
469 const squashOption = decoded.success.squash_option?.trim().toLowerCase();
470 return Result.succeed({
471 merge: mergeMethod === "merge",
472 rebase: mergeMethod === "rebase_merge" || mergeMethod === "ff",
473 squash:
474 squashOption === "always" || squashOption === "default_on" || squashOption === "default_off",
475 });
477​
478export interface GitLabDiffRefs {
479 readonly baseSha: string;
480 readonly headSha: string;
481 readonly startSha: string;
483​
484export interface GitLabDiscussions {
485 readonly threads: ReadonlyArray<PullRequestReviewThread>;
486 readonly rawCount: number;
488​
489export function decodeDiscussionsJson(
490 raw: string,
491): Result.Result<GitLabDiscussions, DecodeFailure> {
492 const decoded = decodeUnknownList(raw);
493 if (!Result.isSuccess(decoded)) {
494 return Result.fail(decoded.failure);
495 }
496 const threads: PullRequestReviewThread[] = [];
497 for (const entry of decoded.success) {
498 const discussion = decodeDiscussionEntry(entry);
499 if (!Exit.isSuccess(discussion)) continue;
500 const notes = (discussion.value.notes ?? []).filter((note) => note.system !== true);
501 const root = notes[0];
502 const position = root?.position;
503 if (root === undefined || !position || position.position_type !== "text") continue;
504 const side = position.new_line === null || position.new_line === undefined ? "left" : "right";
505 const path = trimmed(side === "left" ? position.old_path : position.new_path);
506 const line = side === "left" ? position.old_line : position.new_line;
507 if (path === null) continue;
508 threads.push({
509 id: discussion.value.id,
510 path,
511 line: typeof line === "number" && line > 0 ? line : null,
512 side,
513 isResolved: root.resolved === true,
514 isOutdated: false,
515 comments: notes.map((note) => ({
516 id: String(note.id),
517 author: toActor(note.author),
518 body: note.body ?? "",
519 createdAt: note.created_at,
520 url: null,
521 })),
522 });
523 }
524 return Result.succeed({ threads, rawCount: decoded.success.length });
526​
527export function decodeDiffRefsJson(
528 raw: string,
529): Result.Result<GitLabDiffRefs | null, DecodeFailure> {
530 const decoded = decodeDiffRefs(raw);
531 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
532 const refs = decoded.success.diff_refs;
533 return Result.succeed(
534 refs ? { baseSha: refs.base_sha, headSha: refs.head_sha, startSha: refs.start_sha } : null,
535 );
537​
538export function decodeNotesJson(
539 raw: string,
540): Result.Result<
541 { readonly comments: ReadonlyArray<PullRequestComment>; readonly rawCount: number },
542 DecodeFailure
543> {
544 const decoded = decodeUnknownList(raw);
545 if (!Result.isSuccess(decoded)) {
546 return Result.fail(decoded.failure);
547 }
548 const comments: PullRequestComment[] = [];
549 for (const entry of decoded.success) {
550 const note = decodeNoteEntry(entry);
551 if (Exit.isFailure(note)) continue;
552 const value = note.value;
553 if (value.system === true) continue;
554 const body = value.body ?? "";
555 if (body.trim().length === 0) continue;
556 const isDiffNote = value.type?.trim() === "DiffNote";
557 comments.push({
558 id: String(value.id),
559 kind: isDiffNote ? "review-comment" : "issue-comment",
560 author: toActor(value.author),
561 body,
562 createdAt: value.created_at,
563 url: null,
564 path: trimmed(value.position?.new_path) ?? trimmed(value.position?.old_path),
565 reviewState: null,
566 });
567 }
568 return Result.succeed({ comments, rawCount: decoded.success.length });
570​
571export function decodeCommitsJson(
572 raw: string,
573): Result.Result<ReadonlyArray<PullRequestCommit>, DecodeFailure> {
574 const decoded = decodeUnknownList(raw);
575 if (!Result.isSuccess(decoded)) {
576 return Result.fail(decoded.failure);
577 }
578 const commits: PullRequestCommit[] = [];
579 for (const entry of decoded.success) {
580 const commit = decodeCommitEntry(entry);
581 if (Exit.isFailure(commit)) continue;
582 const committedDate = trimmed(commit.value.committed_date) ?? trimmed(commit.value.created_at);
583 if (committedDate === null) continue;
584 commits.push({
585 oid: commit.value.id,
586 messageHeadline: commit.value.title ?? "",
587 committedDate,
588 ...(commit.value.stats === null || commit.value.stats === undefined
589 ? {}
590 : {
591 additions: Math.max(0, commit.value.stats.additions ?? 0),
592 deletions: Math.max(0, commit.value.stats.deletions ?? 0),
593 }),
594 authors: (() => {
595 const login = trimmed(commit.value.author_name) ?? trimmed(commit.value.author_email);
596 return login === null
597 ? []
598 : [{ login, name: trimmed(commit.value.author_name), avatarUrl: null }];
599 })(),
600 });
601 }
602 return Result.succeed(commits.toReversed());
604​
605export function decodeCommitDiffRefsJson(
606 raw: string,
607): Result.Result<GitLabDiffRefs | null, DecodeFailure> {
608 const decoded = decodeCommit(raw);
609 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
610 const baseSha = trimmed(decoded.success.parent_ids?.[0]);
611 const headSha = trimmed(decoded.success.id);
612 return Result.succeed(
613 baseSha === null || headSha === null ? null : { baseSha, headSha, startSha: baseSha },
614 );
616​
617function diffHeaderPaths(raw: Schema.Schema.Type<typeof RawDiffSchema>): {
618 readonly from: string;
619 readonly to: string;
620} {
621 return {
622 from: raw.new_file === true ? "/dev/null" : quoteGitPatchPath(`a/${raw.old_path}`),
623 to: raw.deleted_file === true ? "/dev/null" : quoteGitPatchPath(`b/${raw.new_path}`),
624 };
626​
627export interface GitLabMergeRequestPatch {
628 readonly patch: string;
629 readonly truncated: boolean;
630 readonly rawCount: number;
632​
633export function decodeMergeRequestDiffsJson(
634 raw: string,
635): Result.Result<GitLabMergeRequestPatch, DecodeFailure> {
636 const decoded = decodeUnknownList(raw);
637 if (!Result.isSuccess(decoded)) {
638 return Result.fail(decoded.failure);
639 }
640 return Result.succeed(mergeRequestPatch(decoded.success));
642​
643/** Older GitLab instances return all files in a non-paginated merge request wrapper. */
644export function decodeMergeRequestChangesJson(
645 raw: string,
646): Result.Result<GitLabMergeRequestPatch, DecodeFailure> {
647 const decoded = decodeMergeRequestChanges(raw);
648 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
649 const patch = mergeRequestPatch(decoded.success.changes);
650 return Result.succeed({
651 ...patch,
652 truncated:
653 patch.truncated ||
654 decoded.success.overflow === true ||
655 decoded.success.changes_count?.endsWith("+") === true,
656 });
658​
659/** Builds file patches, retaining raw counts and recording files whose contents are missing. */
660function mergeRequestPatch(entries: ReadonlyArray<unknown>): GitLabMergeRequestPatch {
661 const sections: string[] = [];
662 let truncated = false;
663 for (const entry of entries) {
664 const file = decodeDiffEntry(entry);
665 if (Exit.isFailure(file)) {
666 truncated = true;
667 continue;
668 }
669 const value = file.value;
670 const hunks = value.diff ?? "";
671 if (hunks.length === 0) {
672 truncated = truncated || value.too_large === true || value.collapsed === true;
673 }
674 const { from, to } = diffHeaderPaths(value);
675 const header = [
676 `diff --git ${quoteGitPatchPath(`a/${value.old_path}`)} ${quoteGitPatchPath(`b/${value.new_path}`)}`,
677 ...(value.new_file === true ? [`new file mode ${value.b_mode ?? "100644"}`] : []),
678 ...(value.deleted_file === true ? [`deleted file mode ${value.a_mode ?? "100644"}`] : []),
679 ...(value.renamed_file === true
680 ? [
681 `rename from ${quoteGitPatchPath(value.old_path)}`,
682 `rename to ${quoteGitPatchPath(value.new_path)}`,
683 ]
684 : []),
685 `--- ${from}`,
686 `+++ ${to}`,
687 ].join("\n");
688 sections.push(hunks.length === 0 ? header : `${header}\n${hunks.replace(/\n?$/, "\n")}`);
689 }
690 return {
691 patch: sections.join("\n"),
692 truncated,
693 rawCount: entries.length,
694 };
696​
697const GITLAB_AWARD_BY_CONTENT: Readonly<Record<PullRequestReactionContent, string>> = {
698 "thumbs-up": "thumbsup",
699 "thumbs-down": "thumbsdown",
700 laugh: "laughing",
701 hooray: "tada",
702 confused: "confused",
703 heart: "heart",
704 rocket: "rocket",
705 eyes: "eyes",
706};
707​
708const CONTENT_BY_GITLAB_AWARD: Readonly<Record<string, PullRequestReactionContent>> =
709 Object.fromEntries(
710 Object.entries(GITLAB_AWARD_BY_CONTENT).map(([content, name]) => [name, content]),
711 ) as Readonly<Record<string, PullRequestReactionContent>>;
712​
713export function gitLabAwardName(content: PullRequestReactionContent): string {
714 return GITLAB_AWARD_BY_CONTENT[content];
716​
717export const AWARD_EMOJI_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!, $cursor: String) {
718 currentUser { username }
719 project(fullPath: $fullPath) {
720 mergeRequest(iid: $iid) {
721 awardEmoji { nodes { name user { username } } }
722 notes(first: 100, after: $cursor) {
723 pageInfo { hasNextPage endCursor }
724 nodes { id awardEmoji { nodes { name user { username } } } }
725 }
726 }
727 }
728}`;
729​
730const RawAwardEmojiNodesSchema = Schema.optional(
731 Schema.NullOr(
732 Schema.Struct({
733 nodes: Schema.optional(
734 Schema.NullOr(
735 Schema.Array(
736 Schema.NullOr(
737 Schema.Struct({
738 name: Schema.optional(Schema.NullOr(Schema.String)),
739 user: Schema.optional(
740 Schema.NullOr(
741 Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) }),
742 ),
743 ),
744 }),
745 ),
746 ),
747 ),
748 ),
749 }),
750 ),
751);
752​
753const RawAwardEmojiPageSchema = Schema.Struct({
754 data: Schema.Struct({
755 currentUser: Schema.optional(
756 Schema.NullOr(Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) })),
757 ),
758 project: Schema.NullOr(
759 Schema.Struct({
760 mergeRequest: Schema.NullOr(
761 Schema.Struct({
762 awardEmoji: RawAwardEmojiNodesSchema,
763 notes: Schema.optional(
764 Schema.NullOr(
765 Schema.Struct({
766 pageInfo: Schema.optional(
767 Schema.Struct({
768 hasNextPage: Schema.optional(Schema.Boolean),
769 endCursor: Schema.optional(Schema.NullOr(Schema.String)),
770 }),
771 ),
772 nodes: Schema.Array(
773 Schema.NullOr(
774 Schema.Struct({
775 id: Schema.optional(Schema.NullOr(Schema.String)),
776 awardEmoji: RawAwardEmojiNodesSchema,
777 }),
778 ),
779 ),
780 }),
781 ),
782 ),
783 }),
784 ),
785 }),
786 ),
787 }),
788});
789​
790const decodeAwardEmojiPage = decodeJsonResult(RawAwardEmojiPageSchema);
791​
792function toReactions(
793 nodes: Schema.Schema.Type<typeof RawAwardEmojiNodesSchema>,
794 viewer: string | null,
795): ReadonlyArray<PullRequestReaction> {
796 const normalizedViewer = viewer?.toLowerCase() ?? null;
797 const groups = new Map<
798 PullRequestReactionContent,
799 { count: number; actors: string[]; viewer: boolean }
800 >();
801 for (const node of nodes?.nodes ?? []) {
802 const content = CONTENT_BY_GITLAB_AWARD[trimmed(node?.name)?.toLowerCase() ?? ""];
803 if (content === undefined) continue;
804 const username = trimmed(node?.user?.username);
805 if (username === null) continue;
806 const group = groups.get(content) ?? { count: 0, actors: [], viewer: false };
807 group.count++;
808 if (normalizedViewer !== null && username.toLowerCase() === normalizedViewer) {
809 group.viewer = true;
810 } else {
811 group.actors.push(username);
812 }
813 groups.set(content, group);
814 }
815 return [...groups].flatMap(([content, group]) =>
816 group.count === 0
817 ? []
818 : [{ content, count: group.count, actors: group.actors, viewerHasReacted: group.viewer }],
819 );
821​
822function noteIdOf(gid: string | null | undefined): string | null {
823 const id = trimmed(gid)?.split("/").at(-1);
824 return id !== undefined && /^\d+$/.test(id) ? id : null;
826​
827export interface GitLabAwardEmojiPage {
828 readonly reactions: ReadonlyArray<PullRequestReaction>;
829 readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>;
830 readonly nextCursor: string | null;
832​
833export function decodeAwardEmojiJson(
834 raw: string,
835): Result.Result<GitLabAwardEmojiPage, DecodeFailure> {
836 const decoded = decodeAwardEmojiPage(raw);
837 if (!Result.isSuccess(decoded)) {
838 return Result.fail(decoded.failure);
839 }
840 const data = decoded.success.data;
841 const viewer = trimmed(data.currentUser?.username);
842 const mergeRequest = data.project?.mergeRequest;
843 const reactionsByNoteId = new Map<string, ReadonlyArray<PullRequestReaction>>();
844 for (const node of mergeRequest?.notes?.nodes ?? []) {
845 const id = noteIdOf(node?.id);
846 if (id === null) continue;
847 const reactions = toReactions(node?.awardEmoji, viewer);
848 if (reactions.length > 0) reactionsByNoteId.set(id, reactions);
849 }
850 const pageInfo = mergeRequest?.notes?.pageInfo;
851 return Result.succeed({
852 reactions: toReactions(mergeRequest?.awardEmoji, viewer),
853 reactionsByNoteId,
854 nextCursor: pageInfo?.hasNextPage === true ? (trimmed(pageInfo.endCursor) ?? null) : null,
855 });
857​
858const RawAwardSchema = Schema.Struct({
859 id: Schema.Int,
860 name: Schema.optional(Schema.NullOr(Schema.String)),
861 user: Schema.optional(
862 Schema.NullOr(Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) })),
863 ),
864});
865​
866const decodeAward = Schema.decodeUnknownExit(RawAwardSchema);
867​
868export function decodeOwnAwardIdJson(
869 raw: string,
870 input: { readonly content: PullRequestReactionContent; readonly viewer: string },
871): Result.Result<number | null, DecodeFailure> {
872 const decoded = decodeUnknownList(raw);
873 if (!Result.isSuccess(decoded)) {
874 return Result.fail(decoded.failure);
875 }
876 const name = gitLabAwardName(input.content);
877 for (const entry of decoded.success) {
878 const award = decodeAward(entry);
879 if (Exit.isFailure(award)) continue;
880 const value = award.value;
881 if (trimmed(value.name)?.toLowerCase() !== name) continue;
882 if (trimmed(value.user?.username) !== input.viewer) continue;
883 return Result.succeed(value.id);
884 }
885 return Result.succeed(null);
887​
888export const REPOSITORY_BLOBS_GRAPHQL_QUERY = `query($fullPath: ID!, $ref: String!, $paths: [String!]!) {
889 project(fullPath: $fullPath) {
890 repository {
891 blobs(ref: $ref, paths: $paths) {
892 nodes { path oid }
893 }
894 }
895 }
896}`;
897​
898const RawRepositoryBlobsSchema = Schema.Struct({
899 data: Schema.Struct({
900 project: Schema.NullOr(
901 Schema.Struct({
902 repository: Schema.optional(
903 Schema.NullOr(
904 Schema.Struct({
905 blobs: Schema.optional(
906 Schema.NullOr(
907 Schema.Struct({
908 nodes: Schema.optional(
909 Schema.NullOr(
910 Schema.Array(
911 Schema.NullOr(
912 Schema.Struct({
913 path: Schema.optional(Schema.NullOr(Schema.String)),
914 oid: Schema.optional(Schema.NullOr(Schema.String)),
915 }),
916 ),
917 ),
918 ),
919 ),
920 }),
921 ),
922 ),
923 }),
924 ),
925 ),
926 }),
927 ),
928 }),
929});
930​
931const decodeRepositoryBlobs = decodeJsonResult(RawRepositoryBlobsSchema);
932​
933/**
934 * Blob ids by path, or null where GitLab did not answer the query at all (a project the token
935 * cannot see, or a repository with no blobs connection). That case must be told apart from an
936 * empty answer: read as "the revision has none of these files", it would report every cleared
937 * file as changed again.
938 */
939export function decodeRepositoryBlobsJson(
940 raw: string,
941): Result.Result<ReadonlyMap<string, string> | null, DecodeFailure> {
942 const decoded = decodeRepositoryBlobs(raw);
943 if (!Result.isSuccess(decoded)) {
944 return Result.fail(decoded.failure);
945 }
946 const nodes = decoded.success.data.project?.repository?.blobs?.nodes;
947 if (nodes === undefined || nodes === null) return Result.succeed(null);
948 const blobs = new Map<string, string>();
949 for (const node of nodes) {
950 // Not trimmed, unlike everything else read out of this payload: a leading or trailing space
951 // is a legal part of a file's name, and trimming it would key this map under a name the
952 // caller's asked-for path never matches.
953 const path = node?.path;
954 const oid = trimmed(node?.oid);
955 if (path === undefined || path === null || path.length === 0 || oid === null) continue;
956 blobs.set(path, oid);
957 }
958 return Result.succeed(blobs);