@red-hat-developer-hub/backstage-plugin-bulk-import-backend 5.2.2 → 5.4.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.
@@ -1 +1 @@
1
- {"version":3,"file":"prUtils.cjs.js","sources":["../../../src/github/utils/prUtils.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 { LoggerService } from '@backstage/backend-plugin-api';\nimport type { Config } from '@backstage/config';\n\nimport { Octokit } from '@octokit/rest';\n\nimport { getCatalogFilename } from '../../catalog/catalogUtils';\nimport { logErrorIfNeeded } from '../../helpers';\n\nexport async function findOpenPRForBranch(\n logger: LoggerService,\n config: Config,\n octo: Octokit,\n owner: string,\n repo: string,\n branchName: string,\n withCatalogInfoContent: boolean = false,\n): Promise<{\n prNum?: number;\n prUrl?: string;\n prTitle?: string;\n prBody?: string;\n prCatalogInfoContent?: string;\n lastUpdate?: string;\n}> {\n try {\n const response = await octo.rest.pulls.list({\n owner: owner,\n repo: repo,\n state: 'open',\n });\n for (const pull of response.data) {\n if (pull.head.ref === branchName) {\n return {\n prNum: pull.number,\n prUrl: pull.html_url,\n prTitle: pull.title,\n prBody: pull.body ?? undefined,\n prCatalogInfoContent: withCatalogInfoContent\n ? await getCatalogInfoContentFromPR(\n logger,\n config,\n octo,\n owner,\n repo,\n pull.number,\n pull.head.sha,\n )\n : undefined,\n lastUpdate: pull.updated_at,\n };\n }\n }\n } catch (error) {\n logErrorIfNeeded(logger, 'Error fetching pull requests', error);\n }\n return {};\n}\n\nasync function getCatalogInfoContentFromPR(\n logger: LoggerService,\n config: Config,\n octo: Octokit,\n owner: string,\n repo: string,\n prNumber: number,\n prHeadSha: string,\n): Promise<string | undefined> {\n try {\n const filePath = getCatalogFilename(config);\n const fileContentResponse = await octo.rest.repos.getContent({\n owner,\n repo,\n path: filePath,\n ref: prHeadSha,\n });\n if (!fileContentResponse.data) {\n return undefined;\n }\n if (!('content' in fileContentResponse.data)) {\n return undefined;\n }\n return Buffer.from(fileContentResponse.data.content, 'base64').toString(\n 'utf-8',\n );\n } catch (error: any) {\n logErrorIfNeeded(\n logger,\n `Error fetching catalog-info content from PR ${prNumber}`,\n error,\n );\n return undefined;\n }\n}\n\nexport async function closePRWithComment(\n octo: Octokit,\n owner: string,\n repo: string,\n prNum: number,\n comment: string,\n) {\n await octo.rest.issues.createComment({\n owner,\n repo,\n issue_number: prNum,\n body: comment,\n });\n await octo.rest.pulls.update({\n owner,\n repo,\n pull_number: prNum,\n state: 'closed',\n });\n}\n"],"names":["logErrorIfNeeded","getCatalogFilename"],"mappings":";;;;;;;;AAwBsB,eAAA,mBAAA,CACpB,QACA,MACA,EAAA,IAAA,EACA,OACA,IACA,EAAA,UAAA,EACA,yBAAkC,KAQjC,EAAA;AACD,EAAI,IAAA;AACF,IAAA,MAAM,QAAW,GAAA,MAAM,IAAK,CAAA,IAAA,CAAK,MAAM,IAAK,CAAA;AAAA,MAC1C,KAAA;AAAA,MACA,IAAA;AAAA,MACA,KAAO,EAAA;AAAA,KACR,CAAA;AACD,IAAW,KAAA,MAAA,IAAA,IAAQ,SAAS,IAAM,EAAA;AAChC,MAAI,IAAA,IAAA,CAAK,IAAK,CAAA,GAAA,KAAQ,UAAY,EAAA;AAChC,QAAO,OAAA;AAAA,UACL,OAAO,IAAK,CAAA,MAAA;AAAA,UACZ,OAAO,IAAK,CAAA,QAAA;AAAA,UACZ,SAAS,IAAK,CAAA,KAAA;AAAA,UACd,MAAA,EAAQ,KAAK,IAAQ,IAAA,KAAA,CAAA;AAAA,UAC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KACA,EAAA,IAAA,EACA,OACA,OACA,EAAA;AACA,EAAM,MAAA,IAAA,CAAK,IAAK,CAAA,MAAA,CAAO,aAAc,CAAA;AAAA,IACnC,KAAA;AAAA,IACA,IAAA;AAAA,IACA,YAAc,EAAA,KAAA;AAAA,IACd,IAAM,EAAA;AAAA,GACP,CAAA;AACD,EAAM,MAAA,IAAA,CAAK,IAAK,CAAA,KAAA,CAAM,MAAO,CAAA;AAAA,IAC3B,KAAA;AAAA,IACA,IAAA;AAAA,IACA,WAAa,EAAA,KAAA;AAAA,IACb,KAAO,EAAA;AAAA,GACR,CAAA;AACH;;;;;"}
1
+ {"version":3,"file":"prUtils.cjs.js","sources":["../../../src/github/utils/prUtils.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 { LoggerService } from '@backstage/backend-plugin-api';\nimport type { Config } from '@backstage/config';\n\nimport { Octokit } from '@octokit/rest';\n\nimport { getCatalogFilename } from '../../catalog/catalogUtils';\nimport { logErrorIfNeeded } from '../../helpers';\n\nexport async function findOpenPRForBranch(\n logger: LoggerService,\n config: Config,\n octo: Octokit,\n owner: string,\n repo: string,\n branchName: string,\n withCatalogInfoContent: boolean = false,\n): Promise<{\n prNum?: number;\n prUrl?: string;\n prTitle?: string;\n prBody?: string;\n prCatalogInfoContent?: string;\n lastUpdate?: string;\n}> {\n try {\n const response = await octo.rest.pulls.list({\n owner: owner,\n repo: repo,\n state: 'open',\n });\n for (const pull of response.data) {\n if (pull.head.ref === branchName) {\n return {\n prNum: pull.number,\n prUrl: pull.html_url,\n prTitle: pull.title,\n prBody: pull.body ?? undefined,\n prCatalogInfoContent: withCatalogInfoContent\n ? await getCatalogInfoContentFromPR(\n logger,\n config,\n octo,\n owner,\n repo,\n pull.number,\n pull.head.sha,\n )\n : undefined,\n lastUpdate: pull.updated_at,\n };\n }\n }\n } catch (error) {\n logErrorIfNeeded(logger, 'Error fetching pull requests', error);\n }\n return {};\n}\n\nasync function getCatalogInfoContentFromPR(\n logger: LoggerService,\n config: Config,\n octo: Octokit,\n owner: string,\n repo: string,\n prNumber: number,\n prHeadSha: string,\n): Promise<string | undefined> {\n try {\n const filePath = getCatalogFilename(config);\n const fileContentResponse = await octo.rest.repos.getContent({\n owner,\n repo,\n path: filePath,\n ref: prHeadSha,\n });\n if (!fileContentResponse.data) {\n return undefined;\n }\n if (!('content' in fileContentResponse.data)) {\n return undefined;\n }\n return Buffer.from(fileContentResponse.data.content, 'base64').toString(\n 'utf-8',\n );\n } catch (error: any) {\n logErrorIfNeeded(\n logger,\n `Error fetching catalog-info content from PR ${prNumber}`,\n error,\n );\n return undefined;\n }\n}\n\nexport async function closePRWithComment(\n octo: Octokit,\n owner: string,\n repo: string,\n prNum: number,\n comment: string,\n) {\n await octo.rest.issues.createComment({\n owner,\n repo,\n issue_number: prNum,\n body: comment,\n });\n await octo.rest.pulls.update({\n owner,\n repo,\n pull_number: prNum,\n state: 'closed',\n });\n}\n"],"names":["logErrorIfNeeded","getCatalogFilename"],"mappings":";;;;;;;;AAwBsB,eAAA,mBAAA,CACpB,QACA,MACA,EAAA,IAAA,EACA,OACA,IACA,EAAA,UAAA,EACA,yBAAkC,KAQjC,EAAA;AACD,EAAI,IAAA;AACF,IAAA,MAAM,QAAW,GAAA,MAAM,IAAK,CAAA,IAAA,CAAK,MAAM,IAAK,CAAA;AAAA,MAC1C,KAAA;AAAA,MACA,IAAA;AAAA,MACA,KAAO,EAAA;AAAA,KACR,CAAA;AACD,IAAW,KAAA,MAAA,IAAA,IAAQ,SAAS,IAAM,EAAA;AAChC,MAAI,IAA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AAE,CAAA,QAAA;AAAA,MAC7D;AAAA,KACF;AAAA,WACO,KAAY,EAAA;AACnB,IAAAD,6BAAA;AAAA,MACE,MAAA;AAAA,MACA,+CAA+C,QAAQ,CAAA,CAAA;AAAA,MACvD;AAAA,KACF;AACA,IAAO,OAAA,SAAA;AAAA;AAEX;AAEA,eAAsB,kBACpB,CAAA,IAAA,EACA,KACA,EAAA,IAAA,EACA,OACA,OACA,EAAA;AACA,EAAM,MAAA,IAAA,CAAK,IAAK,CAAA,MAAA,CAAO,aAAc,CAAA;AAAA,IACnC,KAAA;AAAA,IACA,IAAA;AAAA,IACA,YAAc,EAAA,KAAA;AAAA,IACd,IAAM,EAAA;AAAA,GACP,CAAA;AACD,EAAM,MAAA,IAAA,CAAK,IAAK,CAAA,KAAA,CAAM,MAAO,CAAA;AAAA,IAC3B,KAAA;AAAA,IACA,IAAA;AAAA,IACA,WAAa,EAAA,KAAA;AAAA,IACb,KAAO,EAAA;AAAA,GACR,CAAA;AACH;;;;;"}
@@ -256,7 +256,7 @@ async function fileExistsInDefaultBranch(logger, octo, owner, repo, fileName, de
256
256
  logger.debug(
257
257
  `Unable to determine if a file named ${fileName} already exists in repo ${repo}: ${error}`
258
258
  );
259
- return void 0;
259
+ return undefined;
260
260
  }
261
261
  }
