| 1 | import { mkdtemp, rm } from 'node:fs/promises'; |
| 2 | import { tmpdir } |
| 3 | import path from 'node:path |
| 4 | import { type Database, |
| 5 | import { Inject, Injectable |
| 6 | import { |
| 7 | and, |
| 8 | count, |
| 9 | desc, |
| 10 | eq, |
| 11 | type GetColumnData, |
| 12 | getTableColumns, |
| 13 | inArray, |
| 14 | isNull, |
| 15 | lt, |
| 16 | ne, |
| 17 | or, |
| 18 | sql, |
| 19 | } from 'drizzle-orm'; |
| 20 | |
| 21 | import { DATABASE } |
| 22 | import { publishEvent } |
| 23 | import { listCommits } |
| 24 | import { CommitVerificationService } |
| 25 | import { |
| 26 | listDiffFiles, |
| 27 | mergeBase, |
| 28 | streamDiffPatch, |
| 29 | } from '../../lib/git/diff/diff.js'; |
| 30 | import { runGit } |
| 31 | import { RepositoryMaterializerService } |
| 32 | import { |
| 33 | commitTree, |
| 34 | mergeTree, |
| 35 | packRange, |
| 36 | rebaseCommits, |
| 37 | } from '../../lib/git/merge/merge.js'; |
| 38 | import { |
| 39 | resolveCommit, |
| 40 | resolveDefaultRef, |
| 41 | } from '../../lib/git/tree/resolve-ref.js'; |
| 42 | import { |
| 43 | closeIssue, |
| 44 | MAX_CLOSING_COMMITS, |
| 45 | } from '../../lib/issues/close-issue.js'; |
| 46 | import { IssueReferencesService } |
| 47 | import { IssuesService } |
| 48 | import { fileBody } |
| 49 | import { RepositoryAccessService } |
| 50 | import { |
| 51 | ownerNameOf, |
| 52 | type Repository, |
| 53 | type RepositoryOperation, |
| 54 | } from '../../lib/git/repository-access/repository-access.js'; |
| 55 | import { RepositoryStorageService } |
| 56 | import { PushTransactionService } |
| 57 | import { UsersService } |
| 58 | import { decodeCursor, encodeCursor |
| 59 | import { |
| 60 | BranchNotFoundError, |
| 61 | CommitNotFoundError, |
| 62 | InvalidCursorError, |
| 63 | } from '../repositories/repositories.errors.js'; |
| 64 | import { |
| 65 | CreatePullRequestRequestDTO, |
| 66 | UpdatePullRequestRequestDTO, |
| 67 | } from './dto/create-pull-request.dto.js'; |
| 68 | import { GetPullRequestsQueryDTO } |
| 69 | import type { MergeMethod |
| 70 | import { |
| 71 | NothingToMergeError, |
| 72 | PullRequestAlreadyOpenError, |
| 73 | PullRequestConflictError, |
| 74 | PullRequestDraftError, |
| 75 | PullRequestHeadDeletedError, |
| 76 | PullRequestNotFoundError, |
| 77 | PullRequestNotOpenError, |
| 78 | SameBranchPullRequestError, |
| 79 | UnrelatedHistoriesError, |
| 80 | UnrelatedRepositoriesError, |
| 81 | } from './pull-requests.errors.js'; |
| 82 | |
| 83 | // Number, title, body and author live on the issue a request is attached to. |
| 84 | const pullRequestColumns = { |
| 85 | id: schema.pullRequest |
| 86 | issueId: schema.pullRequest |
| 87 | number: schema.issue |
| 88 | title: schema.issue |
| 89 | body: schema.issue |
| 90 | authorId: schema.issue |
| 91 | state: schema.pullRequest |
| 92 | draft: schema.pullRequest |
| 93 | baseRepositoryId: schema.pullRequest |
| 94 | baseRef: schema.pullRequest |
| 95 | headRepositoryId: schema.pullRequest |
| 96 | headRef: schema.pullRequest |
| 97 | headSha: schema.pullRequest |
| 98 | mergeCommitSha: schema.pullRequest |
| 99 | createdAt: schema.issue |
| 100 | updatedAt: schema.issue |
| 101 | }; |
| 102 | |
| 103 | const DEFAULT_PAGE_SIZE = 20 |
| 104 | // ponytail: a squash message lists at most this many of the head's commits; older ones are left out of the body, not the tree. |
| 105 | const MAX_SQUASH_MESSAGES = 250 |
| 106 | const MAX_PAGE_SIZE = 100 |
| 107 | |
| 108 | type PullRequest |
| 109 | [Key |
| 110 | (typeof pullRequestColumns |
| 111 | >; |
| 112 | }; |
| 113 | |
| 114 | @Injectable() |
| 115 | export class PullRequestsService |
| 116 | constructor( |
| 117 | @Inject(DATABASE) |
| 118 | private readonly users |
| 119 | private readonly access |
| 120 | private readonly storage |
| 121 | private readonly materializer |
| 122 | private readonly pushTransaction |
| 123 | private readonly verification |
| 124 | private readonly issues |
| 125 | private readonly references |
| 126 | ) {} |
| 127 | |
| 128 | async createPullRequest({ |
| 129 | username, |
| 130 | repo, |
| 131 | requesterId, |
| 132 | body, |
| 133 | }: { |
| 134 | username: string |
| 135 | repo: string |
| 136 | requesterId: string |
| 137 | body: CreatePullRequestRequestDTO |
| 138 | }) { |
| 139 | const base = |
| 140 | const head = |
| 141 | const headRef = |
| 142 | ? body.head. |
| 143 | : body.head; |
| 144 | |
| 145 | if (head.id |
| 146 | throw new SameBranchPullRequestError() |
| 147 | } |
| 148 | |
| 149 | const [baseDirectory, |
| 150 | this.openCache(base |
| 151 | this.openCache(head |
| 152 | ]); |
| 153 | const baseSha = |
| 154 | const headSha = |
| 155 | |
| 156 | const alternates = |
| 157 | if ( |
| 158 | !(await mergeBase( |
| 159 | gitDir: baseDirectory, |
| 160 | alternates, |
| 161 | a: baseSha, |
| 162 | b: headSha, |
| 163 | })) |
| 164 | ) { |
| 165 | throw new UnrelatedHistoriesError() |
| 166 | } |
| 167 | |
| 168 | const [existing] |
| 169 | .select({ number: |
| 170 | .from(schema.pullRequest |
| 171 | .innerJoin(schema.issue |
| 172 | .where( |
| 173 | and( |
| 174 | eq(schema.pullRequest |
| 175 | eq(schema.pullRequest |
| 176 | eq(schema.pullRequest |
| 177 | eq(schema.pullRequest |
| 178 | eq(schema.pullRequest |
| 179 | ), |
| 180 | ); |
| 181 | if (existing) throw |
| 182 | |
| 183 | const issue = |
| 184 | { |
| 185 | repository: base, |
| 186 | title: body.title |
| 187 | body: body.body |
| 188 | authorId: requesterId, |
| 189 | isPullRequest: true, |
| 190 | }, |
| 191 | async (tx, |
| 192 | await tx.insert |
| 193 | issueId: row.id |
| 194 | baseRepositoryId: base.id |
| 195 | baseRef: body.base |
| 196 | headRepositoryId: head.id |
| 197 | headRef, |
| 198 | headSha, |
| 199 | draft: body.draft |
| 200 | }); |
| 201 | }, |
| 202 | ); |
| 203 | |
| 204 | const { pullRequest |
| 205 | username, |
| 206 | repo, |
| 207 | number: issue.number |
| 208 | requesterId, |
| 209 | }); |
| 210 | return this.expandPullRequest |
| 211 | } |
| 212 | |
| 213 | /** The files a request would carry, before one is opened. */ |
| 214 | async compare(params |
| 215 | const { from, |
| 216 | return { from, |
| 217 | } |
| 218 | |
| 219 | /** One file of that same diff, or all of it when no path is given. */ |
| 220 | async compareStreamPatch(params |
| 221 | const { range |
| 222 | return streamDiffPatch({ |
| 223 | } |
| 224 | |
| 225 | private async openComparison |
| 226 | username, |
| 227 | repo, |
| 228 | requesterId, |
| 229 | base: baseRef, |
| 230 | head: headSpec, |
| 231 | }: CompareParams |
| 232 | const base = |
| 233 | const head = |
| 234 | const headRef = |
| 235 | ? headSpec.slice( |
| 236 | : headSpec; |
| 237 | |
| 238 | const [baseDirectory, |
| 239 | this.openCache(base |
| 240 | this.openCache(head |
| 241 | ]); |
| 242 | const alternates = |
| 243 | |
| 244 | const baseSha = |
| 245 | const headSha = |
| 246 | const from = |
| 247 | gitDir: baseDirectory, |
| 248 | alternates, |
| 249 | a: baseSha, |
| 250 | b: headSha, |
| 251 | }); |
| 252 | if (!from) |
| 253 | |
| 254 | return { |
| 255 | from, |
| 256 | to: headSha, |
| 257 | range: { gitDir: baseDirectory |
| 258 | }; |
| 259 | } |
| 260 | |
| 261 | async getPullRequests({ |
| 262 | username, |
| 263 | repo, |
| 264 | requesterId, |
| 265 | query, |
| 266 | }: { |
| 267 | username: string |
| 268 | repo: string |
| 269 | requesterId?: string |
| 270 | query: GetPullRequestsQueryDTO |
| 271 | }) { |
| 272 | const base = |
| 273 | |
| 274 | const requested = |
| 275 | const pageSize = |
| 276 | ? Math.min( |
| 277 | : DEFAULT_PAGE_SIZE; |
| 278 | |
| 279 | const decoded = |
| 280 | if (query.cursor |
| 281 | |
| 282 | const state = |
| 283 | const rows = |
| 284 | .select(pullRequestColumns) |
| 285 | .from(schema.pullRequest |
| 286 | .innerJoin(schema.issue |
| 287 | .where( |
| 288 | and( |
| 289 | eq(schema.pullRequest |
| 290 | state === 'all' |
| 291 | decoded |
| 292 | ? or( |
| 293 | lt(schema.issue |
| 294 | and( |
| 295 | eq(schema.issue |
| 296 | lt(schema.pullRequest |
| 297 | ), |
| 298 | ) |
| 299 | : undefined, |
| 300 | ), |
| 301 | ) |
| 302 | .orderBy(desc(schema |
| 303 | .limit(pageSize + |
| 304 | |
| 305 | const hasMore = |
| 306 | const page = |
| 307 | const last = |
| 308 | |
| 309 | const [totals] |
| 310 | .select({ total: |
| 311 | .from(schema.pullRequest |
| 312 | .where( |
| 313 | and( |
| 314 | eq(schema.pullRequest |
| 315 | state === 'all' |
| 316 | ), |
| 317 | ); |
| 318 | |
| 319 | return { |
| 320 | pullRequests: await Promise |
| 321 | page.map((row |
| 322 | ), |
| 323 | total: totals?.total |
| 324 | nextCursor: |
| 325 | hasMore && last |
| 326 | ? encodeCursor({ date |
| 327 | : null, |
| 328 | hasMore, |
| 329 | }; |
| 330 | } |
| 331 | |
| 332 | async getPullRequest(params |
| 333 | const { pullRequest, |
| 334 | const files = |
| 335 | ? await listDiffFiles( |
| 336 | gitDir: git.baseDirectory |
| 337 | alternates: git.alternates |
| 338 | from: git.mergeBase |
| 339 | to: git.headSha |
| 340 | }) |
| 341 | : []; |
| 342 | |
| 343 | const merge = |
| 344 | pullRequest.state === |
| 345 | git.mergeBase !== |
| 346 | git.mergeBase !== |
| 347 | ? await mergeTree( |
| 348 | gitDir: git.baseDirectory |
| 349 | alternates: git.alternates |
| 350 | base: git.baseSha |
| 351 | head: git.headSha |
| 352 | }) |
| 353 | : null; |
| 354 | |
| 355 | return { |
| 356 | ...(await this |
| 357 | // The stored head is only refreshed on merge; an open request's diff, and whether a line comment is outdated, go by the branch as it stands. |
| 358 | headSha: git.headSha |
| 359 | mergeBase: git.mergeBase |
| 360 | commitCount: git.mergeBase |
| 361 | ? await this. |
| 362 | : 0, |
| 363 | changedFiles: files.length, |
| 364 | additions: files.reduce |
| 365 | deletions: files.reduce |
| 366 | mergeable: !pullRequest.draft |
| 367 | conflicts: merge?.conflicts |
| 368 | squash: merge ? |
| 369 | reviewers: await this |
| 370 | }; |
| 371 | } |
| 372 | |
| 373 | /** Each reviewer's latest verdict. A dismissed one leaves that reviewer with none, rather than falling back to an older verdict. */ |
| 374 | private reviewers(pullRequestId |
| 375 | const latest = |
| 376 | .selectDistinctOn([schema.pullRequestReview |
| 377 | username: sql<string |
| 378 | 'username', |
| 379 | ), |
| 380 | image: schema.user |
| 381 | state: schema.pullRequestReview |
| 382 | dismissalMessage: schema.pullRequestReview |
| 383 | }) |
| 384 | .from(schema.pullRequestReview |
| 385 | .innerJoin( |
| 386 | schema.user, |
| 387 | eq(schema.user |
| 388 | ) |
| 389 | .where( |
| 390 | and( |
| 391 | eq(schema.pullRequestReview |
| 392 | inArray(schema.pullRequestReview |
| 393 | 'approved', |
| 394 | 'changes_requested', |
| 395 | ]), |
| 396 | ), |
| 397 | ) |
| 398 | .orderBy( |
| 399 | schema.pullRequestReview.authorId |
| 400 | desc(schema.pullRequestReview |
| 401 | ) |
| 402 | .as('latest') |
| 403 | |
| 404 | return this.db |
| 405 | .select({ |
| 406 | username: latest.username |
| 407 | image: latest.image |
| 408 | state: latest.state |
| 409 | }) |
| 410 | .from(latest) |
| 411 | .where(isNull(latest |
| 412 | } |
| 413 | |
| 414 | async getCommits( |
| 415 | params: PullRequestRef |
| 416 | ) { |
| 417 | const git = |
| 418 | if (!git.mergeBase |
| 419 | |
| 420 | const limit = |
| 421 | Math.max(params |
| 422 | MAX_PAGE_SIZE, |
| 423 | ); |
| 424 | const { commits, |
| 425 | gitDir: git.baseDirectory |
| 426 | env: git.env |
| 427 | ref: `${git. |
| 428 | limit, |
| 429 | }); |
| 430 | |
| 431 | // A fork's commits live in the other repository's objects, which is why the lending env has to come along for the signatures to be readable. |
| 432 | const verdicts = |
| 433 | gitDir: git.baseDirectory |
| 434 | env: git.env |
| 435 | commits, |
| 436 | }); |
| 437 | |
| 438 | return { |
| 439 | commits: commits.map |
| 440 | ...commit, |
| 441 | verification: verdicts.get |
| 442 | })), |
| 443 | total: await this |
| 444 | nextCursor, |
| 445 | }; |
| 446 | } |
| 447 | |
| 448 | async getFiles(params |
| 449 | const git = |
| 450 | if (!git.mergeBase |
| 451 | return { from: |
| 452 | } |
| 453 | |
| 454 | return { |
| 455 | from: git.mergeBase |
| 456 | to: git.headSha |
| 457 | files: await listDiffFiles |
| 458 | gitDir: git.baseDirectory |
| 459 | alternates: git.alternates |
| 460 | from: git.mergeBase |
| 461 | to: git.headSha |
| 462 | }), |
| 463 | }; |
| 464 | } |
| 465 | |
| 466 | async streamPatch(params |
| 467 | const git = |
| 468 | if (git.headDeleted |
| 469 | return streamDiffPatch({ |
| 470 | gitDir: git.baseDirectory |
| 471 | alternates: git.alternates |
| 472 | from: git.mergeBase |
| 473 | to: git.headSha |
| 474 | path: params.path |
| 475 | }); |
| 476 | } |
| 477 | |
| 478 | /** The result is built in the base cache and then pushed through `commitPush`, the same commit point a `git push` uses. Nothing about a merge is allowed to reach the base repository by another route. */ |
| 479 | async mergePullRequest( |
| 480 | params: PullRequestRef |
| 481 | requesterId: string |
| 482 | title?: string |
| 483 | message?: string |
| 484 | method?: MergeMethod |
| 485 | }, |
| 486 | ) { |
| 487 | const { pullRequest, |
| 488 | ...params, |
| 489 | operation: 'write', |
| 490 | }); |
| 491 | if (pullRequest.state |
| 492 | throw new PullRequestNotOpenError( |
| 493 | } |
| 494 | // An open request always has its head: a repository heading one cannot be deleted. |
| 495 | const git = |
| 496 | pullRequest, |
| 497 | base, |
| 498 | pullRequest.headRepositoryId!, |
| 499 | ); |
| 500 | if (!git.mergeBase |
| 501 | if (git.mergeBase |
| 502 | |
| 503 | const method = |
| 504 | const merger = |
| 505 | const committer = |
| 506 | const mergeCommitSha = |
| 507 | method === 'rebase' |
| 508 | ? await this. |
| 509 | : await this. |
| 510 | squash: method === |
| 511 | title: params.title |
| 512 | message: params.message |
| 513 | committer, |
| 514 | }); |
| 515 | // A rebase drops merge commits, so a head made only of them replays to nothing. |
| 516 | if (mergeCommitSha === |
| 517 | |
| 518 | const directory = |
| 519 | try { |
| 520 | // ponytail: excludes only the base tip, so objects on the base repository's other branches can be packed again. Exclude every base ref if entry size matters. |
| 521 | const pack = |
| 522 | gitDir: git.baseDirectory |
| 523 | alternates: git.alternates |
| 524 | // The head rides along even when a squash or rebase leaves it unreachable: a merged request reads its commits and diff from the base alone. |
| 525 | include: [mergeCommitSha, |
| 526 | exclude: [git.baseSha |
| 527 | prefix: path.join |
| 528 | }); |
| 529 | |
| 530 | // The row stays locked until the merge is recorded, so the request cannot be closed or turned into a draft between this check and the push. Nothing that can fail after the push belongs in here: a rollback would leave the branch merged and the request open. |
| 531 | const seq = |
| 532 | const [locked] |
| 533 | .select({ |
| 534 | state: schema.pullRequest |
| 535 | draft: schema.pullRequest |
| 536 | }) |
| 537 | .from(schema.pullRequest |
| 538 | .where(eq(schema |
| 539 | .for('update') |
| 540 | if (locked.draft |
| 541 | if (locked.state |
| 542 | throw new PullRequestNotOpenError( |
| 543 | } |
| 544 | |
| 545 | const { seq |
| 546 | repoId: base.id |
| 547 | transitions: [ |
| 548 | { |
| 549 | ref: `refs/heads/${pullRequest |
| 550 | oldOid: Buffer.from |
| 551 | newOid: Buffer.from |
| 552 | }, |
| 553 | ], |
| 554 | body: fileBody(pack |
| 555 | packOffset: 0, |
| 556 | pushedBy: params.requesterId |
| 557 | }); |
| 558 | |
| 559 | await tx |
| 560 | .update(schema.pullRequest |
| 561 | .set({ |
| 562 | state: 'merged', |
| 563 | mergeCommitSha, |
| 564 | headSha: git.headSha |
| 565 | mergedAt: new Date |
| 566 | }) |
| 567 | .where(eq(schema |
| 568 | await closeIssue(tx |
| 569 | issueId: pullRequest.issueId |
| 570 | actorId: params.requesterId |
| 571 | type: 'merged', |
| 572 | commitSha: mergeCommitSha, |
| 573 | }); |
| 574 | return seq; |
| 575 | }); |
| 576 | |
| 577 | // Only a merge into the default branch closes anything, the same rule GitHub follows. |
| 578 | const isDefaultBranch = |
| 579 | (await resolveDefaultRef({ |
| 580 | `refs/heads/${pullRequest.baseRef |
| 581 | if (isDefaultBranch) { |
| 582 | const { commits |
| 583 | gitDir: git.baseDirectory |
| 584 | env: git.env |
| 585 | // What landed on the base: the head's own commits, or their squashed or rebased copies. |
| 586 | ref: `${git. |
| 587 | limit: MAX_CLOSING_COMMITS, |
| 588 | }); |
| 589 | await this.db |
| 590 | await this.references |
| 591 | repository: base, |
| 592 | actorId: params.requesterId |
| 593 | commits, |
| 594 | }); |
| 595 | await this.references |
| 596 | sources: [ |
| 597 | { type: 'issue', |
| 598 | ...commits.map |
| 599 | type: 'commit' as |
| 600 | id: commit.sha |
| 601 | })), |
| 602 | ], |
| 603 | actorId: params.requesterId |
| 604 | sourceIssueId: pullRequest.issueId |
| 605 | }); |
| 606 | }); |
| 607 | } |
| 608 | |
| 609 | await this.db |
| 610 | .update(schema.repository |
| 611 | .set({ lastPushedAt: |
| 612 | .where(eq(schema |
| 613 | |
| 614 | return { mergeCommitSha, |
| 615 | } finally { |
| 616 | await rm(directory |
| 617 | } |
| 618 | } |
| 619 | |
| 620 | /** A merge commit on top of the base tip, or with `squash` the same tree as a single-parent commit credited to the request's author. */ |
| 621 | private async commitMerge |
| 622 | git: LiveComparison |
| 623 | { |
| 624 | squash, |
| 625 | title, |
| 626 | message, |
| 627 | committer, |
| 628 | }: { |
| 629 | squash: boolean |
| 630 | title?: string |
| 631 | message?: string |
| 632 | committer: { |
| 633 | }, |
| 634 | ) { |
| 635 | const { tree, |
| 636 | gitDir: git.baseDirectory |
| 637 | alternates: git.alternates |
| 638 | base: git.baseSha |
| 639 | head: git.headSha |
| 640 | }); |
| 641 | if (!clean) |
| 642 | |
| 643 | const { pullRequest |
| 644 | if (squash) { |
| 645 | const author = |
| 646 | const fallback = |
| 647 | const body = |
| 648 | return commitTree({ |
| 649 | gitDir: git.baseDirectory |
| 650 | alternates: git.alternates |
| 651 | tree, |
| 652 | parents: [git.baseSha |
| 653 | message: `${title |
| 654 | author: { name: author |
| 655 | committer, |
| 656 | }); |
| 657 | } |
| 658 | |
| 659 | // a fork's branch name is ambiguous on its own, so the merge subject carries the owner exactly as the request was opened with |
| 660 | const { head |
| 661 | const headLabel = |
| 662 | git.head.id |
| 663 | ? pullRequest.headRef |
| 664 | : `${head.username |
| 665 | return commitTree({ |
| 666 | gitDir: git.baseDirectory |
| 667 | alternates: git.alternates |
| 668 | tree, |
| 669 | parents: [git.baseSha |
| 670 | message: `${title |
| 671 | author: committer, |
| 672 | }); |
| 673 | } |
| 674 | |
| 675 | /** What a squash commit says unless the merger rewrites it: the request title, then the head's commit messages oldest first. */ |
| 676 | private async squashMessage |
| 677 | pullRequest, |
| 678 | baseDirectory, |
| 679 | env, |
| 680 | mergeBase, |
| 681 | headSha, |
| 682 | }: { |
| 683 | pullRequest: PullRequest |
| 684 | baseDirectory: string |
| 685 | env?: Record |
| 686 | mergeBase: string |
| 687 | headSha: string |
| 688 | }) { |
| 689 | const { commits |
| 690 | gitDir: baseDirectory, |
| 691 | env, |
| 692 | ref: `${mergeBase} |
| 693 | limit: MAX_SQUASH_MESSAGES, |
| 694 | }); |
| 695 | return { |
| 696 | title: `${pullRequest. |
| 697 | message: commits |
| 698 | .reverse() |
| 699 | .map( |
| 700 | (commit) => |
| 701 | `* ${[commit.subject |
| 702 | ) |
| 703 | .join('\n\n') |
| 704 | }; |
| 705 | } |
| 706 | |
| 707 | private async rebase |
| 708 | git: LiveComparison |
| 709 | committer: { |
| 710 | ) { |
| 711 | const rebased = |
| 712 | gitDir: git.baseDirectory |
| 713 | alternates: git.alternates |
| 714 | onto: git.baseSha |
| 715 | from: git.mergeBase |
| 716 | to: git.headSha |
| 717 | committer, |
| 718 | }); |
| 719 | if (!rebased.clean |
| 720 | return rebased.tip |
| 721 | } |
| 722 | |
| 723 | /** Title and description only - the branches a request spans never move. */ |
| 724 | async updatePullRequest( |
| 725 | params: PullRequestRef |
| 726 | requesterId: string |
| 727 | body: UpdatePullRequestRequestDTO |
| 728 | }, |
| 729 | ) { |
| 730 | await this.load |
| 731 | await this.issues |
| 732 | return this.expandPullRequest |
| 733 | } |
| 734 | |
| 735 | async closePullRequest(params |
| 736 | const { pullRequest |
| 737 | if (pullRequest.state |
| 738 | throw new PullRequestNotOpenError( |
| 739 | } |
| 740 | |
| 741 | await this.issues |
| 742 | return this.expandPullRequest |
| 743 | } |
| 744 | |
| 745 | /** Marks a request ready for review, or turns it back into a draft. Asking for the state it is already in records nothing. */ |
| 746 | async setDraft( |
| 747 | params: PullRequestRef |
| 748 | ) { |
| 749 | const { pullRequest, |
| 750 | if (pullRequest.authorId |
| 751 | await this.authorize |
| 752 | } |
| 753 | if (pullRequest.state |
| 754 | throw new PullRequestNotOpenError( |
| 755 | } |
| 756 | |
| 757 | // Conditional, so two identical requests record one event and a request merged in the meantime is left alone. |
| 758 | await this.db |
| 759 | const changed = |
| 760 | .update(schema.pullRequest |
| 761 | .set({ draft: |
| 762 | .where( |
| 763 | and( |
| 764 | eq(schema.pullRequest |
| 765 | eq(schema.pullRequest |
| 766 | ne(schema.pullRequest |
| 767 | ), |
| 768 | ) |
| 769 | .returning({ id: |
| 770 | if (changed.length |
| 771 | await tx.insert |
| 772 | issueId: pullRequest.issueId |
| 773 | actorId: params.requesterId |
| 774 | type: params.draft |
| 775 | }); |
| 776 | await publishEvent(tx |
| 777 | type: params.draft |
| 778 | ? 'pull_request.converted_to_draft' |
| 779 | : 'pull_request.ready_for_review', |
| 780 | repositoryId: base.id |
| 781 | actorId: params.requesterId |
| 782 | payload: { issueId: pullRequest |
| 783 | }); |
| 784 | }); |
| 785 | return this.expandPullRequest |
| 786 | } |
| 787 | |
| 788 | /** Resolves the range the request covers. A merged request reads only the base, which has held its commits since the merge, so it outlives its head branch and repository. */ |
| 789 | async open(params |
| 790 | const { pullRequest, |
| 791 | if (pullRequest.mergeCommitSha |
| 792 | return this.openMerged |
| 793 | } |
| 794 | if (!pullRequest.headRepositoryId |
| 795 | return { |
| 796 | pullRequest, |
| 797 | base, |
| 798 | baseDirectory: await this |
| 799 | alternates: [], |
| 800 | env: undefined, |
| 801 | baseSha: pullRequest.headSha |
| 802 | headSha: pullRequest.headSha |
| 803 | mergeBase: null, |
| 804 | headDeleted: true, |
| 805 | }; |
| 806 | } |
| 807 | return this.openLive |
| 808 | } |
| 809 | |
| 810 | private async openMerged |
| 811 | pullRequest: PullRequest |
| 812 | base: Repository |
| 813 | mergeCommitSha: string, |
| 814 | ) { |
| 815 | const baseDirectory = |
| 816 | const baseSha = |
| 817 | if (!baseSha) |
| 818 | |
| 819 | return { |
| 820 | pullRequest, |
| 821 | base, |
| 822 | baseDirectory, |
| 823 | alternates: [], |
| 824 | env: undefined, |
| 825 | baseSha, |
| 826 | headSha: pullRequest.headSha |
| 827 | mergeBase: await mergeBase |
| 828 | gitDir: baseDirectory, |
| 829 | alternates: [], |
| 830 | a: baseSha, |
| 831 | b: pullRequest.headSha |
| 832 | }), |
| 833 | headDeleted: false, |
| 834 | }; |
| 835 | } |
| 836 | |
| 837 | /** Materializes both sides and resolves the branches as they stand now. */ |
| 838 | async openLive( |
| 839 | pullRequest: PullRequest |
| 840 | base: Repository |
| 841 | headRepositoryId: string, |
| 842 | ) { |
| 843 | const [head] |
| 844 | .select() |
| 845 | .from(schema.repository |
| 846 | .where(eq(schema |
| 847 | |
| 848 | const [baseDirectory, |
| 849 | this.openCache(base |
| 850 | this.openCache(head |
| 851 | ]); |
| 852 | const alternates = |
| 853 | |
| 854 | const baseSha = |
| 855 | baseDirectory, |
| 856 | pullRequest.baseRef, |
| 857 | ); |
| 858 | const headSha = |
| 859 | headDirectory, |
| 860 | pullRequest.headRef, |
| 861 | ); |
| 862 | |
| 863 | return { |
| 864 | pullRequest, |
| 865 | base, |
| 866 | head, |
| 867 | baseDirectory, |
| 868 | headDirectory, |
| 869 | alternates, |
| 870 | env: alternates.length |
| 871 | ? { |
| 872 | GIT_ALTERNATE_OBJECT_DIRECTORIES: path.join |
| 873 | headDirectory, |
| 874 | 'objects', |
| 875 | ), |
| 876 | } |
| 877 | : undefined, |
| 878 | baseSha, |
| 879 | headSha, |
| 880 | mergeBase: await mergeBase |
| 881 | gitDir: baseDirectory, |
| 882 | alternates, |
| 883 | a: baseSha, |
| 884 | b: headSha, |
| 885 | }), |
| 886 | headDeleted: false, |
| 887 | }; |
| 888 | } |
| 889 | |
| 890 | async load({ |
| 891 | username, |
| 892 | repo, |
| 893 | number, |
| 894 | requesterId, |
| 895 | operation, |
| 896 | }: PullRequestRef |
| 897 | const base = |
| 898 | username, |
| 899 | repo, |
| 900 | requesterId, |
| 901 | operation, |
| 902 | }); |
| 903 | const [pullRequest] |
| 904 | .select(pullRequestColumns) |
| 905 | .from(schema.pullRequest |
| 906 | .innerJoin(schema.issue |
| 907 | .where( |
| 908 | and( |
| 909 | eq(schema.issue |
| 910 | eq(schema.issue |
| 911 | ), |
| 912 | ); |
| 913 | if (!pullRequest) |
| 914 | |
| 915 | return { pullRequest, |
| 916 | } |
| 917 | |
| 918 | private authorize({ |
| 919 | username, |
| 920 | repo, |
| 921 | requesterId, |
| 922 | operation = 'read' |
| 923 | }: { |
| 924 | username: string |
| 925 | repo: string |
| 926 | requesterId?: string |
| 927 | operation?: RepositoryOperation |
| 928 | }) { |
| 929 | return this.access |
| 930 | username, |
| 931 | repo, |
| 932 | actor: requesterId ? |
| 933 | operation, |
| 934 | }); |
| 935 | } |
| 936 | |
| 937 | private async openCache |
| 938 | const directory = |
| 939 | await this.materializer |
| 940 | repository.id, |
| 941 | directory, |
| 942 | repository.defaultBranch, |
| 943 | ); |
| 944 | return directory; |
| 945 | } |
| 946 | |
| 947 | private async resolveBranch |
| 948 | const sha = |
| 949 | args: [ |
| 950 | 'rev-parse', |
| 951 | '--verify', |
| 952 | '--end-of-options', |
| 953 | `refs/heads/${branch}`, |
| 954 | ], |
| 955 | gitDir, |
| 956 | }).catch(() |
| 957 | |
| 958 | if (!sha.trim |
| 959 | return sha.trim |
| 960 | } |
| 961 | |
| 962 | private async countRange |
| 963 | { |
| 964 | baseDirectory, |
| 965 | env, |
| 966 | }: { baseDirectory |
| 967 | range: string, |
| 968 | ) { |
| 969 | const raw = |
| 970 | args: ['rev-list', |
| 971 | gitDir: baseDirectory, |
| 972 | env, |
| 973 | }); |
| 974 | return Number(raw |
| 975 | } |
| 976 | |
| 977 | /** `owner:branch` names a branch on another repository in the same fork network - the base itself, a fork of it, or the repository the base was forked from. Anything else is not a pull request, it is two unrelated repos. */ |
| 978 | private async resolveHead |
| 979 | base: Repository |
| 980 | head: string, |
| 981 | requesterId: string, |
| 982 | ) { |
| 983 | if (!head.includes |
| 984 | |
| 985 | const owner = |
| 986 | const candidates = |
| 987 | .select(getTableColumns(schema |
| 988 | .from(schema.repository |
| 989 | .innerJoin(schema.user |
| 990 | .leftJoin( |
| 991 | schema.organization, |
| 992 | eq(schema.organization |
| 993 | ) |
| 994 | .where(eq(ownerNameOf |
| 995 | |
| 996 | const related = |
| 997 | (candidate) => |
| 998 | candidate.id === |
| 999 | candidate.parentRepositoryId === |
| 1000 | candidate.id === |
| 1001 | ); |
| 1002 | if (!related) |
| 1003 | |
| 1004 | return this.access |
| 1005 | username: owner, |
| 1006 | repo: related.slug |
| 1007 | actor: { userId: requesterId |
| 1008 | operation: 'read', |
| 1009 | }); |
| 1010 | } |
| 1011 | |
| 1012 | private async expandPullRequest |
| 1013 | const sides = |
| 1014 | .select({ |
| 1015 | repositoryId: schema.repository |
| 1016 | slug: schema.repository |
| 1017 | username: ownerNameOf(schema |
| 1018 | }) |
| 1019 | .from(schema.repository |
| 1020 | .innerJoin(schema.user |
| 1021 | .leftJoin( |
| 1022 | schema.organization, |
| 1023 | eq(schema.organization |
| 1024 | ) |
| 1025 | .where( |
| 1026 | inArray(schema.repository |
| 1027 | pullRequest.baseRepositoryId, |
| 1028 | pullRequest.headRepositoryId ?? |
| 1029 | ]), |
| 1030 | ); |
| 1031 | |
| 1032 | const author = |
| 1033 | // A deleted head repository has no row, and reads as null rather than as some other repository. |
| 1034 | const sideOf = |
| 1035 | const row = |
| 1036 | return { username: |
| 1037 | }; |
| 1038 | |
| 1039 | return { |
| 1040 | id: pullRequest.id |
| 1041 | number: pullRequest.number |
| 1042 | title: pullRequest.title |
| 1043 | body: pullRequest.body |
| 1044 | state: pullRequest.state |
| 1045 | draft: pullRequest.draft |
| 1046 | base: sideOf(pullRequest |
| 1047 | head: sideOf(pullRequest |
| 1048 | headSha: pullRequest.headSha |
| 1049 | mergeCommitSha: pullRequest.mergeCommitSha |
| 1050 | authorUsername: author.username |
| 1051 | authorImage: author.image |
| 1052 | createdAt: pullRequest.createdAt |
| 1053 | updatedAt: pullRequest.updatedAt |
| 1054 | }; |
| 1055 | } |
| 1056 | } |
| 1057 | |
| 1058 | type LiveComparison |
| 1059 | |
| 1060 | interface CompareParams { |
| 1061 | username: string; |
| 1062 | repo: string; |
| 1063 | requesterId: string; |
| 1064 | base: string; |
| 1065 | head: string; |
| 1066 | } |
| 1067 | |
| 1068 | export interface PullRequestRef |
| 1069 | username: string; |
| 1070 | repo: string; |
| 1071 | number: number; |
| 1072 | requesterId?: string |
| 1073 | operation?: RepositoryOperation |
| 1074 | } |