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