The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { trimOptionalString as trimmed } from "@t3tools/source-control-core/server/pullRequestUtils"; |
| 2 | import * as Cause from "effect/Cause"; |
| 3 | import * as Exit from "effect/Exit"; |
| 4 | import * as Result from "effect/Result"; |
| 5 | import * as Schema from "effect/Schema"; |
| 6 | import type { |
| 7 | PullRequestActor, |
| 8 | PullRequestCheck, |
| 9 | PullRequestCheckStatus, |
| 10 | PullRequestChecksState, |
| 11 | PullRequestComment, |
| 12 | PullRequestCommit, |
| 13 | PullRequestLabel, |
| 14 | PullRequestMergeability, |
| 15 | PullRequestMergeCapabilities, |
| 16 | PullRequestMergeMethod, |
| 17 | PullRequestReaction, |
| 18 | PullRequestReactionContent, |
| 19 | PullRequestReferenceCandidate, |
| 20 | PullRequestReviewDecision, |
| 21 | PullRequestConversationThread, |
| 22 | PullRequestReviewerCandidate, |
| 23 | PullRequestState, |
| 24 | } from "@t3tools/contracts"; |
| 25 | import { TrimmedNonEmptyString } from "@t3tools/contracts"; |
| 26 | import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath"; |
| 27 | import { decodeJsonResult } from "@t3tools/shared/schemaJson"; |
| 28 | import type { ProviderChangeRequestWatchFingerprint } from "@t3tools/source-control-core/server/PullRequestProvider"; |
| 29 | |
| 30 | /** Unknown pipeline or merge status values must not fail the whole payload. */ |
| 31 | const RawUserSchema = Schema.Struct({ |
| 32 | id: Schema.optional(Schema.Int), |
| 33 | username: Schema.String, |
| 34 | name: Schema.optional(Schema.NullOr(Schema.String)), |
| 35 | avatar_url: Schema.optional(Schema.NullOr(Schema.String)), |
| 36 | }); |
| 37 | |
| 38 | const RawPipelineSchema = Schema.Struct({ |
| 39 | id: Schema.optional(Schema.NullOr(Schema.Int)), |
| 40 | project_id: Schema.optional(Schema.NullOr(Schema.Int)), |
| 41 | status: Schema.optional(Schema.NullOr(Schema.String)), |
| 42 | web_url: Schema.optional(Schema.NullOr(Schema.String)), |
| 43 | source: Schema.optional(Schema.NullOr(Schema.String)), |
| 44 | }); |
| 45 | |
| 46 | const RawTriggerJobSchema = Schema.Struct({ |
| 47 | name: Schema.String, |
| 48 | allow_failure: Schema.optional(Schema.NullOr(Schema.Boolean)), |
| 49 | downstream_pipeline: Schema.optional(Schema.NullOr(RawPipelineSchema)), |
| 50 | }); |
| 51 | |
| 52 | const RawDiffRefs = Schema.Struct({ |
| 53 | base_sha: Schema.String, |
| 54 | head_sha: Schema.String, |
| 55 | start_sha: Schema.String, |
| 56 | }); |
| 57 | |
| 58 | const RawMergeRequestDiffRefs = Schema.Struct({ |
| 59 | base_sha: Schema.NullOr(Schema.String), |
| 60 | head_sha: Schema.NullOr(Schema.String), |
| 61 | start_sha: Schema.NullOr(Schema.String), |
| 62 | }); |
| 63 | |
| 64 | /** `with_labels_details=true` returns label objects; hosts that ignore it still send names. */ |
| 65 | const RawLabelRefSchema = Schema.Union([ |
| 66 | Schema.String, |
| 67 | Schema.Struct({ |
| 68 | name: Schema.String, |
| 69 | color: Schema.optional(Schema.NullOr(Schema.String)), |
| 70 | description: Schema.optional(Schema.NullOr(Schema.String)), |
| 71 | }), |
| 72 | ]); |
| 73 | |
| 74 | const RawMergeRequestSchema = Schema.Struct({ |
| 75 | iid: Schema.Int, |
| 76 | title: Schema.String, |
| 77 | web_url: Schema.String, |
| 78 | description: Schema.optional(Schema.NullOr(Schema.String)), |
| 79 | author: Schema.optional(Schema.NullOr(RawUserSchema)), |
| 80 | source_branch: Schema.String, |
| 81 | target_branch: Schema.String, |
| 82 | sha: Schema.optional(Schema.NullOr(Schema.String)), |
| 83 | state: Schema.optional(Schema.NullOr(Schema.String)), |
| 84 | draft: Schema.optional(Schema.Boolean), |
| 85 | work_in_progress: Schema.optional(Schema.Boolean), |
| 86 | detailed_merge_status: Schema.optional(Schema.NullOr(Schema.String)), |
| 87 | merge_status: Schema.optional(Schema.NullOr(Schema.String)), |
| 88 | has_conflicts: Schema.optional(Schema.NullOr(Schema.Boolean)), |
| 89 | created_at: Schema.String, |
| 90 | updated_at: Schema.String, |
| 91 | merged_at: Schema.optional(Schema.NullOr(Schema.String)), |
| 92 | closed_at: Schema.optional(Schema.NullOr(Schema.String)), |
| 93 | reviewers: Schema.optional(Schema.NullOr(Schema.Array(RawUserSchema))), |
| 94 | labels: Schema.optional(Schema.NullOr(Schema.Array(RawLabelRefSchema))), |
| 95 | // GitLab reports "1000+" past its counting limit. |
| 96 | changes_count: Schema.optional(Schema.NullOr(Schema.String)), |
| 97 | head_pipeline: Schema.optional(Schema.NullOr(RawPipelineSchema)), |
| 98 | user: Schema.optional( |
| 99 | Schema.NullOr(Schema.Struct({ can_merge: Schema.optional(Schema.Boolean) })), |
| 100 | ), |
| 101 | merge_when_pipeline_succeeds: Schema.optional(Schema.NullOr(Schema.Boolean)), |
| 102 | auto_merge_enabled: Schema.optional(Schema.NullOr(Schema.Boolean)), |
| 103 | squash_on_merge: Schema.optional(Schema.NullOr(Schema.Boolean)), |
| 104 | squash: Schema.optional(Schema.NullOr(Schema.Boolean)), |
| 105 | /** Only detail reads with include_diverged_commits_count return this expensive count. */ |
| 106 | diverged_commits_count: Schema.optional(Schema.NullOr(Schema.Int)), |
| 107 | source_project_id: Schema.optional(Schema.NullOr(Schema.Int)), |
| 108 | target_project_id: Schema.optional(Schema.NullOr(Schema.Int)), |
| 109 | /** Null on merge requests from the same project, where it means nothing. */ |
| 110 | allow_collaboration: Schema.optional(Schema.NullOr(Schema.Boolean)), |
| 111 | diff_refs: Schema.optional(Schema.NullOr(RawMergeRequestDiffRefs)), |
| 112 | }); |
| 113 | |
| 114 | const RawNoteSchema = Schema.Struct({ |
| 115 | id: Schema.Int, |
| 116 | body: Schema.optional(Schema.NullOr(Schema.String)), |
| 117 | author: Schema.optional(Schema.NullOr(RawUserSchema)), |
| 118 | created_at: Schema.String, |
| 119 | system: Schema.optional(Schema.Boolean), |
| 120 | type: Schema.optional(Schema.NullOr(Schema.String)), |
| 121 | position: Schema.optional( |
| 122 | Schema.NullOr( |
| 123 | Schema.Struct({ |
| 124 | new_path: Schema.optional(Schema.NullOr(Schema.String)), |
| 125 | old_path: Schema.optional(Schema.NullOr(Schema.String)), |
| 126 | }), |
| 127 | ), |
| 128 | ), |
| 129 | }); |
| 130 | |
| 131 | const RawDiscussionNoteSchema = Schema.Struct({ |
| 132 | id: Schema.Int, |
| 133 | body: Schema.optional(Schema.NullOr(Schema.String)), |
| 134 | author: Schema.optional(Schema.NullOr(RawUserSchema)), |
| 135 | created_at: Schema.String, |
| 136 | system: Schema.optional(Schema.Boolean), |
| 137 | resolvable: Schema.optional(Schema.Boolean), |
| 138 | resolved: Schema.optional(Schema.NullOr(Schema.Boolean)), |
| 139 | position: Schema.optional( |
| 140 | Schema.NullOr( |
| 141 | Schema.Struct({ |
| 142 | position_type: Schema.optional(Schema.NullOr(Schema.String)), |
| 143 | new_path: Schema.optional(Schema.NullOr(Schema.String)), |
| 144 | old_path: Schema.optional(Schema.NullOr(Schema.String)), |
| 145 | new_line: Schema.optional(Schema.NullOr(Schema.Int)), |
| 146 | old_line: Schema.optional(Schema.NullOr(Schema.Int)), |
| 147 | base_sha: Schema.optional(Schema.NullOr(Schema.String)), |
| 148 | start_sha: Schema.optional(Schema.NullOr(Schema.String)), |
| 149 | head_sha: Schema.optional(Schema.NullOr(Schema.String)), |
| 150 | }), |
| 151 | ), |
| 152 | ), |
| 153 | }); |
| 154 | |
| 155 | const RawDiscussionSchema = Schema.Struct({ |
| 156 | id: Schema.String, |
| 157 | notes: Schema.optional(Schema.NullOr(Schema.Array(RawDiscussionNoteSchema))), |
| 158 | }); |
| 159 | |
| 160 | const RawDiffRefsSchema = Schema.Struct({ |
| 161 | diff_refs: Schema.optional(Schema.NullOr(RawDiffRefs)), |
| 162 | }); |
| 163 | |
| 164 | const RawRevertTargetSchema = Schema.Struct({ |
| 165 | title: Schema.String, |
| 166 | state: Schema.String, |
| 167 | target_branch: Schema.String, |
| 168 | merge_commit_sha: Schema.optional(Schema.NullOr(Schema.String)), |
| 169 | squash_commit_sha: Schema.optional(Schema.NullOr(Schema.String)), |
| 170 | }); |
| 171 | |
| 172 | const RawCommitSchema = Schema.Struct({ |
| 173 | id: TrimmedNonEmptyString, |
| 174 | title: Schema.optional(Schema.NullOr(Schema.String)), |
| 175 | committed_date: Schema.optional(Schema.NullOr(Schema.String)), |
| 176 | created_at: Schema.optional(Schema.NullOr(Schema.String)), |
| 177 | parent_ids: Schema.optional(Schema.Array(Schema.String)), |
| 178 | author_name: Schema.optional(Schema.NullOr(Schema.String)), |
| 179 | author_email: Schema.optional(Schema.NullOr(Schema.String)), |
| 180 | stats: Schema.optional( |
| 181 | Schema.NullOr( |
| 182 | Schema.Struct({ |
| 183 | additions: Schema.optional(Schema.Int), |
| 184 | deletions: Schema.optional(Schema.Int), |
| 185 | }), |
| 186 | ), |
| 187 | ), |
| 188 | }); |
| 189 | |
| 190 | const RawDiffSchema = Schema.Struct({ |
| 191 | old_path: Schema.String, |
| 192 | new_path: Schema.String, |
| 193 | a_mode: Schema.optional(Schema.NullOr(Schema.String)), |
| 194 | b_mode: Schema.optional(Schema.NullOr(Schema.String)), |
| 195 | new_file: Schema.optional(Schema.Boolean), |
| 196 | renamed_file: Schema.optional(Schema.Boolean), |
| 197 | deleted_file: Schema.optional(Schema.Boolean), |
| 198 | diff: Schema.optional(Schema.NullOr(Schema.String)), |
| 199 | too_large: Schema.optional(Schema.NullOr(Schema.Boolean)), |
| 200 | collapsed: Schema.optional(Schema.NullOr(Schema.Boolean)), |
| 201 | }); |
| 202 | |
| 203 | const RawViewerSchema = Schema.Struct({ |
| 204 | username: Schema.optional(Schema.NullOr(Schema.String)), |
| 205 | }); |
| 206 | |
| 207 | const RawProjectMergeSettingsSchema = Schema.Struct({ |
| 208 | merge_method: Schema.optional(Schema.NullOr(Schema.String)), |
| 209 | squash_option: Schema.optional(Schema.NullOr(Schema.String)), |
| 210 | }); |
| 211 | |
| 212 | export interface GitLabMergeRequestListItem { |
| 213 | readonly number: number; |
| 214 | readonly title: string; |
| 215 | readonly url: string; |
| 216 | readonly author: PullRequestActor | null; |
| 217 | readonly headBranch: string; |
| 218 | readonly baseBranch: string; |
| 219 | readonly state: PullRequestState; |
| 220 | readonly isDraft: boolean; |
| 221 | readonly mergeability: PullRequestMergeability; |
| 222 | readonly rebaseRequired?: boolean | undefined; |
| 223 | readonly additions: number; |
| 224 | readonly deletions: number; |
| 225 | readonly createdAt: string; |
| 226 | readonly updatedAt: string; |
| 227 | readonly reviewRequestLogins: ReadonlyArray<string>; |
| 228 | readonly labels: ReadonlyArray<PullRequestLabel>; |
| 229 | } |
| 230 | |
| 231 | export interface GitLabMergeRequestDetail extends GitLabMergeRequestListItem { |
| 232 | readonly body: string; |
| 233 | readonly changedFiles: number; |
| 234 | readonly mergedAt: string | null; |
| 235 | readonly closedAt: string | null; |
| 236 | readonly reviewers: ReadonlyArray<PullRequestActor>; |
| 237 | readonly checks: ReadonlyArray<PullRequestCheck>; |
| 238 | readonly viewerCanMerge: boolean; |
| 239 | /** Read only for a closed or merged merge request; absent on an open one. */ |
| 240 | readonly viewerCanDeleteBranch?: boolean; |
| 241 | /** Set by the detail read, which asks GraphQL; REST carries no label permission. */ |
| 242 | readonly viewerCanEditLabels?: boolean; |
| 243 | /** Every reviewer id, even one without a username to show, since writes replace the set. */ |
| 244 | readonly reviewerIds: ReadonlyArray<number>; |
| 245 | /** The candidate list leads with these, since one page of project users need not reach them. */ |
| 246 | readonly reviewerUsers: ReadonlyArray<PullRequestActor & { readonly id: number }>; |
| 247 | readonly autoMergeEnabled?: boolean; |
| 248 | readonly autoMergeMethod?: PullRequestMergeMethod; |
| 249 | /** Absent means not counted, not up to date. */ |
| 250 | readonly divergedCommits?: number; |
| 251 | readonly headSha?: string; |
| 252 | readonly diffRefs?: GitLabDiffRefs; |
| 253 | /** On a fork the pipeline often belongs to the source project, not the target. */ |
| 254 | readonly headPipeline?: { readonly id: number; readonly projectId: number }; |
| 255 | /** Whether target maintainers may push to the source branch. Only set on merge requests from forks. */ |
| 256 | readonly maintainerCanModify?: boolean; |
| 257 | readonly viewerCanEditMaintainerEdits?: boolean; |
| 258 | } |
| 259 | |
| 260 | function toActor(raw: Schema.Schema.Type<typeof RawUserSchema> | null | undefined) { |
| 261 | const login = trimmed(raw?.username); |
| 262 | return login === null |
| 263 | ? null |
| 264 | : { login, name: trimmed(raw?.name), avatarUrl: trimmed(raw?.avatar_url) }; |
| 265 | } |
| 266 | |
| 267 | function toState( |
| 268 | raw: Pick<Schema.Schema.Type<typeof RawMergeRequestSchema>, "state" | "merged_at">, |
| 269 | ): PullRequestState { |
| 270 | if (trimmed(raw.merged_at) !== null) return "merged"; |
| 271 | switch (raw.state?.trim().toLowerCase()) { |
| 272 | case "merged": |
| 273 | return "merged"; |
| 274 | case "closed": |
| 275 | return "closed"; |
| 276 | default: |
| 277 | return "open"; |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | function toMergeability( |
| 282 | raw: Pick<Schema.Schema.Type<typeof RawMergeRequestSchema>, "has_conflicts" | "merge_status">, |
| 283 | ): PullRequestMergeability { |
| 284 | if (raw.has_conflicts === true) return "conflicting"; |
| 285 | switch (raw.merge_status?.trim().toLowerCase()) { |
| 286 | case "can_be_merged": |
| 287 | return "mergeable"; |
| 288 | case "cannot_be_merged": |
| 289 | return "conflicting"; |
| 290 | default: |
| 291 | return "unknown"; |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | function toLabels( |
| 296 | raw: ReadonlyArray<typeof RawLabelRefSchema.Type> | null | undefined, |
| 297 | ): ReadonlyArray<PullRequestLabel> { |
| 298 | return (raw ?? []).flatMap((label): ReadonlyArray<PullRequestLabel> => { |
| 299 | if (typeof label === "string") { |
| 300 | const name = trimmed(label); |
| 301 | return name === null ? [] : [{ name, color: null }]; |
| 302 | } |
| 303 | const name = trimmed(label.name); |
| 304 | return name === null |
| 305 | ? [] |
| 306 | : [{ name, color: trimmed(label.color), description: trimmed(label.description) }]; |
| 307 | }); |
| 308 | } |
| 309 | |
| 310 | function toChangedFiles(value: string | null | undefined): number { |
| 311 | const parsed = Number.parseInt(value?.trim() ?? "", 10); |
| 312 | return Number.isFinite(parsed) && parsed > 0 ? parsed : 0; |
| 313 | } |
| 314 | |
| 315 | function toPipelineStatus(value: string | null | undefined): PullRequestCheckStatus { |
| 316 | switch (value?.trim().toLowerCase()) { |
| 317 | case "success": |
| 318 | return "success"; |
| 319 | case "failed": |
| 320 | return "failure"; |
| 321 | case "canceled": |
| 322 | case "canceling": |
| 323 | return "cancelled"; |
| 324 | case "skipped": |
| 325 | return "skipped"; |
| 326 | case "manual": |
| 327 | return "neutral"; |
| 328 | default: |
| 329 | return "pending"; |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | function toChecks( |
| 334 | raw: Schema.Schema.Type<typeof RawMergeRequestSchema>, |
| 335 | ): ReadonlyArray<PullRequestCheck> { |
| 336 | const pipeline = raw.head_pipeline; |
| 337 | if (!pipeline) return []; |
| 338 | return [ |
| 339 | { |
| 340 | name: "Pipeline", |
| 341 | status: toPipelineStatus(pipeline.status), |
| 342 | description: trimmed(pipeline.source), |
| 343 | url: trimmed(pipeline.web_url), |
| 344 | }, |
| 345 | ]; |
| 346 | } |
| 347 | |
| 348 | export const PIPELINE_STAGES_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!) { |
| 349 | project(fullPath: $fullPath) { |
| 350 | mergeRequest(iid: $iid) { |
| 351 | headPipeline { |
| 352 | path |
| 353 | stages(first: 100) { |
| 354 | nodes { |
| 355 | name |
| 356 | status |
| 357 | detailedStatus { label detailsPath } |
| 358 | jobs(first: 100) { |
| 359 | nodes { |
| 360 | name status allowFailure retried webPath detailedStatus { label } |
| 361 | downstreamPipeline { status path } |
| 362 | } |
| 363 | pageInfo { hasNextPage } |
| 364 | } |
| 365 | } |
| 366 | pageInfo { hasNextPage } |
| 367 | } |
| 368 | } |
| 369 | } |
| 370 | } |
| 371 | }`; |
| 372 | |
| 373 | const OptionalString = Schema.optional(Schema.NullOr(Schema.String)); |
| 374 | |
| 375 | const RawStageJobSchema = Schema.Struct({ |
| 376 | name: OptionalString, |
| 377 | status: OptionalString, |
| 378 | allowFailure: Schema.optional(Schema.NullOr(Schema.Boolean)), |
| 379 | retried: Schema.optional(Schema.NullOr(Schema.Boolean)), |
| 380 | webPath: OptionalString, |
| 381 | detailedStatus: Schema.optional(Schema.NullOr(Schema.Struct({ label: OptionalString }))), |
| 382 | downstreamPipeline: Schema.optional( |
| 383 | Schema.NullOr(Schema.Struct({ status: OptionalString, path: OptionalString })), |
| 384 | ), |
| 385 | }); |
| 386 | |
| 387 | const RawStageSchema = Schema.Struct({ |
| 388 | name: OptionalString, |
| 389 | status: OptionalString, |
| 390 | detailedStatus: Schema.optional( |
| 391 | Schema.NullOr(Schema.Struct({ label: OptionalString, detailsPath: OptionalString })), |
| 392 | ), |
| 393 | jobs: Schema.optional( |
| 394 | Schema.NullOr( |
| 395 | Schema.Struct({ |
| 396 | nodes: Schema.Array(Schema.NullOr(RawStageJobSchema)), |
| 397 | pageInfo: Schema.optional( |
| 398 | Schema.NullOr( |
| 399 | Schema.Struct({ hasNextPage: Schema.optional(Schema.NullOr(Schema.Boolean)) }), |
| 400 | ), |
| 401 | ), |
| 402 | }), |
| 403 | ), |
| 404 | ), |
| 405 | }); |
| 406 | |
| 407 | const RawPipelineStagesSchema = Schema.Struct({ |
| 408 | errors: Schema.optional(Schema.NullOr(Schema.Array(Schema.Unknown))), |
| 409 | data: Schema.optional( |
| 410 | Schema.NullOr( |
| 411 | Schema.Struct({ |
| 412 | project: Schema.NullOr( |
| 413 | Schema.Struct({ |
| 414 | mergeRequest: Schema.NullOr( |
| 415 | Schema.Struct({ |
| 416 | headPipeline: Schema.NullOr( |
| 417 | Schema.Struct({ |
| 418 | path: OptionalString, |
| 419 | stages: Schema.optional( |
| 420 | Schema.NullOr( |
| 421 | Schema.Struct({ |
| 422 | nodes: Schema.Array(Schema.NullOr(RawStageSchema)), |
| 423 | pageInfo: Schema.optional( |
| 424 | Schema.NullOr( |
| 425 | Schema.Struct({ |
| 426 | hasNextPage: Schema.optional(Schema.NullOr(Schema.Boolean)), |
| 427 | }), |
| 428 | ), |
| 429 | ), |
| 430 | }), |
| 431 | ), |
| 432 | ), |
| 433 | }), |
| 434 | ), |
| 435 | }), |
| 436 | ), |
| 437 | }), |
| 438 | ), |
| 439 | }), |
| 440 | ), |
| 441 | ), |
| 442 | }); |
| 443 | |
| 444 | const decodePipelineStages = decodeJsonResult(RawPipelineStagesSchema); |
| 445 | |
| 446 | /** |
| 447 | * The head pipeline as one check per job, named after its stage. A stage whose jobs GitLab did |
| 448 | * not list whole stays one check with GitLab's stage status. Null where there are no stages to |
| 449 | * show, or GitLab returned only some of them, so the caller keeps the single pipeline check. |
| 450 | */ |
| 451 | export function decodePipelineStageChecksJson( |
| 452 | raw: string, |
| 453 | origin: string, |
| 454 | ): Result.Result<ReadonlyArray<PullRequestCheck> | null, DecodeFailure> { |
| 455 | const decoded = decodePipelineStages(raw); |
| 456 | if (!Result.isSuccess(decoded)) { |
| 457 | return Result.fail(decoded.failure); |
| 458 | } |
| 459 | const pipeline = decoded.success.data?.project?.mergeRequest?.headPipeline; |
| 460 | // Any stage left out could be the failed one, so a partial list is no list. |
| 461 | if ( |
| 462 | (decoded.success.errors?.length ?? 0) > 0 || |
| 463 | pipeline?.stages?.pageInfo?.hasNextPage === true || |
| 464 | pipeline?.stages?.nodes.some((stage) => stage === null || trimmed(stage.name) === null) === true |
| 465 | ) { |
| 466 | return Result.succeed(null); |
| 467 | } |
| 468 | const link = (path: string | null) => (path?.startsWith("/") ? `${origin}${path}` : null); |
| 469 | const checks: Array<PullRequestCheck> = []; |
| 470 | for (const stage of pipeline?.stages?.nodes ?? []) { |
| 471 | const name = trimmed(stage?.name); |
| 472 | if (stage === null || name === null) continue; |
| 473 | const jobs = stage.jobs?.nodes ?? []; |
| 474 | const listedWhole = |
| 475 | jobs.length > 0 && |
| 476 | stage.jobs?.pageInfo?.hasNextPage !== true && |
| 477 | jobs.every((job) => job !== null && trimmed(job.name) !== null); |
| 478 | if (!listedWhole) { |
| 479 | checks.push({ |
| 480 | name, |
| 481 | status: toPipelineStatus(stage.status), |
| 482 | description: trimmed(stage.detailedStatus?.label), |
| 483 | url: link(trimmed(stage.detailedStatus?.detailsPath) ?? trimmed(pipeline?.path)), |
| 484 | }); |
| 485 | continue; |
| 486 | } |
| 487 | for (const job of jobs) { |
| 488 | if (job === null || job.retried === true) continue; |
| 489 | // A trigger job reads as its downstream pipeline, as `decodeTriggerJobChecksJson` explains. |
| 490 | const downstream = job.downstreamPipeline; |
| 491 | const status = toPipelineStatus(downstream ? downstream.status : job.status); |
| 492 | checks.push({ |
| 493 | name: `${name} / ${trimmed(job.name)}`, |
| 494 | // The same reading as `manual`: GitLab was told this failure does not fail the pipeline. |
| 495 | status: status === "failure" && job.allowFailure === true ? "neutral" : status, |
| 496 | description: downstream ? "Downstream pipeline" : trimmed(job.detailedStatus?.label), |
| 497 | url: link(trimmed(downstream ? downstream.path : job.webPath)), |
| 498 | }); |
| 499 | } |
| 500 | } |
| 501 | return Result.succeed(checks.length === 0 ? null : checks); |
| 502 | } |
| 503 | |
| 504 | function toListItem( |
| 505 | raw: Schema.Schema.Type<typeof RawMergeRequestSchema>, |
| 506 | ): GitLabMergeRequestListItem { |
| 507 | const detailedMergeStatus = raw.detailed_merge_status?.trim().toLowerCase(); |
| 508 | return { |
| 509 | number: raw.iid, |
| 510 | title: raw.title, |
| 511 | url: raw.web_url, |
| 512 | author: toActor(raw.author), |
| 513 | headBranch: raw.source_branch, |
| 514 | baseBranch: raw.target_branch, |
| 515 | state: toState(raw), |
| 516 | isDraft: raw.draft ?? raw.work_in_progress ?? false, |
| 517 | mergeability: toMergeability(raw), |
| 518 | rebaseRequired: |
| 519 | detailedMergeStatus === "need_rebase" |
| 520 | ? true |
| 521 | : detailedMergeStatus === "mergeable" |
| 522 | ? false |
| 523 | : undefined, |
| 524 | additions: 0, |
| 525 | deletions: 0, |
| 526 | createdAt: raw.created_at, |
| 527 | updatedAt: raw.updated_at, |
| 528 | reviewRequestLogins: (raw.reviewers ?? []).flatMap((reviewer) => { |
| 529 | const login = trimmed(reviewer.username); |
| 530 | return login === null ? [] : [login]; |
| 531 | }), |
| 532 | labels: toLabels(raw.labels), |
| 533 | }; |
| 534 | } |
| 535 | |
| 536 | function toDetail(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): GitLabMergeRequestDetail { |
| 537 | const listItem = toListItem(raw); |
| 538 | const headSha = trimmed(raw.sha); |
| 539 | const refs = raw.diff_refs; |
| 540 | const diffRefs = |
| 541 | refs && refs.base_sha !== null && refs.head_sha !== null && refs.start_sha !== null |
| 542 | ? toDiffRefs({ base_sha: refs.base_sha, head_sha: refs.head_sha, start_sha: refs.start_sha }) |
| 543 | : null; |
| 544 | const autoMerge = |
| 545 | raw.merge_when_pipeline_succeeds == null && raw.auto_merge_enabled == null |
| 546 | ? undefined |
| 547 | : raw.merge_when_pipeline_succeeds === true || raw.auto_merge_enabled === true; |
| 548 | return { |
| 549 | ...listItem, |
| 550 | body: raw.description ?? "", |
| 551 | changedFiles: toChangedFiles(raw.changes_count), |
| 552 | mergedAt: trimmed(raw.merged_at), |
| 553 | closedAt: trimmed(raw.closed_at), |
| 554 | reviewers: (raw.reviewers ?? []).flatMap((reviewer) => { |
| 555 | const actor = toActor(reviewer); |
| 556 | return actor === null ? [] : [actor]; |
| 557 | }), |
| 558 | checks: toChecks(raw), |
| 559 | viewerCanMerge: raw.user?.can_merge !== false, |
| 560 | reviewerIds: (raw.reviewers ?? []).flatMap((reviewer) => |
| 561 | reviewer.id === undefined ? [] : [reviewer.id], |
| 562 | ), |
| 563 | reviewerUsers: (raw.reviewers ?? []).flatMap((reviewer) => { |
| 564 | const actor = toActor(reviewer); |
| 565 | return actor === null || reviewer.id === undefined ? [] : [{ ...actor, id: reviewer.id }]; |
| 566 | }), |
| 567 | ...(autoMerge === undefined ? {} : { autoMergeEnabled: autoMerge }), |
| 568 | ...(autoMerge === true && raw.squash_on_merge === true |
| 569 | ? { autoMergeMethod: "squash" as const } |
| 570 | : {}), |
| 571 | ...(raw.diverged_commits_count == null ? {} : { divergedCommits: raw.diverged_commits_count }), |
| 572 | ...(headSha === null ? {} : { headSha }), |
| 573 | ...(diffRefs === null ? {} : { diffRefs }), |
| 574 | ...(raw.head_pipeline?.id == null || raw.head_pipeline.project_id == null |
| 575 | ? {} |
| 576 | : { headPipeline: { id: raw.head_pipeline.id, projectId: raw.head_pipeline.project_id } }), |
| 577 | ...(raw.source_project_id != null && |
| 578 | raw.target_project_id != null && |
| 579 | raw.source_project_id !== raw.target_project_id |
| 580 | ? { maintainerCanModify: raw.allow_collaboration === true } |
| 581 | : {}), |
| 582 | }; |
| 583 | } |
| 584 | |
| 585 | const decodeUnknownList = decodeJsonResult(Schema.Array(Schema.Unknown)); |
| 586 | const decodeMergeRequestEntry = Schema.decodeUnknownExit(RawMergeRequestSchema); |
| 587 | const decodeMergeRequest = decodeJsonResult(RawMergeRequestSchema); |
| 588 | const decodeTriggerJobEntry = Schema.decodeUnknownExit(RawTriggerJobSchema); |
| 589 | const decodeNoteEntry = Schema.decodeUnknownExit(RawNoteSchema); |
| 590 | const decodeUserEntry = Schema.decodeUnknownExit(RawUserSchema); |
| 591 | const decodeCommitEntry = Schema.decodeUnknownExit(RawCommitSchema); |
| 592 | const decodeCommit = decodeJsonResult(RawCommitSchema); |
| 593 | const decodeMergeRequestChanges = decodeJsonResult( |
| 594 | Schema.Struct({ |
| 595 | changes: Schema.Array(Schema.Unknown), |
| 596 | overflow: Schema.optional(Schema.Boolean), |
| 597 | changes_count: Schema.optional(Schema.NullOr(Schema.String)), |
| 598 | }), |
| 599 | ); |
| 600 | const decodeDiffEntry = Schema.decodeUnknownExit(RawDiffSchema); |
| 601 | const decodeDiscussionEntry = Schema.decodeUnknownExit(RawDiscussionSchema); |
| 602 | const decodeDiffRefs = decodeJsonResult(RawDiffRefsSchema); |
| 603 | const decodeRevertTarget = decodeJsonResult(RawRevertTargetSchema); |
| 604 | const decodeViewer = decodeJsonResult(RawViewerSchema); |
| 605 | const decodeProjectMergeSettings = decodeJsonResult(RawProjectMergeSettingsSchema); |
| 606 | |
| 607 | type DecodeFailure = Cause.Cause<Schema.SchemaError>; |
| 608 | |
| 609 | export interface GitLabProjectUsers { |
| 610 | readonly candidates: ReadonlyArray<PullRequestReviewerCandidate>; |
| 611 | /** Count before decoding to avoid ending pagination on skipped rows. */ |
| 612 | readonly rawCount: number; |
| 613 | } |
| 614 | |
| 615 | export interface GitLabMergeRequestListBatch { |
| 616 | readonly items: ReadonlyArray<GitLabMergeRequestListItem>; |
| 617 | readonly rawIndexes: ReadonlyArray<number>; |
| 618 | readonly rawCount: number; |
| 619 | } |
| 620 | |
| 621 | export function decodeMergeRequestListJson( |
| 622 | raw: string, |
| 623 | ): Result.Result<GitLabMergeRequestListBatch, DecodeFailure> { |
| 624 | const decoded = decodeUnknownList(raw); |
| 625 | if (!Result.isSuccess(decoded)) { |
| 626 | return Result.fail(decoded.failure); |
| 627 | } |
| 628 | const items: GitLabMergeRequestListItem[] = []; |
| 629 | const rawIndexes: number[] = []; |
| 630 | for (const [rawIndex, entry] of decoded.success.entries()) { |
| 631 | const item = decodeMergeRequestEntry(entry); |
| 632 | if (Exit.isSuccess(item)) { |
| 633 | items.push(toListItem(item.value)); |
| 634 | rawIndexes.push(rawIndex); |
| 635 | } |
| 636 | } |
| 637 | return Result.succeed({ items, rawIndexes, rawCount: decoded.success.length }); |
| 638 | } |
| 639 | |
| 640 | export function decodeMergeRequestDetailJson( |
| 641 | raw: string, |
| 642 | ): Result.Result<GitLabMergeRequestDetail, DecodeFailure> { |
| 643 | const decoded = decodeMergeRequest(raw); |
| 644 | return Result.isSuccess(decoded) |
| 645 | ? Result.succeed(toDetail(decoded.success)) |
| 646 | : Result.fail(decoded.failure); |
| 647 | } |
| 648 | |
| 649 | export interface GitLabTriggerJobChecks { |
| 650 | readonly checks: ReadonlyArray<PullRequestCheck>; |
| 651 | readonly rawCount: number; |
| 652 | } |
| 653 | |
| 654 | /** |
| 655 | * Without `strategy: depend` a trigger job succeeds as soon as it starts its downstream |
| 656 | * pipeline, so the head pipeline stays green when that pipeline fails. Each row carries the |
| 657 | * downstream pipeline's own status instead of the trigger job's. |
| 658 | */ |
| 659 | export function decodeTriggerJobChecksJson( |
| 660 | raw: string, |
| 661 | ): Result.Result<GitLabTriggerJobChecks, DecodeFailure> { |
| 662 | const decoded = decodeUnknownList(raw); |
| 663 | if (!Result.isSuccess(decoded)) { |
| 664 | return Result.fail(decoded.failure); |
| 665 | } |
| 666 | const checks: PullRequestCheck[] = []; |
| 667 | for (const entry of decoded.success) { |
| 668 | const job = decodeTriggerJobEntry(entry); |
| 669 | if (Exit.isFailure(job)) continue; |
| 670 | const name = trimmed(job.value.name); |
| 671 | const downstream = job.value.downstream_pipeline; |
| 672 | if (name === null || !downstream) continue; |
| 673 | const status = toPipelineStatus(downstream.status); |
| 674 | checks.push({ |
| 675 | name, |
| 676 | // The same reading as `manual`: GitLab was told this failure does not fail the pipeline. |
| 677 | status: status === "failure" && job.value.allow_failure === true ? "neutral" : status, |
| 678 | description: "Downstream pipeline", |
| 679 | url: trimmed(downstream.web_url), |
| 680 | }); |
| 681 | } |
| 682 | return Result.succeed({ checks, rawCount: decoded.success.length }); |
| 683 | } |
| 684 | |
| 685 | export function decodeViewerJson(raw: string): Result.Result<string | null, DecodeFailure> { |
| 686 | const decoded = decodeViewer(raw); |
| 687 | return Result.isSuccess(decoded) |
| 688 | ? Result.succeed(trimmed(decoded.success.username)) |
| 689 | : Result.fail(decoded.failure); |
| 690 | } |
| 691 | |
| 692 | export function decodeProjectUsersJson( |
| 693 | raw: string, |
| 694 | ): Result.Result<GitLabProjectUsers, DecodeFailure> { |
| 695 | const decoded = decodeUnknownList(raw); |
| 696 | if (!Result.isSuccess(decoded)) { |
| 697 | return Result.fail(decoded.failure); |
| 698 | } |
| 699 | const candidates: PullRequestReviewerCandidate[] = []; |
| 700 | for (const entry of decoded.success) { |
| 701 | const user = decodeUserEntry(entry); |
| 702 | if (Exit.isFailure(user) || user.value.id === undefined) continue; |
| 703 | const actor = toActor(user.value); |
| 704 | if (actor === null) continue; |
| 705 | candidates.push({ |
| 706 | ...actor, |
| 707 | id: String(user.value.id), |
| 708 | kind: "user", |
| 709 | isRequested: false, |
| 710 | }); |
| 711 | } |
| 712 | return Result.succeed({ candidates, rawCount: decoded.success.length }); |
| 713 | } |
| 714 | |
| 715 | const RawReferenceSchema = Schema.Struct({ |
| 716 | iid: Schema.Number, |
| 717 | title: Schema.String, |
| 718 | state: Schema.String, |
| 719 | }); |
| 720 | const decodeReferenceEntry = Schema.decodeUnknownExit(RawReferenceSchema); |
| 721 | |
| 722 | /** A list of issues (`#`) or merge requests (`!`), as composers reference them. */ |
| 723 | export function decodeReferenceCandidatesJson( |
| 724 | raw: string, |
| 725 | kind: PullRequestReferenceCandidate["kind"], |
| 726 | ): Result.Result< |
| 727 | { readonly items: ReadonlyArray<PullRequestReferenceCandidate>; readonly rawCount: number }, |
| 728 | DecodeFailure |
| 729 | > { |
| 730 | const decoded = decodeUnknownList(raw); |
| 731 | if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure); |
| 732 | const items: PullRequestReferenceCandidate[] = []; |
| 733 | for (const entry of decoded.success) { |
| 734 | const reference = decodeReferenceEntry(entry); |
| 735 | if (Exit.isFailure(reference) || !Number.isInteger(reference.value.iid)) continue; |
| 736 | if (reference.value.iid < 1) continue; |
| 737 | const { iid, title, state } = reference.value; |
| 738 | items.push({ |
| 739 | reference: `${kind === "issue" ? "#" : "!"}${iid}`, |
| 740 | kind, |
| 741 | number: iid, |
| 742 | title, |
| 743 | state: state === "merged" ? "merged" : state === "opened" ? "open" : "closed", |
| 744 | }); |
| 745 | } |
| 746 | return Result.succeed({ items, rawCount: decoded.success.length }); |
| 747 | } |
| 748 | |
| 749 | const RawLabelSchema = Schema.Struct({ |
| 750 | name: Schema.String, |
| 751 | color: Schema.optional(Schema.NullOr(Schema.String)), |
| 752 | description: Schema.optional(Schema.NullOr(Schema.String)), |
| 753 | archived: Schema.optional(Schema.Boolean), |
| 754 | }); |
| 755 | const decodeLabelEntry = Schema.decodeUnknownExit(RawLabelSchema); |
| 756 | const decodeLabel = decodeJsonResult(RawLabelSchema); |
| 757 | |
| 758 | export function decodeLabelNameJson(raw: string): Result.Result<string | null, DecodeFailure> { |
| 759 | return Result.map(decodeLabel(raw), (label) => trimmed(label.name)); |
| 760 | } |
| 761 | |
| 762 | export interface GitLabProjectLabel extends PullRequestLabel { |
| 763 | readonly description: string | null; |
| 764 | readonly archived: boolean; |
| 765 | } |
| 766 | |
| 767 | export interface GitLabProjectLabels { |
| 768 | readonly labels: ReadonlyArray<GitLabProjectLabel>; |
| 769 | readonly rawCount: number; |
| 770 | } |
| 771 | |
| 772 | export function decodeProjectLabelsJson( |
| 773 | raw: string, |
| 774 | ): Result.Result<GitLabProjectLabels, DecodeFailure> { |
| 775 | const decoded = decodeUnknownList(raw); |
| 776 | if (!Result.isSuccess(decoded)) { |
| 777 | return Result.fail(decoded.failure); |
| 778 | } |
| 779 | const labels: GitLabProjectLabel[] = []; |
| 780 | for (const entry of decoded.success) { |
| 781 | const label = decodeLabelEntry(entry); |
| 782 | if (Exit.isFailure(label)) continue; |
| 783 | const name = trimmed(label.value.name); |
| 784 | if (name !== null) { |
| 785 | labels.push({ |
| 786 | name, |
| 787 | color: trimmed(label.value.color), |
| 788 | description: trimmed(label.value.description), |
| 789 | archived: label.value.archived === true, |
| 790 | }); |
| 791 | } |
| 792 | } |
| 793 | return Result.succeed({ labels, rawCount: decoded.success.length }); |
| 794 | } |
| 795 | |
| 796 | export function decodeProjectMergeCapabilitiesJson( |
| 797 | raw: string, |
| 798 | ): Result.Result<PullRequestMergeCapabilities, DecodeFailure> { |
| 799 | const decoded = decodeProjectMergeSettings(raw); |
| 800 | if (!Result.isSuccess(decoded)) { |
| 801 | return Result.fail(decoded.failure); |
| 802 | } |
| 803 | const mergeMethod = decoded.success.merge_method?.trim().toLowerCase(); |
| 804 | const squashOption = decoded.success.squash_option?.trim().toLowerCase(); |
| 805 | return Result.succeed({ |
| 806 | merge: mergeMethod === "merge", |
| 807 | rebase: mergeMethod === "rebase_merge" || mergeMethod === "ff", |
| 808 | squash: |
| 809 | squashOption === "always" || squashOption === "default_on" || squashOption === "default_off", |
| 810 | }); |
| 811 | } |
| 812 | |
| 813 | export interface GitLabDiffRefs { |
| 814 | readonly baseSha: string; |
| 815 | readonly headSha: string; |
| 816 | readonly startSha: string; |
| 817 | } |
| 818 | |
| 819 | export interface GitLabDiscussions { |
| 820 | readonly threads: ReadonlyArray<PullRequestConversationThread>; |
| 821 | /** GitLab moves a thread onto each new diff that still has its line; this is the last one. */ |
| 822 | readonly diffRefsByThreadId: ReadonlyMap<string, GitLabDiffRefs>; |
| 823 | /** First notes of unresolved discussions on the MR itself rather than a diff line. */ |
| 824 | readonly overviewFindingIds: ReadonlyArray<string>; |
| 825 | readonly rawCount: number; |
| 826 | } |
| 827 | |
| 828 | function toDiffRefs(raw: Schema.Schema.Type<typeof RawDiffRefs>): GitLabDiffRefs { |
| 829 | return { baseSha: raw.base_sha, headSha: raw.head_sha, startSha: raw.start_sha }; |
| 830 | } |
| 831 | |
| 832 | export function decodeDiscussionsJson( |
| 833 | raw: string, |
| 834 | ): Result.Result<GitLabDiscussions, DecodeFailure> { |
| 835 | const decoded = decodeUnknownList(raw); |
| 836 | if (!Result.isSuccess(decoded)) { |
| 837 | return Result.fail(decoded.failure); |
| 838 | } |
| 839 | const threads: PullRequestConversationThread[] = []; |
| 840 | const diffRefsByThreadId = new Map<string, GitLabDiffRefs>(); |
| 841 | const overviewFindingIds: string[] = []; |
| 842 | for (const entry of decoded.success) { |
| 843 | const discussion = decodeDiscussionEntry(entry); |
| 844 | if (!Exit.isSuccess(discussion)) continue; |
| 845 | const notes = (discussion.value.notes ?? []).filter((note) => note.system !== true); |
| 846 | const root = notes[0]; |
| 847 | if (root === undefined) continue; |
| 848 | const comments = notes.map((note) => ({ |
| 849 | id: String(note.id), |
| 850 | author: toActor(note.author), |
| 851 | body: note.body ?? "", |
| 852 | createdAt: note.created_at, |
| 853 | url: null, |
| 854 | })); |
| 855 | const position = root.position; |
| 856 | if (!position) { |
| 857 | // A thread started on the overview: resolvable, unlike a single comment. |
| 858 | if (root.resolvable !== true) continue; |
| 859 | if (root.resolved !== true) overviewFindingIds.push(String(root.id)); |
| 860 | threads.push({ |
| 861 | id: discussion.value.id, |
| 862 | path: null, |
| 863 | line: null, |
| 864 | side: "right", |
| 865 | isResolved: root.resolved === true, |
| 866 | isOutdated: false, |
| 867 | comments, |
| 868 | }); |
| 869 | continue; |
| 870 | } |
| 871 | let side: "left" | "right"; |
| 872 | let path: string | null; |
| 873 | let line: number | null | undefined; |
| 874 | if (position.position_type === "text") { |
| 875 | side = position.new_line === null || position.new_line === undefined ? "left" : "right"; |
| 876 | path = trimmed(side === "left" ? position.old_path : position.new_path); |
| 877 | line = side === "left" ? position.old_line : position.new_line; |
| 878 | } else if (position.position_type === "file" || position.position_type === "image") { |
| 879 | side = "right"; |
| 880 | path = trimmed(position.new_path) ?? trimmed(position.old_path); |
| 881 | line = null; |
| 882 | } else { |
| 883 | continue; |
| 884 | } |
| 885 | if (path === null) continue; |
| 886 | if (position.base_sha && position.start_sha && position.head_sha) { |
| 887 | diffRefsByThreadId.set(discussion.value.id, { |
| 888 | baseSha: position.base_sha, |
| 889 | startSha: position.start_sha, |
| 890 | headSha: position.head_sha, |
| 891 | }); |
| 892 | } |
| 893 | threads.push({ |
| 894 | id: discussion.value.id, |
| 895 | path, |
| 896 | line: typeof line === "number" && line > 0 ? line : null, |
| 897 | side, |
| 898 | isResolved: root.resolved === true, |
| 899 | isOutdated: false, |
| 900 | comments, |
| 901 | }); |
| 902 | } |
| 903 | return Result.succeed({ |
| 904 | threads, |
| 905 | diffRefsByThreadId, |
| 906 | overviewFindingIds, |
| 907 | rawCount: decoded.success.length, |
| 908 | }); |
| 909 | } |
| 910 | |
| 911 | export function decodeDiffRefsJson( |
| 912 | raw: string, |
| 913 | ): Result.Result<GitLabDiffRefs | null, DecodeFailure> { |
| 914 | const decoded = decodeDiffRefs(raw); |
| 915 | if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure); |
| 916 | const refs = decoded.success.diff_refs; |
| 917 | return Result.succeed(refs ? toDiffRefs(refs) : null); |
| 918 | } |
| 919 | |
| 920 | export interface GitLabRevertTarget { |
| 921 | readonly merged: boolean; |
| 922 | readonly title: string; |
| 923 | readonly targetBranch: string; |
| 924 | /** Null for a fast-forward merge without squash, which records neither SHA. */ |
| 925 | readonly commitSha: string | null; |
| 926 | } |
| 927 | |
| 928 | export function decodeRevertTargetJson( |
| 929 | raw: string, |
| 930 | ): Result.Result<GitLabRevertTarget, DecodeFailure> { |
| 931 | const decoded = decodeRevertTarget(raw); |
| 932 | if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure); |
| 933 | const mr = decoded.success; |
| 934 | return Result.succeed({ |
| 935 | merged: mr.state === "merged", |
| 936 | title: mr.title, |
| 937 | targetBranch: mr.target_branch, |
| 938 | commitSha: trimmed(mr.merge_commit_sha) ?? trimmed(mr.squash_commit_sha), |
| 939 | }); |
| 940 | } |
| 941 | |
| 942 | export function decodeNotesJson( |
| 943 | raw: string, |
| 944 | ): Result.Result< |
| 945 | { readonly comments: ReadonlyArray<PullRequestComment>; readonly rawCount: number }, |
| 946 | DecodeFailure |
| 947 | > { |
| 948 | const decoded = decodeUnknownList(raw); |
| 949 | if (!Result.isSuccess(decoded)) { |
| 950 | return Result.fail(decoded.failure); |
| 951 | } |
| 952 | const comments: PullRequestComment[] = []; |
| 953 | for (const entry of decoded.success) { |
| 954 | const note = decodeNoteEntry(entry); |
| 955 | if (Exit.isFailure(note)) continue; |
| 956 | const value = note.value; |
| 957 | if (value.system === true) continue; |
| 958 | const body = value.body ?? ""; |
| 959 | if (body.trim().length === 0) continue; |
| 960 | const isDiffNote = value.type?.trim() === "DiffNote"; |
| 961 | comments.push({ |
| 962 | id: String(value.id), |
| 963 | kind: isDiffNote ? "review-comment" : "issue-comment", |
| 964 | author: toActor(value.author), |
| 965 | body, |
| 966 | createdAt: value.created_at, |
| 967 | url: null, |
| 968 | path: trimmed(value.position?.new_path) ?? trimmed(value.position?.old_path), |
| 969 | reviewState: null, |
| 970 | }); |
| 971 | } |
| 972 | return Result.succeed({ comments, rawCount: decoded.success.length }); |
| 973 | } |
| 974 | |
| 975 | export function decodeCommitsJson( |
| 976 | raw: string, |
| 977 | ): Result.Result<ReadonlyArray<PullRequestCommit>, DecodeFailure> { |
| 978 | const decoded = decodeUnknownList(raw); |
| 979 | if (!Result.isSuccess(decoded)) { |
| 980 | return Result.fail(decoded.failure); |
| 981 | } |
| 982 | const commits: PullRequestCommit[] = []; |
| 983 | for (const entry of decoded.success) { |
| 984 | const commit = decodeCommitEntry(entry); |
| 985 | if (Exit.isFailure(commit)) continue; |
| 986 | const committedDate = trimmed(commit.value.committed_date) ?? trimmed(commit.value.created_at); |
| 987 | if (committedDate === null) continue; |
| 988 | commits.push({ |
| 989 | oid: commit.value.id, |
| 990 | messageHeadline: commit.value.title ?? "", |
| 991 | committedDate, |
| 992 | ...(commit.value.stats === null || commit.value.stats === undefined |
| 993 | ? {} |
| 994 | : { |
| 995 | additions: Math.max(0, commit.value.stats.additions ?? 0), |
| 996 | deletions: Math.max(0, commit.value.stats.deletions ?? 0), |
| 997 | }), |
| 998 | authors: (() => { |
| 999 | const login = trimmed(commit.value.author_name) ?? trimmed(commit.value.author_email); |
| 1000 | return login === null |
| 1001 | ? [] |
| 1002 | : [{ login, name: trimmed(commit.value.author_name), avatarUrl: null }]; |
| 1003 | })(), |
| 1004 | }); |
| 1005 | } |
| 1006 | return Result.succeed(commits.toReversed()); |
| 1007 | } |
| 1008 | |
| 1009 | export function decodeCommitDiffRefsJson( |
| 1010 | raw: string, |
| 1011 | ): Result.Result<GitLabDiffRefs | null, DecodeFailure> { |
| 1012 | const decoded = decodeCommit(raw); |
| 1013 | if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure); |
| 1014 | const baseSha = trimmed(decoded.success.parent_ids?.[0]); |
| 1015 | const headSha = trimmed(decoded.success.id); |
| 1016 | return Result.succeed( |
| 1017 | baseSha === null || headSha === null ? null : { baseSha, headSha, startSha: baseSha }, |
| 1018 | ); |
| 1019 | } |
| 1020 | |
| 1021 | function diffHeaderPaths(raw: Schema.Schema.Type<typeof RawDiffSchema>): { |
| 1022 | readonly from: string; |
| 1023 | readonly to: string; |
| 1024 | } { |
| 1025 | return { |
| 1026 | from: raw.new_file === true ? "/dev/null" : quoteGitPatchPath(`a/${raw.old_path}`), |
| 1027 | to: raw.deleted_file === true ? "/dev/null" : quoteGitPatchPath(`b/${raw.new_path}`), |
| 1028 | }; |
| 1029 | } |
| 1030 | |
| 1031 | export interface GitLabMergeRequestPatch { |
| 1032 | readonly patch: string; |
| 1033 | readonly truncated: boolean; |
| 1034 | readonly rawCount: number; |
| 1035 | /** Files GitLab sent without their diff because they are too large or collapsed. */ |
| 1036 | readonly withheldPaths: ReadonlyArray<string>; |
| 1037 | } |
| 1038 | |
| 1039 | export function decodeMergeRequestDiffsJson( |
| 1040 | raw: string, |
| 1041 | ): Result.Result<GitLabMergeRequestPatch, DecodeFailure> { |
| 1042 | const decoded = decodeUnknownList(raw); |
| 1043 | if (!Result.isSuccess(decoded)) { |
| 1044 | return Result.fail(decoded.failure); |
| 1045 | } |
| 1046 | return Result.succeed(mergeRequestPatch(decoded.success)); |
| 1047 | } |
| 1048 | |
| 1049 | /** Older GitLab instances return all files in a non-paginated merge request wrapper. */ |
| 1050 | export function decodeMergeRequestChangesJson( |
| 1051 | raw: string, |
| 1052 | ): Result.Result<GitLabMergeRequestPatch, DecodeFailure> { |
| 1053 | const decoded = decodeMergeRequestChanges(raw); |
| 1054 | if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure); |
| 1055 | const patch = mergeRequestPatch(decoded.success.changes); |
| 1056 | return Result.succeed({ |
| 1057 | ...patch, |
| 1058 | truncated: |
| 1059 | patch.truncated || |
| 1060 | decoded.success.overflow === true || |
| 1061 | decoded.success.changes_count?.endsWith("+") === true, |
| 1062 | }); |
| 1063 | } |
| 1064 | |
| 1065 | function mergeRequestPatch(entries: ReadonlyArray<unknown>): GitLabMergeRequestPatch { |
| 1066 | const sections: string[] = []; |
| 1067 | const withheldPaths: string[] = []; |
| 1068 | let truncated = false; |
| 1069 | for (const entry of entries) { |
| 1070 | const file = decodeDiffEntry(entry); |
| 1071 | if (Exit.isFailure(file)) { |
| 1072 | truncated = true; |
| 1073 | continue; |
| 1074 | } |
| 1075 | const value = file.value; |
| 1076 | const hunks = value.diff ?? ""; |
| 1077 | if (hunks.length === 0 && (value.too_large === true || value.collapsed === true)) { |
| 1078 | truncated = true; |
| 1079 | withheldPaths.push(value.new_path); |
| 1080 | } |
| 1081 | const { from, to } = diffHeaderPaths(value); |
| 1082 | const header = [ |
| 1083 | `diff --git ${quoteGitPatchPath(`a/${value.old_path}`)} ${quoteGitPatchPath(`b/${value.new_path}`)}`, |
| 1084 | ...(value.new_file === true ? [`new file mode ${value.b_mode ?? "100644"}`] : []), |
| 1085 | ...(value.deleted_file === true ? [`deleted file mode ${value.a_mode ?? "100644"}`] : []), |
| 1086 | ...(value.renamed_file === true |
| 1087 | ? [ |
| 1088 | // GitLab has no similarity score; Pierre needs this header to keep the rename. |
| 1089 | `similarity index ${hunks.length > 0 || value.too_large === true || value.collapsed === true ? 0 : 100}%`, |
| 1090 | `rename from ${quoteGitPatchPath(value.old_path)}`, |
| 1091 | `rename to ${quoteGitPatchPath(value.new_path)}`, |
| 1092 | ] |
| 1093 | : []), |
| 1094 | `--- ${from}`, |
| 1095 | `+++ ${to}`, |
| 1096 | ].join("\n"); |
| 1097 | sections.push(hunks.length === 0 ? header : `${header}\n${hunks.replace(/\n?$/, "\n")}`); |
| 1098 | } |
| 1099 | return { |
| 1100 | patch: sections.join("\n"), |
| 1101 | truncated, |
| 1102 | rawCount: entries.length, |
| 1103 | withheldPaths, |
| 1104 | }; |
| 1105 | } |
| 1106 | |
| 1107 | const GITLAB_AWARD_BY_CONTENT: Readonly<Record<PullRequestReactionContent, string>> = { |
| 1108 | "thumbs-up": "thumbsup", |
| 1109 | "thumbs-down": "thumbsdown", |
| 1110 | laugh: "laughing", |
| 1111 | hooray: "tada", |
| 1112 | confused: "confused", |
| 1113 | heart: "heart", |
| 1114 | rocket: "rocket", |
| 1115 | eyes: "eyes", |
| 1116 | }; |
| 1117 | |
| 1118 | const CONTENT_BY_GITLAB_AWARD: Readonly<Record<string, PullRequestReactionContent>> = |
| 1119 | Object.fromEntries( |
| 1120 | Object.entries(GITLAB_AWARD_BY_CONTENT).map(([content, name]) => [name, content]), |
| 1121 | ) as Readonly<Record<string, PullRequestReactionContent>>; |
| 1122 | |
| 1123 | export function gitLabAwardName(content: PullRequestReactionContent): string { |
| 1124 | return GITLAB_AWARD_BY_CONTENT[content]; |
| 1125 | } |
| 1126 | |
| 1127 | export const AWARD_EMOJI_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!, $cursor: String) { |
| 1128 | currentUser { username } |
| 1129 | project(fullPath: $fullPath) { |
| 1130 | mergeRequest(iid: $iid) { |
| 1131 | awardEmoji { nodes { name user { username } } } |
| 1132 | notes(first: 100, after: $cursor) { |
| 1133 | pageInfo { hasNextPage endCursor } |
| 1134 | nodes { id author { username bot } lastEditedAt lastEditedBy { username } resolved awardEmoji { nodes { name user { username } } } } |
| 1135 | } |
| 1136 | } |
| 1137 | } |
| 1138 | }`; |
| 1139 | |
| 1140 | const RawAwardEmojiNodesSchema = Schema.optional( |
| 1141 | Schema.NullOr( |
| 1142 | Schema.Struct({ |
| 1143 | nodes: Schema.optional( |
| 1144 | Schema.NullOr( |
| 1145 | Schema.Array( |
| 1146 | Schema.NullOr( |
| 1147 | Schema.Struct({ |
| 1148 | name: Schema.optional(Schema.NullOr(Schema.String)), |
| 1149 | user: Schema.optional( |
| 1150 | Schema.NullOr( |
| 1151 | Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) }), |
| 1152 | ), |
| 1153 | ), |
| 1154 | }), |
| 1155 | ), |
| 1156 | ), |
| 1157 | ), |
| 1158 | ), |
| 1159 | }), |
| 1160 | ), |
| 1161 | ); |
| 1162 | |
| 1163 | const RawAwardEmojiPageSchema = Schema.Struct({ |
| 1164 | data: Schema.Struct({ |
| 1165 | currentUser: Schema.optional( |
| 1166 | Schema.NullOr(Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) })), |
| 1167 | ), |
| 1168 | project: Schema.NullOr( |
| 1169 | Schema.Struct({ |
| 1170 | mergeRequest: Schema.NullOr( |
| 1171 | Schema.Struct({ |
| 1172 | awardEmoji: RawAwardEmojiNodesSchema, |
| 1173 | notes: Schema.optional( |
| 1174 | Schema.NullOr( |
| 1175 | Schema.Struct({ |
| 1176 | pageInfo: Schema.optional( |
| 1177 | Schema.Struct({ |
| 1178 | hasNextPage: Schema.optional(Schema.Boolean), |
| 1179 | endCursor: Schema.optional(Schema.NullOr(Schema.String)), |
| 1180 | }), |
| 1181 | ), |
| 1182 | nodes: Schema.Array( |
| 1183 | Schema.NullOr( |
| 1184 | Schema.Struct({ |
| 1185 | id: Schema.optional(Schema.NullOr(Schema.String)), |
| 1186 | lastEditedAt: Schema.optional(Schema.NullOr(Schema.String)), |
| 1187 | lastEditedBy: Schema.optional( |
| 1188 | Schema.NullOr( |
| 1189 | Schema.Struct({ |
| 1190 | username: Schema.optional(Schema.NullOr(Schema.String)), |
| 1191 | }), |
| 1192 | ), |
| 1193 | ), |
| 1194 | resolved: Schema.optional(Schema.NullOr(Schema.Boolean)), |
| 1195 | // REST note authors carry no bot flag; GraphQL's does. |
| 1196 | author: Schema.optional( |
| 1197 | Schema.NullOr( |
| 1198 | Schema.Struct({ |
| 1199 | username: Schema.optional(Schema.NullOr(Schema.String)), |
| 1200 | bot: Schema.optional(Schema.NullOr(Schema.Boolean)), |
| 1201 | }), |
| 1202 | ), |
| 1203 | ), |
| 1204 | awardEmoji: RawAwardEmojiNodesSchema, |
| 1205 | }), |
| 1206 | ), |
| 1207 | ), |
| 1208 | }), |
| 1209 | ), |
| 1210 | ), |
| 1211 | }), |
| 1212 | ), |
| 1213 | }), |
| 1214 | ), |
| 1215 | }), |
| 1216 | }); |
| 1217 | |
| 1218 | const decodeAwardEmojiPage = decodeJsonResult(RawAwardEmojiPageSchema); |
| 1219 | |
| 1220 | function toReactions( |
| 1221 | nodes: Schema.Schema.Type<typeof RawAwardEmojiNodesSchema>, |
| 1222 | viewer: string | null, |
| 1223 | ): ReadonlyArray<PullRequestReaction> { |
| 1224 | const normalizedViewer = viewer?.toLowerCase() ?? null; |
| 1225 | const groups = new Map< |
| 1226 | PullRequestReactionContent, |
| 1227 | { count: number; actors: string[]; viewer: boolean } |
| 1228 | >(); |
| 1229 | for (const node of nodes?.nodes ?? []) { |
| 1230 | const content = CONTENT_BY_GITLAB_AWARD[trimmed(node?.name)?.toLowerCase() ?? ""]; |
| 1231 | if (content === undefined) continue; |
| 1232 | const username = trimmed(node?.user?.username); |
| 1233 | if (username === null) continue; |
| 1234 | const group = groups.get(content) ?? { count: 0, actors: [], viewer: false }; |
| 1235 | group.count++; |
| 1236 | if (normalizedViewer !== null && username.toLowerCase() === normalizedViewer) { |
| 1237 | group.viewer = true; |
| 1238 | } else { |
| 1239 | group.actors.push(username); |
| 1240 | } |
| 1241 | groups.set(content, group); |
| 1242 | } |
| 1243 | return [...groups].flatMap(([content, group]) => |
| 1244 | group.count === 0 |
| 1245 | ? [] |
| 1246 | : [{ content, count: group.count, actors: group.actors, viewerHasReacted: group.viewer }], |
| 1247 | ); |
| 1248 | } |
| 1249 | |
| 1250 | /** |
| 1251 | * Resolving a thread moves lastEditedAt on every note in it; only lastEditedBy marks a text |
| 1252 | * edit, and a resolved note's stamp may be the resolve rather than that edit. |
| 1253 | */ |
| 1254 | function textEditedAt( |
| 1255 | note: { |
| 1256 | readonly lastEditedAt?: string | null | undefined; |
| 1257 | readonly lastEditedBy?: { readonly username?: string | null | undefined } | null | undefined; |
| 1258 | readonly resolved?: boolean | null | undefined; |
| 1259 | } | null, |
| 1260 | ): string | null { |
| 1261 | const editedAt = trimmed(note?.lastEditedAt); |
| 1262 | return editedAt !== null && |
| 1263 | trimmed(note?.lastEditedBy?.username) !== null && |
| 1264 | note?.resolved !== true |
| 1265 | ? editedAt |
| 1266 | : null; |
| 1267 | } |
| 1268 | |
| 1269 | function noteIdOf(gid: string | null | undefined): string | null { |
| 1270 | const id = trimmed(gid)?.split("/").at(-1); |
| 1271 | return id !== undefined && /^\d+$/.test(id) ? id : null; |
| 1272 | } |
| 1273 | |
| 1274 | export interface GitLabAwardEmojiPage { |
| 1275 | readonly reactions: ReadonlyArray<PullRequestReaction>; |
| 1276 | readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>; |
| 1277 | readonly editedAtByNoteId: ReadonlyMap<string, string>; |
| 1278 | readonly botLogins: ReadonlySet<string>; |
| 1279 | readonly nextCursor: string | null; |
| 1280 | } |
| 1281 | |
| 1282 | export function decodeAwardEmojiJson( |
| 1283 | raw: string, |
| 1284 | ): Result.Result<GitLabAwardEmojiPage, DecodeFailure> { |
| 1285 | const decoded = decodeAwardEmojiPage(raw); |
| 1286 | if (!Result.isSuccess(decoded)) { |
| 1287 | return Result.fail(decoded.failure); |
| 1288 | } |
| 1289 | const data = decoded.success.data; |
| 1290 | const viewer = trimmed(data.currentUser?.username); |
| 1291 | const mergeRequest = data.project?.mergeRequest; |
| 1292 | const reactionsByNoteId = new Map<string, ReadonlyArray<PullRequestReaction>>(); |
| 1293 | const editedAtByNoteId = new Map<string, string>(); |
| 1294 | const botLogins = new Set<string>(); |
| 1295 | for (const node of mergeRequest?.notes?.nodes ?? []) { |
| 1296 | const author = trimmed(node?.author?.username); |
| 1297 | if (author !== null && node?.author?.bot === true) botLogins.add(author); |
| 1298 | const id = noteIdOf(node?.id); |
| 1299 | if (id === null) continue; |
| 1300 | const reactions = toReactions(node?.awardEmoji, viewer); |
| 1301 | if (reactions.length > 0) reactionsByNoteId.set(id, reactions); |
| 1302 | const editedAt = textEditedAt(node); |
| 1303 | if (editedAt !== null) editedAtByNoteId.set(id, editedAt); |
| 1304 | } |
| 1305 | const pageInfo = mergeRequest?.notes?.pageInfo; |
| 1306 | return Result.succeed({ |
| 1307 | reactions: toReactions(mergeRequest?.awardEmoji, viewer), |
| 1308 | reactionsByNoteId, |
| 1309 | editedAtByNoteId, |
| 1310 | botLogins, |
| 1311 | nextCursor: pageInfo?.hasNextPage === true ? (trimmed(pageInfo.endCursor) ?? null) : null, |
| 1312 | }); |
| 1313 | } |
| 1314 | |
| 1315 | const RawAwardSchema = Schema.Struct({ |
| 1316 | id: Schema.Int, |
| 1317 | name: Schema.optional(Schema.NullOr(Schema.String)), |
| 1318 | user: Schema.optional( |
| 1319 | Schema.NullOr(Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) })), |
| 1320 | ), |
| 1321 | }); |
| 1322 | |
| 1323 | const decodeAward = Schema.decodeUnknownExit(RawAwardSchema); |
| 1324 | |
| 1325 | type GitLabAward = typeof RawAwardSchema.Type; |
| 1326 | |
| 1327 | /** A page of REST `award_emoji`; a row that cannot be read is skipped. */ |
| 1328 | export function decodeAwardListJson( |
| 1329 | raw: string, |
| 1330 | ): Result.Result<ReadonlyArray<GitLabAward>, DecodeFailure> { |
| 1331 | return Result.map(decodeUnknownList(raw), (rows) => |
| 1332 | rows.flatMap((entry) => { |
| 1333 | const award = decodeAward(entry); |
| 1334 | return Exit.isSuccess(award) ? [award.value] : []; |
| 1335 | }), |
| 1336 | ); |
| 1337 | } |
| 1338 | |
| 1339 | export function awardReactions( |
| 1340 | awards: ReadonlyArray<GitLabAward>, |
| 1341 | viewer: string | null, |
| 1342 | ): ReadonlyArray<PullRequestReaction> { |
| 1343 | return toReactions({ nodes: awards }, viewer); |
| 1344 | } |
| 1345 | |
| 1346 | export function decodeOwnAwardIdJson( |
| 1347 | raw: string, |
| 1348 | input: { readonly content: PullRequestReactionContent; readonly viewer: string }, |
| 1349 | ): Result.Result<{ readonly id: number | null; readonly empty: boolean }, DecodeFailure> { |
| 1350 | const decoded = decodeUnknownList(raw); |
| 1351 | if (!Result.isSuccess(decoded)) { |
| 1352 | return Result.fail(decoded.failure); |
| 1353 | } |
| 1354 | const name = gitLabAwardName(input.content); |
| 1355 | for (const entry of decoded.success) { |
| 1356 | const award = decodeAward(entry); |
| 1357 | if (Exit.isFailure(award)) continue; |
| 1358 | const value = award.value; |
| 1359 | if (trimmed(value.name)?.toLowerCase() !== name) continue; |
| 1360 | if (trimmed(value.user?.username) !== input.viewer) continue; |
| 1361 | return Result.succeed({ id: value.id, empty: false }); |
| 1362 | } |
| 1363 | return Result.succeed({ id: null, empty: decoded.success.length === 0 }); |
| 1364 | } |
| 1365 | |
| 1366 | export const REPOSITORY_BLOBS_GRAPHQL_QUERY = `query($fullPath: ID!, $ref: String!, $paths: [String!]!) { |
| 1367 | project(fullPath: $fullPath) { |
| 1368 | repository { |
| 1369 | blobs(ref: $ref, paths: $paths) { |
| 1370 | nodes { path oid } |
| 1371 | } |
| 1372 | } |
| 1373 | } |
| 1374 | }`; |
| 1375 | |
| 1376 | const RawRepositoryBlobsSchema = Schema.Struct({ |
| 1377 | data: Schema.Struct({ |
| 1378 | project: Schema.NullOr( |
| 1379 | Schema.Struct({ |
| 1380 | repository: Schema.optional( |
| 1381 | Schema.NullOr( |
| 1382 | Schema.Struct({ |
| 1383 | blobs: Schema.optional( |
| 1384 | Schema.NullOr( |
| 1385 | Schema.Struct({ |
| 1386 | nodes: Schema.optional( |
| 1387 | Schema.NullOr( |
| 1388 | Schema.Array( |
| 1389 | Schema.NullOr( |
| 1390 | Schema.Struct({ |
| 1391 | path: Schema.optional(Schema.NullOr(Schema.String)), |
| 1392 | oid: Schema.optional(Schema.NullOr(Schema.String)), |
| 1393 | }), |
| 1394 | ), |
| 1395 | ), |
| 1396 | ), |
| 1397 | ), |
| 1398 | }), |
| 1399 | ), |
| 1400 | ), |
| 1401 | }), |
| 1402 | ), |
| 1403 | ), |
| 1404 | }), |
| 1405 | ), |
| 1406 | }), |
| 1407 | }); |
| 1408 | |
| 1409 | const decodeRepositoryBlobs = decodeJsonResult(RawRepositoryBlobsSchema); |
| 1410 | |
| 1411 | /** Null means unknown, not deleted; preserve viewed marks. */ |
| 1412 | export function decodeRepositoryBlobsJson( |
| 1413 | raw: string, |
| 1414 | ): Result.Result<ReadonlyMap<string, string> | null, DecodeFailure> { |
| 1415 | const decoded = decodeRepositoryBlobs(raw); |
| 1416 | if (!Result.isSuccess(decoded)) { |
| 1417 | return Result.fail(decoded.failure); |
| 1418 | } |
| 1419 | const nodes = decoded.success.data.project?.repository?.blobs?.nodes; |
| 1420 | if (nodes === undefined || nodes === null) return Result.succeed(null); |
| 1421 | const blobs = new Map<string, string>(); |
| 1422 | for (const node of nodes) { |
| 1423 | // Preserve path whitespace so blob-map keys match the caller's exact filenames. |
| 1424 | const path = node?.path; |
| 1425 | const oid = trimmed(node?.oid); |
| 1426 | if (path === undefined || path === null || path.length === 0 || oid === null) continue; |
| 1427 | blobs.set(path, oid); |
| 1428 | } |
| 1429 | return Result.succeed(blobs); |
| 1430 | } |
| 1431 | |
| 1432 | export const SOURCE_BRANCH_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!) { |
| 1433 | project(fullPath: $fullPath) { |
| 1434 | mergeRequest(iid: $iid) { |
| 1435 | state sourceBranch diffHeadSha |
| 1436 | sourceProject { fullPath } |
| 1437 | userPermissions { removeSourceBranch } |
| 1438 | } |
| 1439 | } |
| 1440 | }`; |
| 1441 | |
| 1442 | const RawSourceBranchSchema = Schema.Struct({ |
| 1443 | data: Schema.Struct({ |
| 1444 | project: Schema.NullOr( |
| 1445 | Schema.Struct({ |
| 1446 | mergeRequest: Schema.NullOr( |
| 1447 | Schema.Struct({ |
| 1448 | state: Schema.String, |
| 1449 | sourceBranch: Schema.String, |
| 1450 | diffHeadSha: Schema.optional(Schema.NullOr(Schema.String)), |
| 1451 | sourceProject: Schema.optional( |
| 1452 | Schema.NullOr(Schema.Struct({ fullPath: Schema.String })), |
| 1453 | ), |
| 1454 | userPermissions: Schema.optional( |
| 1455 | Schema.NullOr( |
| 1456 | Schema.Struct({ |
| 1457 | removeSourceBranch: Schema.optional(Schema.NullOr(Schema.Boolean)), |
| 1458 | }), |
| 1459 | ), |
| 1460 | ), |
| 1461 | }), |
| 1462 | ), |
| 1463 | }), |
| 1464 | ), |
| 1465 | }), |
| 1466 | }); |
| 1467 | |
| 1468 | const decodeSourceBranch = decodeJsonResult(RawSourceBranchSchema); |
| 1469 | |
| 1470 | export interface GitLabSourceBranch { |
| 1471 | readonly open: boolean; |
| 1472 | readonly branch: string; |
| 1473 | readonly headSha: string | null; |
| 1474 | /** Null when the source project is gone or hidden from the viewer, as a deleted fork is. */ |
| 1475 | readonly sourceProject: string | null; |
| 1476 | /** GitLab's own answer: false once the branch is gone, protected, or out of the viewer's reach. */ |
| 1477 | readonly canDelete: boolean; |
| 1478 | } |
| 1479 | |
| 1480 | export function decodeSourceBranchJson( |
| 1481 | raw: string, |
| 1482 | ): Result.Result<GitLabSourceBranch | null, DecodeFailure> { |
| 1483 | return Result.map(decodeSourceBranch(raw), (decoded) => { |
| 1484 | const mergeRequest = decoded.data.project?.mergeRequest; |
| 1485 | if (mergeRequest == null) return null; |
| 1486 | return { |
| 1487 | // `locked` is GitLab's transient state while a merge runs, so only these two are settled. |
| 1488 | open: mergeRequest.state !== "merged" && mergeRequest.state !== "closed", |
| 1489 | branch: mergeRequest.sourceBranch, |
| 1490 | headSha: trimmed(mergeRequest.diffHeadSha), |
| 1491 | sourceProject: mergeRequest.sourceProject?.fullPath ?? null, |
| 1492 | canDelete: mergeRequest.userPermissions?.removeSourceBranch === true, |
| 1493 | }; |
| 1494 | }); |
| 1495 | } |
| 1496 | |
| 1497 | const decodeBranch = decodeJsonResult( |
| 1498 | Schema.Struct({ |
| 1499 | default: Schema.optional(Schema.NullOr(Schema.Boolean)), |
| 1500 | commit: Schema.optional( |
| 1501 | Schema.NullOr( |
| 1502 | Schema.Struct({ |
| 1503 | id: Schema.String, |
| 1504 | authored_date: Schema.optional(Schema.NullOr(Schema.String)), |
| 1505 | }), |
| 1506 | ), |
| 1507 | ), |
| 1508 | }), |
| 1509 | ); |
| 1510 | |
| 1511 | export function decodeBranchJson(raw: string): Result.Result< |
| 1512 | { |
| 1513 | readonly isDefault: boolean; |
| 1514 | readonly headSha: string | null; |
| 1515 | readonly headAuthoredDate: string | null; |
| 1516 | }, |
| 1517 | DecodeFailure |
| 1518 | > { |
| 1519 | return Result.map(decodeBranch(raw), (branch) => ({ |
| 1520 | isDefault: branch.default === true, |
| 1521 | headSha: trimmed(branch.commit?.id), |
| 1522 | headAuthoredDate: trimmed(branch.commit?.authored_date), |
| 1523 | })); |
| 1524 | } |
| 1525 | |
| 1526 | export const MERGE_MESSAGES_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!) { |
| 1527 | project(fullPath: $fullPath) { |
| 1528 | mergeRequest(iid: $iid) { title squashOnMerge defaultMergeCommitMessage defaultSquashCommitMessage } |
| 1529 | } |
| 1530 | }`; |
| 1531 | |
| 1532 | const RawMergeMessagesSchema = Schema.Struct({ |
| 1533 | // A field that errored reads as null, which must not pass for an absent template. |
| 1534 | errors: Schema.optionalKey(Schema.Never), |
| 1535 | data: Schema.Struct({ |
| 1536 | project: Schema.NullOr( |
| 1537 | Schema.Struct({ |
| 1538 | mergeRequest: Schema.NullOr( |
| 1539 | Schema.Struct({ |
| 1540 | title: Schema.optional(Schema.NullOr(Schema.String)), |
| 1541 | squashOnMerge: Schema.optional(Schema.NullOr(Schema.Boolean)), |
| 1542 | defaultMergeCommitMessage: Schema.optional(Schema.NullOr(Schema.String)), |
| 1543 | defaultSquashCommitMessage: Schema.optional(Schema.NullOr(Schema.String)), |
| 1544 | }), |
| 1545 | ), |
| 1546 | }), |
| 1547 | ), |
| 1548 | }), |
| 1549 | }); |
| 1550 | |
| 1551 | const decodeMergeMessages = decodeJsonResult(RawMergeMessagesSchema); |
| 1552 | |
| 1553 | export interface GitLabMergeMessages { |
| 1554 | readonly title: string | null; |
| 1555 | readonly merge: string | null; |
| 1556 | readonly squash: string | null; |
| 1557 | /** GitLab squashes when the project always does or the merge request asks to. */ |
| 1558 | readonly squashOnMerge: boolean; |
| 1559 | } |
| 1560 | |
| 1561 | /** The messages GitLab would write from the project's merge and squash templates. */ |
| 1562 | export function decodeMergeMessagesJson( |
| 1563 | raw: string, |
| 1564 | ): Result.Result<GitLabMergeMessages, DecodeFailure> { |
| 1565 | return Result.map(decodeMergeMessages(raw), (decoded) => { |
| 1566 | const mergeRequest = decoded.data.project?.mergeRequest; |
| 1567 | return { |
| 1568 | title: mergeRequest?.title ?? null, |
| 1569 | merge: mergeRequest?.defaultMergeCommitMessage ?? null, |
| 1570 | squash: mergeRequest?.defaultSquashCommitMessage ?? null, |
| 1571 | squashOnMerge: mergeRequest?.squashOnMerge === true, |
| 1572 | }; |
| 1573 | }); |
| 1574 | } |
| 1575 | |
| 1576 | /** What a listed merge request needs beyond REST: its approval, reviewer and pipeline state. */ |
| 1577 | const LIST_STATE_GRAPHQL_FIELDS = `iid approved approvedBy(first: 1) { nodes { username } } |
| 1578 | reviewers(first: 20) { nodes { username mergeRequestInteraction { reviewState } } } |
| 1579 | headPipeline { status }`; |
| 1580 | |
| 1581 | export const LIST_STATES_GRAPHQL_QUERY = `query($fullPath: ID!, $iids: [String!]) { |
| 1582 | metadata { enterprise } |
| 1583 | project(fullPath: $fullPath) { |
| 1584 | mergeRequests(iids: $iids, first: 100) { |
| 1585 | nodes { ${LIST_STATE_GRAPHQL_FIELDS} } |
| 1586 | } |
| 1587 | } |
| 1588 | }`; |
| 1589 | |
| 1590 | const RawMetadataSchema = Schema.optional( |
| 1591 | Schema.NullOr(Schema.Struct({ enterprise: Schema.optional(Schema.NullOr(Schema.Boolean)) })), |
| 1592 | ); |
| 1593 | |
| 1594 | const RawListStateFields = { |
| 1595 | iid: Schema.String, |
| 1596 | approved: Schema.optional(Schema.NullOr(Schema.Boolean)), |
| 1597 | approvedBy: Schema.optional( |
| 1598 | Schema.NullOr( |
| 1599 | Schema.Struct({ |
| 1600 | nodes: Schema.optional(Schema.NullOr(Schema.Array(Schema.Unknown))), |
| 1601 | }), |
| 1602 | ), |
| 1603 | ), |
| 1604 | reviewers: Schema.optional( |
| 1605 | Schema.NullOr( |
| 1606 | Schema.Struct({ |
| 1607 | nodes: Schema.optional( |
| 1608 | Schema.NullOr( |
| 1609 | Schema.Array( |
| 1610 | Schema.NullOr( |
| 1611 | Schema.Struct({ |
| 1612 | username: Schema.optional(Schema.NullOr(Schema.String)), |
| 1613 | mergeRequestInteraction: Schema.optional( |
| 1614 | Schema.NullOr( |
| 1615 | Schema.Struct({ reviewState: Schema.optional(Schema.NullOr(Schema.String)) }), |
| 1616 | ), |
| 1617 | ), |
| 1618 | }), |
| 1619 | ), |
| 1620 | ), |
| 1621 | ), |
| 1622 | ), |
| 1623 | }), |
| 1624 | ), |
| 1625 | ), |
| 1626 | headPipeline: Schema.optional( |
| 1627 | Schema.NullOr(Schema.Struct({ status: Schema.optional(Schema.NullOr(Schema.String)) })), |
| 1628 | ), |
| 1629 | }; |
| 1630 | |
| 1631 | const RawListStateNodeSchema = Schema.Struct(RawListStateFields); |
| 1632 | |
| 1633 | const RawListStatesSchema = Schema.Struct({ |
| 1634 | data: Schema.Struct({ |
| 1635 | metadata: RawMetadataSchema, |
| 1636 | project: Schema.NullOr( |
| 1637 | Schema.Struct({ |
| 1638 | mergeRequests: Schema.optional( |
| 1639 | Schema.NullOr( |
| 1640 | Schema.Struct({ nodes: Schema.Array(Schema.NullOr(RawListStateNodeSchema)) }), |
| 1641 | ), |
| 1642 | ), |
| 1643 | }), |
| 1644 | ), |
| 1645 | }), |
| 1646 | }); |
| 1647 | |
| 1648 | const decodeListStates = decodeJsonResult(RawListStatesSchema); |
| 1649 | |
| 1650 | export interface GitLabMergeRequestListState { |
| 1651 | /** Absent when the approval state can't be judged. */ |
| 1652 | readonly reviewDecision?: PullRequestReviewDecision | null; |
| 1653 | readonly checksState: PullRequestChecksState | null; |
| 1654 | } |
| 1655 | |
| 1656 | function toChecksState(pipelineStatus: string | null | undefined): PullRequestChecksState | null { |
| 1657 | if (pipelineStatus == null) return null; |
| 1658 | switch (toPipelineStatus(pipelineStatus)) { |
| 1659 | case "success": |
| 1660 | return "passing"; |
| 1661 | case "failure": |
| 1662 | case "cancelled": |
| 1663 | return "failing"; |
| 1664 | case "pending": |
| 1665 | return "pending"; |
| 1666 | default: |
| 1667 | return null; |
| 1668 | } |
| 1669 | } |
| 1670 | |
| 1671 | /** |
| 1672 | * Only Enterprise Edition holds `approved` to the project's approval rules, so an unapproved |
| 1673 | * merge request there still needs review even when someone, such as a bot, approved it. |
| 1674 | * Community Edition reports `approved` once anyone approves and requires no review. |
| 1675 | * A reviewer asking for changes outranks both, as it does on GitHub. |
| 1676 | */ |
| 1677 | function toListState( |
| 1678 | node: typeof RawListStateNodeSchema.Type, |
| 1679 | enterprise: boolean | null | undefined, |
| 1680 | ): GitLabMergeRequestListState { |
| 1681 | const checksState = toChecksState(node.headPipeline?.status); |
| 1682 | if ( |
| 1683 | node.reviewers?.nodes?.some( |
| 1684 | (reviewer) => reviewer?.mergeRequestInteraction?.reviewState === "REQUESTED_CHANGES", |
| 1685 | ) |
| 1686 | ) { |
| 1687 | return { reviewDecision: "changes-requested", checksState }; |
| 1688 | } |
| 1689 | const approvals = node.approvedBy?.nodes?.length; |
| 1690 | if ( |
| 1691 | node.approved == null || |
| 1692 | approvals === undefined || |
| 1693 | (node.approved === false && approvals === 0 && enterprise == null) |
| 1694 | ) { |
| 1695 | return { checksState }; |
| 1696 | } |
| 1697 | return { |
| 1698 | reviewDecision: |
| 1699 | node.approved === false && (enterprise || approvals > 0) |
| 1700 | ? "review-required" |
| 1701 | : approvals > 0 |
| 1702 | ? "approved" |
| 1703 | : null, |
| 1704 | checksState, |
| 1705 | }; |
| 1706 | } |
| 1707 | |
| 1708 | export function decodeListStatesJson( |
| 1709 | raw: string, |
| 1710 | ): Result.Result<ReadonlyMap<number, GitLabMergeRequestListState>, DecodeFailure> { |
| 1711 | const decoded = decodeListStates(raw); |
| 1712 | if (!Result.isSuccess(decoded)) { |
| 1713 | return Result.fail(decoded.failure); |
| 1714 | } |
| 1715 | const enterprise = decoded.success.data.metadata?.enterprise; |
| 1716 | const states = new Map<number, GitLabMergeRequestListState>(); |
| 1717 | for (const node of decoded.success.data.project?.mergeRequests?.nodes ?? []) { |
| 1718 | const number = Number(node?.iid); |
| 1719 | if (node === null || !Number.isSafeInteger(number)) continue; |
| 1720 | states.set(number, toListState(node, enterprise)); |
| 1721 | } |
| 1722 | return Result.succeed(states); |
| 1723 | } |
| 1724 | |
| 1725 | /** The fields a listed merge request needs, so one GraphQL read stands in for REST and states. */ |
| 1726 | export const LIST_ITEM_GRAPHQL_FIELDS = `${LIST_STATE_GRAPHQL_FIELDS} |
| 1727 | title webUrl state draft createdAt updatedAt mergedAt sourceBranch targetBranch |
| 1728 | conflicts mergeStatusEnum author { username name avatarUrl } labels(first: 100) { nodes { title color description } }`; |
| 1729 | |
| 1730 | const RawGraphqlListNodeSchema = Schema.Struct({ |
| 1731 | ...RawListStateFields, |
| 1732 | title: Schema.String, |
| 1733 | webUrl: Schema.String, |
| 1734 | state: Schema.optional(Schema.NullOr(Schema.String)), |
| 1735 | draft: Schema.optional(Schema.NullOr(Schema.Boolean)), |
| 1736 | createdAt: Schema.String, |
| 1737 | updatedAt: Schema.String, |
| 1738 | mergedAt: Schema.optional(Schema.NullOr(Schema.String)), |
| 1739 | sourceBranch: Schema.String, |
| 1740 | targetBranch: Schema.String, |
| 1741 | conflicts: Schema.optional(Schema.NullOr(Schema.Boolean)), |
| 1742 | mergeStatusEnum: Schema.optional(Schema.NullOr(Schema.String)), |
| 1743 | author: Schema.optional( |
| 1744 | Schema.NullOr( |
| 1745 | Schema.Struct({ |
| 1746 | username: Schema.optional(Schema.NullOr(Schema.String)), |
| 1747 | name: Schema.optional(Schema.NullOr(Schema.String)), |
| 1748 | avatarUrl: Schema.optional(Schema.NullOr(Schema.String)), |
| 1749 | }), |
| 1750 | ), |
| 1751 | ), |
| 1752 | labels: Schema.optional( |
| 1753 | Schema.NullOr( |
| 1754 | Schema.Struct({ |
| 1755 | nodes: Schema.optional( |
| 1756 | Schema.NullOr( |
| 1757 | Schema.Array( |
| 1758 | Schema.NullOr( |
| 1759 | Schema.Struct({ |
| 1760 | title: Schema.String, |
| 1761 | color: Schema.optional(Schema.NullOr(Schema.String)), |
| 1762 | description: Schema.optional(Schema.NullOr(Schema.String)), |
| 1763 | }), |
| 1764 | ), |
| 1765 | ), |
| 1766 | ), |
| 1767 | ), |
| 1768 | }), |
| 1769 | ), |
| 1770 | ), |
| 1771 | }); |
| 1772 | |
| 1773 | // GitLab answers `project: null` for a project the reader cannot see, which REST reports as an error. |
| 1774 | const RawGraphqlListSchema = Schema.Struct({ |
| 1775 | data: Schema.Struct({ |
| 1776 | metadata: RawMetadataSchema, |
| 1777 | project: Schema.Struct({ |
| 1778 | mergeRequests: Schema.Struct({ |
| 1779 | pageInfo: Schema.Struct({ |
| 1780 | hasNextPage: Schema.Boolean, |
| 1781 | endCursor: Schema.optional(Schema.NullOr(Schema.String)), |
| 1782 | }), |
| 1783 | nodes: Schema.Array(Schema.Unknown), |
| 1784 | }), |
| 1785 | }), |
| 1786 | }), |
| 1787 | }); |
| 1788 | |
| 1789 | const decodeGraphqlList = decodeJsonResult(RawGraphqlListSchema); |
| 1790 | const decodeGraphqlListNode = Schema.decodeUnknownExit(RawGraphqlListNodeSchema); |
| 1791 | |
| 1792 | export interface GitLabMergeRequestGraphqlPage { |
| 1793 | readonly items: ReadonlyArray<GitLabMergeRequestListItem>; |
| 1794 | readonly states: ReadonlyMap<number, GitLabMergeRequestListState>; |
| 1795 | /** Count before decoding, so a page of rows that fail to decode still moves on. */ |
| 1796 | readonly rawCount: number; |
| 1797 | readonly hasNextPage: boolean; |
| 1798 | readonly endCursor: string | null; |
| 1799 | } |
| 1800 | |
| 1801 | export function decodeMergeRequestGraphqlListJson( |
| 1802 | raw: string, |
| 1803 | ): Result.Result<GitLabMergeRequestGraphqlPage, DecodeFailure> { |
| 1804 | const decoded = decodeGraphqlList(raw); |
| 1805 | if (!Result.isSuccess(decoded)) { |
| 1806 | return Result.fail(decoded.failure); |
| 1807 | } |
| 1808 | const page = decoded.success.data.project.mergeRequests; |
| 1809 | const enterprise = decoded.success.data.metadata?.enterprise; |
| 1810 | const items: GitLabMergeRequestListItem[] = []; |
| 1811 | const states = new Map<number, GitLabMergeRequestListState>(); |
| 1812 | for (const entry of page.nodes) { |
| 1813 | const exit = decodeGraphqlListNode(entry); |
| 1814 | if (!Exit.isSuccess(exit)) continue; |
| 1815 | const node = exit.value; |
| 1816 | const number = Number(node.iid); |
| 1817 | if (!Number.isSafeInteger(number)) continue; |
| 1818 | items.push({ |
| 1819 | number, |
| 1820 | title: node.title, |
| 1821 | url: node.webUrl, |
| 1822 | author: toActor( |
| 1823 | node.author == null |
| 1824 | ? null |
| 1825 | : { |
| 1826 | username: node.author.username ?? "", |
| 1827 | name: node.author.name, |
| 1828 | avatar_url: node.author.avatarUrl, |
| 1829 | }, |
| 1830 | ), |
| 1831 | headBranch: node.sourceBranch, |
| 1832 | baseBranch: node.targetBranch, |
| 1833 | state: toState({ state: node.state, merged_at: node.mergedAt }), |
| 1834 | isDraft: node.draft ?? false, |
| 1835 | mergeability: toMergeability({ |
| 1836 | has_conflicts: node.conflicts, |
| 1837 | merge_status: node.mergeStatusEnum, |
| 1838 | }), |
| 1839 | additions: 0, |
| 1840 | deletions: 0, |
| 1841 | createdAt: node.createdAt, |
| 1842 | updatedAt: node.updatedAt, |
| 1843 | reviewRequestLogins: (node.reviewers?.nodes ?? []).flatMap((reviewer) => { |
| 1844 | const login = trimmed(reviewer?.username); |
| 1845 | return login === null ? [] : [login]; |
| 1846 | }), |
| 1847 | labels: toLabels( |
| 1848 | (node.labels?.nodes ?? []).flatMap((label) => |
| 1849 | label ? [{ name: label.title, color: label.color, description: label.description }] : [], |
| 1850 | ), |
| 1851 | ), |
| 1852 | }); |
| 1853 | states.set(number, toListState(node, enterprise)); |
| 1854 | } |
| 1855 | return Result.succeed({ |
| 1856 | items, |
| 1857 | states, |
| 1858 | rawCount: page.nodes.length, |
| 1859 | hasNextPage: page.pageInfo.hasNextPage, |
| 1860 | endCursor: trimmed(page.pageInfo.endCursor), |
| 1861 | }); |
| 1862 | } |
| 1863 | |
| 1864 | export const SERVER_VERSION_GRAPHQL_QUERY = "{ metadata { version } }"; |
| 1865 | |
| 1866 | const decodeServerVersion = decodeJsonResult( |
| 1867 | Schema.Struct({ |
| 1868 | data: Schema.Struct({ |
| 1869 | metadata: Schema.optional( |
| 1870 | Schema.NullOr(Schema.Struct({ version: Schema.optional(Schema.NullOr(Schema.String)) })), |
| 1871 | ), |
| 1872 | }), |
| 1873 | }), |
| 1874 | ); |
| 1875 | |
| 1876 | /** |
| 1877 | * Whether the GraphQL merge request list takes every filter the REST list does: `search` came |
| 1878 | * last, in 17.9. An instance that hides its version keeps REST. |
| 1879 | */ |
| 1880 | export function decodeGraphqlListSupportJson(raw: string): Result.Result<boolean, DecodeFailure> { |
| 1881 | const decoded = decodeServerVersion(raw); |
| 1882 | if (!Result.isSuccess(decoded)) { |
| 1883 | return Result.fail(decoded.failure); |
| 1884 | } |
| 1885 | const match = /^(\d+)\.(\d+)/u.exec(decoded.success.data.metadata?.version?.trim() ?? ""); |
| 1886 | if (match === null) return Result.succeed(false); |
| 1887 | const major = Number(match[1]); |
| 1888 | const minor = Number(match[2]); |
| 1889 | return Result.succeed(major > 17 || (major === 17 && minor >= 9)); |
| 1890 | } |
| 1891 | |
| 1892 | const decodeMutationPayloads = decodeJsonResult( |
| 1893 | Schema.Struct({ |
| 1894 | data: Schema.Record( |
| 1895 | Schema.String, |
| 1896 | Schema.NullOr( |
| 1897 | Schema.Struct({ errors: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))) }), |
| 1898 | ), |
| 1899 | ), |
| 1900 | }), |
| 1901 | ); |
| 1902 | |
| 1903 | /** GitLab answers a refused mutation with HTTP 200 and the reasons in each payload's `errors`. */ |
| 1904 | export function decodeMutationErrorsJson( |
| 1905 | raw: string, |
| 1906 | ): Result.Result<ReadonlyArray<string>, DecodeFailure> { |
| 1907 | const decoded = decodeMutationPayloads(raw); |
| 1908 | if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure); |
| 1909 | return Result.succeed( |
| 1910 | Object.values(decoded.success.data).flatMap((payload) => payload?.errors ?? []), |
| 1911 | ); |
| 1912 | } |
| 1913 | |
| 1914 | /** |
| 1915 | * Line counts for merge requests of one project. The REST listing carries no line counts, and |
| 1916 | * reading each diff to count them would cost a request per row, so GraphQL's per-merge-request |
| 1917 | * summary is asked for in one read instead. |
| 1918 | */ |
| 1919 | export const MERGE_REQUEST_STATS_GRAPHQL_QUERY = `query($fullPath: ID!, $iids: [String!]) { |
| 1920 | project(fullPath: $fullPath) { |
| 1921 | mergeRequests(iids: $iids, first: 100) { |
| 1922 | nodes { iid diffStatsSummary { additions deletions } } |
| 1923 | } |
| 1924 | } |
| 1925 | }`; |
| 1926 | |
| 1927 | const LineCountsSchema = Schema.Struct({ additions: Schema.Int, deletions: Schema.Int }); |
| 1928 | |
| 1929 | const RawMergeRequestStatsSchema = Schema.Struct({ |
| 1930 | data: Schema.Struct({ |
| 1931 | project: Schema.NullOr( |
| 1932 | Schema.Struct({ |
| 1933 | mergeRequests: Schema.NullOr( |
| 1934 | Schema.Struct({ |
| 1935 | nodes: Schema.Array( |
| 1936 | Schema.NullOr( |
| 1937 | Schema.Struct({ |
| 1938 | iid: Schema.String, |
| 1939 | diffStatsSummary: Schema.NullOr(LineCountsSchema), |
| 1940 | }), |
| 1941 | ), |
| 1942 | ), |
| 1943 | }), |
| 1944 | ), |
| 1945 | }), |
| 1946 | ), |
| 1947 | }), |
| 1948 | }); |
| 1949 | |
| 1950 | const decodeMergeRequestStats = decodeJsonResult(RawMergeRequestStatsSchema); |
| 1951 | |
| 1952 | /** |
| 1953 | * The counts by merge request number. A merge request GitLab returned no summary for is left |
| 1954 | * out rather than counted as zero, so its row keeps whatever it already showed. |
| 1955 | */ |
| 1956 | export function decodeMergeRequestStatsJson( |
| 1957 | raw: string, |
| 1958 | ): Result.Result< |
| 1959 | ReadonlyMap<number, { readonly additions: number; readonly deletions: number }>, |
| 1960 | DecodeFailure |
| 1961 | > { |
| 1962 | const decoded = decodeMergeRequestStats(raw); |
| 1963 | if (!Result.isSuccess(decoded)) { |
| 1964 | return Result.fail(decoded.failure); |
| 1965 | } |
| 1966 | const stats = new Map<number, { readonly additions: number; readonly deletions: number }>(); |
| 1967 | for (const node of decoded.success.data.project?.mergeRequests?.nodes ?? []) { |
| 1968 | const iid = Number(node?.iid); |
| 1969 | if (!Number.isSafeInteger(iid) || iid <= 0 || node?.diffStatsSummary == null) continue; |
| 1970 | stats.set(iid, node.diffStatsSummary); |
| 1971 | } |
| 1972 | return Result.succeed(stats); |
| 1973 | } |
| 1974 | |
| 1975 | /** |
| 1976 | * GitLab lets whoever may change a merge request's metadata set its labels. The labels ride along |
| 1977 | * because GET /merge_requests/:iid ignores `with_labels_details` and so carries no colours. |
| 1978 | */ |
| 1979 | export const LABEL_PERMISSION_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!) { |
| 1980 | project(fullPath: $fullPath) { |
| 1981 | mergeRequest(iid: $iid) { |
| 1982 | userPermissions { adminMergeRequest } |
| 1983 | labels(first: 100) { nodes { title color description } } |
| 1984 | } |
| 1985 | } |
| 1986 | }`; |
| 1987 | |
| 1988 | const decodeLabelPermission = decodeJsonResult( |
| 1989 | Schema.Struct({ |
| 1990 | data: Schema.Struct({ |
| 1991 | project: Schema.NullOr( |
| 1992 | Schema.Struct({ |
| 1993 | mergeRequest: Schema.NullOr( |
| 1994 | Schema.Struct({ |
| 1995 | userPermissions: Schema.Struct({ adminMergeRequest: Schema.Boolean }), |
| 1996 | labels: Schema.optional( |
| 1997 | Schema.NullOr( |
| 1998 | Schema.Struct({ |
| 1999 | nodes: Schema.optional( |
| 2000 | Schema.NullOr( |
| 2001 | Schema.Array( |
| 2002 | Schema.NullOr( |
| 2003 | Schema.Struct({ |
| 2004 | title: Schema.String, |
| 2005 | color: Schema.optional(Schema.NullOr(Schema.String)), |
| 2006 | description: Schema.optional(Schema.NullOr(Schema.String)), |
| 2007 | }), |
| 2008 | ), |
| 2009 | ), |
| 2010 | ), |
| 2011 | ), |
| 2012 | }), |
| 2013 | ), |
| 2014 | ), |
| 2015 | }), |
| 2016 | ), |
| 2017 | }), |
| 2018 | ), |
| 2019 | }), |
| 2020 | }), |
| 2021 | ); |
| 2022 | |
| 2023 | export interface GitLabLabelPermission { |
| 2024 | readonly viewerCanEditLabels: boolean; |
| 2025 | readonly labels: ReadonlyArray<PullRequestLabel> | null; |
| 2026 | } |
| 2027 | |
| 2028 | export function decodeLabelPermissionJson( |
| 2029 | raw: string, |
| 2030 | ): Result.Result<GitLabLabelPermission, DecodeFailure> { |
| 2031 | const decoded = decodeLabelPermission(raw); |
| 2032 | if (!Result.isSuccess(decoded)) { |
| 2033 | return Result.fail(decoded.failure); |
| 2034 | } |
| 2035 | const mergeRequest = decoded.success.data.project?.mergeRequest; |
| 2036 | return Result.succeed({ |
| 2037 | viewerCanEditLabels: mergeRequest?.userPermissions.adminMergeRequest === true, |
| 2038 | labels: |
| 2039 | mergeRequest?.labels == null |
| 2040 | ? null |
| 2041 | : toLabels( |
| 2042 | (mergeRequest.labels.nodes ?? []).flatMap((label) => |
| 2043 | label |
| 2044 | ? [{ name: label.title, color: label.color, description: label.description }] |
| 2045 | : [], |
| 2046 | ), |
| 2047 | ), |
| 2048 | }); |
| 2049 | } |
| 2050 | |
| 2051 | /** |
| 2052 | * GitLab lets whoever can push to a fork's branch allow maintainer pushes, but once allowed the |
| 2053 | * target's maintainers can push too, so only the author may change it, as on GitHub. GitLab |
| 2054 | * drops the setting unless the source branch is unprotected and neither project is private |
| 2055 | * (`MergeRequest#collaborative_push_possible?`). |
| 2056 | */ |
| 2057 | export const MAINTAINER_EDITS_PERMISSION_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!) { |
| 2058 | currentUser { username } |
| 2059 | project(fullPath: $fullPath) { |
| 2060 | visibility |
| 2061 | mergeRequest(iid: $iid) { |
| 2062 | author { username } |
| 2063 | userPermissions { pushToSourceBranch } |
| 2064 | sourceBranchProtected |
| 2065 | sourceProject { visibility } |
| 2066 | } |
| 2067 | } |
| 2068 | }`; |
| 2069 | |
| 2070 | const decodeMaintainerEditsPermission = decodeJsonResult( |
| 2071 | Schema.Struct({ |
| 2072 | data: Schema.Struct({ |
| 2073 | currentUser: Schema.NullOr(Schema.Struct({ username: Schema.String })), |
| 2074 | project: Schema.NullOr( |
| 2075 | Schema.Struct({ |
| 2076 | visibility: Schema.NullOr(Schema.String), |
| 2077 | mergeRequest: Schema.NullOr( |
| 2078 | Schema.Struct({ |
| 2079 | author: Schema.NullOr(Schema.Struct({ username: Schema.String })), |
| 2080 | userPermissions: Schema.Struct({ pushToSourceBranch: Schema.Boolean }), |
| 2081 | sourceBranchProtected: Schema.Boolean, |
| 2082 | sourceProject: Schema.NullOr( |
| 2083 | Schema.Struct({ visibility: Schema.NullOr(Schema.String) }), |
| 2084 | ), |
| 2085 | }), |
| 2086 | ), |
| 2087 | }), |
| 2088 | ), |
| 2089 | }), |
| 2090 | }), |
| 2091 | ); |
| 2092 | |
| 2093 | export function decodeMaintainerEditsPermissionJson( |
| 2094 | raw: string, |
| 2095 | ): Result.Result<boolean, DecodeFailure> { |
| 2096 | const decoded = decodeMaintainerEditsPermission(raw); |
| 2097 | if (Result.isFailure(decoded)) return Result.fail(decoded.failure); |
| 2098 | const { currentUser, project } = decoded.success.data; |
| 2099 | const mergeRequest = project?.mergeRequest; |
| 2100 | const isPublicOrInternal = (visibility: string | null | undefined) => |
| 2101 | visibility === "public" || visibility === "internal"; |
| 2102 | return Result.succeed( |
| 2103 | currentUser !== null && |
| 2104 | mergeRequest?.author?.username === currentUser.username && |
| 2105 | mergeRequest.userPermissions.pushToSourceBranch && |
| 2106 | !mergeRequest.sourceBranchProtected && |
| 2107 | isPublicOrInternal(project?.visibility) && |
| 2108 | isPublicOrInternal(mergeRequest.sourceProject?.visibility), |
| 2109 | ); |
| 2110 | } |
| 2111 | |
| 2112 | /** Per-file line counts for one merge request, which the code/tests/generated breakdown sorts. */ |
| 2113 | export const MERGE_REQUEST_FILE_STATS_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!) { |
| 2114 | project(fullPath: $fullPath) { |
| 2115 | mergeRequest(iid: $iid) { |
| 2116 | diffStatsSummary { fileCount } |
| 2117 | diffStats { path additions deletions } |
| 2118 | } |
| 2119 | } |
| 2120 | }`; |
| 2121 | |
| 2122 | const decodeMergeRequestFileStats = decodeJsonResult( |
| 2123 | Schema.Struct({ |
| 2124 | data: Schema.Struct({ |
| 2125 | project: Schema.NullOr( |
| 2126 | Schema.Struct({ |
| 2127 | mergeRequest: Schema.NullOr( |
| 2128 | Schema.Struct({ |
| 2129 | diffStatsSummary: Schema.NullOr(Schema.Struct({ fileCount: Schema.Int })), |
| 2130 | diffStats: Schema.NullOr( |
| 2131 | Schema.Array(Schema.Struct({ path: Schema.String, ...LineCountsSchema.fields })), |
| 2132 | ), |
| 2133 | }), |
| 2134 | ), |
| 2135 | }), |
| 2136 | ), |
| 2137 | }), |
| 2138 | }), |
| 2139 | ); |
| 2140 | |
| 2141 | /** |
| 2142 | * GitLab stops listing files past its diff limits while the summary still counts them all, so a |
| 2143 | * shorter list is reported as truncated rather than as a breakdown that misses lines. |
| 2144 | */ |
| 2145 | export function decodeMergeRequestFileStatsJson(raw: string): Result.Result< |
| 2146 | { |
| 2147 | readonly files: ReadonlyArray<{ |
| 2148 | readonly path: string; |
| 2149 | readonly additions: number; |
| 2150 | readonly deletions: number; |
| 2151 | }>; |
| 2152 | readonly truncated: boolean; |
| 2153 | }, |
| 2154 | DecodeFailure |
| 2155 | > { |
| 2156 | const decoded = decodeMergeRequestFileStats(raw); |
| 2157 | if (!Result.isSuccess(decoded)) { |
| 2158 | return Result.fail(decoded.failure); |
| 2159 | } |
| 2160 | const mergeRequest = decoded.success.data.project?.mergeRequest; |
| 2161 | const files = mergeRequest?.diffStats ?? []; |
| 2162 | const fileCount = mergeRequest?.diffStatsSummary?.fileCount; |
| 2163 | return Result.succeed({ files, truncated: fileCount === undefined || files.length < fileCount }); |
| 2164 | } |
| 2165 | |
| 2166 | /** |
| 2167 | * One cheap read that tells a watch whether anything it reports on changed. Edits to comments |
| 2168 | * older than the newest 100 are missed here and left to the watch's periodic full reread. |
| 2169 | * Finished job counts move whenever one job settles while its pipeline still runs, and bridge |
| 2170 | * jobs are read because their downstream pipelines are checks of their own. |
| 2171 | */ |
| 2172 | export const MERGE_REQUEST_WATCH_FINGERPRINT_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!) { |
| 2173 | project(fullPath: $fullPath) { |
| 2174 | mergeRequest(iid: $iid) { |
| 2175 | state mergeStatusEnum detailedMergeStatus conflicts diffHeadSha |
| 2176 | userPermissions { updateMergeRequest } |
| 2177 | headPipeline { |
| 2178 | id status |
| 2179 | succeeded: jobs(retried: false, statuses: [SUCCESS]) { count } |
| 2180 | failed: jobs(retried: false, statuses: [FAILED]) { count } |
| 2181 | stopped: jobs(retried: false, statuses: [CANCELED, SKIPPED]) { count } |
| 2182 | jobs(jobKind: BRIDGE, retried: false, first: 100) { |
| 2183 | pageInfo { hasNextPage } |
| 2184 | nodes { name status downstreamPipeline { id status } } |
| 2185 | } |
| 2186 | } |
| 2187 | userNotesCount |
| 2188 | notes(filter: ONLY_COMMENTS, last: 100) { |
| 2189 | nodes { lastEditedAt lastEditedBy { username } resolved } |
| 2190 | } |
| 2191 | } |
| 2192 | } |
| 2193 | }`; |
| 2194 | |
| 2195 | const PipelineIdentitySchema = Schema.Struct({ id: Schema.String, status: Schema.String }); |
| 2196 | const JobCountSchema = Schema.NullOr(Schema.Struct({ count: Schema.Int })); |
| 2197 | // GitLab's connection `count` stops at its default limit and answers `limit + 1` above it. |
| 2198 | const JOB_COUNT_LIMIT = 1000; |
| 2199 | |
| 2200 | const decodeMergeRequestWatchFingerprint = decodeJsonResult( |
| 2201 | Schema.Struct({ |
| 2202 | data: Schema.Struct({ |
| 2203 | project: Schema.NullOr( |
| 2204 | Schema.Struct({ |
| 2205 | mergeRequest: Schema.NullOr( |
| 2206 | Schema.Struct({ |
| 2207 | state: Schema.String, |
| 2208 | mergeStatusEnum: Schema.NullOr(Schema.String), |
| 2209 | detailedMergeStatus: Schema.optional(Schema.NullOr(Schema.String)), |
| 2210 | conflicts: Schema.Boolean, |
| 2211 | diffHeadSha: Schema.NullOr(Schema.String), |
| 2212 | userPermissions: Schema.Struct({ updateMergeRequest: Schema.Boolean }), |
| 2213 | headPipeline: Schema.NullOr( |
| 2214 | Schema.Struct({ |
| 2215 | ...PipelineIdentitySchema.fields, |
| 2216 | succeeded: JobCountSchema, |
| 2217 | failed: JobCountSchema, |
| 2218 | stopped: JobCountSchema, |
| 2219 | jobs: Schema.NullOr( |
| 2220 | Schema.Struct({ |
| 2221 | pageInfo: Schema.Struct({ hasNextPage: Schema.Boolean }), |
| 2222 | nodes: Schema.Array( |
| 2223 | Schema.NullOr( |
| 2224 | Schema.Struct({ |
| 2225 | name: Schema.NullOr(Schema.String), |
| 2226 | status: Schema.NullOr(Schema.String), |
| 2227 | downstreamPipeline: Schema.NullOr(PipelineIdentitySchema), |
| 2228 | }), |
| 2229 | ), |
| 2230 | ), |
| 2231 | }), |
| 2232 | ), |
| 2233 | }), |
| 2234 | ), |
| 2235 | userNotesCount: Schema.NullOr(Schema.Int), |
| 2236 | notes: Schema.Struct({ |
| 2237 | nodes: Schema.Array( |
| 2238 | Schema.NullOr( |
| 2239 | Schema.Struct({ |
| 2240 | lastEditedAt: Schema.NullOr(Schema.String), |
| 2241 | lastEditedBy: Schema.NullOr( |
| 2242 | Schema.Struct({ username: Schema.NullOr(Schema.String) }), |
| 2243 | ), |
| 2244 | resolved: Schema.NullOr(Schema.Boolean), |
| 2245 | }), |
| 2246 | ), |
| 2247 | ), |
| 2248 | }), |
| 2249 | }), |
| 2250 | ), |
| 2251 | }), |
| 2252 | ), |
| 2253 | }), |
| 2254 | }), |
| 2255 | ); |
| 2256 | |
| 2257 | /** Null when GitLab returned no merge request, so the watch falls back to full reads. */ |
| 2258 | export function decodeMergeRequestWatchFingerprintJson( |
| 2259 | raw: string, |
| 2260 | ): Result.Result<ProviderChangeRequestWatchFingerprint | null, DecodeFailure> { |
| 2261 | const decoded = decodeMergeRequestWatchFingerprint(raw); |
| 2262 | if (!Result.isSuccess(decoded)) { |
| 2263 | return Result.fail(decoded.failure); |
| 2264 | } |
| 2265 | const mr = decoded.success.data.project?.mergeRequest; |
| 2266 | if (mr == null) return Result.succeed(null); |
| 2267 | const newestEdit = mr.notes.nodes.reduce((newest, note) => { |
| 2268 | const editedAt = textEditedAt(note); |
| 2269 | return editedAt !== null && editedAt > newest ? editedAt : newest; |
| 2270 | }, ""); |
| 2271 | const pipeline = mr.headPipeline; |
| 2272 | const jobCounts = [pipeline?.succeeded, pipeline?.failed, pipeline?.stopped].map( |
| 2273 | (jobs) => jobs?.count ?? null, |
| 2274 | ); |
| 2275 | // Past a capped count or the first bridge page, a job can settle without moving the status. |
| 2276 | const seesEveryJob = |
| 2277 | pipeline?.jobs?.pageInfo.hasNextPage !== true && |
| 2278 | jobCounts.every((count) => count === null || count <= JOB_COUNT_LIMIT); |
| 2279 | const bridges = (pipeline?.jobs?.nodes ?? []) |
| 2280 | .flatMap((job) => |
| 2281 | job === null |
| 2282 | ? [] |
| 2283 | : [ |
| 2284 | [job.name, job.status, job.downstreamPipeline?.id, job.downstreamPipeline?.status] |
| 2285 | .map((part) => part ?? "") |
| 2286 | .join(":"), |
| 2287 | ], |
| 2288 | ) |
| 2289 | .toSorted() |
| 2290 | .join(","); |
| 2291 | return Result.succeed({ |
| 2292 | status: [ |
| 2293 | mr.state, |
| 2294 | mr.mergeStatusEnum ?? "", |
| 2295 | mr.detailedMergeStatus ?? "", |
| 2296 | mr.conflicts, |
| 2297 | mr.diffHeadSha ?? "", |
| 2298 | pipeline?.id ?? "", |
| 2299 | pipeline?.status ?? "", |
| 2300 | jobCounts.map((count) => count ?? "").join("/"), |
| 2301 | bridges, |
| 2302 | ].join(" "), |
| 2303 | remarks: [mr.userNotesCount ?? "", newestEdit].join(" "), |
| 2304 | // GraphQL never asks GitLab to recheck mergeability. The REST detail read does, but only for |
| 2305 | // viewers who can update the merge request, so only they keep detail reads going until it settles. |
| 2306 | coversDetail: |
| 2307 | seesEveryJob && |
| 2308 | (mr.conflicts || |
| 2309 | !mr.userPermissions.updateMergeRequest || |
| 2310 | mr.mergeStatusEnum === "CAN_BE_MERGED" || |
| 2311 | mr.mergeStatusEnum === "CANNOT_BE_MERGED"), |
| 2312 | }); |
| 2313 | } |