262
262
  async function createOrUpdateFileInBranch(octo, owner, repo, branchName, fileName, fileContent) {
@@ -1 +1 @@
1
- {"version":3,"file":"repoUtils.cjs.js","sources":["../../../src/github/utils/repoUtils.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 { LoggerService } from '@backstage/backend-plugin-api';\nimport type { Config } from '@backstage/config';\nimport type {\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 } from '../../catalog/catalogUtils';\nimport { logErrorIfNeeded } from '../../helpers';\nimport {\n DefaultPageNumber,\n DefaultPageSize,\n} from '../../service/handlers/handlers';\nimport type { CustomGithubCredentialsProvider } from '../GithubAppManager';\nimport type {\n ExtendedGithubCredentials,\n GithubAppCredentials,\n GithubFetchError,\n GithubRepository,\n} from '../types';\nimport { getAllAppOrgs } from './orgUtils';\nimport {\n computeTotalCountFromGitHubToken,\n createCredentialError,\n handleError,\n} from './utils';\n\nexport type ValidatedRepo = {\n ghConfig: GithubIntegrationConfig;\n credentials: ExtendedGithubCredentials[];\n owner: string;\n repo: string;\n branchName: string;\n};\n\nexport async function validateAndBuildRepoData(\n githubCredentialsProvider: CustomGithubCredentialsProvider,\n integrations: ScmIntegrations,\n config: Config,\n input: {\n repoUrl: string;\n },\n): Promise<ValidatedRepo> {\n const ghConfig = integrations.github.byUrl(input.repoUrl)?.config;\n if (!ghConfig) {\n throw new Error(`Could not find GH integration from ${input.repoUrl}`);\n }\n\n const gitUrl = gitUrlParse(input.repoUrl);\n const owner = gitUrl.organization;\n const repo = gitUrl.name;\n\n const credentials = await githubCredentialsProvider.getAllCredentials({\n host: ghConfig.host,\n });\n if (credentials.length === 0) {\n throw new Error(`No credentials for GH integration`);\n }\n\n const branchName = getBranchName(config);\n return { ghConfig, owner, repo, credentials, branchName };\n}\n\nexport async function searchRepos(\n octokit: Octokit,\n ghSearchQuery: string,\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n): Promise<{ totalCount?: number; repositories: GithubRepository[] }> {\n const repoSearchResp = await octokit.rest.search.repos({\n q: ghSearchQuery,\n order: 'asc',\n page: pageNumber,\n per_page: pageSize,\n });\n return {\n totalCount: repoSearchResp?.data?.total_count,\n repositories:\n repoSearchResp?.data?.items?.map(repo => {\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\n/**\n * Adds the repositories accessible by the provided github app to the provided repositories Map<string, GithubRepository>\n * If any errors occurs, adds them to the provided errors Map<number, GithubFetchError>\n */\nexport async function addGithubAppRepositories(\n deps: {\n logger: LoggerService;\n githubCredentialsProvider: CustomGithubCredentialsProvider;\n },\n octokit: Octokit,\n credential: GithubAppCredentials,\n ghConfig: GithubIntegrationConfig,\n repositories: Map<string, GithubRepository>,\n errors: Map<number, GithubFetchError>,\n reqParams?: {\n search?: string;\n pageNumber?: number;\n pageSize?: number;\n },\n): Promise<{ totalCount?: number }> {\n const search = reqParams?.search;\n const pageNumber = reqParams?.pageNumber ?? DefaultPageNumber;\n const pageSize = reqParams?.pageSize ?? DefaultPageSize;\n let totalCount: number | undefined;\n try {\n if (search) {\n const allOrgsMap = await getAllAppOrgs(\n deps.githubCredentialsProvider,\n ghConfig,\n credential.accountLogin,\n );\n const orgSearch: string[] = [];\n for (const [_orgUrl, ghOrg] of allOrgsMap) {\n orgSearch.push(`org:${ghOrg.name}`);\n }\n const query = `${search} in:name ${orgSearch.join(' ')}`;\n const searchResp = await searchRepos(\n octokit,\n query,\n pageNumber,\n pageSize,\n );\n totalCount = searchResp.totalCount;\n searchResp.repositories.forEach(repo =>\n repositories.set(repo.full_name, repo),\n );\n } else {\n const resp = await octokit.apps.listReposAccessibleToInstallation({\n page: pageNumber,\n per_page: pageSize,\n });\n const repos = resp?.data?.repositories ?? resp?.data;\n repos?.forEach(repo => {\n repositories.set(repo.full_name, {\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 totalCount = resp?.data?.total_count;\n }\n } catch (err: any) {\n logErrorIfNeeded(\n deps.logger,\n `Fetching repositories with access token for github app ${credential.appId}`,\n err,\n );\n const credentialError = createCredentialError(credential, err as Error);\n if (credentialError) {\n errors.set(credential.appId, credentialError);\n }\n }\n return { totalCount };\n}\n\n/**\n * Adds the user or organization repositories accessible by the github token to the provided repositories Map<string, GithubRepository> if they're owned by the specified owner\n * If any errors occurs, adds them to the provided errors Map<number, GithubFetchError>\n */\nexport async function addGithubTokenRepositories(\n deps: {\n logger: LoggerService;\n },\n octokit: Octokit,\n credential: GithubCredentials,\n repositories: Map<string, GithubRepository>,\n errors: Map<number, GithubFetchError>,\n reqParams?: {\n search?: string;\n pageNumber?: number;\n pageSize?: number;\n },\n): Promise<{ totalCount?: number }> {\n const search = reqParams?.search;\n const pageNumber = reqParams?.pageNumber ?? DefaultPageNumber;\n const pageSize = reqParams?.pageSize ?? DefaultPageSize;\n let totalCount: number | undefined;\n try {\n if (search) {\n // Get currently authenticated user\n const username = (await octokit.rest.users.getAuthenticated())?.data\n ?.login;\n let query = `${search} in:name user:${username}`;\n\n const allOrgsResp = await octokit.paginate(\n octokit.rest.orgs.listForAuthenticatedUser,\n {\n sort: 'full_name',\n direction: 'asc',\n },\n );\n const orgSearch: string[] = [];\n allOrgsResp?.forEach(org => orgSearch.push(`org:${org.login}`));\n if (orgSearch.length > 0) {\n query += ` ${orgSearch.join(' ')}`;\n }\n\n const searchResp = await searchRepos(\n octokit,\n query,\n pageNumber,\n pageSize,\n );\n totalCount = searchResp.totalCount;\n searchResp.repositories.forEach(repo =>\n repositories.set(repo.full_name, repo),\n );\n } else {\n /**\n * The listForAuthenticatedUser endpoint will grab all the repositories the github token has explicit access to.\n * These would include repositories they own, repositories where they are a collaborator,\n * and repositories that they can access through an organization membership.\n */\n const resp = await octokit.rest.repos.listForAuthenticatedUser({\n page: pageNumber,\n per_page: pageSize,\n sort: 'full_name',\n direction: 'asc',\n });\n resp?.data?.forEach(repo => {\n repositories.set(repo.full_name, {\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 totalCount = await computeTotalCountFromGitHubToken(\n deps,\n async (lastPageNumber: number) =>\n octokit.repos\n .listForAuthenticatedUser({\n page: lastPageNumber,\n per_page: 100,\n })\n .then(lastPageResp => lastPageResp.data.length),\n 'repos.listForAuthenticatedUser',\n resp?.data?.length,\n resp?.headers?.link,\n );\n }\n } catch (err) {\n handleError(\n deps,\n 'Fetching repositories with token from token',\n credential,\n errors,\n err,\n );\n }\n return { totalCount };\n}\n\nexport async function addGithubTokenOrgRepositories(\n deps: {\n logger: LoggerService;\n },\n octokit: Octokit,\n credential: GithubCredentials,\n org: string,\n repositories: Map<string, GithubRepository>,\n errors: Map<number, GithubFetchError>,\n reqParams?: {\n search?: string;\n pageNumber?: number;\n pageSize?: number;\n },\n): Promise<{ totalCount?: number }> {\n const search = reqParams?.search;\n const pageNumber = reqParams?.pageNumber ?? DefaultPageNumber;\n const pageSize = reqParams?.pageSize ?? DefaultPageSize;\n let totalCount: number | undefined;\n try {\n if (search) {\n const query = `${search} in:name org:${org}`;\n const searchResp = await searchRepos(\n octokit,\n query,\n pageNumber,\n pageSize,\n );\n totalCount = searchResp.totalCount;\n searchResp.repositories.forEach(repo =>\n repositories.set(repo.full_name, repo),\n );\n } else {\n /**\n * The listForAuthenticatedUser endpoint will grab all the repositories the github token has explicit access to.\n * These would include repositories they own, repositories where they are a collaborator,\n * and repositories that they can access through an organization membership.\n */\n const resp = await octokit.rest.repos.listForOrg({\n org,\n page: pageNumber,\n per_page: pageSize,\n sort: 'full_name',\n direction: 'asc',\n });\n resp?.data?.forEach(repo => {\n const githubRepo: GithubRepository = {\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 ?? 'main',\n updated_at: repo.updated_at,\n };\n repositories.set(githubRepo.full_name, githubRepo);\n });\n\n totalCount = await computeTotalCountFromGitHubToken(\n deps,\n async (lastPageNumber: number) =>\n octokit.repos\n .listForOrg({\n org,\n page: lastPageNumber,\n per_page: 100,\n })\n .then(lastPageResp => lastPageResp.data.length),\n 'repos.listForOrg',\n resp?.data?.length,\n resp?.headers?.link,\n );\n }\n } catch (err) {\n handleError(\n deps,\n 'Fetching org repositories with token from token',\n credential,\n errors,\n err,\n );\n }\n return { totalCount };\n}\n\nexport async function fileExistsInDefaultBranch(\n logger: LoggerService,\n octo: Octokit,\n owner: string,\n repo: string,\n fileName: string,\n defaultBranch: string = 'main',\n) {\n try {\n await octo.rest.repos.getContent({\n owner,\n repo,\n path: fileName,\n ref: defaultBranch,\n });\n return true;\n } catch (error: any) {\n if (error.status === 404) {\n return false;\n }\n logger.debug(\n `Unable to determine if a file named ${fileName} already exists in repo ${repo}: ${error}`,\n );\n return undefined;\n }\n}\n\nexport async function createOrUpdateFileInBranch(\n octo: Octokit,\n owner: string,\n repo: string,\n branchName: string,\n fileName: string,\n fileContent: string,\n): Promise<void> {\n try {\n const { data: existingFile } = await octo.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 octo.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 octo.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"],"names":["gitUrlParse","getBranchName","DefaultPageNumber","DefaultPageSize","getAllAppOrgs","logErrorIfNeeded","createCredentialError","computeTotalCountFromGitHubToken","handle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IAAK,CAAA,IAAA,CAAK,MAAM,UAAW,CAAA;AAAA,MAC9D,KAAA;AAAA,MACA,IAAA;AAAA,MACA,IAAM,EAAA,QAAA;AAAA,MACN,GAAK,EAAA;AAAA,KACN,CAAA;AAED,IAAA,IAAI,MAAM,OAAQ,CAAA,YAAY,CAAK,IAAA,EAAE,SAAS,YAAe,CAAA,EAAA;AAC3D,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,uBAAuB,QAAQ,CAAA,+EAAA;AAAA,OACjC;AAAA;AAGF,IAAM,MAAA,IAAA,CAAK,IAAK,CAAA,KAAA,CAAM,0BAA2B,CAAA;AAAA,MAC/C,KAAA;AAAA,MACA,IAAA;AAAA,MACA,IAAM,EAAA,QAAA;AAAA,MACN,OAAA,EAAS,OAAO,QAAQ,CAAA,YAAA,CAAA;AAAA,MACxB,OAAA,EAAS,KAAK,WAAW,CAAA;AAAA,MACzB,KAAK,YAAa,CAAA,GAAA;AAAA,MAClB,MAAQ,EAAA;AAAA,KACT,CAAA;AAAA,WACM,KAAY,EAAA;AACnB,IAAI,IAAA,KAAA,CAAM,WAAW,GAAK,EAAA;AAExB,MAAM,MAAA,IAAA,CAAK,IAAK,CAAA,KAAA,CAAM,0BAA2B,CAAA;AAAA,QAC/C,KAAA;AAAA,QACA,IAAA;AAAA,QACA,IAAM,EAAA,QAAA;AAAA,QACN,OAAA,EAAS,OAAO,QAAQ,CAAA,YAAA,CAAA;AAAA,QACxB,OAAA,EAAS,KAAK,WAAW,CAAA;AAAA,QACzB,MAAQ,EAAA;AAAA,OACT,CAAA;AAAA,KACI,MAAA;AACL,MAAM,MAAA,KAAA;AAAA;AACR;AAEJ;;;;;;;;;;"}
1
+ {"version":3,"file":"repoUtils.cjs.js","sources":["../../../src/github/utils/repoUtils.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 { LoggerService } from '@backstage/backend-plugin-api';\nimport type { Config } from '@backstage/config';\nimport type {\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 } from '../../catalog/catalogUtils';\nimport { logErrorIfNeeded } from '../../helpers';\nimport {\n DefaultPageNumber,\n DefaultPageSize,\n} from '../../service/handlers/handlers';\nimport type { CustomGithubCredentialsProvider } from '../GithubAppManager';\nimport type {\n ExtendedGithubCredentials,\n GithubAppCredentials,\n GithubFetchError,\n GithubRepository,\n} from '../types';\nimport { getAllAppOrgs } from './orgUtils';\nimport {\n computeTotalCountFromGitHubToken,\n createCredentialError,\n handleError,\n} from './utils';\n\nexport type ValidatedRepo = {\n ghConfig: GithubIntegrationConfig;\n credentials: ExtendedGithubCredentials[];\n owner: string;\n repo: string;\n branchName: string;\n};\n\nexport async function validateAndBuildRepoData(\n githubCredentialsProvider: CustomGithubCredentialsProvider,\n integrations: ScmIntegrations,\n config: Config,\n input: {\n repoUrl: string;\n },\n): Promise<ValidatedRepo> {\n const ghConfig = integrations.github.byUrl(input.repoUrl)?.config;\n if (!ghConfig) {\n throw new Error(`Could not find GH integration from ${input.repoUrl}`);\n }\n\n const gitUrl = gitUrlParse(input.repoUrl);\n const owner = gitUrl.organization;\n const repo = gitUrl.name;\n\n const credentials = await githubCredentialsProvider.getAllCredentials({\n host: ghConfig.host,\n });\n if (credentials.length === 0) {\n throw new Error(`No credentials for GH integration`);\n }\n\n const branchName = getBranchName(config);\n return { ghConfig, owner, repo, credentials, branchName };\n}\n\nexport async function searchRepos(\n octokit: Octokit,\n ghSearchQuery: string,\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n): Promise<{ totalCount?: number; repositories: GithubRepository[] }> {\n const repoSearchResp = await octokit.rest.search.repos({\n q: ghSearchQuery,\n order: 'asc',\n page: pageNumber,\n per_page: pageSize,\n });\n return {\n totalCount: repoSearchResp?.data?.total_count,\n repositories:\n repoSearchResp?.data?.items?.map(repo => {\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\n/**\n * Adds the repositories accessible by the provided github app to the provided repositories Map<string, GithubRepository>\n * If any errors occurs, adds them to the provided errors Map<number, GithubFetchError>\n */\nexport async function addGithubAppRepositories(\n deps: {\n logger: LoggerService;\n githubCredentialsProvider: CustomGithubCredentialsProvider;\n },\n octokit: Octokit,\n credential: GithubAppCredentials,\n ghConfig: GithubIntegrationConfig,\n repositories: Map<string, GithubRepository>,\n errors: Map<number, GithubFetchError>,\n reqParams?: {\n search?: string;\n pageNumber?: number;\n pageSize?: number;\n },\n): Promise<{ totalCount?: number }> {\n const search = reqParams?.search;\n const pageNumber = reqParams?.pageNumber ?? DefaultPageNumber;\n const pageSize = reqParams?.pageSize ?? DefaultPageSize;\n let totalCount: number | undefined;\n try {\n if (search) {\n const allOrgsMap = await getAllAppOrgs(\n deps.githubCredentialsProvider,\n ghConfig,\n credential.accountLogin,\n );\n const orgSearch: string[] = [];\n for (const [_orgUrl, ghOrg] of allOrgsMap) {\n orgSearch.push(`org:${ghOrg.name}`);\n }\n const query = `${search} in:name ${orgSearch.join(' ')}`;\n const searchResp = await searchRepos(\n octokit,\n query,\n pageNumber,\n pageSize,\n );\n totalCount = searchResp.totalCount;\n searchResp.repositories.forEach(repo =>\n repositories.set(repo.full_name, repo),\n );\n } else {\n const resp = await octokit.apps.listReposAccessibleToInstallation({\n page: pageNumber,\n per_page: pageSize,\n });\n const repos = resp?.data?.repositories ?? resp?.data;\n repos?.forEach(repo => {\n repositories.set(repo.full_name, {\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 totalCount = resp?.data?.total_count;\n }\n } catch (err: any) {\n logErrorIfNeeded(\n deps.logger,\n `Fetching repositories with access token for github app ${credential.appId}`,\n err,\n );\n const credentialError = createCredentialError(credential, err as Error);\n if (credentialError) {\n errors.set(credential.appId, credentialError);\n }\n }\n return { totalCount };\n}\n\n/**\n * Adds the user or organization repositories accessible by the github token to the provided repositories Map<string, GithubRepository> if they're owned by the specified owner\n * If any errors occurs, adds them to the provided errors Map<number, GithubFetchError>\n */\nexport async function addGithubTokenRepositories(\n deps: {\n logger: LoggerService;\n },\n octokit: Octokit,\n credential: GithubCredentials,\n repositories: Map<string, GithubRepository>,\n errors: Map<number, GithubFetchError>,\n reqParams?: {\n search?: string;\n pageNumber?: number;\n pageSize?: number;\n },\n): Promise<{ totalCount?: number }> {\n const search = reqParams?.search;\n const pageNumber = reqParams?.pageNumber ?? DefaultPageNumber;\n const pageSize = reqParams?.pageSize ?? DefaultPageSize;\n let totalCount: number | undefined;\n try {\n if (search) {\n // Get currently authenticated user\n const username = (await octokit.rest.users.getAuthenticated())?.data\n ?.login;\n let query = `${search} in:name user:${username}`;\n\n const allOrgsResp = await octokit.paginate(\n octokit.rest.orgs.listForAuthenticatedUser,\n {\n sort: 'full_name',\n direction: 'asc',\n },\n );\n const orgSearch: string[] = [];\n allOrgsResp?.forEach(org => orgSearch.push(`org:${org.login}`));\n if (orgSearch.length > 0) {\n query += ` ${orgSearch.join(' ')}`;\n }\n\n const searchResp = await searchRepos(\n octokit,\n query,\n pageNumber,\n pageSize,\n );\n totalCount = searchResp.totalCount;\n searchResp.repositories.forEach(repo =>\n repositories.set(repo.full_name, repo),\n );\n } else {\n /**\n * The listForAuthenticatedUser endpoint will grab all the repositories the github token has explicit access to.\n * These would include repositories they own, repositories where they are a collaborator,\n * and repositories that they can access through an organization membership.\n */\n const resp = await octokit.rest.repos.listForAuthenticatedUser({\n page: pageNumber,\n per_page: pageSize,\n sort: 'full_name',\n direction: 'asc',\n });\n resp?.data?.forEach(repo => {\n repositories.set(repo.full_name, {\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 totalCount = await computeTotalCountFromGitHubToken(\n deps,\n async (lastPageNumber: number) =>\n octokit.repos\n .listForAuthenticatedUser({\n page: lastPageNumber,\n per_page: 100,\n })\n .then(lastPageResp => lastPageResp.data.length),\n 'repos.listForAuthenticatedUser',\n resp?.data?.length,\n resp?.headers?.link,\n );\n }\n } catch (err) {\n handleError(\n deps,\n 'Fetching repositories with token from token',\n credential,\n errors,\n err,\n );\n }\n return { totalCount };\n}\n\nexport async function addGithubTokenOrgRepositories(\n deps: {\n logger: LoggerService;\n },\n octokit: Octokit,\n credential: GithubCredentials,\n org: string,\n repositories: Map<string, GithubRepository>,\n errors: Map<number, GithubFetchError>,\n reqParams?: {\n search?: string;\n pageNumber?: number;\n pageSize?: number;\n },\n): Promise<{ totalCount?: number }> {\n const search = reqParams?.search;\n const pageNumber = reqParams?.pageNumber ?? DefaultPageNumber;\n const pageSize = reqParams?.pageSize ?? DefaultPageSize;\n let totalCount: number | undefined;\n try {\n if (search) {\n const query = `${search} in:name org:${org}`;\n const searchResp = await searchRepos(\n octokit,\n query,\n pageNumber,\n pageSize,\n );\n totalCount = searchResp.totalCount;\n searchResp.repositories.forEach(repo =>\n repositories.set(repo.full_name, repo),\n );\n } else {\n /**\n * The listForAuthenticatedUser endpoint will grab all the repositories the github token has explicit access to.\n * These would include repositories they own, repositories where they are a collaborator,\n * and repositories that they can access through an organization membership.\n */\n const resp = await octokit.rest.repos.listForOrg({\n org,\n page: pageNumber,\n per_page: pageSize,\n sort: 'full_name',\n direction: 'asc',\n });\n resp?.data?.forEach(repo => {\n const githubRepo: GithubRepository = {\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 ?? 'main',\n updated_at: repo.updated_at,\n };\n repositories.set(githubRepo.full_name, githubRepo);\n });\n\n totalCount = await computeTotalCountFromGitHubToken(\n deps,\n async (lastPageNumber: number) =>\n octokit.repos\n .listForOrg({\n org,\n page: lastPageNumber,\n per_page: 100,\n })\n .then(lastPageResp => lastPageResp.data.length),\n 'repos.listForOrg',\n resp?.data?.length,\n resp?.headers?.link,\n );\n }\n } catch (err) {\n handleError(\n deps,\n 'Fetching org repositories with token from token',\n credential,\n errors,\n err,\n );\n }\n return { totalCount };\n}\n\nexport async function fileExistsInDefaultBranch(\n logger: LoggerService,\n octo: Octokit,\n owner: string,\n repo: string,\n fileName: string,\n defaultBranch: string = 'main',\n) {\n try {\n await octo.rest.repos.getContent({\n owner,\n repo,\n path: fileName,\n ref: defaultBranch,\n });\n return true;\n } catch (error: any) {\n if (error.status === 404) {\n return false;\n }\n logger.debug(\n `Unable to determine if a file named ${fileName} already exists in repo ${repo}: ${error}`,\n );\n return undefined;\n }\n}\n\nexport async function createOrUpdateFileInBranch(\n octo: Octokit,\n owner: string,\n repo: string,\n branchName: string,\n fileName: string,\n fileContent: string,\n): Promise<void> {\n try {\n const { data: existingFile } = await octo.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 octo.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 octo.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"],"names":["gitUrlParse","getBranchName","DefaultPageNumber","DefaultPageSize","getAllAppOrgs","logErrorIfNeeded","createCredentialError","computeTotalCountFromGitHubToken","handleError"],"mappings":";;;;;;;;;;;;;;;;AAuDA,eAAsB,wBACpB,CAAA,yBAAA,EACA,YACA,EAAA,MAAA,EACA,KAGwB,EAAA;AACxB,EAAA,MAAM,WAAW,YAAa,CAAA,MAAA,CAAO,KAAM,CAAA,KAAA,CAAM,OAAO,CAAG,EAAA,MAAA;AAC3D,EAAA,IAAI,CAAC,QAAU,EAAA;AACb,IAAA,MAAM,IAAI,KAAA,CAAM,CAAsC,mCAAA,EAAA,KAAA,CAAM,OAAO,CAAE,CAAA,CAAA;AAAA;AAGvE,EAAM,MAAA,MAAA,GAASA,4BAAY,CAAA,KAAA,CAAM,OAAO,CAAA;AACxC,EAAA,MAAM,QAAQ,MAAO,CAAA,YAAA;AACrB,EAAA,MAAM,OAAO,MAAO,CAAA,IAAA;AAEpB,EAAM,MAAA,WAAA,GAAc,MAAM,yBAAA,CAA0B,iBAAkB,CAAA;AAAA,IACpE,MAAM,QAAS,CAAA;AAAA,GAChB,CAAA;AACD,EAAI,IAAA,WAAA,CAAY,WAAW,CAAG,EAAA;AAC5B,IAAM,MAAA,IAAI,MAAM,CAAmC,iCAAA,CAAA,CAAA;AAAA;AAGrD,EAAM,MAAA,UAAA,GAAaC,2BAAc,MAAM,CAAA;AACvC,EAAA,OAAO,EAAE,QAAA,EAAU,KAAO,EAAA,IAAA,EAAM,aAAa,UAAW,EAAA;AAC1D;AAEA,eAAsB,YACpB,OACA,EAAA,aAAA,EACA,UAAqB,GAAAC,0BAAA,EACrB,WAAmBC,wBACiD,EAAA;AACpE,EAAA,MAAM,cAAiB,GAAA,MAAM,OAAQ,CAAA,IAAA,CAAK,OAAO,KAAM,CAAA;AAAA,IACrD,CAAG,EAAA,aAAA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7 @@ function createCredentialError(credential, err) {
43
43
  }
44
44
  };
45
45
  }
