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

gitLabMergeRequestJson.ts

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