@red-hat-developer-hub/backstage-plugin-bulk-import-backend 7.1.1 → 7.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/dist/catalog/catalogHttpClient.cjs.js.map +1 -1
- package/dist/catalog/catalogInfoGenerator.cjs.js.map +1 -1
- package/dist/catalog/catalogUtils.cjs.js.map +1 -1
- package/dist/database/migration.cjs.js.map +1 -1
- package/dist/database/repositoryDao.cjs.js.map +1 -1
- package/dist/generated/openapidocument.cjs.js.map +1 -1
- package/dist/github/GithubAppManager.cjs.js +8 -8
- package/dist/github/GithubAppManager.cjs.js.map +1 -1
- package/dist/github/githubApiService.cjs.js +6 -6
- package/dist/github/githubApiService.cjs.js.map +1 -1
- package/dist/github/types.cjs.js.map +1 -1
- package/dist/github/utils/ghUtils.cjs.js +3 -3
- package/dist/github/utils/ghUtils.cjs.js.map +1 -1
- package/dist/github/utils/orgUtils.cjs.js +1 -1
- package/dist/github/utils/orgUtils.cjs.js.map +1 -1
- package/dist/github/utils/prUtils.cjs.js +1 -1
- package/dist/github/utils/prUtils.cjs.js.map +1 -1
- package/dist/github/utils/repoUtils.cjs.js +1 -1
- package/dist/github/utils/repoUtils.cjs.js.map +1 -1
- package/dist/github/utils/utils.cjs.js +3 -3
- package/dist/github/utils/utils.cjs.js.map +1 -1
- package/dist/gitlab/GitlabAppManager.cjs.js.map +1 -1
- package/dist/gitlab/gitlabApiService.cjs.js +11 -11
- package/dist/gitlab/gitlabApiService.cjs.js.map +1 -1
- package/dist/gitlab/utils/glUtils.cjs.js.map +1 -1
- package/dist/gitlab/utils/orgUtils.cjs.js +1 -1
- package/dist/gitlab/utils/orgUtils.cjs.js.map +1 -1
- package/dist/gitlab/utils/prUtils.cjs.js +1 -1
- package/dist/gitlab/utils/prUtils.cjs.js.map +1 -1
- package/dist/gitlab/utils/repoUtils.cjs.js +1 -1
- package/dist/gitlab/utils/repoUtils.cjs.js.map +1 -1
- package/dist/gitlab/utils/utils.cjs.js +3 -3
- package/dist/gitlab/utils/utils.cjs.js.map +1 -1
- package/dist/helpers/auditorUtils.cjs.js.map +1 -1
- package/dist/helpers/auth.cjs.js.map +1 -1
- package/dist/helpers/loggingUtils.cjs.js.map +1 -1
- package/dist/helpers/pagination.cjs.js.map +1 -1
- package/dist/helpers/utils.cjs.js +1 -1
- package/dist/helpers/utils.cjs.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/plugin.cjs.js.map +1 -1
- package/dist/service/handlers/handlers.cjs.js.map +1 -1
- package/dist/service/handlers/import/bulkImports.cjs.js +12 -12
- package/dist/service/handlers/import/bulkImports.cjs.js.map +1 -1
- package/dist/service/handlers/import/execute-orchestrator-workflow.cjs.js.map +1 -1
- package/dist/service/handlers/import/execute-template.cjs.js.map +1 -1
- package/dist/service/handlers/import/importStatus.cjs.js.map +1 -1
- package/dist/service/handlers/organization/organizations.cjs.js +4 -4
- package/dist/service/handlers/organization/organizations.cjs.js.map +1 -1
- package/dist/service/handlers/ping/ping.cjs.js.map +1 -1
- package/dist/service/handlers/repository/repositories.cjs.js +5 -5
- package/dist/service/handlers/repository/repositories.cjs.js.map +1 -1
- package/dist/service/router.cjs.js +5 -7
- package/dist/service/router.cjs.js.map +1 -1
- package/package.json +2 -2
|
@@ -58,7 +58,7 @@ async function getCatalogInfoContentFromPR(logger, config, gitlab, owner, repo,
|
|
|
58
58
|
`Error fetching catalog-info content from PR ${prNumber}`,
|
|
59
59
|
error
|
|
60
60
|
);
|
|
61
|
-
return
|
|
61
|
+
return void 0;
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
64
|
async function closePRWithComment(gitlab, owner, repo, prNum, comment) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prUtils.cjs.js","sources":["../../../src/gitlab/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 { getCatalogFilename } from '../../catalog/catalogUtils';\nimport { logErrorIfNeeded } from '../../helpers';\n\nexport async function findOpenPRForBranch(\n logger: LoggerService,\n config: Config,\n gitlab: any,\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 gitlab.MergeRequests.all({\n projectId: `${owner}/${repo}`,\n state: 'opened',\n });\n\n for (const pull of response) {\n if (pull.source_branch === branchName) {\n return {\n prNum: pull.iid,\n prUrl: pull.web_url,\n prTitle: pull.title,\n prBody: pull.description ?? undefined,\n prCatalogInfoContent: withCatalogInfoContent\n ? await getCatalogInfoContentFromPR(\n logger,\n config,\n gitlab,\n owner,\n repo,\n pull.iid,\n pull.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 gitlab: any,\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 gitlab.RepositoryFiles.show(\n `${owner}/${repo}`,\n filePath,\n prHeadSha,\n );\n if (!('content' in fileContentResponse)) {\n return undefined;\n }\n return Buffer.from(fileContentResponse.content, 'base64').toString('utf-8');\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 gitlab: any,\n owner: string,\n repo: string,\n prNum: number,\n comment: string,\n) {\n await gitlab.MergeRequestNotes.create(`${owner}/${repo}`, prNum, comment);\n await gitlab.MergeRequests.edit(`${owner}/${repo}`, prNum, {\n stateEvent: 'close',\n });\n}\n"],"names":["logErrorIfNeeded","getCatalogFilename"],"mappings":";;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"prUtils.cjs.js","sources":["../../../src/gitlab/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 { getCatalogFilename } from '../../catalog/catalogUtils';\nimport { logErrorIfNeeded } from '../../helpers';\n\nexport async function findOpenPRForBranch(\n logger: LoggerService,\n config: Config,\n gitlab: any,\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 gitlab.MergeRequests.all({\n projectId: `${owner}/${repo}`,\n state: 'opened',\n });\n\n for (const pull of response) {\n if (pull.source_branch === branchName) {\n return {\n prNum: pull.iid,\n prUrl: pull.web_url,\n prTitle: pull.title,\n prBody: pull.description ?? undefined,\n prCatalogInfoContent: withCatalogInfoContent\n ? await getCatalogInfoContentFromPR(\n logger,\n config,\n gitlab,\n owner,\n repo,\n pull.iid,\n pull.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 gitlab: any,\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 gitlab.RepositoryFiles.show(\n `${owner}/${repo}`,\n filePath,\n prHeadSha,\n );\n if (!('content' in fileContentResponse)) {\n return undefined;\n }\n return Buffer.from(fileContentResponse.content, 'base64').toString('utf-8');\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 gitlab: any,\n owner: string,\n repo: string,\n prNum: number,\n comment: string,\n) {\n await gitlab.MergeRequestNotes.create(`${owner}/${repo}`, prNum, comment);\n await gitlab.MergeRequests.edit(`${owner}/${repo}`, prNum, {\n stateEvent: 'close',\n });\n}\n"],"names":["logErrorIfNeeded","getCatalogFilename"],"mappings":";;;;;;;;;;;AAsBA,eAAsB,mBAAA,CACpB,QACA,MAAA,EACA,MAAA,EACA,OACA,IAAA,EACA,UAAA,EACA,yBAAkC,KAAA,EAQjC;AACD,EAAA,IAAI;AACF,IAAA,MAAM,QAAA,GAAW,MAAM,MAAA,CAAO,aAAA,CAAc,GAAA,CAAI;AAAA,MAC9C,SAAA,EAAW,CAAA,EAAG,KAAK,CAAA,CAAA,EAAI,IAAI,CAAA,CAAA;AAAA,MAC3B,KAAA,EAAO;AAAA,KACR,CAAA;AAED,IAAA,KAAA,MAAW,QAAQ,QAAA,EAAU;AAC3B,MAAA,IAAI,IAAA,CAAK,kBAAkB,UAAA,EAAY;AACrC,QAAA,OAAO;AAAA,UACL,OAAO,IAAA,CAAK,GAAA;AAAA,UACZ,OAAO,IAAA,C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EACA,IAAA,EACA,OACA,OAAA,EACA;AACA,EAAA,MAAM,MAAA,CAAO,kBAAkB,MAAA,CAAO,CAAA,EAAG,KAAK,CAAA,CAAA,EAAI,IAAI,CAAA,CAAA,EAAI,KAAA,EAAO,OAAO,CAAA;AACxE,EAAA,MAAM,MAAA,CAAO,cAAc,IAAA,CAAK,CAAA,EAAG,KAAK,CAAA,CAAA,EAAI,IAAI,IAAI,KAAA,EAAO;AAAA,IACzD,UAAA,EAAY;AAAA,GACb,CAAA;AACH;;;;;"}
|
|
@@ -154,7 +154,7 @@ async function fileExistsInDefaultBranch(logger, gitlab, owner, repo, fileName,
|
|
|
154
154
|
logger.debug(
|
|
155
155
|
`Unable to determine if a file named ${fileName} already exists in repo ${repo}: ${error}`
|
|
156
156
|
);
|
|
157
|
-
return
|
|
157
|
+
return void 0;
|
|
158
158
|
}
|
|
159
159
|
}
|
|
160
160
|
async function createOrUpdateFileInBranch(gitlab, owner, repo, branchName, fileName, fileContent) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"repoUtils.cjs.js","sources":["../../../src/gitlab/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 GitlabCredentials,\n GitLabIntegrationConfig,\n ScmIntegrations,\n} from '@backstage/integration';\n\nimport {\n AllGroupProjectsOptions,\n BasePaginationRequestOptions,\n Gitlab,\n OffsetPaginationRequestOptions,\n ProjectSchema,\n ShowExpanded,\n Sudo,\n} from '@gitbeaker/rest';\nimport gitUrlParse from 'git-url-parse';\n\nimport { getBranchName } from '../../catalog/catalogUtils';\nimport {\n DefaultPageNumber,\n DefaultPageSize,\n} from '../../service/handlers/handlers';\nimport { CustomGitlabCredentialsProvider } from '../GitlabAppManager';\nimport type {\n ExtendedGitlabCredentials,\n GitlabFetchError,\n GitlabRepository,\n} from '../types';\nimport { computeTotalCountFromPaginationInfo, handleError } from './utils';\n\nexport type ValidatedRepo = {\n glConfig: GitLabIntegrationConfig;\n credentials: ExtendedGitlabCredentials[];\n owner: string;\n repo: string;\n branchName: string;\n};\n\nexport async function validateAndBuildRepoData(\n gitlabCredentialsProvider: CustomGitlabCredentialsProvider,\n integrations: ScmIntegrations,\n config: Config,\n input: {\n repoUrl: string;\n },\n): Promise<ValidatedRepo> {\n const glConfig = integrations.gitlab.byUrl(input.repoUrl)?.config;\n if (!glConfig) {\n throw new Error(`Could not find GL 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 gitlabCredentialsProvider.getAllCredentials({\n host: glConfig.host,\n });\n if (credentials.length === 0) {\n throw new Error(`No credentials for GL integration`);\n }\n\n const branchName = getBranchName(config);\n return { glConfig, owner, repo, credentials, branchName };\n}\n\nexport async function searchRepos(\n gitlab: InstanceType<typeof Gitlab<false>>,\n glSearchQuery: string,\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n): Promise<{ totalCount?: number; repositories: GitlabRepository[] }> {\n const repoSearchResp = await gitlab.Projects.all<true, 'offset'>({\n search: glSearchQuery,\n membership: true,\n perPage: pageSize,\n page: pageNumber,\n });\n\n return {\n totalCount: repoSearchResp?.paginationInfo?.total,\n repositories:\n repoSearchResp?.data?.map((repo: ProjectSchema) => {\n return {\n name: repo.name,\n full_name: repo.path_with_namespace,\n url: repo._links.self,\n html_url: repo.web_url,\n default_branch: repo.default_branch,\n updated_at: repo.updated_at,\n };\n }) ?? [],\n };\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 addGitlabTokenRepositories(\n deps: {\n logger: LoggerService;\n },\n gitlab: InstanceType<typeof Gitlab<false>>,\n credential: GitlabCredentials,\n repositories: Map<string, GitlabRepository>,\n errors: Map<number, GitlabFetchError>,\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 // Use the projects api with the search param\n // that api gives us all the things the token has access to including the different projects in various groups\n\n const searchResp = await searchRepos(\n gitlab,\n search,\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 Projects.all method with the membership: true option will grab all the repositories/projects the gitlab 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 { data, paginationInfo } = await gitlab.Projects.all<\n true,\n 'offset'\n >({\n membership: true,\n perPage: pageSize,\n page: pageNumber,\n showExpanded: true,\n });\n\n data?.forEach((repo: ProjectSchema) => {\n repositories.set(repo.path_with_namespace, {\n name: repo.name,\n full_name: repo.path_with_namespace,\n url: repo._links.self,\n html_url: repo.web_url,\n default_branch: repo.default_branch,\n updated_at: repo?.updated_at,\n });\n });\n\n /*\n paginationInfo: {\n total: , This is the total amount of repos, but will be NaN if the value is above 10k, see: https://github.com/jdalrymple/gitbeaker/issues/839#issuecomment-636482319\n next: ,\n current: ,\n previous: ,\n perPage: ,\n totalPages:\n }\n */\n\n totalCount = await computeTotalCountFromPaginationInfo(\n deps,\n paginationInfo,\n pageSize, // Not thrilled with this for some reason\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 addGitlabTokenOrgRepositories(\n deps: {\n logger: LoggerService;\n },\n gitlab: InstanceType<typeof Gitlab<false>>,\n credential: GitlabCredentials,\n org: string,\n repositories: Map<string, GitlabRepository>,\n errors: Map<number, GitlabFetchError>,\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 // For Search: Use the group allProjects api with the search param.\n // I noticed that using this api will only return values when 3 or more characters are used for the search\n // that api gives us all the things the token has access\n const params:\n | (AllGroupProjectsOptions &\n BasePaginationRequestOptions<'offset'> &\n OffsetPaginationRequestOptions &\n Sudo &\n ShowExpanded<true>)\n | undefined = {\n perPage: pageSize,\n search: search ?? undefined,\n page: pageNumber,\n showExpanded: true,\n };\n\n const { data, paginationInfo } = await gitlab.Groups.allProjects<\n true,\n 'offset'\n >(org, params);\n\n data?.forEach((repo: ProjectSchema) => {\n repositories.set(repo.path_with_namespace, {\n name: repo.name,\n full_name: repo.path_with_namespace,\n url: repo._links.self,\n html_url: repo.web_url,\n default_branch: repo.default_branch,\n updated_at: repo.updated_at,\n });\n });\n\n totalCount = await computeTotalCountFromPaginationInfo(\n deps,\n paginationInfo,\n pageSize, // Not thrilled with this for some reason\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 gitlab: InstanceType<typeof Gitlab<false>>,\n owner: string,\n repo: string,\n fileName: string,\n defaultBranch: string = 'main',\n) {\n try {\n await gitlab.RepositoryFiles.show(\n `${owner}/${repo}`,\n fileName,\n defaultBranch,\n );\n return true;\n } catch (error: any) {\n if (error.cause.response.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 gitlab: InstanceType<typeof Gitlab<false>>,\n owner: string,\n repo: string,\n branchName: string,\n fileName: string,\n fileContent: string,\n): Promise<void> {\n try {\n const existingFile = await gitlab.RepositoryFiles.show(\n `${owner}/${repo}`,\n fileName,\n 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) || !('content_sha256' in existingFile)) {\n throw new Error(\n `The content at path ${fileName} is not a file or the response from gitlab does not contain the 'content_sha256' property.`,\n );\n }\n // If the file already exists, update it\n await gitlab.RepositoryFiles.edit(\n `${owner}/${repo}`,\n fileName,\n branchName,\n fileContent,\n `Add ${fileName} config file`,\n );\n } catch (error: any) {\n if (error.cause.response.status === 404) {\n // If the file does not exist, create it\n await gitlab.RepositoryFiles.create(\n `${owner}/${repo}`,\n fileName,\n branchName,\n fileContent,\n `Add ${fileName} config file`,\n );\n } else {\n throw error;\n }\n }\n}\n"],"names":["gitUrlParse","getBranchName","DefaultPageNumber","DefaultPageSize","computeTotalCountFromPaginationInfo","handleError"],"mappings":";;;;;;;;;;;AAwDA,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,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,CAAA,EAAI,IAAI,CAAA,CAAA;AAAA,MAChB,QAAA;AAAA,MACA,UAAA;AAAA,MACA,WAAA;AAAA,MACA,OAAO,QAAQ,CAAA,YAAA;AAAA,KACjB;AAAA,WACO,KAAY,EAAA;AACnB,IAAA,IAAI,KAAM,CAAA,KAAA,CAAM,QAAS,CAAA,MAAA,KAAW,GAAK,EAAA;AAEvC,MAAA,MAAM,OAAO,eAAgB,CAAA,MAAA;AAAA,QAC3B,CAAA,EAAG,KAAK,CAAA,CAAA,EAAI,IAAI,CAAA,CAAA;AAAA,QAChB,QAAA;AAAA,QACA,UAAA;AAAA,QACA,WAAA;AAAA,QACA,OAAO,QAAQ,CAAA,YAAA;AAAA,OACjB;AAAA,KACK,MAAA;AACL,MAAM,MAAA,KAAA;AAAA;AACR;AAEJ;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"repoUtils.cjs.js","sources":["../../../src/gitlab/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 GitlabCredentials,\n GitLabIntegrationConfig,\n ScmIntegrations,\n} from '@backstage/integration';\n\nimport {\n AllGroupProjectsOptions,\n BasePaginationRequestOptions,\n Gitlab,\n OffsetPaginationRequestOptions,\n ProjectSchema,\n ShowExpanded,\n Sudo,\n} from '@gitbeaker/rest';\nimport gitUrlParse from 'git-url-parse';\n\nimport { getBranchName } from '../../catalog/catalogUtils';\nimport {\n DefaultPageNumber,\n DefaultPageSize,\n} from '../../service/handlers/handlers';\nimport { CustomGitlabCredentialsProvider } from '../GitlabAppManager';\nimport type {\n ExtendedGitlabCredentials,\n GitlabFetchError,\n GitlabRepository,\n} from '../types';\nimport { computeTotalCountFromPaginationInfo, handleError } from './utils';\n\nexport type ValidatedRepo = {\n glConfig: GitLabIntegrationConfig;\n credentials: ExtendedGitlabCredentials[];\n owner: string;\n repo: string;\n branchName: string;\n};\n\nexport async function validateAndBuildRepoData(\n gitlabCredentialsProvider: CustomGitlabCredentialsProvider,\n integrations: ScmIntegrations,\n config: Config,\n input: {\n repoUrl: string;\n },\n): Promise<ValidatedRepo> {\n const glConfig = integrations.gitlab.byUrl(input.repoUrl)?.config;\n if (!glConfig) {\n throw new Error(`Could not find GL 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 gitlabCredentialsProvider.getAllCredentials({\n host: glConfig.host,\n });\n if (credentials.length === 0) {\n throw new Error(`No credentials for GL integration`);\n }\n\n const branchName = getBranchName(config);\n return { glConfig, owner, repo, credentials, branchName };\n}\n\nexport async function searchRepos(\n gitlab: InstanceType<typeof Gitlab<false>>,\n glSearchQuery: string,\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n): Promise<{ totalCount?: number; repositories: GitlabRepository[] }> {\n const repoSearchResp = await gitlab.Projects.all<true, 'offset'>({\n search: glSearchQuery,\n membership: true,\n perPage: pageSize,\n page: pageNumber,\n });\n\n return {\n totalCount: repoSearchResp?.paginationInfo?.total,\n repositories:\n repoSearchResp?.data?.map((repo: ProjectSchema) => {\n return {\n name: repo.name,\n full_name: repo.path_with_namespace,\n url: repo._links.self,\n html_url: repo.web_url,\n default_branch: repo.default_branch,\n updated_at: repo.updated_at,\n };\n }) ?? [],\n };\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 addGitlabTokenRepositories(\n deps: {\n logger: LoggerService;\n },\n gitlab: InstanceType<typeof Gitlab<false>>,\n credential: GitlabCredentials,\n repositories: Map<string, GitlabRepository>,\n errors: Map<number, GitlabFetchError>,\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 // Use the projects api with the search param\n // that api gives us all the things the token has access to including the different projects in various groups\n\n const searchResp = await searchRepos(\n gitlab,\n search,\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 Projects.all method with the membership: true option will grab all the repositories/projects the gitlab 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 { data, paginationInfo } = await gitlab.Projects.all<\n true,\n 'offset'\n >({\n membership: true,\n perPage: pageSize,\n page: pageNumber,\n showExpanded: true,\n });\n\n data?.forEach((repo: ProjectSchema) => {\n repositories.set(repo.path_with_namespace, {\n name: repo.name,\n full_name: repo.path_with_namespace,\n url: repo._links.self,\n html_url: repo.web_url,\n default_branch: repo.default_branch,\n updated_at: repo?.updated_at,\n });\n });\n\n /*\n paginationInfo: {\n total: , This is the total amount of repos, but will be NaN if the value is above 10k, see: https://github.com/jdalrymple/gitbeaker/issues/839#issuecomment-636482319\n next: ,\n current: ,\n previous: ,\n perPage: ,\n totalPages:\n }\n */\n\n totalCount = await computeTotalCountFromPaginationInfo(\n deps,\n paginationInfo,\n pageSize, // Not thrilled with this for some reason\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 addGitlabTokenOrgRepositories(\n deps: {\n logger: LoggerService;\n },\n gitlab: InstanceType<typeof Gitlab<false>>,\n credential: GitlabCredentials,\n org: string,\n repositories: Map<string, GitlabRepository>,\n errors: Map<number, GitlabFetchError>,\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 // For Search: Use the group allProjects api with the search param.\n // I noticed that using this api will only return values when 3 or more characters are used for the search\n // that api gives us all the things the token has access\n const params:\n | (AllGroupProjectsOptions &\n BasePaginationRequestOptions<'offset'> &\n OffsetPaginationRequestOptions &\n Sudo &\n ShowExpanded<true>)\n | undefined = {\n perPage: pageSize,\n search: search ?? undefined,\n page: pageNumber,\n showExpanded: true,\n };\n\n const { data, paginationInfo } = await gitlab.Groups.allProjects<\n true,\n 'offset'\n >(org, params);\n\n data?.forEach((repo: ProjectSchema) => {\n repositories.set(repo.path_with_namespace, {\n name: repo.name,\n full_name: repo.path_with_namespace,\n url: repo._links.self,\n html_url: repo.web_url,\n default_branch: repo.default_branch,\n updated_at: repo.updated_at,\n });\n });\n\n totalCount = await computeTotalCountFromPaginationInfo(\n deps,\n paginationInfo,\n pageSize, // Not thrilled with this for some reason\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 gitlab: InstanceType<typeof Gitlab<false>>,\n owner: string,\n repo: string,\n fileName: string,\n defaultBranch: string = 'main',\n) {\n try {\n await gitlab.RepositoryFiles.show(\n `${owner}/${repo}`,\n fileName,\n defaultBranch,\n );\n return true;\n } catch (error: any) {\n if (error.cause.response.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 gitlab: InstanceType<typeof Gitlab<false>>,\n owner: string,\n repo: string,\n branchName: string,\n fileName: string,\n fileContent: string,\n): Promise<void> {\n try {\n const existingFile = await gitlab.RepositoryFiles.show(\n `${owner}/${repo}`,\n fileName,\n 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) || !('content_sha256' in existingFile)) {\n throw new Error(\n `The content at path ${fileName} is not a file or the response from gitlab does not contain the 'content_sha256' property.`,\n );\n }\n // If the file already exists, update it\n await gitlab.RepositoryFiles.edit(\n `${owner}/${repo}`,\n fileName,\n branchName,\n fileContent,\n `Add ${fileName} config file`,\n );\n } catch (error: any) {\n if (error.cause.response.status === 404) {\n // If the file does not exist, create it\n await gitlab.RepositoryFiles.create(\n `${owner}/${repo}`,\n fileName,\n branchName,\n fileContent,\n `Add ${fileName} config file`,\n );\n } else {\n throw error;\n }\n }\n}\n"],"names":["gitUrlParse","getBranchName","DefaultPageNumber","DefaultPageSize","computeTotalCountFromPaginationInfo","handleError"],"mappings":";;;;;;;;;;;AAwDA,eAAsB,wBAAA,CACpB,yBAAA,EACA,YAAA,EACA,MAAA,EACA,KAAA,EAGwB;AACxB,EAAA,MAAM,WAAW,YAAA,CAAa,MAAA,CAAO,KAAA,CAAM,KAAA,CAAM,OAAO,CAAA,EAAG,MAAA;AAC3D,EAAA,IAAI,CAAC,QAAA,EAAU;AACb,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,mCAAA,EAAsC,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA;AAAA,EACvE;AAEA,EAAA,MAAM,MAAA,GAASA,4BAAA,CAAY,KAAA,CAAM,OAAO,CAAA;AACxC,EAAA,MAAM,QAAQ,MAAA,CAAO,YAAA;AACrB,EAAA,MAAM,OAAO,MAAA,CAAO,IAAA;AAEpB,EAAA,MAAM,WAAA,GAAc,MAAM,yBAAA,CAA0B,iBAAA,CAAkB;AAAA,IACp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AChB,QAAA;AAAA,MACA,UAAA;AAAA,MACA,WAAA;AAAA,MACA,OAAO,QAAQ,CAAA,YAAA;AAAA,KACjB;AAAA,EACF,SAAS,KAAA,EAAY;AACnB,IAAA,IAAI,KAAA,CAAM,KAAA,CAAM,QAAA,CAAS,MAAA,KAAW,GAAA,EAAK;AAEvC,MAAA,MAAM,OAAO,eAAA,CAAgB,MAAA;AAAA,QAC3B,CAAA,EAAG,KAAK,CAAA,CAAA,EAAI,IAAI,CAAA,CAAA;AAAA,QAChB,QAAA;AAAA,QACA,UAAA;AAAA,QACA,WAAA;AAAA,QACA,OAAO,QAAQ,CAAA,YAAA;AAAA,OACjB;AAAA,IACF,CAAA,MAAO;AACL,MAAA,MAAM,KAAA;AAAA,IACR;AAAA,EACF;AACF;;;;;;;;;"}
|
|
@@ -20,7 +20,7 @@ function createCredentialError(err) {
|
|
|
20
20
|
}
|
|
21
21
|
};
|
|
22
22
|
}
|
|
23
|
-
return
|
|
23
|
+
return void 0;
|
|
24
24
|
}
|
|
25
25
|
function verifyAndGetIntegrations(deps, integrations) {
|
|
26
26
|
const glConfigs = integrations.gitlab.list().map((glInit) => glInit.config);
|
|
@@ -85,7 +85,7 @@ async function executeFunctionOnFirstSuccessfulIntegration(deps, integrations, p
|
|
|
85
85
|
}
|
|
86
86
|
return res.result;
|
|
87
87
|
}
|
|
88
|
-
return
|
|
88
|
+
return void 0;
|
|
89
89
|
}
|
|
90
90
|
async function fetchFromAllIntegrations(deps, integrations, params) {
|
|
91
91
|
const glConfigs = verifyAndGetIntegrations(deps, integrations);
|
|
@@ -105,7 +105,7 @@ async function fetchFromAllIntegrations(deps, integrations, params) {
|
|
|
105
105
|
`Got ${credentials.length} credential(s) for ${glConfig.host}`
|
|
106
106
|
);
|
|
107
107
|
for (const credential of credentials) {
|
|
108
|
-
const glKit = glUtils.buildGitlab(deps, { credential
|
|
108
|
+
const glKit = glUtils.buildGitlab(deps, { credential}, glConfig.baseUrl);
|
|
109
109
|
const res = await params.dataFetcher(glKit, credential, glConfig);
|
|
110
110
|
res.errors?.forEach((err) => dataErrs.push(err));
|
|
111
111
|
if (res.result) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs.js","sources":["../../../src/gitlab/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 GitLabIntegrationConfig,\n} from '@backstage/integration';\n\nimport { Gitlab, OffsetPagination } from '@gitbeaker/rest';\n\nimport { logErrorIfNeeded } from '../../helpers';\nimport type { CustomGitlabCredentialsProvider } from '../GitlabAppManager';\nimport {\n type ExtendedGitlabCredentials,\n type GitlabFetchError,\n} from '../types';\nimport { buildGitlab } from './glUtils';\nimport { validateAndBuildRepoData, ValidatedRepo } from './repoUtils';\n\n// /**\n// * Creates the GitlabFetchError to be stored in the returned errors array of the returned GitlabRepositoryResponse object\n// */\nexport function createCredentialError(\n err?: Error,\n): GitlabFetchError | undefined {\n if (err) {\n return {\n type: 'token',\n error: {\n name: err.name,\n message: err.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 glConfigs = integrations.gitlab.list().map(glInit => glInit.config);\n\n if (glConfigs.length === 0) {\n deps.logger.debug(\n 'No GitLab Integration in config => returning an empty list of repositories.',\n );\n throw new Error(\n \"Looks like there is no GitLab Integration in config. Please add a configuration entry under 'integrations.gitlab\",\n );\n }\n return glConfigs;\n}\n\nexport async function getCredentialsFromIntegrations(\n gitlabCredentialsProvider: CustomGitlabCredentialsProvider,\n glConfigs: GitLabIntegrationConfig[],\n) {\n const credentialsByConfig = new Map<\n GitLabIntegrationConfig,\n ExtendedGitlabCredentials[]\n >();\n for (const glConfig of glConfigs) {\n const creds = await getCredentialsForConfig(\n gitlabCredentialsProvider,\n glConfig,\n );\n credentialsByConfig.set(glConfig, creds);\n }\n return credentialsByConfig;\n}\n\nexport async function getCredentialsForConfig(\n gitlabCredentialsProvider: CustomGitlabCredentialsProvider,\n glConfig: GitLabIntegrationConfig,\n) {\n return await gitlabCredentialsProvider.getAllCredentials({\n host: glConfig.host,\n });\n}\n\nexport function handleError(\n deps: {\n logger: LoggerService;\n },\n desc: string,\n _credential: ExtendedGitlabCredentials,\n errors: Map<number, GitlabFetchError>,\n err: any,\n) {\n logErrorIfNeeded(deps.logger, `${desc} failed`, err);\n const credentialError = createCredentialError(err as Error);\n if (credentialError) {\n errors.set(-1, credentialError);\n }\n}\n\nexport async function computeTotalCountFromPaginationInfo(\n deps: {\n logger: LoggerService;\n },\n paginationInfo: OffsetPagination,\n pageSize?: number,\n): Promise<number | undefined> {\n /*\n paginationInfo: {\n total: , This is the total amount of repos, but will be NaN if the value is above 10k, see: https://github.com/jdalrymple/gitbeaker/issues/839#issuecomment-636482319\n next: ,\n current: ,\n previous: ,\n perPage: ,\n totalPages:\n }\n */\n\n if (isNaN(paginationInfo.total)) {\n deps.logger.debug(\n `Too many result, total count is NaN, returning current page size`,\n );\n return pageSize;\n }\n return paginationInfo.total;\n}\n\nexport async function executeFunctionOnFirstSuccessfulIntegration<T>(\n deps: {\n logger: LoggerService;\n cache: CacheService;\n config: Config;\n gitlabCredentialsProvider: CustomGitlabCredentialsProvider;\n },\n integrations: ScmIntegrations,\n params: {\n repoUrl: string;\n fn: (\n validatedRepo: ValidatedRepo,\n gitlab: InstanceType<typeof Gitlab<false>>,\n ) => Promise<{ successful: boolean; result?: T }>;\n },\n) {\n const validatedRepo = await validateAndBuildRepoData(\n deps.gitlabCredentialsProvider,\n integrations,\n deps.config,\n params,\n );\n for (const credential of validatedRepo.credentials) {\n const glKit = buildGitlab(\n deps,\n { credential, owner: validatedRepo.owner },\n validatedRepo.glConfig.baseUrl,\n );\n const res = await params.fn(validatedRepo, glKit);\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 gitlabCredentialsProvider: CustomGitlabCredentialsProvider;\n },\n integrations: ScmIntegrations,\n params: {\n dataFetcher: (\n gitlab: InstanceType<typeof Gitlab<false>>,\n credential: ExtendedGitlabCredentials,\n glConfig: GitLabIntegrationConfig,\n ) => Promise<{\n stopFetchingData?: boolean;\n result?: T;\n errors?: GitlabFetchError[];\n }>;\n },\n) {\n const glConfigs = verifyAndGetIntegrations(deps, integrations);\n\n const credentialsByConfig = await getCredentialsFromIntegrations(\n deps.gitlabCredentialsProvider,\n glConfigs,\n );\n const errors = new Map<number, GitlabFetchError>();\n const data: T[] = [];\n const dataErrs: GitlabFetchError[] = [];\n let stopFetchingData: boolean | undefined = false;\n for (const [glConfig, credentials] of credentialsByConfig) {\n if (stopFetchingData) {\n break;\n }\n deps.logger.debug(\n `Got ${credentials.length} credential(s) for ${glConfig.host}`,\n );\n for (const credential of credentials) {\n const glKit = buildGitlab(deps, { credential, errors }, glConfig.baseUrl);\n const res = await params.dataFetcher(glKit, credential, glConfig);\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, GitlabFetchError>();\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"],"names":["logErrorIfNeeded","validateAndBuildRepoData","buildGitlab"],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AE,IAAM,EAAA,MAAA,EAAQ,gBAAiB,EAAA;AAC1C;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"utils.cjs.js","sources":["../../../src/gitlab/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 GitLabIntegrationConfig,\n} from '@backstage/integration';\n\nimport { Gitlab, OffsetPagination } from '@gitbeaker/rest';\n\nimport { logErrorIfNeeded } from '../../helpers';\nimport type { CustomGitlabCredentialsProvider } from '../GitlabAppManager';\nimport {\n type ExtendedGitlabCredentials,\n type GitlabFetchError,\n} from '../types';\nimport { buildGitlab } from './glUtils';\nimport { validateAndBuildRepoData, ValidatedRepo } from './repoUtils';\n\n// /**\n// * Creates the GitlabFetchError to be stored in the returned errors array of the returned GitlabRepositoryResponse object\n// */\nexport function createCredentialError(\n err?: Error,\n): GitlabFetchError | undefined {\n if (err) {\n return {\n type: 'token',\n error: {\n name: err.name,\n message: err.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 glConfigs = integrations.gitlab.list().map(glInit => glInit.config);\n\n if (glConfigs.length === 0) {\n deps.logger.debug(\n 'No GitLab Integration in config => returning an empty list of repositories.',\n );\n throw new Error(\n \"Looks like there is no GitLab Integration in config. Please add a configuration entry under 'integrations.gitlab\",\n );\n }\n return glConfigs;\n}\n\nexport async function getCredentialsFromIntegrations(\n gitlabCredentialsProvider: CustomGitlabCredentialsProvider,\n glConfigs: GitLabIntegrationConfig[],\n) {\n const credentialsByConfig = new Map<\n GitLabIntegrationConfig,\n ExtendedGitlabCredentials[]\n >();\n for (const glConfig of glConfigs) {\n const creds = await getCredentialsForConfig(\n gitlabCredentialsProvider,\n glConfig,\n );\n credentialsByConfig.set(glConfig, creds);\n }\n return credentialsByConfig;\n}\n\nexport async function getCredentialsForConfig(\n gitlabCredentialsProvider: CustomGitlabCredentialsProvider,\n glConfig: GitLabIntegrationConfig,\n) {\n return await gitlabCredentialsProvider.getAllCredentials({\n host: glConfig.host,\n });\n}\n\nexport function handleError(\n deps: {\n logger: LoggerService;\n },\n desc: string,\n _credential: ExtendedGitlabCredentials,\n errors: Map<number, GitlabFetchError>,\n err: any,\n) {\n logErrorIfNeeded(deps.logger, `${desc} failed`, err);\n const credentialError = createCredentialError(err as Error);\n if (credentialError) {\n errors.set(-1, credentialError);\n }\n}\n\nexport async function computeTotalCountFromPaginationInfo(\n deps: {\n logger: LoggerService;\n },\n paginationInfo: OffsetPagination,\n pageSize?: number,\n): Promise<number | undefined> {\n /*\n paginationInfo: {\n total: , This is the total amount of repos, but will be NaN if the value is above 10k, see: https://github.com/jdalrymple/gitbeaker/issues/839#issuecomment-636482319\n next: ,\n current: ,\n previous: ,\n perPage: ,\n totalPages:\n }\n */\n\n if (isNaN(paginationInfo.total)) {\n deps.logger.debug(\n `Too many result, total count is NaN, returning current page size`,\n );\n return pageSize;\n }\n return paginationInfo.total;\n}\n\nexport async function executeFunctionOnFirstSuccessfulIntegration<T>(\n deps: {\n logger: LoggerService;\n cache: CacheService;\n config: Config;\n gitlabCredentialsProvider: CustomGitlabCredentialsProvider;\n },\n integrations: ScmIntegrations,\n params: {\n repoUrl: string;\n fn: (\n validatedRepo: ValidatedRepo,\n gitlab: InstanceType<typeof Gitlab<false>>,\n ) => Promise<{ successful: boolean; result?: T }>;\n },\n) {\n const validatedRepo = await validateAndBuildRepoData(\n deps.gitlabCredentialsProvider,\n integrations,\n deps.config,\n params,\n );\n for (const credential of validatedRepo.credentials) {\n const glKit = buildGitlab(\n deps,\n { credential, owner: validatedRepo.owner },\n validatedRepo.glConfig.baseUrl,\n );\n const res = await params.fn(validatedRepo, glKit);\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 gitlabCredentialsProvider: CustomGitlabCredentialsProvider;\n },\n integrations: ScmIntegrations,\n params: {\n dataFetcher: (\n gitlab: InstanceType<typeof Gitlab<false>>,\n credential: ExtendedGitlabCredentials,\n glConfig: GitLabIntegrationConfig,\n ) => Promise<{\n stopFetchingData?: boolean;\n result?: T;\n errors?: GitlabFetchError[];\n }>;\n },\n) {\n const glConfigs = verifyAndGetIntegrations(deps, integrations);\n\n const credentialsByConfig = await getCredentialsFromIntegrations(\n deps.gitlabCredentialsProvider,\n glConfigs,\n );\n const errors = new Map<number, GitlabFetchError>();\n const data: T[] = [];\n const dataErrs: GitlabFetchError[] = [];\n let stopFetchingData: boolean | undefined = false;\n for (const [glConfig, credentials] of credentialsByConfig) {\n if (stopFetchingData) {\n break;\n }\n deps.logger.debug(\n `Got ${credentials.length} credential(s) for ${glConfig.host}`,\n );\n for (const credential of credentials) {\n const glKit = buildGitlab(deps, { credential, errors }, glConfig.baseUrl);\n const res = await params.dataFetcher(glKit, credential, glConfig);\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, GitlabFetchError>();\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"],"names":["logErrorIfNeeded","validateAndBuildRepoData","buildGitlab"],"mappings":";;;;;;;;;;;;AAwCO,SAAS,sBACd,GA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,IAAA,EAAM,MAAA,EAAQ,gBAAA,EAAiB;AAC1C;;;;;;;;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auditorUtils.cjs.js","sources":["../../src/helpers/auditorUtils.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 AuditorService,\n AuditorServiceEvent,\n} from '@backstage/backend-plugin-api';\nimport { JsonObject } from '@backstage/types';\n\nimport express from 'express';\nimport kebabCase from 'just-kebab-case';\n\nconst UNKNOWN_ENDPOINT_EVENT = `unknown-endpoint`;\n\nexport async function auditCreateEvent(\n auditor: AuditorService,\n eventId: string | undefined,\n req: express.Request,\n meta?: JsonObject,\n): Promise<AuditorServiceEvent> {\n return await auditor.createEvent({\n eventId: eventId ? kebabCase(eventId) : UNKNOWN_ENDPOINT_EVENT,\n severityLevel: 'medium',\n request: req,\n meta,\n });\n}\n"],"names":["kebabCase"],"mappings":";;;;;;;;AAyBA,MAAM,
|
|
1
|
+
{"version":3,"file":"auditorUtils.cjs.js","sources":["../../src/helpers/auditorUtils.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 AuditorService,\n AuditorServiceEvent,\n} from '@backstage/backend-plugin-api';\nimport { JsonObject } from '@backstage/types';\n\nimport express from 'express';\nimport kebabCase from 'just-kebab-case';\n\nconst UNKNOWN_ENDPOINT_EVENT = `unknown-endpoint`;\n\nexport async function auditCreateEvent(\n auditor: AuditorService,\n eventId: string | undefined,\n req: express.Request,\n meta?: JsonObject,\n): Promise<AuditorServiceEvent> {\n return await auditor.createEvent({\n eventId: eventId ? kebabCase(eventId) : UNKNOWN_ENDPOINT_EVENT,\n severityLevel: 'medium',\n request: req,\n meta,\n });\n}\n"],"names":["kebabCase"],"mappings":";;;;;;;;AAyBA,MAAM,sBAAA,GAAyB,CAAA,gBAAA,CAAA;AAE/B,eAAsB,gBAAA,CACpB,OAAA,EACA,OAAA,EACA,GAAA,EACA,IAAA,EAC8B;AAC9B,EAAA,OAAO,MAAM,QAAQ,WAAA,CAAY;AAAA,IAC/B,OAAA,EAAS,OAAA,GAAUA,0BAAA,CAAU,OAAO,CAAA,GAAI,sBAAA;AAAA,IACxC,aAAA,EAAe,QAAA;AAAA,IACf,OAAA,EAAS,GAAA;AAAA,IACT;AAAA,GACD,CAAA;AACH;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.cjs.js","sources":["../../src/helpers/auth.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 AuditorService,\n AuthService,\n HttpAuthService,\n PermissionsService,\n} from '@backstage/backend-plugin-api';\nimport { NotAllowedError } from '@backstage/errors';\nimport { AuthorizeResult } from '@backstage/plugin-permission-common';\n\nimport express from 'express';\n\nimport { bulkImportPermission } from '@red-hat-developer-hub/backstage-plugin-bulk-import-common';\n\nimport { auditCreateEvent } from './auditorUtils';\n\n/**\n * This will resolve to { result: AuthorizeResult.ALLOW } if the permission framework is disabled\n */\nexport async function permissionCheck(\n auditor: AuditorService,\n openApiOperationId: string | undefined,\n permissions: PermissionsService,\n httpAuth: HttpAuthService,\n req: express.Request,\n) {\n const decision = (\n await permissions.authorize(\n [\n {\n permission: bulkImportPermission,\n resourceRef: bulkImportPermission.resourceType,\n },\n ],\n {\n credentials: await httpAuth.credentials(req),\n },\n )\n )[0];\n\n if (decision.result === AuthorizeResult.DENY) {\n const err = new NotAllowedError('Unauthorized');\n const auditorEvent = await auditCreateEvent(\n auditor,\n openApiOperationId,\n req,\n );\n await auditorEvent.fail({ error: err, meta: { responseStatus: 403 } });\n throw err;\n }\n}\n\nexport async function getTokenForPlugin(\n auth: AuthService,\n targetPluginId: string,\n): Promise<string> {\n const resp = await auth.getPluginRequestToken({\n onBehalfOf: await auth.getOwnServiceCredentials(),\n targetPluginId,\n });\n return resp.token;\n}\n"],"names":["bulkImportPermission","AuthorizeResult","NotAllowedError","auditCreateEvent"],"mappings":";;;;;;;AAkCA,eAAsB,
|
|
1
|
+
{"version":3,"file":"auth.cjs.js","sources":["../../src/helpers/auth.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 AuditorService,\n AuthService,\n HttpAuthService,\n PermissionsService,\n} from '@backstage/backend-plugin-api';\nimport { NotAllowedError } from '@backstage/errors';\nimport { AuthorizeResult } from '@backstage/plugin-permission-common';\n\nimport express from 'express';\n\nimport { bulkImportPermission } from '@red-hat-developer-hub/backstage-plugin-bulk-import-common';\n\nimport { auditCreateEvent } from './auditorUtils';\n\n/**\n * This will resolve to { result: AuthorizeResult.ALLOW } if the permission framework is disabled\n */\nexport async function permissionCheck(\n auditor: AuditorService,\n openApiOperationId: string | undefined,\n permissions: PermissionsService,\n httpAuth: HttpAuthService,\n req: express.Request,\n) {\n const decision = (\n await permissions.authorize(\n [\n {\n permission: bulkImportPermission,\n resourceRef: bulkImportPermission.resourceType,\n },\n ],\n {\n credentials: await httpAuth.credentials(req),\n },\n )\n )[0];\n\n if (decision.result === AuthorizeResult.DENY) {\n const err = new NotAllowedError('Unauthorized');\n const auditorEvent = await auditCreateEvent(\n auditor,\n openApiOperationId,\n req,\n );\n await auditorEvent.fail({ error: err, meta: { responseStatus: 403 } });\n throw err;\n }\n}\n\nexport async function getTokenForPlugin(\n auth: AuthService,\n targetPluginId: string,\n): Promise<string> {\n const resp = await auth.getPluginRequestToken({\n onBehalfOf: await auth.getOwnServiceCredentials(),\n targetPluginId,\n });\n return resp.token;\n}\n"],"names":["bulkImportPermission","AuthorizeResult","NotAllowedError","auditCreateEvent"],"mappings":";;;;;;;AAkCA,eAAsB,eAAA,CACpB,OAAA,EACA,kBAAA,EACA,WAAA,EACA,UACA,GAAA,EACA;AACA,EAAA,MAAM,QAAA,GAAA,CACJ,MAAM,WAAA,CAAY,SAAA;AAAA,IAChB;AAAA,MACE;AAAA,QACE,UAAA,EAAYA,oDAAA;AAAA,QACZ,aAAaA,oDAAA,CAAqB;AAAA;AACpC,KACF;AAAA,IACA;AAAA,MACE,WAAA,EAAa,MAAM,QAAA,CAAS,WAAA,CAAY,GAAG;AAAA;AAC7C,KAEF,CAAC,CAAA;AAEH,EAAA,IAAI,QAAA,CAAS,MAAA,KAAWC,sCAAA,CAAgB,IAAA,EAAM;AAC5C,IAAA,MAAM,GAAA,GAAM,IAAIC,sBAAA,CAAgB,cAAc,CAAA;AAC9C,IAAA,MAAM,eAAe,MAAMC,6BAAA;AAAA,MACzB,OAAA;AAAA,MACA,kBAAA;AAAA,MACA;AAAA,KACF;AACA,IAAA,MAAM,YAAA,CAAa,IAAA,CAAK,EAAE,KAAA,EAAO,GAAA,EAAK,MAAM,EAAE,cAAA,EAAgB,GAAA,EAAI,EAAG,CAAA;AACrE,IAAA,MAAM,GAAA;AAAA,EACR;AACF;AAEA,eAAsB,iBAAA,CACpB,MACA,cAAA,EACiB;AACjB,EAAA,MAAM,IAAA,GAAO,MAAM,IAAA,CAAK,qBAAA,CAAsB;AAAA,IAC5C,UAAA,EAAY,MAAM,IAAA,CAAK,wBAAA,EAAyB;AAAA,IAChD;AAAA,GACD,CAAA;AACD,EAAA,OAAO,IAAA,CAAK,KAAA;AACd;;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loggingUtils.cjs.js","sources":["../../src/helpers/loggingUtils.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 { isError } from '@backstage/errors';\n\n/**\n * Logs the error specified by ensuring no sensitive internal data is disclosed.\n * @param logger the logger\n * @param logMsg the log message\n * @param error the error\n */\nexport function logErrorIfNeeded(\n logger: LoggerService,\n logMsg: string,\n error: any,\n) {\n if (isError(error)) {\n // Ensure that we don't log any sensitive internal data:\n logger.error(logMsg, {\n // Default Error properties:\n name: error.name,\n message: error.message,\n stack: error.stack,\n // Additional status code if available:\n status: (error.response as { status?: string })?.status,\n });\n }\n}\n"],"names":["isError"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"loggingUtils.cjs.js","sources":["../../src/helpers/loggingUtils.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 { isError } from '@backstage/errors';\n\n/**\n * Logs the error specified by ensuring no sensitive internal data is disclosed.\n * @param logger the logger\n * @param logMsg the log message\n * @param error the error\n */\nexport function logErrorIfNeeded(\n logger: LoggerService,\n logMsg: string,\n error: any,\n) {\n if (isError(error)) {\n // Ensure that we don't log any sensitive internal data:\n logger.error(logMsg, {\n // Default Error properties:\n name: error.name,\n message: error.message,\n stack: error.stack,\n // Additional status code if available:\n status: (error.response as { status?: string })?.status,\n });\n }\n}\n"],"names":["isError"],"mappings":";;;;AAyBO,SAAS,gBAAA,CACd,MAAA,EACA,MAAA,EACA,KAAA,EACA;AACA,EAAA,IAAIA,cAAA,CAAQ,KAAK,CAAA,EAAG;AAElB,IAAA,MAAA,CAAO,MAAM,MAAA,EAAQ;AAAA;AAAA,MAEnB,MAAM,KAAA,CAAM,IAAA;AAAA,MACZ,SAAS,KAAA,CAAM,OAAA;AAAA,MACf,OAAO,KAAA,CAAM,KAAA;AAAA;AAAA,MAEb,MAAA,EAAS,MAAM,QAAA,EAAkC;AAAA,KAClD,CAAA;AAAA,EACH;AACF;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pagination.cjs.js","sources":["../../src/helpers/pagination.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\n/**\n * Returns a paginated chunk of the specified array\n * @param array the array to paginate\n * @param page the page number\n * @param size the maximum number of elements in each page\n */\nexport function paginateArray<T>(\n array: T[] | undefined,\n page: number,\n size: number,\n): { result: T[]; totalCount: number } {\n if (page <= 0) {\n throw new Error(`page must be >0. Got page=${page}`);\n }\n if (size < 0) {\n throw new Error(`size must be >=0. Got size=${size}`);\n }\n\n const startIndex = (page - 1) * size;\n const endIndex = startIndex + size;\n\n return {\n result: array?.slice(startIndex, endIndex) ?? [],\n totalCount: array?.length ?? 0,\n };\n}\n"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"pagination.cjs.js","sources":["../../src/helpers/pagination.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\n/**\n * Returns a paginated chunk of the specified array\n * @param array the array to paginate\n * @param page the page number\n * @param size the maximum number of elements in each page\n */\nexport function paginateArray<T>(\n array: T[] | undefined,\n page: number,\n size: number,\n): { result: T[]; totalCount: number } {\n if (page <= 0) {\n throw new Error(`page must be >0. Got page=${page}`);\n }\n if (size < 0) {\n throw new Error(`size must be >=0. Got size=${size}`);\n }\n\n const startIndex = (page - 1) * size;\n const endIndex = startIndex + size;\n\n return {\n result: array?.slice(startIndex, endIndex) ?? [],\n totalCount: array?.length ?? 0,\n };\n}\n"],"names":[],"mappings":";;AAsBO,SAAS,aAAA,CACd,KAAA,EACA,IAAA,EACA,IAAA,EACqC;AACrC,EAAA,IAAI,QAAQ,CAAA,EAAG;AACb,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,0BAAA,EAA6B,IAAI,CAAA,CAAE,CAAA;AAAA,EACrD;AACA,EAAA,IAAI,OAAO,CAAA,EAAG;AACZ,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,2BAAA,EAA8B,IAAI,CAAA,CAAE,CAAA;AAAA,EACtD;AAEA,EAAA,MAAM,UAAA,GAAA,CAAc,OAAO,CAAA,IAAK,IAAA;AAChC,EAAA,MAAM,WAAW,UAAA,GAAa,IAAA;AAE9B,EAAA,OAAO;AAAA,IACL,QAAQ,KAAA,EAAO,KAAA,CAAM,UAAA,EAAY,QAAQ,KAAK,EAAC;AAAA,IAC/C,UAAA,EAAY,OAAO,MAAA,IAAU;AAAA,GAC/B;AACF;;;;"}
|
|
@@ -10,7 +10,7 @@ var gitUrlParse__default = /*#__PURE__*/_interopDefaultCompat(gitUrlParse);
|
|
|
10
10
|
|
|
11
11
|
function getNestedValue(obj, path) {
|
|
12
12
|
return path.split(".").reduce(
|
|
13
|
-
(acc, key) => acc && acc[key] ? acc[key] :
|
|
13
|
+
(acc, key) => acc && acc[key] ? acc[key] : void 0,
|
|
14
14
|
obj
|
|
15
15
|
);
|
|
16
16
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs.js","sources":["../../src/helpers/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 { parseEntityRef, stringifyEntityRef } from '@backstage/catalog-model';\nimport { InputError } from '@backstage/errors';\n\nimport gitUrlParse from 'git-url-parse';\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\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\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 parseGitURLForApprovalTool(repoUrl: string) {\n const parsedRepoUrl = new URL(repoUrl);\n if (parsedRepoUrl.hostname.includes('gitlab')) {\n return 'GITLAB';\n }\n\n return 'GIT';\n}\n\nexport function getImportTemplateRef(templateRef: string): string {\n try {\n const { name, namespace, kind } = parseEntityRef(templateRef, {\n defaultKind: 'template',\n defaultNamespace: 'default',\n });\n\n if (kind !== 'template') {\n throw new InputError(\n `Invalid 'kind' in bulkImport.importTemplate: expected 'template' but got '${kind}'.`,\n );\n }\n\n return stringifyEntityRef({ kind, namespace, name });\n } catch (err) {\n throw new InputError(\n `Invalid scaffolder template entity reference in the configuration 'bulkImport.importTemplate': '${templateRef}'. ` +\n `Error: ${(err as Error).message}`,\n );\n }\n}\n"],"names":["gitUrlParse","parseEntityRef","InputError","stringifyEntityRef"],"mappings":";;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"utils.cjs.js","sources":["../../src/helpers/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 { parseEntityRef, stringifyEntityRef } from '@backstage/catalog-model';\nimport { InputError } from '@backstage/errors';\n\nimport gitUrlParse from 'git-url-parse';\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\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\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 parseGitURLForApprovalTool(repoUrl: string) {\n const parsedRepoUrl = new URL(repoUrl);\n if (parsedRepoUrl.hostname.includes('gitlab')) {\n return 'GITLAB';\n }\n\n return 'GIT';\n}\n\nexport function getImportTemplateRef(templateRef: string): string {\n try {\n const { name, namespace, kind } = parseEntityRef(templateRef, {\n defaultKind: 'template',\n defaultNamespace: 'default',\n });\n\n if (kind !== 'template') {\n throw new InputError(\n `Invalid 'kind' in bulkImport.importTemplate: expected 'template' but got '${kind}'.`,\n );\n }\n\n return stringifyEntityRef({ kind, namespace, name });\n } catch (err) {\n throw new InputError(\n `Invalid scaffolder template entity reference in the configuration 'bulkImport.importTemplate': '${templateRef}'. ` +\n `Error: ${(err as Error).message}`,\n );\n }\n}\n"],"names":["gitUrlParse","parseEntityRef","InputError","stringifyEntityRef"],"mappings":";;;;;;;;;;AAqBO,SAAS,cAAA,CAAkB,KAAQ,IAAA,EAAmB;AAC3D,EAAA,OAAO,IAAA,CACJ,KAAA,CAAM,GAAG,CAAA,CACT,MAAA;AAAA,IACC,CAAC,KAAK,GAAA,KACJ,GAAA,IAAQ,IAA4B,GAAG,CAAA,GAClC,GAAA,CAA4B,GAAG,CAAA,GAChC,MAAA;AAAA,IACN;AAAA,GACF;AACJ;AAEO,SAAS,wBAAwB,YAAA,EAAwB;AAC9D,EAAA,MAAM,mBAAA,uBAA0B,GAAA,EAAoB;AACpD,EAAA,KAAA,MAAW,eAAe,YAAA,EAAc;AACtC,IAAA,MAAM,KAAA,GAAQ,WAAA,CAAY,KAAA,CAAM,QAAQ,CAAA;AACxC,IAAA,IAAI,KAAA,CAAM,SAAS,CAAA,EAAG;AACpB,MAAA;AAAA,IACF;AACA,IAAA,mBAAA,CAAoB,IAAI,WAAA,EAAaA,4BAAA,CAAY,MAAM,CAAC,CAAC,EAAE,KAAK,CAAA;AAAA,EAClE;AACA,EAAA,OAAO,mBAAA;AACT;AAEO,SAAS,iBAAA,CACd,IAAA,EACA,SAAA,EACA,QAAA,EACA;AACA,EAAA,IAAI,aAAa,SAAA,CAAU,MAAA;AAAA,IACzB,CAAC,WAAA,EAAa,YAAA,KAAiB,WAAA,GAAc,YAAA;AAAA,IAC7C;AAAA,GACF;AACA,EAAA,IAAI,aAAa,QAAA,EAAU;AACzB,IAAA,UAAA,GAAa,IAAA,CAAK,MAAA;AAAA,EACpB;AACA,EAAA,OAAO,UAAA;AACT;AAEO,SAAS,2BAA2B,OAAA,EAAiB;AAC1D,EAAA,MAAM,aAAA,GAAgB,IAAI,GAAA,CAAI,OAAO,CAAA;AACrC,EAAA,IAAI,aAAA,CAAc,QAAA,CAAS,QAAA,CAAS,QAAQ,CAAA,EAAG;AAC7C,IAAA,OAAO,QAAA;AAAA,EACT;AAEA,EAAA,OAAO,KAAA;AACT;AAEO,SAAS,qBAAqB,WAAA,EAA6B;AAChE,EAAA,IAAI;AACF,IAAA,MAAM,EAAE,IAAA,EAAM,SAAA,EAAW,IAAA,EAAK,GAAIC,4BAAe,WAAA,EAAa;AAAA,MAC5D,WAAA,EAAa,UAAA;AAAA,MACb,gBAAA,EAAkB;AAAA,KACnB,CAAA;AAED,IAAA,IAAI,SAAS,UAAA,EAAY;AACvB,MAAA,MAAM,IAAIC,iBAAA;AAAA,QACR,6EAA6E,IAAI,CAAA,EAAA;AAAA,OACnF;AAAA,IACF;AAEA,IAAA,OAAOC,+BAAA,CAAmB,EAAE,IAAA,EAAM,SAAA,EAAW,MAAM,CAAA;AAAA,EACrD,SAAS,GAAA,EAAK;AACZ,IAAA,MAAM,IAAID,iBAAA;AAAA,MACR,CAAA,gGAAA,EAAmG,WAAW,CAAA,UAAA,EACjG,GAAA,CAAc,OAAO,CAAA;AAAA,KACpC;AAAA,EACF;AACF;;;;;;;;"}
|
package/dist/index.d.ts
CHANGED
|
@@ -33,4 +33,5 @@ interface RouterOptions {
|
|
|
33
33
|
*/
|
|
34
34
|
declare function createRouter(options: RouterOptions): Promise<express.Router>;
|
|
35
35
|
|
|
36
|
-
export {
|
|
36
|
+
export { createRouter, bulkImportPlugin as default };
|
|
37
|
+
export type { RouterOptions };
|
package/dist/plugin.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.cjs.js","sources":["../src/plugin.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 {\n coreServices,\n createBackendPlugin,\n} from '@backstage/backend-plugin-api';\nimport { catalogServiceRef } from '@backstage/plugin-catalog-node/alpha';\n\nimport { createRouter } from './service/router';\n\n/**\n * The bulk-import backend plugin.\n * @public\n */\nexport const bulkImportPlugin = createBackendPlugin({\n pluginId: 'bulk-import',\n register(env) {\n env.registerInit({\n deps: {\n logger: coreServices.logger,\n config: coreServices.rootConfig,\n http: coreServices.httpRouter,\n cache: coreServices.cache,\n discovery: coreServices.discovery,\n permissions: coreServices.permissions,\n httpAuth: coreServices.httpAuth,\n auth: coreServices.auth,\n catalogApi: catalogServiceRef,\n auditor: coreServices.auditor,\n database: coreServices.database,\n },\n async init({\n config,\n logger,\n http,\n cache,\n discovery,\n permissions,\n httpAuth,\n auth,\n catalogApi,\n auditor,\n database,\n }) {\n const router = await createRouter({\n config,\n cache,\n discovery,\n permissions,\n logger,\n httpAuth,\n auth,\n catalogApi,\n auditor,\n database,\n });\n http.use(router);\n http.addAuthPolicy({\n path: '/ping',\n allow: 'unauthenticated',\n });\n },\n });\n },\n});\n"],"names":["createBackendPlugin","coreServices","catalogServiceRef","router","createRouter"],"mappings":";;;;;;AA4BO,MAAM,mBAAmBA,
|
|
1
|
+
{"version":3,"file":"plugin.cjs.js","sources":["../src/plugin.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 {\n coreServices,\n createBackendPlugin,\n} from '@backstage/backend-plugin-api';\nimport { catalogServiceRef } from '@backstage/plugin-catalog-node/alpha';\n\nimport { createRouter } from './service/router';\n\n/**\n * The bulk-import backend plugin.\n * @public\n */\nexport const bulkImportPlugin = createBackendPlugin({\n pluginId: 'bulk-import',\n register(env) {\n env.registerInit({\n deps: {\n logger: coreServices.logger,\n config: coreServices.rootConfig,\n http: coreServices.httpRouter,\n cache: coreServices.cache,\n discovery: coreServices.discovery,\n permissions: coreServices.permissions,\n httpAuth: coreServices.httpAuth,\n auth: coreServices.auth,\n catalogApi: catalogServiceRef,\n auditor: coreServices.auditor,\n database: coreServices.database,\n },\n async init({\n config,\n logger,\n http,\n cache,\n discovery,\n permissions,\n httpAuth,\n auth,\n catalogApi,\n auditor,\n database,\n }) {\n const router = await createRouter({\n config,\n cache,\n discovery,\n permissions,\n logger,\n httpAuth,\n auth,\n catalogApi,\n auditor,\n database,\n });\n http.use(router);\n http.addAuthPolicy({\n path: '/ping',\n allow: 'unauthenticated',\n });\n },\n });\n },\n});\n"],"names":["createBackendPlugin","coreServices","catalogServiceRef","router","createRouter"],"mappings":";;;;;;AA4BO,MAAM,mBAAmBA,oCAAA,CAAoB;AAAA,EAClD,QAAA,EAAU,aAAA;AAAA,EACV,SAAS,GAAA,EAAK;AACZ,IAAA,GAAA,CAAI,YAAA,CAAa;AAAA,MACf,IAAA,EAAM;AAAA,QACJ,QAAQC,6BAAA,CAAa,MAAA;AAAA,QACrB,QAAQA,6BAAA,CAAa,UAAA;AAAA,QACrB,MAAMA,6BAAA,CAAa,UAAA;AAAA,QACnB,OAAOA,6BAAA,CAAa,KAAA;AAAA,QACpB,WAAWA,6BAAA,CAAa,SAAA;AAAA,QACxB,aAAaA,6BAAA,CAAa,WAAA;AAAA,QAC1B,UAAUA,6BAAA,CAAa,QAAA;AAAA,QACvB,MAAMA,6BAAA,CAAa,IAAA;AAAA,QACnB,UAAA,EAAYC,uBAAA;AAAA,QACZ,SAASD,6BAAA,CAAa,OAAA;AAAA,QACtB,UAAUA,6BAAA,CAAa;AAAA,OACzB;AAAA,MACA,MAAM,IAAA,CAAK;AAAA,QACT,MAAA;AAAA,QACA,MAAA;AAAA,QACA,IAAA;AAAA,QACA,KAAA;AAAA,QACA,SAAA;AAAA,QACA,WAAA;AAAA,QACA,QAAA;AAAA,QACA,IAAA;AAAA,QACA,UAAA;AAAA,QACA,OAAA;AAAA,QACA;AAAA,OACF,EAAG;AACD,QAAA,MAAME,QAAA,GAAS,MAAMC,mBAAA,CAAa;AAAA,UAChC,MAAA;AAAA,UACA,KAAA;AAAA,UACA,SAAA;AAAA,UACA,WAAA;AAAA,UACA,MAAA;AAAA,UACA,QAAA;AAAA,UACA,IAAA;AAAA,UACA,UAAA;AAAA,UACA,OAAA;AAAA,UACA;AAAA,SACD,CAAA;AACD,QAAA,IAAA,CAAK,IAAID,QAAM,CAAA;AACf,QAAA,IAAA,CAAK,aAAA,CAAc;AAAA,UACjB,IAAA,EAAM,OAAA;AAAA,UACN,KAAA,EAAO;AAAA,SACR,CAAA;AAAA,MACH;AAAA,KACD,CAAA;AAAA,EACH;AACF,CAAC;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handlers.cjs.js","sources":["../../../src/service/handlers/handlers.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 */\nimport type { Components } from '../../generated/openapi';\n\nexport const DefaultPageNumber = 1;\nexport const DefaultPageSize = 20;\n\nexport const DefaultSortColumn: Components.Parameters.SortColumnQueryParam =\n 'repository.name';\nexport const DefaultSortOrder: Components.Parameters.SortOrderQueryParam =\n 'asc';\n\nexport interface HandlerResponse<ResponseBody = any> {\n statusCode: number;\n responseBody?: ResponseBody;\n}\n"],"names":[],"mappings":";;AAiBO,MAAM,
|
|
1
|
+
{"version":3,"file":"handlers.cjs.js","sources":["../../../src/service/handlers/handlers.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 */\nimport type { Components } from '../../generated/openapi';\n\nexport const DefaultPageNumber = 1;\nexport const DefaultPageSize = 20;\n\nexport const DefaultSortColumn: Components.Parameters.SortColumnQueryParam =\n 'repository.name';\nexport const DefaultSortOrder: Components.Parameters.SortOrderQueryParam =\n 'asc';\n\nexport interface HandlerResponse<ResponseBody = any> {\n statusCode: number;\n responseBody?: ResponseBody;\n}\n"],"names":[],"mappings":";;AAiBO,MAAM,iBAAA,GAAoB;AAC1B,MAAM,eAAA,GAAkB;AAExB,MAAM,iBAAA,GACX;AACK,MAAM,gBAAA,GACX;;;;;;;"}
|
|
@@ -20,9 +20,9 @@ function sortImports(imports, sortColumn = handlers.DefaultSortColumn, sortOrder
|
|
|
20
20
|
imports.sort((a, b) => {
|
|
21
21
|
const value1 = utils.getNestedValue(a, sortColumn);
|
|
22
22
|
const value2 = utils.getNestedValue(b, sortColumn);
|
|
23
|
-
if (value1 ===
|
|
24
|
-
if (value1 ===
|
|
25
|
-
if (value2 ===
|
|
23
|
+
if (value1 === void 0 && value2 === void 0) return 0;
|
|
24
|
+
if (value1 === void 0) return sortOrder === "asc" ? -1 : 1;
|
|
25
|
+
if (value2 === void 0) return sortOrder === "asc" ? 1 : -1;
|
|
26
26
|
if (sortColumn === "lastUpdate") {
|
|
27
27
|
const date1 = new Date(value1);
|
|
28
28
|
const date2 = new Date(value2);
|
|
@@ -105,10 +105,10 @@ async function findAllImports(deps, requestHeaders, queryParams) {
|
|
|
105
105
|
const result = await Promise.all(importStatusPromises);
|
|
106
106
|
const imports = result.filter((res) => res.responseBody).map((res) => res.responseBody).map((res) => {
|
|
107
107
|
const key = res?.repository?.url;
|
|
108
|
-
const location = key ? repoUrlToLocation.get(key) :
|
|
108
|
+
const location = key ? repoUrlToLocation.get(key) : void 0;
|
|
109
109
|
return {
|
|
110
110
|
...res,
|
|
111
|
-
source: location ? allLocations.get(location)?.source :
|
|
111
|
+
source: location ? allLocations.get(location)?.source : void 0
|
|
112
112
|
};
|
|
113
113
|
});
|
|
114
114
|
sortImports(imports, sortColumn, sortOrder);
|
|
@@ -153,7 +153,7 @@ async function resolveReposDefaultBranches(logger, gitlabApiService, githubApiSe
|
|
|
153
153
|
);
|
|
154
154
|
return {
|
|
155
155
|
repoUrl,
|
|
156
|
-
defaultBranch:
|
|
156
|
+
defaultBranch: void 0
|
|
157
157
|
};
|
|
158
158
|
})
|
|
159
159
|
);
|
|
@@ -168,7 +168,7 @@ async function resolveReposDefaultBranches(logger, gitlabApiService, githubApiSe
|
|
|
168
168
|
function repoUrlFromLocation(loc) {
|
|
169
169
|
const split = loc.split("/blob/");
|
|
170
170
|
if (split.length < 2) {
|
|
171
|
-
return
|
|
171
|
+
return void 0;
|
|
172
172
|
}
|
|
173
173
|
return split[0];
|
|
174
174
|
}
|
|
@@ -242,7 +242,7 @@ async function handleAddedReposFromCreateImportJobs(deps, importRequests) {
|
|
|
242
242
|
const gitUrl = gitUrlParse__default.default(req.repository.url);
|
|
243
243
|
result.push({
|
|
244
244
|
status: "ADDED",
|
|
245
|
-
lastUpdate: ghRepo?.repository?.updated_at ??
|
|
245
|
+
lastUpdate: ghRepo?.repository?.updated_at ?? void 0,
|
|
246
246
|
repository: {
|
|
247
247
|
url: req.repository.url,
|
|
248
248
|
name: gitUrl.name,
|
|
@@ -706,7 +706,7 @@ async function findOrchestratorImportStatusByRepo(deps, repoUrl, token, skipWork
|
|
|
706
706
|
}
|
|
707
707
|
async function parsePullOrMergeRequestInfo(checkpoints, githubApiService, gitlabApiService, approvalTool, logger, repoUrl) {
|
|
708
708
|
if (approvalTool !== "GITLAB" && approvalTool !== "GIT") {
|
|
709
|
-
return
|
|
709
|
+
return void 0;
|
|
710
710
|
}
|
|
711
711
|
const gitApiService = approvalTool === "GITLAB" ? gitlabApiService : githubApiService;
|
|
712
712
|
for (const key in checkpoints) {
|
|
@@ -743,7 +743,7 @@ async function parsePullOrMergeRequestInfo(checkpoints, githubApiService, gitlab
|
|
|
743
743
|
continue;
|
|
744
744
|
}
|
|
745
745
|
}
|
|
746
|
-
return
|
|
746
|
+
return void 0;
|
|
747
747
|
}
|
|
748
748
|
async function deleteImportByRepo(deps, repoUrl, defaultBranch) {
|
|
749
749
|
deps.logger.debug(`Deleting bulk import job status for ${repoUrl}..`);
|
|
@@ -771,7 +771,7 @@ async function deleteImportByRepo(deps, repoUrl, defaultBranch) {
|
|
|
771
771
|
return loc.id;
|
|
772
772
|
}
|
|
773
773
|
}
|
|
774
|
-
return
|
|
774
|
+
return void 0;
|
|
775
775
|
};
|
|
776
776
|
const locationId = findLocationFrom(
|
|
777
777
|
(await deps.catalogHttpClient.listCatalogUrlLocationsByIdFromLocationsEndpoint()).locations
|
|
@@ -781,7 +781,7 @@ async function deleteImportByRepo(deps, repoUrl, defaultBranch) {
|
|
|
781
781
|
}
|
|
782
782
|
return {
|
|
783
783
|
statusCode: 204,
|
|
784
|
-
responseBody:
|
|
784
|
+
responseBody: void 0
|
|
785
785
|
};
|
|
786
786
|
}
|
|
787
787
|
async function deleteRepositoryRecord(deps, repoUrl) {
|