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 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;
378}
379
380export interface GitLabMergeRequestListBatch {
381 readonly items: ReadonlyArray<GitLabMergeRequestListItem>;
382 readonly rawIndexes: ReadonlyArray<number>;
383 readonly rawCount: number;
384}
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 });
403}
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);
412}
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);
419}
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 });
442}
443
444const RawLabelSchema = Schema.Struct({
445 name: Schema.String,
446 color: Schema.optional(Schema.NullOr(Schema.String)),
447});
448const decodeLabelEntry = Schema.decodeUnknownExit(RawLabelSchema);
449
450export interface GitLabProjectLabels {
451 readonly labels: ReadonlyArray<PullRequestLabel>;
452 readonly rawCount: number;
453}
454
455export function decodeProjectLabelsJson(
456 raw: string,
457): Result.Result<GitLabProjectLabels, DecodeFailure> {
458 const decoded = decodeUnknownList(raw);
459 if (!Result.isSuccess(decoded)) {
460 return Result.fail(decoded.failure);
461 }
462 const labels: PullRequestLabel[] = [];
463 for (const entry of decoded.success) {
464 const label = decodeLabelEntry(entry);
465 if (Exit.isFailure(label)) continue;
466 const name = trimmed(label.value.name);
467 if (name !== null) labels.push({ name, color: trimmed(label.value.color) });
468 }
469 return Result.succeed({ labels, rawCount: decoded.success.length });
470}
471
472export function decodeProjectMergeCapabilitiesJson(
473 raw: string,
474): Result.Result<PullRequestMergeCapabilities, DecodeFailure> {
475 const decoded = decodeProjectMergeSettings(raw);
476 if (!Result.isSuccess(decoded)) {
477 return Result.fail(decoded.failure);
478 }
479 const mergeMethod = decoded.success.merge_method?.trim().toLowerCase();
480 const squashOption = decoded.success.squash_option?.trim().toLowerCase();
481 return Result.succeed({
482 merge: mergeMethod === "merge",
483 rebase: mergeMethod === "rebase_merge" || mergeMethod === "ff",
484 squash:
485 squashOption === "always" || squashOption === "default_on" || squashOption === "default_off",
486 });
487}
488
489export interface GitLabDiffRefs {
490 readonly baseSha: string;
491 readonly headSha: string;
492 readonly startSha: string;
493}
494
495export interface GitLabDiscussions {
496 readonly threads: ReadonlyArray<PullRequestReviewThread>;
497 readonly rawCount: number;
498}
499
500export function decodeDiscussionsJson(
501 raw: string,
502): Result.Result<GitLabDiscussions, DecodeFailure> {
503 const decoded = decodeUnknownList(raw);
504 if (!Result.isSuccess(decoded)) {
505 return Result.fail(decoded.failure);
506 }
507 const threads: PullRequestReviewThread[] = [];
508 for (const entry of decoded.success) {
509 const discussion = decodeDiscussionEntry(entry);
510 if (!Exit.isSuccess(discussion)) continue;
511 const notes = (discussion.value.notes ?? []).filter((note) => note.system !== true);
512 const root = notes[0];
513 const position = root?.position;
514 if (root === undefined || !position || position.position_type !== "text") continue;
515 const side = position.new_line === null || position.new_line === undefined ? "left" : "right";
516 const path = trimmed(side === "left" ? position.old_path : position.new_path);
517 const line = side === "left" ? position.old_line : position.new_line;
518 if (path === null) continue;
519 threads.push({
520 id: discussion.value.id,
521 path,
522 line: typeof line === "number" && line > 0 ? line : null,
523 side,
524 isResolved: root.resolved === true,
525 isOutdated: false,
526 comments: notes.map((note) => ({
527 id: String(note.id),
528 author: toActor(note.author),
529 body: note.body ?? "",
530 createdAt: note.created_at,
531 url: null,
532 })),
533 });
534 }
535 return Result.succeed({ threads, rawCount: decoded.success.length });
536}
537
538export function decodeDiffRefsJson(
539 raw: string,
540): Result.Result<GitLabDiffRefs | null, DecodeFailure> {
541 const decoded = decodeDiffRefs(raw);
542 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
543 const refs = decoded.success.diff_refs;
544 return Result.succeed(
545 refs ? { baseSha: refs.base_sha, headSha: refs.head_sha, startSha: refs.start_sha } : null,
546 );
547}
548
549export function decodeNotesJson(
550 raw: string,
551): Result.Result<
552 { readonly comments: ReadonlyArray<PullRequestComment>; readonly rawCount: number },
553 DecodeFailure
554> {
555 const decoded = decodeUnknownList(raw);
556 if (!Result.isSuccess(decoded)) {
557 return Result.fail(decoded.failure);
558 }
559 const comments: PullRequestComment[] = [];
560 for (const entry of decoded.success) {
561 const note = decodeNoteEntry(entry);
562 if (Exit.isFailure(note)) continue;
563 const value = note.value;
564 if (value.system === true) continue;
565 const body = value.body ?? "";
566 if (body.trim().length === 0) continue;
567 const isDiffNote = value.type?.trim() === "DiffNote";
568 comments.push({
569 id: String(value.id),
570 kind: isDiffNote ? "review-comment" : "issue-comment",
571 author: toActor(value.author),
572 body,
573 createdAt: value.created_at,
574 url: null,
575 path: trimmed(value.position?.new_path) ?? trimmed(value.position?.old_path),
576 reviewState: null,
577 });
578 }
579 return Result.succeed({ comments, rawCount: decoded.success.length });
580}
581
582export function decodeCommitsJson(
583 raw: string,
584): Result.Result<ReadonlyArray<PullRequestCommit>, DecodeFailure> {
585 const decoded = decodeUnknownList(raw);
586 if (!Result.isSuccess(decoded)) {
587 return Result.fail(decoded.failure);
588 }
589 const commits: PullRequestCommit[] = [];
590 for (const entry of decoded.success) {
591 const commit = decodeCommitEntry(entry);
592 if (Exit.isFailure(commit)) continue;
593 const committedDate = trimmed(commit.value.committed_date) ?? trimmed(commit.value.created_at);
594 if (committedDate === null) continue;
595 commits.push({
596 oid: commit.value.id,
597 messageHeadline: commit.value.title ?? "",
598 committedDate,
599 ...(commit.value.stats === null || commit.value.stats === undefined
600 ? {}
601 : {
602 additions: Math.max(0, commit.value.stats.additions ?? 0),
603 deletions: Math.max(0, commit.value.stats.deletions ?? 0),
604 }),
605 authors: (() => {
606 const login = trimmed(commit.value.author_name) ?? trimmed(commit.value.author_email);
607 return login === null
608 ? []
609 : [{ login, name: trimmed(commit.value.author_name), avatarUrl: null }];
610 })(),
611 });
612 }
613 return Result.succeed(commits.toReversed());
614}
615
616export function decodeCommitDiffRefsJson(
617 raw: string,
618): Result.Result<GitLabDiffRefs | null, DecodeFailure> {
619 const decoded = decodeCommit(raw);
620 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
621 const baseSha = trimmed(decoded.success.parent_ids?.[0]);
622 const headSha = trimmed(decoded.success.id);
623 return Result.succeed(
624 baseSha === null || headSha === null ? null : { baseSha, headSha, startSha: baseSha },
625 );
626}
627
628function diffHeaderPaths(raw: Schema.Schema.Type<typeof RawDiffSchema>): {
629 readonly from: string;
630 readonly to: string;
631} {
632 return {
633 from: raw.new_file === true ? "/dev/null" : quoteGitPatchPath(`a/${raw.old_path}`),
634 to: raw.deleted_file === true ? "/dev/null" : quoteGitPatchPath(`b/${raw.new_path}`),
635 };
636}
637
638export interface GitLabMergeRequestPatch {
639 readonly patch: string;
640 readonly truncated: boolean;
641 readonly rawCount: number;
642}
643
644export function decodeMergeRequestDiffsJson(
645 raw: string,
646): Result.Result<GitLabMergeRequestPatch, DecodeFailure> {
647 const decoded = decodeUnknownList(raw);
648 if (!Result.isSuccess(decoded)) {
649 return Result.fail(decoded.failure);
650 }
651 return Result.succeed(mergeRequestPatch(decoded.success));
652}
653
654/** Older GitLab instances return all files in a non-paginated merge request wrapper. */
655export function decodeMergeRequestChangesJson(
656 raw: string,
657): Result.Result<GitLabMergeRequestPatch, DecodeFailure> {
658 const decoded = decodeMergeRequestChanges(raw);
659 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
660 const patch = mergeRequestPatch(decoded.success.changes);
661 return Result.succeed({
662 ...patch,
663 truncated:
664 patch.truncated ||
665 decoded.success.overflow === true ||
666 decoded.success.changes_count?.endsWith("+") === true,
667 });
668}
669
670/** Builds file patches, retaining raw counts and recording files whose contents are missing. */
671function mergeRequestPatch(entries: ReadonlyArray<unknown>): GitLabMergeRequestPatch {
672 const sections: string[] = [];
673 let truncated = false;
674 for (const entry of entries) {
675 const file = decodeDiffEntry(entry);
676 if (Exit.isFailure(file)) {
677 truncated = true;
678 continue;
679 }
680 const value = file.value;
681 const hunks = value.diff ?? "";
682 if (hunks.length === 0) {
683 truncated = truncated || value.too_large === true || value.collapsed === true;
684 }
685 const { from, to } = diffHeaderPaths(value);
686 const header = [
687 `diff --git ${quoteGitPatchPath(`a/${value.old_path}`)} ${quoteGitPatchPath(`b/${value.new_path}`)}`,
688 ...(value.new_file === true ? [`new file mode ${value.b_mode ?? "100644"}`] : []),
689 ...(value.deleted_file === true ? [`deleted file mode ${value.a_mode ?? "100644"}`] : []),
690 ...(value.renamed_file === true
691 ? [
692 `rename from ${quoteGitPatchPath(value.old_path)}`,
693 `rename to ${quoteGitPatchPath(value.new_path)}`,
694 ]
695 : []),
696 `--- ${from}`,
697 `+++ ${to}`,
698 ].join("\n");
699 sections.push(hunks.length === 0 ? header : `${header}\n${hunks.replace(/\n?$/, "\n")}`);
700 }
701 return {
702 patch: sections.join("\n"),
703 truncated,
704 rawCount: entries.length,
705 };
706}
707
708const GITLAB_AWARD_BY_CONTENT: Readonly<Record<PullRequestReactionContent, string>> = {
709 "thumbs-up": "thumbsup",
710 "thumbs-down": "thumbsdown",
711 laugh: "laughing",
712 hooray: "tada",
713 confused: "confused",
714 heart: "heart",
715 rocket: "rocket",
716 eyes: "eyes",
717};
718
719const CONTENT_BY_GITLAB_AWARD: Readonly<Record<string, PullRequestReactionContent>> =
720 Object.fromEntries(
721 Object.entries(GITLAB_AWARD_BY_CONTENT).map(([content, name]) => [name, content]),
722 ) as Readonly<Record<string, PullRequestReactionContent>>;
723
724export function gitLabAwardName(content: PullRequestReactionContent): string {
725 return GITLAB_AWARD_BY_CONTENT[content];
726}
727
728export const AWARD_EMOJI_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!, $cursor: String) {
729 currentUser { username }
730 project(fullPath: $fullPath) {
731 mergeRequest(iid: $iid) {
732 awardEmoji { nodes { name user { username } } }
733 notes(first: 100, after: $cursor) {
734 pageInfo { hasNextPage endCursor }
735 nodes { id awardEmoji { nodes { name user { username } } } }
736 }
737 }
738 }
739}`;
740
741const RawAwardEmojiNodesSchema = Schema.optional(
742 Schema.NullOr(
743 Schema.Struct({
744 nodes: Schema.optional(
745 Schema.NullOr(
746 Schema.Array(
747 Schema.NullOr(
748 Schema.Struct({
749 name: Schema.optional(Schema.NullOr(Schema.String)),
750 user: Schema.optional(
751 Schema.NullOr(
752 Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) }),
753 ),
754 ),
755 }),
756 ),
757 ),
758 ),
759 ),
760 }),
761 ),
762);
763
764const RawAwardEmojiPageSchema = Schema.Struct({
765 data: Schema.Struct({
766 currentUser: Schema.optional(
767 Schema.NullOr(Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) })),
768 ),
769 project: Schema.NullOr(
770 Schema.Struct({
771 mergeRequest: Schema.NullOr(
772 Schema.Struct({
773 awardEmoji: RawAwardEmojiNodesSchema,
774 notes: Schema.optional(
775 Schema.NullOr(
776 Schema.Struct({
777 pageInfo: Schema.optional(
778 Schema.Struct({
779 hasNextPage: Schema.optional(Schema.Boolean),
780 endCursor: Schema.optional(Schema.NullOr(Schema.String)),
781 }),
782 ),
783 nodes: Schema.Array(
784 Schema.NullOr(
785 Schema.Struct({
786 id: Schema.optional(Schema.NullOr(Schema.String)),
787 awardEmoji: RawAwardEmojiNodesSchema,
788 }),
789 ),
790 ),
791 }),
792 ),
793 ),
794 }),
795 ),
796 }),
797 ),
798 }),
799});
800
801const decodeAwardEmojiPage = decodeJsonResult(RawAwardEmojiPageSchema);
802
803function toReactions(
804 nodes: Schema.Schema.Type<typeof RawAwardEmojiNodesSchema>,
805 viewer: string | null,
806): ReadonlyArray<PullRequestReaction> {
807 const normalizedViewer = viewer?.toLowerCase() ?? null;
808 const groups = new Map<
809 PullRequestReactionContent,
810 { count: number; actors: string[]; viewer: boolean }
811 >();
812 for (const node of nodes?.nodes ?? []) {
813 const content = CONTENT_BY_GITLAB_AWARD[trimmed(node?.name)?.toLowerCase() ?? ""];
814 if (content === undefined) continue;
815 const username = trimmed(node?.user?.username);
816 if (username === null) continue;
817 const group = groups.get(content) ?? { count: 0, actors: [], viewer: false };
818 group.count++;
819 if (normalizedViewer !== null && username.toLowerCase() === normalizedViewer) {
820 group.viewer = true;
821 } else {
822 group.actors.push(username);
823 }
824 groups.set(content, group);
825 }
826 return [...groups].flatMap(([content, group]) =>
827 group.count === 0
828 ? []
829 : [{ content, count: group.count, actors: group.actors, viewerHasReacted: group.viewer }],
830 );
831}
832
833function noteIdOf(gid: string | null | undefined): string | null {
834 const id = trimmed(gid)?.split("/").at(-1);
835 return id !== undefined && /^\d+$/.test(id) ? id : null;
836}
837
838export interface GitLabAwardEmojiPage {
839 readonly reactions: ReadonlyArray<PullRequestReaction>;
840 readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>;
841 readonly nextCursor: string | null;
842}
843
844export function decodeAwardEmojiJson(
845 raw: string,
846): Result.Result<GitLabAwardEmojiPage, DecodeFailure> {
847 const decoded = decodeAwardEmojiPage(raw);
848 if (!Result.isSuccess(decoded)) {
849 return Result.fail(decoded.failure);
850 }
851 const data = decoded.success.data;
852 const viewer = trimmed(data.currentUser?.username);
853 const mergeRequest = data.project?.mergeRequest;
854 const reactionsByNoteId = new Map<string, ReadonlyArray<PullRequestReaction>>();
855 for (const node of mergeRequest?.notes?.nodes ?? []) {
856 const id = noteIdOf(node?.id);
857 if (id === null) continue;
858 const reactions = toReactions(node?.awardEmoji, viewer);
859 if (reactions.length > 0) reactionsByNoteId.set(id, reactions);
860 }
861 const pageInfo = mergeRequest?.notes?.pageInfo;
862 return Result.succeed({
863 reactions: toReactions(mergeRequest?.awardEmoji, viewer),
864 reactionsByNoteId,
865 nextCursor: pageInfo?.hasNextPage === true ? (trimmed(pageInfo.endCursor) ?? null) : null,
866 });
867}
868
869const RawAwardSchema = Schema.Struct({
870 id: Schema.Int,
871 name: Schema.optional(Schema.NullOr(Schema.String)),
872 user: Schema.optional(
873 Schema.NullOr(Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) })),
874 ),
875});
876
877const decodeAward = Schema.decodeUnknownExit(RawAwardSchema);
878
879export function decodeOwnAwardIdJson(
880 raw: string,
881 input: { readonly content: PullRequestReactionContent; readonly viewer: string },
882): Result.Result<number | null, DecodeFailure> {
883 const decoded = decodeUnknownList(raw);
884 if (!Result.isSuccess(decoded)) {
885 return Result.fail(decoded.failure);
886 }
887 const name = gitLabAwardName(input.content);
888 for (const entry of decoded.success) {
889 const award = decodeAward(entry);
890 if (Exit.isFailure(award)) continue;
891 const value = award.value;
892 if (trimmed(value.name)?.toLowerCase() !== name) continue;
893 if (trimmed(value.user?.username) !== input.viewer) continue;
894 return Result.succeed(value.id);
895 }
896 return Result.succeed(null);
897}
898
899export const REPOSITORY_BLOBS_GRAPHQL_QUERY = `query($fullPath: ID!, $ref: String!, $paths: [String!]!) {
900 project(fullPath: $fullPath) {
901 repository {
902 blobs(ref: $ref, paths: $paths) {
903 nodes { path oid }
904 }
905 }
906 }
907}`;
908
909const RawRepositoryBlobsSchema = Schema.Struct({
910 data: Schema.Struct({
911 project: Schema.NullOr(
912 Schema.Struct({
913 repository: Schema.optional(
914 Schema.NullOr(
915 Schema.Struct({
916 blobs: Schema.optional(
917 Schema.NullOr(
918 Schema.Struct({
919 nodes: Schema.optional(
920 Schema.NullOr(
921 Schema.Array(
922 Schema.NullOr(
923 Schema.Struct({
924 path: Schema.optional(Schema.NullOr(Schema.String)),
925 oid: Schema.optional(Schema.NullOr(Schema.String)),
926 }),
927 ),
928 ),
929 ),
930 ),
931 }),
932 ),
933 ),
934 }),
935 ),
936 ),
937 }),
938 ),
939 }),
940});
941
942const decodeRepositoryBlobs = decodeJsonResult(RawRepositoryBlobsSchema);
943
944/**
945 * Blob ids by path, or null where GitLab did not answer the query at all (a project the token
946 * cannot see, or a repository with no blobs connection). That case must be told apart from an
947 * empty answer: read as "the revision has none of these files", it would report every cleared
948 * file as changed again.
949 */
950export function decodeRepositoryBlobsJson(
951 raw: string,
952): Result.Result<ReadonlyMap<string, string> | null, DecodeFailure> {
953 const decoded = decodeRepositoryBlobs(raw);
954 if (!Result.isSuccess(decoded)) {
955 return Result.fail(decoded.failure);
956 }
957 const nodes = decoded.success.data.project?.repository?.blobs?.nodes;
958 if (nodes === undefined || nodes === null) return Result.succeed(null);
959 const blobs = new Map<string, string>();
960 for (const node of nodes) {
961 // Not trimmed, unlike everything else read out of this payload: a leading or trailing space
962 // is a legal part of a file's name, and trimming it would key this map under a name the
963 // caller's asked-for path never matches.
964 const path = node?.path;
965 const oid = trimmed(node?.oid);
966 if (path === undefined || path === null || path.length === 0 || oid === null) continue;
967 blobs.set(path, oid);
968 }
969 return Result.succeed(blobs);
970}