@red-hat-developer-hub/backstage-plugin-bulk-import-backend 5.0.1
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 +115 -0
- package/README.md +161 -0
- package/app-config.yaml +0 -0
- package/config.d.ts +17 -0
- package/dist/catalog/catalogHttpClient.cjs.js +284 -0
- package/dist/catalog/catalogHttpClient.cjs.js.map +1 -0
- package/dist/catalog/catalogInfoGenerator.cjs.js +60 -0
- package/dist/catalog/catalogInfoGenerator.cjs.js.map +1 -0
- package/dist/catalog/catalogUtils.cjs.js +34 -0
- package/dist/catalog/catalogUtils.cjs.js.map +1 -0
- package/dist/generated/openapidocument.cjs.js +1168 -0
- package/dist/generated/openapidocument.cjs.js.map +1 -0
- package/dist/github/GithubAppManager.cjs.js +395 -0
- package/dist/github/GithubAppManager.cjs.js.map +1 -0
- package/dist/github/githubApiService.cjs.js +659 -0
- package/dist/github/githubApiService.cjs.js.map +1 -0
- package/dist/github/types.cjs.js +8 -0
- package/dist/github/types.cjs.js.map +1 -0
- package/dist/github/utils/ghUtils.cjs.js +103 -0
- package/dist/github/utils/ghUtils.cjs.js.map +1 -0
- package/dist/github/utils/orgUtils.cjs.js +151 -0
- package/dist/github/utils/orgUtils.cjs.js.map +1 -0
- package/dist/github/utils/prUtils.cjs.js +85 -0
- package/dist/github/utils/prUtils.cjs.js.map +1 -0
- package/dist/github/utils/repoUtils.cjs.js +307 -0
- package/dist/github/utils/repoUtils.cjs.js.map +1 -0
- package/dist/github/utils/utils.cjs.js +206 -0
- package/dist/github/utils/utils.cjs.js.map +1 -0
- package/dist/helpers/auditLogUtils.cjs.js +112 -0
- package/dist/helpers/auditLogUtils.cjs.js.map +1 -0
- package/dist/helpers/auth.cjs.js +36 -0
- package/dist/helpers/auth.cjs.js.map +1 -0
- package/dist/helpers/loggingUtils.cjs.js +19 -0
- package/dist/helpers/loggingUtils.cjs.js.map +1 -0
- package/dist/helpers/pagination.cjs.js +19 -0
- package/dist/helpers/pagination.cjs.js.map +1 -0
- package/dist/index.cjs.js +12 -0
- package/dist/index.cjs.js.map +1 -0
- package/dist/index.d.ts +25 -0
- package/dist/plugin.cjs.js +54 -0
- package/dist/plugin.cjs.js.map +1 -0
- package/dist/service/handlers/handlers.cjs.js +8 -0
- package/dist/service/handlers/handlers.cjs.js.map +1 -0
- package/dist/service/handlers/import/bulkImports.cjs.js +551 -0
- package/dist/service/handlers/import/bulkImports.cjs.js.map +1 -0
- package/dist/service/handlers/import/importStatus.cjs.js +49 -0
- package/dist/service/handlers/import/importStatus.cjs.js.map +1 -0
- package/dist/service/handlers/organization/organizations.cjs.js +77 -0
- package/dist/service/handlers/organization/organizations.cjs.js.map +1 -0
- package/dist/service/handlers/ping/ping.cjs.js +12 -0
- package/dist/service/handlers/ping/ping.cjs.js.map +1 -0
- package/dist/service/handlers/repository/repositories.cjs.js +99 -0
- package/dist/service/handlers/repository/repositories.cjs.js.map +1 -0
- package/dist/service/router.cjs.js +324 -0
- package/dist/service/router.cjs.js.map +1 -0
- package/package.json +110 -0
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var gitUrlParse = require('git-url-parse');
|
|
4
|
+
var catalogUtils = require('../../catalog/catalogUtils.cjs.js');
|
|
5
|
+
require('@backstage/errors');
|
|
6
|
+
require('@backstage/plugin-permission-common');
|
|
7
|
+
require('@red-hat-developer-hub/backstage-plugin-bulk-import-common');
|
|
8
|
+
var loggingUtils = require('../../helpers/loggingUtils.cjs.js');
|
|
9
|
+
var handlers = require('../../service/handlers/handlers.cjs.js');
|
|
10
|
+
var orgUtils = require('./orgUtils.cjs.js');
|
|
11
|
+
var utils = require('./utils.cjs.js');
|
|
12
|
+
|
|
13
|
+
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
|
|
14
|
+
|
|
15
|
+
var gitUrlParse__default = /*#__PURE__*/_interopDefaultCompat(gitUrlParse);
|
|
16
|
+
|
|
17
|
+
async function validateAndBuildRepoData(githubCredentialsProvider, integrations, config, input) {
|
|
18
|
+
const ghConfig = integrations.github.byUrl(input.repoUrl)?.config;
|
|
19
|
+
if (!ghConfig) {
|
|
20
|
+
throw new Error(`Could not find GH integration from ${input.repoUrl}`);
|
|
21
|
+
}
|
|
22
|
+
const gitUrl = gitUrlParse__default.default(input.repoUrl);
|
|
23
|
+
const owner = gitUrl.organization;
|
|
24
|
+
const repo = gitUrl.name;
|
|
25
|
+
const credentials = await githubCredentialsProvider.getAllCredentials({
|
|
26
|
+
host: ghConfig.host
|
|
27
|
+
});
|
|
28
|
+
if (credentials.length === 0) {
|
|
29
|
+
throw new Error(`No credentials for GH integration`);
|
|
30
|
+
}
|
|
31
|
+
const branchName = catalogUtils.getBranchName(config);
|
|
32
|
+
return { ghConfig, owner, repo, credentials, branchName };
|
|
33
|
+
}
|
|
34
|
+
async function searchRepos(octokit, ghSearchQuery, pageNumber = handlers.DefaultPageNumber, pageSize = handlers.DefaultPageSize) {
|
|
35
|
+
const repoSearchResp = await octokit.rest.search.repos({
|
|
36
|
+
q: ghSearchQuery,
|
|
37
|
+
order: "asc",
|
|
38
|
+
page: pageNumber,
|
|
39
|
+
per_page: pageSize
|
|
40
|
+
});
|
|
41
|
+
return {
|
|
42
|
+
totalCount: repoSearchResp?.data?.total_count,
|
|
43
|
+
repositories: repoSearchResp?.data?.items?.map((repo) => {
|
|
44
|
+
return {
|
|
45
|
+
name: repo.name,
|
|
46
|
+
full_name: repo.full_name,
|
|
47
|
+
url: repo.url,
|
|
48
|
+
html_url: repo.html_url,
|
|
49
|
+
default_branch: repo.default_branch,
|
|
50
|
+
updated_at: repo.updated_at
|
|
51
|
+
};
|
|
52
|
+
}) ?? []
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
async function addGithubAppRepositories(deps, octokit, credential, ghConfig, repositories, errors, reqParams) {
|
|
56
|
+
const search = reqParams?.search;
|
|
57
|
+
const pageNumber = reqParams?.pageNumber ?? handlers.DefaultPageNumber;
|
|
58
|
+
const pageSize = reqParams?.pageSize ?? handlers.DefaultPageSize;
|
|
59
|
+
let totalCount;
|
|
60
|
+
try {
|
|
61
|
+
if (search) {
|
|
62
|
+
const allOrgsMap = await orgUtils.getAllAppOrgs(
|
|
63
|
+
deps.githubCredentialsProvider,
|
|
64
|
+
ghConfig,
|
|
65
|
+
credential.accountLogin
|
|
66
|
+
);
|
|
67
|
+
const orgSearch = [];
|
|
68
|
+
for (const [_orgUrl, ghOrg] of allOrgsMap) {
|
|
69
|
+
orgSearch.push(`org:${ghOrg.name}`);
|
|
70
|
+
}
|
|
71
|
+
const query = `${search} in:name ${orgSearch.join(" ")}`;
|
|
72
|
+
const searchResp = await searchRepos(
|
|
73
|
+
octokit,
|
|
74
|
+
query,
|
|
75
|
+
pageNumber,
|
|
76
|
+
pageSize
|
|
77
|
+
);
|
|
78
|
+
totalCount = searchResp.totalCount;
|
|
79
|
+
searchResp.repositories.forEach(
|
|
80
|
+
(repo) => repositories.set(repo.full_name, repo)
|
|
81
|
+
);
|
|
82
|
+
} else {
|
|
83
|
+
const resp = await octokit.apps.listReposAccessibleToInstallation({
|
|
84
|
+
page: pageNumber,
|
|
85
|
+
per_page: pageSize
|
|
86
|
+
});
|
|
87
|
+
const repos = resp?.data?.repositories ?? resp?.data;
|
|
88
|
+
repos?.forEach((repo) => {
|
|
89
|
+
repositories.set(repo.full_name, {
|
|
90
|
+
name: repo.name,
|
|
91
|
+
full_name: repo.full_name,
|
|
92
|
+
url: repo.url,
|
|
93
|
+
html_url: repo.html_url,
|
|
94
|
+
default_branch: repo.default_branch,
|
|
95
|
+
updated_at: repo.updated_at
|
|
96
|
+
});
|
|
97
|
+
});
|
|
98
|
+
totalCount = resp?.data?.total_count;
|
|
99
|
+
}
|
|
100
|
+
} catch (err) {
|
|
101
|
+
loggingUtils.logErrorIfNeeded(
|
|
102
|
+
deps.logger,
|
|
103
|
+
`Fetching repositories with access token for github app ${credential.appId}`,
|
|
104
|
+
err
|
|
105
|
+
);
|
|
106
|
+
const credentialError = utils.createCredentialError(credential, err);
|
|
107
|
+
if (credentialError) {
|
|
108
|
+
errors.set(credential.appId, credentialError);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return { totalCount };
|
|
112
|
+
}
|
|
113
|
+
async function addGithubTokenRepositories(deps, octokit, credential, repositories, errors, reqParams) {
|
|
114
|
+
const search = reqParams?.search;
|
|
115
|
+
const pageNumber = reqParams?.pageNumber ?? handlers.DefaultPageNumber;
|
|
116
|
+
const pageSize = reqParams?.pageSize ?? handlers.DefaultPageSize;
|
|
117
|
+
let totalCount;
|
|
118
|
+
try {
|
|
119
|
+
if (search) {
|
|
120
|
+
const username = (await octokit.rest.users.getAuthenticated())?.data?.login;
|
|
121
|
+
let query = `${search} in:name user:${username}`;
|
|
122
|
+
const allOrgsResp = await octokit.paginate(
|
|
123
|
+
octokit.rest.orgs.listForAuthenticatedUser,
|
|
124
|
+
{
|
|
125
|
+
sort: "full_name",
|
|
126
|
+
direction: "asc"
|
|
127
|
+
}
|
|
128
|
+
);
|
|
129
|
+
const orgSearch = [];
|
|
130
|
+
allOrgsResp?.forEach((org) => orgSearch.push(`org:${org.login}`));
|
|
131
|
+
if (orgSearch.length > 0) {
|
|
132
|
+
query += ` ${orgSearch.join(" ")}`;
|
|
133
|
+
}
|
|
134
|
+
const searchResp = await searchRepos(
|
|
135
|
+
octokit,
|
|
136
|
+
query,
|
|
137
|
+
pageNumber,
|
|
138
|
+
pageSize
|
|
139
|
+
);
|
|
140
|
+
totalCount = searchResp.totalCount;
|
|
141
|
+
searchResp.repositories.forEach(
|
|
142
|
+
(repo) => repositories.set(repo.full_name, repo)
|
|
143
|
+
);
|
|
144
|
+
} else {
|
|
145
|
+
const resp = await octokit.rest.repos.listForAuthenticatedUser({
|
|
146
|
+
page: pageNumber,
|
|
147
|
+
per_page: pageSize,
|
|
148
|
+
sort: "full_name",
|
|
149
|
+
direction: "asc"
|
|
150
|
+
});
|
|
151
|
+
resp?.data?.forEach((repo) => {
|
|
152
|
+
repositories.set(repo.full_name, {
|
|
153
|
+
name: repo.name,
|
|
154
|
+
full_name: repo.full_name,
|
|
155
|
+
url: repo.url,
|
|
156
|
+
html_url: repo.html_url,
|
|
157
|
+
default_branch: repo.default_branch,
|
|
158
|
+
updated_at: repo.updated_at
|
|
159
|
+
});
|
|
160
|
+
});
|
|
161
|
+
totalCount = await utils.computeTotalCountFromGitHubToken(
|
|
162
|
+
deps,
|
|
163
|
+
async (lastPageNumber) => octokit.repos.listForAuthenticatedUser({
|
|
164
|
+
page: lastPageNumber,
|
|
165
|
+
per_page: 100
|
|
166
|
+
}).then((lastPageResp) => lastPageResp.data.length),
|
|
167
|
+
"repos.listForAuthenticatedUser",
|
|
168
|
+
resp?.data?.length,
|
|
169
|
+
resp?.headers?.link
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
} catch (err) {
|
|
173
|
+
utils.handleError(
|
|
174
|
+
deps,
|
|
175
|
+
"Fetching repositories with token from token",
|
|
176
|
+
credential,
|
|
177
|
+
errors,
|
|
178
|
+
err
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
return { totalCount };
|
|
182
|
+
}
|
|
183
|
+
async function addGithubTokenOrgRepositories(deps, octokit, credential, org, repositories, errors, reqParams) {
|
|
184
|
+
const search = reqParams?.search;
|
|
185
|
+
const pageNumber = reqParams?.pageNumber ?? handlers.DefaultPageNumber;
|
|
186
|
+
const pageSize = reqParams?.pageSize ?? handlers.DefaultPageSize;
|
|
187
|
+
let totalCount;
|
|
188
|
+
try {
|
|
189
|
+
if (search) {
|
|
190
|
+
const query = `${search} in:name org:${org}`;
|
|
191
|
+
const searchResp = await searchRepos(
|
|
192
|
+
octokit,
|
|
193
|
+
query,
|
|
194
|
+
pageNumber,
|
|
195
|
+
pageSize
|
|
196
|
+
);
|
|
197
|
+
totalCount = searchResp.totalCount;
|
|
198
|
+
searchResp.repositories.forEach(
|
|
199
|
+
(repo) => repositories.set(repo.full_name, repo)
|
|
200
|
+
);
|
|
201
|
+
} else {
|
|
202
|
+
const resp = await octokit.rest.repos.listForOrg({
|
|
203
|
+
org,
|
|
204
|
+
page: pageNumber,
|
|
205
|
+
per_page: pageSize,
|
|
206
|
+
sort: "full_name",
|
|
207
|
+
direction: "asc"
|
|
208
|
+
});
|
|
209
|
+
resp?.data?.forEach((repo) => {
|
|
210
|
+
const githubRepo = {
|
|
211
|
+
name: repo.name,
|
|
212
|
+
full_name: repo.full_name,
|
|
213
|
+
url: repo.url,
|
|
214
|
+
html_url: repo.html_url,
|
|
215
|
+
default_branch: repo.default_branch ?? "main",
|
|
216
|
+
updated_at: repo.updated_at
|
|
217
|
+
};
|
|
218
|
+
repositories.set(githubRepo.full_name, githubRepo);
|
|
219
|
+
});
|
|
220
|
+
totalCount = await utils.computeTotalCountFromGitHubToken(
|
|
221
|
+
deps,
|
|
222
|
+
async (lastPageNumber) => octokit.repos.listForOrg({
|
|
223
|
+
org,
|
|
224
|
+
page: lastPageNumber,
|
|
225
|
+
per_page: 100
|
|
226
|
+
}).then((lastPageResp) => lastPageResp.data.length),
|
|
227
|
+
"repos.listForOrg",
|
|
228
|
+
resp?.data?.length,
|
|
229
|
+
resp?.headers?.link
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
} catch (err) {
|
|
233
|
+
utils.handleError(
|
|
234
|
+
deps,
|
|
235
|
+
"Fetching org repositories with token from token",
|
|
236
|
+
credential,
|
|
237
|
+
errors,
|
|
238
|
+
err
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
return { totalCount };
|
|
242
|
+
}
|
|
243
|
+
async function fileExistsInDefaultBranch(logger, octo, owner, repo, fileName, defaultBranch = "main") {
|
|
244
|
+
try {
|
|
245
|
+
await octo.rest.repos.getContent({
|
|
246
|
+
owner,
|
|
247
|
+
repo,
|
|
248
|
+
path: fileName,
|
|
249
|
+
ref: defaultBranch
|
|
250
|
+
});
|
|
251
|
+
return true;
|
|
252
|
+
} catch (error) {
|
|
253
|
+
if (error.status === 404) {
|
|
254
|
+
return false;
|
|
255
|
+
}
|
|
256
|
+
logger.debug(
|
|
257
|
+
`Unable to determine if a file named ${fileName} already exists in repo ${repo}: ${error}`
|
|
258
|
+
);
|
|
259
|
+
return void 0;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
async function createOrUpdateFileInBranch(octo, owner, repo, branchName, fileName, fileContent) {
|
|
263
|
+
try {
|
|
264
|
+
const { data: existingFile } = await octo.rest.repos.getContent({
|
|
265
|
+
owner,
|
|
266
|
+
repo,
|
|
267
|
+
path: fileName,
|
|
268
|
+
ref: branchName
|
|
269
|
+
});
|
|
270
|
+
if (Array.isArray(existingFile) || !("sha" in existingFile)) {
|
|
271
|
+
throw new Error(
|
|
272
|
+
`The content at path ${fileName} is not a file or the response from GitHub does not contain the 'sha' property.`
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
await octo.rest.repos.createOrUpdateFileContents({
|
|
276
|
+
owner,
|
|
277
|
+
repo,
|
|
278
|
+
path: fileName,
|
|
279
|
+
message: `Add ${fileName} config file`,
|
|
280
|
+
content: btoa(fileContent),
|
|
281
|
+
sha: existingFile.sha,
|
|
282
|
+
branch: branchName
|
|
283
|
+
});
|
|
284
|
+
} catch (error) {
|
|
285
|
+
if (error.status === 404) {
|
|
286
|
+
await octo.rest.repos.createOrUpdateFileContents({
|
|
287
|
+
owner,
|
|
288
|
+
repo,
|
|
289
|
+
path: fileName,
|
|
290
|
+
message: `Add ${fileName} config file`,
|
|
291
|
+
content: btoa(fileContent),
|
|
292
|
+
branch: branchName
|
|
293
|
+
});
|
|
294
|
+
} else {
|
|
295
|
+
throw error;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
exports.addGithubAppRepositories = addGithubAppRepositories;
|
|
301
|
+
exports.addGithubTokenOrgRepositories = addGithubTokenOrgRepositories;
|
|
302
|
+
exports.addGithubTokenRepositories = addGithubTokenRepositories;
|
|
303
|
+
exports.createOrUpdateFileInBranch = createOrUpdateFileInBranch;
|
|
304
|
+
exports.fileExistsInDefaultBranch = fileExistsInDefaultBranch;
|
|
305
|
+
exports.searchRepos = searchRepos;
|
|
306
|
+
exports.validateAndBuildRepoData = validateAndBuildRepoData;
|
|
307
|
+
//# sourceMappingURL=repoUtils.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"repoUtils.cjs.js","sources":["../../../src/github/utils/repoUtils.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 */\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,CAAA;AAC3D,EAAA,IAAI,CAAC,QAAU,EAAA;AACb,IAAA,MAAM,IAAI,KAAA,CAAM,CAAsC,mCAAA,EAAA,KAAA,CAAM,OAAO,CAAE,CAAA,CAAA,CAAA;AAAA,GACvE;AAEA,EAAM,MAAA,MAAA,GAASA,4BAAY,CAAA,KAAA,CAAM,OAAO,CAAA,CAAA;AACxC,EAAA,MAAM,QAAQ,MAAO,CAAA,YAAA,CAAA;AACrB,EAAA,MAAM,OAAO,MAAO,CAAA,IAAA,CAAA;AAEpB,EAAM,MAAA,WAAA,GAAc,MAAM,yBAAA,CAA0B,iBAA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-0,0 +1,206 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var gitUrlParse = require('git-url-parse');
|
|
4
|
+
require('@backstage/errors');
|
|
5
|
+
require('@backstage/plugin-permission-common');
|
|
6
|
+
require('@red-hat-developer-hub/backstage-plugin-bulk-import-common');
|
|
7
|
+
var loggingUtils = require('../../helpers/loggingUtils.cjs.js');
|
|
8
|
+
var types = require('../types.cjs.js');
|
|
9
|
+
var ghUtils = require('./ghUtils.cjs.js');
|
|
10
|
+
var repoUtils = require('./repoUtils.cjs.js');
|
|
11
|
+
|
|
12
|
+
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
|
|
13
|
+
|
|
14
|
+
var gitUrlParse__default = /*#__PURE__*/_interopDefaultCompat(gitUrlParse);
|
|
15
|
+
|
|
16
|
+
function createCredentialError(credential, err) {
|
|
17
|
+
if (err) {
|
|
18
|
+
if (types.isGithubAppCredential(credential)) {
|
|
19
|
+
return {
|
|
20
|
+
appId: credential.appId,
|
|
21
|
+
type: "app",
|
|
22
|
+
error: {
|
|
23
|
+
name: err.name,
|
|
24
|
+
message: err.message
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
return {
|
|
29
|
+
type: "token",
|
|
30
|
+
error: {
|
|
31
|
+
name: err.name,
|
|
32
|
+
message: err.message
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
if ("error" in credential) {
|
|
37
|
+
return {
|
|
38
|
+
appId: credential.appId,
|
|
39
|
+
type: "app",
|
|
40
|
+
error: {
|
|
41
|
+
name: credential.error.name,
|
|
42
|
+
message: credential.error.message
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
return void 0;
|
|
47
|
+
}
|
|
48
|
+
function verifyAndGetIntegrations(deps, integrations) {
|
|
49
|
+
const ghConfigs = integrations.github.list().map((ghInt) => ghInt.config);
|
|
50
|
+
if (ghConfigs.length === 0) {
|
|
51
|
+
deps.logger.debug(
|
|
52
|
+
"No GitHub Integration in config => returning an empty list of repositories."
|
|
53
|
+
);
|
|
54
|
+
throw new Error(
|
|
55
|
+
"Looks like there is no GitHub Integration in config. Please add a configuration entry under 'integrations.github"
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
return ghConfigs;
|
|
59
|
+
}
|
|
60
|
+
async function getCredentialsFromIntegrations(githubCredentialsProvider, ghConfigs) {
|
|
61
|
+
const credentialsByConfig = /* @__PURE__ */ new Map();
|
|
62
|
+
for (const ghConfig of ghConfigs) {
|
|
63
|
+
const creds = await getCredentialsForConfig(
|
|
64
|
+
githubCredentialsProvider,
|
|
65
|
+
ghConfig
|
|
66
|
+
);
|
|
67
|
+
credentialsByConfig.set(ghConfig, creds);
|
|
68
|
+
}
|
|
69
|
+
return credentialsByConfig;
|
|
70
|
+
}
|
|
71
|
+
async function getCredentialsForConfig(githubCredentialsProvider, ghConfig) {
|
|
72
|
+
return await githubCredentialsProvider.getAllCredentials({
|
|
73
|
+
host: ghConfig.host
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
function handleError(deps, desc, credential, errors, err) {
|
|
77
|
+
loggingUtils.logErrorIfNeeded(deps.logger, `${desc} failed`, err);
|
|
78
|
+
const credentialError = createCredentialError(credential, err);
|
|
79
|
+
if (credentialError) {
|
|
80
|
+
errors.set(-1, credentialError);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
async function computeTotalCountFromGitHubToken(deps, lastPageDataLengthProviderFn, ghApiName, pageSize, linkHeader) {
|
|
84
|
+
if (!linkHeader) {
|
|
85
|
+
deps.logger.debug(
|
|
86
|
+
`No link header found in response from ${ghApiName} GH endpoint => returning current page size`
|
|
87
|
+
);
|
|
88
|
+
return pageSize;
|
|
89
|
+
}
|
|
90
|
+
const lastPageLink = linkHeader.split(",").find((s) => s.includes('rel="last"'));
|
|
91
|
+
if (!lastPageLink) {
|
|
92
|
+
deps.logger.debug(
|
|
93
|
+
`No rel='last' link found in response headers from ${ghApiName} GH endpoint => returning current page size`
|
|
94
|
+
);
|
|
95
|
+
return pageSize;
|
|
96
|
+
}
|
|
97
|
+
const match = lastPageLink.match(/page=(\d+)/);
|
|
98
|
+
if (!match || match.length < 2) {
|
|
99
|
+
deps.logger.debug(
|
|
100
|
+
`Unable to extract page number from rel='last' link found in response headers from ${ghApiName} GH endpoint => returning current page size`
|
|
101
|
+
);
|
|
102
|
+
return pageSize;
|
|
103
|
+
}
|
|
104
|
+
const lastPageNumber = parseInt(match[1], 10);
|
|
105
|
+
const lastPageDataLength = await lastPageDataLengthProviderFn(lastPageNumber);
|
|
106
|
+
return pageSize ? (lastPageNumber - 1) * pageSize + lastPageDataLength : void 0;
|
|
107
|
+
}
|
|
108
|
+
async function executeFunctionOnFirstSuccessfulIntegration(deps, integrations, params) {
|
|
109
|
+
const validatedRepo = await repoUtils.validateAndBuildRepoData(
|
|
110
|
+
deps.githubCredentialsProvider,
|
|
111
|
+
integrations,
|
|
112
|
+
deps.config,
|
|
113
|
+
params
|
|
114
|
+
);
|
|
115
|
+
for (const credential of validatedRepo.credentials) {
|
|
116
|
+
const octo = ghUtils.buildOcto(
|
|
117
|
+
{
|
|
118
|
+
logger: deps.logger,
|
|
119
|
+
cache: deps.cache
|
|
120
|
+
},
|
|
121
|
+
{ credential, owner: validatedRepo.owner },
|
|
122
|
+
validatedRepo.ghConfig.apiBaseUrl
|
|
123
|
+
);
|
|
124
|
+
if (!octo) {
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
const res = await params.fn(validatedRepo, octo);
|
|
128
|
+
if (!res.successful) {
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
return res.result;
|
|
132
|
+
}
|
|
133
|
+
return void 0;
|
|
134
|
+
}
|
|
135
|
+
async function fetchFromAllIntegrations(deps, integrations, params) {
|
|
136
|
+
const ghConfigs = verifyAndGetIntegrations(deps, integrations);
|
|
137
|
+
const credentialsByConfig = await getCredentialsFromIntegrations(
|
|
138
|
+
deps.githubCredentialsProvider,
|
|
139
|
+
ghConfigs
|
|
140
|
+
);
|
|
141
|
+
const errors = /* @__PURE__ */ new Map();
|
|
142
|
+
const data = [];
|
|
143
|
+
const dataErrs = [];
|
|
144
|
+
let stopFetchingData = false;
|
|
145
|
+
for (const [ghConfig, credentials] of credentialsByConfig) {
|
|
146
|
+
if (stopFetchingData) {
|
|
147
|
+
break;
|
|
148
|
+
}
|
|
149
|
+
deps.logger.debug(
|
|
150
|
+
`Got ${credentials.length} credential(s) for ${ghConfig.host}`
|
|
151
|
+
);
|
|
152
|
+
for (const credential of credentials) {
|
|
153
|
+
const octokit = ghUtils.buildOcto(
|
|
154
|
+
deps,
|
|
155
|
+
{ credential, errors },
|
|
156
|
+
ghConfig.apiBaseUrl
|
|
157
|
+
);
|
|
158
|
+
if (!octokit) {
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
const res = await params.dataFetcher(octokit, credential, ghConfig);
|
|
162
|
+
res.errors?.forEach((err) => dataErrs.push(err));
|
|
163
|
+
if (res.result) {
|
|
164
|
+
data.push(res.result);
|
|
165
|
+
}
|
|
166
|
+
stopFetchingData = res.stopFetchingData;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const aggregatedErrors = /* @__PURE__ */ new Map();
|
|
170
|
+
errors.forEach((err, num) => aggregatedErrors.set(num, err));
|
|
171
|
+
dataErrs.forEach((err, idx) => aggregatedErrors.set(idx, err));
|
|
172
|
+
return { data, errors: aggregatedErrors };
|
|
173
|
+
}
|
|
174
|
+
function computeTotalCount(data, countList, pageSize) {
|
|
175
|
+
let totalCount = countList.reduce(
|
|
176
|
+
(accumulator, currentValue) => accumulator + currentValue,
|
|
177
|
+
0
|
|
178
|
+
);
|
|
179
|
+
if (totalCount < pageSize) {
|
|
180
|
+
totalCount = data.length;
|
|
181
|
+
}
|
|
182
|
+
return totalCount;
|
|
183
|
+
}
|
|
184
|
+
function extractLocationOwnerMap(locationUrls) {
|
|
185
|
+
const locationGitOwnerMap = /* @__PURE__ */ new Map();
|
|
186
|
+
for (const locationUrl of locationUrls) {
|
|
187
|
+
const split = locationUrl.split("/blob/");
|
|
188
|
+
if (split.length < 2) {
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
locationGitOwnerMap.set(locationUrl, gitUrlParse__default.default(split[0]).owner);
|
|
192
|
+
}
|
|
193
|
+
return locationGitOwnerMap;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
exports.computeTotalCount = computeTotalCount;
|
|
197
|
+
exports.computeTotalCountFromGitHubToken = computeTotalCountFromGitHubToken;
|
|
198
|
+
exports.createCredentialError = createCredentialError;
|
|
199
|
+
exports.executeFunctionOnFirstSuccessfulIntegration = executeFunctionOnFirstSuccessfulIntegration;
|
|
200
|
+
exports.extractLocationOwnerMap = extractLocationOwnerMap;
|
|
201
|
+
exports.fetchFromAllIntegrations = fetchFromAllIntegrations;
|
|
202
|
+
exports.getCredentialsForConfig = getCredentialsForConfig;
|
|
203
|
+
exports.getCredentialsFromIntegrations = getCredentialsFromIntegrations;
|
|
204
|
+
exports.handleError = handleError;
|
|
205
|
+
exports.verifyAndGetIntegrations = verifyAndGetIntegrations;
|
|
206
|
+
//# sourceMappingURL=utils.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.cjs.js","sources":["../../../src/github/utils/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 */\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,OAAA;AAAA,SACf;AAAA,OACF,CAAA;AAA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