The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import { removeAgentCredits } from "@t3tools/source-control-core/server/mergeMessage"; |
| 2 | import { isCommitSha } from "@t3tools/source-control-core/server/pullRequestUtils"; |
| 3 | import { |
| 4 | diffFileSection, |
| 5 | truncateLongDiffLines, |
| 6 | } from "@t3tools/source-control-core/server/diffFileRevisions"; |
| 7 | import * as Context from "effect/Context"; |
| 8 | import * as Digest from "effect/crypto/Digest"; |
| 9 | import * as DateTime from "effect/DateTime"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Layer from "effect/Layer"; |
| 12 | import * as Option from "effect/Option"; |
| 13 | import * as Result from "effect/Result"; |
| 14 | import * as Schema from "effect/Schema"; |
| 15 | import { resolvePullRequestAuthorFilter, VcsProcessExitError } from "@t3tools/contracts"; |
| 16 | import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath"; |
| 17 | import type { |
| 18 | PullRequestAction, |
| 19 | PullRequestActor, |
| 20 | PullRequestReferenceCandidate, |
| 21 | PullRequestReferenceSigil, |
| 22 | PullRequestCheck, |
| 23 | PullRequestComment, |
| 24 | PullRequestCommit, |
| 25 | PullRequestInvolvement, |
| 26 | PullRequestLabel, |
| 27 | PullRequestLabelCandidateList, |
| 28 | PullRequestListFilters, |
| 29 | PullRequestListState, |
| 30 | PullRequestMergeCapabilities, |
| 31 | PullRequestMergeMethod, |
| 32 | PullRequestOmittedFileStat, |
| 33 | PullRequestReaction, |
| 34 | PullRequestReactionContent, |
| 35 | PullRequestReviewCommentDraft, |
| 36 | PullRequestReviewPosition, |
| 37 | PullRequestConversationThread, |
| 38 | PullRequestReviewVerdict, |
| 39 | PullRequestReviewerCandidateList, |
| 40 | } from "@t3tools/contracts"; |
| 41 | |
| 42 | import * as GitLabCli from "./GitLabCli.ts"; |
| 43 | import { |
| 44 | AWARD_EMOJI_GRAPHQL_QUERY, |
| 45 | PIPELINE_STAGES_GRAPHQL_QUERY, |
| 46 | decodeAwardEmojiJson, |
| 47 | decodeBranchJson, |
| 48 | decodeCommitDiffRefsJson, |
| 49 | decodeCommitsJson, |
| 50 | decodeDiffRefsJson, |
| 51 | decodeRevertTargetJson, |
| 52 | decodeDiscussionsJson, |
| 53 | decodeMaintainerEditsPermissionJson, |
| 54 | decodeLabelNameJson, |
| 55 | decodeLabelPermissionJson, |
| 56 | decodeMergeMessagesJson, |
| 57 | decodeMergeRequestDetailJson, |
| 58 | decodeMergeRequestDiffsJson, |
| 59 | decodeMergeRequestChangesJson, |
| 60 | decodeGraphqlListSupportJson, |
| 61 | decodeMergeRequestGraphqlListJson, |
| 62 | decodeMergeRequestListJson, |
| 63 | decodeMergeRequestFileStatsJson, |
| 64 | decodeMergeRequestWatchFingerprintJson, |
| 65 | decodeMergeRequestStatsJson, |
| 66 | decodeMutationErrorsJson, |
| 67 | decodeNotesJson, |
| 68 | decodeOwnAwardIdJson, |
| 69 | decodePipelineStageChecksJson, |
| 70 | decodeProjectMergeCapabilitiesJson, |
| 71 | decodeProjectLabelsJson, |
| 72 | decodeProjectUsersJson, |
| 73 | decodeReferenceCandidatesJson, |
| 74 | decodeRepositoryBlobsJson, |
| 75 | decodeListStatesJson, |
| 76 | decodeSourceBranchJson, |
| 77 | decodeTriggerJobChecksJson, |
| 78 | decodeViewerJson, |
| 79 | gitLabAwardName, |
| 80 | MAINTAINER_EDITS_PERMISSION_GRAPHQL_QUERY, |
| 81 | LABEL_PERMISSION_GRAPHQL_QUERY, |
| 82 | MERGE_MESSAGES_GRAPHQL_QUERY, |
| 83 | MERGE_REQUEST_FILE_STATS_GRAPHQL_QUERY, |
| 84 | MERGE_REQUEST_WATCH_FINGERPRINT_GRAPHQL_QUERY, |
| 85 | MERGE_REQUEST_STATS_GRAPHQL_QUERY, |
| 86 | REPOSITORY_BLOBS_GRAPHQL_QUERY, |
| 87 | LIST_ITEM_GRAPHQL_FIELDS, |
| 88 | LIST_STATES_GRAPHQL_QUERY, |
| 89 | SERVER_VERSION_GRAPHQL_QUERY, |
| 90 | SOURCE_BRANCH_GRAPHQL_QUERY, |
| 91 | type GitLabDiffRefs, |
| 92 | type GitLabMergeRequestDetail, |
| 93 | type GitLabMergeRequestListItem, |
| 94 | type GitLabMergeRequestListState, |
| 95 | type GitLabProjectUsers, |
| 96 | } from "./gitLabMergeRequestJson.ts"; |
| 97 | import type { |
| 98 | ProviderChangeRequestSummary, |
| 99 | ProviderChangeRequestWatchFingerprint, |
| 100 | ProviderFileStats, |
| 101 | ProviderListCursor, |
| 102 | } from "@t3tools/source-control-core/server/PullRequestProvider"; |
| 103 | |
| 104 | export class GitLabMergeRequestReadError extends Schema.TaggedError<GitLabMergeRequestReadError>()( |
| 105 | "GitLabMergeRequestReadError", |
| 106 | { |
| 107 | command: Schema.Literal("glab"), |
| 108 | cwd: Schema.String, |
| 109 | operation: Schema.String, |
| 110 | cause: Schema.Defect(), |
| 111 | }, |
| 112 | ) { |
| 113 | get detail(): string { |
| 114 | return `GitLab CLI returned an unreadable ${this.operation} response.`; |
| 115 | } |
| 116 | |
| 117 | override get message(): string { |
| 118 | return `GitLab CLI failed in ${this.operation}: ${this.detail}`; |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | export class GitLabViewerUnavailableError extends Schema.TaggedError<GitLabViewerUnavailableError>()( |
| 123 | "GitLabViewerUnavailableError", |
| 124 | { |
| 125 | command: Schema.Literal("glab"), |
| 126 | cwd: Schema.String, |
| 127 | }, |
| 128 | ) { |
| 129 | get detail(): string { |
| 130 | return "GitLab CLI returned no username for the authenticated account."; |
| 131 | } |
| 132 | |
| 133 | override get message(): string { |
| 134 | return `GitLab CLI failed in getViewerUsername: ${this.detail}`; |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | export class GitLabDiffRefsUnavailableError extends Schema.TaggedError<GitLabDiffRefsUnavailableError>()( |
| 139 | "GitLabDiffRefsUnavailableError", |
| 140 | { |
| 141 | command: Schema.Literal("glab"), |
| 142 | cwd: Schema.String, |
| 143 | number: Schema.Int, |
| 144 | }, |
| 145 | ) { |
| 146 | get detail(): string { |
| 147 | return "The merge request reported no diff revisions."; |
| 148 | } |
| 149 | |
| 150 | override get message(): string { |
| 151 | return `GitLab CLI failed in getDiffRefs: ${this.detail}`; |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | export class GitLabRevertUnavailableError extends Schema.TaggedError<GitLabRevertUnavailableError>()( |
| 156 | "GitLabRevertUnavailableError", |
| 157 | { |
| 158 | command: Schema.Literal("glab"), |
| 159 | cwd: Schema.String, |
| 160 | number: Schema.Int, |
| 161 | reason: Schema.Literals(["not-merged", "several-commits"]), |
| 162 | }, |
| 163 | ) { |
| 164 | get detail(): string { |
| 165 | return this.reason === "not-merged" |
| 166 | ? "Only a merged merge request can be reverted." |
| 167 | : "This merge request landed as several commits, so there is no single commit to revert."; |
| 168 | } |
| 169 | |
| 170 | override get message(): string { |
| 171 | return `GitLab CLI failed in runMergeRequestAction: ${this.detail}`; |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | export class GitLabDiffCursorError extends Schema.TaggedError<GitLabDiffCursorError>()( |
| 176 | "GitLabDiffCursorError", |
| 177 | { |
| 178 | command: Schema.Literal("glab"), |
| 179 | cwd: Schema.String, |
| 180 | }, |
| 181 | ) { |
| 182 | get detail(): string { |
| 183 | return "The diff cursor was not one this merge request handed out."; |
| 184 | } |
| 185 | |
| 186 | override get message(): string { |
| 187 | return `GitLab CLI failed in getMergeRequestDiff: ${this.detail}`; |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | export class GitLabDiffCommitError extends Schema.TaggedError<GitLabDiffCommitError>()( |
| 192 | "GitLabDiffCommitError", |
| 193 | { |
| 194 | command: Schema.Literal("glab"), |
| 195 | cwd: Schema.String, |
| 196 | }, |
| 197 | ) { |
| 198 | get detail(): string { |
| 199 | return "The named commit was not a commit sha."; |
| 200 | } |
| 201 | |
| 202 | override get message(): string { |
| 203 | return `GitLab CLI failed in getMergeRequestDiff: ${this.detail}`; |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | export class GitLabDiffCommitParentUnavailableError extends Schema.TaggedError<GitLabDiffCommitParentUnavailableError>()( |
| 208 | "GitLabDiffCommitParentUnavailableError", |
| 209 | { |
| 210 | command: Schema.Literal("glab"), |
| 211 | cwd: Schema.String, |
| 212 | commit: Schema.String, |
| 213 | }, |
| 214 | ) { |
| 215 | get detail(): string { |
| 216 | return `Commit ${this.commit} reported no parent revision.`; |
| 217 | } |
| 218 | |
| 219 | override get message(): string { |
| 220 | return `GitLab CLI failed in getMergeRequestDiffFileContents: ${this.detail}`; |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | export class GitLabDiffFileContentsUnavailableError extends Schema.TaggedError<GitLabDiffFileContentsUnavailableError>()( |
| 225 | "GitLabDiffFileContentsUnavailableError", |
| 226 | { |
| 227 | command: Schema.Literal("glab"), |
| 228 | cwd: Schema.String, |
| 229 | path: Schema.String, |
| 230 | reason: Schema.Literals(["oversized", "binary"]), |
| 231 | }, |
| 232 | ) { |
| 233 | get detail(): string { |
| 234 | return this.reason === "oversized" |
| 235 | ? `The diff file '${this.path}' exceeds the 1 MB expansion limit.` |
| 236 | : `The diff file '${this.path}' is binary.`; |
| 237 | } |
| 238 | |
| 239 | override get message(): string { |
| 240 | return `GitLab CLI failed in getMergeRequestDiffFileContents: ${this.detail}`; |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | export class GitLabMutationRefusedError extends Schema.TaggedError<GitLabMutationRefusedError>()( |
| 245 | "GitLabMutationRefusedError", |
| 246 | { |
| 247 | command: Schema.Literal("glab"), |
| 248 | cwd: Schema.String, |
| 249 | operation: Schema.String, |
| 250 | reasons: Schema.Array(Schema.String), |
| 251 | }, |
| 252 | ) { |
| 253 | get detail(): string { |
| 254 | return `GitLab refused it: ${this.reasons.join("; ")}`; |
| 255 | } |
| 256 | |
| 257 | override get message(): string { |
| 258 | return `GitLab CLI failed in ${this.operation}: ${this.detail}`; |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | const SET_SELF_AS_REVIEWER_MUTATION = `mutation($projectPath: ID!, $iid: String!, $reviewers: [String!]!) { |
| 263 | mergeRequestSetReviewers( |
| 264 | input: { projectPath: $projectPath, iid: $iid, reviewerUsernames: $reviewers, operationMode: APPEND } |
| 265 | ) { errors } |
| 266 | }`; |
| 267 | |
| 268 | const REQUEST_CHANGES_MUTATION = `mutation($projectPath: ID!, $iid: String!) { |
| 269 | mergeRequestRequestChanges(input: { projectPath: $projectPath, iid: $iid }) { errors } |
| 270 | }`; |
| 271 | |
| 272 | export class GitLabBranchDeletionRefusedError extends Schema.TaggedError<GitLabBranchDeletionRefusedError>()( |
| 273 | "GitLabBranchDeletionRefusedError", |
| 274 | { |
| 275 | command: Schema.Literal("glab"), |
| 276 | cwd: Schema.String, |
| 277 | number: Schema.Int, |
| 278 | reason: Schema.Literals([ |
| 279 | "open", |
| 280 | "not-allowed", |
| 281 | "source-unavailable", |
| 282 | "default-branch", |
| 283 | "head-changed", |
| 284 | ]), |
| 285 | }, |
| 286 | ) { |
| 287 | get detail(): string { |
| 288 | switch (this.reason) { |
| 289 | case "open": |
| 290 | return `Close or merge merge request !${this.number} before deleting its source branch.`; |
| 291 | case "not-allowed": |
| 292 | return "GitLab does not let you delete this source branch. It may be protected, or you may not be able to push to it."; |
| 293 | case "source-unavailable": |
| 294 | return `GitLab did not report a source project for merge request !${this.number}.`; |
| 295 | case "default-branch": |
| 296 | return "The source branch is its project's default branch and cannot be deleted here."; |
| 297 | case "head-changed": |
| 298 | return "The source branch has new commits and was not deleted."; |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | override get message(): string { |
| 303 | return `GitLab CLI failed in deleteSourceBranch: ${this.detail}`; |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | export class GitLabUnknownLabelError extends Schema.TaggedError<GitLabUnknownLabelError>()( |
| 308 | "GitLabUnknownLabelError", |
| 309 | { |
| 310 | command: Schema.Literal("glab"), |
| 311 | cwd: Schema.String, |
| 312 | labels: Schema.Array(Schema.String), |
| 313 | }, |
| 314 | ) { |
| 315 | get detail(): string { |
| 316 | return `The project has no label named ${this.labels.map((label) => `"${label}"`).join(", ")}.`; |
| 317 | } |
| 318 | |
| 319 | override get message(): string { |
| 320 | return `GitLab CLI failed in setLabels: ${this.detail}`; |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | export type GitLabPullRequestCliError = |
| 325 | | GitLabCli.GitLabCliError |
| 326 | | GitLabBranchDeletionRefusedError |
| 327 | | GitLabMergeRequestReadError |
| 328 | | GitLabUnknownLabelError |
| 329 | | GitLabDiffCursorError |
| 330 | | GitLabDiffCommitError |
| 331 | | GitLabDiffCommitParentUnavailableError |
| 332 | | GitLabDiffFileContentsUnavailableError |
| 333 | | GitLabDiffRefsUnavailableError |
| 334 | | GitLabRevertUnavailableError |
| 335 | | GitLabViewerUnavailableError |
| 336 | | GitLabMutationRefusedError; |
| 337 | |
| 338 | /** GitLab's `per_page` limit. */ |
| 339 | const MAX_PAGE_SIZE = 100; |
| 340 | const COMMIT_PAGE_SIZE = 100; |
| 341 | /** |
| 342 | * GitLab 15.7 through 17.10 answer the merge request `/diffs` endpoint with a 500 for any |
| 343 | * `per_page` above 30 (fixed in 17.11), so those pages stay at a size every version accepts. |
| 344 | * A commit's own diff endpoint never had that bug and keeps the full page. |
| 345 | */ |
| 346 | const MERGE_REQUEST_DIFF_PAGE_SIZE = 30; |
| 347 | const diffPageSize = (commit: string | undefined) => |
| 348 | commit === undefined ? MERGE_REQUEST_DIFF_PAGE_SIZE : MAX_PAGE_SIZE; |
| 349 | const CONVERSATION_PAGES = 10; |
| 350 | const DIFF_MAX_OUTPUT_BYTES = 8 * 1024 * 1024; |
| 351 | const DIFF_TIMEOUT_MS = 60_000; |
| 352 | const WITHHELD_FILE_DIFF_MAX_OUTPUT_BYTES = 32 * 1024 * 1024; |
| 353 | // Withheld files are often generated or minified, where one line can be megabytes. |
| 354 | const WITHHELD_FILE_MAX_LINE_LENGTH = 1_000; |
| 355 | const isVcsProcessExitError = Schema.is(VcsProcessExitError); |
| 356 | const DIFF_FILE_MAX_OUTPUT_BYTES = 1024 * 1024; |
| 357 | // REST list rows carry full descriptions, so a page can pass the 1 MB default output cap. |
| 358 | const MERGE_REQUEST_LIST_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; |
| 359 | |
| 360 | export interface GitLabDiscussionThreads { |
| 361 | readonly threads: ReadonlyArray<PullRequestConversationThread>; |
| 362 | readonly diffRefsByThreadId: ReadonlyMap<string, GitLabDiffRefs>; |
| 363 | readonly overviewFindingIds: ReadonlyArray<string>; |
| 364 | readonly truncated: boolean; |
| 365 | } |
| 366 | |
| 367 | export interface GitLabMergeRequestListBatch { |
| 368 | readonly items: ReadonlyArray<GitLabMergeRequestListItem>; |
| 369 | readonly truncated: boolean; |
| 370 | readonly cursorAdvance: number; |
| 371 | /** GitLab's GraphQL cursor past the last row, when the page was read through GraphQL. */ |
| 372 | readonly resumeAfter?: string; |
| 373 | /** Present when the read already carried each row's approval and pipeline state. */ |
| 374 | readonly listStates?: ReadonlyMap<number, GitLabMergeRequestListState>; |
| 375 | } |
| 376 | |
| 377 | export interface GitLabMergeRequestDiffSlice { |
| 378 | readonly patch: string; |
| 379 | readonly truncated: boolean; |
| 380 | readonly nextCursor: string | null; |
| 381 | readonly omittedFileStats?: ReadonlyArray<PullRequestOmittedFileStat>; |
| 382 | readonly withheldFilesReadable?: boolean; |
| 383 | } |
| 384 | |
| 385 | export class GitLabPullRequestCli extends Context.Service< |
| 386 | GitLabPullRequestCli, |
| 387 | { |
| 388 | readonly getViewerUsername: (input: { |
| 389 | readonly cwd: string; |
| 390 | readonly host?: string | undefined; |
| 391 | }) => Effect.Effect<string, GitLabPullRequestCliError>; |
| 392 | |
| 393 | readonly listMergeRequests: (input: { |
| 394 | readonly cwd: string; |
| 395 | readonly host?: string | undefined; |
| 396 | readonly repository: string; |
| 397 | readonly state: PullRequestListState; |
| 398 | readonly involvement: PullRequestInvolvement; |
| 399 | readonly viewer: string; |
| 400 | readonly limit: number; |
| 401 | readonly query?: string | undefined; |
| 402 | readonly cursor?: ProviderListCursor | undefined; |
| 403 | readonly filters?: PullRequestListFilters | undefined; |
| 404 | /** |
| 405 | * Read a first page through GraphQL, which narrows more filters; see `supportsGraphqlList`. |
| 406 | * A cursor keeps the API that handed it out. |
| 407 | */ |
| 408 | readonly graphql?: boolean; |
| 409 | }) => Effect.Effect<GitLabMergeRequestListBatch, GitLabPullRequestCliError>; |
| 410 | |
| 411 | /** Whether this host's GraphQL list takes every filter the REST list does. */ |
| 412 | readonly supportsGraphqlList: (input: { |
| 413 | readonly cwd: string; |
| 414 | readonly host?: string | undefined; |
| 415 | }) => Effect.Effect<boolean, GitLabPullRequestCliError>; |
| 416 | |
| 417 | readonly getMergeRequestDetail: (input: { |
| 418 | readonly cwd: string; |
| 419 | readonly host?: string | undefined; |
| 420 | readonly repository: string; |
| 421 | readonly number: number; |
| 422 | /** `false` skips the stage and trigger job reads, as write permission checks do. */ |
| 423 | readonly downstreamChecks?: boolean; |
| 424 | /** `false` skips a fork's maintainer edits permission read, for views that never show it. */ |
| 425 | readonly maintainerEdits?: boolean; |
| 426 | }) => Effect.Effect<GitLabMergeRequestDetail, GitLabPullRequestCliError>; |
| 427 | |
| 428 | /** Approval and head pipeline state, read in one GraphQL request per 100 merge requests. */ |
| 429 | readonly getListStates: (input: { |
| 430 | readonly cwd: string; |
| 431 | readonly host?: string | undefined; |
| 432 | readonly repository: string; |
| 433 | readonly numbers: ReadonlyArray<number>; |
| 434 | }) => Effect.Effect< |
| 435 | ReadonlyMap<number, GitLabMergeRequestListState>, |
| 436 | GitLabPullRequestCliError |
| 437 | >; |
| 438 | |
| 439 | /** Line counts for the given merge requests; one with no answer is left out. */ |
| 440 | readonly listMergeRequestStats: (input: { |
| 441 | readonly cwd: string; |
| 442 | readonly host?: string | undefined; |
| 443 | readonly changeRequests: ReadonlyArray<{ |
| 444 | readonly repository: string; |
| 445 | readonly number: number; |
| 446 | }>; |
| 447 | }) => Effect.Effect< |
| 448 | ReadonlyArray<{ |
| 449 | readonly repository: string; |
| 450 | readonly number: number; |
| 451 | readonly additions: number; |
| 452 | readonly deletions: number; |
| 453 | }>, |
| 454 | GitLabPullRequestCliError |
| 455 | >; |
| 456 | |
| 457 | readonly getMergeRequestFileStats: (input: { |
| 458 | readonly cwd: string; |
| 459 | readonly host?: string | undefined; |
| 460 | readonly repository: string; |
| 461 | readonly number: number; |
| 462 | }) => Effect.Effect<ProviderFileStats, GitLabPullRequestCliError>; |
| 463 | |
| 464 | readonly getMergeRequestWatchFingerprint: (input: { |
| 465 | readonly cwd: string; |
| 466 | readonly host?: string | undefined; |
| 467 | readonly repository: string; |
| 468 | readonly number: number; |
| 469 | }) => Effect.Effect<ProviderChangeRequestWatchFingerprint | null, GitLabPullRequestCliError>; |
| 470 | |
| 471 | readonly listNotes: (input: { |
| 472 | readonly cwd: string; |
| 473 | readonly host?: string | undefined; |
| 474 | readonly repository: string; |
| 475 | readonly number: number; |
| 476 | }) => Effect.Effect< |
| 477 | { readonly comments: ReadonlyArray<PullRequestComment>; readonly truncated: boolean }, |
| 478 | GitLabPullRequestCliError |
| 479 | >; |
| 480 | |
| 481 | readonly listCommits: (input: { |
| 482 | readonly cwd: string; |
| 483 | readonly host?: string | undefined; |
| 484 | readonly repository: string; |
| 485 | readonly number: number; |
| 486 | }) => Effect.Effect<ReadonlyArray<PullRequestCommit>, GitLabPullRequestCliError>; |
| 487 | |
| 488 | readonly getMergeRequestDiff: (input: { |
| 489 | readonly cwd: string; |
| 490 | readonly host?: string | undefined; |
| 491 | readonly repository: string; |
| 492 | readonly number: number; |
| 493 | readonly cursor?: string | undefined; |
| 494 | readonly commit?: string | undefined; |
| 495 | /** Reads one file a page withheld as too large; ignores `cursor`. */ |
| 496 | readonly path?: string | undefined; |
| 497 | }) => Effect.Effect<GitLabMergeRequestDiffSlice, GitLabPullRequestCliError>; |
| 498 | |
| 499 | readonly getMergeRequestDiffFileContents: (input: { |
| 500 | readonly cwd: string; |
| 501 | readonly host?: string | undefined; |
| 502 | readonly repository: string; |
| 503 | readonly number: number; |
| 504 | readonly commit?: string | undefined; |
| 505 | readonly changeType: "change" | "rename-pure" | "rename-changed" | "new" | "deleted"; |
| 506 | readonly oldPath: string; |
| 507 | readonly newPath: string; |
| 508 | }) => Effect.Effect< |
| 509 | { readonly oldContents: string; readonly newContents: string }, |
| 510 | GitLabPullRequestCliError |
| 511 | >; |
| 512 | |
| 513 | readonly getProjectMergeCapabilities: (input: { |
| 514 | readonly cwd: string; |
| 515 | readonly host?: string | undefined; |
| 516 | readonly repository: string; |
| 517 | }) => Effect.Effect<PullRequestMergeCapabilities, GitLabPullRequestCliError>; |
| 518 | |
| 519 | readonly getFileRevisions: (input: { |
| 520 | readonly cwd: string; |
| 521 | readonly host?: string | undefined; |
| 522 | readonly repository: string; |
| 523 | readonly number: number; |
| 524 | readonly paths: ReadonlyArray<string>; |
| 525 | }) => Effect.Effect<ReadonlyMap<string, string>, GitLabPullRequestCliError>; |
| 526 | |
| 527 | readonly listReviewerCandidates: (input: { |
| 528 | readonly cwd: string; |
| 529 | readonly host?: string | undefined; |
| 530 | readonly repository: string; |
| 531 | readonly number: number; |
| 532 | readonly query?: string | undefined; |
| 533 | }) => Effect.Effect<PullRequestReviewerCandidateList, GitLabPullRequestCliError>; |
| 534 | |
| 535 | readonly listProjectLabels: (input: { |
| 536 | readonly cwd: string; |
| 537 | readonly host?: string | undefined; |
| 538 | readonly repository: string; |
| 539 | readonly search?: string | undefined; |
| 540 | }) => Effect.Effect< |
| 541 | { readonly items: ReadonlyArray<PullRequestLabel>; readonly truncated: boolean }, |
| 542 | GitLabPullRequestCliError |
| 543 | >; |
| 544 | |
| 545 | readonly listLabelCandidates: (input: { |
| 546 | readonly cwd: string; |
| 547 | readonly host?: string | undefined; |
| 548 | readonly repository: string; |
| 549 | readonly number: number; |
| 550 | }) => Effect.Effect<PullRequestLabelCandidateList, GitLabPullRequestCliError>; |
| 551 | |
| 552 | readonly setLabels: (input: { |
| 553 | readonly cwd: string; |
| 554 | readonly host?: string | undefined; |
| 555 | readonly repository: string; |
| 556 | readonly number: number; |
| 557 | readonly labels: ReadonlyArray<string>; |
| 558 | readonly applied: boolean; |
| 559 | }) => Effect.Effect<void, GitLabPullRequestCliError>; |
| 560 | |
| 561 | readonly listProjectUsers: (input: { |
| 562 | readonly cwd: string; |
| 563 | readonly host?: string | undefined; |
| 564 | readonly repository: string; |
| 565 | readonly search?: string | undefined; |
| 566 | }) => Effect.Effect< |
| 567 | { readonly items: ReadonlyArray<PullRequestActor>; readonly truncated: boolean }, |
| 568 | GitLabPullRequestCliError |
| 569 | >; |
| 570 | |
| 571 | readonly searchProjectReferences: (input: { |
| 572 | readonly cwd: string; |
| 573 | readonly host?: string | undefined; |
| 574 | readonly repository: string; |
| 575 | readonly search?: string | undefined; |
| 576 | readonly sigil?: PullRequestReferenceSigil | undefined; |
| 577 | }) => Effect.Effect< |
| 578 | { |
| 579 | readonly items: ReadonlyArray<PullRequestReferenceCandidate>; |
| 580 | readonly truncated: boolean; |
| 581 | }, |
| 582 | GitLabPullRequestCliError |
| 583 | >; |
| 584 | |
| 585 | readonly setReviewerRequest: (input: { |
| 586 | readonly cwd: string; |
| 587 | readonly host?: string | undefined; |
| 588 | readonly repository: string; |
| 589 | readonly number: number; |
| 590 | readonly reviewers: ReadonlyArray<{ readonly id: string }>; |
| 591 | readonly requested: boolean; |
| 592 | }) => Effect.Effect<void, GitLabPullRequestCliError>; |
| 593 | |
| 594 | readonly runMergeRequestAction: (input: { |
| 595 | readonly cwd: string; |
| 596 | readonly host?: string | undefined; |
| 597 | readonly repository: string; |
| 598 | readonly number: number; |
| 599 | readonly action: PullRequestAction; |
| 600 | readonly mergeMethod?: PullRequestMergeMethod; |
| 601 | readonly removeAgentCreditsOnMerge?: boolean; |
| 602 | /** The head the caller reviewed; a merge refuses any other. */ |
| 603 | readonly expectedHeadSha?: string; |
| 604 | }) => Effect.Effect<ProviderChangeRequestSummary | void, GitLabPullRequestCliError>; |
| 605 | |
| 606 | readonly updateMergeRequest: (input: { |
| 607 | readonly cwd: string; |
| 608 | readonly host?: string | undefined; |
| 609 | readonly repository: string; |
| 610 | readonly number: number; |
| 611 | readonly title?: string | undefined; |
| 612 | readonly description?: string | undefined; |
| 613 | readonly allowCollaboration?: boolean | undefined; |
| 614 | }) => Effect.Effect<void, GitLabPullRequestCliError>; |
| 615 | |
| 616 | readonly commentOnMergeRequest: (input: { |
| 617 | readonly cwd: string; |
| 618 | readonly host?: string | undefined; |
| 619 | readonly repository: string; |
| 620 | readonly number: number; |
| 621 | readonly body: string; |
| 622 | }) => Effect.Effect<void, GitLabPullRequestCliError>; |
| 623 | |
| 624 | readonly updateNote: (input: { |
| 625 | readonly cwd: string; |
| 626 | readonly host?: string | undefined; |
| 627 | readonly repository: string; |
| 628 | readonly number: number; |
| 629 | readonly noteId: string; |
| 630 | readonly body: string; |
| 631 | }) => Effect.Effect<void, GitLabPullRequestCliError>; |
| 632 | |
| 633 | readonly listDiscussions: (input: { |
| 634 | readonly cwd: string; |
| 635 | readonly host?: string | undefined; |
| 636 | readonly repository: string; |
| 637 | readonly number: number; |
| 638 | }) => Effect.Effect<GitLabDiscussionThreads, GitLabPullRequestCliError>; |
| 639 | |
| 640 | readonly submitReview: (input: { |
| 641 | readonly cwd: string; |
| 642 | readonly host?: string | undefined; |
| 643 | readonly repository: string; |
| 644 | readonly number: number; |
| 645 | readonly verdict: PullRequestReviewVerdict; |
| 646 | readonly body: string; |
| 647 | readonly comments: ReadonlyArray<PullRequestReviewCommentDraft>; |
| 648 | }) => Effect.Effect<void, GitLabPullRequestCliError>; |
| 649 | |
| 650 | readonly replyToDiscussion: (input: { |
| 651 | readonly cwd: string; |
| 652 | readonly host?: string | undefined; |
| 653 | readonly repository: string; |
| 654 | readonly number: number; |
| 655 | readonly discussionId: string; |
| 656 | readonly body: string; |
| 657 | }) => Effect.Effect<void, GitLabPullRequestCliError>; |
| 658 | |
| 659 | readonly setDiscussionResolution: (input: { |
| 660 | readonly cwd: string; |
| 661 | readonly host?: string | undefined; |
| 662 | readonly repository: string; |
| 663 | readonly number: number; |
| 664 | readonly discussionId: string; |
| 665 | readonly resolved: boolean; |
| 666 | }) => Effect.Effect<void, GitLabPullRequestCliError>; |
| 667 | |
| 668 | readonly listReactions: (input: { |
| 669 | readonly cwd: string; |
| 670 | readonly host?: string | undefined; |
| 671 | readonly repository: string; |
| 672 | readonly number: number; |
| 673 | }) => Effect.Effect< |
| 674 | { |
| 675 | readonly reactions: ReadonlyArray<PullRequestReaction>; |
| 676 | readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>; |
| 677 | readonly editedAtByNoteId: ReadonlyMap<string, string>; |
| 678 | readonly botLogins: ReadonlySet<string>; |
| 679 | }, |
| 680 | GitLabPullRequestCliError |
| 681 | >; |
| 682 | |
| 683 | readonly setReaction: (input: { |
| 684 | readonly cwd: string; |
| 685 | readonly host?: string | undefined; |
| 686 | readonly repository: string; |
| 687 | readonly number: number; |
| 688 | readonly noteId?: string | undefined; |
| 689 | readonly content: PullRequestReactionContent; |
| 690 | readonly reacted: boolean; |
| 691 | }) => Effect.Effect<void, GitLabPullRequestCliError>; |
| 692 | } |
| 693 | >()("@t3tools/source-control-gitlab/server/GitLabPullRequestCli") {} |
| 694 | |
| 695 | function projectPath(repository: string): string { |
| 696 | return encodeURIComponent(repository.trim()); |
| 697 | } |
| 698 | |
| 699 | function gitLabReviewPositionLines( |
| 700 | position: PullRequestReviewPosition, |
| 701 | ): |
| 702 | | { readonly new_line: number } |
| 703 | | { readonly old_line: number } |
| 704 | | { readonly old_line: number; readonly new_line: number } { |
| 705 | switch (position.kind) { |
| 706 | case "added": |
| 707 | return { new_line: position.newLine }; |
| 708 | case "deleted": |
| 709 | return { old_line: position.oldLine }; |
| 710 | case "context": |
| 711 | return { old_line: position.oldLine, new_line: position.newLine }; |
| 712 | } |
| 713 | } |
| 714 | |
| 715 | function gitLabDiffHeader(oldPath: string, newPath: string): string { |
| 716 | return `diff --git ${quoteGitPatchPath(`a/${oldPath}`)} ${quoteGitPatchPath(`b/${newPath}`)}\n`; |
| 717 | } |
| 718 | |
| 719 | /** |
| 720 | * The old and new line counters GitLab's diff parser holds at a changed line. An added line |
| 721 | * keeps the old counter where it stands, and a removed line the new one, so neither side of a |
| 722 | * changed line's `line_code` is known without walking its hunk. |
| 723 | */ |
| 724 | function gitLabLineCounters( |
| 725 | patch: string, |
| 726 | header: string, |
| 727 | position: PullRequestReviewPosition, |
| 728 | ): { readonly old: number; readonly new: number } | undefined { |
| 729 | if (position.kind === "context") return { old: position.oldLine, new: position.newLine }; |
| 730 | const start = `\n${patch}`.indexOf(`\n${header}`); |
| 731 | if (start === -1) return undefined; |
| 732 | const end = patch.indexOf("\ndiff --git ", start + header.length - 1); |
| 733 | const section = patch.slice(start, end === -1 ? undefined : end); |
| 734 | const firstHunk = section.indexOf("\n@@ "); |
| 735 | if (firstHunk === -1) return undefined; |
| 736 | let oldLine = 0; |
| 737 | let newLine = 0; |
| 738 | for (const line of section.slice(firstHunk + 1).split("\n")) { |
| 739 | const hunk = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/u.exec(line); |
| 740 | if (hunk) { |
| 741 | oldLine = Number(hunk[1]); |
| 742 | newLine = Number(hunk[2]); |
| 743 | } else if (line.startsWith("+")) { |
| 744 | if (position.kind === "added" && newLine === position.newLine) { |
| 745 | return { old: oldLine, new: newLine }; |
| 746 | } |
| 747 | newLine += 1; |
| 748 | } else if (line.startsWith("-")) { |
| 749 | if (position.kind === "deleted" && oldLine === position.oldLine) { |
| 750 | return { old: oldLine, new: newLine }; |
| 751 | } |
| 752 | oldLine += 1; |
| 753 | } else if (line.startsWith(" ")) { |
| 754 | oldLine += 1; |
| 755 | newLine += 1; |
| 756 | } |
| 757 | } |
| 758 | return undefined; |
| 759 | } |
| 760 | |
| 761 | /** |
| 762 | * One end of a ranged comment. GitLab labels the range from `old_line`/`new_line` and `type`, |
| 763 | * the way its own UI sends them (`type` is null on a context line), and finds the lines to |
| 764 | * highlight by `line_code`, which needs both counters from the diff. |
| 765 | */ |
| 766 | function gitLabLineRangeEnd( |
| 767 | fileHash: string, |
| 768 | position: PullRequestReviewPosition, |
| 769 | counters: { readonly old: number; readonly new: number } | undefined, |
| 770 | ) { |
| 771 | const lines = gitLabReviewPositionLines(position); |
| 772 | const oldLine = counters?.old ?? ("old_line" in lines ? lines.old_line : 0); |
| 773 | const newLine = counters?.new ?? ("new_line" in lines ? lines.new_line : 0); |
| 774 | return { |
| 775 | line_code: `${fileHash}_${oldLine}_${newLine}`, |
| 776 | type: position.kind === "added" ? "new" : position.kind === "deleted" ? "old" : null, |
| 777 | ...lines, |
| 778 | }; |
| 779 | } |
| 780 | |
| 781 | const gitLabLineRange = Effect.fn("GitLabPullRequestCli.lineRange")(function* ( |
| 782 | patch: string, |
| 783 | comment: PullRequestReviewCommentDraft, |
| 784 | ) { |
| 785 | const start = comment.startPosition; |
| 786 | if (start === undefined) return {}; |
| 787 | const digest = yield* Digest.Digest; |
| 788 | const fileHash = yield* digest.digestHex(Digest.sha1, new TextEncoder().encode(comment.path)); |
| 789 | const header = gitLabDiffHeader(comment.oldPath ?? comment.path, comment.path); |
| 790 | const first = gitLabLineRangeEnd(fileHash, start, gitLabLineCounters(patch, header, start)); |
| 791 | const last = gitLabLineRangeEnd( |
| 792 | fileHash, |
| 793 | comment.position, |
| 794 | gitLabLineCounters(patch, header, comment.position), |
| 795 | ); |
| 796 | return first.line_code === last.line_code ? {} : { line_range: { start: first, end: last } }; |
| 797 | }, Effect.provide(Digest.layerWebCrypto)); |
| 798 | |
| 799 | function stateParam(state: PullRequestListState): string { |
| 800 | return state === "open" ? "opened" : state; |
| 801 | } |
| 802 | |
| 803 | function involvementParams(input: { |
| 804 | readonly involvement: PullRequestInvolvement; |
| 805 | readonly viewer: string; |
| 806 | }): ReadonlyArray<readonly [string, string]> { |
| 807 | switch (input.involvement) { |
| 808 | case "authored": |
| 809 | return [["author_username", input.viewer]]; |
| 810 | case "reviewing": |
| 811 | return [["reviewer_username", input.viewer]]; |
| 812 | case "all": |
| 813 | return []; |
| 814 | } |
| 815 | } |
| 816 | |
| 817 | /** |
| 818 | * GitLab's `labels` asks for every label it names, so only groups of one go to it; a group of |
| 819 | * alternatives is left for the service to narrow. A comma would split a name in two, and `None` |
| 820 | * and `Any` mean "unlabeled" and "labeled" to GitLab rather than labels of those names. |
| 821 | * Review filters go only where GitLab returns every row the service's exact filter keeps. |
| 822 | */ |
| 823 | function listableLabels(filters: PullRequestListFilters) { |
| 824 | const listable = (names: ReadonlyArray<string>) => |
| 825 | names.filter((name) => !name.includes(",") && !/^(?:none|any)$/iu.test(name.trim())); |
| 826 | return { |
| 827 | required: listable( |
| 828 | (filters.labels ?? []).flatMap((group) => (group.length === 1 ? group : [])), |
| 829 | ), |
| 830 | excluded: listable(filters.excludedLabels ?? []), |
| 831 | }; |
| 832 | } |
| 833 | |
| 834 | function filterParams(input: { |
| 835 | readonly filters?: PullRequestListFilters | undefined; |
| 836 | readonly involvement: PullRequestInvolvement; |
| 837 | readonly viewer: string; |
| 838 | }): ReadonlyArray<readonly [string, string]> { |
| 839 | const filters = input.filters; |
| 840 | if (filters === undefined) return []; |
| 841 | const { required, excluded } = listableLabels(filters); |
| 842 | return [ |
| 843 | ...(required.length === 0 ? [] : [["labels", required.join(",")] as const]), |
| 844 | ...(excluded.length === 0 ? [] : [["not[labels]", excluded.join(",")] as const]), |
| 845 | ...(filters.author === undefined || input.involvement === "authored" |
| 846 | ? [] |
| 847 | : [ |
| 848 | [ |
| 849 | "author_username", |
| 850 | resolvePullRequestAuthorFilter(filters.author, input.viewer), |
| 851 | ] as const, |
| 852 | ]), |
| 853 | ...(filters.draft === undefined |
| 854 | ? [] |
| 855 | : [["wip", filters.draft === "only" ? "yes" : "no"] as const]), |
| 856 | ...(filters.review === "approved" |
| 857 | ? [["approved_by_usernames[]", "Any"] as const] |
| 858 | : filters.review === "none" |
| 859 | ? [["approved_by_ids[]", "None"] as const] |
| 860 | : []), |
| 861 | ]; |
| 862 | } |
| 863 | |
| 864 | /** |
| 865 | * The GraphQL list takes the REST filters and narrows two review filters exactly: `approvedBy` |
| 866 | * Any for approved, and reviewer states for changes requested. Only arguments in use are |
| 867 | * declared, since GraphQL rejects a declared variable the query never reads. |
| 868 | */ |
| 869 | function graphqlListQuery(input: { |
| 870 | readonly repository: string; |
| 871 | readonly state: PullRequestListState; |
| 872 | readonly involvement: PullRequestInvolvement; |
| 873 | readonly viewer: string; |
| 874 | readonly query?: string | undefined; |
| 875 | readonly filters?: PullRequestListFilters | undefined; |
| 876 | readonly first: number; |
| 877 | readonly after: string | undefined; |
| 878 | }): { readonly query: string; readonly variables: Record<string, unknown> } { |
| 879 | const filters = input.filters ?? {}; |
| 880 | const { required, excluded } = listableLabels(filters); |
| 881 | const search = input.query?.trim() ?? ""; |
| 882 | const author = |
| 883 | input.involvement === "authored" |
| 884 | ? input.viewer |
| 885 | : filters.author === undefined |
| 886 | ? undefined |
| 887 | : resolvePullRequestAuthorFilter(filters.author, input.viewer); |
| 888 | const args: ReadonlyArray<readonly [name: string, type: string, value: unknown]> = [ |
| 889 | ["state", "MergeRequestState", stateParam(input.state)], |
| 890 | ...(author === undefined ? [] : [["authorUsername", "String", author] as const]), |
| 891 | ...(input.involvement === "reviewing" |
| 892 | ? [["reviewerUsername", "String", input.viewer] as const] |
| 893 | : []), |
| 894 | ...(search.length === 0 ? [] : [["search", "String", search] as const]), |
| 895 | ...(required.length === 0 ? [] : [["labels", "[String!]", required] as const]), |
| 896 | ...(filters.draft === undefined |
| 897 | ? [] |
| 898 | : [["draft", "Boolean", filters.draft === "only"] as const]), |
| 899 | ...(filters.review === "approved" ? [["approvedBy", "[String!]", ["Any"]] as const] : []), |
| 900 | // Beside `reviewerUsername`, GitLab matches review states on that reviewer alone. |
| 901 | ...(filters.review === "changes-requested" && input.involvement !== "reviewing" |
| 902 | ? [["reviewStates", "[MergeRequestReviewState!]", ["REQUESTED_CHANGES"]] as const] |
| 903 | : []), |
| 904 | ]; |
| 905 | const declarations = [ |
| 906 | "$fullPath: ID!", |
| 907 | "$first: Int!", |
| 908 | "$after: String", |
| 909 | ...args.map(([name, type]) => `$${name}: ${type}`), |
| 910 | ...(excluded.length === 0 ? [] : ["$notLabels: [String!]"]), |
| 911 | ]; |
| 912 | const usages = [ |
| 913 | "sort: UPDATED_DESC", |
| 914 | "first: $first", |
| 915 | "after: $after", |
| 916 | ...args.map(([name]) => `${name}: $${name}`), |
| 917 | ...(excluded.length === 0 ? [] : ["not: { labels: $notLabels }"]), |
| 918 | ]; |
| 919 | return { |
| 920 | query: `query(${declarations.join(", ")}) { |
| 921 | metadata { enterprise } |
| 922 | project(fullPath: $fullPath) { |
| 923 | mergeRequests(${usages.join(", ")}) { |
| 924 | pageInfo { hasNextPage endCursor } |
| 925 | nodes { ${LIST_ITEM_GRAPHQL_FIELDS} } |
| 926 | } |
| 927 | } |
| 928 | }`, |
| 929 | variables: { |
| 930 | fullPath: input.repository.trim(), |
| 931 | first: input.first, |
| 932 | after: input.after ?? null, |
| 933 | ...Object.fromEntries(args.map(([name, , value]) => [name, value])), |
| 934 | ...(excluded.length === 0 ? {} : { notLabels: excluded }), |
| 935 | }, |
| 936 | }; |
| 937 | } |
| 938 | |
| 939 | /** The list cursor carries GitLab's own position only when it fits the cursor's alphabet. */ |
| 940 | const RESUME_AFTER_PATTERN = /^[\w.:~+-]{1,128}$/u; |
| 941 | |
| 942 | function diffCursorPage(cursor: string): number | null { |
| 943 | return /^[1-9][0-9]{0,6}$/.test(cursor) ? Number(cursor) : null; |
| 944 | } |
| 945 | |
| 946 | function searchParams(search: string | undefined): ReadonlyArray<readonly [string, string]> { |
| 947 | const trimmed = search?.trim() ?? ""; |
| 948 | return trimmed.length === 0 ? [] : [["search", trimmed]]; |
| 949 | } |
| 950 | |
| 951 | // GitLab's user, issue and merge request searches answer nothing under three characters, so |
| 952 | // shorter text reads the unsearched page, which the server narrows. |
| 953 | function hostSearchParams(search: string | undefined): ReadonlyArray<readonly [string, string]> { |
| 954 | return (search?.trim().length ?? 0) >= 3 ? searchParams(search) : []; |
| 955 | } |
| 956 | |
| 957 | const REFERENCE_PAGE_SIZE = 20; |
| 958 | |
| 959 | /** |
| 960 | * Recently updated issues and merge requests, by title for text. Issue and MR search cannot match |
| 961 | * a number, so a numeric query also asks for that iid of each. |
| 962 | */ |
| 963 | export function referenceSearches( |
| 964 | search: string | undefined, |
| 965 | sigil?: PullRequestReferenceSigil | undefined, |
| 966 | ): ReadonlyArray<{ |
| 967 | readonly kind: PullRequestReferenceCandidate["kind"]; |
| 968 | readonly params: ReadonlyArray<readonly [string, string]>; |
| 969 | }> { |
| 970 | const text = search?.trim() ?? ""; |
| 971 | const numeric = /^\d+$/.test(text); |
| 972 | const recent: ReadonlyArray<readonly [string, string]> = [ |
| 973 | ["order_by", "updated_at"], |
| 974 | ["sort", "desc"], |
| 975 | ...(numeric || hostSearchParams(text).length === 0 |
| 976 | ? [] |
| 977 | : ([...hostSearchParams(text), ["in", "title"]] as const)), |
| 978 | ]; |
| 979 | const kinds = |
| 980 | sigil === "#" |
| 981 | ? (["issue"] as const) |
| 982 | : sigil === "!" |
| 983 | ? (["change-request"] as const) |
| 984 | : (["issue", "change-request"] as const); |
| 985 | return [ |
| 986 | ...(numeric ? kinds.map((kind) => ({ kind, params: [["iids[]", text]] as const })) : []), |
| 987 | ...kinds.map((kind) => ({ kind, params: recent })), |
| 988 | ]; |
| 989 | } |
| 990 | |
| 991 | function mergeReferencePages( |
| 992 | pages: ReadonlyArray<{ |
| 993 | readonly items: ReadonlyArray<PullRequestReferenceCandidate>; |
| 994 | readonly rawCount: number; |
| 995 | }>, |
| 996 | ) { |
| 997 | return { |
| 998 | items: pages.flatMap((page) => page.items), |
| 999 | truncated: pages.some((page) => page.rawCount >= REFERENCE_PAGE_SIZE), |
| 1000 | }; |
| 1001 | } |
| 1002 | |
| 1003 | function query(params: ReadonlyArray<readonly [string, string]>): string { |
| 1004 | return params.map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&"); |
| 1005 | } |
| 1006 | |
| 1007 | /** REST names every label; GraphQL's `labels(first: 100)` only colours the ones on its page. */ |
| 1008 | function colourLabels( |
| 1009 | rest: ReadonlyArray<PullRequestLabel>, |
| 1010 | graphql: ReadonlyArray<PullRequestLabel> | null, |
| 1011 | ): ReadonlyArray<PullRequestLabel> { |
| 1012 | if (graphql === null) return rest; |
| 1013 | const byName = new Map(graphql.map((label) => [label.name, label])); |
| 1014 | return rest.map((label) => byName.get(label.name) ?? label); |
| 1015 | } |
| 1016 | |
| 1017 | function actionArgs( |
| 1018 | action: PullRequestAction, |
| 1019 | mergeMethod: PullRequestMergeMethod | undefined, |
| 1020 | ): ReadonlyArray<string> { |
| 1021 | switch (action) { |
| 1022 | case "merge": |
| 1023 | return [ |
| 1024 | "merge", |
| 1025 | // glab defaults to auto-merge during a running pipeline. |
| 1026 | "--auto-merge=false", |
| 1027 | "--yes", |
| 1028 | ...(mergeMethod === "squash" ? ["--squash"] : []), |
| 1029 | ]; |
| 1030 | case "enable-auto-merge": |
| 1031 | return [ |
| 1032 | "merge", |
| 1033 | "--auto-merge=true", |
| 1034 | "--yes", |
| 1035 | ...(mergeMethod === "squash" ? ["--squash"] : []), |
| 1036 | ]; |
| 1037 | case "disable-auto-merge": |
| 1038 | return []; |
| 1039 | case "ready": |
| 1040 | return ["update", "--ready"]; |
| 1041 | case "draft": |
| 1042 | return ["update", "--draft"]; |
| 1043 | case "close": |
| 1044 | return ["close"]; |
| 1045 | case "update-branch": |
| 1046 | return ["rebase"]; |
| 1047 | case "reopen": |
| 1048 | return ["reopen"]; |
| 1049 | case "revert": |
| 1050 | return []; |
| 1051 | case "approve-workflows": |
| 1052 | case "delete-branch": |
| 1053 | throw new Error(`GitLab merge request action ${action} is unsupported`); |
| 1054 | } |
| 1055 | } |
| 1056 | |
| 1057 | /** @public */ |
| 1058 | export const make = Effect.gen(function* () { |
| 1059 | const gitlab = yield* GitLabCli.GitLabCli; |
| 1060 | |
| 1061 | const api = (input: { |
| 1062 | readonly cwd: string; |
| 1063 | readonly host?: string | undefined; |
| 1064 | readonly path: string; |
| 1065 | readonly method?: string; |
| 1066 | readonly stdin?: string; |
| 1067 | readonly headers?: ReadonlyArray<string>; |
| 1068 | readonly maxOutputBytes?: number; |
| 1069 | readonly timeoutMs?: number; |
| 1070 | }) => |
| 1071 | gitlab.execute({ |
| 1072 | cwd: input.cwd, |
| 1073 | host: input.host, |
| 1074 | args: [ |
| 1075 | "api", |
| 1076 | input.path, |
| 1077 | ...(input.method === undefined ? [] : ["--method", input.method]), |
| 1078 | // glab --input keeps payloads out of argv/logs but omits GitLab's required Content-Type. |
| 1079 | ...(input.stdin === undefined |
| 1080 | ? [] |
| 1081 | : ["--input", "-", "--header", "Content-Type: application/json"]), |
| 1082 | ...(input.headers ?? []).flatMap((header) => ["--header", header]), |
| 1083 | ], |
| 1084 | ...(input.stdin === undefined ? {} : { stdin: input.stdin }), |
| 1085 | ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }), |
| 1086 | ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }), |
| 1087 | }); |
| 1088 | |
| 1089 | const listPage = (input: { |
| 1090 | readonly cwd: string; |
| 1091 | readonly host?: string | undefined; |
| 1092 | readonly repository: string; |
| 1093 | readonly state: PullRequestListState; |
| 1094 | readonly involvement: PullRequestInvolvement; |
| 1095 | readonly viewer: string; |
| 1096 | readonly limit: number; |
| 1097 | readonly query?: string | undefined; |
| 1098 | readonly cursor?: ProviderListCursor | undefined; |
| 1099 | readonly filters?: PullRequestListFilters | undefined; |
| 1100 | readonly page: number; |
| 1101 | readonly collected: ReadonlyArray<GitLabMergeRequestListItem>; |
| 1102 | readonly cursorAdvance: number; |
| 1103 | }): Effect.Effect<GitLabMergeRequestListBatch, GitLabPullRequestCliError> => { |
| 1104 | // GitLab's timestamp filter can repeat equal-time pages forever; use offsets. |
| 1105 | const delivered = input.cursor?.delivered ?? 0; |
| 1106 | const perPage = Math.min(input.limit + 1, MAX_PAGE_SIZE); |
| 1107 | const firstPage = Math.floor(delivered / perPage) + 1; |
| 1108 | const skipOnFirstPage = input.page === firstPage ? delivered % perPage : 0; |
| 1109 | // Bound raw pages to stop recursion on entirely malformed results. |
| 1110 | const lastPage = Math.floor((delivered + input.limit) / perPage) + 1; |
| 1111 | return api({ |
| 1112 | cwd: input.cwd, |
| 1113 | host: input.host, |
| 1114 | path: `projects/${projectPath(input.repository)}/merge_requests?${query([ |
| 1115 | ["state", stateParam(input.state)], |
| 1116 | ...involvementParams(input), |
| 1117 | ...searchParams(input.query), |
| 1118 | ...filterParams(input), |
| 1119 | ["order_by", "updated_at"], |
| 1120 | ["sort", "desc"], |
| 1121 | ["with_labels_details", "true"], |
| 1122 | ["per_page", String(perPage)], |
| 1123 | ["page", String(input.page)], |
| 1124 | ])}`, |
| 1125 | maxOutputBytes: MERGE_REQUEST_LIST_MAX_OUTPUT_BYTES, |
| 1126 | }).pipe( |
| 1127 | Effect.flatMap((result) => { |
| 1128 | const raw = result.stdout.trim(); |
| 1129 | if (raw.length === 0) { |
| 1130 | return Effect.succeed({ |
| 1131 | items: input.collected, |
| 1132 | truncated: false, |
| 1133 | cursorAdvance: input.cursorAdvance, |
| 1134 | }); |
| 1135 | } |
| 1136 | const decoded = decodeMergeRequestListJson(raw); |
| 1137 | if (!Result.isSuccess(decoded)) { |
| 1138 | return Effect.fail( |
| 1139 | new GitLabMergeRequestReadError({ |
| 1140 | command: "glab", |
| 1141 | cwd: input.cwd, |
| 1142 | operation: "listMergeRequests", |
| 1143 | cause: decoded.failure, |
| 1144 | }), |
| 1145 | ); |
| 1146 | } |
| 1147 | const pageItems: GitLabMergeRequestListItem[] = []; |
| 1148 | const pageRawIndexes: number[] = []; |
| 1149 | for (const [index, item] of decoded.success.items.entries()) { |
| 1150 | const rawIndex = decoded.success.rawIndexes[index]!; |
| 1151 | if (rawIndex < skipOnFirstPage) continue; |
| 1152 | pageItems.push(item); |
| 1153 | pageRawIndexes.push(rawIndex); |
| 1154 | } |
| 1155 | const remaining = input.limit - input.collected.length; |
| 1156 | const lastItemRawIndex = pageRawIndexes[remaining - 1]; |
| 1157 | if (lastItemRawIndex !== undefined) { |
| 1158 | const consumed = lastItemRawIndex + 1 - skipOnFirstPage; |
| 1159 | return Effect.succeed({ |
| 1160 | items: [...input.collected, ...pageItems.slice(0, remaining)], |
| 1161 | truncated: |
| 1162 | lastItemRawIndex + 1 < decoded.success.rawCount || |
| 1163 | decoded.success.rawCount === perPage, |
| 1164 | cursorAdvance: input.cursorAdvance + consumed, |
| 1165 | }); |
| 1166 | } |
| 1167 | const collected = [...input.collected, ...pageItems]; |
| 1168 | const consumed = Math.max(0, decoded.success.rawCount - skipOnFirstPage); |
| 1169 | // Count malformed rows to avoid ending pagination early. |
| 1170 | const exhausted = decoded.success.rawCount < perPage; |
| 1171 | if (exhausted) { |
| 1172 | return Effect.succeed({ |
| 1173 | items: collected, |
| 1174 | truncated: false, |
| 1175 | cursorAdvance: input.cursorAdvance + consumed, |
| 1176 | }); |
| 1177 | } |
| 1178 | if (input.page >= lastPage) { |
| 1179 | return Effect.succeed({ |
| 1180 | items: collected, |
| 1181 | truncated: true, |
| 1182 | cursorAdvance: input.cursorAdvance + consumed, |
| 1183 | }); |
| 1184 | } |
| 1185 | return listPage({ |
| 1186 | ...input, |
| 1187 | page: input.page + 1, |
| 1188 | collected, |
| 1189 | cursorAdvance: input.cursorAdvance + consumed, |
| 1190 | }); |
| 1191 | }), |
| 1192 | ); |
| 1193 | }; |
| 1194 | |
| 1195 | const diffPage = (input: { |
| 1196 | readonly cwd: string; |
| 1197 | readonly host?: string | undefined; |
| 1198 | readonly repository: string; |
| 1199 | readonly number: number; |
| 1200 | readonly page: number; |
| 1201 | readonly commit?: string | undefined; |
| 1202 | }): Effect.Effect< |
| 1203 | GitLabMergeRequestDiffSlice & { |
| 1204 | readonly withheldPaths: ReadonlyArray<string>; |
| 1205 | readonly legacy: boolean; |
| 1206 | }, |
| 1207 | GitLabPullRequestCliError |
| 1208 | > => |
| 1209 | api({ |
| 1210 | cwd: input.cwd, |
| 1211 | host: input.host, |
| 1212 | path: `projects/${projectPath(input.repository)}/${ |
| 1213 | input.commit === undefined |
| 1214 | ? `merge_requests/${input.number}/diffs` |
| 1215 | : `repository/commits/${input.commit}/diff` |
| 1216 | }?${query([ |
| 1217 | ["per_page", String(diffPageSize(input.commit))], |
| 1218 | ["page", String(input.page)], |
| 1219 | ])}`, |
| 1220 | maxOutputBytes: DIFF_MAX_OUTPUT_BYTES, |
| 1221 | timeoutMs: DIFF_TIMEOUT_MS, |
| 1222 | }).pipe( |
| 1223 | Effect.map((result) => ({ result, legacy: false })), |
| 1224 | Effect.catchTags({ |
| 1225 | GitLabCliCommandError: (error) => { |
| 1226 | if ( |
| 1227 | input.commit !== undefined || |
| 1228 | input.page !== 1 || |
| 1229 | !isVcsProcessExitError(error.cause) || |
| 1230 | error.cause.failureKind !== "not-found" |
| 1231 | ) { |
| 1232 | return Effect.fail(error); |
| 1233 | } |
| 1234 | // GitLab before 15.7 has no /diffs endpoint. /changes returns one complete slice. |
| 1235 | return api({ |
| 1236 | cwd: input.cwd, |
| 1237 | host: input.host, |
| 1238 | path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/changes?access_raw_diffs=true`, |
| 1239 | maxOutputBytes: DIFF_MAX_OUTPUT_BYTES, |
| 1240 | timeoutMs: DIFF_TIMEOUT_MS, |
| 1241 | }).pipe(Effect.map((result) => ({ result, legacy: true }))); |
| 1242 | }, |
| 1243 | }), |
| 1244 | Effect.flatMap(({ result, legacy }) => { |
| 1245 | // Returning no cursor for byte-truncated JSON would lose subsequent pages. |
| 1246 | if (result.stdoutTruncated) { |
| 1247 | return Effect.fail( |
| 1248 | new GitLabMergeRequestReadError({ |
| 1249 | command: "glab", |
| 1250 | cwd: input.cwd, |
| 1251 | operation: "getMergeRequestDiff", |
| 1252 | cause: new Error( |
| 1253 | `Page ${input.page} of the merge request diff was too large to read.`, |
| 1254 | ), |
| 1255 | }), |
| 1256 | ); |
| 1257 | } |
| 1258 | const decoded = (legacy ? decodeMergeRequestChangesJson : decodeMergeRequestDiffsJson)( |
| 1259 | result.stdout.trim(), |
| 1260 | ); |
| 1261 | if (!Result.isSuccess(decoded)) { |
| 1262 | return Effect.fail( |
| 1263 | new GitLabMergeRequestReadError({ |
| 1264 | command: "glab", |
| 1265 | cwd: input.cwd, |
| 1266 | operation: "getMergeRequestDiff", |
| 1267 | cause: decoded.failure, |
| 1268 | }), |
| 1269 | ); |
| 1270 | } |
| 1271 | const patch = decoded.success.patch; |
| 1272 | // Counted before decoding, so a page whose files all failed to decode still moves on |
| 1273 | // rather than pointing the reader back at the page it just read. |
| 1274 | const morePages = !legacy && decoded.success.rawCount >= diffPageSize(input.commit); |
| 1275 | return Effect.succeed({ |
| 1276 | // Terminate slices so a hunkless header cannot run into the next slice. |
| 1277 | patch: patch.length === 0 ? patch : patch.replace(/\n?$/, "\n"), |
| 1278 | truncated: decoded.success.truncated, |
| 1279 | nextCursor: morePages ? String(input.page + 1) : null, |
| 1280 | withheldPaths: decoded.success.withheldPaths, |
| 1281 | legacy, |
| 1282 | }); |
| 1283 | }), |
| 1284 | ); |
| 1285 | |
| 1286 | /** Reads diff pages only until every header is found, for the files ranged comments sit on. */ |
| 1287 | const patchCovering = ( |
| 1288 | input: { |
| 1289 | readonly cwd: string; |
| 1290 | readonly host?: string | undefined; |
| 1291 | readonly repository: string; |
| 1292 | readonly number: number; |
| 1293 | }, |
| 1294 | headers: ReadonlyArray<string>, |
| 1295 | page: number, |
| 1296 | collected: string, |
| 1297 | ): Effect.Effect<string, GitLabPullRequestCliError> => |
| 1298 | headers.every((header) => `\n${collected}`.includes(`\n${header}`)) |
| 1299 | ? Effect.succeed(collected) |
| 1300 | : diffPage({ ...input, page }).pipe( |
| 1301 | Effect.flatMap((slice) => |
| 1302 | slice.nextCursor === null |
| 1303 | ? Effect.succeed(collected + slice.patch) |
| 1304 | : patchCovering(input, headers, page + 1, collected + slice.patch), |
| 1305 | ), |
| 1306 | ); |
| 1307 | |
| 1308 | const notesPage = (input: { |
| 1309 | readonly cwd: string; |
| 1310 | readonly host?: string | undefined; |
| 1311 | readonly repository: string; |
| 1312 | readonly number: number; |
| 1313 | readonly page: number; |
| 1314 | readonly collected: ReadonlyArray<PullRequestComment>; |
| 1315 | }): Effect.Effect< |
| 1316 | { readonly comments: ReadonlyArray<PullRequestComment>; readonly truncated: boolean }, |
| 1317 | GitLabPullRequestCliError |
| 1318 | > => |
| 1319 | api({ |
| 1320 | cwd: input.cwd, |
| 1321 | host: input.host, |
| 1322 | path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/notes?${query( |
| 1323 | [ |
| 1324 | ["per_page", String(MAX_PAGE_SIZE)], |
| 1325 | ["page", String(input.page)], |
| 1326 | ["order_by", "created_at"], |
| 1327 | ["sort", "asc"], |
| 1328 | ], |
| 1329 | )}`, |
| 1330 | }).pipe( |
| 1331 | Effect.flatMap((result) => { |
| 1332 | const decoded = decodeNotesJson(result.stdout.trim()); |
| 1333 | if (!Result.isSuccess(decoded)) { |
| 1334 | return Effect.fail( |
| 1335 | new GitLabMergeRequestReadError({ |
| 1336 | command: "glab", |
| 1337 | cwd: input.cwd, |
| 1338 | operation: "listNotes", |
| 1339 | cause: decoded.failure, |
| 1340 | }), |
| 1341 | ); |
| 1342 | } |
| 1343 | const collected = [...input.collected, ...decoded.success.comments]; |
| 1344 | if (decoded.success.rawCount < MAX_PAGE_SIZE) { |
| 1345 | return Effect.succeed({ comments: collected, truncated: false }); |
| 1346 | } |
| 1347 | return input.page >= CONVERSATION_PAGES |
| 1348 | ? Effect.succeed({ comments: collected, truncated: true }) |
| 1349 | : notesPage({ ...input, page: input.page + 1, collected }); |
| 1350 | }), |
| 1351 | ); |
| 1352 | |
| 1353 | const discussionsPage = (input: { |
| 1354 | readonly cwd: string; |
| 1355 | readonly host?: string | undefined; |
| 1356 | readonly repository: string; |
| 1357 | readonly number: number; |
| 1358 | readonly page: number; |
| 1359 | readonly collected: ReadonlyArray<PullRequestConversationThread>; |
| 1360 | readonly collectedDiffRefs: ReadonlyMap<string, GitLabDiffRefs>; |
| 1361 | readonly collectedFindingIds: ReadonlyArray<string>; |
| 1362 | }): Effect.Effect<GitLabDiscussionThreads, GitLabPullRequestCliError> => |
| 1363 | api({ |
| 1364 | cwd: input.cwd, |
| 1365 | host: input.host, |
| 1366 | path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/discussions?${query( |
| 1367 | [ |
| 1368 | ["per_page", String(MAX_PAGE_SIZE)], |
| 1369 | ["page", String(input.page)], |
| 1370 | ], |
| 1371 | )}`, |
| 1372 | }).pipe( |
| 1373 | Effect.flatMap((result) => { |
| 1374 | const decoded = decodeDiscussionsJson(result.stdout.trim()); |
| 1375 | if (!Result.isSuccess(decoded)) { |
| 1376 | return Effect.fail( |
| 1377 | new GitLabMergeRequestReadError({ |
| 1378 | command: "glab", |
| 1379 | cwd: input.cwd, |
| 1380 | operation: "listDiscussions", |
| 1381 | cause: decoded.failure, |
| 1382 | }), |
| 1383 | ); |
| 1384 | } |
| 1385 | const collected = [...input.collected, ...decoded.success.threads]; |
| 1386 | const collectedDiffRefs = new Map([ |
| 1387 | ...input.collectedDiffRefs, |
| 1388 | ...decoded.success.diffRefsByThreadId, |
| 1389 | ]); |
| 1390 | const collectedFindingIds = [ |
| 1391 | ...input.collectedFindingIds, |
| 1392 | ...decoded.success.overviewFindingIds, |
| 1393 | ]; |
| 1394 | const read = (truncated: boolean) => ({ |
| 1395 | threads: collected, |
| 1396 | diffRefsByThreadId: collectedDiffRefs, |
| 1397 | overviewFindingIds: collectedFindingIds, |
| 1398 | truncated, |
| 1399 | }); |
| 1400 | // Plain notes count toward the page size even when no positioned threads survive decoding. |
| 1401 | if (decoded.success.rawCount < MAX_PAGE_SIZE) return Effect.succeed(read(false)); |
| 1402 | return input.page >= CONVERSATION_PAGES |
| 1403 | ? Effect.succeed(read(true)) |
| 1404 | : discussionsPage({ |
| 1405 | ...input, |
| 1406 | page: input.page + 1, |
| 1407 | collected, |
| 1408 | collectedDiffRefs, |
| 1409 | collectedFindingIds, |
| 1410 | }); |
| 1411 | }), |
| 1412 | ); |
| 1413 | |
| 1414 | /** GitLab reverts a fast-forward merge without squash only when it landed as one commit. */ |
| 1415 | const soleCommitSha = (input: { |
| 1416 | readonly cwd: string; |
| 1417 | readonly host?: string | undefined; |
| 1418 | readonly repository: string; |
| 1419 | readonly number: number; |
| 1420 | }) => |
| 1421 | api({ |
| 1422 | cwd: input.cwd, |
| 1423 | host: input.host, |
| 1424 | path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/commits?per_page=2`, |
| 1425 | }).pipe( |
| 1426 | Effect.flatMap((result) => { |
| 1427 | const decoded = decodeCommitsJson(result.stdout.trim()); |
| 1428 | if (!Result.isSuccess(decoded)) { |
| 1429 | return Effect.fail( |
| 1430 | new GitLabMergeRequestReadError({ |
| 1431 | command: "glab", |
| 1432 | cwd: input.cwd, |
| 1433 | operation: "runMergeRequestAction", |
| 1434 | cause: decoded.failure, |
| 1435 | }), |
| 1436 | ); |
| 1437 | } |
| 1438 | const [only, ...rest] = decoded.success; |
| 1439 | return Effect.succeed(only !== undefined && rest.length === 0 ? only.oid : null); |
| 1440 | }), |
| 1441 | ); |
| 1442 | |
| 1443 | /** What GitLab's own Revert button does: revert onto a new branch and open a merge request. */ |
| 1444 | const revertMergeRequest = Effect.fn("GitLabPullRequestCli.revertMergeRequest")( |
| 1445 | function* (input: { |
| 1446 | readonly cwd: string; |
| 1447 | readonly host?: string | undefined; |
| 1448 | readonly repository: string; |
| 1449 | readonly number: number; |
| 1450 | }) { |
| 1451 | const project = `projects/${projectPath(input.repository)}`; |
| 1452 | const write = (path: string, body: object) => |
| 1453 | api({ |
| 1454 | cwd: input.cwd, |
| 1455 | host: input.host, |
| 1456 | path: `${project}/${path}`, |
| 1457 | method: "POST", |
| 1458 | stdin: JSON.stringify(body), |
| 1459 | }); |
| 1460 | const raw = yield* api({ |
| 1461 | cwd: input.cwd, |
| 1462 | host: input.host, |
| 1463 | path: `${project}/merge_requests/${input.number}`, |
| 1464 | }); |
| 1465 | const decoded = decodeRevertTargetJson(raw.stdout.trim()); |
| 1466 | if (!Result.isSuccess(decoded)) { |
| 1467 | return yield* new GitLabMergeRequestReadError({ |
| 1468 | command: "glab", |
| 1469 | cwd: input.cwd, |
| 1470 | operation: "runMergeRequestAction", |
| 1471 | cause: decoded.failure, |
| 1472 | }); |
| 1473 | } |
| 1474 | const target = decoded.success; |
| 1475 | if (!target.merged) { |
| 1476 | return yield* new GitLabRevertUnavailableError({ |
| 1477 | command: "glab", |
| 1478 | cwd: input.cwd, |
| 1479 | number: input.number, |
| 1480 | reason: "not-merged", |
| 1481 | }); |
| 1482 | } |
| 1483 | const commitSha = target.commitSha ?? (yield* soleCommitSha(input)); |
| 1484 | if (commitSha === null) { |
| 1485 | return yield* new GitLabRevertUnavailableError({ |
| 1486 | command: "glab", |
| 1487 | cwd: input.cwd, |
| 1488 | number: input.number, |
| 1489 | reason: "several-commits", |
| 1490 | }); |
| 1491 | } |
| 1492 | const branch = `revert-${commitSha.slice(0, 8)}`; |
| 1493 | yield* write("repository/branches", { branch, ref: target.targetBranch }); |
| 1494 | yield* Effect.andThen( |
| 1495 | write(`repository/commits/${commitSha}/revert`, { branch }), |
| 1496 | write("merge_requests", { |
| 1497 | source_branch: branch, |
| 1498 | target_branch: target.targetBranch, |
| 1499 | title: `Revert "${target.title}"`, |
| 1500 | description: `This reverts merge request !${input.number}`, |
| 1501 | remove_source_branch: true, |
| 1502 | }), |
| 1503 | ).pipe( |
| 1504 | // Leaving the branch behind would make every retry fail on creating it again. Runs on |
| 1505 | // interruption too, which a cancelled request or a dropped socket causes. |
| 1506 | Effect.onError(() => |
| 1507 | api({ |
| 1508 | cwd: input.cwd, |
| 1509 | host: input.host, |
| 1510 | path: `${project}/repository/branches/${encodeURIComponent(branch)}`, |
| 1511 | method: "DELETE", |
| 1512 | }).pipe(Effect.ignore), |
| 1513 | ), |
| 1514 | ); |
| 1515 | }, |
| 1516 | ); |
| 1517 | |
| 1518 | const getDiffRefs = (input: { |
| 1519 | readonly cwd: string; |
| 1520 | readonly host?: string | undefined; |
| 1521 | readonly repository: string; |
| 1522 | readonly number: number; |
| 1523 | }): Effect.Effect<GitLabDiffRefs, GitLabPullRequestCliError> => |
| 1524 | api({ |
| 1525 | cwd: input.cwd, |
| 1526 | host: input.host, |
| 1527 | path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`, |
| 1528 | }).pipe( |
| 1529 | Effect.flatMap((result): Effect.Effect<GitLabDiffRefs, GitLabPullRequestCliError> => { |
| 1530 | const decoded = decodeDiffRefsJson(result.stdout.trim()); |
| 1531 | if (!Result.isSuccess(decoded)) { |
| 1532 | return Effect.fail( |
| 1533 | new GitLabMergeRequestReadError({ |
| 1534 | command: "glab", |
| 1535 | cwd: input.cwd, |
| 1536 | operation: "getDiffRefs", |
| 1537 | cause: decoded.failure, |
| 1538 | }), |
| 1539 | ); |
| 1540 | } |
| 1541 | return decoded.success === null |
| 1542 | ? Effect.fail( |
| 1543 | new GitLabDiffRefsUnavailableError({ |
| 1544 | command: "glab", |
| 1545 | cwd: input.cwd, |
| 1546 | number: input.number, |
| 1547 | }), |
| 1548 | ) |
| 1549 | : Effect.succeed(decoded.success); |
| 1550 | }), |
| 1551 | ); |
| 1552 | |
| 1553 | const getCommitDiffRefs = (input: { |
| 1554 | readonly cwd: string; |
| 1555 | readonly host?: string | undefined; |
| 1556 | readonly repository: string; |
| 1557 | readonly commit: string; |
| 1558 | readonly allowRoot: boolean; |
| 1559 | }): Effect.Effect<GitLabDiffRefs, GitLabPullRequestCliError> => |
| 1560 | api({ |
| 1561 | cwd: input.cwd, |
| 1562 | host: input.host, |
| 1563 | path: `projects/${projectPath(input.repository)}/repository/commits/${input.commit}`, |
| 1564 | }).pipe( |
| 1565 | Effect.flatMap((result): Effect.Effect<GitLabDiffRefs, GitLabPullRequestCliError> => { |
| 1566 | const decoded = decodeCommitDiffRefsJson(result.stdout.trim()); |
| 1567 | if (!Result.isSuccess(decoded)) { |
| 1568 | return Effect.fail( |
| 1569 | new GitLabMergeRequestReadError({ |
| 1570 | command: "glab", |
| 1571 | cwd: input.cwd, |
| 1572 | operation: "getMergeRequestDiffFileContents", |
| 1573 | cause: decoded.failure, |
| 1574 | }), |
| 1575 | ); |
| 1576 | } |
| 1577 | return decoded.success === null |
| 1578 | ? input.allowRoot |
| 1579 | ? Effect.succeed({ |
| 1580 | baseSha: "", |
| 1581 | headSha: input.commit, |
| 1582 | startSha: "", |
| 1583 | }) |
| 1584 | : Effect.fail( |
| 1585 | new GitLabDiffCommitParentUnavailableError({ |
| 1586 | command: "glab", |
| 1587 | cwd: input.cwd, |
| 1588 | commit: input.commit, |
| 1589 | }), |
| 1590 | ) |
| 1591 | : Effect.succeed(decoded.success); |
| 1592 | }), |
| 1593 | ); |
| 1594 | |
| 1595 | const mergeRequestDetail = (input: { |
| 1596 | readonly cwd: string; |
| 1597 | readonly host?: string | undefined; |
| 1598 | readonly repository: string; |
| 1599 | readonly number: number; |
| 1600 | }): Effect.Effect<GitLabMergeRequestDetail, GitLabPullRequestCliError> => |
| 1601 | api({ |
| 1602 | cwd: input.cwd, |
| 1603 | host: input.host, |
| 1604 | path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}?${query([ |
| 1605 | ["include_diverged_commits_count", "true"], |
| 1606 | ])}`, |
| 1607 | }).pipe( |
| 1608 | Effect.flatMap((result) => { |
| 1609 | const decoded = decodeMergeRequestDetailJson(result.stdout.trim()); |
| 1610 | return Result.isSuccess(decoded) |
| 1611 | ? Effect.succeed(decoded.success) |
| 1612 | : Effect.fail( |
| 1613 | new GitLabMergeRequestReadError({ |
| 1614 | command: "glab", |
| 1615 | cwd: input.cwd, |
| 1616 | operation: "getMergeRequestDetail", |
| 1617 | cause: decoded.failure, |
| 1618 | }), |
| 1619 | ); |
| 1620 | }), |
| 1621 | ); |
| 1622 | |
| 1623 | // Best-effort: a trigger job read that fails, or a full page that may have left out the one |
| 1624 | // whose pipeline failed, adds no rows and leaves the detail as it was. |
| 1625 | const triggerJobChecks = (input: { |
| 1626 | readonly cwd: string; |
| 1627 | readonly pipeline: { readonly id: number; readonly projectId: number }; |
| 1628 | }): Effect.Effect<ReadonlyArray<PullRequestCheck>> => |
| 1629 | api({ |
| 1630 | cwd: input.cwd, |
| 1631 | // `bridges` rather than `trigger_jobs`: GitLab 19.2 deprecates it but still serves it, and |
| 1632 | // older self-managed installs know no other name. |
| 1633 | path: `projects/${input.pipeline.projectId}/pipelines/${input.pipeline.id}/bridges?${query([ |
| 1634 | ["per_page", String(MAX_PAGE_SIZE)], |
| 1635 | ])}`, |
| 1636 | }).pipe( |
| 1637 | Effect.map((result) => { |
| 1638 | const decoded = decodeTriggerJobChecksJson(result.stdout.trim()); |
| 1639 | return Result.isSuccess(decoded) && decoded.success.rawCount < MAX_PAGE_SIZE |
| 1640 | ? decoded.success.checks |
| 1641 | : []; |
| 1642 | }), |
| 1643 | Effect.orElseSucceed((): ReadonlyArray<PullRequestCheck> => []), |
| 1644 | ); |
| 1645 | |
| 1646 | // Best-effort: stages that can't be read keep the merge request's single pipeline check. |
| 1647 | const pipelineStageChecks = (input: { |
| 1648 | readonly cwd: string; |
| 1649 | readonly host?: string | undefined; |
| 1650 | readonly repository: string; |
| 1651 | readonly number: number; |
| 1652 | readonly url: string; |
| 1653 | }): Effect.Effect<ReadonlyArray<PullRequestCheck> | null> => |
| 1654 | URL.canParse(input.url) |
| 1655 | ? graphqlRead({ |
| 1656 | cwd: input.cwd, |
| 1657 | host: input.host, |
| 1658 | operation: "getPipelineStageChecks", |
| 1659 | query: PIPELINE_STAGES_GRAPHQL_QUERY, |
| 1660 | variables: { fullPath: input.repository, iid: String(input.number) }, |
| 1661 | decode: (raw) => decodePipelineStageChecksJson(raw, new URL(input.url).origin), |
| 1662 | }).pipe(Effect.orElseSucceed(() => null)) |
| 1663 | : Effect.succeed(null); |
| 1664 | |
| 1665 | const projectUsers = (input: { |
| 1666 | readonly cwd: string; |
| 1667 | readonly host?: string | undefined; |
| 1668 | readonly repository: string; |
| 1669 | readonly search?: string | undefined; |
| 1670 | }): Effect.Effect<GitLabProjectUsers, GitLabPullRequestCliError> => |
| 1671 | api({ |
| 1672 | cwd: input.cwd, |
| 1673 | host: input.host, |
| 1674 | path: `projects/${projectPath(input.repository)}/users?${query([ |
| 1675 | ["per_page", String(MAX_PAGE_SIZE)], |
| 1676 | ...hostSearchParams(input.search), |
| 1677 | ])}`, |
| 1678 | }).pipe( |
| 1679 | Effect.flatMap((result) => { |
| 1680 | const decoded = decodeProjectUsersJson(result.stdout.trim()); |
| 1681 | return Result.isSuccess(decoded) |
| 1682 | ? Effect.succeed(decoded.success) |
| 1683 | : Effect.fail( |
| 1684 | new GitLabMergeRequestReadError({ |
| 1685 | command: "glab", |
| 1686 | cwd: input.cwd, |
| 1687 | operation: "listReviewerCandidates", |
| 1688 | cause: decoded.failure, |
| 1689 | }), |
| 1690 | ); |
| 1691 | }), |
| 1692 | ); |
| 1693 | |
| 1694 | const projectReferences = (input: { |
| 1695 | readonly cwd: string; |
| 1696 | readonly host?: string | undefined; |
| 1697 | readonly repository: string; |
| 1698 | readonly kind: PullRequestReferenceCandidate["kind"]; |
| 1699 | readonly params: ReadonlyArray<readonly [string, string]>; |
| 1700 | }) => |
| 1701 | api({ |
| 1702 | cwd: input.cwd, |
| 1703 | host: input.host, |
| 1704 | path: `projects/${projectPath(input.repository)}/${ |
| 1705 | input.kind === "issue" ? "issues" : "merge_requests" |
| 1706 | }?${query([...input.params, ["per_page", String(REFERENCE_PAGE_SIZE)]])}`, |
| 1707 | }).pipe( |
| 1708 | Effect.flatMap((result) => { |
| 1709 | const decoded = decodeReferenceCandidatesJson(result.stdout.trim(), input.kind); |
| 1710 | return Result.isSuccess(decoded) |
| 1711 | ? Effect.succeed(decoded.success) |
| 1712 | : Effect.fail( |
| 1713 | new GitLabMergeRequestReadError({ |
| 1714 | command: "glab", |
| 1715 | cwd: input.cwd, |
| 1716 | operation: "searchProjectReferences", |
| 1717 | cause: decoded.failure, |
| 1718 | }), |
| 1719 | ); |
| 1720 | }), |
| 1721 | ); |
| 1722 | |
| 1723 | const awardSubjectPath = (input: { |
| 1724 | readonly repository: string; |
| 1725 | readonly number: number; |
| 1726 | readonly noteId?: string | undefined; |
| 1727 | }) => { |
| 1728 | const mergeRequest = `projects/${projectPath(input.repository)}/merge_requests/${input.number}`; |
| 1729 | return input.noteId === undefined |
| 1730 | ? `${mergeRequest}/award_emoji` |
| 1731 | : `${mergeRequest}/notes/${encodeURIComponent(input.noteId)}/award_emoji`; |
| 1732 | }; |
| 1733 | |
| 1734 | const awardsPage = (input: { |
| 1735 | readonly cwd: string; |
| 1736 | readonly host?: string | undefined; |
| 1737 | readonly repository: string; |
| 1738 | readonly number: number; |
| 1739 | readonly cursor: string | null; |
| 1740 | readonly page: number; |
| 1741 | readonly collected: { |
| 1742 | readonly reactions: ReadonlyArray<PullRequestReaction>; |
| 1743 | readonly reactionsByNoteId: Map<string, ReadonlyArray<PullRequestReaction>>; |
| 1744 | readonly editedAtByNoteId: Map<string, string>; |
| 1745 | readonly botLogins: Set<string>; |
| 1746 | } | null; |
| 1747 | }): Effect.Effect< |
| 1748 | { |
| 1749 | readonly reactions: ReadonlyArray<PullRequestReaction>; |
| 1750 | readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>; |
| 1751 | readonly editedAtByNoteId: ReadonlyMap<string, string>; |
| 1752 | readonly botLogins: ReadonlySet<string>; |
| 1753 | }, |
| 1754 | GitLabPullRequestCliError |
| 1755 | > => |
| 1756 | api({ |
| 1757 | cwd: input.cwd, |
| 1758 | host: input.host, |
| 1759 | path: "graphql", |
| 1760 | method: "POST", |
| 1761 | stdin: JSON.stringify({ |
| 1762 | query: AWARD_EMOJI_GRAPHQL_QUERY, |
| 1763 | variables: { |
| 1764 | fullPath: input.repository, |
| 1765 | iid: String(input.number), |
| 1766 | cursor: input.cursor, |
| 1767 | }, |
| 1768 | }), |
| 1769 | }).pipe( |
| 1770 | Effect.flatMap((result) => { |
| 1771 | const decoded = decodeAwardEmojiJson(result.stdout.trim()); |
| 1772 | if (!Result.isSuccess(decoded)) { |
| 1773 | return Effect.fail( |
| 1774 | new GitLabMergeRequestReadError({ |
| 1775 | command: "glab", |
| 1776 | cwd: input.cwd, |
| 1777 | operation: "listReactions", |
| 1778 | cause: decoded.failure, |
| 1779 | }), |
| 1780 | ); |
| 1781 | } |
| 1782 | const collected = input.collected ?? { |
| 1783 | reactions: decoded.success.reactions, |
| 1784 | reactionsByNoteId: new Map<string, ReadonlyArray<PullRequestReaction>>(), |
| 1785 | editedAtByNoteId: new Map<string, string>(), |
| 1786 | botLogins: new Set<string>(), |
| 1787 | }; |
| 1788 | for (const [id, reactions] of decoded.success.reactionsByNoteId) |
| 1789 | collected.reactionsByNoteId.set(id, reactions); |
| 1790 | for (const [id, editedAt] of decoded.success.editedAtByNoteId) |
| 1791 | collected.editedAtByNoteId.set(id, editedAt); |
| 1792 | for (const login of decoded.success.botLogins) collected.botLogins.add(login); |
| 1793 | return decoded.success.nextCursor === null || input.page >= CONVERSATION_PAGES |
| 1794 | ? Effect.succeed(collected) |
| 1795 | : awardsPage({ |
| 1796 | ...input, |
| 1797 | cursor: decoded.success.nextCursor, |
| 1798 | page: input.page + 1, |
| 1799 | collected, |
| 1800 | }); |
| 1801 | }), |
| 1802 | ); |
| 1803 | |
| 1804 | /** The stats connection hands back one page, so a repository's rows are asked for 100 at a time. */ |
| 1805 | const STAT_IIDS_PER_REQUEST = 100; |
| 1806 | |
| 1807 | const projectLabels = (input: { |
| 1808 | readonly cwd: string; |
| 1809 | readonly host?: string | undefined; |
| 1810 | readonly repository: string; |
| 1811 | readonly search?: string | undefined; |
| 1812 | }) => |
| 1813 | api({ |
| 1814 | cwd: input.cwd, |
| 1815 | host: input.host, |
| 1816 | path: `projects/${projectPath(input.repository)}/labels?${query([ |
| 1817 | ["per_page", String(MAX_PAGE_SIZE)], |
| 1818 | ["include_ancestor_groups", "true"], |
| 1819 | ...searchParams(input.search), |
| 1820 | ])}`, |
| 1821 | }).pipe( |
| 1822 | Effect.flatMap((result) => { |
| 1823 | const decoded = decodeProjectLabelsJson(result.stdout.trim()); |
| 1824 | return Result.isSuccess(decoded) |
| 1825 | ? Effect.succeed({ |
| 1826 | labels: decoded.success.labels, |
| 1827 | truncated: decoded.success.rawCount >= MAX_PAGE_SIZE, |
| 1828 | }) |
| 1829 | : Effect.fail( |
| 1830 | new GitLabMergeRequestReadError({ |
| 1831 | command: "glab", |
| 1832 | cwd: input.cwd, |
| 1833 | operation: "listProjectLabels", |
| 1834 | cause: decoded.failure, |
| 1835 | }), |
| 1836 | ); |
| 1837 | }), |
| 1838 | ); |
| 1839 | |
| 1840 | const graphqlRead = <A>(input: { |
| 1841 | readonly cwd: string; |
| 1842 | readonly host?: string | undefined; |
| 1843 | readonly operation: string; |
| 1844 | readonly query: string; |
| 1845 | readonly variables: Record<string, unknown>; |
| 1846 | readonly decode: (raw: string) => Result.Result<A, unknown>; |
| 1847 | }) => |
| 1848 | api({ |
| 1849 | cwd: input.cwd, |
| 1850 | host: input.host, |
| 1851 | path: "graphql", |
| 1852 | method: "POST", |
| 1853 | stdin: JSON.stringify({ query: input.query, variables: input.variables }), |
| 1854 | }).pipe( |
| 1855 | Effect.flatMap((result) => { |
| 1856 | const decoded = input.decode(result.stdout.trim()); |
| 1857 | return Result.isSuccess(decoded) |
| 1858 | ? Effect.succeed(decoded.success) |
| 1859 | : Effect.fail( |
| 1860 | new GitLabMergeRequestReadError({ |
| 1861 | command: "glab", |
| 1862 | cwd: input.cwd, |
| 1863 | operation: input.operation, |
| 1864 | cause: decoded.failure, |
| 1865 | }), |
| 1866 | ); |
| 1867 | }), |
| 1868 | ); |
| 1869 | |
| 1870 | // A read GitLab could not answer (an older host, a field it rejects) is not worth failing the |
| 1871 | // surrounding operation for. An unusable CLI or account still reaches the caller. |
| 1872 | const isOptionalReadFailure = (cause: GitLabPullRequestCliError) => |
| 1873 | cause._tag !== "GitLabCliUnavailableError" && |
| 1874 | cause._tag !== "GitLabCliAuthenticationError" && |
| 1875 | cause._tag !== "GitLabCliRateLimitError"; |
| 1876 | |
| 1877 | const orWhenUnanswered = <A>( |
| 1878 | read: Effect.Effect<A, GitLabPullRequestCliError>, |
| 1879 | fallback: A, |
| 1880 | ): Effect.Effect<A, GitLabPullRequestCliError> => |
| 1881 | read.pipe(Effect.catchIf(isOptionalReadFailure, () => Effect.succeed(fallback))); |
| 1882 | |
| 1883 | const mergeRequestFileStats = (input: { |
| 1884 | readonly cwd: string; |
| 1885 | readonly host?: string | undefined; |
| 1886 | readonly repository: string; |
| 1887 | readonly number: number; |
| 1888 | }) => |
| 1889 | graphqlRead({ |
| 1890 | cwd: input.cwd, |
| 1891 | host: input.host, |
| 1892 | operation: "getMergeRequestFileStats", |
| 1893 | query: MERGE_REQUEST_FILE_STATS_GRAPHQL_QUERY, |
| 1894 | variables: { fullPath: input.repository, iid: String(input.number) }, |
| 1895 | decode: decodeMergeRequestFileStatsJson, |
| 1896 | }); |
| 1897 | |
| 1898 | // GitLab has no per-file diff, so a withheld file is cut from the whole raw diff here and |
| 1899 | // only its section reaches the client. `/raw_diffs` needs GitLab 17.9 or newer. |
| 1900 | const withheldFileDiff = (input: { |
| 1901 | readonly cwd: string; |
| 1902 | readonly host?: string | undefined; |
| 1903 | readonly repository: string; |
| 1904 | readonly number: number; |
| 1905 | readonly commit?: string | undefined; |
| 1906 | readonly path: string; |
| 1907 | }): Effect.Effect<GitLabMergeRequestDiffSlice, GitLabPullRequestCliError> => { |
| 1908 | const readError = (message: string) => |
| 1909 | new GitLabMergeRequestReadError({ |
| 1910 | command: "glab", |
| 1911 | cwd: input.cwd, |
| 1912 | operation: "getMergeRequestDiff", |
| 1913 | cause: new Error(message), |
| 1914 | }); |
| 1915 | if (input.commit !== undefined) { |
| 1916 | return Effect.fail(readError("A commit's withheld files cannot be read one at a time.")); |
| 1917 | } |
| 1918 | return api({ |
| 1919 | cwd: input.cwd, |
| 1920 | host: input.host, |
| 1921 | path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/raw_diffs`, |
| 1922 | maxOutputBytes: WITHHELD_FILE_DIFF_MAX_OUTPUT_BYTES, |
| 1923 | timeoutMs: DIFF_TIMEOUT_MS, |
| 1924 | }).pipe( |
| 1925 | Effect.flatMap((result) => { |
| 1926 | const section = result.stdoutTruncated ? null : diffFileSection(result.stdout, input.path); |
| 1927 | return section === null |
| 1928 | ? Effect.fail( |
| 1929 | readError( |
| 1930 | result.stdoutTruncated |
| 1931 | ? `The diff for ${input.path} is too large to load.` |
| 1932 | : `GitLab's diff does not include ${input.path}.`, |
| 1933 | ), |
| 1934 | ) |
| 1935 | : Effect.succeed({ |
| 1936 | patch: truncateLongDiffLines(section, WITHHELD_FILE_MAX_LINE_LENGTH), |
| 1937 | truncated: false, |
| 1938 | nextCursor: null, |
| 1939 | }); |
| 1940 | }), |
| 1941 | ); |
| 1942 | }; |
| 1943 | |
| 1944 | const graphqlMutation = (input: { |
| 1945 | readonly cwd: string; |
| 1946 | readonly host?: string | undefined; |
| 1947 | readonly operation: string; |
| 1948 | readonly query: string; |
| 1949 | readonly variables: Record<string, unknown>; |
| 1950 | }) => |
| 1951 | graphqlRead({ ...input, decode: decodeMutationErrorsJson }).pipe( |
| 1952 | Effect.flatMap((reasons) => |
| 1953 | reasons.length === 0 |
| 1954 | ? Effect.void |
| 1955 | : Effect.fail( |
| 1956 | new GitLabMutationRefusedError({ |
| 1957 | command: "glab", |
| 1958 | cwd: input.cwd, |
| 1959 | operation: input.operation, |
| 1960 | reasons, |
| 1961 | }), |
| 1962 | ), |
| 1963 | ), |
| 1964 | ); |
| 1965 | |
| 1966 | const graphqlListPage = (input: { |
| 1967 | readonly cwd: string; |
| 1968 | readonly host?: string | undefined; |
| 1969 | readonly repository: string; |
| 1970 | readonly state: PullRequestListState; |
| 1971 | readonly involvement: PullRequestInvolvement; |
| 1972 | readonly viewer: string; |
| 1973 | readonly limit: number; |
| 1974 | readonly query?: string | undefined; |
| 1975 | readonly filters?: PullRequestListFilters | undefined; |
| 1976 | readonly after: string | undefined; |
| 1977 | readonly collected: ReadonlyArray<GitLabMergeRequestListItem>; |
| 1978 | readonly states: ReadonlyMap<number, GitLabMergeRequestListState>; |
| 1979 | readonly cursorAdvance: number; |
| 1980 | /** Bounds the walk when whole pages fail to decode. */ |
| 1981 | readonly reads: number; |
| 1982 | }): Effect.Effect<GitLabMergeRequestListBatch, GitLabPullRequestCliError> => |
| 1983 | graphqlRead({ |
| 1984 | cwd: input.cwd, |
| 1985 | host: input.host, |
| 1986 | operation: "listMergeRequests", |
| 1987 | ...graphqlListQuery({ |
| 1988 | ...input, |
| 1989 | first: Math.max(1, Math.min(input.limit - input.collected.length, MAX_PAGE_SIZE)), |
| 1990 | }), |
| 1991 | decode: decodeMergeRequestGraphqlListJson, |
| 1992 | }).pipe( |
| 1993 | Effect.flatMap((page) => { |
| 1994 | const collected = [...input.collected, ...page.items]; |
| 1995 | const states = new Map([...input.states, ...page.states]); |
| 1996 | const cursorAdvance = input.cursorAdvance + page.rawCount; |
| 1997 | const resumeAfter = |
| 1998 | page.endCursor !== null && RESUME_AFTER_PATTERN.test(page.endCursor) |
| 1999 | ? page.endCursor |
| 2000 | : undefined; |
| 2001 | if ( |
| 2002 | page.hasNextPage && |
| 2003 | resumeAfter !== undefined && |
| 2004 | collected.length < input.limit && |
| 2005 | input.reads > 1 |
| 2006 | ) { |
| 2007 | return graphqlListPage({ |
| 2008 | ...input, |
| 2009 | after: resumeAfter, |
| 2010 | collected, |
| 2011 | states, |
| 2012 | cursorAdvance, |
| 2013 | reads: input.reads - 1, |
| 2014 | }); |
| 2015 | } |
| 2016 | return Effect.succeed({ |
| 2017 | items: collected, |
| 2018 | truncated: page.hasNextPage, |
| 2019 | cursorAdvance, |
| 2020 | ...(resumeAfter === undefined ? {} : { resumeAfter }), |
| 2021 | listStates: states, |
| 2022 | }); |
| 2023 | }), |
| 2024 | ); |
| 2025 | |
| 2026 | const labelPermission = (input: { |
| 2027 | readonly cwd: string; |
| 2028 | readonly host?: string | undefined; |
| 2029 | readonly repository: string; |
| 2030 | readonly number: number; |
| 2031 | }) => |
| 2032 | orWhenUnanswered( |
| 2033 | graphqlRead({ |
| 2034 | cwd: input.cwd, |
| 2035 | host: input.host, |
| 2036 | operation: "getLabelPermission", |
| 2037 | query: LABEL_PERMISSION_GRAPHQL_QUERY, |
| 2038 | variables: { fullPath: input.repository, iid: String(input.number) }, |
| 2039 | decode: decodeLabelPermissionJson, |
| 2040 | }), |
| 2041 | { viewerCanEditLabels: false, labels: null }, |
| 2042 | ); |
| 2043 | |
| 2044 | const sourceBranch = (input: { |
| 2045 | readonly cwd: string; |
| 2046 | readonly host?: string | undefined; |
| 2047 | readonly repository: string; |
| 2048 | readonly number: number; |
| 2049 | }) => |
| 2050 | graphqlRead({ |
| 2051 | cwd: input.cwd, |
| 2052 | host: input.host, |
| 2053 | operation: "getSourceBranch", |
| 2054 | query: SOURCE_BRANCH_GRAPHQL_QUERY, |
| 2055 | variables: { fullPath: input.repository, iid: String(input.number) }, |
| 2056 | decode: decodeSourceBranchJson, |
| 2057 | }); |
| 2058 | |
| 2059 | const deleteSourceBranch = Effect.fn("GitLabPullRequestCli.deleteSourceBranch")( |
| 2060 | function* (input: { |
| 2061 | readonly cwd: string; |
| 2062 | readonly host?: string | undefined; |
| 2063 | readonly repository: string; |
| 2064 | readonly number: number; |
| 2065 | }) { |
| 2066 | const refuse = (reason: GitLabBranchDeletionRefusedError["reason"]) => |
| 2067 | new GitLabBranchDeletionRefusedError({ |
| 2068 | command: "glab", |
| 2069 | cwd: input.cwd, |
| 2070 | number: input.number, |
| 2071 | reason, |
| 2072 | }); |
| 2073 | const source = yield* sourceBranch(input); |
| 2074 | if (source === null) { |
| 2075 | return yield* new GitLabMergeRequestReadError({ |
| 2076 | command: "glab", |
| 2077 | cwd: input.cwd, |
| 2078 | operation: "getSourceBranch", |
| 2079 | cause: new Error("GitLab reported no merge request."), |
| 2080 | }); |
| 2081 | } |
| 2082 | if (source.open) return yield* refuse("open"); |
| 2083 | if (!source.canDelete) return yield* refuse("not-allowed"); |
| 2084 | if (source.sourceProject === null || source.headSha === null) { |
| 2085 | return yield* refuse("source-unavailable"); |
| 2086 | } |
| 2087 | const path = `projects/${projectPath(source.sourceProject)}/repository/branches/${encodeURIComponent(source.branch)}`; |
| 2088 | const branch = yield* api({ cwd: input.cwd, host: input.host, path }).pipe( |
| 2089 | Effect.flatMap((result) => { |
| 2090 | const decoded = decodeBranchJson(result.stdout.trim()); |
| 2091 | return Result.isSuccess(decoded) |
| 2092 | ? Effect.succeed(decoded.success) |
| 2093 | : Effect.fail( |
| 2094 | new GitLabMergeRequestReadError({ |
| 2095 | command: "glab", |
| 2096 | cwd: input.cwd, |
| 2097 | operation: "getSourceBranch", |
| 2098 | cause: decoded.failure, |
| 2099 | }), |
| 2100 | ); |
| 2101 | }), |
| 2102 | ); |
| 2103 | if (branch.isDefault) return yield* refuse("default-branch"); |
| 2104 | if (branch.headSha !== source.headSha) return yield* refuse("head-changed"); |
| 2105 | // GitLab's branch delete takes no expected SHA. It answers 412 when the head's authored |
| 2106 | // date is newer than If-Unmodified-Since, which catches a commit pushed after this read but |
| 2107 | // not a force-push of an older-dated commit (a rebase keeps author dates). |
| 2108 | const authoredAt = |
| 2109 | branch.headAuthoredDate === null ? Option.none() : DateTime.make(branch.headAuthoredDate); |
| 2110 | yield* api({ |
| 2111 | cwd: input.cwd, |
| 2112 | host: input.host, |
| 2113 | path, |
| 2114 | method: "DELETE", |
| 2115 | ...(Option.isNone(authoredAt) |
| 2116 | ? {} |
| 2117 | : { |
| 2118 | headers: [ |
| 2119 | `If-Unmodified-Since: ${DateTime.toDateUtc(authoredAt.value).toUTCString()}`, |
| 2120 | ], |
| 2121 | }), |
| 2122 | }); |
| 2123 | }, |
| 2124 | ); |
| 2125 | |
| 2126 | const mergeRequestStats = (input: { |
| 2127 | readonly cwd: string; |
| 2128 | readonly host?: string | undefined; |
| 2129 | readonly repository: string; |
| 2130 | readonly numbers: ReadonlyArray<number>; |
| 2131 | }) => |
| 2132 | graphqlRead({ |
| 2133 | cwd: input.cwd, |
| 2134 | host: input.host, |
| 2135 | operation: "listMergeRequestStats", |
| 2136 | query: MERGE_REQUEST_STATS_GRAPHQL_QUERY, |
| 2137 | variables: { fullPath: input.repository, iids: input.numbers.map(String) }, |
| 2138 | decode: decodeMergeRequestStatsJson, |
| 2139 | }); |
| 2140 | |
| 2141 | const STAT_REQUEST_CONCURRENCY = 4; |
| 2142 | |
| 2143 | const listMergeRequestStats: GitLabPullRequestCli["Service"]["listMergeRequestStats"] = ( |
| 2144 | input, |
| 2145 | ) => { |
| 2146 | const byRepository = new Map<string, Set<number>>(); |
| 2147 | for (const { repository, number } of input.changeRequests) { |
| 2148 | const numbers = byRepository.get(repository) ?? new Set<number>(); |
| 2149 | numbers.add(number); |
| 2150 | byRepository.set(repository, numbers); |
| 2151 | } |
| 2152 | const reads: Array<{ readonly repository: string; readonly numbers: ReadonlyArray<number> }> = |
| 2153 | []; |
| 2154 | for (const [repository, numberSet] of byRepository) { |
| 2155 | const numbers = [...numberSet]; |
| 2156 | for (let start = 0; start < numbers.length; start += STAT_IIDS_PER_REQUEST) { |
| 2157 | reads.push({ repository, numbers: numbers.slice(start, start + STAT_IIDS_PER_REQUEST) }); |
| 2158 | } |
| 2159 | } |
| 2160 | return Effect.forEach( |
| 2161 | reads, |
| 2162 | (read) => |
| 2163 | mergeRequestStats({ cwd: input.cwd, host: input.host, ...read }).pipe( |
| 2164 | Effect.map((stats) => |
| 2165 | read.numbers.flatMap((number) => { |
| 2166 | const stat = stats.get(number); |
| 2167 | return stat === undefined ? [] : [{ repository: read.repository, number, ...stat }]; |
| 2168 | }), |
| 2169 | ), |
| 2170 | // One failed read costs its own rows their counts, not every other read's on the page. |
| 2171 | Effect.catchIf(isOptionalReadFailure, (cause) => |
| 2172 | Effect.logWarning("GitLab merge request line count read failed", { |
| 2173 | repository: read.repository, |
| 2174 | reason: cause._tag, |
| 2175 | }).pipe(Effect.as([])), |
| 2176 | ), |
| 2177 | ), |
| 2178 | { concurrency: STAT_REQUEST_CONCURRENCY }, |
| 2179 | ).pipe(Effect.map((results) => results.flat())); |
| 2180 | }; |
| 2181 | |
| 2182 | // GitLab charges by path count and returns one connection page; respect both limits. |
| 2183 | const BLOB_PATHS_PER_REQUEST = 100; |
| 2184 | |
| 2185 | const blobsAt = (input: { |
| 2186 | readonly cwd: string; |
| 2187 | readonly host?: string | undefined; |
| 2188 | readonly repository: string; |
| 2189 | readonly ref: string; |
| 2190 | readonly paths: ReadonlyArray<string>; |
| 2191 | }): Effect.Effect<ReadonlyMap<string, string> | null, GitLabPullRequestCliError> => |
| 2192 | api({ |
| 2193 | cwd: input.cwd, |
| 2194 | host: input.host, |
| 2195 | path: "graphql", |
| 2196 | method: "POST", |
| 2197 | stdin: JSON.stringify({ |
| 2198 | query: REPOSITORY_BLOBS_GRAPHQL_QUERY, |
| 2199 | variables: { fullPath: input.repository, ref: input.ref, paths: input.paths }, |
| 2200 | }), |
| 2201 | }).pipe( |
| 2202 | Effect.flatMap( |
| 2203 | (result): Effect.Effect<ReadonlyMap<string, string> | null, GitLabPullRequestCliError> => { |
| 2204 | const decoded = decodeRepositoryBlobsJson(result.stdout.trim()); |
| 2205 | return Result.isSuccess(decoded) |
| 2206 | ? Effect.succeed(decoded.success) |
| 2207 | : Effect.fail( |
| 2208 | new GitLabMergeRequestReadError({ |
| 2209 | command: "glab", |
| 2210 | cwd: input.cwd, |
| 2211 | operation: "getFileRevisions", |
| 2212 | cause: decoded.failure, |
| 2213 | }), |
| 2214 | ); |
| 2215 | }, |
| 2216 | ), |
| 2217 | ); |
| 2218 | |
| 2219 | const fileRevisions = (input: { |
| 2220 | readonly cwd: string; |
| 2221 | readonly host?: string | undefined; |
| 2222 | readonly repository: string; |
| 2223 | readonly number: number; |
| 2224 | readonly paths: ReadonlyArray<string>; |
| 2225 | }): Effect.Effect<ReadonlyMap<string, string>, GitLabPullRequestCliError> => |
| 2226 | input.paths.length === 0 |
| 2227 | ? Effect.succeed(new Map()) |
| 2228 | : getDiffRefs(input).pipe( |
| 2229 | Effect.flatMap((refs) => { |
| 2230 | const batches: Array<ReadonlyArray<string>> = []; |
| 2231 | for (let at = 0; at < input.paths.length; at += BLOB_PATHS_PER_REQUEST) { |
| 2232 | batches.push(input.paths.slice(at, at + BLOB_PATHS_PER_REQUEST)); |
| 2233 | } |
| 2234 | return Effect.forEach( |
| 2235 | batches, |
| 2236 | (paths) => |
| 2237 | blobsAt({ ...input, ref: refs.headSha, paths }).pipe( |
| 2238 | Effect.map((page) => ({ paths, page })), |
| 2239 | ), |
| 2240 | { concurrency: 2 }, |
| 2241 | ).pipe( |
| 2242 | Effect.map((pages) => { |
| 2243 | const revisions = new Map<string, string>(); |
| 2244 | for (const { paths, page } of pages) { |
| 2245 | // Unanswered paths are unknown; omit them to preserve viewed marks. |
| 2246 | if (page === null) continue; |
| 2247 | for (const [path, oid] of page) revisions.set(path, oid); |
| 2248 | for (const path of paths) { |
| 2249 | if (!revisions.has(path)) revisions.set(path, ""); |
| 2250 | } |
| 2251 | } |
| 2252 | return revisions as ReadonlyMap<string, string>; |
| 2253 | }), |
| 2254 | ); |
| 2255 | }), |
| 2256 | ); |
| 2257 | |
| 2258 | const listStatesOf = (input: { |
| 2259 | readonly cwd: string; |
| 2260 | readonly host?: string | undefined; |
| 2261 | readonly repository: string; |
| 2262 | readonly numbers: ReadonlyArray<number>; |
| 2263 | }): Effect.Effect<ReadonlyMap<number, GitLabMergeRequestListState>, GitLabPullRequestCliError> => |
| 2264 | graphqlRead({ |
| 2265 | cwd: input.cwd, |
| 2266 | host: input.host, |
| 2267 | operation: "getListStates", |
| 2268 | query: LIST_STATES_GRAPHQL_QUERY, |
| 2269 | variables: { fullPath: input.repository, iids: input.numbers.map(String) }, |
| 2270 | decode: decodeListStatesJson, |
| 2271 | }); |
| 2272 | |
| 2273 | const viewerUsername = (input: { readonly cwd: string; readonly host?: string | undefined }) => |
| 2274 | api({ cwd: input.cwd, host: input.host, path: "user" }).pipe( |
| 2275 | Effect.flatMap((result): Effect.Effect<string, GitLabPullRequestCliError> => { |
| 2276 | const decoded = decodeViewerJson(result.stdout.trim()); |
| 2277 | if (!Result.isSuccess(decoded)) { |
| 2278 | return Effect.fail( |
| 2279 | new GitLabMergeRequestReadError({ |
| 2280 | command: "glab", |
| 2281 | cwd: input.cwd, |
| 2282 | operation: "getViewerUsername", |
| 2283 | cause: decoded.failure, |
| 2284 | }), |
| 2285 | ); |
| 2286 | } |
| 2287 | return decoded.success === null |
| 2288 | ? Effect.fail(new GitLabViewerUnavailableError({ command: "glab", cwd: input.cwd })) |
| 2289 | : Effect.succeed(decoded.success); |
| 2290 | }), |
| 2291 | ); |
| 2292 | |
| 2293 | return GitLabPullRequestCli.of({ |
| 2294 | getViewerUsername: viewerUsername, |
| 2295 | |
| 2296 | listMergeRequests: Effect.fn("GitLabPullRequestCli.listMergeRequests")(function (input) { |
| 2297 | const perPage = Math.min(input.limit + 1, MAX_PAGE_SIZE); |
| 2298 | const page = Math.floor((input.cursor?.delivered ?? 0) / perPage) + 1; |
| 2299 | const rest = Effect.suspend(() => |
| 2300 | listPage({ ...input, page, collected: [], cursorAdvance: 0 }), |
| 2301 | ); |
| 2302 | // A cursor's offset means something only to the API that handed it out. |
| 2303 | const viaGraphql = |
| 2304 | input.cursor === undefined |
| 2305 | ? input.graphql === true |
| 2306 | : input.cursor.resumeAfter !== undefined; |
| 2307 | if (!viaGraphql) return rest; |
| 2308 | const graphql = graphqlListPage({ |
| 2309 | ...input, |
| 2310 | after: input.cursor?.resumeAfter, |
| 2311 | collected: [], |
| 2312 | states: new Map(), |
| 2313 | cursorAdvance: 0, |
| 2314 | reads: Math.ceil(input.limit / MAX_PAGE_SIZE) + 1, |
| 2315 | }); |
| 2316 | // GraphQL counts only filtered rows, so its `delivered` is no REST offset once resumed. |
| 2317 | if (input.cursor !== undefined) return graphql; |
| 2318 | return graphql.pipe( |
| 2319 | Effect.catchIf( |
| 2320 | (cause) => |
| 2321 | cause._tag !== "GitLabCliUnavailableError" && |
| 2322 | cause._tag !== "GitLabCliAuthenticationError" && |
| 2323 | cause._tag !== "GitLabCliRateLimitError", |
| 2324 | (cause) => |
| 2325 | Effect.logWarning("GitLab GraphQL merge request list failed; reading REST instead", { |
| 2326 | repository: input.repository, |
| 2327 | reason: cause._tag, |
| 2328 | }).pipe(Effect.andThen(rest)), |
| 2329 | ), |
| 2330 | ); |
| 2331 | }), |
| 2332 | |
| 2333 | supportsGraphqlList: Effect.fn("GitLabPullRequestCli.supportsGraphqlList")((input) => |
| 2334 | graphqlRead({ |
| 2335 | cwd: input.cwd, |
| 2336 | host: input.host, |
| 2337 | operation: "supportsGraphqlList", |
| 2338 | query: SERVER_VERSION_GRAPHQL_QUERY, |
| 2339 | variables: {}, |
| 2340 | decode: decodeGraphqlListSupportJson, |
| 2341 | }), |
| 2342 | ), |
| 2343 | |
| 2344 | getMergeRequestDetail: Effect.fn("GitLabPullRequestCli.getMergeRequestDetail")( |
| 2345 | function* (input) { |
| 2346 | const [read, extras] = yield* Effect.all( |
| 2347 | [mergeRequestDetail(input), labelPermission(input)], |
| 2348 | { concurrency: 2 }, |
| 2349 | ); |
| 2350 | const labeled = { ...read, labels: colourLabels(read.labels, extras.labels) }; |
| 2351 | const viewerCanEditLabels = extras.viewerCanEditLabels; |
| 2352 | // Only a closed or merged merge request offers its branch for deletion, and only an open |
| 2353 | // fork's has maintainer edits to change, so each extra read is skipped elsewhere. |
| 2354 | const detail = |
| 2355 | labeled.state === "open" |
| 2356 | ? input.maintainerEdits === false || labeled.maintainerCanModify === undefined |
| 2357 | ? { ...labeled, viewerCanEditLabels } |
| 2358 | : { |
| 2359 | ...labeled, |
| 2360 | viewerCanEditLabels, |
| 2361 | viewerCanEditMaintainerEdits: yield* orWhenUnanswered( |
| 2362 | graphqlRead({ |
| 2363 | cwd: input.cwd, |
| 2364 | host: input.host, |
| 2365 | operation: "getMaintainerEditsPermission", |
| 2366 | query: MAINTAINER_EDITS_PERMISSION_GRAPHQL_QUERY, |
| 2367 | variables: { fullPath: input.repository, iid: String(input.number) }, |
| 2368 | decode: decodeMaintainerEditsPermissionJson, |
| 2369 | }), |
| 2370 | false, |
| 2371 | ), |
| 2372 | } |
| 2373 | : { |
| 2374 | ...labeled, |
| 2375 | viewerCanEditLabels, |
| 2376 | viewerCanDeleteBranch: yield* orWhenUnanswered( |
| 2377 | sourceBranch(input).pipe(Effect.map((source) => source?.canDelete === true)), |
| 2378 | false, |
| 2379 | ), |
| 2380 | }; |
| 2381 | if (input.downstreamChecks === false || detail.headPipeline === undefined) return detail; |
| 2382 | // The stages already carry each trigger job's downstream pipeline. |
| 2383 | const stages = yield* pipelineStageChecks({ ...input, url: detail.url }); |
| 2384 | if (stages !== null) return { ...detail, checks: stages }; |
| 2385 | const downstream = yield* triggerJobChecks({ |
| 2386 | cwd: input.cwd, |
| 2387 | pipeline: detail.headPipeline, |
| 2388 | }); |
| 2389 | return downstream.length === 0 |
| 2390 | ? detail |
| 2391 | : { ...detail, checks: [...detail.checks, ...downstream] }; |
| 2392 | }, |
| 2393 | ), |
| 2394 | |
| 2395 | getListStates: Effect.fn("GitLabPullRequestCli.getListStates")(function (input) { |
| 2396 | const batches: Array<ReadonlyArray<number>> = []; |
| 2397 | for (let at = 0; at < input.numbers.length; at += MAX_PAGE_SIZE) { |
| 2398 | batches.push(input.numbers.slice(at, at + MAX_PAGE_SIZE)); |
| 2399 | } |
| 2400 | return Effect.forEach(batches, (numbers) => listStatesOf({ ...input, numbers }), { |
| 2401 | concurrency: 2, |
| 2402 | }).pipe(Effect.map((pages) => new Map(pages.flatMap((page) => [...page])))); |
| 2403 | }), |
| 2404 | |
| 2405 | listMergeRequestStats, |
| 2406 | |
| 2407 | getMergeRequestFileStats: Effect.fn("GitLabPullRequestCli.getMergeRequestFileStats")( |
| 2408 | mergeRequestFileStats, |
| 2409 | ), |
| 2410 | |
| 2411 | getMergeRequestWatchFingerprint: Effect.fn( |
| 2412 | "GitLabPullRequestCli.getMergeRequestWatchFingerprint", |
| 2413 | )((input) => |
| 2414 | graphqlRead({ |
| 2415 | cwd: input.cwd, |
| 2416 | host: input.host, |
| 2417 | operation: "getMergeRequestWatchFingerprint", |
| 2418 | query: MERGE_REQUEST_WATCH_FINGERPRINT_GRAPHQL_QUERY, |
| 2419 | variables: { fullPath: input.repository, iid: String(input.number) }, |
| 2420 | decode: decodeMergeRequestWatchFingerprintJson, |
| 2421 | }), |
| 2422 | ), |
| 2423 | |
| 2424 | listNotes: Effect.fn("GitLabPullRequestCli.listNotes")(function (input) { |
| 2425 | return notesPage({ ...input, page: 1, collected: [] }); |
| 2426 | }), |
| 2427 | |
| 2428 | listReactions: Effect.fn("GitLabPullRequestCli.listReactions")(function (input) { |
| 2429 | return awardsPage({ ...input, cursor: null, page: 1, collected: null }); |
| 2430 | }), |
| 2431 | |
| 2432 | getFileRevisions: fileRevisions, |
| 2433 | |
| 2434 | setReaction: Effect.fn("GitLabPullRequestCli.setReaction")(function* (input) { |
| 2435 | const subject = awardSubjectPath(input); |
| 2436 | if (input.reacted) { |
| 2437 | yield* api({ |
| 2438 | cwd: input.cwd, |
| 2439 | host: input.host, |
| 2440 | path: `${subject}?${query([["name", gitLabAwardName(input.content)]])}`, |
| 2441 | method: "POST", |
| 2442 | }); |
| 2443 | return; |
| 2444 | } |
| 2445 | // GitLab deletes an award by its id and takes no emoji name there, so the reader's own |
| 2446 | // award of that name is looked up first. |
| 2447 | const viewer = yield* viewerUsername(input); |
| 2448 | for (let page = 1; ; page++) { |
| 2449 | const listed = yield* api({ |
| 2450 | cwd: input.cwd, |
| 2451 | host: input.host, |
| 2452 | path: `${subject}?${query([ |
| 2453 | ["per_page", String(MAX_PAGE_SIZE)], |
| 2454 | ["page", String(page)], |
| 2455 | ])}`, |
| 2456 | }); |
| 2457 | const own = decodeOwnAwardIdJson(listed.stdout.trim(), { |
| 2458 | content: input.content, |
| 2459 | viewer, |
| 2460 | }); |
| 2461 | if (!Result.isSuccess(own)) { |
| 2462 | return yield* new GitLabMergeRequestReadError({ |
| 2463 | command: "glab", |
| 2464 | cwd: input.cwd, |
| 2465 | operation: "setReaction", |
| 2466 | cause: own.failure, |
| 2467 | }); |
| 2468 | } |
| 2469 | if (own.success.id !== null) { |
| 2470 | yield* api({ |
| 2471 | cwd: input.cwd, |
| 2472 | host: input.host, |
| 2473 | path: `${subject}/${own.success.id}`, |
| 2474 | method: "DELETE", |
| 2475 | }); |
| 2476 | return; |
| 2477 | } |
| 2478 | // An empty raw page establishes exhaustion even when the host caps page size. |
| 2479 | if (own.success.empty) return; |
| 2480 | } |
| 2481 | }), |
| 2482 | |
| 2483 | listCommits: Effect.fn("GitLabPullRequestCli.listCommits")(function (input) { |
| 2484 | return api({ |
| 2485 | cwd: input.cwd, |
| 2486 | host: input.host, |
| 2487 | path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/commits?${query( |
| 2488 | [ |
| 2489 | ["per_page", String(COMMIT_PAGE_SIZE)], |
| 2490 | ["with_stats", "true"], |
| 2491 | ], |
| 2492 | )}`, |
| 2493 | }).pipe( |
| 2494 | Effect.flatMap((result) => { |
| 2495 | const decoded = decodeCommitsJson(result.stdout.trim()); |
| 2496 | return Result.isSuccess(decoded) |
| 2497 | ? Effect.succeed(decoded.success) |
| 2498 | : Effect.fail( |
| 2499 | new GitLabMergeRequestReadError({ |
| 2500 | command: "glab", |
| 2501 | cwd: input.cwd, |
| 2502 | operation: "listCommits", |
| 2503 | cause: decoded.failure, |
| 2504 | }), |
| 2505 | ); |
| 2506 | }), |
| 2507 | ); |
| 2508 | }), |
| 2509 | |
| 2510 | getMergeRequestDiff: Effect.fn("GitLabPullRequestCli.getMergeRequestDiff")(function* (input) { |
| 2511 | if (input.commit !== undefined && !isCommitSha(input.commit)) { |
| 2512 | return yield* new GitLabDiffCommitError({ command: "glab", cwd: input.cwd }); |
| 2513 | } |
| 2514 | const target = { |
| 2515 | cwd: input.cwd, |
| 2516 | host: input.host, |
| 2517 | repository: input.repository, |
| 2518 | number: input.number, |
| 2519 | ...(input.commit === undefined ? {} : { commit: input.commit }), |
| 2520 | }; |
| 2521 | if (input.path !== undefined) { |
| 2522 | return yield* withheldFileDiff({ ...target, path: input.path }); |
| 2523 | } |
| 2524 | const page = input.cursor === undefined ? 1 : diffCursorPage(input.cursor); |
| 2525 | if (page === null) |
| 2526 | return yield* new GitLabDiffCursorError({ command: "glab", cwd: input.cwd }); |
| 2527 | const { withheldPaths, legacy, ...slice } = yield* diffPage({ ...target, page }); |
| 2528 | // A commit's diff has no per-file counts or raw diff to read a withheld file from. |
| 2529 | if (input.commit !== undefined) return slice; |
| 2530 | const readable = page === 1 && !legacy ? { withheldFilesReadable: true } : {}; |
| 2531 | if (withheldPaths.length === 0) return { ...slice, ...readable }; |
| 2532 | const stats = yield* orWhenUnanswered(mergeRequestFileStats(target), { |
| 2533 | files: [], |
| 2534 | truncated: true, |
| 2535 | }); |
| 2536 | const statsByPath = new Map(stats.files.map((file) => [file.path, file])); |
| 2537 | const omittedFileStats = withheldPaths.flatMap((path) => { |
| 2538 | const stat = statsByPath.get(path); |
| 2539 | return stat === undefined |
| 2540 | ? [] |
| 2541 | : [{ path, additions: stat.additions, deletions: stat.deletions }]; |
| 2542 | }); |
| 2543 | return { |
| 2544 | ...slice, |
| 2545 | ...readable, |
| 2546 | ...(omittedFileStats.length === 0 ? {} : { omittedFileStats }), |
| 2547 | }; |
| 2548 | }), |
| 2549 | |
| 2550 | getMergeRequestDiffFileContents: Effect.fn( |
| 2551 | "GitLabPullRequestCli.getMergeRequestDiffFileContents", |
| 2552 | )(function* (input) { |
| 2553 | if (input.commit !== undefined && !isCommitSha(input.commit)) { |
| 2554 | return yield* new GitLabDiffCommitError({ command: "glab", cwd: input.cwd }); |
| 2555 | } |
| 2556 | const refs = yield* input.commit === undefined |
| 2557 | ? getDiffRefs(input) |
| 2558 | : getCommitDiffRefs({ |
| 2559 | cwd: input.cwd, |
| 2560 | host: input.host, |
| 2561 | repository: input.repository, |
| 2562 | commit: input.commit, |
| 2563 | allowRoot: input.changeType === "new", |
| 2564 | }); |
| 2565 | |
| 2566 | const readFile = (revision: string, filePath: string) => |
| 2567 | api({ |
| 2568 | cwd: input.cwd, |
| 2569 | host: input.host, |
| 2570 | path: `projects/${projectPath(input.repository)}/repository/files/${encodeURIComponent( |
| 2571 | filePath, |
| 2572 | )}/raw?ref=${encodeURIComponent(revision)}`, |
| 2573 | maxOutputBytes: DIFF_FILE_MAX_OUTPUT_BYTES, |
| 2574 | timeoutMs: DIFF_TIMEOUT_MS, |
| 2575 | }).pipe( |
| 2576 | Effect.flatMap((result) => |
| 2577 | result.stdoutTruncated || |
| 2578 | result.stdout.includes("\0") || |
| 2579 | result.stdoutInvalidUtf8 === true |
| 2580 | ? Effect.fail( |
| 2581 | new GitLabDiffFileContentsUnavailableError({ |
| 2582 | command: "glab", |
| 2583 | cwd: input.cwd, |
| 2584 | path: filePath, |
| 2585 | reason: result.stdoutTruncated ? "oversized" : "binary", |
| 2586 | }), |
| 2587 | ) |
| 2588 | : Effect.succeed(result.stdout), |
| 2589 | ), |
| 2590 | ); |
| 2591 | |
| 2592 | const [oldContents, newContents] = yield* Effect.all( |
| 2593 | [ |
| 2594 | input.changeType === "new" ? Effect.succeed("") : readFile(refs.baseSha, input.oldPath), |
| 2595 | input.changeType === "deleted" |
| 2596 | ? Effect.succeed("") |
| 2597 | : readFile(refs.headSha, input.newPath), |
| 2598 | ], |
| 2599 | { concurrency: 2 }, |
| 2600 | ); |
| 2601 | return { oldContents, newContents }; |
| 2602 | }), |
| 2603 | |
| 2604 | getProjectMergeCapabilities: Effect.fn("GitLabPullRequestCli.getProjectMergeCapabilities")( |
| 2605 | function (input) { |
| 2606 | return api({ |
| 2607 | cwd: input.cwd, |
| 2608 | host: input.host, |
| 2609 | path: `projects/${projectPath(input.repository)}?license=false`, |
| 2610 | }).pipe( |
| 2611 | Effect.flatMap((result) => { |
| 2612 | const decoded = decodeProjectMergeCapabilitiesJson(result.stdout.trim()); |
| 2613 | return Result.isSuccess(decoded) |
| 2614 | ? Effect.succeed(decoded.success) |
| 2615 | : Effect.fail( |
| 2616 | new GitLabMergeRequestReadError({ |
| 2617 | command: "glab", |
| 2618 | cwd: input.cwd, |
| 2619 | operation: "getProjectMergeCapabilities", |
| 2620 | cause: decoded.failure, |
| 2621 | }), |
| 2622 | ); |
| 2623 | }), |
| 2624 | ); |
| 2625 | }, |
| 2626 | ), |
| 2627 | |
| 2628 | listProjectLabels: Effect.fn("GitLabPullRequestCli.listProjectLabels")(function (input) { |
| 2629 | return projectLabels(input).pipe( |
| 2630 | Effect.map(({ labels, truncated }) => ({ |
| 2631 | items: labels.map(({ name, color }) => ({ name, color })), |
| 2632 | truncated, |
| 2633 | })), |
| 2634 | ); |
| 2635 | }), |
| 2636 | |
| 2637 | listLabelCandidates: Effect.fn("GitLabPullRequestCli.listLabelCandidates")(function* (input) { |
| 2638 | const [mergeRequest, project] = yield* Effect.all( |
| 2639 | [mergeRequestDetail(input), projectLabels(input)], |
| 2640 | { concurrency: 2 }, |
| 2641 | ); |
| 2642 | const applied = new Set(mergeRequest.labels.map((label) => label.name)); |
| 2643 | const listed = new Set(project.labels.map((label) => label.name)); |
| 2644 | return { |
| 2645 | // GitLab's own picker hides archived labels. Applied ones stay so they can be removed, |
| 2646 | // as do applied labels past the project's first page. |
| 2647 | candidates: [ |
| 2648 | ...mergeRequest.labels |
| 2649 | .filter((label) => !listed.has(label.name)) |
| 2650 | .map((label) => ({ ...label, description: null, isApplied: true })), |
| 2651 | ...project.labels |
| 2652 | .filter((label) => !label.archived || applied.has(label.name)) |
| 2653 | .map(({ archived: _archived, ...label }) => ({ |
| 2654 | ...label, |
| 2655 | isApplied: applied.has(label.name), |
| 2656 | })), |
| 2657 | ], |
| 2658 | truncated: project.truncated, |
| 2659 | }; |
| 2660 | }), |
| 2661 | |
| 2662 | setLabels: Effect.fn("GitLabPullRequestCli.setLabels")(function* (input) { |
| 2663 | if (input.applied) { |
| 2664 | // GitLab creates any label it is asked to add that the project does not have yet. |
| 2665 | const found = yield* Effect.forEach( |
| 2666 | input.labels, |
| 2667 | (label) => |
| 2668 | api({ |
| 2669 | cwd: input.cwd, |
| 2670 | host: input.host, |
| 2671 | path: `projects/${projectPath(input.repository)}/labels/${encodeURIComponent(label)}?${query( |
| 2672 | [["include_ancestor_groups", "true"]], |
| 2673 | )}`, |
| 2674 | }).pipe( |
| 2675 | // The lookup also matches a numeric id, so the returned name must be the one asked for. |
| 2676 | Effect.map((result) => { |
| 2677 | const decoded = decodeLabelNameJson(result.stdout.trim()); |
| 2678 | return Result.isSuccess(decoded) && decoded.success === label; |
| 2679 | }), |
| 2680 | Effect.catchTags({ |
| 2681 | GitLabCliCommandError: (error) => |
| 2682 | isVcsProcessExitError(error.cause) && error.cause.failureKind === "not-found" |
| 2683 | ? Effect.succeed(false) |
| 2684 | : Effect.fail(error), |
| 2685 | }), |
| 2686 | ), |
| 2687 | { concurrency: 4 }, |
| 2688 | ); |
| 2689 | const unknown = input.labels.filter((_, index) => !found[index]); |
| 2690 | if (unknown.length > 0) { |
| 2691 | return yield* new GitLabUnknownLabelError({ |
| 2692 | command: "glab", |
| 2693 | cwd: input.cwd, |
| 2694 | labels: unknown, |
| 2695 | }); |
| 2696 | } |
| 2697 | } |
| 2698 | yield* api({ |
| 2699 | cwd: input.cwd, |
| 2700 | host: input.host, |
| 2701 | path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`, |
| 2702 | method: "PUT", |
| 2703 | // GitLab label names cannot contain a comma. |
| 2704 | // @effect-diagnostics-next-line globalJsonInEffect:off |
| 2705 | stdin: JSON.stringify({ |
| 2706 | [input.applied ? "add_labels" : "remove_labels"]: input.labels.join(","), |
| 2707 | }), |
| 2708 | }); |
| 2709 | }), |
| 2710 | |
| 2711 | listProjectUsers: Effect.fn("GitLabPullRequestCli.listProjectUsers")(function (input) { |
| 2712 | return projectUsers(input).pipe( |
| 2713 | Effect.map(({ candidates, rawCount }) => ({ |
| 2714 | items: candidates.map(({ login, name, avatarUrl }) => ({ login, name, avatarUrl })), |
| 2715 | truncated: rawCount >= MAX_PAGE_SIZE, |
| 2716 | })), |
| 2717 | ); |
| 2718 | }), |
| 2719 | |
| 2720 | searchProjectReferences: Effect.fn("GitLabPullRequestCli.searchProjectReferences")( |
| 2721 | function (input) { |
| 2722 | return Effect.forEach( |
| 2723 | referenceSearches(input.search, input.sigil), |
| 2724 | ({ kind, params }) => |
| 2725 | projectReferences({ ...input, kind, params }).pipe( |
| 2726 | // A project with issues turned off answers 403 for issues; its merge requests still |
| 2727 | // complete. An unusable CLI or account still reaches the caller. |
| 2728 | Effect.catchIf( |
| 2729 | (cause) => |
| 2730 | cause._tag !== "GitLabCliUnavailableError" && |
| 2731 | cause._tag !== "GitLabCliAuthenticationError" && |
| 2732 | cause._tag !== "GitLabCliRateLimitError", |
| 2733 | (cause) => |
| 2734 | Effect.logWarning("GitLab reference search failed", { |
| 2735 | repository: input.repository, |
| 2736 | kind, |
| 2737 | reason: cause._tag, |
| 2738 | }).pipe(Effect.as({ items: [], rawCount: 0 })), |
| 2739 | ), |
| 2740 | ), |
| 2741 | { concurrency: "unbounded" }, |
| 2742 | ).pipe(Effect.map(mergeReferencePages)); |
| 2743 | }, |
| 2744 | ), |
| 2745 | |
| 2746 | listReviewerCandidates: Effect.fn("GitLabPullRequestCli.listReviewerCandidates")( |
| 2747 | function (input) { |
| 2748 | return Effect.all( |
| 2749 | [mergeRequestDetail(input), projectUsers({ ...input, search: input.query })], |
| 2750 | { |
| 2751 | concurrency: 2, |
| 2752 | }, |
| 2753 | ).pipe( |
| 2754 | Effect.map(([mergeRequest, users]) => { |
| 2755 | const author = mergeRequest.author?.login; |
| 2756 | const requested = (input.query?.trim() ? [] : mergeRequest.reviewerUsers).map( |
| 2757 | ({ id, ...actor }) => ({ |
| 2758 | ...actor, |
| 2759 | id: String(id), |
| 2760 | kind: "user" as const, |
| 2761 | isRequested: true, |
| 2762 | }), |
| 2763 | ); |
| 2764 | const listed = new Set(requested.map((reviewer) => reviewer.id)); |
| 2765 | // Every reviewer id, not just the ones shown above: a reviewer GitLab sent without a |
| 2766 | // username can still turn up on the users page, and must read as requested there or |
| 2767 | // choosing them would ask again instead of taking the request back. |
| 2768 | const requestedIds = new Set(mergeRequest.reviewerIds.map(String)); |
| 2769 | return { |
| 2770 | // The reviewers lead, and come from the merge request rather than the users page: |
| 2771 | // that page stops at a hundred, and somebody missing from it could not be taken off. |
| 2772 | // The author is dropped rather than shown unusable: GitLab refuses to make the person |
| 2773 | // who opened a merge request its reviewer. |
| 2774 | candidates: [ |
| 2775 | ...requested, |
| 2776 | ...users.candidates |
| 2777 | .filter((candidate) => candidate.login !== author && !listed.has(candidate.id)) |
| 2778 | .map((candidate) => |
| 2779 | requestedIds.has(candidate.id) |
| 2780 | ? { ...candidate, isRequested: true } |
| 2781 | : candidate, |
| 2782 | ), |
| 2783 | ], |
| 2784 | truncated: users.rawCount >= MAX_PAGE_SIZE, |
| 2785 | }; |
| 2786 | }), |
| 2787 | ); |
| 2788 | }, |
| 2789 | ), |
| 2790 | |
| 2791 | setReviewerRequest: Effect.fn("GitLabPullRequestCli.setReviewerRequest")(function (input) { |
| 2792 | return mergeRequestDetail(input).pipe( |
| 2793 | Effect.flatMap((mergeRequest) => { |
| 2794 | // GitLab replaces reviewer_ids wholesale. |
| 2795 | const ids = new Set(mergeRequest.reviewerIds); |
| 2796 | for (const reviewer of input.reviewers) { |
| 2797 | const id = Number(reviewer.id); |
| 2798 | if (!Number.isSafeInteger(id) || id <= 0) continue; |
| 2799 | if (input.requested) ids.add(id); |
| 2800 | else ids.delete(id); |
| 2801 | } |
| 2802 | return api({ |
| 2803 | cwd: input.cwd, |
| 2804 | host: input.host, |
| 2805 | path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`, |
| 2806 | method: "PUT", |
| 2807 | stdin: JSON.stringify({ reviewer_ids: [...ids] }), |
| 2808 | }); |
| 2809 | }), |
| 2810 | Effect.asVoid, |
| 2811 | ); |
| 2812 | }), |
| 2813 | |
| 2814 | runMergeRequestAction: Effect.fn("GitLabPullRequestCli.runMergeRequestAction")( |
| 2815 | function* (input) { |
| 2816 | // `glab mr merge` arms auto-merge and never disarms it, so the one direction the CLI has |
| 2817 | // no flag for is asked of GitLab directly through the same `api` passthrough the rest of |
| 2818 | // this module writes with. |
| 2819 | if (input.action === "delete-branch") return yield* deleteSourceBranch(input); |
| 2820 | if (input.action === "disable-auto-merge") { |
| 2821 | const result = yield* api({ |
| 2822 | cwd: input.cwd, |
| 2823 | host: input.host, |
| 2824 | path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/cancel_merge_when_pipeline_succeeds`, |
| 2825 | method: "POST", |
| 2826 | }); |
| 2827 | // The other actions run `glab mr`, which prints prose rather than the merge request. |
| 2828 | const decoded = decodeMergeRequestDetailJson(result.stdout.trim()); |
| 2829 | if (Result.isFailure(decoded)) return; |
| 2830 | // The decoder fills absent counts with zeros, which would be guesses here. |
| 2831 | const { |
| 2832 | additions: _additions, |
| 2833 | deletions: _deletions, |
| 2834 | changedFiles: _changedFiles, |
| 2835 | ...summary |
| 2836 | } = decoded.success; |
| 2837 | return summary; |
| 2838 | } |
| 2839 | if (input.action === "revert") return yield* revertMergeRequest(input); |
| 2840 | const executeMr = (subcommand: string, ...flags: ReadonlyArray<string>) => |
| 2841 | gitlab.execute({ |
| 2842 | cwd: input.cwd, |
| 2843 | host: input.host, |
| 2844 | args: ["mr", subcommand, String(input.number), "--repo", input.repository, ...flags], |
| 2845 | }); |
| 2846 | const [subcommand, ...flags] = actionArgs(input.action, input.mergeMethod); |
| 2847 | if (input.action === "merge" || input.action === "enable-auto-merge") { |
| 2848 | if (input.mergeMethod === "rebase") { |
| 2849 | // GitLab's rebase takes no SHA, so the reviewed head is checked just before it. |
| 2850 | if (input.expectedHeadSha !== undefined) { |
| 2851 | const current = yield* getDiffRefs(input); |
| 2852 | if (current.headSha !== input.expectedHeadSha) { |
| 2853 | return yield* new GitLabMutationRefusedError({ |
| 2854 | command: "glab", |
| 2855 | cwd: input.cwd, |
| 2856 | operation: "runMergeRequestAction", |
| 2857 | reasons: [`the head is now ${current.headSha}, not ${input.expectedHeadSha}`], |
| 2858 | }); |
| 2859 | } |
| 2860 | } |
| 2861 | // A rebase changes the source SHA, so wait for it before reading the merge guard. |
| 2862 | yield* executeMr("rebase"); |
| 2863 | } |
| 2864 | const refs = yield* getDiffRefs(input); |
| 2865 | // After a rebase, the head checked above is replaced by its rebased commits. |
| 2866 | flags.push( |
| 2867 | "--sha", |
| 2868 | input.mergeMethod === "rebase" ? refs.headSha : (input.expectedHeadSha ?? refs.headSha), |
| 2869 | ); |
| 2870 | if (input.removeAgentCreditsOnMerge === true) { |
| 2871 | // Read after the SHA guard, so a push since then fails the merge instead of |
| 2872 | // merging commits whose credits these messages don't cover. |
| 2873 | const messages = yield* graphqlRead({ |
| 2874 | cwd: input.cwd, |
| 2875 | host: input.host, |
| 2876 | operation: "getMergeMessages", |
| 2877 | query: MERGE_MESSAGES_GRAPHQL_QUERY, |
| 2878 | variables: { fullPath: input.repository, iid: String(input.number) }, |
| 2879 | decode: decodeMergeMessagesJson, |
| 2880 | }); |
| 2881 | // glab drops an empty message, which would bring the credits back. |
| 2882 | const clean = (message: string) => { |
| 2883 | const cleaned = removeAgentCredits(message); |
| 2884 | return cleaned.trim() === "" ? (messages.title ?? message) : cleaned; |
| 2885 | }; |
| 2886 | const merge = messages.merge === null ? null : clean(messages.merge); |
| 2887 | if (merge !== null && merge !== messages.merge) flags.push("--message", merge); |
| 2888 | const squashes = input.mergeMethod === "squash" || messages.squashOnMerge; |
| 2889 | const squash = messages.squash === null || !squashes ? null : clean(messages.squash); |
| 2890 | if (squash !== null && squash !== messages.squash) { |
| 2891 | // glab takes a squash message only alongside --squash, which changes nothing here. |
| 2892 | if (!flags.includes("--squash")) flags.push("--squash"); |
| 2893 | flags.push("--squash-message", squash); |
| 2894 | } |
| 2895 | } |
| 2896 | } |
| 2897 | yield* executeMr(subcommand!, ...flags); |
| 2898 | }, |
| 2899 | ), |
| 2900 | |
| 2901 | updateMergeRequest: Effect.fn("GitLabPullRequestCli.updateMergeRequest")(function (input) { |
| 2902 | return api({ |
| 2903 | cwd: input.cwd, |
| 2904 | host: input.host, |
| 2905 | path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`, |
| 2906 | method: "PUT", |
| 2907 | // Omitted fields remain unchanged; empty values clear them. |
| 2908 | stdin: JSON.stringify({ |
| 2909 | ...(input.title === undefined ? {} : { title: input.title }), |
| 2910 | ...(input.description === undefined ? {} : { description: input.description }), |
| 2911 | ...(input.allowCollaboration === undefined |
| 2912 | ? {} |
| 2913 | : { allow_collaboration: input.allowCollaboration }), |
| 2914 | }), |
| 2915 | }).pipe(Effect.asVoid); |
| 2916 | }), |
| 2917 | |
| 2918 | commentOnMergeRequest: Effect.fn("GitLabPullRequestCli.commentOnMergeRequest")( |
| 2919 | function (input) { |
| 2920 | return api({ |
| 2921 | cwd: input.cwd, |
| 2922 | host: input.host, |
| 2923 | path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/notes`, |
| 2924 | method: "POST", |
| 2925 | // JSON avoids glab's coercion of numeric/boolean comment bodies. |
| 2926 | stdin: JSON.stringify({ body: input.body }), |
| 2927 | }).pipe(Effect.asVoid); |
| 2928 | }, |
| 2929 | ), |
| 2930 | |
| 2931 | updateNote: Effect.fn("GitLabPullRequestCli.updateNote")(function (input) { |
| 2932 | return api({ |
| 2933 | cwd: input.cwd, |
| 2934 | host: input.host, |
| 2935 | path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/notes/${encodeURIComponent( |
| 2936 | input.noteId, |
| 2937 | )}`, |
| 2938 | method: "PUT", |
| 2939 | stdin: JSON.stringify({ body: input.body }), |
| 2940 | }).pipe(Effect.asVoid); |
| 2941 | }), |
| 2942 | |
| 2943 | listDiscussions: Effect.fn("GitLabPullRequestCli.listDiscussions")(function (input) { |
| 2944 | return discussionsPage({ |
| 2945 | ...input, |
| 2946 | page: 1, |
| 2947 | collected: [], |
| 2948 | collectedDiffRefs: new Map(), |
| 2949 | collectedFindingIds: [], |
| 2950 | }); |
| 2951 | }), |
| 2952 | |
| 2953 | submitReview: Effect.fn("GitLabPullRequestCli.submitReview")(function* (input) { |
| 2954 | const project = projectPath(input.repository); |
| 2955 | const mergeRequest = `projects/${project}/merge_requests/${input.number}`; |
| 2956 | // GitLab has no pending review, so a review is replayed as separate requests and a failure |
| 2957 | // leaves earlier ones posted. Requesting changes (GitLab 18.9+) goes first so an older |
| 2958 | // server fails before any comment lands; approval goes last so a half-sent review never |
| 2959 | // approves. |
| 2960 | if (input.verdict === "request-changes") { |
| 2961 | // GitLab keeps the verdict on the reviewer, so the viewer joins the reviewers first. |
| 2962 | const viewer = yield* viewerUsername(input); |
| 2963 | const target = { projectPath: input.repository, iid: String(input.number) }; |
| 2964 | yield* graphqlMutation({ |
| 2965 | cwd: input.cwd, |
| 2966 | host: input.host, |
| 2967 | operation: "submitReview", |
| 2968 | query: SET_SELF_AS_REVIEWER_MUTATION, |
| 2969 | variables: { ...target, reviewers: [viewer] }, |
| 2970 | }); |
| 2971 | yield* graphqlMutation({ |
| 2972 | cwd: input.cwd, |
| 2973 | host: input.host, |
| 2974 | operation: "submitReview", |
| 2975 | query: REQUEST_CHANGES_MUTATION, |
| 2976 | variables: target, |
| 2977 | }); |
| 2978 | } |
| 2979 | if (input.comments.length > 0) { |
| 2980 | const refs = yield* getDiffRefs(input); |
| 2981 | const rangedFileHeaders = input.comments.flatMap((comment) => |
| 2982 | comment.startPosition !== undefined && |
| 2983 | (comment.startPosition.kind !== "context" || comment.position.kind !== "context") |
| 2984 | ? [gitLabDiffHeader(comment.oldPath ?? comment.path, comment.path)] |
| 2985 | : [], |
| 2986 | ); |
| 2987 | // Line codes only steer GitLab's highlight of a range, so an unreadable diff falls back |
| 2988 | // to codes without the other side's counter rather than blocking the review. |
| 2989 | const patch = yield* patchCovering(input, rangedFileHeaders, 1, "").pipe( |
| 2990 | Effect.orElseSucceed(() => ""), |
| 2991 | ); |
| 2992 | yield* Effect.forEach( |
| 2993 | input.comments, |
| 2994 | (comment) => |
| 2995 | gitLabLineRange(patch, comment).pipe( |
| 2996 | Effect.flatMap((lineRange) => |
| 2997 | api({ |
| 2998 | cwd: input.cwd, |
| 2999 | host: input.host, |
| 3000 | path: `${mergeRequest}/discussions`, |
| 3001 | method: "POST", |
| 3002 | stdin: JSON.stringify({ |
| 3003 | body: comment.body, |
| 3004 | position: { |
| 3005 | base_sha: refs.baseSha, |
| 3006 | head_sha: refs.headSha, |
| 3007 | start_sha: refs.startSha, |
| 3008 | position_type: "text", |
| 3009 | // Both paths are sent because GitLab resolves a position against both |
| 3010 | // sides of the diff. They differ only for a renamed file, which is why the |
| 3011 | // draft carries the name the file had before the change. |
| 3012 | old_path: comment.oldPath ?? comment.path, |
| 3013 | new_path: comment.path, |
| 3014 | ...gitLabReviewPositionLines(comment.position), |
| 3015 | ...lineRange, |
| 3016 | }, |
| 3017 | }), |
| 3018 | }), |
| 3019 | ), |
| 3020 | ), |
| 3021 | { discard: true }, |
| 3022 | ); |
| 3023 | } |
| 3024 | if (input.body.trim().length > 0) { |
| 3025 | yield* api({ |
| 3026 | cwd: input.cwd, |
| 3027 | host: input.host, |
| 3028 | path: `${mergeRequest}/notes`, |
| 3029 | method: "POST", |
| 3030 | // @effect-diagnostics-next-line globalJsonInEffect:off |
| 3031 | stdin: JSON.stringify({ body: input.body }), |
| 3032 | }); |
| 3033 | } |
| 3034 | if (input.verdict === "approve") { |
| 3035 | yield* api({ |
| 3036 | cwd: input.cwd, |
| 3037 | host: input.host, |
| 3038 | path: `${mergeRequest}/approve`, |
| 3039 | method: "POST", |
| 3040 | }); |
| 3041 | } |
| 3042 | }), |
| 3043 | |
| 3044 | replyToDiscussion: Effect.fn("GitLabPullRequestCli.replyToDiscussion")(function (input) { |
| 3045 | return api({ |
| 3046 | cwd: input.cwd, |
| 3047 | host: input.host, |
| 3048 | path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/discussions/${encodeURIComponent( |
| 3049 | input.discussionId, |
| 3050 | )}/notes`, |
| 3051 | method: "POST", |
| 3052 | stdin: JSON.stringify({ body: input.body }), |
| 3053 | }).pipe(Effect.asVoid); |
| 3054 | }), |
| 3055 | |
| 3056 | setDiscussionResolution: Effect.fn("GitLabPullRequestCli.setDiscussionResolution")( |
| 3057 | function (input) { |
| 3058 | return api({ |
| 3059 | cwd: input.cwd, |
| 3060 | host: input.host, |
| 3061 | path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/discussions/${encodeURIComponent( |
| 3062 | input.discussionId, |
| 3063 | )}`, |
| 3064 | method: "PUT", |
| 3065 | stdin: JSON.stringify({ resolved: input.resolved }), |
| 3066 | }).pipe(Effect.asVoid); |
| 3067 | }, |
| 3068 | ), |
| 3069 | }); |
| 3070 | }); |
| 3071 | |
| 3072 | export const layer = Layer.effect(GitLabPullRequestCli, make); |