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

gitLabMergeRequestJson.ts

948 lines31.8 KB

1import { trimOptionalString as trimmed } from "@t3tools/source-control-core/server/pullRequestUtils";
2import * as Cause from "effect/Cause";
3import * as Exit from "effect/Exit";
4import * as Result from "effect/Result";
5import * as Schema from "effect/Schema";
6import type {
7 PullRequestActor,
8 PullRequestCheck,
9 PullRequestCheckStatus,
10 PullRequestComment,
11 PullRequestCommit,
12 PullRequestLabel,
13 PullRequestMergeability,
14 PullRequestMergeCapabilities,
15 PullRequestMergeMethod,
16 PullRequestReaction,
17 PullRequestReactionContent,
18 PullRequestReviewThread,
19 PullRequestReviewerCandidate,
20 PullRequestState,
21} from "@t3tools/contracts";
22import { TrimmedNonEmptyString } from "@t3tools/contracts";
23import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath";
24import { decodeJsonResult } from "@t3tools/shared/schemaJson";
25​
26/** Unknown pipeline or merge status values must not fail the whole payload. */
27const RawUserSchema = Schema.Struct({
28 id: Schema.optional(Schema.Int),
29 username: Schema.String,
30 name: Schema.optional(Schema.NullOr(Schema.String)),
31 avatar_url: Schema.optional(Schema.NullOr(Schema.String)),
32});
33​
34const RawPipelineSchema = Schema.Struct({
35 status: Schema.optional(Schema.NullOr(Schema.String)),
36 web_url: Schema.optional(Schema.NullOr(Schema.String)),
37 source: Schema.optional(Schema.NullOr(Schema.String)),
38});
39​
40const RawMergeRequestSchema = Schema.Struct({
41 iid: Schema.Int,
42 title: Schema.String,
43 web_url: Schema.String,
44 description: Schema.optional(Schema.NullOr(Schema.String)),
45 author: Schema.optional(Schema.NullOr(RawUserSchema)),
46 source_branch: Schema.String,
47 target_branch: Schema.String,
48 sha: Schema.optional(Schema.NullOr(Schema.String)),
49 state: Schema.optional(Schema.NullOr(Schema.String)),
50 draft: Schema.optional(Schema.Boolean),
51 work_in_progress: Schema.optional(Schema.Boolean),
52 merge_status: Schema.optional(Schema.NullOr(Schema.String)),
53 has_conflicts: Schema.optional(Schema.NullOr(Schema.Boolean)),
54 created_at: Schema.String,
55 updated_at: Schema.String,
56 merged_at: Schema.optional(Schema.NullOr(Schema.String)),
57 closed_at: Schema.optional(Schema.NullOr(Schema.String)),
58 reviewers: Schema.optional(Schema.NullOr(Schema.Array(RawUserSchema))),
59 labels: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))),
60 // GitLab reports "1000+" past its counting limit.
61 changes_count: Schema.optional(Schema.NullOr(Schema.String)),
62 head_pipeline: Schema.optional(Schema.NullOr(RawPipelineSchema)),
63 user: Schema.optional(
64 Schema.NullOr(Schema.Struct({ can_merge: Schema.optional(Schema.Boolean) })),
65 ),
66 merge_when_pipeline_succeeds: Schema.optional(Schema.NullOr(Schema.Boolean)),
67 auto_merge_enabled: Schema.optional(Schema.NullOr(Schema.Boolean)),
68 squash_on_merge: Schema.optional(Schema.NullOr(Schema.Boolean)),
69 squash: Schema.optional(Schema.NullOr(Schema.Boolean)),
70 /** Only detail reads with include_diverged_commits_count return this expensive count. */
71 diverged_commits_count: Schema.optional(Schema.NullOr(Schema.Int)),
72});
73​
74const RawNoteSchema = Schema.Struct({
75 id: Schema.Int,
76 body: Schema.optional(Schema.NullOr(Schema.String)),
77 author: Schema.optional(Schema.NullOr(RawUserSchema)),
78 created_at: Schema.String,
79 system: Schema.optional(Schema.Boolean),
80 type: Schema.optional(Schema.NullOr(Schema.String)),
81 position: Schema.optional(
82 Schema.NullOr(
83 Schema.Struct({
84 new_path: Schema.optional(Schema.NullOr(Schema.String)),
85 old_path: Schema.optional(Schema.NullOr(Schema.String)),
86 }),
87 ),
88 ),
89});
90​
91const RawDiscussionNoteSchema = Schema.Struct({
92 id: Schema.Int,
93 body: Schema.optional(Schema.NullOr(Schema.String)),
94 author: Schema.optional(Schema.NullOr(RawUserSchema)),
95 created_at: Schema.String,
96 system: Schema.optional(Schema.Boolean),
97 resolvable: Schema.optional(Schema.Boolean),
98 resolved: Schema.optional(Schema.NullOr(Schema.Boolean)),
99 position: Schema.optional(
100 Schema.NullOr(
101 Schema.Struct({
102 position_type: Schema.optional(Schema.NullOr(Schema.String)),
103 new_path: Schema.optional(Schema.NullOr(Schema.String)),
104 old_path: Schema.optional(Schema.NullOr(Schema.String)),
105 new_line: Schema.optional(Schema.NullOr(Schema.Int)),
106 old_line: Schema.optional(Schema.NullOr(Schema.Int)),
107 }),
108 ),
109 ),
110});
111​
112const RawDiscussionSchema = Schema.Struct({
113 id: Schema.String,
114 notes: Schema.optional(Schema.NullOr(Schema.Array(RawDiscussionNoteSchema))),
115});
116​
117const RawDiffRefsSchema = Schema.Struct({
118 diff_refs: Schema.optional(
119 Schema.NullOr(
120 Schema.Struct({
121 base_sha: Schema.String,
122 head_sha: Schema.String,
123 start_sha: Schema.String,
124 }),
125 ),
126 ),
127});
128​
129const RawCommitSchema = Schema.Struct({
130 id: TrimmedNonEmptyString,
131 title: Schema.optional(Schema.NullOr(Schema.String)),
132 committed_date: Schema.optional(Schema.NullOr(Schema.String)),
133 created_at: Schema.optional(Schema.NullOr(Schema.String)),
134 parent_ids: Schema.optional(Schema.Array(Schema.String)),
135 author_name: Schema.optional(Schema.NullOr(Schema.String)),
136 author_email: Schema.optional(Schema.NullOr(Schema.String)),
137 stats: Schema.optional(
138 Schema.NullOr(
139 Schema.Struct({
140 additions: Schema.optional(Schema.Int),
141 deletions: Schema.optional(Schema.Int),
142 }),
143 ),
144 ),
145});
146​
147const RawDiffSchema = Schema.Struct({
148 old_path: Schema.String,
149 new_path: Schema.String,
150 a_mode: Schema.optional(Schema.NullOr(Schema.String)),
151 b_mode: Schema.optional(Schema.NullOr(Schema.String)),
152 new_file: Schema.optional(Schema.Boolean),
153 renamed_file: Schema.optional(Schema.Boolean),
154 deleted_file: Schema.optional(Schema.Boolean),
155 diff: Schema.optional(Schema.NullOr(Schema.String)),
156 too_large: Schema.optional(Schema.NullOr(Schema.Boolean)),
157 collapsed: Schema.optional(Schema.NullOr(Schema.Boolean)),
158});
159​
160const RawViewerSchema = Schema.Struct({
161 username: Schema.optional(Schema.NullOr(Schema.String)),
162});
163​
164const RawProjectMergeSettingsSchema = Schema.Struct({
165 merge_method: Schema.optional(Schema.NullOr(Schema.String)),
166 squash_option: Schema.optional(Schema.NullOr(Schema.String)),
167});
168​
169export interface GitLabMergeRequestListItem {
170 readonly number: number;
171 readonly title: string;
172 readonly url: string;
173 readonly author: PullRequestActor | null;
174 readonly headBranch: string;
175 readonly baseBranch: string;
176 readonly state: PullRequestState;
177 readonly isDraft: boolean;
178 readonly mergeability: PullRequestMergeability;
179 readonly additions: number;
180 readonly deletions: number;
181 readonly createdAt: string;
182 readonly updatedAt: string;
183 readonly reviewRequestLogins: ReadonlyArray<string>;
184 readonly labels: ReadonlyArray<PullRequestLabel>;
186​
187export interface GitLabMergeRequestDetail extends GitLabMergeRequestListItem {
188 readonly body: string;
189 readonly changedFiles: number;
190 readonly mergedAt: string | null;
191 readonly closedAt: string | null;
192 readonly reviewers: ReadonlyArray<PullRequestActor>;
193 readonly checks: ReadonlyArray<PullRequestCheck>;
194 readonly viewerCanMerge: boolean;
195 readonly reviewerIds: ReadonlyArray<number>;
196 readonly autoMergeEnabled?: boolean;
197 readonly autoMergeMethod?: PullRequestMergeMethod;
198 /** Absent means not counted, not up to date. */
199 readonly divergedCommits?: number;
200 readonly headSha?: string;
202​
203function toActor(raw: Schema.Schema.Type<typeof RawUserSchema> | null | undefined) {
204 const login = trimmed(raw?.username);
205 return login === null
206 ? null
207 : { login, name: trimmed(raw?.name), avatarUrl: trimmed(raw?.avatar_url) };
209​
210function toState(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): PullRequestState {
211 if (trimmed(raw.merged_at) !== null) return "merged";
212 switch (raw.state?.trim().toLowerCase()) {
213 case "merged":
214 return "merged";
215 case "closed":
216 return "closed";
217 default:
218 return "open";
219 }
221​
222function toMergeability(
223 raw: Schema.Schema.Type<typeof RawMergeRequestSchema>,
224): PullRequestMergeability {
225 if (raw.has_conflicts === true) return "conflicting";
226 switch (raw.merge_status?.trim().toLowerCase()) {
227 case "can_be_merged":
228 return "mergeable";
229 case "cannot_be_merged":
230 return "conflicting";
231 default:
232 return "unknown";
233 }
235​
236function toLabels(raw: ReadonlyArray<string> | null | undefined): ReadonlyArray<PullRequestLabel> {
237 return (raw ?? []).flatMap((label) => {
238 const name = trimmed(label);
239 return name === null ? [] : [{ name, color: null }];
240 });
242​
243function toChangedFiles(value: string | null | undefined): number {
244 const parsed = Number.parseInt(value?.trim() ?? "", 10);
245 return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
247​
248function toPipelineStatus(value: string | null | undefined): PullRequestCheckStatus {
249 switch (value?.trim().toLowerCase()) {
250 case "success":
251 return "success";
252 case "failed":
253 return "failure";
254 case "canceled":
255 case "cancelling":
256 return "cancelled";
257 case "skipped":
258 return "skipped";
259 case "manual":
260 case "scheduled":
261 return "neutral";
262 default:
263 return "pending";
264 }
266​
267function toChecks(
268 raw: Schema.Schema.Type<typeof RawMergeRequestSchema>,
269): ReadonlyArray<PullRequestCheck> {
270 const pipeline = raw.head_pipeline;
271 if (!pipeline) return [];
272 return [
273 {
274 name: "Pipeline",
275 status: toPipelineStatus(pipeline.status),
276 description: trimmed(pipeline.source),
277 url: trimmed(pipeline.web_url),
278 },
279 ];
281​
282function toListItem(
283 raw: Schema.Schema.Type<typeof RawMergeRequestSchema>,
284): GitLabMergeRequestListItem {
285 return {
286 number: raw.iid,
287 title: raw.title,
288 url: raw.web_url,
289 author: toActor(raw.author),
290 headBranch: raw.source_branch,
291 baseBranch: raw.target_branch,
292 state: toState(raw),
293 isDraft: raw.draft ?? raw.work_in_progress ?? false,
294 mergeability: toMergeability(raw),
295 additions: 0,
296 deletions: 0,
297 createdAt: raw.created_at,
298 updatedAt: raw.updated_at,
299 reviewRequestLogins: (raw.reviewers ?? []).flatMap((reviewer) => {
300 const login = trimmed(reviewer.username);
301 return login === null ? [] : [login];
302 }),
303 labels: toLabels(raw.labels),
304 };
306​
307function toDetail(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): GitLabMergeRequestDetail {
308 const listItem = toListItem(raw);
309 const headSha = trimmed(raw.sha);
310 const autoMerge =
311 raw.merge_when_pipeline_succeeds == null && raw.auto_merge_enabled == null
312 ? undefined
313 : raw.merge_when_pipeline_succeeds === true || raw.auto_merge_enabled === true;
314 return {
315 ...listItem,
316 body: raw.description ?? "",
317 changedFiles: toChangedFiles(raw.changes_count),
318 mergedAt: trimmed(raw.merged_at),
319 closedAt: trimmed(raw.closed_at),
320 reviewers: (raw.reviewers ?? []).flatMap((reviewer) => {
321 const actor = toActor(reviewer);
322 return actor === null ? [] : [actor];
323 }),
324 checks: toChecks(raw),
325 viewerCanMerge: raw.user?.can_merge !== false,
326 reviewerIds: (raw.reviewers ?? []).flatMap((reviewer) =>
327 reviewer.id === undefined ? [] : [reviewer.id],
328 ),
329 ...(autoMerge === undefined ? {} : { autoMergeEnabled: autoMerge }),
330 ...(autoMerge === true && raw.squash_on_merge === true
331 ? { autoMergeMethod: "squash" as const }
332 : {}),
333 ...(raw.diverged_commits_count == null ? {} : { divergedCommits: raw.diverged_commits_count }),
334 ...(headSha === null ? {} : { headSha }),
335 };
337​
338const decodeUnknownList = decodeJsonResult(Schema.Array(Schema.Unknown));
339const decodeMergeRequestEntry = Schema.decodeUnknownExit(RawMergeRequestSchema);
340const decodeMergeRequest = decodeJsonResult(RawMergeRequestSchema);
341const decodeNoteEntry = Schema.decodeUnknownExit(RawNoteSchema);
342const decodeUserEntry = Schema.decodeUnknownExit(RawUserSchema);
343const decodeCommitEntry = Schema.decodeUnknownExit(RawCommitSchema);
344const decodeCommit = decodeJsonResult(RawCommitSchema);
345const decodeMergeRequestChanges = decodeJsonResult(
346 Schema.Struct({
347 changes: Schema.Array(Schema.Unknown),
348 overflow: Schema.optional(Schema.Boolean),
349 changes_count: Schema.optional(Schema.NullOr(Schema.String)),
350 }),
351);
352const decodeDiffEntry = Schema.decodeUnknownExit(RawDiffSchema);
353const decodeDiscussionEntry = Schema.decodeUnknownExit(RawDiscussionSchema);
354const decodeDiffRefs = decodeJsonResult(RawDiffRefsSchema);
355const decodeViewer = decodeJsonResult(RawViewerSchema);
356const decodeProjectMergeSettings = decodeJsonResult(RawProjectMergeSettingsSchema);
357​
358type DecodeFailure = Cause.Cause<Schema.SchemaError>;
359​
360export interface GitLabProjectUsers {
361 readonly candidates: ReadonlyArray<PullRequestReviewerCandidate>;
362 /** Count before decoding to avoid ending pagination on skipped rows. */
363 readonly rawCount: number;
365​
366export interface GitLabMergeRequestListBatch {
367 readonly items: ReadonlyArray<GitLabMergeRequestListItem>;
368 readonly rawIndexes: ReadonlyArray<number>;
369 readonly rawCount: number;
371​
372export function decodeMergeRequestListJson(
373 raw: string,
374): Result.Result<GitLabMergeRequestListBatch, DecodeFailure> {
375 const decoded = decodeUnknownList(raw);
376 if (!Result.isSuccess(decoded)) {
377 return Result.fail(decoded.failure);
378 }
379 const items: GitLabMergeRequestListItem[] = [];
380 const rawIndexes: number[] = [];
381 for (const [rawIndex, entry] of decoded.success.entries()) {
382 const item = decodeMergeRequestEntry(entry);
383 if (Exit.isSuccess(item)) {
384 items.push(toListItem(item.value));
385 rawIndexes.push(rawIndex);
386 }
387 }
388 return Result.succeed({ items, rawIndexes, rawCount: decoded.success.length });
390​
391export function decodeMergeRequestDetailJson(
392 raw: string,
393): Result.Result<GitLabMergeRequestDetail, DecodeFailure> {
394 const decoded = decodeMergeRequest(raw);
395 return Result.isSuccess(decoded)
396 ? Result.succeed(toDetail(decoded.success))
397 : Result.fail(decoded.failure);
399​
400export function decodeViewerJson(raw: string): Result.Result<string | null, DecodeFailure> {
401 const decoded = decodeViewer(raw);
402 return Result.isSuccess(decoded)
403 ? Result.succeed(trimmed(decoded.success.username))
404 : Result.fail(decoded.failure);
406​
407export function decodeProjectUsersJson(
408 raw: string,
409): Result.Result<GitLabProjectUsers, DecodeFailure> {
410 const decoded = decodeUnknownList(raw);
411 if (!Result.isSuccess(decoded)) {
412 return Result.fail(decoded.failure);
413 }
414 const candidates: PullRequestReviewerCandidate[] = [];
415 for (const entry of decoded.success) {
416 const user = decodeUserEntry(entry);
417 if (Exit.isFailure(user) || user.value.id === undefined) continue;
418 const actor = toActor(user.value);
419 if (actor === null) continue;
420 candidates.push({
421 ...actor,
422 id: String(user.value.id),
423 kind: "user",
424 isRequested: false,
425 });
426 }
427 return Result.succeed({ candidates, rawCount: decoded.success.length });
429​
430const RawLabelSchema = Schema.Struct({
431 name: Schema.String,
432 color: Schema.optional(Schema.NullOr(Schema.String)),
433});
434const decodeLabelEntry = Schema.decodeUnknownExit(RawLabelSchema);
435​
436export interface GitLabProjectLabels {
437 readonly labels: ReadonlyArray<PullRequestLabel>;
438 readonly rawCount: number;
440​
441export function decodeProjectLabelsJson(
442 raw: string,
443): Result.Result<GitLabProjectLabels, DecodeFailure> {
444 const decoded = decodeUnknownList(raw);
445 if (!Result.isSuccess(decoded)) {
446 return Result.fail(decoded.failure);
447 }
448 const labels: PullRequestLabel[] = [];
449 for (const entry of decoded.success) {
450 const label = decodeLabelEntry(entry);
451 if (Exit.isFailure(label)) continue;
452 const name = trimmed(label.value.name);
453 if (name !== null) labels.push({ name, color: trimmed(label.value.color) });
454 }
455 return Result.succeed({ labels, rawCount: decoded.success.length });
457​
458export function decodeProjectMergeCapabilitiesJson(
459 raw: string,
460): Result.Result<PullRequestMergeCapabilities, DecodeFailure> {
461 const decoded = decodeProjectMergeSettings(raw);
462 if (!Result.isSuccess(decoded)) {
463 return Result.fail(decoded.failure);
464 }
465 const mergeMethod = decoded.success.merge_method?.trim().toLowerCase();
466 const squashOption = decoded.success.squash_option?.trim().toLowerCase();
467 return Result.succeed({
468 merge: mergeMethod === "merge",
469 rebase: mergeMethod === "rebase_merge" || mergeMethod === "ff",
470 squash:
471 squashOption === "always" || squashOption === "default_on" || squashOption === "default_off",
472 });
474​
475export interface GitLabDiffRefs {
476 readonly baseSha: string;
477 readonly headSha: string;
478 readonly startSha: string;
480​
481export interface GitLabDiscussions {
482 readonly threads: ReadonlyArray<PullRequestReviewThread>;
483 readonly rawCount: number;
485​
486export function decodeDiscussionsJson(
487 raw: string,
488): Result.Result<GitLabDiscussions, DecodeFailure> {
489 const decoded = decodeUnknownList(raw);
490 if (!Result.isSuccess(decoded)) {
491 return Result.fail(decoded.failure);
492 }
493 const threads: PullRequestReviewThread[] = [];
494 for (const entry of decoded.success) {
495 const discussion = decodeDiscussionEntry(entry);
496 if (!Exit.isSuccess(discussion)) continue;
497 const notes = (discussion.value.notes ?? []).filter((note) => note.system !== true);
498 const root = notes[0];
499 const position = root?.position;
500 if (root === undefined || !position || position.position_type !== "text") continue;
501 const side = position.new_line === null || position.new_line === undefined ? "left" : "right";
502 const path = trimmed(side === "left" ? position.old_path : position.new_path);
503 const line = side === "left" ? position.old_line : position.new_line;
504 if (path === null) continue;
505 threads.push({
506 id: discussion.value.id,
507 path,
508 line: typeof line === "number" && line > 0 ? line : null,
509 side,
510 isResolved: root.resolved === true,
511 isOutdated: false,
512 comments: notes.map((note) => ({
513 id: String(note.id),
514 author: toActor(note.author),
515 body: note.body ?? "",
516 createdAt: note.created_at,
517 url: null,
518 })),
519 });
520 }
521 return Result.succeed({ threads, rawCount: decoded.success.length });
523​
524export function decodeDiffRefsJson(
525 raw: string,
526): Result.Result<GitLabDiffRefs | null, DecodeFailure> {
527 const decoded = decodeDiffRefs(raw);
528 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
529 const refs = decoded.success.diff_refs;
530 return Result.succeed(
531 refs ? { baseSha: refs.base_sha, headSha: refs.head_sha, startSha: refs.start_sha } : null,
532 );
534​
535export function decodeNotesJson(
536 raw: string,
537): Result.Result<
538 { readonly comments: ReadonlyArray<PullRequestComment>; readonly rawCount: number },
539 DecodeFailure
540> {
541 const decoded = decodeUnknownList(raw);
542 if (!Result.isSuccess(decoded)) {
543 return Result.fail(decoded.failure);
544 }
545 const comments: PullRequestComment[] = [];
546 for (const entry of decoded.success) {
547 const note = decodeNoteEntry(entry);
548 if (Exit.isFailure(note)) continue;
549 const value = note.value;
550 if (value.system === true) continue;
551 const body = value.body ?? "";
552 if (body.trim().length === 0) continue;
553 const isDiffNote = value.type?.trim() === "DiffNote";
554 comments.push({
555 id: String(value.id),
556 kind: isDiffNote ? "review-comment" : "issue-comment",
557 author: toActor(value.author),
558 body,
559 createdAt: value.created_at,
560 url: null,
561 path: trimmed(value.position?.new_path) ?? trimmed(value.position?.old_path),
562 reviewState: null,
563 });
564 }
565 return Result.succeed({ comments, rawCount: decoded.success.length });
567​
568export function decodeCommitsJson(
569 raw: string,
570): Result.Result<ReadonlyArray<PullRequestCommit>, DecodeFailure> {
571 const decoded = decodeUnknownList(raw);
572 if (!Result.isSuccess(decoded)) {
573 return Result.fail(decoded.failure);
574 }
575 const commits: PullRequestCommit[] = [];
576 for (const entry of decoded.success) {
577 const commit = decodeCommitEntry(entry);
578 if (Exit.isFailure(commit)) continue;
579 const committedDate = trimmed(commit.value.committed_date) ?? trimmed(commit.value.created_at);
580 if (committedDate === null) continue;
581 commits.push({
582 oid: commit.value.id,
583 messageHeadline: commit.value.title ?? "",
584 committedDate,
585 ...(commit.value.stats === null || commit.value.stats === undefined
586 ? {}
587 : {
588 additions: Math.max(0, commit.value.stats.additions ?? 0),
589 deletions: Math.max(0, commit.value.stats.deletions ?? 0),
590 }),
591 authors: (() => {
592 const login = trimmed(commit.value.author_name) ?? trimmed(commit.value.author_email);
593 return login === null
594 ? []
595 : [{ login, name: trimmed(commit.value.author_name), avatarUrl: null }];
596 })(),
597 });
598 }
599 return Result.succeed(commits.toReversed());
601​
602export function decodeCommitDiffRefsJson(
603 raw: string,
604): Result.Result<GitLabDiffRefs | null, DecodeFailure> {
605 const decoded = decodeCommit(raw);
606 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
607 const baseSha = trimmed(decoded.success.parent_ids?.[0]);
608 const headSha = trimmed(decoded.success.id);
609 return Result.succeed(
610 baseSha === null || headSha === null ? null : { baseSha, headSha, startSha: baseSha },
611 );
613​
614function diffHeaderPaths(raw: Schema.Schema.Type<typeof RawDiffSchema>): {
615 readonly from: string;
616 readonly to: string;
617} {
618 return {
619 from: raw.new_file === true ? "/dev/null" : quoteGitPatchPath(`a/${raw.old_path}`),
620 to: raw.deleted_file === true ? "/dev/null" : quoteGitPatchPath(`b/${raw.new_path}`),
621 };
623​
624export interface GitLabMergeRequestPatch {
625 readonly patch: string;
626 readonly truncated: boolean;
627 readonly rawCount: number;
629​
630export function decodeMergeRequestDiffsJson(
631 raw: string,
632): Result.Result<GitLabMergeRequestPatch, DecodeFailure> {
633 const decoded = decodeUnknownList(raw);
634 if (!Result.isSuccess(decoded)) {
635 return Result.fail(decoded.failure);
636 }
637 return Result.succeed(mergeRequestPatch(decoded.success));
639​
640/** Older GitLab instances return all files in a non-paginated merge request wrapper. */
641export function decodeMergeRequestChangesJson(
642 raw: string,
643): Result.Result<GitLabMergeRequestPatch, DecodeFailure> {
644 const decoded = decodeMergeRequestChanges(raw);
645 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
646 const patch = mergeRequestPatch(decoded.success.changes);
647 return Result.succeed({
648 ...patch,
649 truncated:
650 patch.truncated ||
651 decoded.success.overflow === true ||
652 decoded.success.changes_count?.endsWith("+") === true,
653 });
655​
656function mergeRequestPatch(entries: ReadonlyArray<unknown>): GitLabMergeRequestPatch {
657 const sections: string[] = [];
658 let truncated = false;
659 for (const entry of entries) {
660 const file = decodeDiffEntry(entry);
661 if (Exit.isFailure(file)) {
662 truncated = true;
663 continue;
664 }
665 const value = file.value;
666 const hunks = value.diff ?? "";
667 if (hunks.length === 0) {
668 truncated = truncated || value.too_large === true || value.collapsed === true;
669 }
670 const { from, to } = diffHeaderPaths(value);
671 const header = [
672 `diff --git ${quoteGitPatchPath(`a/${value.old_path}`)} ${quoteGitPatchPath(`b/${value.new_path}`)}`,
673 ...(value.new_file === true ? [`new file mode ${value.b_mode ?? "100644"}`] : []),
674 ...(value.deleted_file === true ? [`deleted file mode ${value.a_mode ?? "100644"}`] : []),
675 ...(value.renamed_file === true
676 ? [
677 `rename from ${quoteGitPatchPath(value.old_path)}`,
678 `rename to ${quoteGitPatchPath(value.new_path)}`,
679 ]
680 : []),
681 `--- ${from}`,
682 `+++ ${to}`,
683 ].join("\n");
684 sections.push(hunks.length === 0 ? header : `${header}\n${hunks.replace(/\n?$/, "\n")}`);
685 }
686 return {
687 patch: sections.join("\n"),
688 truncated,
689 rawCount: entries.length,
690 };
692​
693const GITLAB_AWARD_BY_CONTENT: Readonly<Record<PullRequestReactionContent, string>> = {
694 "thumbs-up": "thumbsup",
695 "thumbs-down": "thumbsdown",
696 laugh: "laughing",
697 hooray: "tada",
698 confused: "confused",
699 heart: "heart",
700 rocket: "rocket",
701 eyes: "eyes",
702};
703​
704const CONTENT_BY_GITLAB_AWARD: Readonly<Record<string, PullRequestReactionContent>> =
705 Object.fromEntries(
706 Object.entries(GITLAB_AWARD_BY_CONTENT).map(([content, name]) => [name, content]),
707 ) as Readonly<Record<string, PullRequestReactionContent>>;
708​
709export function gitLabAwardName(content: PullRequestReactionContent): string {
710 return GITLAB_AWARD_BY_CONTENT[content];
712​
713export const AWARD_EMOJI_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!, $cursor: String) {
714 currentUser { username }
715 project(fullPath: $fullPath) {
716 mergeRequest(iid: $iid) {
717 awardEmoji { nodes { name user { username } } }
718 notes(first: 100, after: $cursor) {
719 pageInfo { hasNextPage endCursor }
720 nodes { id awardEmoji { nodes { name user { username } } } }
721 }
722 }
723 }
724}`;
725​
726const RawAwardEmojiNodesSchema = Schema.optional(
727 Schema.NullOr(
728 Schema.Struct({
729 nodes: Schema.optional(
730 Schema.NullOr(
731 Schema.Array(
732 Schema.NullOr(
733 Schema.Struct({
734 name: Schema.optional(Schema.NullOr(Schema.String)),
735 user: Schema.optional(
736 Schema.NullOr(
737 Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) }),
738 ),
739 ),
740 }),
741 ),
742 ),
743 ),
744 ),
745 }),
746 ),
747);
748​
749const RawAwardEmojiPageSchema = Schema.Struct({
750 data: Schema.Struct({
751 currentUser: Schema.optional(
752 Schema.NullOr(Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) })),
753 ),
754 project: Schema.NullOr(
755 Schema.Struct({
756 mergeRequest: Schema.NullOr(
757 Schema.Struct({
758 awardEmoji: RawAwardEmojiNodesSchema,
759 notes: Schema.optional(
760 Schema.NullOr(
761 Schema.Struct({
762 pageInfo: Schema.optional(
763 Schema.Struct({
764 hasNextPage: Schema.optional(Schema.Boolean),
765 endCursor: Schema.optional(Schema.NullOr(Schema.String)),
766 }),
767 ),
768 nodes: Schema.Array(
769 Schema.NullOr(
770 Schema.Struct({
771 id: Schema.optional(Schema.NullOr(Schema.String)),
772 awardEmoji: RawAwardEmojiNodesSchema,
773 }),
774 ),
775 ),
776 }),
777 ),
778 ),
779 }),
780 ),
781 }),
782 ),
783 }),
784});
785​
786const decodeAwardEmojiPage = decodeJsonResult(RawAwardEmojiPageSchema);
787​
788function toReactions(
789 nodes: Schema.Schema.Type<typeof RawAwardEmojiNodesSchema>,
790 viewer: string | null,
791): ReadonlyArray<PullRequestReaction> {
792 const normalizedViewer = viewer?.toLowerCase() ?? null;
793 const groups = new Map<
794 PullRequestReactionContent,
795 { count: number; actors: string[]; viewer: boolean }
796 >();
797 for (const node of nodes?.nodes ?? []) {
798 const content = CONTENT_BY_GITLAB_AWARD[trimmed(node?.name)?.toLowerCase() ?? ""];
799 if (content === undefined) continue;
800 const username = trimmed(node?.user?.username);
801 if (username === null) continue;
802 const group = groups.get(content) ?? { count: 0, actors: [], viewer: false };
803 group.count++;
804 if (normalizedViewer !== null && username.toLowerCase() === normalizedViewer) {
805 group.viewer = true;
806 } else {
807 group.actors.push(username);
808 }
809 groups.set(content, group);
810 }
811 return [...groups].flatMap(([content, group]) =>
812 group.count === 0
813 ? []
814 : [{ content, count: group.count, actors: group.actors, viewerHasReacted: group.viewer }],
815 );
817​
818function noteIdOf(gid: string | null | undefined): string | null {
819 const id = trimmed(gid)?.split("/").at(-1);
820 return id !== undefined && /^\d+$/.test(id) ? id : null;
822​
823export interface GitLabAwardEmojiPage {
824 readonly reactions: ReadonlyArray<PullRequestReaction>;
825 readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>;
826 readonly nextCursor: string | null;
828​
829export function decodeAwardEmojiJson(
830 raw: string,
831): Result.Result<GitLabAwardEmojiPage, DecodeFailure> {
832 const decoded = decodeAwardEmojiPage(raw);
833 if (!Result.isSuccess(decoded)) {
834 return Result.fail(decoded.failure);
835 }
836 const data = decoded.success.data;
837 const viewer = trimmed(data.currentUser?.username);
838 const mergeRequest = data.project?.mergeRequest;
839 const reactionsByNoteId = new Map<string, ReadonlyArray<PullRequestReaction>>();
840 for (const node of mergeRequest?.notes?.nodes ?? []) {
841 const id = noteIdOf(node?.id);
842 if (id === null) continue;
843 const reactions = toReactions(node?.awardEmoji, viewer);
844 if (reactions.length > 0) reactionsByNoteId.set(id, reactions);
845 }
846 const pageInfo = mergeRequest?.notes?.pageInfo;
847 return Result.succeed({
848 reactions: toReactions(mergeRequest?.awardEmoji, viewer),
849 reactionsByNoteId,
850 nextCursor: pageInfo?.hasNextPage === true ? (trimmed(pageInfo.endCursor) ?? null) : null,
851 });
853​
854const RawAwardSchema = Schema.Struct({
855 id: Schema.Int,
856 name: Schema.optional(Schema.NullOr(Schema.String)),
857 user: Schema.optional(
858 Schema.NullOr(Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) })),
859 ),
860});
861​
862const decodeAward = Schema.decodeUnknownExit(RawAwardSchema);
863​
864export function decodeOwnAwardIdJson(
865 raw: string,
866 input: { readonly content: PullRequestReactionContent; readonly viewer: string },
867): Result.Result<number | null, DecodeFailure> {
868 const decoded = decodeUnknownList(raw);
869 if (!Result.isSuccess(decoded)) {
870 return Result.fail(decoded.failure);
871 }
872 const name = gitLabAwardName(input.content);
873 for (const entry of decoded.success) {
874 const award = decodeAward(entry);
875 if (Exit.isFailure(award)) continue;
876 const value = award.value;
877 if (trimmed(value.name)?.toLowerCase() !== name) continue;
878 if (trimmed(value.user?.username) !== input.viewer) continue;
879 return Result.succeed(value.id);
880 }
881 return Result.succeed(null);
883​
884export const REPOSITORY_BLOBS_GRAPHQL_QUERY = `query($fullPath: ID!, $ref: String!, $paths: [String!]!) {
885 project(fullPath: $fullPath) {
886 repository {
887 blobs(ref: $ref, paths: $paths) {
888 nodes { path oid }
889 }
890 }
891 }
892}`;
893​
894const RawRepositoryBlobsSchema = Schema.Struct({
895 data: Schema.Struct({
896 project: Schema.NullOr(
897 Schema.Struct({
898 repository: Schema.optional(
899 Schema.NullOr(
900 Schema.Struct({
901 blobs: Schema.optional(
902 Schema.NullOr(
903 Schema.Struct({
904 nodes: Schema.optional(
905 Schema.NullOr(
906 Schema.Array(
907 Schema.NullOr(
908 Schema.Struct({
909 path: Schema.optional(Schema.NullOr(Schema.String)),
910 oid: Schema.optional(Schema.NullOr(Schema.String)),
911 }),
912 ),
913 ),
914 ),
915 ),
916 }),
917 ),
918 ),
919 }),
920 ),
921 ),
922 }),
923 ),
924 }),
925});
926​
927const decodeRepositoryBlobs = decodeJsonResult(RawRepositoryBlobsSchema);
928​
929/** Null means unknown, not deleted; preserve viewed marks. */
930export function decodeRepositoryBlobsJson(
931 raw: string,
932): Result.Result<ReadonlyMap<string, string> | null, DecodeFailure> {
933 const decoded = decodeRepositoryBlobs(raw);
934 if (!Result.isSuccess(decoded)) {
935 return Result.fail(decoded.failure);
936 }
937 const nodes = decoded.success.data.project?.repository?.blobs?.nodes;
938 if (nodes === undefined || nodes === null) return Result.succeed(null);
939 const blobs = new Map<string, string>();
940 for (const node of nodes) {
941 // Preserve path whitespace so blob-map keys match the caller's exact filenames.
942 const path = node?.path;
943 const oid = trimmed(node?.oid);
944 if (path === undefined || path === null || path.length === 0 || oid === null) continue;
945 blobs.set(path, oid);
946 }
947 return Result.succeed(blobs);