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 // GitLab has no similarity score; Pierre needs this header to keep the rename.
728 `similarity index ${hunks.length > 0 || value.too_large === true || value.collapsed === true ? 0 : 100}%`,
729 `rename from ${quoteGitPatchPath(value.old_path)}`,
730 `rename to ${quoteGitPatchPath(value.new_path)}`,
731 ]
732 : []),
733 `--- ${from}`,
734 `+++ ${to}`,
735 ].join("\n");
736 sections.push(hunks.length === 0 ? header : `${header}\n${hunks.replace(/\n?$/, "\n")}`);
737 }
738 return {
739 patch: sections.join("\n"),
740 truncated,
741 rawCount: entries.length,
742 };
743}
744
745const GITLAB_AWARD_BY_CONTENT: Readonly<Record<PullRequestReactionContent, string>> = {
746 "thumbs-up": "thumbsup",
747 "thumbs-down": "thumbsdown",
748 laugh: "laughing",
749 hooray: "tada",
750 confused: "confused",
751 heart: "heart",
752 rocket: "rocket",
753 eyes: "eyes",
754};
755
756const CONTENT_BY_GITLAB_AWARD: Readonly<Record<string, PullRequestReactionContent>> =
757 Object.fromEntries(
758 Object.entries(GITLAB_AWARD_BY_CONTENT).map(([content, name]) => [name, content]),
759 ) as Readonly<Record<string, PullRequestReactionContent>>;
760
761export function gitLabAwardName(content: PullRequestReactionContent): string {
762 return GITLAB_AWARD_BY_CONTENT[content];
763}
764
765export const AWARD_EMOJI_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!, $cursor: String) {
766 currentUser { username }
767 project(fullPath: $fullPath) {
768 mergeRequest(iid: $iid) {
769 awardEmoji { nodes { name user { username } } }
770 notes(first: 100, after: $cursor) {
771 pageInfo { hasNextPage endCursor }
772 nodes { id awardEmoji { nodes { name user { username } } } }
773 }
774 }
775 }
776}`;
777
778const RawAwardEmojiNodesSchema = Schema.optional(
779 Schema.NullOr(
780 Schema.Struct({
781 nodes: Schema.optional(
782 Schema.NullOr(
783 Schema.Array(
784 Schema.NullOr(
785 Schema.Struct({
786 name: Schema.optional(Schema.NullOr(Schema.String)),
787 user: Schema.optional(
788 Schema.NullOr(
789 Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) }),
790 ),
791 ),
792 }),
793 ),
794 ),
795 ),
796 ),
797 }),
798 ),
799);
800
801const RawAwardEmojiPageSchema = Schema.Struct({
802 data: Schema.Struct({
803 currentUser: Schema.optional(
804 Schema.NullOr(Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) })),
805 ),
806 project: Schema.NullOr(
807 Schema.Struct({
808 mergeRequest: Schema.NullOr(
809 Schema.Struct({
810 awardEmoji: RawAwardEmojiNodesSchema,
811 notes: Schema.optional(
812 Schema.NullOr(
813 Schema.Struct({
814 pageInfo: Schema.optional(
815 Schema.Struct({
816 hasNextPage: Schema.optional(Schema.Boolean),
817 endCursor: Schema.optional(Schema.NullOr(Schema.String)),
818 }),
819 ),
820 nodes: Schema.Array(
821 Schema.NullOr(
822 Schema.Struct({
823 id: Schema.optional(Schema.NullOr(Schema.String)),
824 awardEmoji: RawAwardEmojiNodesSchema,
825 }),
826 ),
827 ),
828 }),
829 ),
830 ),
831 }),
832 ),
833 }),
834 ),
835 }),
836});
837
838const decodeAwardEmojiPage = decodeJsonResult(RawAwardEmojiPageSchema);
839
840function toReactions(
841 nodes: Schema.Schema.Type<typeof RawAwardEmojiNodesSchema>,
842 viewer: string | null,
843): ReadonlyArray<PullRequestReaction> {
844 const normalizedViewer = viewer?.toLowerCase() ?? null;
845 const groups = new Map<
846 PullRequestReactionContent,
847 { count: number; actors: string[]; viewer: boolean }
848 >();
849 for (const node of nodes?.nodes ?? []) {
850 const content = CONTENT_BY_GITLAB_AWARD[trimmed(node?.name)?.toLowerCase() ?? ""];
851 if (content === undefined) continue;
852 const username = trimmed(node?.user?.username);
853 if (username === null) continue;
854 const group = groups.get(content) ?? { count: 0, actors: [], viewer: false };
855 group.count++;
856 if (normalizedViewer !== null && username.toLowerCase() === normalizedViewer) {
857 group.viewer = true;
858 } else {
859 group.actors.push(username);
860 }
861 groups.set(content, group);
862 }
863 return [...groups].flatMap(([content, group]) =>
864 group.count === 0
865 ? []
866 : [{ content, count: group.count, actors: group.actors, viewerHasReacted: group.viewer }],
867 );
868}
869
870function noteIdOf(gid: string | null | undefined): string | null {
871 const id = trimmed(gid)?.split("/").at(-1);
872 return id !== undefined && /^\d+$/.test(id) ? id : null;
873}
874
875export interface GitLabAwardEmojiPage {
876 readonly reactions: ReadonlyArray<PullRequestReaction>;
877 readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>;
878 readonly nextCursor: string | null;
879}
880
881export function decodeAwardEmojiJson(
882 raw: string,
883): Result.Result<GitLabAwardEmojiPage, DecodeFailure> {
884 const decoded = decodeAwardEmojiPage(raw);
885 if (!Result.isSuccess(decoded)) {
886 return Result.fail(decoded.failure);
887 }
888 const data = decoded.success.data;
889 const viewer = trimmed(data.currentUser?.username);
890 const mergeRequest = data.project?.mergeRequest;
891 const reactionsByNoteId = new Map<string, ReadonlyArray<PullRequestReaction>>();
892 for (const node of mergeRequest?.notes?.nodes ?? []) {
893 const id = noteIdOf(node?.id);
894 if (id === null) continue;
895 const reactions = toReactions(node?.awardEmoji, viewer);
896 if (reactions.length > 0) reactionsByNoteId.set(id, reactions);
897 }
898 const pageInfo = mergeRequest?.notes?.pageInfo;
899 return Result.succeed({
900 reactions: toReactions(mergeRequest?.awardEmoji, viewer),
901 reactionsByNoteId,
902 nextCursor: pageInfo?.hasNextPage === true ? (trimmed(pageInfo.endCursor) ?? null) : null,
903 });
904}
905
906const RawAwardSchema = Schema.Struct({
907 id: Schema.Int,
908 name: Schema.optional(Schema.NullOr(Schema.String)),
909 user: Schema.optional(
910 Schema.NullOr(Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) })),
911 ),
912});
913
914const decodeAward = Schema.decodeUnknownExit(RawAwardSchema);
915
916export function decodeOwnAwardIdJson(
917 raw: string,
918 input: { readonly content: PullRequestReactionContent; readonly viewer: string },
919): Result.Result<number | null, DecodeFailure> {
920 const decoded = decodeUnknownList(raw);
921 if (!Result.isSuccess(decoded)) {
922 return Result.fail(decoded.failure);
923 }
924 const name = gitLabAwardName(input.content);
925 for (const entry of decoded.success) {
926 const award = decodeAward(entry);
927 if (Exit.isFailure(award)) continue;
928 const value = award.value;
929 if (trimmed(value.name)?.toLowerCase() !== name) continue;
930 if (trimmed(value.user?.username) !== input.viewer) continue;
931 return Result.succeed(value.id);
932 }
933 return Result.succeed(null);
934}
935
936export const REPOSITORY_BLOBS_GRAPHQL_QUERY = `query($fullPath: ID!, $ref: String!, $paths: [String!]!) {
937 project(fullPath: $fullPath) {
938 repository {
939 blobs(ref: $ref, paths: $paths) {
940 nodes { path oid }
941 }
942 }
943 }
944}`;
945
946const RawRepositoryBlobsSchema = Schema.Struct({
947 data: Schema.Struct({
948 project: Schema.NullOr(
949 Schema.Struct({
950 repository: Schema.optional(
951 Schema.NullOr(
952 Schema.Struct({
953 blobs: Schema.optional(
954 Schema.NullOr(
955 Schema.Struct({
956 nodes: Schema.optional(
957 Schema.NullOr(
958 Schema.Array(
959 Schema.NullOr(
960 Schema.Struct({
961 path: Schema.optional(Schema.NullOr(Schema.String)),
962 oid: Schema.optional(Schema.NullOr(Schema.String)),
963 }),
964 ),
965 ),
966 ),
967 ),
968 }),
969 ),
970 ),
971 }),
972 ),
973 ),
974 }),
975 ),
976 }),
977});
978
979const decodeRepositoryBlobs = decodeJsonResult(RawRepositoryBlobsSchema);
980
981/** Null means unknown, not deleted; preserve viewed marks. */
982export function decodeRepositoryBlobsJson(
983 raw: string,
984): Result.Result<ReadonlyMap<string, string> | null, DecodeFailure> {
985 const decoded = decodeRepositoryBlobs(raw);
986 if (!Result.isSuccess(decoded)) {
987 return Result.fail(decoded.failure);
988 }
989 const nodes = decoded.success.data.project?.repository?.blobs?.nodes;
990 if (nodes === undefined || nodes === null) return Result.succeed(null);
991 const blobs = new Map<string, string>();
992 for (const node of nodes) {
993 // Preserve path whitespace so blob-map keys match the caller's exact filenames.
994 const path = node?.path;
995 const oid = trimmed(node?.oid);
996 if (path === undefined || path === null || path.length === 0 || oid === null) continue;
997 blobs.set(path, oid);
998 }
999 return Result.succeed(blobs);
1000}
1001
1002export const REVIEW_DECISIONS_GRAPHQL_QUERY = `query($fullPath: ID!, $iids: [String!]) {
1003 metadata { enterprise }
1004 project(fullPath: $fullPath) {
1005 mergeRequests(iids: $iids, first: 100) {
1006 nodes { iid approved approvedBy(first: 1) { nodes { username } } }
1007 }
1008 }
1009}`;
1010
1011const RawReviewDecisionsSchema = Schema.Struct({
1012 data: Schema.Struct({
1013 metadata: Schema.optional(
1014 Schema.NullOr(Schema.Struct({ enterprise: Schema.optional(Schema.NullOr(Schema.Boolean)) })),
1015 ),
1016 project: Schema.NullOr(
1017 Schema.Struct({
1018 mergeRequests: Schema.optional(
1019 Schema.NullOr(
1020 Schema.Struct({
1021 nodes: Schema.Array(
1022 Schema.NullOr(
1023 Schema.Struct({
1024 iid: Schema.String,
1025 approved: Schema.optional(Schema.NullOr(Schema.Boolean)),
1026 approvedBy: Schema.optional(
1027 Schema.NullOr(
1028 Schema.Struct({
1029 nodes: Schema.optional(Schema.NullOr(Schema.Array(Schema.Unknown))),
1030 }),
1031 ),
1032 ),
1033 }),
1034 ),
1035 ),
1036 }),
1037 ),
1038 ),
1039 }),
1040 ),
1041 }),
1042});
1043
1044const decodeReviewDecisions = decodeJsonResult(RawReviewDecisionsSchema);
1045
1046/**
1047 * Only Enterprise Edition holds `approved` to the project's approval rules, so an unapproved
1048 * merge request there still needs review even when someone, such as a bot, approved it.
1049 * Community Edition reports `approved` once anyone approves and requires no review.
1050 */
1051export function decodeReviewDecisionsJson(
1052 raw: string,
1053): Result.Result<ReadonlyMap<number, PullRequestReviewDecision | null>, DecodeFailure> {
1054 const decoded = decodeReviewDecisions(raw);
1055 if (!Result.isSuccess(decoded)) {
1056 return Result.fail(decoded.failure);
1057 }
1058 const enterprise = decoded.success.data.metadata?.enterprise;
1059 const decisions = new Map<number, PullRequestReviewDecision | null>();
1060 for (const node of decoded.success.data.project?.mergeRequests?.nodes ?? []) {
1061 const number = Number(node?.iid);
1062 if (
1063 node === null ||
1064 !Number.isSafeInteger(number) ||
1065 node.approved == null ||
1066 node.approvedBy?.nodes == null
1067 )
1068 continue;
1069 const approvals = node.approvedBy.nodes.length;
1070 if (node.approved === false && approvals === 0 && enterprise == null) continue;
1071 decisions.set(
1072 number,
1073 node.approved === false && (enterprise || approvals > 0)
1074 ? "review-required"
1075 : approvals > 0
1076 ? "approved"
1077 : null,
1078 );
1079 }
1080 return Result.succeed(decisions);
1081}
1082
1083/**
1084 * Line counts for merge requests of one project. The REST listing carries no line counts, and
1085 * reading each diff to count them would cost a request per row, so GraphQL's per-merge-request
1086 * summary is asked for in one read instead.
1087 */
1088export const MERGE_REQUEST_STATS_GRAPHQL_QUERY = `query($fullPath: ID!, $iids: [String!]) {
1089 project(fullPath: $fullPath) {
1090 mergeRequests(iids: $iids, first: 100) {
1091 nodes { iid diffStatsSummary { additions deletions } }
1092 }
1093 }
1094}`;
1095
1096const LineCountsSchema = Schema.Struct({ additions: Schema.Int, deletions: Schema.Int });
1097
1098const RawMergeRequestStatsSchema = Schema.Struct({
1099 data: Schema.Struct({
1100 project: Schema.NullOr(
1101 Schema.Struct({
1102 mergeRequests: Schema.NullOr(
1103 Schema.Struct({
1104 nodes: Schema.Array(
1105 Schema.NullOr(
1106 Schema.Struct({
1107 iid: Schema.String,
1108 diffStatsSummary: Schema.NullOr(LineCountsSchema),
1109 }),
1110 ),
1111 ),
1112 }),
1113 ),
1114 }),
1115 ),
1116 }),
1117});
1118
1119const decodeMergeRequestStats = decodeJsonResult(RawMergeRequestStatsSchema);
1120
1121/**
1122 * The counts by merge request number. A merge request GitLab returned no summary for is left
1123 * out rather than counted as zero, so its row keeps whatever it already showed.
1124 */
1125export function decodeMergeRequestStatsJson(
1126 raw: string,
1127): Result.Result<
1128 ReadonlyMap<number, { readonly additions: number; readonly deletions: number }>,
1129 DecodeFailure
1130> {
1131 const decoded = decodeMergeRequestStats(raw);
1132 if (!Result.isSuccess(decoded)) {
1133 return Result.fail(decoded.failure);
1134 }
1135 const stats = new Map<number, { readonly additions: number; readonly deletions: number }>();
1136 for (const node of decoded.success.data.project?.mergeRequests?.nodes ?? []) {
1137 const iid = Number(node?.iid);
1138 if (!Number.isSafeInteger(iid) || iid <= 0 || node?.diffStatsSummary == null) continue;
1139 stats.set(iid, node.diffStatsSummary);
1140 }
1141 return Result.succeed(stats);
1142}
1143
1144/** Per-file line counts for one merge request, which the code/tests/generated breakdown sorts. */
1145export const MERGE_REQUEST_FILE_STATS_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!) {
1146 project(fullPath: $fullPath) {
1147 mergeRequest(iid: $iid) {
1148 diffStatsSummary { fileCount }
1149 diffStats { path additions deletions }
1150 }
1151 }
1152}`;
1153
1154const decodeMergeRequestFileStats = decodeJsonResult(
1155 Schema.Struct({
1156 data: Schema.Struct({
1157 project: Schema.NullOr(
1158 Schema.Struct({
1159 mergeRequest: Schema.NullOr(
1160 Schema.Struct({
1161 diffStatsSummary: Schema.NullOr(Schema.Struct({ fileCount: Schema.Int })),
1162 diffStats: Schema.NullOr(
1163 Schema.Array(Schema.Struct({ path: Schema.String, ...LineCountsSchema.fields })),
1164 ),
1165 }),
1166 ),
1167 }),
1168 ),
1169 }),
1170 }),
1171);
1172
1173/**
1174 * GitLab stops listing files past its diff limits while the summary still counts them all, so a
1175 * shorter list is reported as truncated rather than as a breakdown that misses lines.
1176 */
1177export function decodeMergeRequestFileStatsJson(raw: string): Result.Result<
1178 {
1179 readonly files: ReadonlyArray<{
1180 readonly path: string;
1181 readonly additions: number;
1182 readonly deletions: number;
1183 }>;
1184 readonly truncated: boolean;
1185 },
1186 DecodeFailure
1187> {
1188 const decoded = decodeMergeRequestFileStats(raw);
1189 if (!Result.isSuccess(decoded)) {
1190 return Result.fail(decoded.failure);
1191 }
1192 const mergeRequest = decoded.success.data.project?.mergeRequest;
1193 const files = mergeRequest?.diffStats ?? [];
1194 const fileCount = mergeRequest?.diffStatsSummary?.fileCount;
1195 return Result.succeed({ files, truncated: fileCount === undefined || files.length < fileCount });
1196}