Open History to see the last commit
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>;
191}
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;
210}
211
212function trimmed(value: string | null | undefined): string | null {
213 const text = value?.trim() ?? "";
214 return text.length > 0 ? text : null;
215}
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) };
222}
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 }
234}
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 }
248}
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 });
255}
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;
260}
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 }
279}
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 ];
294}
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 };
319}
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 };
350}
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 decodeDiffEntry = Schema.decodeUnknownExit(RawDiffSchema);
360const decodeDiscussionEntry = Schema.decodeUnknownExit(RawDiscussionSchema);
361const decodeDiffRefs = decodeJsonResult(RawDiffRefsSchema);
362const decodeViewer = decodeJsonResult(RawViewerSchema);
363const decodeProjectMergeSettings = decodeJsonResult(RawProjectMergeSettingsSchema);
364
365type DecodeFailure = Cause.Cause<Schema.SchemaError>;
366
367export interface GitLabProjectUsers {
368 readonly candidates: ReadonlyArray<PullRequestReviewerCandidate>;
369 /** Rows GitLab returned, counted before decoding, so a skipped row cannot hide a next page. */
370 readonly rawCount: number;
371}
372
373export interface GitLabMergeRequestListBatch {
374 readonly items: ReadonlyArray<GitLabMergeRequestListItem>;
375 readonly rawIndexes: ReadonlyArray<number>;
376 readonly rawCount: number;
377}
378
379export function decodeMergeRequestListJson(
380 raw: string,
381): Result.Result<GitLabMergeRequestListBatch, DecodeFailure> {
382 const decoded = decodeUnknownList(raw);
383 if (!Result.isSuccess(decoded)) {
384 return Result.fail(decoded.failure);
385 }
386 const items: GitLabMergeRequestListItem[] = [];
387 const rawIndexes: number[] = [];
388 for (const [rawIndex, entry] of decoded.success.entries()) {
389 const item = decodeMergeRequestEntry(entry);
390 if (Exit.isSuccess(item)) {
391 items.push(toListItem(item.value));
392 rawIndexes.push(rawIndex);
393 }
394 }
395 return Result.succeed({ items, rawIndexes, rawCount: decoded.success.length });
396}
397
398export function decodeMergeRequestDetailJson(
399 raw: string,
400): Result.Result<GitLabMergeRequestDetail, DecodeFailure> {
401 const decoded = decodeMergeRequest(raw);
402 return Result.isSuccess(decoded)
403 ? Result.succeed(toDetail(decoded.success))
404 : Result.fail(decoded.failure);
405}
406
407export function decodeViewerJson(raw: string): Result.Result<string | null, DecodeFailure> {
408 const decoded = decodeViewer(raw);
409 return Result.isSuccess(decoded)
410 ? Result.succeed(trimmed(decoded.success.username))
411 : Result.fail(decoded.failure);
412}
413
414export function decodeProjectUsersJson(
415 raw: string,
416): Result.Result<GitLabProjectUsers, DecodeFailure> {
417 const decoded = decodeUnknownList(raw);
418 if (!Result.isSuccess(decoded)) {
419 return Result.fail(decoded.failure);
420 }
421 const candidates: PullRequestReviewerCandidate[] = [];
422 for (const entry of decoded.success) {
423 const user = decodeUserEntry(entry);
424 if (Exit.isFailure(user) || user.value.id === undefined) continue;
425 const actor = toActor(user.value);
426 if (actor === null) continue;
427 candidates.push({
428 ...actor,
429 id: String(user.value.id),
430 kind: "user",
431 isRequested: false,
432 });
433 }
434 return Result.succeed({ candidates, rawCount: decoded.success.length });
435}
436
437export function decodeProjectMergeCapabilitiesJson(
438 raw: string,
439): Result.Result<PullRequestMergeCapabilities, DecodeFailure> {
440 const decoded = decodeProjectMergeSettings(raw);
441 if (!Result.isSuccess(decoded)) {
442 return Result.fail(decoded.failure);
443 }
444 const mergeMethod = decoded.success.merge_method?.trim().toLowerCase();
445 const squashOption = decoded.success.squash_option?.trim().toLowerCase();
446 return Result.succeed({
447 merge: mergeMethod === "merge",
448 rebase: mergeMethod === "rebase_merge" || mergeMethod === "ff",
449 squash:
450 squashOption === "always" || squashOption === "default_on" || squashOption === "default_off",
451 });
452}
453
454export interface GitLabDiffRefs {
455 readonly baseSha: string;
456 readonly headSha: string;
457 readonly startSha: string;
458}
459
460export interface GitLabDiscussions {
461 readonly threads: ReadonlyArray<PullRequestReviewThread>;
462 readonly rawCount: number;
463}
464
465export function decodeDiscussionsJson(
466 raw: string,
467): Result.Result<GitLabDiscussions, DecodeFailure> {
468 const decoded = decodeUnknownList(raw);
469 if (!Result.isSuccess(decoded)) {
470 return Result.fail(decoded.failure);
471 }
472 const threads: PullRequestReviewThread[] = [];
473 for (const entry of decoded.success) {
474 const discussion = decodeDiscussionEntry(entry);
475 if (!Exit.isSuccess(discussion)) continue;
476 const notes = (discussion.value.notes ?? []).filter((note) => note.system !== true);
477 const root = notes[0];
478 const position = root?.position;
479 if (root === undefined || !position || position.position_type !== "text") continue;
480 const side = position.new_line === null || position.new_line === undefined ? "left" : "right";
481 const path = trimmed(side === "left" ? position.old_path : position.new_path);
482 const line = side === "left" ? position.old_line : position.new_line;
483 if (path === null) continue;
484 threads.push({
485 id: discussion.value.id,
486 path,
487 line: typeof line === "number" && line > 0 ? line : null,
488 side,
489 isResolved: root.resolved === true,
490 isOutdated: false,
491 comments: notes.map((note) => ({
492 id: String(note.id),
493 author: toActor(note.author),
494 body: note.body ?? "",
495 createdAt: note.created_at,
496 url: null,
497 })),
498 });
499 }
500 return Result.succeed({ threads, rawCount: decoded.success.length });
501}
502
503export function decodeDiffRefsJson(
504 raw: string,
505): Result.Result<GitLabDiffRefs | null, DecodeFailure> {
506 const decoded = decodeDiffRefs(raw);
507 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
508 const refs = decoded.success.diff_refs;
509 return Result.succeed(
510 refs ? { baseSha: refs.base_sha, headSha: refs.head_sha, startSha: refs.start_sha } : null,
511 );
512}
513
514export function decodeNotesJson(
515 raw: string,
516): Result.Result<
517 { readonly comments: ReadonlyArray<PullRequestComment>; readonly rawCount: number },
518 DecodeFailure
519> {
520 const decoded = decodeUnknownList(raw);
521 if (!Result.isSuccess(decoded)) {
522 return Result.fail(decoded.failure);
523 }
524 const comments: PullRequestComment[] = [];
525 for (const entry of decoded.success) {
526 const note = decodeNoteEntry(entry);
527 if (Exit.isFailure(note)) continue;
528 const value = note.value;
529 if (value.system === true) continue;
530 const body = value.body ?? "";
531 if (body.trim().length === 0) continue;
532 const isDiffNote = value.type?.trim() === "DiffNote";
533 comments.push({
534 id: String(value.id),
535 kind: isDiffNote ? "review-comment" : "issue-comment",
536 author: toActor(value.author),
537 body,
538 createdAt: value.created_at,
539 url: null,
540 path: trimmed(value.position?.new_path) ?? trimmed(value.position?.old_path),
541 reviewState: null,
542 });
543 }
544 return Result.succeed({ comments, rawCount: decoded.success.length });
545}
546
547export function decodeCommitsJson(
548 raw: string,
549): Result.Result<ReadonlyArray<PullRequestCommit>, DecodeFailure> {
550 const decoded = decodeUnknownList(raw);
551 if (!Result.isSuccess(decoded)) {
552 return Result.fail(decoded.failure);
553 }
554 const commits: PullRequestCommit[] = [];
555 for (const entry of decoded.success) {
556 const commit = decodeCommitEntry(entry);
557 if (Exit.isFailure(commit)) continue;
558 const committedDate = trimmed(commit.value.committed_date) ?? trimmed(commit.value.created_at);
559 if (committedDate === null) continue;
560 commits.push({
561 oid: commit.value.id,
562 messageHeadline: commit.value.title ?? "",
563 committedDate,
564 ...(commit.value.stats === null || commit.value.stats === undefined
565 ? {}
566 : {
567 additions: Math.max(0, commit.value.stats.additions ?? 0),
568 deletions: Math.max(0, commit.value.stats.deletions ?? 0),
569 }),
570 authors: (() => {
571 const login = trimmed(commit.value.author_name) ?? trimmed(commit.value.author_email);
572 return login === null
573 ? []
574 : [{ login, name: trimmed(commit.value.author_name), avatarUrl: null }];
575 })(),
576 });
577 }
578 return Result.succeed(commits.toReversed());
579}
580
581export function decodeCommitDiffRefsJson(
582 raw: string,
583): Result.Result<GitLabDiffRefs | null, DecodeFailure> {
584 const decoded = decodeCommit(raw);
585 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
586 const baseSha = trimmed(decoded.success.parent_ids?.[0]);
587 const headSha = trimmed(decoded.success.id);
588 return Result.succeed(
589 baseSha === null || headSha === null ? null : { baseSha, headSha, startSha: baseSha },
590 );
591}
592
593function diffHeaderPaths(raw: Schema.Schema.Type<typeof RawDiffSchema>): {
594 readonly from: string;
595 readonly to: string;
596} {
597 return {
598 from: raw.new_file === true ? "/dev/null" : quoteGitPatchPath(`a/${raw.old_path}`),
599 to: raw.deleted_file === true ? "/dev/null" : quoteGitPatchPath(`b/${raw.new_path}`),
600 };
601}
602
603export interface GitLabMergeRequestPatch {
604 readonly patch: string;
605 readonly truncated: boolean;
606 readonly rawCount: number;
607}
608
609export function decodeMergeRequestDiffsJson(
610 raw: string,
611): Result.Result<GitLabMergeRequestPatch, DecodeFailure> {
612 const decoded = decodeUnknownList(raw);
613 if (!Result.isSuccess(decoded)) {
614 return Result.fail(decoded.failure);
615 }
616 const sections: string[] = [];
617 let truncated = false;
618 for (const entry of decoded.success) {
619 const file = decodeDiffEntry(entry);
620 if (Exit.isFailure(file)) continue;
621 const value = file.value;
622 const hunks = value.diff ?? "";
623 if (hunks.length === 0) {
624 truncated = truncated || value.too_large === true || value.collapsed === true;
625 }
626 const { from, to } = diffHeaderPaths(value);
627 const header = [
628 `diff --git ${quoteGitPatchPath(`a/${value.old_path}`)} ${quoteGitPatchPath(`b/${value.new_path}`)}`,
629 ...(value.new_file === true ? [`new file mode ${value.b_mode ?? "100644"}`] : []),
630 ...(value.deleted_file === true ? [`deleted file mode ${value.a_mode ?? "100644"}`] : []),
631 ...(value.renamed_file === true
632 ? [
633 `rename from ${quoteGitPatchPath(value.old_path)}`,
634 `rename to ${quoteGitPatchPath(value.new_path)}`,
635 ]
636 : []),
637 `--- ${from}`,
638 `+++ ${to}`,
639 ].join("\n");
640 sections.push(hunks.length === 0 ? header : `${header}\n${hunks.replace(/\n?$/, "\n")}`);
641 }
642 return Result.succeed({
643 patch: sections.join("\n"),
644 truncated,
645 rawCount: decoded.success.length,
646 });
647}
648
649const GITLAB_AWARD_BY_CONTENT: Readonly<Record<PullRequestReactionContent, string>> = {
650 "thumbs-up": "thumbsup",
651 "thumbs-down": "thumbsdown",
652 laugh: "laughing",
653 hooray: "tada",
654 confused: "confused",
655 heart: "heart",
656 rocket: "rocket",
657 eyes: "eyes",
658};
659
660const CONTENT_BY_GITLAB_AWARD: Readonly<Record<string, PullRequestReactionContent>> =
661 Object.fromEntries(
662 Object.entries(GITLAB_AWARD_BY_CONTENT).map(([content, name]) => [name, content]),
663 ) as Readonly<Record<string, PullRequestReactionContent>>;
664
665export function gitLabAwardName(content: PullRequestReactionContent): string {
666 return GITLAB_AWARD_BY_CONTENT[content];
667}
668
669export const AWARD_EMOJI_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!, $cursor: String) {
670 currentUser { username }
671 project(fullPath: $fullPath) {
672 mergeRequest(iid: $iid) {
673 awardEmoji { nodes { name user { username } } }
674 notes(first: 100, after: $cursor) {
675 pageInfo { hasNextPage endCursor }
676 nodes { id awardEmoji { nodes { name user { username } } } }
677 }
678 }
679 }
680}`;
681
682const RawAwardEmojiNodesSchema = Schema.optional(
683 Schema.NullOr(
684 Schema.Struct({
685 nodes: Schema.optional(
686 Schema.NullOr(
687 Schema.Array(
688 Schema.NullOr(
689 Schema.Struct({
690 name: Schema.optional(Schema.NullOr(Schema.String)),
691 user: Schema.optional(
692 Schema.NullOr(
693 Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) }),
694 ),
695 ),
696 }),
697 ),
698 ),
699 ),
700 ),
701 }),
702 ),
703);
704
705const RawAwardEmojiPageSchema = Schema.Struct({
706 data: Schema.Struct({
707 currentUser: Schema.optional(
708 Schema.NullOr(Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) })),
709 ),
710 project: Schema.NullOr(
711 Schema.Struct({
712 mergeRequest: Schema.NullOr(
713 Schema.Struct({
714 awardEmoji: RawAwardEmojiNodesSchema,
715 notes: Schema.optional(
716 Schema.NullOr(
717 Schema.Struct({
718 pageInfo: Schema.optional(
719 Schema.Struct({
720 hasNextPage: Schema.optional(Schema.Boolean),
721 endCursor: Schema.optional(Schema.NullOr(Schema.String)),
722 }),
723 ),
724 nodes: Schema.Array(
725 Schema.NullOr(
726 Schema.Struct({
727 id: Schema.optional(Schema.NullOr(Schema.String)),
728 awardEmoji: RawAwardEmojiNodesSchema,
729 }),
730 ),
731 ),
732 }),
733 ),
734 ),
735 }),
736 ),
737 }),
738 ),
739 }),
740});
741
742const decodeAwardEmojiPage = decodeJsonResult(RawAwardEmojiPageSchema);
743
744function toReactions(
745 nodes: Schema.Schema.Type<typeof RawAwardEmojiNodesSchema>,
746 viewer: string | null,
747): ReadonlyArray<PullRequestReaction> {
748 const normalizedViewer = viewer?.toLowerCase() ?? null;
749 const groups = new Map<
750 PullRequestReactionContent,
751 { count: number; actors: string[]; viewer: boolean }
752 >();
753 for (const node of nodes?.nodes ?? []) {
754 const content = CONTENT_BY_GITLAB_AWARD[trimmed(node?.name)?.toLowerCase() ?? ""];
755 if (content === undefined) continue;
756 const username = trimmed(node?.user?.username);
757 if (username === null) continue;
758 const group = groups.get(content) ?? { count: 0, actors: [], viewer: false };
759 group.count++;
760 if (normalizedViewer !== null && username.toLowerCase() === normalizedViewer) {
761 group.viewer = true;
762 } else {
763 group.actors.push(username);
764 }
765 groups.set(content, group);
766 }
767 return [...groups].flatMap(([content, group]) =>
768 group.count === 0
769 ? []
770 : [{ content, count: group.count, actors: group.actors, viewerHasReacted: group.viewer }],
771 );
772}
773
774function noteIdOf(gid: string | null | undefined): string | null {
775 const id = trimmed(gid)?.split("/").at(-1);
776 return id !== undefined && /^\d+$/.test(id) ? id : null;
777}
778
779export interface GitLabAwardEmojiPage {
780 readonly reactions: ReadonlyArray<PullRequestReaction>;
781 readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>;
782 readonly nextCursor: string | null;
783}
784
785export function decodeAwardEmojiJson(
786 raw: string,
787): Result.Result<GitLabAwardEmojiPage, DecodeFailure> {
788 const decoded = decodeAwardEmojiPage(raw);
789 if (!Result.isSuccess(decoded)) {
790 return Result.fail(decoded.failure);
791 }
792 const data = decoded.success.data;
793 const viewer = trimmed(data.currentUser?.username);
794 const mergeRequest = data.project?.mergeRequest;
795 const reactionsByNoteId = new Map<string, ReadonlyArray<PullRequestReaction>>();
796 for (const node of mergeRequest?.notes?.nodes ?? []) {
797 const id = noteIdOf(node?.id);
798 if (id === null) continue;
799 const reactions = toReactions(node?.awardEmoji, viewer);
800 if (reactions.length > 0) reactionsByNoteId.set(id, reactions);
801 }
802 const pageInfo = mergeRequest?.notes?.pageInfo;
803 return Result.succeed({
804 reactions: toReactions(mergeRequest?.awardEmoji, viewer),
805 reactionsByNoteId,
806 nextCursor: pageInfo?.hasNextPage === true ? (trimmed(pageInfo.endCursor) ?? null) : null,
807 });
808}
809
810const RawAwardSchema = Schema.Struct({
811 id: Schema.Int,
812 name: Schema.optional(Schema.NullOr(Schema.String)),
813 user: Schema.optional(
814 Schema.NullOr(Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) })),
815 ),
816});
817
818const decodeAward = Schema.decodeUnknownExit(RawAwardSchema);
819
820export function decodeOwnAwardIdJson(
821 raw: string,
822 input: { readonly content: PullRequestReactionContent; readonly viewer: string },
823): Result.Result<number | null, DecodeFailure> {
824 const decoded = decodeUnknownList(raw);
825 if (!Result.isSuccess(decoded)) {
826 return Result.fail(decoded.failure);
827 }
828 const name = gitLabAwardName(input.content);
829 for (const entry of decoded.success) {
830 const award = decodeAward(entry);
831 if (Exit.isFailure(award)) continue;
832 const value = award.value;
833 if (trimmed(value.name)?.toLowerCase() !== name) continue;
834 if (trimmed(value.user?.username) !== input.viewer) continue;
835 return Result.succeed(value.id);
836 }
837 return Result.succeed(null);
838}
839
840export const REPOSITORY_BLOBS_GRAPHQL_QUERY = `query($fullPath: ID!, $ref: String!, $paths: [String!]!) {
841 project(fullPath: $fullPath) {
842 repository {
843 blobs(ref: $ref, paths: $paths) {
844 nodes { path oid }
845 }
846 }
847 }
848}`;
849
850const RawRepositoryBlobsSchema = Schema.Struct({
851 data: Schema.Struct({
852 project: Schema.NullOr(
853 Schema.Struct({
854 repository: Schema.optional(
855 Schema.NullOr(
856 Schema.Struct({
857 blobs: Schema.optional(
858 Schema.NullOr(
859 Schema.Struct({
860 nodes: Schema.optional(
861 Schema.NullOr(
862 Schema.Array(
863 Schema.NullOr(
864 Schema.Struct({
865 path: Schema.optional(Schema.NullOr(Schema.String)),
866 oid: Schema.optional(Schema.NullOr(Schema.String)),
867 }),
868 ),
869 ),
870 ),
871 ),
872 }),
873 ),
874 ),
875 }),
876 ),
877 ),
878 }),
879 ),
880 }),
881});
882
883const decodeRepositoryBlobs = decodeJsonResult(RawRepositoryBlobsSchema);
884
885/**
886 * Blob ids by path, or null where GitLab did not answer the query at all (a project the token
887 * cannot see, or a repository with no blobs connection). That case must be told apart from an
888 * empty answer: read as "the revision has none of these files", it would report every cleared
889 * file as changed again.
890 */
891export function decodeRepositoryBlobsJson(
892 raw: string,
893): Result.Result<ReadonlyMap<string, string> | null, DecodeFailure> {
894 const decoded = decodeRepositoryBlobs(raw);
895 if (!Result.isSuccess(decoded)) {
896 return Result.fail(decoded.failure);
897 }
898 const nodes = decoded.success.data.project?.repository?.blobs?.nodes;
899 if (nodes === undefined || nodes === null) return Result.succeed(null);
900 const blobs = new Map<string, string>();
901 for (const node of nodes) {
902 // Not trimmed, unlike everything else read out of this payload: a leading or trailing space
903 // is a legal part of a file's name, and trimming it would key this map under a name the
904 // caller's asked-for path never matches.
905 const path = node?.path;
906 const oid = trimmed(node?.oid);
907 if (path === undefined || path === null || path.length === 0 || oid === null) continue;
908 blobs.set(path, oid);
909 }
910 return Result.succeed(blobs);
911}