46
- return void 0;
46
+ return undefined;
47
47
  }
48
48
  function verifyAndGetIntegrations(deps, integrations) {
49
49
  const ghConfigs = integrations.github.list().map((ghInt) => ghInt.config);
@@ -103,7 +103,7 @@ async function computeTotalCountFromGitHubToken(deps, lastPageDataLengthProvider
103
103
  }
104
104
  const lastPageNumber = parseInt(match[1], 10);
105
105
  const lastPageDataLength = await lastPageDataLengthProviderFn(lastPageNumber);
106
- return pageSize ? (lastPageNumber - 1) * pageSize + lastPageDataLength : void 0;
106
+ return pageSize ? (lastPageNumber - 1) * pageSize + lastPageDataLength : undefined;
107
107
  }
108
108
  async function executeFunctionOnFirstSuccessfulIntegration(deps, integrations, params) {
109
109
  const validatedRepo = await repoUtils.validateAndBuildRepoData(
@@ -130,7 +130,7 @@ async function executeFunctionOnFirstSuccessfulIntegration(deps, integrations, p
130
130
  }
131
131
  return res.result;
132
132
  }
133
- return void 0;
133
+ return undefined;
134
134
  }
135
135
  async function fetchFromAllIntegrations(deps, integrations, params) {
136
136
  const ghConfigs = verifyAndGetIntegrations(deps, integrations);
@@ -1 +1 @@
1
- {"version":3,"file":"utils.cjs.js","sources":["../../../src/github/utils/utils.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 ScmIntegrations,\n type GithubIntegrationConfig,\n} from '@backstage/integration';\n\nimport { Octokit } from '@octokit/rest';\nimport gitUrlParse from 'git-url-parse';\n\nimport { logErrorIfNeeded } from '../../helpers';\nimport type { CustomGithubCredentialsProvider } from '../GithubAppManager';\nimport {\n isGithubAppCredential,\n type ExtendedGithubCredentials,\n type GithubFetchError,\n} from '../types';\nimport { buildOcto } from './ghUtils';\nimport { validateAndBuildRepoData, ValidatedRepo } from './repoUtils';\n\n/**\n * Creates the GithubFetchError to be stored in the returned errors array of the returned GithubRepositoryResponse object\n */\nexport function createCredentialError(\n credential: ExtendedGithubCredentials,\n err?: Error,\n): GithubFetchError | undefined {\n if (err) {\n if (isGithubAppCredential(credential)) {\n return {\n appId: credential.appId,\n type: 'app',\n error: {\n name: err.name,\n message: err.message,\n },\n };\n }\n return {\n type: 'token',\n error: {\n name: err.name,\n message: err.message,\n },\n };\n }\n if ('error' in credential) {\n return {\n appId: credential.appId,\n type: 'app',\n error: {\n name: credential.error.name,\n message: credential.error.message,\n },\n };\n }\n return undefined;\n}\n\nexport function verifyAndGetIntegrations(\n deps: {\n logger: LoggerService;\n },\n\n integrations: ScmIntegrations,\n) {\n const ghConfigs = integrations.github.list().map(ghInt => ghInt.config);\n if (ghConfigs.length === 0) {\n deps.logger.debug(\n 'No GitHub Integration in config => returning an empty list of repositories.',\n );\n throw new Error(\n \"Looks like there is no GitHub Integration in config. Please add a configuration entry under 'integrations.github\",\n );\n }\n return ghConfigs;\n}\n\nexport async function getCredentialsFromIntegrations(\n githubCredentialsProvider: CustomGithubCredentialsProvider,\n ghConfigs: GithubIntegrationConfig[],\n) {\n const credentialsByConfig = new Map<\n GithubIntegrationConfig,\n ExtendedGithubCredentials[]\n >();\n for (const ghConfig of ghConfigs) {\n const creds = await getCredentialsForConfig(\n githubCredentialsProvider,\n ghConfig,\n );\n credentialsByConfig.set(ghConfig, creds);\n }\n return credentialsByConfig;\n}\n\nexport async function getCredentialsForConfig(\n githubCredentialsProvider: CustomGithubCredentialsProvider,\n ghConfig: GithubIntegrationConfig,\n) {\n return await githubCredentialsProvider.getAllCredentials({\n host: ghConfig.host,\n });\n}\n\nexport async function extractConfigAndCreds(\n githubCredentialsProvider: CustomGithubCredentialsProvider,\n integrations: ScmIntegrations,\n input: {\n repoUrl: string;\n defaultBranch?: string;\n },\n) {\n const ghConfig = integrations.github.byUrl(input.repoUrl)?.config;\n if (!ghConfig) {\n throw new Error(`Could not find GH integration from ${input.repoUrl}`);\n }\n\n const credentials = await githubCredentialsProvider.getAllCredentials({\n host: ghConfig.host,\n });\n if (credentials.length === 0) {\n throw new Error(`No credentials for GH integration`);\n }\n\n const gitUrl = gitUrlParse(input.repoUrl);\n return { ghConfig, credentials, gitUrl };\n}\n\nexport function handleError(\n deps: {\n logger: LoggerService;\n },\n desc: string,\n credential: ExtendedGithubCredentials,\n errors: Map<number, GithubFetchError>,\n err: any,\n) {\n logErrorIfNeeded(deps.logger, `${desc} failed`, err);\n const credentialError = createCredentialError(credential, err as Error);\n if (credentialError) {\n errors.set(-1, credentialError);\n }\n}\n\nexport async function computeTotalCountFromGitHubToken(\n deps: {\n logger: LoggerService;\n },\n lastPageDataLengthProviderFn: (lastPageNumber: number) => Promise<number>,\n ghApiName: string,\n pageSize?: number,\n linkHeader?: string,\n): Promise<number | undefined> {\n // There is no direct way to get the total count of repositories other than using octokit.paginate,\n // but will make us retrieve all pages, thus increasing our response time.\n // Workaround here is to analyze the headers, and get the link to the last page.\n if (!linkHeader) {\n deps.logger.debug(\n `No link header found in response from ${ghApiName} GH endpoint => returning current page size`,\n );\n return pageSize;\n }\n const lastPageLink = linkHeader\n .split(',')\n .find(s => s.includes('rel=\"last\"'));\n if (!lastPageLink) {\n deps.logger.debug(\n `No rel='last' link found in response headers from ${ghApiName} GH endpoint => returning current page size`,\n );\n return pageSize;\n }\n const match = lastPageLink.match(/page=(\\d+)/);\n if (!match || match.length < 2) {\n deps.logger.debug(\n `Unable to extract page number from rel='last' link found in response headers from ${ghApiName} GH endpoint => returning current page size`,\n );\n return pageSize;\n }\n\n const lastPageNumber = parseInt(match[1], 10);\n // Fetch the last page to count its items, as it might contain fewer than the requested size\n const lastPageDataLength = await lastPageDataLengthProviderFn(lastPageNumber);\n return pageSize\n ? (lastPageNumber - 1) * pageSize + lastPageDataLength\n : undefined;\n}\n\nexport async function executeFunctionOnFirstSuccessfulIntegration<T>(\n deps: {\n logger: LoggerService;\n cache: CacheService;\n config: Config;\n githubCredentialsProvider: CustomGithubCredentialsProvider;\n },\n integrations: ScmIntegrations,\n params: {\n repoUrl: string;\n fn: (\n validatedRepo: ValidatedRepo,\n octo: Octokit,\n ) => Promise<{ successful: boolean; result?: T }>;\n },\n) {\n const validatedRepo = await validateAndBuildRepoData(\n deps.githubCredentialsProvider,\n integrations,\n deps.config,\n params,\n );\n for (const credential of validatedRepo.credentials) {\n const octo = buildOcto(\n {\n logger: deps.logger,\n cache: deps.cache,\n },\n { credential, owner: validatedRepo.owner },\n validatedRepo.ghConfig.apiBaseUrl,\n );\n if (!octo) {\n continue;\n }\n const res = await params.fn(validatedRepo, octo);\n if (!res.successful) {\n continue;\n }\n return res.result;\n }\n return undefined;\n}\n\nexport async function fetchFromAllIntegrations<T>(\n deps: {\n logger: LoggerService;\n cache: CacheService;\n githubCredentialsProvider: CustomGithubCredentialsProvider;\n },\n integrations: ScmIntegrations,\n params: {\n dataFetcher: (\n octo: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => Promise<{\n stopFetchingData?: boolean;\n result?: T;\n errors?: GithubFetchError[];\n }>;\n },\n) {\n const ghConfigs = verifyAndGetIntegrations(deps, integrations);\n\n const credentialsByConfig = await getCredentialsFromIntegrations(\n deps.githubCredentialsProvider,\n ghConfigs,\n );\n const errors = new Map<number, GithubFetchError>();\n const data: T[] = [];\n const dataErrs: GithubFetchError[] = [];\n let stopFetchingData: boolean | undefined = false;\n for (const [ghConfig, credentials] of credentialsByConfig) {\n if (stopFetchingData) {\n break;\n }\n deps.logger.debug(\n `Got ${credentials.length} credential(s) for ${ghConfig.host}`,\n );\n for (const credential of credentials) {\n const octokit = buildOcto(\n deps,\n { credential, errors },\n ghConfig.apiBaseUrl,\n );\n if (!octokit) {\n continue;\n }\n const res = await params.dataFetcher(octokit, credential, ghConfig);\n res.errors?.forEach(err => dataErrs.push(err));\n\n if (res.result) {\n data.push(res.result);\n }\n\n stopFetchingData = res.stopFetchingData;\n }\n }\n\n const aggregatedErrors = new Map<number, GithubFetchError>();\n errors.forEach((err, num) => aggregatedErrors.set(num, err));\n dataErrs.forEach((err, idx) => aggregatedErrors.set(idx, err));\n\n return { data, errors: aggregatedErrors };\n}\n\nexport function computeTotalCount<T>(\n data: T[],\n countList: number[],\n pageSize: number,\n) {\n let totalCount = countList.reduce(\n (accumulator, currentValue) => accumulator + currentValue,\n 0,\n );\n if (totalCount < pageSize) {\n totalCount = data.length;\n }\n return totalCount;\n}\n\nexport function extractLocationOwnerMap(locationUrls: string[]) {\n const locationGitOwnerMap = new Map<string, string>();\n for (const locationUrl of locationUrls) {\n const split = locationUrl.split('/blob/');\n if (split.length < 2) {\n continue;\n }\n locationGitOwnerMap.set(locationUrl, gitUrlParse(split[0]).owner);\n }\n return locationGitOwnerMap;\n}\n"],"names":["isGithubAppCredential","logErrorIfNeeded","validateAndBuildRepoData","buildOcto","gitUrlParse"],"mappings":";;;;;;;;;;;;;;;AA0CgB,SAAA,qBAAA,CACd,YACA,GAC8B,EAAA;AAC9B,EAAA,IAAI,GAAK,EAAA;AACP,IAAI,IAAAA,2BAAA,CAAsB,UAAU,CAAG,EAAA;AACrC,MAAO,OAAA;AAAA,QACL,OAAO,UAAW,CAAA,KAAA;AAAA,QAClB,IAAM,EAAA,KAAA;AAAA,QACN,KAAO,EAAA;AAAA,UACL,MAAM,GAAI,CAAA,IAAA;AAAA,UACV,SAAS,GAAI,CAAA;AAAA;AACf,OACF;AAAA;AAEF,IAAO,OAAA;AAAA,MACL,IAAM,EAAA,OAAA;AAAA,MACN,KAAO,EAAA;AAAA,QACL,MAAM,GAAI,CAAA,IAAA;AAAA,QACV,SAAS,GAAI,C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AiB,WAAc,GAAA,YAAA;AAAA,IAC7C;AAAA,GACF;AACA,EAAA,IAAI,aAAa,QAAU,EAAA;AACzB,IAAA,UAAA,GAAa,IAAK,CAAA,MAAA;AAAA;AAEpB,EAAO,OAAA,UAAA;AACT;AAEO,SAAS,wBAAwB,YAAwB,EAAA;AAC9D,EAAM,MAAA,mBAAA,uBAA0B,GAAoB,EAAA;AACpD,EAAA,KAAA,MAAW,eAAe,YAAc,EAAA;AACtC,IAAM,MAAA,KAAA,GAAQ,WAAY,CAAA,KAAA,CAAM,QAAQ,CAAA;AACxC,IAAI,IAAA,KAAA,CAAM,SAAS,CAAG,EAAA;AACpB,MAAA;AAAA;AAEF,IAAA,mBAAA,CAAoB,IAAI,WAAa,EAAAC,4BAAA,CAAY,MAAM,CAAC,CAAC,EAAE,KAAK,CAAA;AAAA;AAElE,EAAO,OAAA,mBAAA;AACT;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"utils.cjs.js","sources":["../../../src/github/utils/utils.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 ScmIntegrations,\n type GithubIntegrationConfig,\n} from '@backstage/integration';\n\nimport { Octokit } from '@octokit/rest';\nimport gitUrlParse from 'git-url-parse';\n\nimport { logErrorIfNeeded } from '../../helpers';\nimport type { CustomGithubCredentialsProvider } from '../GithubAppManager';\nimport {\n isGithubAppCredential,\n type ExtendedGithubCredentials,\n type GithubFetchError,\n} from '../types';\nimport { buildOcto } from './ghUtils';\nimport { validateAndBuildRepoData, ValidatedRepo } from './repoUtils';\n\n/**\n * Creates the GithubFetchError to be stored in the returned errors array of the returned GithubRepositoryResponse object\n */\nexport function createCredentialError(\n credential: ExtendedGithubCredentials,\n err?: Error,\n): GithubFetchError | undefined {\n if (err) {\n if (isGithubAppCredential(credential)) {\n return {\n appId: credential.appId,\n type: 'app',\n error: {\n name: err.name,\n message: err.message,\n },\n };\n }\n return {\n type: 'token',\n error: {\n name: err.name,\n message: err.message,\n },\n };\n }\n if ('error' in credential) {\n return {\n appId: credential.appId,\n type: 'app',\n error: {\n name: credential.error.name,\n message: credential.error.message,\n },\n };\n }\n return undefined;\n}\n\nexport function verifyAndGetIntegrations(\n deps: {\n logger: LoggerService;\n },\n\n integrations: ScmIntegrations,\n) {\n const ghConfigs = integrations.github.list().map(ghInt => ghInt.config);\n if (ghConfigs.length === 0) {\n deps.logger.debug(\n 'No GitHub Integration in config => returning an empty list of repositories.',\n );\n throw new Error(\n \"Looks like there is no GitHub Integration in config. Please add a configuration entry under 'integrations.github\",\n );\n }\n return ghConfigs;\n}\n\nexport async function getCredentialsFromIntegrations(\n githubCredentialsProvider: CustomGithubCredentialsProvider,\n ghConfigs: GithubIntegrationConfig[],\n) {\n const credentialsByConfig = new Map<\n GithubIntegrationConfig,\n ExtendedGithubCredentials[]\n >();\n for (const ghConfig of ghConfigs) {\n const creds = await getCredentialsForConfig(\n githubCredentialsProvider,\n ghConfig,\n );\n credentialsByConfig.set(ghConfig, creds);\n }\n return credentialsByConfig;\n}\n\nexport async function getCredentialsForConfig(\n githubCredentialsProvider: CustomGithubCredentialsProvider,\n ghConfig: GithubIntegrationConfig,\n) {\n return await githubCredentialsProvider.getAllCredentials({\n host: ghConfig.host,\n });\n}\n\nexport async function extractConfigAndCreds(\n githubCredentialsProvider: CustomGithubCredentialsProvider,\n integrations: ScmIntegrations,\n input: {\n repoUrl: string;\n defaultBranch?: string;\n },\n) {\n const ghConfig = integrations.github.byUrl(input.repoUrl)?.config;\n if (!ghConfig) {\n throw new Error(`Could not find GH integration from ${input.repoUrl}`);\n }\n\n const credentials = await githubCredentialsProvider.getAllCredentials({\n host: ghConfig.host,\n });\n if (credentials.length === 0) {\n throw new Error(`No credentials for GH integration`);\n }\n\n const gitUrl = gitUrlParse(input.repoUrl);\n return { ghConfig, credentials, gitUrl };\n}\n\nexport function handleError(\n deps: {\n logger: LoggerService;\n },\n desc: string,\n credential: ExtendedGithubCredentials,\n errors: Map<number, GithubFetchError>,\n err: any,\n) {\n logErrorIfNeeded(deps.logger, `${desc} failed`, err);\n const credentialError = createCredentialError(credential, err as Error);\n if (credentialError) {\n errors.set(-1, credentialError);\n }\n}\n\nexport async function computeTotalCountFromGitHubToken(\n deps: {\n logger: LoggerService;\n },\n lastPageDataLengthProviderFn: (lastPageNumber: number) => Promise<number>,\n ghApiName: string,\n pageSize?: number,\n linkHeader?: string,\n): Promise<number | undefined> {\n // There is no direct way to get the total count of repositories other than using octokit.paginate,\n // but will make us retrieve all pages, thus increasing our response time.\n // Workaround here is to analyze the headers, and get the link to the last page.\n if (!linkHeader) {\n deps.logger.debug(\n `No link header found in response from ${ghApiName} GH endpoint => returning current page size`,\n );\n return pageSize;\n }\n const lastPageLink = linkHeader\n .split(',')\n .find(s => s.includes('rel=\"last\"'));\n if (!lastPageLink) {\n deps.logger.debug(\n `No rel='last' link found in response headers from ${ghApiName} GH endpoint => returning current page size`,\n );\n return pageSize;\n }\n const match = lastPageLink.match(/page=(\\d+)/);\n if (!match || match.length < 2) {\n deps.logger.debug(\n `Unable to extract page number from rel='last' link found in response headers from ${ghApiName} GH endpoint => returning current page size`,\n );\n return pageSize;\n }\n\n const lastPageNumber = parseInt(match[1], 10);\n // Fetch the last page to count its items, as it might contain fewer than the requested size\n const lastPageDataLength = await lastPageDataLengthProviderFn(lastPageNumber);\n return pageSize\n ? (lastPageNumber - 1) * pageSize + lastPageDataLength\n : undefined;\n}\n\nexport async function executeFunctionOnFirstSuccessfulIntegration<T>(\n deps: {\n logger: LoggerService;\n cache: CacheService;\n config: Config;\n githubCredentialsProvider: CustomGithubCredentialsProvider;\n },\n integrations: ScmIntegrations,\n params: {\n repoUrl: string;\n fn: (\n validatedRepo: ValidatedRepo,\n octo: Octokit,\n ) => Promise<{ successful: boolean; result?: T }>;\n },\n) {\n const validatedRepo = await validateAndBuildRepoData(\n deps.githubCredentialsProvider,\n integrations,\n deps.config,\n params,\n );\n for (const credential of validatedRepo.credentials) {\n const octo = buildOcto(\n {\n logger: deps.logger,\n cache: deps.cache,\n },\n { credential, owner: validatedRepo.owner },\n validatedRepo.ghConfig.apiBaseUrl,\n );\n if (!octo) {\n continue;\n }\n const res = await params.fn(validatedRepo, octo);\n if (!res.successful) {\n continue;\n }\n return res.result;\n }\n return undefined;\n}\n\nexport async function fetchFromAllIntegrations<T>(\n deps: {\n logger: LoggerService;\n cache: CacheService;\n githubCredentialsProvider: CustomGithubCredentialsProvider;\n },\n integrations: ScmIntegrations,\n params: {\n dataFetcher: (\n octo: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => Promise<{\n stopFetchingData?: boolean;\n result?: T;\n errors?: GithubFetchError[];\n }>;\n },\n) {\n const ghConfigs = verifyAndGetIntegrations(deps, integrations);\n\n const credentialsByConfig = await getCredentialsFromIntegrations(\n deps.githubCredentialsProvider,\n ghConfigs,\n );\n const errors = new Map<number, GithubFetchError>();\n const data: T[] = [];\n const dataErrs: GithubFetchError[] = [];\n let stopFetchingData: boolean | undefined = false;\n for (const [ghConfig, credentials] of credentialsByConfig) {\n if (stopFetchingData) {\n break;\n }\n deps.logger.debug(\n `Got ${credentials.length} credential(s) for ${ghConfig.host}`,\n );\n for (const credential of credentials) {\n const octokit = buildOcto(\n deps,\n { credential, errors },\n ghConfig.apiBaseUrl,\n );\n if (!octokit) {\n continue;\n }\n const res = await params.dataFetcher(octokit, credential, ghConfig);\n res.errors?.forEach(err => dataErrs.push(err));\n\n if (res.result) {\n data.push(res.result);\n }\n\n stopFetchingData = res.stopFetchingData;\n }\n }\n\n const aggregatedErrors = new Map<number, GithubFetchError>();\n errors.forEach((err, num) => aggregatedErrors.set(num, err));\n dataErrs.forEach((err, idx) => aggregatedErrors.set(idx, err));\n\n return { data, errors: aggregatedErrors };\n}\n\nexport function computeTotalCount<T>(\n data: T[],\n countList: number[],\n pageSize: number,\n) {\n let totalCount = countList.reduce(\n (accumulator, currentValue) => accumulator + currentValue,\n 0,\n );\n if (totalCount < pageSize) {\n totalCount = data.length;\n }\n return totalCount;\n}\n\nexport function extractLocationOwnerMap(locationUrls: string[]) {\n const locationGitOwnerMap = new Map<string, string>();\n for (const locationUrl of locationUrls) {\n const split = locationUrl.split('/blob/');\n if (split.length < 2) {\n continue;\n }\n locationGitOwnerMap.set(locationUrl, gitUrlParse(split[0]).owner);\n }\n return locationGitOwnerMap;\n}\n"],"names":["isGithubAppCredential","logErrorIfNeeded","validateAndBuildRepoData","buildOcto","gitUrlParse"],"mappings":";;;;;;;;;;;;;;;AA0CgB,SAAA,qBAAA,CACd,YACA,GAC8B,EAAA;AAC9B,EAAA,IAAI,GAAK,EAAA;AACP,IAAI,IAAAA,2BAAA,CAAsB,UAAU,CAAG,EAAA;AACrC,MAAO,OAAA;AAAA,QACL,OAAO,UAAW,CAAA,KAAA;AAAA,QAClB,IAAM,EAAA,KAAA;AAAA,QACN,KAAO,EAAA;AAAA,UACL,MAAM,GAAI,CAAA,IAAA;AAAA,UACV,SAAS,GAAI,CAAA;AAAA;AACf,OACF;AAAA;AAEF,IAAO,OAAA;AAAA,MACL,IAAM,EAAA,OAAA;AAAA,MACN,KAAO,EAAA;AAAA,QACL,MAAM,GAAI,CAAA,IAAA;AAAA,QACV,SAAS,GAAI,CAAA;AAAA;AACf,KACF;AAAA;AAEF,EAAA,IAAI,WAAW,UAAY,EAAA;AACzB,IAAO,OAAA;AAAA,MACL,OAAO,UAAW,CAAA,KAAA;AAAA,MAClB,IAAM,EAAA,KAAA;AAAA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AS,wBAAwB,YAAwB,EAAA;AAC9D,EAAM,MAAA,mBAAA,uBAA0B,GAAoB,EAAA;AACpD,EAAA,KAAA,MAAW,eAAe,YAAc,EAAA;AACtC,IAAM,MAAA,KAAA,GAAQ,WAAY,CAAA,KAAA,CAAM,QAAQ,CAAA;AACxC,IAAI,IAAA,KAAA,CAAM,SAAS,CAAG,EAAA;AACpB,MAAA;AAAA;AAEF,IAAA,mBAAA,CAAoB,IAAI,WAAa,EAAAC,4BAAA,CAAY,MAAM,CAAC,CAAC,EAAE,KAAK,CAAA;AAAA;AAElE,EAAO,OAAA,mBAAA;AACT;;;;;;;;;;;;;"}
@@ -2,7 +2,7 @@
2
2
 
3
3
  function getNestedValue(obj, path) {
4
4
  return path.split(".").reduce(
5
- (acc, key) => acc && acc[key] ? acc[key] : void 0,
5
+ (acc, key) => acc && acc[key] ? acc[key] : undefined,
6
6
  obj
7
7
  );
8
8
  }
@@ -1 +1 @@
1
- {"version":3,"file":"utils.cjs.js","sources":["../../src/helpers/utils.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\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 */\nexport function getNestedValue<T>(obj: T, path: string): any {\n return path\n .split('.')\n .reduce(\n (acc, key) =>\n acc && (acc as Record<string, any>)[key]\n ? (acc as Record<string, any>)[key]\n : undefined,\n obj,\n );\n}\n"],"names":[],"mappings":";;AAegB,SAAA,cAAA,CAAkB,KAAQ,IAAmB,EAAA;AAC3D,EAAO,OAAA,IAAA,CACJ,KAAM,CAAA,GAAG,CACT,CAAA,MAAA;AAAA,IACC,CAAC,KAAK,GACJ,KAAA,GAAA,IAAQ,IAA4B,GAAG,CAAA,GAClC,GAA4B,CAAA,GAAG,CAChC,GAAA,KAAA,CAAA;AAAA,IACN;AAAA,GACF;AACJ;;;;"}
1
+ {"version":3,"file":"utils.cjs.js","sources":["../../src/helpers/utils.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\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 */\nexport function getNestedValue<T>(obj: T, path: string): any {\n return path\n .split('.')\n .reduce(\n (acc, key) =>\n acc && (acc as Record<string, any>)[key]\n ? (acc as Record<string, any>)[key]\n : undefined,\n obj,\n );\n}\n"],"names":[],"mappings":";;AAegB,SAAA,cAAA,CAAkB,KAAQ,IAAmB,EAAA;AAC3D,EAAO,OAAA,IAAA,CACJ,KAAM,CAAA,GAAG,CACT,CAAA,MAAA;AAAA,IACC,CAAC,KAAK,GACJ,KAAA,GAAA,IAAQ,IAA4B,GAAG,CAAA,GAClC,GAA4B,CAAA,GAAG,CAChC,GAAA,SAAA;AAAA,IACN;AAAA,GACF;AACJ;;;;"}
@@ -18,9 +18,9 @@ function sortImports(imports, sortColumn = handlers.DefaultSortColumn, sortOrder
18
18
  imports.sort((a, b) => {
19
19
  const value1 = utils.getNestedValue(a, sortColumn);
20
20
  const value2 = utils.getNestedValue(b, sortColumn);
21
- if (value1 === void 0 && value2 === void 0) return 0;
22
- if (value1 === void 0) return sortOrder === "asc" ? -1 : 1;
23
- if (value2 === void 0) return sortOrder === "asc" ? 1 : -1;
21
+ if (value1 === undefined && value2 === undefined) return 0;
22
+ if (value1 === undefined) return sortOrder === "asc" ? -1 : 1;
23
+ if (value2 === undefined) return sortOrder === "asc" ? 1 : -1;
24
24
  if (sortColumn === "lastUpdate") {
25
25
  const date1 = new Date(value1);
26
26
  const date2 = new Date(value2);
@@ -76,10 +76,10 @@ async function findAllImports(deps, requestHeaders, queryParams) {
76
76
  const result = await Promise.all(importStatusPromises);
77
77
  const imports = result.filter((res) => res.responseBody).map((res) => res.responseBody).map((res) => {
78
78
  const key = res?.repository?.url;
79
- const location = key ? repoUrlToLocation.get(key) : void 0;
79
+ const location = key ? repoUrlToLocation.get(key) : undefined;
80
80
  return {
81
81
  ...res,
82
- source: location ? allLocations.get(location)?.source : void 0
82
+ source: location ? allLocations.get(location)?.source : undefined
83
83
  };
84
84
  });
85
85
  sortImports(imports, sortColumn, sortOrder);
@@ -124,7 +124,7 @@ async function resolveReposDefaultBranches(logger, githubApiService, allLocation
124
124
  );
125
125
  return {
126
126
  repoUrl,
127
- defaultBranch: void 0
127
+ defaultBranch: undefined
128
128
  };
129
129
  })
130
130
  );
@@ -139,7 +139,7 @@ async function resolveReposDefaultBranches(logger, githubApiService, allLocation
139
139
  function repoUrlFromLocation(loc) {
140
140
  const split = loc.split("/blob/");
141
141
  if (split.length < 2) {
142
- return void 0;
142
+ return undefined;
143
143
  }
144
144
  return split[0];
145
145
  }
@@ -212,7 +212,7 @@ async function handleAddedReposFromCreateImportJobs(deps, importRequests) {
212
212
  const gitUrl = gitUrlParse__default.default(req.repository.url);
213
213
  result.push({
214
214
  status: "ADDED",
215
- lastUpdate: ghRepo?.repository?.updated_at ?? void 0,
215
+ lastUpdate: ghRepo?.repository?.updated_at ?? undefined,
216
216
  repository: {
217
217
  url: req.repository.url,
218
218
  name: gitUrl.name,
@@ -534,7 +534,7 @@ async function deleteImportByRepo(deps, repoUrl, defaultBranch) {
534
534
  return loc.id;
535
535
  }
536
536
  }
537
- return void 0;
537
+ return undefined;
538
538
  };
539
539
  const locationId = findLocationFrom(
540
540
  (await deps.catalogHttpClient.listCatalogUrlLocationsByIdFromLocationsEndpoint()).locations
@@ -544,7 +544,7 @@ async function deleteImportByRepo(deps, repoUrl, defaultBranch) {
544
544
  }
545
545
  return {
546
546
  statusCode: 204,
547
- responseBody: void 0
547
+ responseBody: undefined
548
548
  };
549
549
  }
550
550
 
@@ -1 +1 @@
1
- {"version":3,"file":"bulkImports.cjs.js","sources":["../../../../src/service/handlers/import/bulkImports.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 { AuthService, LoggerService } from '@backstage/backend-plugin-api';\nimport type { CatalogApi } from '@backstage/catalog-client';\nimport type { Config } from '@backstage/config';\n\nimport gitUrlParse from 'git-url-parse';\n\nimport { CatalogHttpClient } from '../../../catalog/catalogHttpClient';\nimport type { CatalogInfoGenerator } from '../../../catalog/catalogInfoGenerator';\nimport {\n getCatalogFilename,\n getCatalogUrl,\n} from '../../../catalog/catalogUtils';\nimport type { Components, Paths } from '../../../generated/openapi';\nimport type { GithubApiService } from '../../../github';\nimport {\n getNestedValue,\n logErrorIfNeeded,\n paginateArray,\n} from '../../../helpers';\nimport {\n DefaultPageNumber,\n DefaultPageSize,\n DefaultSortColumn,\n DefaultSortOrder,\n type HandlerResponse,\n} from '../handlers';\n\ntype CreateImportDryRunStatus =\n | 'CATALOG_ENTITY_CONFLICT'\n | 'CATALOG_INFO_FILE_EXISTS_IN_REPO'\n | 'CODEOWNERS_FILE_NOT_FOUND_IN_REPO'\n | 'REPO_EMPTY';\n\ntype FindAllImportsResponse =\n | Components.Schemas.Import[]\n | Components.Schemas.ImportJobListV2;\n\nfunction sortImports(\n imports: Components.Schemas.Import[],\n sortColumn: Components.Parameters.SortColumnQueryParam = DefaultSortColumn,\n sortOrder: Components.Parameters.SortOrderQueryParam = DefaultSortOrder,\n) {\n imports.sort((a, b) => {\n const value1 = getNestedValue(a, sortColumn);\n const value2 = getNestedValue(b, sortColumn);\n // Handle cases where values are undefined\n if (value1 === undefined && value2 === undefined) return 0;\n if (value1 === undefined) return sortOrder === 'asc' ? -1 : 1;\n if (value2 === undefined) return sortOrder === 'asc' ? 1 : -1;\n\n if (sortColumn === 'lastUpdate') {\n const date1 = new Date(value1); // Convert string to Date object\n const date2 = new Date(value2); // Convert string to Date object\n // Compare dates\n return sortOrder === 'asc'\n ? date2.getTime() - date1.getTime()\n : date1.getTime() - date2.getTime();\n }\n // Compare values based on sort order\n return sortOrder === 'asc'\n ? value1.localeCompare(value2)\n : value2.localeCompare(value1);\n });\n}\n\nexport async function findAllImports(\n deps: {\n logger: LoggerService;\n config: Config;\n githubApiService: GithubApiService;\n catalogHttpClient: CatalogHttpClient;\n },\n requestHeaders?: {\n apiVersion?: Paths.FindAllImports.Parameters.ApiVersion;\n },\n queryParams?: {\n search?: string;\n pageNumber?: number;\n pageSize?: number;\n sortColumn?: Components.Parameters.SortColumnQueryParam;\n sortOrder?: Components.Parameters.SortOrderQueryParam;\n },\n): Promise<HandlerResponse<FindAllImportsResponse>> {\n const apiVersion = requestHeaders?.apiVersion ?? 'v1';\n const search = queryParams?.search;\n const pageNumber = queryParams?.pageNumber ?? DefaultPageNumber;\n const pageSize = queryParams?.pageSize ?? DefaultPageSize;\n const sortColumn = queryParams?.sortColumn ?? DefaultSortColumn;\n const sortOrder = queryParams?.sortOrder ?? DefaultSortOrder;\n\n const catalogFilename = getCatalogFilename(deps.config);\n\n const allLocations = (\n await deps.catalogHttpClient.listCatalogUrlLocations(\n search,\n pageNumber,\n pageSize,\n )\n ).uniqueCatalogUrlLocations;\n\n // resolve default branches for each unique repo URL from GH,\n // because we cannot easily determine that from the location target URL.\n // It can be 'main' or something more convoluted like 'our/awesome/main'.\n const defaultBranchByRepoUrl = await resolveReposDefaultBranches(\n deps.logger,\n deps.githubApiService,\n allLocations.keys(),\n catalogFilename,\n );\n\n // filter out locations that do not match what we are expecting, i.e.:\n // an URL to a catalog-info YAML file at the root of the repo\n const importCandidates = findImportCandidates(\n allLocations.keys(),\n defaultBranchByRepoUrl,\n catalogFilename,\n );\n\n // Keep only repos that are accessible from the configured GH integrations\n const importsReachableFromGHIntegrations =\n await deps.githubApiService.filterLocationsAccessibleFromIntegrations(\n importCandidates,\n );\n\n const repoUrlToLocation = new Map<string, string>();\n\n // now fetch the import statuses in different promises\n const importStatusPromises: Promise<\n HandlerResponse<Components.Schemas.Import>\n >[] = [];\n for (const loc of importsReachableFromGHIntegrations) {\n const repoUrl = repoUrlFromLocation(loc);\n if (!repoUrl) {\n continue;\n }\n repoUrlToLocation.set(repoUrl, loc);\n\n importStatusPromises.push(\n findImportStatusByRepo(\n deps,\n repoUrl,\n defaultBranchByRepoUrl.get(repoUrl),\n false,\n ),\n );\n }\n\n const result = await Promise.all(importStatusPromises);\n const imports = result\n .filter(res => res.responseBody)\n .map(res => res.responseBody!)\n .map(res => {\n const key = res?.repository?.url;\n const location = key ? repoUrlToLocation.get(key) : undefined;\n return {\n ...res,\n source: location ? allLocations.get(location)?.source : undefined,\n };\n });\n\n // sorting the output to make it deterministic and easy to navigate in the UI\n\n sortImports(imports, sortColumn, sortOrder);\n const paginated = paginateArray(imports, pageNumber, pageSize);\n if (apiVersion === 'v1') {\n return {\n statusCode: 200,\n responseBody: paginated.result,\n };\n }\n return {\n statusCode: 200,\n responseBody: {\n imports: paginated.result,\n totalCount: paginated.totalCount,\n page: pageNumber,\n size: pageSize,\n },\n };\n}\n\nasync function resolveReposDefaultBranches(\n logger: LoggerService,\n githubApiService: GithubApiService,\n allLocations: Iterable<string>,\n catalogFilename: string,\n) {\n const defaultBranchByRepoUrlPromises: Promise<{\n repoUrl: string;\n defaultBranch?: string;\n }>[] = [];\n for (const loc of allLocations) {\n // loc has the following format: https://github.com/<org>/<repo>/blob/<default-branch>/catalog-info.yaml\n // but it can have a more convoluted format like 'https://github.com/janus-idp/backstage-plugins/blob/main/plugins/scaffolder-annotator-action/examples/templates/01-scaffolder-template.yaml'\n // if registered manually from the 'Register existing component' feature in Backstage.\n if (!loc.endsWith(catalogFilename)) {\n logger.debug(\n `Ignored location ${loc} because it does not point to a file named ${catalogFilename}`,\n );\n continue;\n }\n const repoUrl = repoUrlFromLocation(loc);\n if (!repoUrl) {\n continue;\n }\n defaultBranchByRepoUrlPromises.push(\n githubApiService\n .getRepositoryFromIntegrations(repoUrl)\n .then(resp => {\n return { repoUrl, defaultBranch: resp?.repository?.default_branch };\n })\n .catch((err: any) => {\n logErrorIfNeeded(\n logger,\n `Ignored repo ${repoUrl} due to an error while fetching details from GitHub`,\n err,\n );\n return {\n repoUrl,\n defaultBranch: undefined,\n };\n }),\n );\n }\n const defaultBranchesResponses = await Promise.all(\n defaultBranchByRepoUrlPromises,\n );\n return new Map(\n defaultBranchesResponses\n .flat()\n .filter(r => r.defaultBranch)\n .map(r => [r.repoUrl, r.defaultBranch!]),\n );\n}\n\nfunction repoUrlFromLocation(loc: string) {\n const split = loc.split('/blob/');\n if (split.length < 2) {\n return undefined;\n }\n return split[0];\n}\n\nfunction findImportCandidates(\n allLocations: Iterable<string>,\n defaultBranchByRepoUrl: Map<string, string>,\n catalogFilename: string,\n) {\n const filteredLocations: string[] = [];\n for (const loc of allLocations) {\n const repoUrl = repoUrlFromLocation(loc);\n if (!repoUrl) {\n continue;\n }\n\n const defaultBranch = defaultBranchByRepoUrl.get(repoUrl);\n if (!defaultBranch) {\n continue;\n }\n if (loc !== `${repoUrl}/blob/${defaultBranch}/${catalogFilename}`) {\n // Because users can use the \"Register existing component\" workflow to register a Location\n // using any file path in the repo, we consider a repository as an Import Location only\n // if it is at the root of the repository, because that is what the import PR ultimately does.\n continue;\n }\n filteredLocations.push(loc);\n }\n return filteredLocations;\n}\n\nasync function createPR(\n githubApiService: GithubApiService,\n logger: LoggerService,\n req: Components.Schemas.ImportRequest,\n gitUrl: gitUrlParse.GitUrl,\n catalogInfoGenerator: CatalogInfoGenerator,\n config: Config,\n) {\n const appTitle =\n config.getOptionalString('app.title') ?? 'Red Hat Developer Hub';\n const appBaseUrl = config.getString('app.baseUrl');\n const catalogFileName = getCatalogFilename(config);\n return await githubApiService.submitPrToRepo(logger, {\n repoUrl: req.repository.url,\n gitUrl: gitUrl,\n defaultBranch: req.repository.defaultBranch,\n catalogInfoContent:\n req.catalogInfoContent ??\n (await catalogInfoGenerator.generateDefaultCatalogInfoContent(\n req.repository.url,\n )),\n prTitle: req.github?.pullRequest?.title ?? `Add ${catalogFileName}`,\n prBody:\n req.github?.pullRequest?.body ??\n `\nThis pull request adds a **Backstage entity metadata file** to this repository so that the component can be added to a Backstage application.\n\nAfter this pull request is merged, the component will become available in the [${appTitle} software catalog](${appBaseUrl}).\n\nFor more information, read an [overview of the Backstage software catalog](https://backstage.io/docs/features/software-catalog/).\n`,\n });\n}\n\nasync function handleAddedReposFromCreateImportJobs(\n deps: {\n logger: LoggerService;\n config: Config;\n auth: AuthService;\n catalogApi: CatalogApi;\n githubApiService: GithubApiService;\n catalogInfoGenerator: CatalogInfoGenerator;\n catalogHttpClient: CatalogHttpClient;\n },\n importRequests: Components.Schemas.ImportRequest[],\n) {\n const result: Components.Schemas.Import[] = [];\n\n for (const req of importRequests) {\n // Check if repo is already imported\n const repoCatalogUrl = getCatalogUrl(\n deps.config,\n req.repository.url,\n req.repository.defaultBranch,\n );\n const hasLocation =\n await deps.catalogHttpClient.verifyLocationExistence(repoCatalogUrl);\n if (!hasLocation) {\n continue;\n }\n const hasCatalogInfoFileInRepo = await deps.githubApiService.hasFileInRepo({\n repoUrl: req.repository.url,\n defaultBranch: req.repository.defaultBranch,\n fileName: getCatalogFilename(deps.config),\n });\n if (!hasCatalogInfoFileInRepo) {\n continue;\n }\n\n const ghRepo = await deps.githubApiService.getRepositoryFromIntegrations(\n req.repository.url,\n );\n\n // Force a refresh of the Location, so that the entities from the catalog-info.yaml can show up quickly (not guaranteed however).\n await deps.catalogHttpClient.refreshLocationByRepoUrl(\n req.repository.url,\n req.repository.defaultBranch,\n );\n\n const gitUrl = gitUrlParse(req.repository.url);\n result.push({\n status: 'ADDED',\n lastUpdate: ghRepo?.repository?.updated_at ?? undefined,\n repository: {\n url: req.repository.url,\n name: gitUrl.name,\n organization: gitUrl.organization,\n },\n });\n }\n return result;\n}\n\nasync function handlePrCreationRequest(\n deps: {\n logger: LoggerService;\n config: Config;\n auth: AuthService;\n catalogApi: CatalogApi;\n githubApiService: GithubApiService;\n catalogInfoGenerator: CatalogInfoGenerator;\n catalogHttpClient: CatalogHttpClient;\n },\n req: Components.Schemas.ImportRequest,\n gitUrl: gitUrlParse.GitUrl,\n): Promise<Components.Schemas.Import> {\n const repoCatalogUrl = getCatalogUrl(\n deps.config,\n req.repository.url,\n req.repository.defaultBranch,\n );\n const prToRepo = await createPR(\n deps.githubApiService,\n deps.logger,\n req,\n gitUrl,\n deps.catalogInfoGenerator,\n deps.config,\n );\n if (prToRepo.errors && prToRepo.errors.length > 0) {\n return {\n errors: prToRepo.errors,\n status: 'PR_ERROR',\n repository: req.repository,\n };\n }\n if (prToRepo.prUrl) {\n deps.logger.debug(`Created new PR from request: ${prToRepo.prUrl}`);\n }\n\n // Create Location\n await deps.catalogHttpClient.possiblyCreateLocation(repoCatalogUrl);\n\n if (prToRepo.hasChanges === false) {\n deps.logger.debug(\n `No bulk import PR created on ${req.repository.url} since its default branch (${req.repository.defaultBranch}) already contains a catalog-info file`,\n );\n\n // Force a refresh of the Location, so that the entities from the catalog-info.yaml can show up quickly (not guaranteed however).\n await deps.catalogHttpClient.refreshLocationByRepoUrl(\n req.repository.url,\n req.repository.defaultBranch,\n );\n return {\n status: 'ADDED',\n lastUpdate: prToRepo.lastUpdate,\n repository: {\n url: req.repository.url,\n name: gitUrl.name,\n organization: gitUrl.organization,\n },\n };\n }\n\n return {\n errors: prToRepo.errors,\n status: 'WAIT_PR_APPROVAL',\n lastUpdate: prToRepo.lastUpdate,\n repository: {\n url: req.repository.url,\n name: gitUrl.name,\n organization: gitUrl.organization,\n },\n github: {\n pullRequest: {\n url: prToRepo.prUrl,\n number: prToRepo.prNumber,\n },\n },\n };\n}\n\nexport async function createImportJobs(\n deps: {\n logger: LoggerService;\n config: Config;\n auth: AuthService;\n catalogApi: CatalogApi;\n githubApiService: GithubApiService;\n catalogInfoGenerator: CatalogInfoGenerator;\n catalogHttpClient: CatalogHttpClient;\n },\n reqParams: {\n importRequests: Paths.CreateImportJobs.RequestBody;\n dryRun?: boolean;\n },\n): Promise<\n HandlerResponse<Components.Schemas.Import[] | { errors: string[] }>\n> {\n const dryRun = reqParams.dryRun ?? false;\n const importRequests = reqParams.importRequests;\n deps.logger.debug(\n `Handling request to import ${importRequests?.length} repo(s) (dryRun=${dryRun})..`,\n );\n\n if (importRequests.length === 0) {\n deps.logger.debug('Missing import requests from request body');\n return {\n statusCode: 400,\n responseBody: [],\n };\n }\n\n if (dryRun) {\n return {\n statusCode: 202,\n responseBody: await dryRunCreateImportJobs(deps, importRequests),\n };\n }\n\n const result: Components.Schemas.Import[] = [];\n\n const addedRepos = await handleAddedReposFromCreateImportJobs(\n deps,\n importRequests,\n );\n result.push(...addedRepos);\n const addedReposMap = new Map(\n addedRepos.map(res => [res.repository?.url, res]),\n );\n const remainingRequests = importRequests.filter(\n req => !addedReposMap.has(req.repository.url),\n );\n\n for (const req of remainingRequests) {\n const gitUrl = gitUrlParse(req.repository.url);\n\n // Create PR\n try {\n result.push(await handlePrCreationRequest(deps, req, gitUrl));\n } catch (error: any) {\n result.push({\n errors: [error.message],\n status: 'PR_ERROR',\n repository: {\n url: req.repository.url,\n name: gitUrl.name,\n organization: gitUrl.organization,\n },\n } as Components.Schemas.Import);\n }\n }\n\n sortImports(result);\n\n return {\n statusCode: 202,\n responseBody: result,\n };\n}\n\nasync function dryRunCreateImportJobs(\n deps: {\n logger: LoggerService;\n config: Config;\n auth: AuthService;\n catalogApi: CatalogApi;\n githubApiService: GithubApiService;\n catalogInfoGenerator: CatalogInfoGenerator;\n catalogHttpClient: CatalogHttpClient;\n },\n importRequests: Paths.CreateImportJobs.RequestBody,\n) {\n const result: Components.Schemas.Import[] = [];\n for (const req of importRequests) {\n const gitUrl = gitUrlParse(req.repository.url);\n\n const dryRunChecks = await performDryRunChecks(deps, req);\n if (dryRunChecks.errors?.length > 0) {\n deps.logger.warn(\n `Errors while performing dry-run checks: ${dryRunChecks.errors}`,\n );\n }\n result.push({\n errors: dryRunChecks.dryRunStatuses,\n catalogEntityName: req.catalogEntityName,\n repository: {\n url: req.repository.url,\n name: gitUrl.name,\n organization: gitUrl.organization,\n },\n });\n }\n return result;\n}\n\nasync function performDryRunChecks(\n deps: {\n logger: LoggerService;\n auth: AuthService;\n catalogApi: CatalogApi;\n config: Config;\n githubApiService: GithubApiService;\n catalogHttpClient: CatalogHttpClient;\n },\n req: Components.Schemas.ImportRequest,\n): Promise<{ dryRunStatuses: CreateImportDryRunStatus[]; errors: string[] }> {\n const checkCatalog = async (\n catalogEntityName: string,\n ): Promise<{\n dryRunStatuses?: CreateImportDryRunStatus[];\n errors?: string[];\n }> => {\n const hasEntity =\n await deps.catalogHttpClient.hasEntityInCatalog(catalogEntityName);\n if (hasEntity) {\n return { dryRunStatuses: ['CATALOG_ENTITY_CONFLICT'] };\n }\n return {};\n };\n\n const checkEmptyRepo = async (): Promise<{\n dryRunStatuses?: CreateImportDryRunStatus[];\n errors?: string[];\n }> => {\n const empty = await deps.githubApiService.isRepoEmpty({\n repoUrl: req.repository.url,\n });\n if (empty) {\n return {\n dryRunStatuses: ['REPO_EMPTY'],\n };\n }\n return {};\n };\n\n const checkCatalogInfoPresenceInRepo = async (): Promise<{\n dryRunStatuses?: CreateImportDryRunStatus[];\n errors?: string[];\n }> => {\n const exists = await deps.githubApiService.hasFileInRepo({\n repoUrl: req.repository.url,\n defaultBranch: req.repository.defaultBranch,\n fileName: getCatalogFilename(deps.config),\n });\n if (exists) {\n return {\n dryRunStatuses: ['CATALOG_INFO_FILE_EXISTS_IN_REPO'],\n };\n }\n return {};\n };\n\n const checkCodeOwnersFileInRepo = async (): Promise<{\n dryRunStatuses?: CreateImportDryRunStatus[];\n errors?: string[];\n }> => {\n const exists = await deps.githubApiService.hasFileInRepo({\n repoUrl: req.repository.url,\n defaultBranch: req.repository.defaultBranch,\n fileName: '.github/CODEOWNERS',\n });\n if (!exists) {\n return {\n dryRunStatuses: ['CODEOWNERS_FILE_NOT_FOUND_IN_REPO'],\n };\n }\n return {};\n };\n\n const dryRunStatuses: CreateImportDryRunStatus[] = [];\n const errors: string[] = [];\n const allChecksFn = [checkEmptyRepo(), checkCatalogInfoPresenceInRepo()];\n if (req.catalogEntityName?.trim()) {\n allChecksFn.push(checkCatalog(req.catalogEntityName));\n }\n if (req.codeOwnersFileAsEntityOwner) {\n allChecksFn.push(checkCodeOwnersFileInRepo());\n }\n const allChecks = await Promise.all(allChecksFn);\n allChecks.flat().forEach(res => {\n if (res.dryRunStatuses) {\n dryRunStatuses.push(...res.dryRunStatuses);\n }\n if (res.errors) {\n errors.push(...res.errors);\n }\n });\n\n dryRunStatuses.sort((a, b) => a.localeCompare(b));\n\n return {\n dryRunStatuses,\n errors,\n };\n}\n\nexport async function findImportStatusByRepo(\n deps: {\n logger: LoggerService;\n config: Config;\n githubApiService: GithubApiService;\n catalogHttpClient: CatalogHttpClient;\n },\n repoUrl: string,\n defaultBranch?: string,\n includeCatalogInfoContent?: boolean,\n): Promise<HandlerResponse<Components.Schemas.Import>> {\n deps.logger.debug(`Getting bulk import job status for ${repoUrl}..`);\n\n const gitUrl = gitUrlParse(repoUrl);\n\n const errors: string[] = [];\n const result = {\n id: repoUrl,\n repository: {\n url: repoUrl,\n name: gitUrl.name,\n organization: gitUrl.organization,\n id: `${gitUrl.organization}/${gitUrl.name}`,\n defaultBranch,\n },\n approvalTool: 'GIT',\n status: null,\n } as Components.Schemas.Import;\n try {\n // Check to see if there are any PR\n const openImportPr = await deps.githubApiService.findImportOpenPr(\n deps.logger,\n {\n repoUrl: repoUrl,\n includeCatalogInfoContent,\n },\n );\n if (!openImportPr.prUrl) {\n const catalogLocations = (\n await deps.catalogHttpClient.listCatalogUrlLocations()\n ).uniqueCatalogUrlLocations.keys();\n\n const catalogUrl = getCatalogUrl(deps.config, repoUrl, defaultBranch);\n let exists = false;\n for (const loc of catalogLocations) {\n if (loc === catalogUrl) {\n exists = true;\n break;\n }\n }\n if (\n exists &&\n (await deps.githubApiService.hasFileInRepo({\n repoUrl,\n defaultBranch,\n fileName: getCatalogFilename(deps.config),\n }))\n ) {\n result.status = 'ADDED';\n // Force a refresh of the Location, so that the entities from the catalog-info.yaml can show up quickly (not guaranteed however).\n await deps.catalogHttpClient.refreshLocationByRepoUrl(\n repoUrl,\n defaultBranch,\n );\n }\n // No import PR => let's determine last update from the repository\n const ghRepo =\n await deps.githubApiService.getRepositoryFromIntegrations(repoUrl);\n result.lastUpdate = ghRepo.repository?.updated_at ?? undefined;\n return {\n statusCode: 200,\n responseBody: result,\n };\n }\n result.status = 'WAIT_PR_APPROVAL';\n result.github = {\n pullRequest: {\n number: openImportPr.prNum,\n url: openImportPr.prUrl,\n title: openImportPr.prTitle,\n body: openImportPr.prBody,\n catalogInfoContent: openImportPr.prCatalogInfoContent,\n },\n };\n result.lastUpdate = openImportPr.lastUpdate;\n } catch (error: any) {\n errors.push(error.message);\n result.errors = errors;\n if (error.message?.includes('Not Found')) {\n return {\n statusCode: 404,\n responseBody: result,\n };\n }\n result.status = 'PR_ERROR';\n }\n\n return {\n statusCode: 200,\n responseBody: result,\n };\n}\n\nexport async function deleteImportByRepo(\n deps: {\n logger: LoggerService;\n config: Config;\n githubApiService: GithubApiService;\n catalogHttpClient: CatalogHttpClient;\n },\n repoUrl: string,\n defaultBranch?: string,\n): Promise<HandlerResponse<void>> {\n deps.logger.debug(`Deleting bulk import job status for ${repoUrl}..`);\n\n // Check to see if there are any PR\n const openImportPr = await deps.githubApiService.findImportOpenPr(\n deps.logger,\n {\n repoUrl: repoUrl,\n },\n );\n const gitUrl = gitUrlParse(repoUrl);\n if (openImportPr.prUrl) {\n // Close PR\n const appTitle =\n deps.config.getOptionalString('app.title') ?? 'Red Hat Developer Hub';\n const appBaseUrl = deps.config.getString('app.baseUrl');\n await deps.githubApiService.closeImportPR(deps.logger, {\n repoUrl,\n gitUrl,\n comment: `Closing PR upon request for bulk import deletion. This request was created from [${appTitle}](${appBaseUrl}).`,\n });\n }\n // Also delete the import branch, so that it is not outdated if we try later to import the repo again\n await deps.githubApiService.deleteImportBranch({\n repoUrl,\n gitUrl,\n });\n // Remove Location from catalog\n const catalogUrl = getCatalogUrl(deps.config, repoUrl, defaultBranch);\n const findLocationFrom = (list: { id?: string; target: string }[]) => {\n for (const loc of list) {\n if (loc.target === catalogUrl) {\n return loc.id;\n }\n }\n return undefined;\n };\n\n const locationId = findLocationFrom(\n (\n await deps.catalogHttpClient.listCatalogUrlLocationsByIdFromLocationsEndpoint()\n ).locations,\n );\n if (locationId) {\n await deps.catalogHttpClient.deleteCatalogLocationById(locationId);\n }\n\n return {\n statusCode: 204,\n responseBody: undefined,\n };\n}\n"],"names":["DefaultSortColumn","DefaultSortOrder","getNestedValue","DefaultPageNumber","DefaultPageSize","getCatalogFilename","paginateArray","logErrorIfNeeded","getCatalogUrl","gitUrlParse"],"mappings":";;;;;;;;;;;;;;;;AAqDA,SAAS,WACP,CAAA,OAAA,EACA,UAAyD,GAAAA,0BAAA,EACzD,YAAuDC,yBACvD,EAAA;AACA,EAAQ,OAAA,CAAA,IAAA,CAAK,CAAC,CAAA,EAAG,CAAM,KAAA;AACrB,IAAM,MAAA,MAAA,GAASC,oBAAe,CAAA,CAAA,EAAG,UAAU,CAAA;AAC3C,IAAM,MAAA,MAAA,GAASA,oBAAe,CAAA,CAAA,EAAG,UAAU,CAAA;AAE3C,IAAA,IAAI,MAAW,KAAA,KAAA,CAAA,IAAa,MAAW,KAAA,KA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K,UAAU,CAAA,EAAA;AAAA,KACrH,CAAA;AAAA;AAGH,EAAM,MAAA,IAAA,CAAK,iBAAiB,kBAAmB,CAAA;AAAA,IAC7C,OAAA;AAAA,IACA;AAAA,GACD,CAAA;AAED,EAAA,MAAM,UAAa,GAAAD,0BAAA,CAAc,IAAK,CAAA,MAAA,EAAQ,SAAS,aAAa,CAAA;AACpE,EAAM,MAAA,gBAAA,GAAmB,CAAC,IAA4C,KAAA;AACpE,IAAA,KAAA,MAAW,OAAO,IAAM,EAAA;AACtB,MAAI,IAAA,GAAA,CAAI,WAAW,UAAY,EAAA;AAC7B,QAAA,OAAO,GAAI,CAAA,EAAA;AAAA;AACb;AAEF,IAAO,OAAA,KAAA,CAAA;AAAA,GACT;AAEA,EAAA,MAAM,UAAa,GAAA,gBAAA;AAAA,IAAA,CAEf,MAAM,IAAA,CAAK,iBAAkB,CAAA,gDAAA,EAC7B,EAAA;AAAA,GACJ;AACA,EAAA,IAAI,UAAY,EAAA;AACd,IAAM,MAAA,IAAA,CAAK,iBAAkB,CAAA,yBAAA,CAA0B,UAAU,CAAA;AAAA;AAGnE,EAAO,OAAA;AAAA,IACL,UAAY,EAAA,GAAA;AAAA,IACZ,YAAc,EAAA,KAAA;AAAA,GAChB;AACF;;;;;;;"}
1
+ {"version":3,"file":"bulkImports.cjs.js","sources":["../../../../src/service/handlers/import/bulkImports.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 { AuthService, LoggerService } from '@backstage/backend-plugin-api';\nimport type { CatalogApi } from '@backstage/catalog-client';\nimport type { Config } from '@backstage/config';\n\nimport gitUrlParse from 'git-url-parse';\n\nimport { CatalogHttpClient } from '../../../catalog/catalogHttpClient';\nimport type { CatalogInfoGenerator } from '../../../catalog/catalogInfoGenerator';\nimport {\n getCatalogFilename,\n getCatalogUrl,\n} from '../../../catalog/catalogUtils';\nimport type { Components, Paths } from '../../../generated/openapi';\nimport type { GithubApiService } from '../../../github';\nimport {\n getNestedValue,\n logErrorIfNeeded,\n paginateArray,\n} from '../../../helpers';\nimport {\n DefaultPageNumber,\n DefaultPageSize,\n DefaultSortColumn,\n DefaultSortOrder,\n type HandlerResponse,\n} from '../handlers';\n\ntype CreateImportDryRunStatus =\n | 'CATALOG_ENTITY_CONFLICT'\n | 'CATALOG_INFO_FILE_EXISTS_IN_REPO'\n | 'CODEOWNERS_FILE_NOT_FOUND_IN_REPO'\n | 'REPO_EMPTY';\n\ntype FindAllImportsResponse =\n | Components.Schemas.Import[]\n | Components.Schemas.ImportJobListV2;\n\nfunction sortImports(\n imports: Components.Schemas.Import[],\n sortColumn: Components.Parameters.SortColumnQueryParam = DefaultSortColumn,\n sortOrder: Components.Parameters.SortOrderQueryParam = DefaultSortOrder,\n) {\n imports.sort((a, b) => {\n const value1 = getNestedValue(a, sortColumn);\n const value2 = getNestedValue(b, sortColumn);\n // Handle cases where values are undefined\n if (value1 === undefined && value2 === undefined) return 0;\n if (value1 === undefined) return sortOrder === 'asc' ? -1 : 1;\n if (value2 === undefined) return sortOrder === 'asc' ? 1 : -1;\n\n if (sortColumn === 'lastUpdate') {\n const date1 = new Date(value1); // Convert string to Date object\n const date2 = new Date(value2); // Convert string to Date object\n // Compare dates\n return sortOrder === 'asc'\n ? date2.getTime() - date1.getTime()\n : date1.getTime() - date2.getTime();\n }\n // Compare values based on sort order\n return sortOrder === 'asc'\n ? value1.localeCompare(value2)\n : value2.localeCompare(value1);\n });\n}\n\nexport async function findAllImports(\n deps: {\n logger: LoggerService;\n config: Config;\n githubApiService: GithubApiService;\n catalogHttpClient: CatalogHttpClient;\n },\n requestHeaders?: {\n apiVersion?: Paths.FindAllImports.Parameters.ApiVersion;\n },\n queryParams?: {\n search?: string;\n pageNumber?: number;\n pageSize?: number;\n sortColumn?: Components.Parameters.SortColumnQueryParam;\n sortOrder?: Components.Parameters.SortOrderQueryParam;\n },\n): Promise<HandlerResponse<FindAllImportsResponse>> {\n const apiVersion = requestHeaders?.apiVersion ?? 'v1';\n const search = queryParams?.search;\n const pageNumber = queryParams?.pageNumber ?? DefaultPageNumber;\n const pageSize = queryParams?.pageSize ?? DefaultPageSize;\n const sortColumn = queryParams?.sortColumn ?? DefaultSortColumn;\n const sortOrder = queryParams?.sortOrder ?? DefaultSortOrder;\n\n const catalogFilename = getCatalogFilename(deps.config);\n\n const allLocations = (\n await deps.catalogHttpClient.listCatalogUrlLocations(\n search,\n pageNumber,\n pageSize,\n )\n ).uniqueCatalogUrlLocations;\n\n // resolve default branches for each unique repo URL from GH,\n // because we cannot easily determine that from the location target URL.\n // It can be 'main' or something more convoluted like 'our/awesome/main'.\n const defaultBranchByRepoUrl = await resolveReposDefaultBranches(\n deps.logger,\n deps.githubApiService,\n allLocations.keys(),\n catalogFilename,\n );\n\n // filter out locations that do not match what we are expecting, i.e.:\n // an URL to a catalog-info YAML file at the root of the repo\n const importCandidates = findImportCandidates(\n allLocations.keys(),\n defaultBranchByRepoUrl,\n catalogFilename,\n );\n\n // Keep only repos that are accessible from the configured GH integrations\n const importsReachableFromGHIntegrations =\n await deps.githubApiService.filterLocationsAccessibleFromIntegrations(\n importCandidates,\n );\n\n const repoUrlToLocation = new Map<string, string>();\n\n // now fetch the import statuses in different promises\n const importStatusPromises: Promise<\n HandlerResponse<Components.Schemas.Import>\n >[] = [];\n for (const loc of importsReachableFromGHIntegrations) {\n const repoUrl = repoUrlFromLocation(loc);\n if (!repoUrl) {\n continue;\n }\n repoUrlToLocation.set(repoUrl, loc);\n\n importStatusPromises.push(\n findImportStatusByRepo(\n deps,\n repoUrl,\n defaultBranchByRepoUrl.get(repoUrl),\n false,\n ),\n );\n }\n\n const result = await Promise.all(importStatusPromises);\n const imports = result\n .filter(res => res.responseBody)\n .map(res => res.responseBody!)\n .map(res => {\n const key = res?.repository?.url;\n const location = key ? repoUrlToLocation.get(key) : undefined;\n return {\n ...res,\n source: location ? allLocations.get(location)?.source : undefined,\n };\n });\n\n // sorting the output to make it deterministic and easy to navigate in the UI\n\n sortImports(imports, sortColumn, sortOrder);\n const paginated = paginateArray(imports, pageNumber, pageSize);\n if (apiVersion === 'v1') {\n return {\n statusCode: 200,\n responseBody: paginated.result,\n };\n }\n return {\n statusCode: 200,\n responseBody: {\n imports: paginated.result,\n totalCount: paginated.totalCount,\n page: pageNumber,\n size: pageSize,\n },\n };\n}\n\nasync function resolveReposDefaultBranches(\n logger: LoggerService,\n githubApiService: GithubApiService,\n allLocations: Iterable<string>,\n catalogFilename: string,\n) {\n const defaultBranchByRepoUrlPromises: Promise<{\n repoUrl: string;\n defaultBranch?: string;\n }>[] = [];\n for (const loc of allLocations) {\n // loc has the following format: https://github.com/<org>/<repo>/blob/<default-branch>/catalog-info.yaml\n // but it can have a more convoluted format like 'https://github.com/janus-idp/backstage-plugins/blob/main/plugins/scaffolder-annotator-action/examples/templates/01-scaffolder-template.yaml'\n // if registered manually from the 'Register existing component' feature in Backstage.\n if (!loc.endsWith(catalogFilename)) {\n logger.debug(\n `Ignored location ${loc} because it does not point to a file named ${catalogFilename}`,\n );\n continue;\n }\n const repoUrl = repoUrlFromLocation(loc);\n if (!repoUrl) {\n continue;\n }\n defaultBranchByRepoUrlPromises.push(\n githubApiService\n .getRepositoryFromIntegrations(repoUrl)\n .then(resp => {\n return { repoUrl, defaultBranch: resp?.repository?.default_branch };\n })\n .catch((err: any) => {\n logErrorIfNeeded(\n logger,\n `Ignored repo ${repoUrl} due to an error while fetching details from GitHub`,\n err,\n );\n return {\n repoUrl,\n defaultBranch: undefined,\n };\n }),\n );\n }\n const defaultBranchesResponses = await Promise.all(\n defaultBranchByRepoUrlPromises,\n );\n return new Map(\n defaultBranchesResponses\n .flat()\n .filter(r => r.defaultBranch)\n .map(r => [r.repoUrl, r.defaultBranch!]),\n );\n}\n\nfunction repoUrlFromLocation(loc: string) {\n const split = loc.split('/blob/');\n if (split.length < 2) {\n return undefined;\n }\n return split[0];\n}\n\nfunction findImportCandidates(\n allLocations: Iterable<string>,\n defaultBranchByRepoUrl: Map<string, string>,\n catalogFilename: string,\n) {\n const filteredLocations: string[] = [];\n for (const loc of allLocations) {\n const repoUrl = repoUrlFromLocation(loc);\n if (!repoUrl) {\n continue;\n }\n\n const defaultBranch = defaultBranchByRepoUrl.get(repoUrl);\n if (!defaultBranch) {\n continue;\n }\n if (loc !== `${repoUrl}/blob/${defaultBranch}/${catalogFilename}`) {\n // Because users can use the \"Register existing component\" workflow to register a Location\n // using any file path in the repo, we consider a repository as an Import Location only\n // if it is at the root of the repository, because that is what the import PR ultimately does.\n continue;\n }\n filteredLocations.push(loc);\n }\n return filteredLocations;\n}\n\nasync function createPR(\n githubApiService: GithubApiService,\n logger: LoggerService,\n req: Components.Schemas.ImportRequest,\n gitUrl: gitUrlParse.GitUrl,\n catalogInfoGenerator: CatalogInfoGenerator,\n config: Config,\n) {\n const appTitle =\n config.getOptionalString('app.title') ?? 'Red Hat Developer Hub';\n const appBaseUrl = config.getString('app.baseUrl');\n const catalogFileName = getCatalogFilename(config);\n return await githubApiService.submitPrToRepo(logger, {\n repoUrl: req.repository.url,\n gitUrl: gitUrl,\n defaultBranch: req.repository.defaultBranch,\n catalogInfoContent:\n req.catalogInfoContent ??\n (await catalogInfoGenerator.generateDefaultCatalogInfoContent(\n req.repository.url,\n )),\n prTitle: req.github?.pullRequest?.title ?? `Add ${catalogFileName}`,\n prBody:\n req.github?.pullRequest?.body ??\n `\nThis pull request adds a **Backstage entity metadata file** to this repository so that the component can be added to a Backstage application.\n\nAfter this pull request is merged, the component will become available in the [${appTitle} software catalog](${appBaseUrl}).\n\nFor more information, read an [overview of the Backstage software catalog](https://backstage.io/docs/features/software-catalog/).\n`,\n });\n}\n\nasync function handleAddedReposFromCreateImportJobs(\n deps: {\n logger: LoggerService;\n config: Config;\n auth: AuthService;\n catalogApi: CatalogApi;\n githubApiService: GithubApiService;\n catalogInfoGenerator: CatalogInfoGenerator;\n catalogHttpClient: CatalogHttpClient;\n },\n importRequests: Components.Schemas.ImportRequest[],\n) {\n const result: Components.Schemas.Import[] = [];\n\n for (const req of importRequests) {\n // Check if repo is already imported\n const repoCatalogUrl = getCatalogUrl(\n deps.config,\n req.repository.url,\n req.repository.defaultBranch,\n );\n const hasLocation =\n await deps.catalogHttpClient.verifyLocationExistence(repoCatalogUrl);\n if (!hasLocation) {\n continue;\n }\n const hasCatalogInfoFileInRepo = await deps.githubApiService.hasFileInRepo({\n repoUrl: req.repository.url,\n defaultBranch: req.repository.defaultBranch,\n fileName: getCatalogFilename(deps.config),\n });\n if (!hasCatalogInfoFileInRepo) {\n continue;\n }\n\n const ghRepo = await deps.githubApiService.getRepositoryFromIntegrations(\n req.repository.url,\n );\n\n // Force a refresh of the Location, so that the entities from the catalog-info.yaml can show up quickly (not guaranteed however).\n await deps.catalogHttpClient.refreshLocationByRepoUrl(\n req.repository.url,\n req.repository.defaultBranch,\n );\n\n const gitUrl = gitUrlParse(req.repository.url);\n result.push({\n status: 'ADDED',\n lastUpdate: ghRepo?.repository?.updated_at ?? undefined,\n repository: {\n url: req.repository.url,\n name: gitUrl.name,\n organization: gitUrl.organization,\n },\n });\n }\n return result;\n}\n\nasync function handlePrCreationRequest(\n deps: {\n logger: LoggerService;\n config: Config;\n auth: AuthService;\n catalogApi: CatalogApi;\n githubApiService: GithubApiService;\n catalogInfoGenerator: CatalogInfoGenerator;\n catalogHttpClient: CatalogHttpClient;\n },\n req: Components.Schemas.ImportRequest,\n gitUrl: gitUrlParse.GitUrl,\n): Promise<Components.Schemas.Import> {\n const repoCatalogUrl = getCatalogUrl(\n deps.config,\n req.repository.url,\n req.repository.defaultBranch,\n );\n const prToRepo = await createPR(\n deps.githubApiService,\n deps.logger,\n req,\n gitUrl,\n deps.catalogInfoGenerator,\n deps.config,\n );\n if (prToRepo.errors && prToRepo.errors.length > 0) {\n return {\n errors: prToRepo.errors,\n status: 'PR_ERROR',\n repository: req.repository,\n };\n }\n if (prToRepo.prUrl) {\n deps.logger.debug(`Created new PR from request: ${prToRepo.prUrl}`);\n }\n\n // Create Location\n await deps.catalogHttpClient.possiblyCreateLocation(repoCatalogUrl);\n\n if (prToRepo.hasChanges === false) {\n deps.logger.debug(\n `No bulk import PR created on ${req.repository.url} since its default branch (${req.repository.defaultBranch}) already contains a catalog-info file`,\n );\n\n // Force a refresh of the Location, so that the entities from the catalog-info.yaml can show up quickly (not guaranteed however).\n await deps.catalogHttpClient.refreshLocationByRepoUrl(\n req.repository.url,\n req.repository.defaultBranch,\n );\n return {\n status: 'ADDED',\n lastUpdate: prToRepo.lastUpdate,\n repository: {\n url: req.repository.url,\n name: gitUrl.name,\n organization: gitUrl.organization,\n },\n };\n }\n\n return {\n errors: prToRepo.errors,\n status: 'WAIT_PR_APPROVAL',\n lastUpdate: prToRepo.lastUpdate,\n repository: {\n url: req.repository.url,\n name: gitUrl.name,\n organization: gitUrl.organization,\n },\n github: {\n pullRequest: {\n url: prToRepo.prUrl,\n number: prToRepo.prNumber,\n },\n },\n };\n}\n\nexport async function createImportJobs(\n deps: {\n logger: LoggerService;\n config: Config;\n auth: AuthService;\n catalogApi: CatalogApi;\n githubApiService: GithubApiService;\n catalogInfoGenerator: CatalogInfoGenerator;\n catalogHttpClient: CatalogHttpClient;\n },\n reqParams: {\n importRequests: Paths.CreateImportJobs.RequestBody;\n dryRun?: boolean;\n },\n): Promise<\n HandlerResponse<Components.Schemas.Import[] | { errors: string[] }>\n> {\n const dryRun = reqParams.dryRun ?? false;\n const importRequests = reqParams.importRequests;\n deps.logger.debug(\n `Handling request to import ${importRequests?.length} repo(s) (dryRun=${dryRun})..`,\n );\n\n if (importRequests.length === 0) {\n deps.logger.debug('Missing import requests from request body');\n return {\n statusCode: 400,\n responseBody: [],\n };\n }\n\n if (dryRun) {\n return {\n statusCode: 202,\n responseBody: await dryRunCreateImportJobs(deps, importRequests),\n };\n }\n\n const result: Components.Schemas.Import[] = [];\n\n const addedRepos = await handleAddedReposFromCreateImportJobs(\n deps,\n importRequests,\n );\n result.push(...addedRepos);\n const addedReposMap = new Map(\n addedRepos.map(res => [res.repository?.url, res]),\n );\n const remainingRequests = importRequests.filter(\n req => !addedReposMap.has(req.repository.url),\n );\n\n for (const req of remainingRequests) {\n const gitUrl = gitUrlParse(req.repository.url);\n\n // Create PR\n try {\n result.push(await handlePrCreationRequest(deps, req, gitUrl));\n } catch (error: any) {\n result.push({\n errors: [error.message],\n status: 'PR_ERROR',\n repository: {\n url: req.repository.url,\n name: gitUrl.name,\n organization: gitUrl.organization,\n },\n } as Components.Schemas.Import);\n }\n }\n\n sortImports(result);\n\n return {\n statusCode: 202,\n responseBody: result,\n };\n}\n\nasync function dryRunCreateImportJobs(\n deps: {\n logger: LoggerService;\n config: Config;\n auth: AuthService;\n catalogApi: CatalogApi;\n githubApiService: GithubApiService;\n catalogInfoGenerator: CatalogInfoGenerator;\n catalogHttpClient: CatalogHttpClient;\n },\n importRequests: Paths.CreateImportJobs.RequestBody,\n) {\n const result: Components.Schemas.Import[] = [];\n for (const req of importRequests) {\n const gitUrl = gitUrlParse(req.repository.url);\n\n const dryRunChecks = await performDryRunChecks(deps, req);\n if (dryRunChecks.errors?.length > 0) {\n deps.logger.warn(\n `Errors while performing dry-run checks: ${dryRunChecks.errors}`,\n );\n }\n result.push({\n errors: dryRunChecks.dryRunStatuses,\n catalogEntityName: req.catalogEntityName,\n repository: {\n url: req.repository.url,\n name: gitUrl.name,\n organization: gitUrl.organization,\n },\n });\n }\n return result;\n}\n\nasync function performDryRunChecks(\n deps: {\n logger: LoggerService;\n auth: AuthService;\n catalogApi: CatalogApi;\n config: Config;\n githubApiService: GithubApiService;\n catalogHttpClient: CatalogHttpClient;\n },\n req: Components.Schemas.ImportRequest,\n): Promise<{ dryRunStatuses: CreateImportDryRunStatus[]; errors: string[] }> {\n const checkCatalog = async (\n catalogEntityName: string,\n ): Promise<{\n dryRunStatuses?: CreateImportDryRunStatus[];\n errors?: string[];\n }> => {\n const hasEntity =\n await deps.catalogHttpClient.hasEntityInCatalog(catalogEntityName);\n if (hasEntity) {\n return { dryRunStatuses: ['CATALOG_ENTITY_CONFLICT'] };\n }\n return {};\n };\n\n const checkEmptyRepo = async (): Promise<{\n dryRunStatuses?: CreateImportDryRunStatus[];\n errors?: string[];\n }> => {\n const empty = await deps.githubApiService.isRepoEmpty({\n repoUrl: req.repository.url,\n });\n if (empty) {\n return {\n dryRunStatuses: ['REPO_EMPTY'],\n };\n }\n return {};\n };\n\n const checkCatalogInfoPresenceInRepo = async (): Promise<{\n dryRunStatuses?: CreateImportDryRunStatus[];\n errors?: string[];\n }> => {\n const exists = await deps.githubApiService.hasFileInRepo({\n repoUrl: req.repository.url,\n defaultBranch: req.repository.defaultBranch,\n fileName: getCatalogFilename(deps.config),\n });\n if (exists) {\n return {\n dryRunStatuses: ['CATALOG_INFO_FILE_EXISTS_IN_REPO'],\n };\n }\n return {};\n };\n\n const checkCodeOwnersFileInRepo = async (): Promise<{\n dryRunStatuses?: CreateImportDryRunStatus[];\n errors?: string[];\n }> => {\n const exists = await deps.githubApiService.hasFileInRepo({\n repoUrl: req.repository.url,\n defaultBranch: req.repository.defaultBranch,\n fileName: '.github/CODEOWNERS',\n });\n if (!exists) {\n return {\n dryRunStatuses: ['CODEOWNERS_FILE_NOT_FOUND_IN_REPO'],\n };\n }\n return {};\n };\n\n const dryRunStatuses: CreateImportDryRunStatus[] = [];\n const errors: string[] = [];\n const allChecksFn = [checkEmptyRepo(), checkCatalogInfoPresenceInRepo()];\n if (req.catalogEntityName?.trim()) {\n allChecksFn.push(checkCatalog(req.catalogEntityName));\n }\n if (req.codeOwnersFileAsEntityOwner) {\n allChecksFn.push(checkCodeOwnersFileInRepo());\n }\n const allChecks = await Promise.all(allChecksFn);\n allChecks.flat().forEach(res => {\n if (res.dryRunStatuses) {\n dryRunStatuses.push(...res.dryRunStatuses);\n }\n if (res.errors) {\n errors.push(...res.errors);\n }\n });\n\n dryRunStatuses.sort((a, b) => a.localeCompare(b));\n\n return {\n dryRunStatuses,\n errors,\n };\n}\n\nexport async function findImportStatusByRepo(\n deps: {\n logger: LoggerService;\n config: Config;\n githubApiService: GithubApiService;\n catalogHttpClient: CatalogHttpClient;\n },\n repoUrl: string,\n defaultBranch?: string,\n includeCatalogInfoContent?: boolean,\n): Promise<HandlerResponse<Components.Schemas.Import>> {\n deps.logger.debug(`Getting bulk import job status for ${repoUrl}..`);\n\n const gitUrl = gitUrlParse(repoUrl);\n\n const errors: string[] = [];\n const result = {\n id: repoUrl,\n repository: {\n url: repoUrl,\n name: gitUrl.name,\n organization: gitUrl.organization,\n id: `${gitUrl.organization}/${gitUrl.name}`,\n defaultBranch,\n },\n approvalTool: 'GIT',\n status: null,\n } as Components.Schemas.Import;\n try {\n // Check to see if there are any PR\n const openImportPr = await deps.githubApiService.findImportOpenPr(\n deps.logger,\n {\n repoUrl: repoUrl,\n includeCatalogInfoContent,\n },\n );\n if (!openImportPr.prUrl) {\n const catalogLocations = (\n await deps.catalogHttpClient.listCatalogUrlLocations()\n ).uniqueCatalogUrlLocations.keys();\n\n const catalogUrl = getCatalogUrl(deps.config, repoUrl, defaultBranch);\n let exists = false;\n for (const loc of catalogLocations) {\n if (loc === catalogUrl) {\n exists = true;\n break;\n }\n }\n if (\n exists &&\n (await deps.githubApiService.hasFileInRepo({\n repoUrl,\n defaultBranch,\n fileName: getCatalogFilename(deps.config),\n }))\n ) {\n result.status = 'ADDED';\n // Force a refresh of the Location, so that the entities from the catalog-info.yaml can show up quickly (not guaranteed however).\n await deps.catalogHttpClient.refreshLocationByRepoUrl(\n repoUrl,\n defaultBranch,\n );\n }\n // No import PR => let's determine last update from the repository\n const ghRepo =\n await deps.githubApiService.getRepositoryFromIntegrations(repoUrl);\n result.lastUpdate = ghRepo.repository?.updated_at ?? undefined;\n return {\n statusCode: 200,\n responseBody: result,\n };\n }\n result.status = 'WAIT_PR_APPROVAL';\n result.github = {\n pullRequest: {\n number: openImportPr.prNum,\n url: openImportPr.prUrl,\n title: openImportPr.prTitle,\n body: openImportPr.prBody,\n catalogInfoContent: openImportPr.prCatalogInfoContent,\n },\n };\n result.lastUpdate = openImportPr.lastUpdate;\n } catch (error: any) {\n errors.push(error.message);\n result.errors = errors;\n if (error.message?.includes('Not Found')) {\n return {\n statusCode: 404,\n responseBody: result,\n };\n }\n result.status = 'PR_ERROR';\n }\n\n return {\n statusCode: 200,\n responseBody: result,\n };\n}\n\nexport async function deleteImportByRepo(\n deps: {\n logger: LoggerService;\n config: Config;\n githubApiService: GithubApiService;\n catalogHttpClient: CatalogHttpClient;\n },\n repoUrl: string,\n defaultBranch?: string,\n): Promise<HandlerResponse<void>> {\n deps.logger.debug(`Deleting bulk import job status for ${repoUrl}..`);\n\n // Check to see if there are any PR\n const openImportPr = await deps.githubApiService.findImportOpenPr(\n deps.logger,\n {\n repoUrl: repoUrl,\n },\n );\n const gitUrl = gitUrlParse(repoUrl);\n if (openImportPr.prUrl) {\n // Close PR\n const appTitle =\n deps.config.getOptionalString('app.title') ?? 'Red Hat Developer Hub';\n const appBaseUrl = deps.config.getString('app.baseUrl');\n await deps.githubApiService.closeImportPR(deps.logger, {\n repoUrl,\n gitUrl,\n comment: `Closing PR upon request for bulk import deletion. This request was created from [${appTitle}](${appBaseUrl}).`,\n });\n }\n // Also delete the import branch, so that it is not outdated if we try later to import the repo again\n await deps.githubApiService.deleteImportBranch({\n repoUrl,\n gitUrl,\n });\n // Remove Location from catalog\n const catalogUrl = getCatalogUrl(deps.config, repoUrl, defaultBranch);\n const findLocationFrom = (list: { id?: string; target: string }[]) => {\n for (const loc of list) {\n if (loc.target === catalogUrl) {\n return loc.id;\n }\n }\n return undefined;\n };\n\n const locationId = findLocationFrom(\n (\n await deps.catalogHttpClient.listCatalogUrlLocationsByIdFromLocationsEndpoint()\n ).locations,\n );\n if (locationId) {\n await deps.catalogHttpClient.deleteCatalogLocationById(locationId);\n }\n\n return {\n statusCode: 204,\n responseBody: undefined,\n };\n}\n"],"names":["DefaultSortColumn","DefaultSortOrder","getNestedValue","DefaultPageNumber","DefaultPageSize","getCatalogFilename","paginateArray","logErrorIfNeeded","getCatalogUrl","gitUrlParse"],"mappings":";;;;;;;;;;;;;;;;AAqDA,SAAS,WACP,CAAA,OAAA,EACA,UAAyD,GAAAA,0BAAA,EACzD,YAAuDC,yBACvD,EAAA;AACA,EAAQ,OAAA,CAAA,IAAA,CAAK,CAAC,CAAA,EAAG,CAAM,KAAA;AACrB,IAAM,MAAA,MAAA,GAASC,oBAAe,CAAA,CAAA,EAAG,UAAU,CAAA;AAC3C,IAAM,MAAA,MAAA,GAASA,oBAAe,CAAA,CAAA,EAAG,UAAU,CAAA;AAE3C,IAAA,IAAI,MAAW,KAAA,SAAA,IAAa,MAAW,KAAA,SAAA,EAAkB,OAAA,CAAA;AACzD,IAAA,IAAI,MAAW,KAAA,SAAA,EAAkB,OAAA,SAAA,KAAc,QAAQ,EAAK,GAAA,CAAA;AAC5D,IAAA,IAAI,MAAW,KAAA,SAAA,EAAkB,OAAA,SAAA,KAAc,QAAQ,CAAI,GAAA,EAAA;AAE3D,IAAA,IAAI,eAAe,YAAc,EAAA;AAC/B,MAAM,MAAA,KAAA,GAAQ,IAAI,IAAA,CAAK,MAAM,CAAA;AAC7B,MAAM,MAAA,KAAA,GAAQ,IAAI,IAAA,CAAK,MAAM,CAAA;AAE7B,MAAA,OAAO,SAAc,KAAA,KAAA,GACjB,KAAM,CAAA,OAAA,EAAY,GAAA,KAAA,CAAM,OAAQ,EAAA,GAChC,KAAM,CAAA,OAAA,EAAY,GAAA,KAAA,CAAM,OAAQ,EAAA;AAAA;AAGtC,IAAO,OAAA,SAAA,KAAc,QACjB,MAAO,CAAA,aAAA,CAAc,MAAM,C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,CAA0B,UAAU,CAAA;AAAA;AAGnE,EAAO,OAAA;AAAA,IACL,UAAY,EAAA,GAAA;AAAA,IACZ,YAAc,EAAA;AAAA,GAChB;AACF;;;;;;;"}
@@ -42,7 +42,7 @@ function extractOrgMap(allOrgsAccessible) {
42
42
  const orgMap = /* @__PURE__ */ new Map();
43
43
  for (const org of allOrgsAccessible.organizations ?? []) {
44
44
  let totalRepoCount;
45
- if (org.public_repos !== void 0 || org.total_private_repos !== void 0 || org.owned_private_repos !== void 0) {
45
+ if (org.public_repos !== undefined || org.total_private_repos !== undefined || org.owned_private_repos !== undefined) {
46
46
  totalRepoCount = (org.public_repos ?? 0) + (org.owned_private_repos ?? org.total_private_repos ?? 0);
47
47
  }
48
48
  orgMap.set(org.name, {
@@ -59,13 +59,13 @@ function extractOrgMap(allOrgsAccessible) {
59
59
  function sortOrgs(orgMap) {
60
60
  const organizations = Array.from(orgMap.values());
61
61
  organizations.sort((a, b) => {
62
- if (a.name === void 0 && b.name === void 0) {
62
+ if (a.name === undefined && b.name === undefined) {
63
63
  return 0;
64
64
  }
65
- if (a.name === void 0) {
65
+ if (a.name === undefined) {
66
66
  return -1;
67
67
  }
68
- if (b.name === void 0) {
68
+ if (b.name === undefined) {
69
69
  return 1;
70
70
  }
71
71
  return a.name.localeCompare(b.name);
@@ -1 +1 @@
1
- {"version":3,"file":"organizations.cjs.js","sources":["../../../../src/service/handlers/organization/organizations.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 { LoggerService } from '@backstage/backend-plugin-api';\n\nimport type { Components } from '../../../generated/openapi';\nimport type {\n GithubApiService,\n GithubOrganizationResponse,\n} from '../../../github';\nimport {\n DefaultPageNumber,\n DefaultPageSize,\n type HandlerResponse,\n} from '../handlers';\n\nexport async function findAllOrganizations(\n logger: LoggerService,\n githubApiService: GithubApiService,\n search?: string,\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n): Promise<HandlerResponse<Components.Schemas.OrganizationList>> {\n logger.debug(\n `Getting all organizations (search,page,size)=('${\n search ?? ''\n }',${pageNumber},${pageSize})..`,\n );\n const allOrgsAccessible =\n await githubApiService.getOrganizationsFromIntegrations(\n search,\n pageNumber,\n pageSize,\n );\n const errorList: string[] = [];\n for (const err of allOrgsAccessible.errors ?? []) {\n if (err.error?.message) {\n errorList.push(err.error.message);\n }\n }\n if (allOrgsAccessible.organizations?.length === 0 && errorList.length > 0) {\n return {\n statusCode: 500,\n responseBody: {\n errors: errorList,\n },\n };\n }\n\n const orgMap = extractOrgMap(allOrgsAccessible);\n\n // sorting the output to make it deterministic and easy to navigate in the UI\n const organizations = sortOrgs(orgMap);\n\n return {\n statusCode: 200,\n responseBody: {\n errors: errorList,\n organizations,\n totalCount: allOrgsAccessible.totalCount,\n pagePerIntegration: pageNumber,\n sizePerIntegration: pageSize,\n },\n };\n}\n\nfunction extractOrgMap(allOrgsAccessible: GithubOrganizationResponse) {\n const orgMap = new Map<string, Components.Schemas.Organization>();\n for (const org of allOrgsAccessible.organizations ?? []) {\n let totalRepoCount: number | undefined;\n if (\n org.public_repos !== undefined ||\n org.total_private_repos !== undefined ||\n org.owned_private_repos !== undefined\n ) {\n totalRepoCount =\n (org.public_repos ?? 0) +\n (org.owned_private_repos ?? org.total_private_repos ?? 0);\n }\n orgMap.set(org.name, {\n id: `${org.id}`,\n name: org.name,\n description: org.description,\n url: org.url,\n totalRepoCount,\n errors: [],\n });\n }\n return orgMap;\n}\n\nfunction sortOrgs(orgMap: Map<string, Components.Schemas.Organization>) {\n const organizations = Array.from(orgMap.values());\n organizations.sort((a, b) => {\n if (a.name === undefined && b.name === undefined) {\n return 0;\n }\n if (a.name === undefined) {\n return -1;\n }\n if (b.name === undefined) {\n return 1;\n }\n return a.name.localeCompare(b.name);\n });\n return organizations;\n}\n"],"names":["DefaultPageNumber","DefaultPageSize"],"mappings":";;;;AA6BA,eAAsB,qBACpB,MACA,EAAA,gBAAA,EACA,QACA,UAAqB,GAAAA,0BAAA,EACrB,WAAmBC,wBAC4C,EAAA;AAC/D,EAAO,MAAA,CAAA,KAAA;AAAA,IACL,kDACE,MAAU,IAAA,EACZ,CAAK,EAAA,EAAA,UAAU,IAAI,QAAQ,CAAA,GAAA;AAAA,GAC7B;AACA,EAAM,MAAA,iBAAA,GACJ,MAAM,gBAAiB,CAAA,gCAAA;AAAA,IACrB,MAAA;AAAA,IACA,UAAA;AAAA,IACA;AAAA,GACF;AACF,EAAA,MAAM,YAAsB,EAAC;AAC7B,EAAA,KAAA,MAAW,GAAO,IAAA,iBAAA,CAAkB,MAAU,IAAA,EAAI,EAAA;AAChD,IAAI,IAAA,GAAA,CAAI,OAAO,OAAS,EAAA;AACtB,MAAU,SAAA,CAAA,IAAA,CAAK,GAAI,CAAA,KAAA,CAAM,OAAO,CAAA;AAAA;AAClC;AAEF,EAAA,IAAI,kBAAkB,aAAe,EAAA,MAAA,KAAW,CAAK,IAAA,SAAA,CAAU,SAAS,CAAG,EAAA;AACzE,IAAO,OAAA;AAAA,MACL,UAAY,EAAA,GAAA;AAAA,MACZ,YAAc,EAAA;AAAA,QACZ,MAAQ,EAAA;AAAA;AACV,KACF;AAAA;AAGF,EAAM,MAAA,MAAA,GAAS,cAAc,iBAAiB,CAAA;AAG9C,EAAM,MAAA,aAAA,GAAgB,SAAS,MAAM,CAAA;AAErC,EAAO,OAAA;AAAA,IACL,UAAY,EAAA,GAAA;AAAA,IACZ,YAAc,EAAA;AAAA,MACZ,MAAQ,EAAA,SAAA;AAAA,MACR,aAAA;AAAA,MACA,YAAY,iBAAkB,CAAA,UAAA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IAAI,IAAA,CAAA,CAAE,SAAS,KAAW,CAAA,EAAA;AACxB,MAAO,OAAA,CAAA;AAAA;AAET,IAAA,OAAO,CAAE,CAAA,IAAA,CAAK,aAAc,CAAA,CAAA,CAAE,IAAI,CAAA;AAAA,GACnC,CAAA;AACD,EAAO,OAAA,aAAA;AACT;;;;"}
1
+ {"version":3,"file":"organizations.cjs.js","sources":["../../../../src/service/handlers/organization/organizations.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 { LoggerService } from '@backstage/backend-plugin-api';\n\nimport type { Components } from '../../../generated/openapi';\nimport type {\n GithubApiService,\n GithubOrganizationResponse,\n} from '../../../github';\nimport {\n DefaultPageNumber,\n DefaultPageSize,\n type HandlerResponse,\n} from '../handlers';\n\nexport async function findAllOrganizations(\n logger: LoggerService,\n githubApiService: GithubApiService,\n search?: string,\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n): Promise<HandlerResponse<Components.Schemas.OrganizationList>> {\n logger.debug(\n `Getting all organizations (search,page,size)=('${\n search ?? ''\n }',${pageNumber},${pageSize})..`,\n );\n const allOrgsAccessible =\n await githubApiService.getOrganizationsFromIntegrations(\n search,\n pageNumber,\n pageSize,\n );\n const errorList: string[] = [];\n for (const err of allOrgsAccessible.errors ?? []) {\n if (err.error?.message) {\n errorList.push(err.error.message);\n }\n }\n if (allOrgsAccessible.organizations?.length === 0 && errorList.length > 0) {\n return {\n statusCode: 500,\n responseBody: {\n errors: errorList,\n },\n };\n }\n\n const orgMap = extractOrgMap(allOrgsAccessible);\n\n // sorting the output to make it deterministic and easy to navigate in the UI\n const organizations = sortOrgs(orgMap);\n\n return {\n statusCode: 200,\n responseBody: {\n errors: errorList,\n organizations,\n totalCount: allOrgsAccessible.totalCount,\n pagePerIntegration: pageNumber,\n sizePerIntegration: pageSize,\n },\n };\n}\n\nfunction extractOrgMap(allOrgsAccessible: GithubOrganizationResponse) {\n const orgMap = new Map<string, Components.Schemas.Organization>();\n for (const org of allOrgsAccessible.organizations ?? []) {\n let totalRepoCount: number | undefined;\n if (\n org.public_repos !== undefined ||\n org.total_private_repos !== undefined ||\n org.owned_private_repos !== undefined\n ) {\n totalRepoCount =\n (org.public_repos ?? 0) +\n (org.owned_private_repos ?? org.total_private_repos ?? 0);\n }\n orgMap.set(org.name, {\n id: `${org.id}`,\n name: org.name,\n description: org.description,\n url: org.url,\n totalRepoCount,\n errors: [],\n });\n }\n return orgMap;\n}\n\nfunction sortOrgs(orgMap: Map<string, Components.Schemas.Organization>) {\n const organizations = Array.from(orgMap.values());\n organizations.sort((a, b) => {\n if (a.name === undefined && b.name === undefined) {\n return 0;\n }\n if (a.name === undefined) {\n return -1;\n }\n if (b.name === undefined) {\n return 1;\n }\n return a.name.localeCompare(b.name);\n });\n return organizations;\n}\n"],"names":["DefaultPageNumber","DefaultPageSize"],"mappings":";;;;AA6BA,eAAsB,qBACpB,MACA,EAAA,gBAAA,EACA,QACA,UAAqB,GAAAA,0BAAA,EACrB,WAAmBC,wBAC4C,EAAA;AAC/D,EAAO,MAAA,CAAA,KAAA;AAAA,IACL,kDACE,MAAU,IAAA,EACZ,CAAK,EAAA,EAAA,UAAU,IAAI,QAAQ,CAAA,GAAA;AAAA,GAC7B;AACA,EAAM,MAAA,iBAAA,GACJ,MAAM,gBAAiB,CAAA,gCAAA;AAAA,IACrB,MAAA;AAAA,IACA,UAAA;AAAA,IACA;AAAA,GACF;AACF,EAAA,MAAM,YAAsB,EAAC;AAC7B,EAAA,KAAA,MAAW,GAAO,IAAA,iBAAA,CAAkB,MAAU,I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