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