@red-hat-developer-hub/backstage-plugin-bulk-import-backend 7.2.1 → 7.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +45 -0
- package/README.md +41 -4
- package/dist/database/repositoryDao.cjs.js +6 -0
- package/dist/database/repositoryDao.cjs.js.map +1 -1
- package/dist/generated/openapidocument.cjs.js +89 -0
- package/dist/generated/openapidocument.cjs.js.map +1 -1
- package/dist/github/GithubAppManager.cjs.js +3 -0
- package/dist/github/GithubAppManager.cjs.js.map +1 -1
- package/dist/github/githubApiService.cjs.js +140 -144
- package/dist/github/githubApiService.cjs.js.map +1 -1
- package/dist/github/types.cjs.js.map +1 -1
- package/dist/github/utils/ghUtils.cjs.js +3 -3
- package/dist/github/utils/ghUtils.cjs.js.map +1 -1
- package/dist/github/utils/repoUtils.cjs.js +53 -99
- package/dist/github/utils/repoUtils.cjs.js.map +1 -1
- package/dist/gitlab/GitlabAppManager.cjs.js +2 -0
- package/dist/gitlab/GitlabAppManager.cjs.js.map +1 -1
- package/dist/gitlab/gitlabApiService.cjs.js +65 -8
- package/dist/gitlab/gitlabApiService.cjs.js.map +1 -1
- package/dist/gitlab/utils/glUtils.cjs.js +1 -1
- package/dist/gitlab/utils/glUtils.cjs.js.map +1 -1
- package/dist/gitlab/utils/repoUtils.cjs.js +32 -57
- package/dist/gitlab/utils/repoUtils.cjs.js.map +1 -1
- package/dist/service/handlers/import/bulkImports.cjs.js +14 -6
- package/dist/service/handlers/import/bulkImports.cjs.js.map +1 -1
- package/dist/service/handlers/import/importStatus.cjs.js.map +1 -1
- package/dist/service/handlers/organization/organizations.cjs.js +2 -2
- package/dist/service/handlers/organization/organizations.cjs.js.map +1 -1
- package/dist/service/handlers/repository/repositories.cjs.js +41 -6
- package/dist/service/handlers/repository/repositories.cjs.js.map +1 -1
- package/dist/service/handlers/scm/scm.cjs.js +16 -0
- package/dist/service/handlers/scm/scm.cjs.js.map +1 -0
- package/dist/service/router.cjs.js +81 -9
- package/dist/service/router.cjs.js.map +1 -1
- package/package.json +16 -16
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"githubApiService.cjs.js","sources":["../../src/github/githubApiService.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n CacheService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport type { Config } from '@backstage/config';\nimport {\n DefaultGithubCredentialsProvider,\n GithubIntegrationConfig,\n ScmIntegrations,\n} from '@backstage/integration';\n\nimport { Octokit } from '@octokit/rest';\nimport gitUrlParse from 'git-url-parse';\n\nimport { getBranchName, getCatalogFilename } from '../catalog/catalogUtils';\nimport {\n computeTotalCount,\n extractLocationOwnerMap,\n logErrorIfNeeded,\n} from '../helpers';\nimport {\n DefaultPageNumber,\n DefaultPageSize,\n} from '../service/handlers/handlers';\nimport { CustomGithubCredentialsProvider } from './GithubAppManager';\nimport {\n isGithubAppCredential,\n type ExtendedGithubCredentials,\n type GithubFetchError,\n type GithubOrganization,\n type GithubOrganizationResponse,\n type GithubRepository,\n type GithubRepositoryResponse,\n} from './types';\nimport { buildOcto } from './utils/ghUtils';\nimport {\n addGithubAppOrgs,\n addGithubTokenOrgs,\n getAllAppOrgs,\n} from './utils/orgUtils';\nimport {\n closePRWithComment,\n findOpenPRForBranch,\n getCatalogInfoContentFromPR,\n} from './utils/prUtils';\nimport {\n addGithubAppRepositories,\n addGithubTokenOrgRepositories,\n addGithubTokenRepositories,\n fileExistsInDefaultBranch,\n type ValidatedRepo,\n} from './utils/repoUtils';\nimport {\n executeFunctionOnFirstSuccessfulIntegration,\n fetchFromAllIntegrations,\n fetchFromMatchedIntegration,\n} from './utils/utils';\n\nexport class GithubApiService {\n private readonly logger: LoggerService;\n private readonly integrations: ScmIntegrations;\n public readonly githubCredentialsProvider: CustomGithubCredentialsProvider;\n private readonly config: Config;\n // Cache for storing ETags (used for efficient caching of unchanged data returned by GitHub)\n private readonly cache: CacheService;\n\n constructor(\n logger: LoggerService,\n config: Config,\n cacheService: CacheService,\n ) {\n this.logger = logger;\n this.config = config;\n this.integrations = ScmIntegrations.fromConfig(config);\n this.githubCredentialsProvider =\n CustomGithubCredentialsProvider.fromIntegrations(this.integrations);\n this.cache = cacheService;\n }\n\n async getCredentials(repoUrl: string): Promise<{ token: string }> {\n const provider = DefaultGithubCredentialsProvider.fromIntegrations(\n this.integrations,\n );\n const creds = await provider.getCredentials({\n url: repoUrl,\n });\n if (!creds || !creds.token) {\n throw new Error(`Token not configured for 'github' provider`);\n }\n return {\n token: creds.token,\n };\n }\n\n async getRepositoryFromIntegrations(repoUrl: string): Promise<{\n repository?: GithubRepository;\n errors?: GithubFetchError[];\n }> {\n const { data, errors } = await fetchFromMatchedIntegration(\n {\n logger: this.logger,\n cache: this.cache,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n repoUrl,\n async (octokit, gitUrl) => {\n const resp = await octokit.rest.repos.get({\n owner: gitUrl.owner,\n repo: gitUrl.name,\n });\n const repo = resp?.data;\n if (!repo) {\n return undefined;\n }\n return {\n name: repo.name,\n full_name: repo.full_name,\n url: repo.url,\n html_url: repo.html_url,\n default_branch: repo.default_branch,\n updated_at: repo.updated_at,\n };\n },\n );\n\n return {\n repository: data,\n errors,\n };\n }\n\n async getOrganizationsFromIntegrations(\n search?: string,\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n ): Promise<GithubOrganizationResponse> {\n const orgs = new Map<string, GithubOrganization>();\n const result = await fetchFromAllIntegrations(\n {\n logger: this.logger,\n cache: this.cache,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n const dataFetchErrors = new Map<number, GithubFetchError>();\n const resp = isGithubAppCredential(credential)\n ? await addGithubAppOrgs(\n {\n logger: this.logger,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n octokit,\n ghConfig,\n {\n credentialAccountLogin: credential.accountLogin,\n search,\n orgs,\n errors: dataFetchErrors,\n },\n )\n : await addGithubTokenOrgs(\n {\n logger: this.logger,\n },\n octokit,\n credential,\n {\n search,\n orgs,\n pageNumber,\n pageSize,\n errors: dataFetchErrors,\n },\n );\n\n this.logger.debug(\n `Got ${resp.totalCount} org(s) for ${ghConfig.host}`,\n );\n return {\n result: resp.totalCount ?? 0,\n errors: Array.from(dataFetchErrors.values()),\n };\n },\n },\n );\n\n const orgList = Array.from(orgs.values());\n const totalCount = computeTotalCount(orgList, result.data, pageSize);\n return {\n organizations: orgList,\n errors: Array.from(result.errors?.values() ?? []),\n totalCount,\n };\n }\n\n async getOrgRepositoriesFromIntegrations(\n orgName: string,\n search?: string,\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n ): Promise<GithubRepositoryResponse> {\n const repositories = new Map<string, GithubRepository>();\n const result = await fetchFromAllIntegrations(\n {\n logger: this.logger,\n cache: this.cache,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n const dataFetchErrors = new Map<number, GithubFetchError>();\n let resp: { totalCount?: number };\n if (isGithubAppCredential(credential)) {\n if (credential.accountLogin !== orgName) {\n return {};\n }\n resp = await addGithubAppRepositories(\n {\n logger: this.logger,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n octokit,\n credential,\n ghConfig,\n repositories,\n dataFetchErrors,\n {\n search,\n pageNumber,\n pageSize,\n },\n );\n } else {\n resp = await addGithubTokenOrgRepositories(\n {\n logger: this.logger,\n },\n octokit,\n credential,\n orgName,\n repositories,\n dataFetchErrors,\n {\n search,\n pageNumber,\n pageSize,\n },\n );\n }\n this.logger.debug(\n `Got ${resp.totalCount} org repo(s) for ${ghConfig.host}`,\n );\n return {\n stopFetchingData: true,\n result: resp.totalCount ?? 0,\n errors: Array.from(dataFetchErrors.values()),\n };\n },\n },\n );\n\n const repoList = Array.from(repositories.values());\n const totalCount = computeTotalCount(repoList, result.data, pageSize);\n return {\n repositories: repoList,\n errors: Array.from(result.errors?.values() ?? []),\n totalCount,\n };\n }\n\n /**\n * Returns GithubRepositoryResponse containing:\n * - a list of unique repositories the github integrations have access to\n * - a list of errors encountered by each app and/or token (if any exist)\n */\n async getRepositoriesFromIntegrations(\n search?: string,\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n ): Promise<GithubRepositoryResponse> {\n const repositories = new Map<string, GithubRepository>();\n const result = await fetchFromAllIntegrations(\n {\n logger: this.logger,\n cache: this.cache,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n const dataFetchErrors = new Map<number, GithubFetchError>();\n const resp = isGithubAppCredential(credential)\n ? await addGithubAppRepositories(\n {\n logger: this.logger,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n octokit,\n credential,\n ghConfig,\n repositories,\n dataFetchErrors,\n {\n search,\n pageNumber,\n pageSize,\n },\n )\n : await addGithubTokenRepositories(\n {\n logger: this.logger,\n },\n octokit,\n credential,\n repositories,\n dataFetchErrors,\n {\n search,\n pageNumber,\n pageSize,\n },\n );\n this.logger.debug(\n `Got ${resp.totalCount} repo(s) for ${ghConfig.host}`,\n );\n return {\n result: resp.totalCount ?? 0,\n errors: Array.from(dataFetchErrors.values()),\n };\n },\n },\n );\n\n const repoList = Array.from(repositories.values());\n const totalCount = computeTotalCount(repoList, result.data, pageSize);\n return {\n repositories: repoList,\n errors: Array.from(result.errors?.values() ?? []),\n totalCount,\n };\n }\n\n async filterLocationsAccessibleFromIntegrations(\n locationUrls: string[],\n ): Promise<string[]> {\n const locationGitOwnerMap = extractLocationOwnerMap(locationUrls);\n\n const allAccessibleAppOrgs = new Set<string>();\n const allAccessibleTokenOrgs = new Set<string>();\n const allAccessibleUsernames = new Set<string>();\n await fetchFromAllIntegrations(\n {\n logger: this.logger,\n cache: this.cache,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n if (isGithubAppCredential(credential)) {\n const appOrgMap = await getAllAppOrgs(\n this.githubCredentialsProvider,\n ghConfig,\n credential.accountLogin,\n );\n for (const [_, ghOrg] of appOrgMap) {\n allAccessibleAppOrgs.add(ghOrg.name);\n }\n } else {\n // find authenticated GitHub owner...\n const username = (await octokit.rest.users.getAuthenticated())?.data\n ?.login;\n if (username) {\n allAccessibleUsernames.add(username);\n }\n // ... along with orgs accessible from the token auth\n (await octokit.paginate(octokit.rest.orgs.listForAuthenticatedUser))\n ?.map(org => org.login)\n ?.forEach(orgName => allAccessibleTokenOrgs.add(orgName));\n }\n return {};\n },\n },\n );\n\n return locationUrls.filter(loc => {\n if (!locationGitOwnerMap.has(loc)) {\n return false;\n }\n const owner = locationGitOwnerMap.get(loc)!;\n return (\n allAccessibleAppOrgs.has(owner) ||\n allAccessibleTokenOrgs.has(owner) ||\n allAccessibleUsernames.has(owner)\n );\n });\n }\n\n async getPullRequest(\n repoUrl: string,\n pullRequestNumber: number,\n ): Promise<{\n title?: string;\n body?: string;\n merged?: boolean;\n lastUpdated?: string;\n prSha?: string;\n prBranch?: string;\n }> {\n const { data } = await fetchFromMatchedIntegration(\n {\n logger: this.logger,\n cache: this.cache,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n repoUrl,\n async (octokit, gitUrl) => {\n try {\n const resp = await octokit.rest.pulls.get({\n owner: gitUrl.owner,\n repo: gitUrl.name,\n pull_number: pullRequestNumber,\n });\n const pr = resp.data;\n return {\n title: pr.title,\n body: pr.body ?? undefined,\n merged: pr.merged,\n lastUpdated: pr.updated_at,\n prSha: pr.head.sha,\n prBranch: pr.head.ref,\n };\n } catch (error: any) {\n logErrorIfNeeded(this.logger, 'Error fetching pull requests', error);\n return undefined;\n }\n },\n );\n return data ?? {};\n }\n\n async updatePullRequest(\n repoUrl: string,\n pullRequestNumber: number,\n title?: string,\n body?: string,\n ): Promise<void> {\n await fetchFromMatchedIntegration(\n {\n logger: this.logger,\n cache: this.cache,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n repoUrl,\n async (octokit, gitUrl) => {\n try {\n await octokit.rest.pulls.update({\n owner: gitUrl.owner,\n repo: gitUrl.name,\n pull_number: pullRequestNumber,\n title: title,\n body: body,\n });\n return;\n } catch (error: any) {\n logErrorIfNeeded(this.logger, 'Error updating pull requests', error);\n throw error;\n }\n },\n );\n }\n\n async createOrUpdateFileInBranch(\n owner: string,\n repo: string,\n branchName: string,\n fileName: string,\n fileContent: string,\n ): Promise<void> {\n try {\n const ghConfig = this.integrations.github.byUrl(\n `https://github.com/${owner}/${repo}`,\n )?.config;\n if (!ghConfig) {\n throw new Error(\n `Could not find GH integration from https://github.com/${owner}/${repo}`,\n );\n }\n\n const credentials =\n await this.githubCredentialsProvider.getAllCredentials({\n host: ghConfig.host,\n });\n\n if (credentials.length === 0) {\n throw new Error(`No credentials for GH integration`);\n }\n\n for (const credential of credentials) {\n const octokit = buildOcto(\n {\n logger: this.logger,\n cache: this.cache,\n },\n { credential, owner },\n ghConfig.apiBaseUrl,\n );\n if (!octokit) {\n continue;\n }\n\n try {\n const { data: existingFile } = await octokit.rest.repos.getContent({\n owner: owner,\n repo: repo,\n path: fileName,\n ref: branchName,\n });\n // Response can either be a directory (array of files) or a single file element. In this case, we ensure it has the sha property to update it.\n if (Array.isArray(existingFile) || !('sha' in existingFile)) {\n throw new Error(\n `The content at path ${fileName} is not a file or the response from GitHub does not contain the 'sha' property.`,\n );\n }\n // If the file already exists, update it\n await octokit.rest.repos.createOrUpdateFileContents({\n owner,\n repo,\n path: fileName,\n message: `Add ${fileName} config file`,\n content: btoa(fileContent),\n sha: existingFile.sha,\n branch: branchName,\n });\n } catch (error: any) {\n if (error.status === 404) {\n // If the file does not exist, create it\n await octokit.rest.repos.createOrUpdateFileContents({\n owner,\n repo,\n path: fileName,\n message: `Add ${fileName} config file`,\n content: btoa(fileContent),\n branch: branchName,\n });\n } else {\n throw error;\n }\n }\n }\n } catch (error: any) {\n this.logger.error(\n `Error creating or updating file in branch ${branchName}`,\n error,\n );\n throw error;\n }\n }\n\n async findImportOpenPr(\n logger: LoggerService,\n input: {\n repoUrl: string;\n includeCatalogInfoContent?: boolean;\n },\n ): Promise<{\n prNum?: number;\n prUrl?: string;\n prTitle?: string;\n prBody?: string;\n prCatalogInfoContent?: string;\n lastUpdate?: string;\n }> {\n const branchName = getBranchName(this.config);\n const { data } = await fetchFromMatchedIntegration(\n {\n logger: this.logger,\n cache: this.cache,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n input.repoUrl,\n async (octokit, gitUrl) => {\n try {\n return await findOpenPRForBranch(\n logger,\n this.config,\n octokit,\n gitUrl.organization,\n gitUrl.name,\n branchName,\n input.includeCatalogInfoContent,\n );\n } catch (error: any) {\n logErrorIfNeeded(this.logger, 'Error fetching pull requests', error);\n return undefined;\n }\n },\n );\n return data ?? {};\n }\n\n async getCatalogInfoFile(\n logger: LoggerService,\n input: {\n repoUrl: string;\n prNumber: number;\n prHeadSha: string;\n },\n ): Promise<string | undefined> {\n const { data } = await fetchFromMatchedIntegration(\n {\n logger: this.logger,\n cache: this.cache,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n input.repoUrl,\n async (octokit, gitUrl) => {\n try {\n return await getCatalogInfoContentFromPR(\n logger,\n this.config,\n octokit,\n gitUrl.organization,\n gitUrl.name,\n input.prNumber,\n input.prHeadSha,\n );\n } catch (error: any) {\n logErrorIfNeeded(\n this.logger,\n 'Error fetching catalog info file content requests',\n error,\n );\n return undefined;\n }\n },\n );\n return data;\n }\n\n async submitPrToRepo(\n logger: LoggerService,\n input: {\n repoUrl: string;\n gitUrl: gitUrlParse.GitUrl;\n defaultBranch?: string;\n prTitle: string;\n prBody: string;\n catalogInfoContent: string;\n },\n ): Promise<{\n prUrl?: string;\n prNumber?: number;\n hasChanges?: boolean;\n lastUpdate?: string;\n errors?: string[];\n }> {\n const fileName = getCatalogFilename(this.config);\n const errors: any[] = [];\n\n const result = await executeFunctionOnFirstSuccessfulIntegration(\n {\n logger: this.logger,\n cache: this.cache,\n config: this.config,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (\n validatedRepo: ValidatedRepo,\n octo: Octokit,\n ): Promise<{\n successful: boolean;\n result?: {\n prUrl?: string;\n prNumber?: number;\n hasChanges?: boolean;\n lastUpdate?: string;\n };\n }> => {\n const { owner, repo, branchName } = validatedRepo;\n try {\n // Check if there is already a catalogInfo in the default branch\n const catalogInfoFileExists = await fileExistsInDefaultBranch(\n logger,\n octo,\n owner,\n repo,\n fileName,\n input.defaultBranch,\n );\n if (catalogInfoFileExists) {\n // No need to create a PR => component will be imported as is\n return {\n successful: true,\n result: {\n hasChanges: false,\n },\n };\n }\n\n const existingPrForBranch = await findOpenPRForBranch(\n logger,\n this.config,\n octo,\n owner,\n repo,\n branchName,\n );\n\n const repoData = await octo.rest.repos.get({\n owner,\n repo,\n });\n const parentRef = await octo.rest.git.getRef({\n owner,\n repo,\n ref: `heads/${repoData.data.default_branch}`,\n });\n if (existingPrForBranch.prNum) {\n await this.createOrUpdateFileInBranch(\n owner,\n repo,\n branchName,\n fileName,\n input.catalogInfoContent,\n );\n const pullRequestResponse = await octo.rest.pulls.update({\n owner,\n repo,\n pull_number: existingPrForBranch.prNum,\n title: input.prTitle,\n body: input.prBody,\n head: branchName,\n base: repoData.data.default_branch,\n });\n return {\n successful: true,\n result: {\n prNumber: existingPrForBranch.prNum,\n prUrl: pullRequestResponse.data.html_url,\n lastUpdate: pullRequestResponse.data.updated_at,\n },\n };\n }\n\n let branchExists = false;\n try {\n await octo.rest.git.getRef({\n owner,\n repo,\n ref: `heads/${branchName}`,\n });\n branchExists = true;\n } catch (error: any) {\n if (error.status === 404) {\n await octo.rest.git.createRef({\n owner,\n repo,\n ref: `refs/heads/${branchName}`,\n sha: parentRef.data.object.sha,\n });\n } else {\n throw error;\n }\n }\n\n if (branchExists) {\n // update it in case it is outdated compared to the base branch\n try {\n await octo.repos.merge({\n owner: owner,\n repo: repo,\n base: branchName,\n head: repoData.data.default_branch,\n });\n } catch (error: any) {\n logErrorIfNeeded(\n this.logger,\n `Could not merge default branch ${repoData.data.default_branch} into import branch ${branchName}`,\n error,\n );\n }\n }\n\n await this.createOrUpdateFileInBranch(\n owner,\n repo,\n branchName,\n fileName,\n input.catalogInfoContent,\n );\n\n const pullRequestResponse = await octo.rest.pulls.create({\n owner,\n repo,\n title: input.prTitle,\n body: input.prBody,\n head: branchName,\n base: repoData.data.default_branch,\n });\n return {\n successful: true,\n result: {\n prNumber: pullRequestResponse.data.number,\n prUrl: pullRequestResponse.data.html_url,\n lastUpdate: pullRequestResponse.data.updated_at,\n hasChanges: true,\n },\n };\n } catch (e: any) {\n logErrorIfNeeded(\n this.logger,\n `Couldn't create PR in ${input.repoUrl}`,\n e,\n );\n errors.push(e.message);\n return { successful: false };\n }\n },\n },\n );\n\n if (result) {\n return result;\n }\n\n logger.warn(\n `Tried all possible GitHub credentials, but could not create PR in ${input.repoUrl}. Please try again later...`,\n );\n\n return {\n errors: errors,\n };\n }\n\n async hasFileInRepo(input: {\n repoUrl: string;\n defaultBranch?: string;\n fileName: string;\n }) {\n const fileExists = await executeFunctionOnFirstSuccessfulIntegration(\n {\n logger: this.logger,\n cache: this.cache,\n config: this.config,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo } = validatedRepo;\n const exists = await fileExistsInDefaultBranch(\n this.logger,\n octo,\n owner,\n repo,\n input.fileName,\n input.defaultBranch,\n );\n if (exists === undefined) {\n return { successful: false };\n }\n return { successful: true, result: exists };\n },\n },\n );\n\n if (fileExists === undefined) {\n throw new Error(\n `Could not determine if repo at ${input.repoUrl} already has a file named ${input.fileName} in its default branch (${input.defaultBranch})`,\n );\n }\n\n return fileExists;\n }\n\n async closeImportPR(\n logger: LoggerService,\n input: {\n repoUrl: string;\n gitUrl: gitUrlParse.GitUrl;\n comment: string;\n },\n ) {\n await executeFunctionOnFirstSuccessfulIntegration(\n {\n logger: this.logger,\n cache: this.cache,\n config: this.config,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo, branchName } = validatedRepo;\n try {\n const existingPrForBranch = await findOpenPRForBranch(\n logger,\n this.config,\n octo,\n owner,\n repo,\n branchName,\n );\n if (existingPrForBranch.prNum) {\n await closePRWithComment(\n octo,\n owner,\n repo,\n existingPrForBranch.prNum,\n input.comment,\n );\n }\n return { successful: true };\n } catch (e: any) {\n logErrorIfNeeded(\n this.logger,\n `Couldn't close PR in ${input.repoUrl}`,\n e,\n );\n return { successful: false };\n }\n },\n },\n );\n }\n\n async deleteImportBranch(input: {\n repoUrl: string;\n gitUrl: gitUrlParse.GitUrl;\n }) {\n await executeFunctionOnFirstSuccessfulIntegration(\n {\n logger: this.logger,\n cache: this.cache,\n config: this.config,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo, branchName } = validatedRepo;\n try {\n await octo.git.deleteRef({\n owner: owner,\n repo: repo,\n ref: `heads/${branchName}`,\n });\n return { successful: true };\n } catch (e: any) {\n logErrorIfNeeded(\n this.logger,\n `Couldn't close import PR and/or delete import branch in ${input.repoUrl}`,\n e,\n );\n return { successful: false };\n }\n },\n },\n );\n }\n\n async isRepoEmpty(input: { repoUrl: string }) {\n return await executeFunctionOnFirstSuccessfulIntegration(\n {\n logger: this.logger,\n cache: this.cache,\n config: this.config,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo } = validatedRepo;\n const resp = await octo.rest.repos.listContributors({\n owner: owner,\n repo: repo,\n page: 1,\n per_page: 1,\n });\n const status = resp.status as 200 | 204;\n return { successful: true, result: status === 204 };\n },\n },\n );\n }\n}\n"],"names":["ScmIntegrations","CustomGithubCredentialsProvider","DefaultGithubCredentialsProvider","fetchFromMatchedIntegration","DefaultPageNumber","DefaultPageSize","fetchFromAllIntegrations","isGithubAppCredential","addGithubAppOrgs","addGithubTokenOrgs","computeTotalCount","addGithubAppRepositories","addGithubTokenOrgRepositories","addGithubTokenRepositories","extractLocationOwnerMap","getAllAppOrgs","logErrorIfNeeded","buildOcto","getBranchName","findOpenPRForBranch","getCatalogInfoContentFromPR","getCatalogFilename","executeFunctionOnFirstSuccessfulIntegration","fileExistsInDefaultBranch","pullRequestResponse","closePRWithComment"],"mappings":";;;;;;;;;;;;;;;;;;;AA0EO,MAAM,gBAAA,CAAiB;AAAA,EACX,MAAA;AAAA,EACA,YAAA;AAAA,EACD,yBAAA;AAAA,EACC,MAAA;AAAA;AAAA,EAEA,KAAA;AAAA,EAEjB,WAAA,CACE,MAAA,EACA,MAAA,EACA,YAAA,EACA;AACA,IAAA,IAAA,CAAK,MA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AA;AACD,UAAA,MAAM,SAAS,IAAA,CAAK,MAAA;AACpB,UAAA,OAAO,EAAE,UAAA,EAAY,IAAA,EAAM,MAAA,EAAQ,WAAW,GAAA,EAAI;AAAA,QACpD;AAAA;AACF,KACF;AAAA,EACF;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"githubApiService.cjs.js","sources":["../../src/github/githubApiService.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n CacheService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport type { Config } from '@backstage/config';\nimport {\n DefaultGithubCredentialsProvider,\n GithubCredentials,\n GithubIntegrationConfig,\n ScmIntegrations,\n} from '@backstage/integration';\n\nimport { Octokit } from '@octokit/rest';\nimport gitUrlParse from 'git-url-parse';\n\nimport { getBranchName, getCatalogFilename } from '../catalog/catalogUtils';\nimport {\n computeTotalCount,\n extractLocationOwnerMap,\n logErrorIfNeeded,\n} from '../helpers';\nimport { GitApiService } from '../scm/GitApiService';\nimport {\n DefaultPageNumber,\n DefaultPageSize,\n} from '../service/handlers/handlers';\nimport { CustomGithubCredentialsProvider } from './GithubAppManager';\nimport {\n isGithubAppCredential,\n type ExtendedGithubCredentials,\n type GithubFetchError,\n type GithubOrganization,\n type GithubOrganizationResponse,\n type GithubRepository,\n type GithubRepositoryResponse,\n} from './types';\nimport { buildOcto } from './utils/ghUtils';\nimport {\n addGithubAppOrgs,\n addGithubTokenOrgs,\n getAllAppOrgs,\n} from './utils/orgUtils';\nimport {\n closePRWithComment,\n findOpenPRForBranch,\n getCatalogInfoContentFromPR,\n} from './utils/prUtils';\nimport {\n addGithubAppRepositories,\n addGithubTokenOrgRepositories,\n addGithubTokenRepositories,\n fileExistsInDefaultBranch,\n type ValidatedRepo,\n} from './utils/repoUtils';\nimport {\n executeFunctionOnFirstSuccessfulIntegration,\n fetchFromAllIntegrations,\n fetchFromMatchedIntegration,\n} from './utils/utils';\n\nexport class GithubApiService implements GitApiService {\n private readonly logger: LoggerService;\n private readonly integrations: ScmIntegrations;\n public readonly githubCredentialsProvider: CustomGithubCredentialsProvider;\n private readonly config: Config;\n // Cache for storing ETags (used for efficient caching of unchanged data returned by GitHub)\n private readonly cache: CacheService;\n\n constructor(\n logger: LoggerService,\n config: Config,\n cacheService: CacheService,\n ) {\n this.logger = logger;\n this.config = config;\n this.integrations = ScmIntegrations.fromConfig(config);\n this.githubCredentialsProvider =\n CustomGithubCredentialsProvider.fromIntegrations(this.integrations);\n this.cache = cacheService;\n }\n\n private get integrationDeps() {\n return {\n logger: this.logger,\n cache: this.cache,\n githubCredentialsProvider: this.githubCredentialsProvider,\n };\n }\n\n private get executionDeps() {\n return {\n ...this.integrationDeps,\n config: this.config,\n };\n }\n\n private buildRepositoryResponse(\n repositories: Map<string, GithubRepository>,\n result: { data: number[]; errors: Map<number, GithubFetchError> },\n pageSize: number,\n ): GithubRepositoryResponse {\n const repoList = Array.from(repositories.values());\n const totalCount = computeTotalCount(repoList, result.data, pageSize);\n return {\n repositories: repoList,\n errors: Array.from(result.errors.values()),\n totalCount,\n };\n }\n\n async getCredentials(repoUrl: string): Promise<{ token: string }> {\n const provider = DefaultGithubCredentialsProvider.fromIntegrations(\n this.integrations,\n );\n const creds = await provider.getCredentials({\n url: repoUrl,\n });\n if (!creds || !creds.token) {\n throw new Error(`Token not configured for 'github' provider`);\n }\n return {\n token: creds.token,\n };\n }\n\n async getRepositoryFromIntegrations(repoUrl: string): Promise<{\n repository?: GithubRepository;\n errors?: GithubFetchError[];\n }> {\n const { data, errors } = await fetchFromMatchedIntegration(\n this.integrationDeps,\n this.integrations,\n repoUrl,\n async (octokit, gitUrl) => {\n const resp = await octokit.rest.repos.get({\n owner: gitUrl.owner,\n repo: gitUrl.name,\n });\n const repo = resp?.data;\n if (!repo) {\n return undefined;\n }\n return {\n name: repo.name,\n full_name: repo.full_name,\n url: repo.url,\n html_url: repo.html_url,\n default_branch: repo.default_branch,\n updated_at: repo.updated_at,\n };\n },\n );\n\n return {\n repository: data,\n errors,\n };\n }\n\n async getOrganizationsFromIntegrations(\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n search?: string,\n ): Promise<GithubOrganizationResponse> {\n const orgs = new Map<string, GithubOrganization>();\n const result = await fetchFromAllIntegrations(\n this.integrationDeps,\n this.integrations,\n {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n const dataFetchErrors = new Map<number, GithubFetchError>();\n const resp = isGithubAppCredential(credential)\n ? await addGithubAppOrgs(\n {\n logger: this.logger,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n octokit,\n ghConfig,\n {\n credentialAccountLogin: credential.accountLogin,\n search,\n orgs,\n errors: dataFetchErrors,\n },\n )\n : await addGithubTokenOrgs(\n {\n logger: this.logger,\n },\n octokit,\n credential,\n {\n search,\n orgs,\n pageNumber,\n pageSize,\n errors: dataFetchErrors,\n },\n );\n\n this.logger.debug(\n `Got ${resp.totalCount} org(s) for ${ghConfig.host}`,\n );\n return {\n result: resp.totalCount ?? 0,\n errors: Array.from(dataFetchErrors.values()),\n };\n },\n },\n );\n\n const orgList = Array.from(orgs.values());\n const totalCount = computeTotalCount(orgList, result.data, pageSize);\n return {\n organizations: orgList,\n errors: Array.from(result.errors?.values() ?? []),\n totalCount,\n };\n }\n\n private async fetchUserTokenGithubIntegrationRepositories(\n userTokens: Record<string, string>,\n fetcher: (\n octokit: Octokit,\n credential: GithubCredentials,\n errors: Map<number, GithubFetchError>,\n ) => Promise<{ totalCount?: number }>,\n ): Promise<{ errors: GithubFetchError[]; totalCount: number | undefined }> {\n const allErrors: GithubFetchError[] = [];\n let totalCount: number | undefined;\n const ghConfigs = this.integrations.github.list().map(i => i.config);\n for (const ghConfig of ghConfigs) {\n const hostUrl = `https://${ghConfig.host}`;\n const token = userTokens[hostUrl];\n if (!token) {\n continue;\n }\n // Synthesize a token credential — same shape buildOcto already accepts\n const userCredential: GithubCredentials = { token, type: 'token' };\n\n // Intentionally no cache: user-token requests must not share the\n // server-credential ETag cache to avoid cross-user data leakage.\n const userOctokit = buildOcto(\n { logger: this.logger, cache: undefined },\n { credential: userCredential },\n ghConfig.apiBaseUrl,\n );\n if (!userOctokit) {\n continue;\n }\n const dataFetchErrors = new Map<number, GithubFetchError>();\n const result = await fetcher(\n userOctokit,\n userCredential,\n dataFetchErrors,\n );\n totalCount = (totalCount ?? 0) + (result.totalCount ?? 0);\n dataFetchErrors.forEach(err => allErrors.push(err));\n }\n return { errors: allErrors, totalCount };\n }\n\n async getOrgRepositoriesFromIntegrations(\n orgName: string,\n search?: string,\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n userTokens?: Record<string, string>,\n ): Promise<GithubRepositoryResponse> {\n const repositories = new Map<string, GithubRepository>();\n\n // When a user token is present, build a user-scoped Octokit per integration\n // config and call addGithubTokenOrgRepositories with it. This scopes the\n // listing to repositories the user has access to within the given organization.\n // When absent, fall through to the existing server-credential path.\n if (userTokens && Object.keys(userTokens).length > 0) {\n const { errors: allErrors, totalCount } =\n await this.fetchUserTokenGithubIntegrationRepositories(\n userTokens,\n (userOctokit, userCredential, dataFetchErrors) =>\n addGithubTokenOrgRepositories(\n { logger: this.logger },\n userOctokit,\n userCredential,\n orgName,\n repositories,\n dataFetchErrors,\n { search, pageNumber, pageSize },\n ),\n );\n const repoList = Array.from(repositories.values());\n return { repositories: repoList, errors: allErrors, totalCount };\n }\n\n const result = await fetchFromAllIntegrations(\n this.integrationDeps,\n this.integrations,\n {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n const dataFetchErrors = new Map<number, GithubFetchError>();\n let resp: { totalCount?: number };\n if (isGithubAppCredential(credential)) {\n if (credential.accountLogin !== orgName) {\n return {};\n }\n resp = await addGithubAppRepositories(\n {\n logger: this.logger,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n octokit,\n credential,\n repositories,\n dataFetchErrors,\n {\n search,\n },\n );\n } else {\n resp = await addGithubTokenOrgRepositories(\n {\n logger: this.logger,\n },\n octokit,\n credential,\n orgName,\n repositories,\n dataFetchErrors,\n {\n search,\n },\n );\n }\n this.logger.debug(\n `Got ${resp.totalCount} org repo(s) for ${ghConfig.host}`,\n );\n return {\n stopFetchingData: true,\n result: resp.totalCount ?? 0,\n errors: Array.from(dataFetchErrors.values()),\n };\n },\n },\n );\n\n return this.buildRepositoryResponse(repositories, result, pageSize);\n }\n\n /**\n * Returns GithubRepositoryResponse containing:\n * - a list of unique repositories the github integrations have access to\n * - a list of errors encountered by each app and/or token (if any exist)\n */\n async getRepositoriesFromIntegrations(\n search?: string,\n userTokens?: Record<string, string>,\n ): Promise<GithubRepositoryResponse> {\n const repositories = new Map<string, GithubRepository>();\n\n // When a user token is present, build a user-scoped Octokit per integration\n // config and call addGithubTokenRepositories with it. This makes\n // listForAuthenticatedUser return only repos the user personally has access to.\n // When absent, fall through to the existing server-credential path.\n if (userTokens && Object.keys(userTokens).length > 0) {\n const { errors: allErrors, totalCount } =\n await this.fetchUserTokenGithubIntegrationRepositories(\n userTokens,\n (userOctokit, userCredential, dataFetchErrors) =>\n addGithubTokenRepositories(\n { logger: this.logger },\n userOctokit,\n userCredential,\n repositories,\n dataFetchErrors,\n { search },\n ),\n );\n const repoList = Array.from(repositories.values());\n return { repositories: repoList, errors: allErrors, totalCount };\n }\n\n const result = await fetchFromAllIntegrations(\n this.integrationDeps,\n this.integrations,\n {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n const dataFetchErrors = new Map<number, GithubFetchError>();\n const resp = isGithubAppCredential(credential)\n ? await addGithubAppRepositories(\n {\n logger: this.logger,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n octokit,\n credential,\n repositories,\n dataFetchErrors,\n {\n search,\n },\n )\n : await addGithubTokenRepositories(\n {\n logger: this.logger,\n },\n octokit,\n credential,\n repositories,\n dataFetchErrors,\n {\n search,\n },\n );\n this.logger.debug(\n `Got ${resp.totalCount} repo(s) for ${ghConfig.host}`,\n );\n return {\n result: resp.totalCount ?? 0,\n errors: Array.from(dataFetchErrors.values()),\n };\n },\n },\n );\n\n return this.buildRepositoryResponse(repositories, result, DefaultPageSize);\n }\n\n async filterLocationsAccessibleFromIntegrations(\n locationUrls: string[],\n ): Promise<string[]> {\n const locationGitOwnerMap = extractLocationOwnerMap(locationUrls);\n\n const allAccessibleAppOrgs = new Set<string>();\n const allAccessibleTokenOrgs = new Set<string>();\n const allAccessibleUsernames = new Set<string>();\n await fetchFromAllIntegrations(this.integrationDeps, this.integrations, {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n if (isGithubAppCredential(credential)) {\n const appOrgMap = await getAllAppOrgs(\n this.githubCredentialsProvider,\n ghConfig,\n credential.accountLogin,\n );\n for (const [_, ghOrg] of appOrgMap) {\n allAccessibleAppOrgs.add(ghOrg.name);\n }\n } else {\n // find authenticated GitHub owner...\n const username = (await octokit.rest.users.getAuthenticated())?.data\n ?.login;\n if (username) {\n allAccessibleUsernames.add(username);\n }\n // ... along with orgs accessible from the token auth\n (await octokit.paginate(octokit.rest.orgs.listForAuthenticatedUser))\n ?.map(org => org.login)\n ?.forEach(orgName => allAccessibleTokenOrgs.add(orgName));\n }\n return {};\n },\n });\n\n return locationUrls.filter(loc => {\n if (!locationGitOwnerMap.has(loc)) {\n return false;\n }\n const owner = locationGitOwnerMap.get(loc)!;\n return (\n allAccessibleAppOrgs.has(owner) ||\n allAccessibleTokenOrgs.has(owner) ||\n allAccessibleUsernames.has(owner)\n );\n });\n }\n\n async getPullRequest(\n repoUrl: string,\n pullRequestNumber: number,\n ): Promise<{\n title?: string;\n body?: string;\n merged?: boolean;\n lastUpdated?: string;\n prSha?: string;\n prBranch?: string;\n }> {\n const { data } = await fetchFromMatchedIntegration(\n this.integrationDeps,\n this.integrations,\n repoUrl,\n async (octokit, gitUrl) => {\n try {\n const resp = await octokit.rest.pulls.get({\n owner: gitUrl.owner,\n repo: gitUrl.name,\n pull_number: pullRequestNumber,\n });\n const pr = resp.data;\n return {\n title: pr.title,\n body: pr.body ?? undefined,\n merged: pr.merged,\n lastUpdated: pr.updated_at,\n prSha: pr.head.sha,\n prBranch: pr.head.ref,\n };\n } catch (error: any) {\n logErrorIfNeeded(this.logger, 'Error fetching pull requests', error);\n return undefined;\n }\n },\n );\n return data ?? {};\n }\n\n async updatePullRequest(\n repoUrl: string,\n pullRequestNumber: number,\n title?: string,\n body?: string,\n ): Promise<void> {\n await fetchFromMatchedIntegration(\n this.integrationDeps,\n this.integrations,\n repoUrl,\n async (octokit, gitUrl) => {\n try {\n await octokit.rest.pulls.update({\n owner: gitUrl.owner,\n repo: gitUrl.name,\n pull_number: pullRequestNumber,\n title: title,\n body: body,\n });\n return;\n } catch (error: any) {\n logErrorIfNeeded(this.logger, 'Error updating pull requests', error);\n throw error;\n }\n },\n );\n }\n\n async createOrUpdateFileInBranch(\n owner: string,\n repo: string,\n branchName: string,\n fileName: string,\n fileContent: string,\n ): Promise<void> {\n try {\n const ghConfig = this.integrations.github.byUrl(\n `https://github.com/${owner}/${repo}`,\n )?.config;\n if (!ghConfig) {\n throw new Error(\n `Could not find GH integration from https://github.com/${owner}/${repo}`,\n );\n }\n\n const credentials =\n await this.githubCredentialsProvider.getAllCredentials({\n host: ghConfig.host,\n });\n\n if (credentials.length === 0) {\n throw new Error(`No credentials for GH integration`);\n }\n\n for (const credential of credentials) {\n const octokit = buildOcto(\n {\n logger: this.logger,\n cache: this.cache,\n },\n { credential, owner },\n ghConfig.apiBaseUrl,\n );\n if (!octokit) {\n continue;\n }\n\n try {\n const { data: existingFile } = await octokit.rest.repos.getContent({\n owner: owner,\n repo: repo,\n path: fileName,\n ref: branchName,\n });\n // Response can either be a directory (array of files) or a single file element. In this case, we ensure it has the sha property to update it.\n if (Array.isArray(existingFile) || !('sha' in existingFile)) {\n throw new Error(\n `The content at path ${fileName} is not a file or the response from GitHub does not contain the 'sha' property.`,\n );\n }\n // If the file already exists, update it\n await octokit.rest.repos.createOrUpdateFileContents({\n owner,\n repo,\n path: fileName,\n message: `Add ${fileName} config file`,\n content: btoa(fileContent),\n sha: existingFile.sha,\n branch: branchName,\n });\n } catch (error: any) {\n if (error.status === 404) {\n // If the file does not exist, create it\n await octokit.rest.repos.createOrUpdateFileContents({\n owner,\n repo,\n path: fileName,\n message: `Add ${fileName} config file`,\n content: btoa(fileContent),\n branch: branchName,\n });\n } else {\n throw error;\n }\n }\n }\n } catch (error: any) {\n this.logger.error(\n `Error creating or updating file in branch ${branchName}`,\n error,\n );\n throw error;\n }\n }\n\n async findImportOpenPr(\n logger: LoggerService,\n input: {\n repoUrl: string;\n includeCatalogInfoContent?: boolean;\n },\n ): Promise<{\n prNum?: number;\n prUrl?: string;\n prTitle?: string;\n prBody?: string;\n prCatalogInfoContent?: string;\n lastUpdate?: string;\n }> {\n const branchName = getBranchName(this.config);\n const { data } = await fetchFromMatchedIntegration(\n this.integrationDeps,\n this.integrations,\n input.repoUrl,\n async (octokit, gitUrl) => {\n try {\n return await findOpenPRForBranch(\n logger,\n this.config,\n octokit,\n gitUrl.organization,\n gitUrl.name,\n branchName,\n input.includeCatalogInfoContent,\n );\n } catch (error: any) {\n logErrorIfNeeded(this.logger, 'Error fetching pull requests', error);\n return undefined;\n }\n },\n );\n return data ?? {};\n }\n\n async getCatalogInfoFile(\n logger: LoggerService,\n input: {\n repoUrl: string;\n prNumber: number;\n prHeadSha: string;\n },\n ): Promise<string | undefined> {\n const { data } = await fetchFromMatchedIntegration(\n this.integrationDeps,\n this.integrations,\n input.repoUrl,\n async (octokit, gitUrl) => {\n try {\n return await getCatalogInfoContentFromPR(\n logger,\n this.config,\n octokit,\n gitUrl.organization,\n gitUrl.name,\n input.prNumber,\n input.prHeadSha,\n );\n } catch (error: any) {\n logErrorIfNeeded(\n this.logger,\n 'Error fetching catalog info file content requests',\n error,\n );\n return undefined;\n }\n },\n );\n return data;\n }\n\n async submitPrToRepo(\n logger: LoggerService,\n input: {\n repoUrl: string;\n gitUrl: gitUrlParse.GitUrl;\n defaultBranch?: string;\n prTitle: string;\n prBody: string;\n catalogInfoContent: string;\n },\n ): Promise<{\n prUrl?: string;\n prNumber?: number;\n hasChanges?: boolean;\n lastUpdate?: string;\n errors?: string[];\n }> {\n const fileName = getCatalogFilename(this.config);\n const errors: any[] = [];\n\n const result = await executeFunctionOnFirstSuccessfulIntegration(\n this.executionDeps,\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (\n validatedRepo: ValidatedRepo,\n octo: Octokit,\n ): Promise<{\n successful: boolean;\n result?: {\n prUrl?: string;\n prNumber?: number;\n hasChanges?: boolean;\n lastUpdate?: string;\n };\n }> => {\n const { owner, repo, branchName } = validatedRepo;\n try {\n // Check if there is already a catalogInfo in the default branch\n const catalogInfoFileExists = await fileExistsInDefaultBranch(\n logger,\n octo,\n owner,\n repo,\n fileName,\n input.defaultBranch,\n );\n if (catalogInfoFileExists) {\n // No need to create a PR => component will be imported as is\n return {\n successful: true,\n result: {\n hasChanges: false,\n },\n };\n }\n\n const existingPrForBranch = await findOpenPRForBranch(\n logger,\n this.config,\n octo,\n owner,\n repo,\n branchName,\n );\n\n const repoData = await octo.rest.repos.get({\n owner,\n repo,\n });\n const parentRef = await octo.rest.git.getRef({\n owner,\n repo,\n ref: `heads/${repoData.data.default_branch}`,\n });\n if (existingPrForBranch.prNum) {\n await this.createOrUpdateFileInBranch(\n owner,\n repo,\n branchName,\n fileName,\n input.catalogInfoContent,\n );\n const pullRequestResponse = await octo.rest.pulls.update({\n owner,\n repo,\n pull_number: existingPrForBranch.prNum,\n title: input.prTitle,\n body: input.prBody,\n head: branchName,\n base: repoData.data.default_branch,\n });\n return {\n successful: true,\n result: {\n prNumber: existingPrForBranch.prNum,\n prUrl: pullRequestResponse.data.html_url,\n lastUpdate: pullRequestResponse.data.updated_at,\n },\n };\n }\n\n let branchExists = false;\n try {\n await octo.rest.git.getRef({\n owner,\n repo,\n ref: `heads/${branchName}`,\n });\n branchExists = true;\n } catch (error: any) {\n if (error.status === 404) {\n await octo.rest.git.createRef({\n owner,\n repo,\n ref: `refs/heads/${branchName}`,\n sha: parentRef.data.object.sha,\n });\n } else {\n throw error;\n }\n }\n\n if (branchExists) {\n // update it in case it is outdated compared to the base branch\n try {\n await octo.repos.merge({\n owner: owner,\n repo: repo,\n base: branchName,\n head: repoData.data.default_branch,\n });\n } catch (error: any) {\n logErrorIfNeeded(\n this.logger,\n `Could not merge default branch ${repoData.data.default_branch} into import branch ${branchName}`,\n error,\n );\n }\n }\n\n await this.createOrUpdateFileInBranch(\n owner,\n repo,\n branchName,\n fileName,\n input.catalogInfoContent,\n );\n\n const pullRequestResponse = await octo.rest.pulls.create({\n owner,\n repo,\n title: input.prTitle,\n body: input.prBody,\n head: branchName,\n base: repoData.data.default_branch,\n });\n return {\n successful: true,\n result: {\n prNumber: pullRequestResponse.data.number,\n prUrl: pullRequestResponse.data.html_url,\n lastUpdate: pullRequestResponse.data.updated_at,\n hasChanges: true,\n },\n };\n } catch (e: any) {\n logErrorIfNeeded(\n this.logger,\n `Couldn't create PR in ${input.repoUrl}`,\n e,\n );\n errors.push(e.message);\n return { successful: false };\n }\n },\n },\n );\n\n if (result) {\n return result;\n }\n\n logger.warn(\n `Tried all possible GitHub credentials, but could not create PR in ${input.repoUrl}. Please try again later...`,\n );\n\n return {\n errors: errors,\n };\n }\n\n async hasFileInRepo(input: {\n repoUrl: string;\n defaultBranch?: string;\n fileName: string;\n }): Promise<boolean> {\n const fileExists = await executeFunctionOnFirstSuccessfulIntegration(\n this.executionDeps,\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo } = validatedRepo;\n const exists = await fileExistsInDefaultBranch(\n this.logger,\n octo,\n owner,\n repo,\n input.fileName,\n input.defaultBranch,\n );\n if (exists === undefined) {\n return { successful: false };\n }\n return { successful: true, result: exists };\n },\n },\n );\n\n if (fileExists === undefined) {\n throw new Error(\n `Could not determine if repo at ${input.repoUrl} already has a file named ${input.fileName} in its default branch (${input.defaultBranch})`,\n );\n }\n\n return fileExists;\n }\n\n async closeImportPR(\n logger: LoggerService,\n input: {\n repoUrl: string;\n gitUrl: gitUrlParse.GitUrl;\n comment: string;\n },\n ): Promise<void> {\n await executeFunctionOnFirstSuccessfulIntegration(\n this.executionDeps,\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo, branchName } = validatedRepo;\n try {\n const existingPrForBranch = await findOpenPRForBranch(\n logger,\n this.config,\n octo,\n owner,\n repo,\n branchName,\n );\n if (existingPrForBranch.prNum) {\n await closePRWithComment(\n octo,\n owner,\n repo,\n existingPrForBranch.prNum,\n input.comment,\n );\n }\n return { successful: true };\n } catch (e: any) {\n logErrorIfNeeded(\n this.logger,\n `Couldn't close PR in ${input.repoUrl}`,\n e,\n );\n return { successful: false };\n }\n },\n },\n );\n }\n\n async deleteImportBranch(input: {\n repoUrl: string;\n gitUrl: gitUrlParse.GitUrl;\n }): Promise<void> {\n await executeFunctionOnFirstSuccessfulIntegration(\n this.executionDeps,\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo, branchName } = validatedRepo;\n try {\n await octo.git.deleteRef({\n owner: owner,\n repo: repo,\n ref: `heads/${branchName}`,\n });\n return { successful: true };\n } catch (e: any) {\n logErrorIfNeeded(\n this.logger,\n `Couldn't close import PR and/or delete import branch in ${input.repoUrl}`,\n e,\n );\n return { successful: false };\n }\n },\n },\n );\n }\n\n async isRepoEmpty(input: { repoUrl: string }): Promise<boolean | undefined> {\n return await executeFunctionOnFirstSuccessfulIntegration(\n this.executionDeps,\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo } = validatedRepo;\n const resp = await octo.rest.repos.listContributors({\n owner: owner,\n repo: repo,\n page: 1,\n per_page: 1,\n });\n const status = resp.status as 200 | 204;\n return { successful: true, result: status === 204 };\n },\n },\n );\n }\n}\n"],"names":["ScmIntegrations","CustomGithubCredentialsProvider","computeTotalCount","DefaultGithubCredentialsProvider","fetchFromMatchedIntegration","DefaultPageNumber","DefaultPageSize","fetchFromAllIntegrations","isGithubAppCredential","addGithubAppOrgs","addGithubTokenOrgs","buildOcto","addGithubTokenOrgRepositories","addGithubAppRepositories","addGithubTokenRepositories","extractLocationOwnerMap","getAllAppOrgs","logErrorIfNeeded","getBranchName","findOpenPRForBranch","getCatalogInfoContentFromPR","getCatalogFilename","executeFunctionOnFirstSuccessfulIntegration","fileExistsInDefaultBranch","pullRequestResponse","closePRWithComment"],"mappings":";;;;;;;;;;;;;;;;;;;AA4EO,MAAM,gBAAA,CAA0C;AAAA,EACpC,MAAA;AAAA,EACA,YAAA;AAAA,EACD,yBAAA;AAAA,EACC,MAAA;AAAA;AAAA,EAEA,KAAA;AAAA,EAEjB,WAAA,CACE,MAAA,EACA,MAAA,EACA,YAAA,EACA;AACA,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,YAAA,GAAeA,2BAAA,CAAgB,UAAA,CAAW,MAAM,CAAA;AACrD,IAAA,IAAA,CAAK,yBAAA,GACHC,gDAAA,CAAgC,gBAAA,CAAiB,I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A;AAAA,cACE,IAAA,CAAK,MAAA;AAAA,cACL,CAAA,wDAAA,EAA2D,MAAM,OAAO,CAAA,CAAA;AAAA,cACxE;AAAA,aACF;AACA,YAAA,OAAO,EAAE,YAAY,KAAA,EAAM;AAAA,UAC7B;AAAA,QACF;AAAA;AACF,KACF;AAAA,EACF;AAAA,EAEA,MAAM,YAAY,KAAA,EAA0D;AAC1E,IAAA,OAAO,MAAMK,mDAAA;AAAA,MACX,IAAA,CAAK,aAAA;AAAA,MACL,IAAA,CAAK,YAAA;AAAA,MACL;AAAA,QACE,SAAS,KAAA,CAAM,OAAA;AAAA,QACf,EAAA,EAAI,OAAO,aAAA,EAA8B,IAAA,KAAkB;AACzD,UAAA,MAAM,EAAE,KAAA,EAAO,IAAA,EAAK,GAAI,aAAA;AACxB,UAAA,MAAM,IAAA,GAAO,MAAM,IAAA,CAAK,IAAA,CAAK,MAAM,gBAAA,CAAiB;AAAA,YAClD,KAAA;AAAA,YACA,IAAA;AAAA,YACA,IAAA,EAAM,CAAA;AAAA,YACN,QAAA,EAAU;AAAA,WACX,CAAA;AACD,UAAA,MAAM,SAAS,IAAA,CAAK,MAAA;AACpB,UAAA,OAAO,EAAE,UAAA,EAAY,IAAA,EAAM,MAAA,EAAQ,WAAW,GAAA,EAAI;AAAA,QACpD;AAAA;AACF,KACF;AAAA,EACF;AACF;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.cjs.js","sources":["../../src/github/types.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {
|
|
1
|
+
{"version":3,"file":"types.cjs.js","sources":["../../src/github/types.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n GithubCredentials,\n GithubCredentialsProvider,\n} from '@backstage/integration';\n\nimport { type RestEndpointMethodTypes } from '@octokit/rest';\n\nexport type {\n SCMFetchError as GithubFetchError,\n SCMOrganization as GithubOrganization,\n SCMOrganizationResponse as GithubOrganizationResponse,\n SCMRepository as GithubRepository,\n SCMRepositoryResponse as GithubRepositoryResponse,\n} from '../scm/types';\n\nexport type AppCredentialFetchResult = AppCredential | AppCredentialError;\n\nexport type AppCredential = {\n appId: number;\n accessToken: string | undefined;\n installationAccountLogin?: string;\n};\nexport type AppCredentialError = { appId: number; error: Error };\n\nexport type ExtendedGithubCredentials =\n | GithubCredentials\n | GithubAppCredentials\n | GithubAppError;\n\nexport type GithubAppCredentials = GithubCredentials & {\n type: 'app';\n appId: number;\n accountLogin?: string;\n};\n\nexport type GithubAppError = {\n type: 'app';\n appId: number;\n error: Error;\n};\n\nexport function isGithubAppCredential(\n credential: ExtendedGithubCredentials,\n): credential is GithubAppCredentials {\n return 'appId' in credential && credential.type === 'app';\n}\n\nexport interface ExtendedGithubCredentialsProvider extends GithubCredentialsProvider {\n getAllCredentials: (options: {\n host: string;\n }) => Promise<ExtendedGithubCredentials[]>;\n}\n\nexport type AuthenticatedUserRepositoryResponse =\n RestEndpointMethodTypes['repos']['listForAuthenticatedUser']['response'];\n\nexport type AuthenticatedUserRepositoryList =\n AuthenticatedUserRepositoryResponse['data'];\n\nexport type AppInstallationRepositoriesResponse =\n RestEndpointMethodTypes['apps']['listReposAccessibleToInstallation']['response'];\n\nexport type AppInstallationRepositories =\n AppInstallationRepositoriesResponse['data'];\n"],"names":[],"mappings":";;AAyDO,SAAS,sBACd,UAAA,EACoC;AACpC,EAAA,OAAO,OAAA,IAAW,UAAA,IAAc,UAAA,CAAW,IAAA,KAAS,KAAA;AACtD;;;;"}
|
|
@@ -42,7 +42,7 @@ function registerHooks(deps, octokit) {
|
|
|
42
42
|
};
|
|
43
43
|
}
|
|
44
44
|
const cacheKey = extractCacheKey(options);
|
|
45
|
-
const existingEtag = await deps.cache
|
|
45
|
+
const existingEtag = await deps.cache?.get(cacheKey)?.then((val) => val?.etag);
|
|
46
46
|
if (existingEtag) {
|
|
47
47
|
options.headers["If-None-Match"] = existingEtag;
|
|
48
48
|
} else {
|
|
@@ -54,7 +54,7 @@ function registerHooks(deps, octokit) {
|
|
|
54
54
|
`[GH API] ${options.method} ${tryReplacingPlaceholdersInUrl(options)}: ${response.status}`
|
|
55
55
|
);
|
|
56
56
|
const cacheKey = extractCacheKey(options);
|
|
57
|
-
await deps.cache
|
|
57
|
+
await deps.cache?.set(
|
|
58
58
|
cacheKey,
|
|
59
59
|
{
|
|
60
60
|
etag: response.headers.etag,
|
|
@@ -70,7 +70,7 @@ function registerHooks(deps, octokit) {
|
|
|
70
70
|
if (error.status !== 304) {
|
|
71
71
|
throw error;
|
|
72
72
|
}
|
|
73
|
-
return await deps.cache
|
|
73
|
+
return await deps.cache?.get(extractCacheKey(options));
|
|
74
74
|
});
|
|
75
75
|
}
|
|
76
76
|
function tryReplacingPlaceholdersInUrl(options) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ghUtils.cjs.js","sources":["../../../src/github/utils/ghUtils.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n CacheService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\n\nimport { Octokit } from '@octokit/rest';\n\nimport {\n isGithubAppCredential,\n type ExtendedGithubCredentials,\n type GithubFetchError,\n} from '../types';\nimport { createCredentialError } from './utils';\n\nconst GITHUB_DEFAULT_API_ENDPOINT = 'https://api.github.com';\n\n// Cache TTL per entry added, based on the lower values of rate limits imposed by GH,\n// i.e., 5K requests per hour for requests using a personal token.\n// GitHub Apps owned by enterprises have a higher limit of 15K per hour.\n// See https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api?apiVersion=2022-11-28\nconst RESPONSE_CACHE_TTL_MILLIS = 60 * 60 * 1000;\n\nexport function buildOcto(\n deps: {\n logger: LoggerService;\n cache: CacheService;\n },\n input: {\n credential: ExtendedGithubCredentials;\n owner?: string;\n errors?: Map<number, GithubFetchError>;\n },\n apiBaseUrl: string = GITHUB_DEFAULT_API_ENDPOINT,\n): Octokit | undefined {\n if ('error' in input.credential) {\n if (input.credential.error?.name !== 'NotFoundError') {\n deps.logger.error(\n `Obtaining the Access Token Github App with appId: ${input.credential.appId} failed with ${input.credential.error}`,\n );\n const credentialError = createCredentialError(input.credential);\n if (credentialError) {\n deps.logger.debug(`${input.credential.appId}: ${credentialError}`);\n if (input.errors) {\n input.errors.set(input.credential.appId, credentialError);\n }\n }\n }\n return undefined;\n }\n if (\n isGithubAppCredential(input.credential) &&\n input.owner &&\n input.credential.accountLogin !== input.owner\n ) {\n return undefined;\n }\n const octokit = new Octokit({\n baseUrl: apiBaseUrl,\n auth: input.credential.token,\n });\n registerHooks(deps, octokit);\n return octokit;\n}\n\nfunction registerHooks(\n deps: {\n logger: LoggerService;\n cache: CacheService;\n },\n octokit: Octokit,\n) {\n const extractCacheKey = (options: any) =>\n `${options.method}--${tryReplacingPlaceholdersInUrl(options)}`;\n\n octokit.hook.before('request', async options => {\n if (!options.headers) {\n options.headers = {\n accept: 'application/json',\n 'user-agent': 'rhdh/bulk-import',\n };\n }\n // Use ETag from in-memory cache if available\n const cacheKey = extractCacheKey(options);\n const existingEtag = await deps.cache\n
|
|
1
|
+
{"version":3,"file":"ghUtils.cjs.js","sources":["../../../src/github/utils/ghUtils.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n CacheService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\n\nimport { Octokit } from '@octokit/rest';\n\nimport {\n isGithubAppCredential,\n type ExtendedGithubCredentials,\n type GithubFetchError,\n} from '../types';\nimport { createCredentialError } from './utils';\n\nconst GITHUB_DEFAULT_API_ENDPOINT = 'https://api.github.com';\n\n// Cache TTL per entry added, based on the lower values of rate limits imposed by GH,\n// i.e., 5K requests per hour for requests using a personal token.\n// GitHub Apps owned by enterprises have a higher limit of 15K per hour.\n// See https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api?apiVersion=2022-11-28\nconst RESPONSE_CACHE_TTL_MILLIS = 60 * 60 * 1000;\n\nexport function buildOcto(\n deps: {\n logger: LoggerService;\n cache: CacheService | undefined;\n },\n input: {\n credential: ExtendedGithubCredentials;\n owner?: string;\n errors?: Map<number, GithubFetchError>;\n },\n apiBaseUrl: string = GITHUB_DEFAULT_API_ENDPOINT,\n): Octokit | undefined {\n if ('error' in input.credential) {\n if (input.credential.error?.name !== 'NotFoundError') {\n deps.logger.error(\n `Obtaining the Access Token Github App with appId: ${input.credential.appId} failed with ${input.credential.error}`,\n );\n const credentialError = createCredentialError(input.credential);\n if (credentialError) {\n deps.logger.debug(`${input.credential.appId}: ${credentialError}`);\n if (input.errors) {\n input.errors.set(input.credential.appId, credentialError);\n }\n }\n }\n return undefined;\n }\n if (\n isGithubAppCredential(input.credential) &&\n input.owner &&\n input.credential.accountLogin !== input.owner\n ) {\n return undefined;\n }\n const octokit = new Octokit({\n baseUrl: apiBaseUrl,\n auth: input.credential.token,\n });\n registerHooks(deps, octokit);\n return octokit;\n}\n\nfunction registerHooks(\n deps: {\n logger: LoggerService;\n cache: CacheService | undefined;\n },\n octokit: Octokit,\n) {\n const extractCacheKey = (options: any) =>\n `${options.method}--${tryReplacingPlaceholdersInUrl(options)}`;\n\n octokit.hook.before('request', async options => {\n if (!options.headers) {\n options.headers = {\n accept: 'application/json',\n 'user-agent': 'rhdh/bulk-import',\n };\n }\n // Use ETag from in-memory cache if available\n const cacheKey = extractCacheKey(options);\n const existingEtag = await deps.cache\n ?.get(cacheKey)\n ?.then((val?: any) => val?.etag);\n if (existingEtag) {\n options.headers['If-None-Match'] = existingEtag;\n } else {\n deps.logger.debug(`cache miss for key \"${cacheKey}\"`);\n }\n });\n\n octokit.hook.after('request', async (response, options) => {\n deps.logger.debug(\n `[GH API] ${options.method} ${tryReplacingPlaceholdersInUrl(options)}: ${\n response.status\n }`,\n );\n // If we get a successful response, the resource has changed, so update the in-memory cache\n const cacheKey = extractCacheKey(options);\n await deps.cache?.set(\n cacheKey,\n {\n etag: response.headers.etag,\n ...response,\n },\n { ttl: RESPONSE_CACHE_TTL_MILLIS },\n );\n });\n\n octokit.hook.error('request', async (error: any, options) => {\n deps.logger.debug(\n `[GH API] ${options.method} ${tryReplacingPlaceholdersInUrl(options)}: ${\n error.status\n }`,\n );\n if (error.status !== 304) {\n throw error;\n }\n // \"304 Not Modified\" means that the resource hasn't changed,\n // and we should have a version of it in the cache\n return await deps.cache?.get(extractCacheKey(options));\n });\n}\n\nfunction tryReplacingPlaceholdersInUrl(options: any) {\n // options.url might contain placeholders => need to replace them with their actual values to not get colliding keys\n\n let result = '';\n let startIdx = 0;\n\n const url = options.url as string | undefined;\n if (!url) {\n return undefined;\n }\n while (startIdx < url.length) {\n const openBraceIdx = url.indexOf('{', startIdx);\n if (openBraceIdx === -1) {\n // no '{' => append the rest of the string\n result += url.slice(startIdx);\n break;\n }\n\n // append part of the string before '{'\n result += url.slice(startIdx, openBraceIdx);\n\n const closeBraceIdx = url.indexOf('}', openBraceIdx);\n if (closeBraceIdx === -1) {\n // no '}' => append the rest of the string\n result += url.slice(openBraceIdx);\n break;\n }\n\n const key = url.slice(openBraceIdx + 1, closeBraceIdx);\n result += options[key] ?? `{${key}}`;\n\n startIdx = closeBraceIdx + 1;\n }\n\n return result;\n}\n"],"names":["createCredentialError","isGithubAppCredential","Octokit"],"mappings":";;;;;;AA8BA,MAAM,2BAAA,GAA8B,wBAAA;AAMpC,MAAM,yBAAA,GAA4B,KAAK,EAAA,GAAK,GAAA;AAErC,SAAS,SAAA,CACd,IAAA,EAIA,KAAA,EAKA,UAAA,GAAqB,2BAAA,EACA;AACrB,EAAA,IAAI,OAAA,IAAW,MAAM,UAAA,EAAY;AAC/B,IAAA,IAAI,KAAA,CAAM,UAAA,CAAW,KAAA,EAAO,IAAA,KAAS,eAAA,EAAiB;AACpD,MAAA,IAAA,CAAK,MAAA,CAAO,KAAA;AAAA,QACV,qDAAqD,KAAA,CAAM,UAAA,CAAW,KAAK,CAAA,aAAA,EAAgB,KAAA,CAAM,WAAW,KAAK,CAAA;AAAA,OACnH;AACA,MAAA,MAAM,eAAA,GAAkBA,2BAAA,CAAsB,KAAA,CAAM,UAAU,CAAA;AAC9D,MAAA,IAAI,eAAA,EAAiB;AACnB,QAAA,IAAA,CAAK,MAAA,CAAO,MAAM,CAAA,EAAG,KAAA,CAAM,WAAW,KAAK,CAAA,EAAA,EAAK,eAAe,CAAA,CAAE,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GnD,EAAA,IAAI,MAAA,GAAS,EAAA;AACb,EAAA,IAAI,QAAA,GAAW,CAAA;AAEf,EAAA,MAAM,MAAM,OAAA,CAAQ,GAAA;AACpB,EAAA,IAAI,CAAC,GAAA,EAAK;AACR,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,OAAO,QAAA,GAAW,IAAI,MAAA,EAAQ;AAC5B,IAAA,MAAM,YAAA,GAAe,GAAA,CAAI,OAAA,CAAQ,GAAA,EAAK,QAAQ,CAAA;AAC9C,IAAA,IAAI,iBAAiB,EAAA,EAAI;AAEvB,MAAA,MAAA,IAAU,GAAA,CAAI,MAAM,QAAQ,CAAA;AAC5B,MAAA;AAAA,IACF;AAGA,IAAA,MAAA,IAAU,GAAA,CAAI,KAAA,CAAM,QAAA,EAAU,YAAY,CAAA;AAE1C,IAAA,MAAM,aAAA,GAAgB,GAAA,CAAI,OAAA,CAAQ,GAAA,EAAK,YAAY,CAAA;AACnD,IAAA,IAAI,kBAAkB,EAAA,EAAI;AAExB,MAAA,MAAA,IAAU,GAAA,CAAI,MAAM,YAAY,CAAA;AAChC,MAAA;AAAA,IACF;AAEA,IAAA,MAAM,GAAA,GAAM,GAAA,CAAI,KAAA,CAAM,YAAA,GAAe,GAAG,aAAa,CAAA;AACrD,IAAA,MAAA,IAAU,OAAA,CAAQ,GAAG,CAAA,IAAK,CAAA,CAAA,EAAI,GAAG,CAAA,CAAA,CAAA;AAEjC,IAAA,QAAA,GAAW,aAAA,GAAgB,CAAA;AAAA,EAC7B;AAEA,EAAA,OAAO,MAAA;AACT;;;;"}
|
|
@@ -9,13 +9,13 @@ require('just-kebab-case');
|
|
|
9
9
|
var loggingUtils = require('../../helpers/loggingUtils.cjs.js');
|
|
10
10
|
require('@backstage/catalog-model');
|
|
11
11
|
var handlers = require('../../service/handlers/handlers.cjs.js');
|
|
12
|
-
var orgUtils = require('./orgUtils.cjs.js');
|
|
13
12
|
var utils = require('./utils.cjs.js');
|
|
14
13
|
|
|
15
14
|
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
|
|
16
15
|
|
|
17
16
|
var gitUrlParse__default = /*#__PURE__*/_interopDefaultCompat(gitUrlParse);
|
|
18
17
|
|
|
18
|
+
const GITHUB_REST_API_MAX_PAGE_SIZE = 100;
|
|
19
19
|
async function validateAndBuildRepoData(githubCredentialsProvider, integrations, config, input) {
|
|
20
20
|
const ghConfig = integrations.github.byUrl(input.repoUrl)?.config;
|
|
21
21
|
if (!ghConfig) {
|
|
@@ -54,51 +54,25 @@ async function searchRepos(octokit, ghSearchQuery, pageNumber = handlers.Default
|
|
|
54
54
|
}) ?? []
|
|
55
55
|
};
|
|
56
56
|
}
|
|
57
|
-
async function addGithubAppRepositories(deps, octokit, credential,
|
|
58
|
-
const
|
|
59
|
-
const pageNumber = reqParams?.pageNumber ?? handlers.DefaultPageNumber;
|
|
60
|
-
const pageSize = reqParams?.pageSize ?? handlers.DefaultPageSize;
|
|
57
|
+
async function addGithubAppRepositories(deps, octokit, credential, repositories, errors, reqParams) {
|
|
58
|
+
const lowercaseSearch = reqParams?.search?.toLocaleLowerCase();
|
|
61
59
|
let totalCount;
|
|
62
60
|
try {
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
)
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
pageSize
|
|
79
|
-
);
|
|
80
|
-
totalCount = searchResp.totalCount;
|
|
81
|
-
searchResp.repositories.forEach(
|
|
82
|
-
(repo) => repositories.set(repo.full_name, repo)
|
|
83
|
-
);
|
|
84
|
-
} else {
|
|
85
|
-
const resp = await octokit.apps.listReposAccessibleToInstallation({
|
|
86
|
-
page: pageNumber,
|
|
87
|
-
per_page: pageSize
|
|
88
|
-
});
|
|
89
|
-
const repos = resp?.data?.repositories ?? resp?.data;
|
|
90
|
-
repos?.forEach((repo) => {
|
|
91
|
-
repositories.set(repo.full_name, {
|
|
92
|
-
name: repo.name,
|
|
93
|
-
full_name: repo.full_name,
|
|
94
|
-
url: repo.url,
|
|
95
|
-
html_url: repo.html_url,
|
|
96
|
-
default_branch: repo.default_branch,
|
|
97
|
-
updated_at: repo.updated_at
|
|
98
|
-
});
|
|
99
|
-
});
|
|
100
|
-
totalCount = resp?.data?.total_count;
|
|
101
|
-
}
|
|
61
|
+
const { repositories: allRepositories } = await listAllRepositoriesAccessibleToInstallation(octokit);
|
|
62
|
+
const filteredRepositories = lowercaseSearch ? allRepositories.filter(
|
|
63
|
+
(repo) => repo.name.toLocaleLowerCase().includes(lowercaseSearch)
|
|
64
|
+
) : allRepositories;
|
|
65
|
+
filteredRepositories.forEach(
|
|
66
|
+
(repo) => repositories.set(repo.full_name, {
|
|
67
|
+
name: repo.name,
|
|
68
|
+
full_name: repo.full_name,
|
|
69
|
+
url: repo.url,
|
|
70
|
+
html_url: repo.html_url,
|
|
71
|
+
default_branch: repo.default_branch,
|
|
72
|
+
updated_at: repo.updated_at
|
|
73
|
+
})
|
|
74
|
+
);
|
|
75
|
+
totalCount = filteredRepositories.length;
|
|
102
76
|
} catch (err) {
|
|
103
77
|
loggingUtils.logErrorIfNeeded(
|
|
104
78
|
deps.logger,
|
|
@@ -113,64 +87,24 @@ async function addGithubAppRepositories(deps, octokit, credential, ghConfig, rep
|
|
|
113
87
|
return { totalCount };
|
|
114
88
|
}
|
|
115
89
|
async function addGithubTokenRepositories(deps, octokit, credential, repositories, errors, reqParams) {
|
|
116
|
-
const
|
|
117
|
-
const pageNumber = reqParams?.pageNumber ?? handlers.DefaultPageNumber;
|
|
118
|
-
const pageSize = reqParams?.pageSize ?? handlers.DefaultPageSize;
|
|
90
|
+
const lowercaseSearch = reqParams?.search?.toLocaleLowerCase();
|
|
119
91
|
let totalCount;
|
|
120
92
|
try {
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
if (orgSearch.length > 0) {
|
|
134
|
-
query += ` ${orgSearch.join(" ")}`;
|
|
135
|
-
}
|
|
136
|
-
const searchResp = await searchRepos(
|
|
137
|
-
octokit,
|
|
138
|
-
query,
|
|
139
|
-
pageNumber,
|
|
140
|
-
pageSize
|
|
141
|
-
);
|
|
142
|
-
totalCount = searchResp.totalCount;
|
|
143
|
-
searchResp.repositories.forEach(
|
|
144
|
-
(repo) => repositories.set(repo.full_name, repo)
|
|
145
|
-
);
|
|
146
|
-
} else {
|
|
147
|
-
const resp = await octokit.rest.repos.listForAuthenticatedUser({
|
|
148
|
-
page: pageNumber,
|
|
149
|
-
per_page: pageSize,
|
|
150
|
-
sort: "full_name",
|
|
151
|
-
direction: "asc"
|
|
152
|
-
});
|
|
153
|
-
resp?.data?.forEach((repo) => {
|
|
154
|
-
repositories.set(repo.full_name, {
|
|
155
|
-
name: repo.name,
|
|
156
|
-
full_name: repo.full_name,
|
|
157
|
-
url: repo.url,
|
|
158
|
-
html_url: repo.html_url,
|
|
159
|
-
default_branch: repo.default_branch,
|
|
160
|
-
updated_at: repo.updated_at
|
|
161
|
-
});
|
|
93
|
+
const allRepositories = await listAllRepositoriesForAuthenticatedUser(octokit);
|
|
94
|
+
const filteredRepositories = lowercaseSearch ? allRepositories.filter(
|
|
95
|
+
(repo) => repo.name.toLocaleLowerCase().includes(lowercaseSearch)
|
|
96
|
+
) : allRepositories;
|
|
97
|
+
filteredRepositories.forEach((repo) => {
|
|
98
|
+
repositories.set(repo.full_name, {
|
|
99
|
+
name: repo.name,
|
|
100
|
+
full_name: repo.full_name,
|
|
101
|
+
url: repo.url,
|
|
102
|
+
html_url: repo.html_url,
|
|
103
|
+
default_branch: repo.default_branch,
|
|
104
|
+
updated_at: repo.updated_at
|
|
162
105
|
});
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
async (lastPageNumber) => octokit.repos.listForAuthenticatedUser({
|
|
166
|
-
page: lastPageNumber,
|
|
167
|
-
per_page: 100
|
|
168
|
-
}).then((lastPageResp) => lastPageResp.data.length),
|
|
169
|
-
"repos.listForAuthenticatedUser",
|
|
170
|
-
resp?.data?.length,
|
|
171
|
-
resp?.headers?.link
|
|
172
|
-
);
|
|
173
|
-
}
|
|
106
|
+
});
|
|
107
|
+
totalCount = filteredRepositories.length;
|
|
174
108
|
} catch (err) {
|
|
175
109
|
utils.handleError(
|
|
176
110
|
deps,
|
|
@@ -261,6 +195,26 @@ async function fileExistsInDefaultBranch(logger, octo, owner, repo, fileName, de
|
|
|
261
195
|
return void 0;
|
|
262
196
|
}
|
|
263
197
|
}
|
|
198
|
+
async function listAllRepositoriesForAuthenticatedUser(octokit) {
|
|
199
|
+
return await octokit.paginate(octokit.rest.repos.listForAuthenticatedUser, {
|
|
200
|
+
per_page: GITHUB_REST_API_MAX_PAGE_SIZE,
|
|
201
|
+
sort: "full_name",
|
|
202
|
+
direction: "asc"
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
async function listAllRepositoriesAccessibleToInstallation(octokit) {
|
|
206
|
+
const repositories = await octokit.paginate(
|
|
207
|
+
octokit.rest.apps.listReposAccessibleToInstallation,
|
|
208
|
+
{
|
|
209
|
+
per_page: GITHUB_REST_API_MAX_PAGE_SIZE
|
|
210
|
+
}
|
|
211
|
+
);
|
|
212
|
+
return {
|
|
213
|
+
repositories,
|
|
214
|
+
total_count: repositories.length,
|
|
215
|
+
repository_selection: repositories.repository_selection ?? "all"
|
|
216
|
+
};
|
|
217
|
+
}
|
|
264
218
|
|
|
265
219
|
exports.addGithubAppRepositories = addGithubAppRepositories;
|
|
266
220
|
exports.addGithubTokenOrgRepositories = addGithubTokenOrgRepositories;
|