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