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