| 1 | import { Inject, Injectable, Logger } from '@nestjs/common'; |
| 2 | import { type Database, |
| 3 | import { |
| 4 | and, |
| 5 | asc, |
| 6 | count, |
| 7 | desc, |
| 8 | eq, |
| 9 | getTableColumns, |
| 10 | ilike, |
| 11 | inArray, |
| 12 | isNotNull, |
| 13 | isNull, |
| 14 | lt, |
| 15 | ne, |
| 16 | or, |
| 17 | sql, |
| 18 | } from 'drizzle-orm'; |
| 19 | import { alias, type |
| 20 | |
| 21 | import { DATABASE } |
| 22 | import { publishEvent } |
| 23 | import { CreateRepositoryRequestDTO } |
| 24 | import { GetRepositoriesQueryDTO } |
| 25 | import { UpdateRepositoryRequestDTO } |
| 26 | import { UsersService } |
| 27 | import { |
| 28 | BlobNotFoundError, |
| 29 | BranchNotFoundError, |
| 30 | CannotForkOwnRepositoryError, |
| 31 | CommitNotFoundError, |
| 32 | InvalidCursorError, |
| 33 | RepositoryAlreadyForkedError, |
| 34 | RepositoryHeadsOpenPullRequestError, |
| 35 | RepositoryNameTakenError, |
| 36 | TransferNotFoundError, |
| 37 | TransferTargetError, |
| 38 | } from './repositories.errors.js'; |
| 39 | import { closeIssue } |
| 40 | import { ownerQualifier } |
| 41 | import { organizationToCreateIn } |
| 42 | import { PrivateForkingDisabledError } |
| 43 | import { |
| 44 | decodeCursor, |
| 45 | encodeCursor, |
| 46 | escapeLike, |
| 47 | isoTimestamp, |
| 48 | titleToSlug, |
| 49 | } from '../../utils/index.js'; |
| 50 | import { RepositoryStorageService } |
| 51 | import { RepositoryMaterializerService } |
| 52 | import { RepositoryPathIndexService } |
| 53 | import { RepositoryLanguageService } |
| 54 | import { runGit } |
| 55 | import { |
| 56 | type CommitVerification, |
| 57 | CommitVerificationService, |
| 58 | } from '../../services/gpg/commit-verification.service.js'; |
| 59 | import { listTree } |
| 60 | import { listTags } |
| 61 | import { |
| 62 | isSha, |
| 63 | listCommits, |
| 64 | readCommit, |
| 65 | readCommitSummary, |
| 66 | } from '../../lib/git/commits/list-commits.js'; |
| 67 | import { |
| 68 | isTextBlob, |
| 69 | readBlob, |
| 70 | statBlob, |
| 71 | streamBlob, |
| 72 | } from '../../lib/git/blob/read-blob.js'; |
| 73 | import { findReadmePath } |
| 74 | import { mediaTypeFor } |
| 75 | import { |
| 76 | normalizeBlobPath, |
| 77 | normalizeTreePath, |
| 78 | } from '../../lib/git/tree/tree-path.js'; |
| 79 | import { |
| 80 | resolveDefaultRef, |
| 81 | resolveRevision, |
| 82 | } from '../../lib/git/tree/resolve-ref.js'; |
| 83 | import type { PathCommit |
| 84 | import type { |
| 85 | CommitSummaryDTO, |
| 86 | GetRepositoryContentsResponseDTO, |
| 87 | } from './dto/get-repository-contents.dto.js'; |
| 88 | import type { GetRepositoryBranchesResponseDTO |
| 89 | import type { |
| 90 | GetRepositoryTagsQueryDTO, |
| 91 | GetRepositoryTagsResponseDTO, |
| 92 | } from './dto/get-repository-tags.dto.js'; |
| 93 | import type { GetRepositoryLanguagesResponseDTO |
| 94 | import type { |
| 95 | GetRepositoryForksQueryDTO, |
| 96 | GetRepositoryForksResponseDTO, |
| 97 | } from './dto/get-repository-forks.dto.js'; |
| 98 | import type { |
| 99 | GetRepositoryContributorsQueryDTO, |
| 100 | GetRepositoryContributorsResponseDTO, |
| 101 | } from './dto/get-repository-contributors.dto.js'; |
| 102 | import type { |
| 103 | GetRepositoryStargazersQueryDTO, |
| 104 | GetRepositoryStargazersResponseDTO, |
| 105 | } from './dto/get-repository-stargazers.dto.js'; |
| 106 | import type { GetRepositoryBlobResponseDTO |
| 107 | import type { GetRepositoryReadmeResponseDTO |
| 108 | import type { |
| 109 | CommitDTO, |
| 110 | GetRepositoryCommitResponseDTO, |
| 111 | GetRepositoryCommitsQueryDTO, |
| 112 | GetRepositoryCommitsResponseDTO, |
| 113 | } from './dto/get-repository-commits.dto.js'; |
| 114 | import { BranchesService } |
| 115 | import { RepositoryContributionService } |
| 116 | import { RepositoryAccessService } |
| 117 | import { |
| 118 | acceptedCollaboration, |
| 119 | type Actor, |
| 120 | basePermissionOf, |
| 121 | grantedTo, |
| 122 | organizationMembership, |
| 123 | ownerNameOf, |
| 124 | readableBy, |
| 125 | type Repository, |
| 126 | type RepositoryOperation, |
| 127 | roleOf, |
| 128 | teamRoleOf, |
| 129 | } from '../../lib/git/repository-access/repository-access.js'; |
| 130 | import { administers, atLeast |
| 131 | import { RepositoryForbiddenError } |
| 132 | import { WalStoreService } |
| 133 | import { CodeSearchService } |
| 134 | import { S3Service } |
| 135 | import { releaseAssetKey } |
| 136 | import type { |
| 137 | SearchCodeResponseDTO, |
| 138 | SearchRepositoryCodeResponseDTO, |
| 139 | } from './dto/search-code.dto.js'; |
| 140 | import type { SearchRepositoriesResponseDTO |
| 141 | import type { GetViewerRepositoriesResponseDTO |
| 142 | |
| 143 | // `/owner/settings` and `/org/teams` are pages of the owner's own, so no repository may live there. |
| 144 | const RESERVED_REPOSITORY_SLUGS = new |
| 145 | const DEFAULT_PAGE_SIZE = 20 |
| 146 | const MAX_PAGE_SIZE = 100 |
| 147 | const MIN_LANGUAGE_PERCENT = 0.5 |
| 148 | const DEFAULT_SEARCH_LIMIT = 50 |
| 149 | |
| 150 | @Injectable() |
| 151 | export class RepositoriesService |
| 152 | private readonly logger |
| 153 | |
| 154 | constructor( |
| 155 | @Inject(DATABASE) |
| 156 | private readonly usersService |
| 157 | private readonly storage |
| 158 | private readonly materializer |
| 159 | private readonly pathIndex |
| 160 | private readonly languages |
| 161 | private readonly branches |
| 162 | private readonly access |
| 163 | private readonly wal |
| 164 | private readonly contributions |
| 165 | private readonly verification |
| 166 | private readonly codeSearch |
| 167 | private readonly s3 |
| 168 | ) {} |
| 169 | |
| 170 | async createRepository(body |
| 171 | const visibility = |
| 172 | const organization = |
| 173 | ? await organizationToCreateIn( |
| 174 | this.db, |
| 175 | body.organization, |
| 176 | userId, |
| 177 | visibility, |
| 178 | ) |
| 179 | : null; |
| 180 | const namespace: |
| 181 | |
| 182 | const [newRepo] |
| 183 | .insert(schema.repository |
| 184 | .values({ |
| 185 | name: body.name |
| 186 | // The creator, even of an organization's repository, which the organization owns. |
| 187 | ownerId: userId, |
| 188 | organizationId: organizationIdOf(namespace |
| 189 | slug: await this |
| 190 | description: body.description |
| 191 | visibility, |
| 192 | defaultBranch: organization?.settings |
| 193 | }) |
| 194 | .returning(); |
| 195 | |
| 196 | return { |
| 197 | id: newRepo.id |
| 198 | slug: newRepo.slug |
| 199 | }; |
| 200 | } |
| 201 | |
| 202 | async getRepositories( |
| 203 | username: string, |
| 204 | requesterId?: string |
| 205 | query: GetRepositoriesQueryDTO |
| 206 | ) { |
| 207 | const namespace = |
| 208 | |
| 209 | const { pageSize, |
| 210 | query, |
| 211 | schema.repository.lastPushedAt |
| 212 | schema.repository.id |
| 213 | ); |
| 214 | |
| 215 | const rows = |
| 216 | .select(getTableColumns(schema |
| 217 | .from(schema.repository |
| 218 | .leftJoin( |
| 219 | schema.repositoryCollaborator, |
| 220 | acceptedCollaboration(schema.repository |
| 221 | ) |
| 222 | .leftJoin( |
| 223 | schema.member, |
| 224 | organizationMembership( |
| 225 | schema.repository.organizationId |
| 226 | actorOf(requesterId), |
| 227 | ), |
| 228 | ) |
| 229 | .where( |
| 230 | and( |
| 231 | inNamespace(namespace), |
| 232 | readableBy(actorOf(requesterId |
| 233 | matching(query.q |
| 234 | after, |
| 235 | ), |
| 236 | ) |
| 237 | .orderBy(desc(schema |
| 238 | .limit(pageSize + |
| 239 | |
| 240 | const { page, |
| 241 | date: row.lastPushedAt |
| 242 | id: row.id |
| 243 | })); |
| 244 | |
| 245 | return { repositories: |
| 246 | } |
| 247 | |
| 248 | /** Repositories the requester owns, collaborates on, or can reach through an organization, most recently pushed first. */ |
| 249 | async getViewerRepositories( |
| 250 | requesterId: string, |
| 251 | query: GetRepositoriesQueryDTO |
| 252 | ): Promise<GetViewerRepositoriesResponseDTO |
| 253 | const search = |
| 254 | const { pageSize, |
| 255 | query, |
| 256 | schema.repository.lastPushedAt |
| 257 | schema.repository.id |
| 258 | ); |
| 259 | |
| 260 | const rows = |
| 261 | .select({ |
| 262 | id: schema.repository |
| 263 | owner: ownerNameOf(schema |
| 264 | name: schema.repository |
| 265 | slug: schema.repository |
| 266 | description: schema.repository |
| 267 | visibility: schema.repository |
| 268 | lastPushedAt: schema.repository |
| 269 | ownerId: schema.repository |
| 270 | organizationId: schema.repository |
| 271 | collaboratorRole: schema.repositoryCollaborator |
| 272 | memberRole: schema.member |
| 273 | teamRole: teamRoleOf(schema |
| 274 | basePermission: basePermissionOf(schema |
| 275 | }) |
| 276 | .from(schema.repository |
| 277 | .innerJoin(schema.user |
| 278 | .leftJoin( |
| 279 | schema.organization, |
| 280 | eq(schema.organization |
| 281 | ) |
| 282 | .leftJoin( |
| 283 | schema.repositoryCollaborator, |
| 284 | acceptedCollaboration(schema.repository |
| 285 | ) |
| 286 | .leftJoin( |
| 287 | schema.member, |
| 288 | organizationMembership( |
| 289 | schema.repository.organizationId |
| 290 | actorOf(requesterId), |
| 291 | ), |
| 292 | ) |
| 293 | .where( |
| 294 | and( |
| 295 | grantedTo(actorOf(requesterId |
| 296 | isNotNull(ownerNameOf(schema |
| 297 | matching(search.rest |
| 298 | search.owner |
| 299 | ? eq(ownerNameOf( |
| 300 | : undefined, |
| 301 | after, |
| 302 | ), |
| 303 | ) |
| 304 | .orderBy(desc(schema |
| 305 | .limit(pageSize + |
| 306 | |
| 307 | const { page, |
| 308 | date: row.lastPushedAt |
| 309 | id: row.id |
| 310 | })); |
| 311 | |
| 312 | return { |
| 313 | repositories: page.map |
| 314 | ({ |
| 315 | ownerId, |
| 316 | organizationId, |
| 317 | collaboratorRole, |
| 318 | memberRole, |
| 319 | teamRole, |
| 320 | basePermission, |
| 321 | ...row |
| 322 | }) => ({ |
| 323 | ...row, |
| 324 | // Every row passed the filter above, so the requester holds some role on it. |
| 325 | viewerRole: roleOf( |
| 326 | { ownerId, organizationId |
| 327 | { collaboratorRole, memberRole |
| 328 | actorOf(requesterId), |
| 329 | )!, |
| 330 | }), |
| 331 | ), |
| 332 | nextCursor, |
| 333 | hasMore, |
| 334 | }; |
| 335 | } |
| 336 | |
| 337 | /** Public repositories across every owner, most recently pushed first. */ |
| 338 | async searchRepositories( |
| 339 | query: GetRepositoriesQueryDTO |
| 340 | ): Promise<SearchRepositoriesResponseDTO |
| 341 | const search = |
| 342 | const { pageSize, |
| 343 | query, |
| 344 | schema.repository.lastPushedAt |
| 345 | schema.repository.id |
| 346 | ); |
| 347 | |
| 348 | const rows = |
| 349 | .select({ |
| 350 | id: schema.repository |
| 351 | owner: ownerNameOf(schema |
| 352 | name: schema.repository |
| 353 | slug: schema.repository |
| 354 | description: schema.repository |
| 355 | lastPushedAt: schema.repository |
| 356 | }) |
| 357 | .from(schema.repository |
| 358 | .innerJoin(schema.user |
| 359 | .leftJoin( |
| 360 | schema.organization, |
| 361 | eq(schema.organization |
| 362 | ) |
| 363 | .where( |
| 364 | and( |
| 365 | eq(schema.repository |
| 366 | // an owner without a username has no page to link the repository under |
| 367 | isNotNull(ownerNameOf(schema |
| 368 | matching(search.rest |
| 369 | search.owner |
| 370 | ? eq(ownerNameOf( |
| 371 | : undefined, |
| 372 | after, |
| 373 | ), |
| 374 | ) |
| 375 | .orderBy(desc(schema |
| 376 | .limit(pageSize + |
| 377 | |
| 378 | const { page, |
| 379 | date: row.lastPushedAt |
| 380 | id: row.id |
| 381 | })); |
| 382 | |
| 383 | return { repositories: |
| 384 | } |
| 385 | |
| 386 | /** Code in public repositories, limited to those opened or pushed to since code search was switched on. */ |
| 387 | async searchCode({ |
| 388 | query, |
| 389 | limit = DEFAULT_SEARCH_LIMIT, |
| 390 | }: { |
| 391 | query: string |
| 392 | limit?: number |
| 393 | }): Promise |
| 394 | const { owner, |
| 395 | if (!rest) |
| 396 | // `org:` names public repositories to scan; one that owns none matches nothing. |
| 397 | const scoped = |
| 398 | ? await this. |
| 399 | .select({ id: |
| 400 | .from(schema.repository |
| 401 | .innerJoin(schema.user |
| 402 | .leftJoin( |
| 403 | schema.organization, |
| 404 | eq(schema.organization |
| 405 | ) |
| 406 | .where( |
| 407 | and( |
| 408 | eq(ownerNameOf(schema |
| 409 | eq(schema.repository |
| 410 | ), |
| 411 | ) |
| 412 | : null; |
| 413 | if (scoped?.length |
| 414 | |
| 415 | const hits = |
| 416 | query: rest, |
| 417 | limit, |
| 418 | repositoryIds: scoped?.map |
| 419 | }); |
| 420 | const ids = |
| 421 | if (ids.length |
| 422 | |
| 423 | // The index only narrows to shards flagged public; the database is what decides. |
| 424 | const repositories = |
| 425 | .select({ |
| 426 | id: schema.repository |
| 427 | owner: ownerNameOf(schema |
| 428 | name: schema.repository |
| 429 | slug: schema.repository |
| 430 | }) |
| 431 | .from(schema.repository |
| 432 | .innerJoin(schema.user |
| 433 | .leftJoin( |
| 434 | schema.organization, |
| 435 | eq(schema.organization |
| 436 | ) |
| 437 | .where( |
| 438 | and( |
| 439 | inArray(schema.repository |
| 440 | eq(schema.repository |
| 441 | isNotNull(ownerNameOf(schema |
| 442 | ), |
| 443 | ); |
| 444 | const byId = |
| 445 | |
| 446 | return { |
| 447 | files: hits.flatMap |
| 448 | const repository = |
| 449 | return repository ? |
| 450 | }), |
| 451 | }; |
| 452 | } |
| 453 | |
| 454 | async getRepository({ |
| 455 | username, |
| 456 | slug, |
| 457 | requesterId, |
| 458 | }: { |
| 459 | username: string |
| 460 | slug: string |
| 461 | requesterId?: string |
| 462 | }) { |
| 463 | const repository = |
| 464 | username, |
| 465 | slug, |
| 466 | requesterId, |
| 467 | }); |
| 468 | const [stars, |
| 469 | this.readStars(repository |
| 470 | |
| 471 | this.db |
| 472 | .select({ |
| 473 | forkCount: count(), |
| 474 | // the viewer's own fork, so the UI can send them there instead of offering another |
| 475 | viewerForkSlug: requesterId |
| 476 | ? sql< |
| 477 | string | null |
| 478 | >`max(${schema.repository |
| 479 | : sql<string |
| 480 | }) |
| 481 | .from(schema.repository |
| 482 | .where(eq(schema |
| 483 | |
| 484 | repository.parentRepositoryId |
| 485 | ? this.db |
| 486 | .select({ |
| 487 | username: ownerNameOf(schema |
| 488 | slug: schema.repository |
| 489 | name: schema.repository |
| 490 | }) |
| 491 | .from(schema.repository |
| 492 | .innerJoin( |
| 493 | schema.user, |
| 494 | eq(schema.user |
| 495 | ) |
| 496 | .leftJoin( |
| 497 | schema.organization, |
| 498 | eq(schema.organization |
| 499 | ) |
| 500 | .where(eq(schema |
| 501 | : [], |
| 502 | ]); |
| 503 | |
| 504 | return { |
| 505 | ...repository, |
| 506 | // Where it lives now, which differs from the requested name after a rename or transfer. |
| 507 | owner: await this |
| 508 | ...stars, |
| 509 | forkCount: forks[0] |
| 510 | viewerForkSlug: forks[0] |
| 511 | parent: parent[0] |
| 512 | ? { ...parent |
| 513 | : null, |
| 514 | }; |
| 515 | } |
| 516 | |
| 517 | async forkRepository({ |
| 518 | username, |
| 519 | slug, |
| 520 | requesterId, |
| 521 | name, |
| 522 | description, |
| 523 | visibility, |
| 524 | organization, |
| 525 | }: { |
| 526 | username: string |
| 527 | slug: string |
| 528 | requesterId: string |
| 529 | name: string |
| 530 | description?: string |
| 531 | visibility: 'public |
| 532 | organization?: string |
| 533 | }) { |
| 534 | const parent = |
| 535 | if (parent.organizationId |
| 536 | const [policy] |
| 537 | .select({ allowed: |
| 538 | .from(schema.organizationSettings |
| 539 | .where( |
| 540 | eq(schema.organizationSettings |
| 541 | ); |
| 542 | if (!policy?.allowed |
| 543 | } |
| 544 | const namespace: |
| 545 | ? await organizationToCreateIn( |
| 546 | this.db, |
| 547 | organization, |
| 548 | requesterId, |
| 549 | visibility, |
| 550 | ) |
| 551 | : { userId: requesterId |
| 552 | if (sameNamespace(namespaceOf |
| 553 | throw new CannotForkOwnRepositoryError() |
| 554 | |
| 555 | // One fork per namespace, so a second press sends the forker to the one they have. |
| 556 | const [existing] |
| 557 | .select({ slug: |
| 558 | .from(schema.repository |
| 559 | .where( |
| 560 | and( |
| 561 | inNamespace(namespace), |
| 562 | eq(schema.repository |
| 563 | ), |
| 564 | ); |
| 565 | if (existing) throw |
| 566 | |
| 567 | const forkSlug = |
| 568 | const fork = |
| 569 | const [row] |
| 570 | .insert(schema.repository |
| 571 | .values({ |
| 572 | name, |
| 573 | description, |
| 574 | visibility, |
| 575 | slug: forkSlug, |
| 576 | ownerId: requesterId, |
| 577 | organizationId: organizationIdOf(namespace |
| 578 | parentRepositoryId: parent.id |
| 579 | }) |
| 580 | .returning(); |
| 581 | await publishEvent(tx |
| 582 | type: 'fork.created', |
| 583 | repositoryId: parent.id |
| 584 | actorId: requesterId, |
| 585 | payload: { forkId: row |
| 586 | }); |
| 587 | return row; |
| 588 | }); |
| 589 | |
| 590 | await this.wal |
| 591 | |
| 592 | return { |
| 593 | id: fork.id |
| 594 | slug: fork.slug |
| 595 | username: |
| 596 | organization ?? |
| 597 | (await this.usersService |
| 598 | '', |
| 599 | }; |
| 600 | } |
| 601 | |
| 602 | /** Moves a repository, which only its owner may: the user who owns it, or an owner of its organization. A move to the requester's own account or to an organization they administer happens at once; any other recipient accepts it first. */ |
| 603 | async transferRepository({ |
| 604 | username, |
| 605 | slug, |
| 606 | requesterId, |
| 607 | owner, |
| 608 | }: { |
| 609 | username: string |
| 610 | slug: string |
| 611 | requesterId: string |
| 612 | owner: string |
| 613 | }) { |
| 614 | const repository = |
| 615 | username, |
| 616 | slug, |
| 617 | requesterId, |
| 618 | }); |
| 619 | if (!atLeast(repository |
| 620 | throw new RepositoryForbiddenError() |
| 621 | } |
| 622 | |
| 623 | const target = |
| 624 | if (sameNamespace(namespaceOf |
| 625 | throw new TransferTargetError() |
| 626 | } |
| 627 | await this.assertSlugFree |
| 628 | |
| 629 | if (await this |
| 630 | await this.move |
| 631 | return { |
| 632 | id: repository.id |
| 633 | slug: repository.slug |
| 634 | username: owner, |
| 635 | pending: false, |
| 636 | }; |
| 637 | } |
| 638 | |
| 639 | await this.db |
| 640 | .insert(schema.repositoryTransfer |
| 641 | .values({ |
| 642 | repositoryId: repository.id |
| 643 | toUserId: 'userId' in |
| 644 | toOrganizationId: organizationIdOf(target |
| 645 | requestedById: requesterId, |
| 646 | }) |
| 647 | .onConflictDoUpdate({ |
| 648 | target: schema.repositoryTransfer |
| 649 | set: { |
| 650 | toUserId: 'userId' in |
| 651 | toOrganizationId: organizationIdOf(target |
| 652 | requestedById: requesterId, |
| 653 | createdAt: new Date |
| 654 | }, |
| 655 | }); |
| 656 | return { |
| 657 | id: repository.id |
| 658 | slug: repository.slug |
| 659 | username: await this |
| 660 | pending: true, |
| 661 | }; |
| 662 | } |
| 663 | |
| 664 | /** Transfers waiting for the requester: to their own account, or to an organization they administer. */ |
| 665 | async listIncomingTransfers(requesterId |
| 666 | const destination = |
| 667 | const requester = |
| 668 | const recipient = |
| 669 | const transfers = |
| 670 | .select({ |
| 671 | repositoryId: schema.repository |
| 672 | repository: { |
| 673 | owner: ownerNameOf(schema |
| 674 | slug: schema.repository |
| 675 | name: schema.repository |
| 676 | }, |
| 677 | to: ownerNameOf(recipient |
| 678 | requestedByUsername: requester.username |
| 679 | createdAt: isoTimestamp(schema |
| 680 | }) |
| 681 | .from(schema.repositoryTransfer |
| 682 | .innerJoin( |
| 683 | schema.repository, |
| 684 | eq(schema.repository |
| 685 | ) |
| 686 | .innerJoin(schema.user |
| 687 | .leftJoin( |
| 688 | schema.organization, |
| 689 | eq(schema.organization |
| 690 | ) |
| 691 | .leftJoin( |
| 692 | destination, |
| 693 | eq(destination.id |
| 694 | ) |
| 695 | .leftJoin( |
| 696 | requester, |
| 697 | eq(requester.id |
| 698 | ) |
| 699 | .leftJoin(recipient, |
| 700 | .leftJoin( |
| 701 | schema.member, |
| 702 | and( |
| 703 | eq( |
| 704 | schema.member.organizationId |
| 705 | schema.repositoryTransfer.toOrganizationId |
| 706 | ), |
| 707 | eq(schema.member |
| 708 | ), |
| 709 | ) |
| 710 | .where( |
| 711 | or( |
| 712 | eq(schema.repositoryTransfer |
| 713 | inArray(schema.member |
| 714 | ), |
| 715 | ) |
| 716 | .orderBy(asc(schema |
| 717 | |
| 718 | return { transfers |
| 719 | } |
| 720 | |
| 721 | async acceptTransfer(repositoryId |
| 722 | const transfer = |
| 723 | const [repository] |
| 724 | .select() |
| 725 | .from(schema.repository |
| 726 | .where(eq(schema |
| 727 | const target: |
| 728 | ? { organizationId: transfer |
| 729 | : { userId: requesterId |
| 730 | await this.assertSlugFree |
| 731 | target, |
| 732 | await this.namespaceName |
| 733 | repository.slug, |
| 734 | ); |
| 735 | await this.move |
| 736 | return { |
| 737 | id: repository.id |
| 738 | slug: repository.slug |
| 739 | username: await this |
| 740 | }; |
| 741 | } |
| 742 | |
| 743 | /** The recipient declines, or whoever asked for it withdraws it. */ |
| 744 | async cancelTransfer(repositoryId |
| 745 | const [transfer] |
| 746 | .select() |
| 747 | .from(schema.repositoryTransfer |
| 748 | .where(eq(schema |
| 749 | if (!transfer) |
| 750 | if (transfer.requestedById |
| 751 | await this.incomingTransfer |
| 752 | } |
| 753 | await this.db |
| 754 | .delete(schema.repositoryTransfer |
| 755 | .where(eq(schema |
| 756 | } |
| 757 | |
| 758 | /** A pending transfer addressed to the requester, or to an organization they administer. */ |
| 759 | private async incomingTransfer |
| 760 | const [transfer] |
| 761 | .select() |
| 762 | .from(schema.repositoryTransfer |
| 763 | .where(eq(schema |
| 764 | if (!transfer) |
| 765 | const recipient = |
| 766 | ? await this. |
| 767 | { organizationId: transfer. |
| 768 | requesterId, |
| 769 | ) |
| 770 | : transfer.toUserId |
| 771 | if (!recipient) |
| 772 | return transfer; |
| 773 | } |
| 774 | |
| 775 | /** Whether the requester may put a repository in `namespace` without anyone else agreeing: it is theirs, or an organization they administer. */ |
| 776 | private async holds |
| 777 | if ('userId' in |
| 778 | const [membership] |
| 779 | .select({ role: |
| 780 | .from(schema.member |
| 781 | .where( |
| 782 | and( |
| 783 | eq(schema.member |
| 784 | eq(schema.member |
| 785 | ), |
| 786 | ); |
| 787 | return administers(organizationRoleOf |
| 788 | } |
| 789 | |
| 790 | private async assertSlugFree |
| 791 | namespace: Namespace |
| 792 | owner: string, |
| 793 | slug: string, |
| 794 | ) { |
| 795 | const [clash] |
| 796 | .select({ id: |
| 797 | .from(schema.repository |
| 798 | .where(and(inNamespace |
| 799 | if (clash) throw |
| 800 | } |
| 801 | |
| 802 | /** Puts the repository in `namespace`, leaving a redirect at its old name and settling any pending transfer. */ |
| 803 | private async move |
| 804 | repository: Repository |
| 805 | namespace: Namespace |
| 806 | actorId: string, |
| 807 | ) { |
| 808 | const previous = |
| 809 | await this.db |
| 810 | await tx |
| 811 | .update(schema.repository |
| 812 | .set({ |
| 813 | ownerId: |
| 814 | 'userId' in namespace |
| 815 | organizationId: organizationIdOf(namespace |
| 816 | }) |
| 817 | .where(eq(schema |
| 818 | // The new owner holds everything already; a collaborator row would only linger. |
| 819 | if ('userId' in |
| 820 | await tx |
| 821 | .delete(schema.repositoryCollaborator |
| 822 | .where( |
| 823 | and( |
| 824 | eq(schema.repositoryCollaborator |
| 825 | eq(schema.repositoryCollaborator |
| 826 | ), |
| 827 | ); |
| 828 | } |
| 829 | await tx |
| 830 | .delete(schema.repositoryTransfer |
| 831 | .where(eq(schema |
| 832 | await this.leaveRedirect |
| 833 | await publishEvent(tx |
| 834 | type: 'repository.transferred', |
| 835 | repositoryId: repository.id |
| 836 | actorId, |
| 837 | payload: { from: previous |
| 838 | }); |
| 839 | }); |
| 840 | } |
| 841 | |
| 842 | /** The newest move wins an old name: a redirect left there by another repository is replaced. */ |
| 843 | private async leaveRedirect |
| 844 | tx: Pick |
| 845 | ownerName: string, |
| 846 | slug: string, |
| 847 | repositoryId: string, |
| 848 | ) { |
| 849 | await tx |
| 850 | .delete(schema.repositoryRedirect |
| 851 | .where( |
| 852 | and( |
| 853 | eq( |
| 854 | sql`lower(${schema. |
| 855 | ownerName.toLowerCase(), |
| 856 | ), |
| 857 | eq(schema.repositoryRedirect |
| 858 | ), |
| 859 | ); |
| 860 | await tx |
| 861 | .insert(schema.repositoryRedirect |
| 862 | .values({ ownerName |
| 863 | } |
| 864 | |
| 865 | private async ownerNameOf |
| 866 | const [row] |
| 867 | .select({ owner: |
| 868 | .from(schema.repository |
| 869 | .innerJoin(schema.user |
| 870 | .leftJoin( |
| 871 | schema.organization, |
| 872 | eq(schema.organization |
| 873 | ) |
| 874 | .where(eq(schema |
| 875 | return row?.owner |
| 876 | } |
| 877 | |
| 878 | private async namespaceName |
| 879 | if ('userId' in |
| 880 | return ( |
| 881 | (await this.usersService |
| 882 | ); |
| 883 | } |
| 884 | const [organization] |
| 885 | .select({ slug: |
| 886 | .from(schema.organization |
| 887 | .where(eq(schema |
| 888 | return organization?.slug |
| 889 | } |
| 890 | |
| 891 | async updateRepository({ |
| 892 | username, |
| 893 | slug, |
| 894 | requesterId, |
| 895 | changes: { name |
| 896 | }: { |
| 897 | username: string |
| 898 | slug: string |
| 899 | requesterId: string |
| 900 | changes: UpdateRepositoryRequestDTO |
| 901 | }) { |
| 902 | const repository = |
| 903 | username, |
| 904 | slug, |
| 905 | requesterId, |
| 906 | }); |
| 907 | // Visibility decides who can see the code at all, which is an admin's call. |
| 908 | if ( |
| 909 | visibility !== undefined && |
| 910 | visibility !== repository. |
| 911 | !atLeast(repository.viewerRole |
| 912 | ) { |
| 913 | throw new RepositoryForbiddenError() |
| 914 | } |
| 915 | |
| 916 | if (defaultBranch !== |
| 917 | const stored = |
| 918 | if (!stored?.index |
| 919 | throw new BranchNotFoundError( |
| 920 | } |
| 921 | |
| 922 | // A form resends the name on every save; recomputing it could hand a suffixed slug a new suffix. |
| 923 | const newSlug = |
| 924 | name === undefined || |
| 925 | ? undefined |
| 926 | : await this. |
| 927 | const updated = |
| 928 | const [row] |
| 929 | .update(schema.repository |
| 930 | .set({ name |
| 931 | .where(eq(schema |
| 932 | .returning(); |
| 933 | if (row.slug |
| 934 | await this.leaveRedirect |
| 935 | tx, |
| 936 | await this.ownerNameOf |
| 937 | repository.slug, |
| 938 | repository.id, |
| 939 | ); |
| 940 | } |
| 941 | if ( |
| 942 | row.name !== |
| 943 | row.description !== |
| 944 | row.visibility !== |
| 945 | row.defaultBranch !== |
| 946 | ) { |
| 947 | await publishEvent(tx |
| 948 | type: 'repository.edited', |
| 949 | repositoryId: repository.id |
| 950 | actorId: requesterId, |
| 951 | payload: {}, |
| 952 | }); |
| 953 | } |
| 954 | return row; |
| 955 | }); |
| 956 | |
| 957 | // The shards carry the public flag, so public search follows the change now rather than on the next push or page view. |
| 958 | if (visibility !== |
| 959 | this.reindexCodeSearch(updated |
| 960 | this.logger.warn |
| 961 | `Reindexing ${updated.id |
| 962 | ), |
| 963 | ); |
| 964 | } |
| 965 | |
| 966 | return { id: |
| 967 | } |
| 968 | |
| 969 | private async reindexCodeSearch |
| 970 | const directory = |
| 971 | await this.materializer |
| 972 | repository.id, |
| 973 | directory, |
| 974 | repository.defaultBranch, |
| 975 | ); |
| 976 | await this.codeSearch |
| 977 | repositoryId: repository.id |
| 978 | isPublic: repository.visibility |
| 979 | repoDirectory: directory, |
| 980 | }); |
| 981 | } |
| 982 | |
| 983 | /** Nothing of the repository outlives a successful call. A failure leaves it tombstoned, unreadable and still listed, so the owner can retry; see docs/0020. */ |
| 984 | async deleteRepository({ |
| 985 | username, |
| 986 | slug, |
| 987 | requesterId, |
| 988 | }: { |
| 989 | username: string |
| 990 | slug: string |
| 991 | requesterId: string |
| 992 | }) { |
| 993 | const repository = |
| 994 | username, |
| 995 | slug, |
| 996 | requesterId, |
| 997 | }); |
| 998 | |
| 999 | const [heading] |
| 1000 | .select({ |
| 1001 | owner: ownerNameOf(schema |
| 1002 | slug: schema.repository |
| 1003 | number: schema.issue |
| 1004 | }) |
| 1005 | .from(schema.pullRequest |
| 1006 | .innerJoin(schema.issue |
| 1007 | .innerJoin( |
| 1008 | schema.repository, |
| 1009 | eq(schema.repository |
| 1010 | ) |
| 1011 | .innerJoin(schema.user |
| 1012 | .leftJoin( |
| 1013 | schema.organization, |
| 1014 | eq(schema.organization |
| 1015 | ) |
| 1016 | .where(this.openRequestsHeadedBy |
| 1017 | .limit(1); |
| 1018 | if (heading) { |
| 1019 | throw new RepositoryHeadsOpenPullRequestError( |
| 1020 | `${heading.owner} |
| 1021 | ); |
| 1022 | } |
| 1023 | |
| 1024 | await this.wal |
| 1025 | await Promise.all |
| 1026 | this.wal.purgeEntries |
| 1027 | this.materializer |
| 1028 | .settle(repository.id |
| 1029 | .then(() => |
| 1030 | this.codeSearch.remove |
| 1031 | this.s3.deleteUnder |
| 1032 | ]); |
| 1033 | |
| 1034 | await this.db |
| 1035 | // A request opened between the check above and the tombstone. Closing it keeps every open request's head repository alive. |
| 1036 | const stragglers = |
| 1037 | .update(schema.pullRequest |
| 1038 | .set({ state: |
| 1039 | .where(this.openRequestsHeadedBy |
| 1040 | .returning({ issueId: |
| 1041 | for (const { |
| 1042 | await closeIssue(tx |
| 1043 | } |
| 1044 | |
| 1045 | await tx |
| 1046 | .delete(schema.repository |
| 1047 | .where(eq(schema |
| 1048 | }); |
| 1049 | } |
| 1050 | |
| 1051 | /** Open requests into other repositories. Requests into this one go with it. */ |
| 1052 | private openRequestsHeadedBy(repositoryId |
| 1053 | return and( |
| 1054 | eq(schema.pullRequest |
| 1055 | ne(schema.pullRequest |
| 1056 | eq(schema.pullRequest |
| 1057 | ); |
| 1058 | } |
| 1059 | |
| 1060 | /** `ownId` is the repository being renamed, which may keep its own slug. */ |
| 1061 | private async freeSlug |
| 1062 | const { slugified, |
| 1063 | if (RESERVED_REPOSITORY_SLUGS.has |
| 1064 | const [taken] |
| 1065 | .select({ id: |
| 1066 | .from(schema.repository |
| 1067 | .where( |
| 1068 | and(inNamespace(namespace |
| 1069 | ); |
| 1070 | return !taken || |
| 1071 | } |
| 1072 | |
| 1073 | /** The namespace `/name/…` points at. Organization slugs and usernames never collide, so the order only saves a query. */ |
| 1074 | private async namespaceNamed |
| 1075 | const [organization] |
| 1076 | .select({ id: |
| 1077 | .from(schema.organization |
| 1078 | .where(eq(schema |
| 1079 | if (organization) return |
| 1080 | |
| 1081 | const user = |
| 1082 | return { userId: |
| 1083 | } |
| 1084 | |
| 1085 | /** Stars are a toggle, so a repeat press is a no-op rather than an error. */ |
| 1086 | async starRepository({ |
| 1087 | username, |
| 1088 | slug, |
| 1089 | requesterId, |
| 1090 | }: { |
| 1091 | username: string |
| 1092 | slug: string |
| 1093 | requesterId: string |
| 1094 | }) { |
| 1095 | const repository = |
| 1096 | username, |
| 1097 | slug, |
| 1098 | requesterId, |
| 1099 | }); |
| 1100 | |
| 1101 | await this.db |
| 1102 | const starred = |
| 1103 | .insert(schema.stars |
| 1104 | .values({ userId: |
| 1105 | .onConflictDoNothing() |
| 1106 | .returning({ id: |
| 1107 | if (starred.length |
| 1108 | await publishEvent(tx |
| 1109 | type: 'star.created', |
| 1110 | repositoryId: repository.id |
| 1111 | actorId: requesterId, |
| 1112 | payload: {}, |
| 1113 | }); |
| 1114 | }); |
| 1115 | |
| 1116 | return this.readStars |
| 1117 | } |
| 1118 | |
| 1119 | async unstarRepository({ |
| 1120 | username, |
| 1121 | slug, |
| 1122 | requesterId, |
| 1123 | }: { |
| 1124 | username: string |
| 1125 | slug: string |
| 1126 | requesterId: string |
| 1127 | }) { |
| 1128 | const repository = |
| 1129 | username, |
| 1130 | slug, |
| 1131 | requesterId, |
| 1132 | }); |
| 1133 | |
| 1134 | await this.db |
| 1135 | const unstarred = |
| 1136 | .delete(schema.stars |
| 1137 | .where( |
| 1138 | and( |
| 1139 | eq(schema.stars |
| 1140 | eq(schema.stars |
| 1141 | ), |
| 1142 | ) |
| 1143 | .returning({ id: |
| 1144 | if (unstarred.length |
| 1145 | await publishEvent(tx |
| 1146 | type: 'star.deleted', |
| 1147 | repositoryId: repository.id |
| 1148 | actorId: requesterId, |
| 1149 | payload: {}, |
| 1150 | }); |
| 1151 | }); |
| 1152 | |
| 1153 | return this.readStars |
| 1154 | } |
| 1155 | |
| 1156 | private authorizeRead({ |
| 1157 | username, |
| 1158 | slug, |
| 1159 | requesterId, |
| 1160 | }: { |
| 1161 | username: string |
| 1162 | slug: string |
| 1163 | requesterId?: string |
| 1164 | }) { |
| 1165 | return this.authorizeAs |
| 1166 | } |
| 1167 | |
| 1168 | private authorizeAs( |
| 1169 | operation: RepositoryOperation |
| 1170 | { |
| 1171 | username, |
| 1172 | slug, |
| 1173 | requesterId, |
| 1174 | }: { username |
| 1175 | ) { |
| 1176 | return this.access |
| 1177 | username, |
| 1178 | repo: slug, |
| 1179 | actor: actorOf(requesterId |
| 1180 | operation, |
| 1181 | }); |
| 1182 | } |
| 1183 | |
| 1184 | private async readStars |
| 1185 | const [row] |
| 1186 | .select({ |
| 1187 | starCount: count(), |
| 1188 | // bool_or is null over no rows, and an anonymous viewer has starred nothing |
| 1189 | viewerHasStarred: requesterId |
| 1190 | ? sql<boolean> |
| 1191 | : sql<boolean> |
| 1192 | }) |
| 1193 | .from(schema.stars |
| 1194 | .where(eq(schema |
| 1195 | |
| 1196 | return { |
| 1197 | starCount: row?.starCount |
| 1198 | viewerHasStarred: row?.viewerHasStarred |
| 1199 | }; |
| 1200 | } |
| 1201 | |
| 1202 | async getRepositoryContents({ |
| 1203 | username, |
| 1204 | repo, |
| 1205 | path = '', |
| 1206 | requesterId, |
| 1207 | ref: requestedRef, |
| 1208 | }: { |
| 1209 | username: string |
| 1210 | repo: string |
| 1211 | path?: string |
| 1212 | requesterId?: string |
| 1213 | ref?: string |
| 1214 | }): Promise |
| 1215 | const prefix = |
| 1216 | |
| 1217 | const { repository, |
| 1218 | username, |
| 1219 | repo, |
| 1220 | requesterId, |
| 1221 | ref: requestedRef, |
| 1222 | }); |
| 1223 | |
| 1224 | // a commit is a fixed point in history, so there is no moving tip to index |
| 1225 | if (detached) { |
| 1226 | const [entries, |
| 1227 | listTree({ gitDir: |
| 1228 | this.countCommits({ |
| 1229 | readCommitSummary({ gitDir: |
| 1230 | ]); |
| 1231 | |
| 1232 | return { |
| 1233 | ref, |
| 1234 | path: prefix, |
| 1235 | commitCount, |
| 1236 | commit, |
| 1237 | // per-entry history would be one walk per path, which only the index makes cheap; a point-in-time listing does without it |
| 1238 | entries: entries.map |
| 1239 | }; |
| 1240 | } |
| 1241 | |
| 1242 | const tip = |
| 1243 | repositoryId: repository.id |
| 1244 | repoDirectory: directory, |
| 1245 | ref, |
| 1246 | }); |
| 1247 | |
| 1248 | // No tip means the ref does not exist yet, i.e. nothing has been pushed. |
| 1249 | if (!tip) |
| 1250 | return { ref, |
| 1251 | } |
| 1252 | |
| 1253 | const [entries, |
| 1254 | listTree({ gitDir: |
| 1255 | this.countCommits({ |
| 1256 | ]); |
| 1257 | const commits = |
| 1258 | repositoryId: repository.id |
| 1259 | ref, |
| 1260 | // the root row is the ref's tip, shown above the listing |
| 1261 | paths: ['', ... |
| 1262 | }); |
| 1263 | |
| 1264 | return { |
| 1265 | ref, |
| 1266 | path: prefix, |
| 1267 | commitCount, |
| 1268 | commit: commits.get |
| 1269 | entries: entries.map |
| 1270 | ...entry, |
| 1271 | lastCommit: commits.get |
| 1272 | })), |
| 1273 | }; |
| 1274 | } |
| 1275 | |
| 1276 | async getRepositoryBlob({ |
| 1277 | username, |
| 1278 | repo, |
| 1279 | path, |
| 1280 | requesterId, |
| 1281 | ref: requestedRef, |
| 1282 | }: { |
| 1283 | username: string |
| 1284 | repo: string |
| 1285 | path: string |
| 1286 | requesterId?: string |
| 1287 | ref?: string |
| 1288 | }): Promise |
| 1289 | const filePath = |
| 1290 | |
| 1291 | const { repository, |
| 1292 | username, |
| 1293 | repo, |
| 1294 | requesterId, |
| 1295 | ref: requestedRef, |
| 1296 | }); |
| 1297 | |
| 1298 | const blob = |
| 1299 | if (!blob) |
| 1300 | |
| 1301 | // one file is one history walk, cheap enough to skip the index for |
| 1302 | const lastCommit = |
| 1303 | ? await readCommitSummary( |
| 1304 | : null; |
| 1305 | |
| 1306 | if (!detached) |
| 1307 | await this.pathIndex |
| 1308 | repositoryId: repository.id |
| 1309 | repoDirectory: directory, |
| 1310 | ref, |
| 1311 | }); |
| 1312 | } |
| 1313 | const commits = |
| 1314 | ? new Map() |
| 1315 | : await this. |
| 1316 | repositoryId: repository.id |
| 1317 | ref, |
| 1318 | paths: [filePath], |
| 1319 | }); |
| 1320 | |
| 1321 | const text = |
| 1322 | |
| 1323 | return { |
| 1324 | ref, |
| 1325 | path: filePath, |
| 1326 | oid: blob.oid |
| 1327 | size: blob.size |
| 1328 | encoding: text ? |
| 1329 | content: blob.content |
| 1330 | commit: lastCommit ?? |
| 1331 | }; |
| 1332 | } |
| 1333 | |
| 1334 | async getRepositoryReadme({ |
| 1335 | username, |
| 1336 | repo, |
| 1337 | requesterId, |
| 1338 | ref: requestedRef, |
| 1339 | path: directoryPath = |
| 1340 | }: { |
| 1341 | username: string |
| 1342 | repo: string |
| 1343 | requesterId?: string |
| 1344 | ref?: string |
| 1345 | /** Directory to look in; the root of the repository when omitted. */ |
| 1346 | path?: string |
| 1347 | }): Promise |
| 1348 | const prefix = |
| 1349 | |
| 1350 | const { directory, |
| 1351 | username, |
| 1352 | repo, |
| 1353 | requesterId, |
| 1354 | ref: requestedRef, |
| 1355 | }); |
| 1356 | |
| 1357 | const path = |
| 1358 | if (!path) |
| 1359 | |
| 1360 | const blob = |
| 1361 | if (!blob) |
| 1362 | |
| 1363 | return { |
| 1364 | ref, |
| 1365 | path, |
| 1366 | size: blob.size |
| 1367 | content: isTextBlob(blob |
| 1368 | }; |
| 1369 | } |
| 1370 | |
| 1371 | /** The raw bytes of a file, for the browser to render or download. */ |
| 1372 | async getRawBlob({ |
| 1373 | username, |
| 1374 | repo, |
| 1375 | path, |
| 1376 | requesterId, |
| 1377 | ref: requestedRef, |
| 1378 | }: { |
| 1379 | username: string |
| 1380 | repo: string |
| 1381 | path: string |
| 1382 | requesterId?: string |
| 1383 | ref?: string |
| 1384 | }) { |
| 1385 | const filePath = |
| 1386 | const { directory, |
| 1387 | username, |
| 1388 | repo, |
| 1389 | requesterId, |
| 1390 | ref: requestedRef, |
| 1391 | }); |
| 1392 | |
| 1393 | const blob = |
| 1394 | if (!blob) |
| 1395 | |
| 1396 | const filename = |
| 1397 | |
| 1398 | return { |
| 1399 | ...blob, |
| 1400 | ...mediaTypeFor(filename |
| 1401 | filename, |
| 1402 | stream: streamBlob({ |
| 1403 | }; |
| 1404 | } |
| 1405 | |
| 1406 | async getRepositoryCommits({ |
| 1407 | username, |
| 1408 | repo, |
| 1409 | requesterId, |
| 1410 | query, |
| 1411 | }: { |
| 1412 | username: string |
| 1413 | repo: string |
| 1414 | requesterId?: string |
| 1415 | query: GetRepositoryCommitsQueryDTO |
| 1416 | }): Promise |
| 1417 | const { directory, |
| 1418 | username, |
| 1419 | repo, |
| 1420 | requesterId, |
| 1421 | ref: query.ref |
| 1422 | }); |
| 1423 | |
| 1424 | if (query.cursor |
| 1425 | throw new InvalidCursorError() |
| 1426 | } |
| 1427 | |
| 1428 | // an unborn ref has no history to walk, and git would fail on the revision |
| 1429 | const tip = |
| 1430 | args: ['rev-parse', |
| 1431 | gitDir: directory, |
| 1432 | }).catch(() |
| 1433 | if (!tip.trim |
| 1434 | return { ref, |
| 1435 | } |
| 1436 | |
| 1437 | const path = |
| 1438 | ? normalizeTreePath(query. |
| 1439 | : undefined; |
| 1440 | |
| 1441 | const [{ commits, |
| 1442 | listCommits({ |
| 1443 | gitDir: directory, |
| 1444 | ref, |
| 1445 | path, |
| 1446 | limit: query.limit |
| 1447 | cursor: query.cursor |
| 1448 | }), |
| 1449 | this.countCommits({ |
| 1450 | // commits above the cursor are the pages already behind this one |
| 1451 | query.cursor |
| 1452 | ? this.countCommits( |
| 1453 | directory, |
| 1454 | range: `${query. |
| 1455 | path, |
| 1456 | }) |
| 1457 | : 0, |
| 1458 | ]); |
| 1459 | |
| 1460 | const verdicts = |
| 1461 | gitDir: directory, |
| 1462 | commits, |
| 1463 | }); |
| 1464 | |
| 1465 | return { |
| 1466 | ref, |
| 1467 | from: commits.length |
| 1468 | to: before + |
| 1469 | total, |
| 1470 | commits: commits.map |
| 1471 | ...commit, |
| 1472 | verification: verdicts.get |
| 1473 | })), |
| 1474 | nextCursor, |
| 1475 | }; |
| 1476 | } |
| 1477 | |
| 1478 | async getRepositoryCommit({ |
| 1479 | username, |
| 1480 | repo, |
| 1481 | sha, |
| 1482 | requesterId, |
| 1483 | }: { |
| 1484 | username: string |
| 1485 | repo: string |
| 1486 | sha: string |
| 1487 | requesterId?: string |
| 1488 | }): Promise |
| 1489 | if (!isSha(sha |
| 1490 | |
| 1491 | const { directory |
| 1492 | username, |
| 1493 | repo, |
| 1494 | requesterId, |
| 1495 | }); |
| 1496 | |
| 1497 | const commit = |
| 1498 | if (!commit) |
| 1499 | |
| 1500 | const verdicts = |
| 1501 | gitDir: directory, |
| 1502 | commits: [commit], |
| 1503 | }); |
| 1504 | |
| 1505 | return { ...commit |
| 1506 | } |
| 1507 | |
| 1508 | /** The commit as a patch file, straight from git. */ |
| 1509 | async getCommitPatch({ |
| 1510 | username, |
| 1511 | repo, |
| 1512 | sha, |
| 1513 | path, |
| 1514 | requesterId, |
| 1515 | }: { |
| 1516 | username: string |
| 1517 | repo: string |
| 1518 | sha: string |
| 1519 | path?: string |
| 1520 | requesterId?: string |
| 1521 | }) { |
| 1522 | if (!isSha(sha |
| 1523 | |
| 1524 | const { directory |
| 1525 | username, |
| 1526 | repo, |
| 1527 | requesterId, |
| 1528 | }); |
| 1529 | |
| 1530 | // -1 keeps it to this commit; a merge legitimately produces no patch |
| 1531 | const patch = |
| 1532 | args: [ |
| 1533 | 'format-patch', |
| 1534 | '-1', |
| 1535 | '--stdout', |
| 1536 | '--end-of-options', |
| 1537 | sha, |
| 1538 | ...(path ? |
| 1539 | ], |
| 1540 | gitDir: directory, |
| 1541 | }).catch(() |
| 1542 | if (patch === |
| 1543 | |
| 1544 | return patch; |
| 1545 | } |
| 1546 | |
| 1547 | async getRepositoryBranches({ |
| 1548 | username, |
| 1549 | repo, |
| 1550 | requesterId, |
| 1551 | }: { |
| 1552 | username: string |
| 1553 | repo: string |
| 1554 | requesterId?: string |
| 1555 | }): Promise |
| 1556 | const { directory, |
| 1557 | username, |
| 1558 | repo, |
| 1559 | requesterId, |
| 1560 | }); |
| 1561 | |
| 1562 | const branches = |
| 1563 | const defaultBranch = |
| 1564 | |
| 1565 | return { |
| 1566 | defaultBranch: branches.includes |
| 1567 | branches, |
| 1568 | }; |
| 1569 | } |
| 1570 | |
| 1571 | /** Pages over the tag list in memory: `for-each-ref` has no offset, and listing every ref is cheap next to anything that reads objects. */ |
| 1572 | async getRepositoryTags({ |
| 1573 | username, |
| 1574 | repo, |
| 1575 | requesterId, |
| 1576 | query, |
| 1577 | }: { |
| 1578 | username: string |
| 1579 | repo: string |
| 1580 | requesterId?: string |
| 1581 | query: GetRepositoryTagsQueryDTO |
| 1582 | }): Promise |
| 1583 | const { directory |
| 1584 | username, |
| 1585 | repo, |
| 1586 | requesterId, |
| 1587 | }); |
| 1588 | |
| 1589 | const tags = |
| 1590 | const start = |
| 1591 | ? tags.findIndex( |
| 1592 | : 0; |
| 1593 | if (start === |
| 1594 | |
| 1595 | const limit = |
| 1596 | const page = |
| 1597 | const hasMore = |
| 1598 | |
| 1599 | return { |
| 1600 | tags: page, |
| 1601 | nextCursor: hasMore ? |
| 1602 | }; |
| 1603 | } |
| 1604 | |
| 1605 | async getRepositoryLanguages({ |
| 1606 | username, |
| 1607 | repo, |
| 1608 | requesterId, |
| 1609 | }: { |
| 1610 | username: string |
| 1611 | repo: string |
| 1612 | requesterId?: string |
| 1613 | }): Promise |
| 1614 | const { repository, |
| 1615 | username, |
| 1616 | repo, |
| 1617 | requesterId, |
| 1618 | }); |
| 1619 | |
| 1620 | const languages = |
| 1621 | repositoryId: repository.id |
| 1622 | repoDirectory: directory, |
| 1623 | ref, |
| 1624 | }); |
| 1625 | |
| 1626 | const total = |
| 1627 | |
| 1628 | // pool anything which is less than half a percentage |
| 1629 | const rows = |
| 1630 | language, |
| 1631 | bytes, |
| 1632 | percent: (bytes / |
| 1633 | })); |
| 1634 | const shown = |
| 1635 | const pooled = |
| 1636 | |
| 1637 | if (pooled.length |
| 1638 | |
| 1639 | return { |
| 1640 | languages: [ |
| 1641 | ...shown, |
| 1642 | { |
| 1643 | language: 'Others', |
| 1644 | bytes: pooled.reduce |
| 1645 | percent: pooled.reduce |
| 1646 | }, |
| 1647 | ], |
| 1648 | }; |
| 1649 | } |
| 1650 | |
| 1651 | /** The index only ever holds HEAD, so this searches the default branch whatever the page is showing. */ |
| 1652 | async searchRepositoryCode({ |
| 1653 | username, |
| 1654 | repo, |
| 1655 | requesterId, |
| 1656 | query, |
| 1657 | limit = DEFAULT_SEARCH_LIMIT, |
| 1658 | }: { |
| 1659 | username: string |
| 1660 | repo: string |
| 1661 | requesterId?: string |
| 1662 | query: string |
| 1663 | limit?: number |
| 1664 | }): Promise |
| 1665 | const { repository, |
| 1666 | username, |
| 1667 | repo, |
| 1668 | requesterId, |
| 1669 | }); |
| 1670 | |
| 1671 | return this.codeSearch |
| 1672 | repositoryId: repository.id |
| 1673 | isPublic: repository.visibility |
| 1674 | repoDirectory: directory, |
| 1675 | query, |
| 1676 | limit, |
| 1677 | }); |
| 1678 | } |
| 1679 | |
| 1680 | /** Who starred the repository, most recent first. */ |
| 1681 | async getRepositoryStargazers({ |
| 1682 | username, |
| 1683 | repo, |
| 1684 | requesterId, |
| 1685 | query = {}, |
| 1686 | }: { |
| 1687 | username: string |
| 1688 | repo: string |
| 1689 | requesterId?: string |
| 1690 | query?: GetRepositoryStargazersQueryDTO |
| 1691 | }): Promise |
| 1692 | const repository = |
| 1693 | username, |
| 1694 | slug: repo, |
| 1695 | requesterId, |
| 1696 | }); |
| 1697 | const { pageSize, |
| 1698 | query, |
| 1699 | schema.stars.createdAt |
| 1700 | schema.stars.id |
| 1701 | ); |
| 1702 | |
| 1703 | const rows = |
| 1704 | .select({ |
| 1705 | id: schema.stars |
| 1706 | starredAt: schema.stars |
| 1707 | username: schema.user |
| 1708 | name: schema.user |
| 1709 | image: schema.user |
| 1710 | }) |
| 1711 | .from(schema.stars |
| 1712 | .innerJoin(schema.user |
| 1713 | .where(and(eq |
| 1714 | .orderBy(desc(schema |
| 1715 | .limit(pageSize + |
| 1716 | |
| 1717 | const { page, |
| 1718 | date: row.starredAt |
| 1719 | id: row.id |
| 1720 | })); |
| 1721 | |
| 1722 | return { |
| 1723 | // an account without a username has nothing to link to, so it is left out |
| 1724 | stargazers: page.flatMap |
| 1725 | ({ username: handle |
| 1726 | handle |
| 1727 | ? [ |
| 1728 | { |
| 1729 | username: handle, |
| 1730 | name, |
| 1731 | image, |
| 1732 | starredAt: starredAt.toISOString |
| 1733 | }, |
| 1734 | ] |
| 1735 | : [], |
| 1736 | ), |
| 1737 | nextCursor, |
| 1738 | hasMore, |
| 1739 | }; |
| 1740 | } |
| 1741 | |
| 1742 | /** Forks of the repository the requester is allowed to see, newest push first. */ |
| 1743 | async getRepositoryForks({ |
| 1744 | username, |
| 1745 | repo, |
| 1746 | requesterId, |
| 1747 | query = {}, |
| 1748 | }: { |
| 1749 | username: string |
| 1750 | repo: string |
| 1751 | requesterId?: string |
| 1752 | query?: GetRepositoryForksQueryDTO |
| 1753 | }): Promise |
| 1754 | const repository = |
| 1755 | username, |
| 1756 | slug: repo, |
| 1757 | requesterId, |
| 1758 | }); |
| 1759 | const { pageSize, |
| 1760 | query, |
| 1761 | schema.repository.lastPushedAt |
| 1762 | schema.repository.id |
| 1763 | ); |
| 1764 | |
| 1765 | const rows = |
| 1766 | .select({ |
| 1767 | id: schema.repository |
| 1768 | slug: schema.repository |
| 1769 | name: schema.repository |
| 1770 | description: schema.repository |
| 1771 | lastPushedAt: schema.repository |
| 1772 | username: ownerNameOf(schema |
| 1773 | }) |
| 1774 | .from(schema.repository |
| 1775 | .innerJoin(schema.user |
| 1776 | .leftJoin( |
| 1777 | schema.organization, |
| 1778 | eq(schema.organization |
| 1779 | ) |
| 1780 | .leftJoin( |
| 1781 | schema.repositoryCollaborator, |
| 1782 | acceptedCollaboration(schema.repository |
| 1783 | ) |
| 1784 | .leftJoin( |
| 1785 | schema.member, |
| 1786 | organizationMembership( |
| 1787 | schema.repository.organizationId |
| 1788 | actorOf(requesterId), |
| 1789 | ), |
| 1790 | ) |
| 1791 | .where( |
| 1792 | and( |
| 1793 | eq(schema.repository |
| 1794 | // a private fork is the forker's business, not the parent's |
| 1795 | readableBy(actorOf(requesterId |
| 1796 | after, |
| 1797 | ), |
| 1798 | ) |
| 1799 | .orderBy(desc(schema |
| 1800 | .limit(pageSize + |
| 1801 | |
| 1802 | const { page, |
| 1803 | date: row.lastPushedAt |
| 1804 | id: row.id |
| 1805 | })); |
| 1806 | |
| 1807 | return { |
| 1808 | forks: page.flatMap |
| 1809 | row.username |
| 1810 | ? [ |
| 1811 | { |
| 1812 | username: row.username |
| 1813 | slug: row.slug |
| 1814 | name: row.name |
| 1815 | description: row.description |
| 1816 | lastPushedAt: row.lastPushedAt |
| 1817 | }, |
| 1818 | ] |
| 1819 | : [], |
| 1820 | ), |
| 1821 | nextCursor, |
| 1822 | hasMore, |
| 1823 | }; |
| 1824 | } |
| 1825 | |
| 1826 | /** Authors of the default branch, most commits first, read from the index. */ |
| 1827 | async getRepositoryContributors({ |
| 1828 | username, |
| 1829 | repo, |
| 1830 | requesterId, |
| 1831 | query = {}, |
| 1832 | }: { |
| 1833 | username: string |
| 1834 | repo: string |
| 1835 | requesterId?: string |
| 1836 | query?: GetRepositoryContributorsQueryDTO |
| 1837 | }): Promise |
| 1838 | const repository = |
| 1839 | username, |
| 1840 | slug: repo, |
| 1841 | requesterId, |
| 1842 | }); |
| 1843 | |
| 1844 | const { contributors, |
| 1845 | await this.contributions |
| 1846 | repositoryId: repository.id |
| 1847 | limit: query.limit |
| 1848 | }); |
| 1849 | |
| 1850 | return { |
| 1851 | contributors: contributors.map |
| 1852 | username: row.username |
| 1853 | name: row.authorName |
| 1854 | image: row.image |
| 1855 | commits: row.commits |
| 1856 | percent: totalCommits > |
| 1857 | lastCommittedAt: row.lastCommittedAt |
| 1858 | })), |
| 1859 | totalCommits, |
| 1860 | totalContributors, |
| 1861 | }; |
| 1862 | } |
| 1863 | |
| 1864 | /** Page size and the keyset predicate shared by the cursor-paged lists. */ |
| 1865 | private page( |
| 1866 | query: { |
| 1867 | dateColumn: PgColumn |
| 1868 | idColumn: PgColumn |
| 1869 | ) { |
| 1870 | const requested = |
| 1871 | const pageSize = |
| 1872 | ? Math.min( |
| 1873 | : DEFAULT_PAGE_SIZE; |
| 1874 | |
| 1875 | const decoded = |
| 1876 | if (query.cursor |
| 1877 | |
| 1878 | return { |
| 1879 | pageSize, |
| 1880 | after: decoded |
| 1881 | ? or( |
| 1882 | lt(dateColumn, decoded |
| 1883 | and(eq(dateColumn |
| 1884 | ) |
| 1885 | : undefined, |
| 1886 | }; |
| 1887 | } |
| 1888 | |
| 1889 | private async countCommits |
| 1890 | directory, |
| 1891 | range, |
| 1892 | path, |
| 1893 | }: { |
| 1894 | directory: string |
| 1895 | range: string |
| 1896 | path?: string |
| 1897 | }) { |
| 1898 | const count = |
| 1899 | args: [ |
| 1900 | 'rev-list', |
| 1901 | '--count', |
| 1902 | '--end-of-options', |
| 1903 | range, |
| 1904 | ...(path ? |
| 1905 | ], |
| 1906 | gitDir: directory, |
| 1907 | }); |
| 1908 | |
| 1909 | return Number(count |
| 1910 | } |
| 1911 | |
| 1912 | /** Resolves the requested branch, tag or sha to a revision. `detached` marks a tag or sha, which has no moving tip and so is never indexed. */ |
| 1913 | private async openRepository |
| 1914 | username, |
| 1915 | repo, |
| 1916 | requesterId, |
| 1917 | ref: requested, |
| 1918 | }: { |
| 1919 | username: string |
| 1920 | repo: string |
| 1921 | requesterId?: string |
| 1922 | ref?: string |
| 1923 | }) { |
| 1924 | const repository = |
| 1925 | username, |
| 1926 | slug: repo, |
| 1927 | requesterId, |
| 1928 | }); |
| 1929 | |
| 1930 | const directory = |
| 1931 | await this.materializer |
| 1932 | repository.id, |
| 1933 | directory, |
| 1934 | repository.defaultBranch, |
| 1935 | ); |
| 1936 | |
| 1937 | // Pushes index too; this catches repositories that predate code search, while the objects are already on disk. |
| 1938 | this.codeSearch.indexInBackground |
| 1939 | repositoryId: repository.id |
| 1940 | isPublic: repository.visibility |
| 1941 | repoDirectory: directory, |
| 1942 | }); |
| 1943 | |
| 1944 | // Keep the contribution index warm while the objects are hot. The profile graph reads the index only, so rendering it never materializes anything itself. A no-op once the default tip is indexed. |
| 1945 | await this.contributions |
| 1946 | repositoryId: repository.id |
| 1947 | repoDirectory: directory, |
| 1948 | }); |
| 1949 | |
| 1950 | const name = |
| 1951 | if (!name) |
| 1952 | return { |
| 1953 | repository, |
| 1954 | directory, |
| 1955 | detached: false, |
| 1956 | ref: await resolveDefaultRef |
| 1957 | gitDir: directory, |
| 1958 | }), |
| 1959 | }; |
| 1960 | } |
| 1961 | |
| 1962 | const [branches, |
| 1963 | this.branches.getGitBranches |
| 1964 | listTags(directory), |
| 1965 | ]); |
| 1966 | const resolved = |
| 1967 | gitDir: directory, |
| 1968 | branches, |
| 1969 | tags, |
| 1970 | requested: name, |
| 1971 | }); |
| 1972 | if (resolved) return |
| 1973 | |
| 1974 | throw new BranchNotFoundError( |
| 1975 | } |
| 1976 | } |
| 1977 | |
| 1978 | function actorOf(requesterId: |
| 1979 | return requesterId ? |
| 1980 | } |
| 1981 | |
| 1982 | /** Where a repository's slug has to be unique: its organization, or its owner's own repositories. */ |
| 1983 | type Namespace |
| 1984 | |
| 1985 | function inNamespace(namespace: |
| 1986 | return 'organizationId' in |
| 1987 | ? eq(schema. |
| 1988 | : and( |
| 1989 | eq(schema.repository |
| 1990 | isNull(schema.repository |
| 1991 | ); |
| 1992 | } |
| 1993 | |
| 1994 | function sameNamespace(a: |
| 1995 | return 'organizationId' in |
| 1996 | ? 'organizationId' in b |
| 1997 | : 'userId' in b |
| 1998 | } |
| 1999 | |
| 2000 | function organizationIdOf(namespace: |
| 2001 | return 'organizationId' in |
| 2002 | } |
| 2003 | |
| 2004 | function namespaceOf( |
| 2005 | repository: Pick |
| 2006 | ): Namespace { |
| 2007 | return repository.organizationId |
| 2008 | ? { organizationId: repository |
| 2009 | : { userId: repository |
| 2010 | } |
| 2011 | |
| 2012 | /** Name or description contains `q`, ignoring case. A blank query filters nothing. */ |
| 2013 | function matching(q: |
| 2014 | const needle = |
| 2015 | if (!needle) |
| 2016 | |
| 2017 | const pattern = |
| 2018 | return or( |
| 2019 | ilike(schema.repository |
| 2020 | ilike(schema.repository |
| 2021 | ); |
| 2022 | } |
| 2023 | |
| 2024 | /** One extra row was fetched: it only tells us whether another page exists. */ |
| 2025 | function paginate<T |
| 2026 | rows: T |
| 2027 | pageSize: number, |
| 2028 | keyOf: (row |
| 2029 | ) { |
| 2030 | const hasMore = |
| 2031 | const page = |
| 2032 | const last = |
| 2033 | |
| 2034 | return { |
| 2035 | page, |
| 2036 | hasMore, |
| 2037 | nextCursor: hasMore && |
| 2038 | }; |
| 2039 | } |