@red-hat-developer-hub/backstage-plugin-bulk-import-backend 5.2.2 → 5.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/dist/github/GithubAppManager.cjs.js +8 -8
- package/dist/github/GithubAppManager.cjs.js.map +1 -1
- package/dist/github/githubApiService.cjs.js +3 -3
- package/dist/github/githubApiService.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/helpers/utils.cjs.js +1 -1
- package/dist/helpers/utils.cjs.js.map +1 -1
- package/dist/service/handlers/import/bulkImports.cjs.js +10 -10
- package/dist/service/handlers/import/bulkImports.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/repository/repositories.cjs.js +5 -5
- package/dist/service/handlers/repository/repositories.cjs.js.map +1 -1
- package/dist/service/router.cjs.js +3 -3
- package/dist/service/router.cjs.js.map +1 -1
- package/package.json +27 -17
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,29 @@
|
|
|
1
1
|
### Dependencies
|
|
2
2
|
|
|
3
|
+
## 5.4.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 95b14e6: Backstage version bump to v1.36.1
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- Updated dependencies [95b14e6]
|
|
12
|
+
- @red-hat-developer-hub/backstage-plugin-bulk-import-common@1.6.0
|
|
13
|
+
|
|
14
|
+
## 5.3.0
|
|
15
|
+
|
|
16
|
+
### Minor Changes
|
|
17
|
+
|
|
18
|
+
- fbbd37f: Backstage version bump to v1.35.0
|
|
19
|
+
|
|
20
|
+
### Patch Changes
|
|
21
|
+
|
|
22
|
+
- 05a1ce0: Updated dependency `@openapitools/openapi-generator-cli` to `2.16.3`.
|
|
23
|
+
- 816d8bc: Updated dependency `@openapitools/openapi-generator-cli` to `2.16.2`.
|
|
24
|
+
- Updated dependencies [fbbd37f]
|
|
25
|
+
- @red-hat-developer-hub/backstage-plugin-bulk-import-common@1.5.0
|
|
26
|
+
|
|
3
27
|
## 5.2.2
|
|
4
28
|
|
|
5
29
|
### Patch Changes
|
|
@@ -69,7 +69,7 @@ class GithubAppManager {
|
|
|
69
69
|
installationDataFiltered = installationData;
|
|
70
70
|
}
|
|
71
71
|
if (installationDataFiltered.length === 0) {
|
|
72
|
-
return Array.of({ accessToken:
|
|
72
|
+
return Array.of({ accessToken: undefined });
|
|
73
73
|
}
|
|
74
74
|
for (const installation of installationDataFiltered) {
|
|
75
75
|
const installationId = installation.installationId;
|
|
@@ -147,13 +147,13 @@ class GithubAppsCredentialManager {
|
|
|
147
147
|
}
|
|
148
148
|
async getAppToken(host) {
|
|
149
149
|
if (this.apps.length === 0) {
|
|
150
|
-
return
|
|
150
|
+
return undefined;
|
|
151
151
|
}
|
|
152
152
|
const results = await Promise.all(
|
|
153
153
|
this.apps.map(
|
|
154
154
|
(app) => app.getInstallationCredentials(host).then(
|
|
155
|
-
(credentials) => ({ credentials, error:
|
|
156
|
-
(error) => ({ credentials:
|
|
155
|
+
(credentials) => ({ credentials, error: undefined }),
|
|
156
|
+
(error) => ({ credentials: undefined, error })
|
|
157
157
|
)
|
|
158
158
|
)
|
|
159
159
|
);
|
|
@@ -168,7 +168,7 @@ class GithubAppsCredentialManager {
|
|
|
168
168
|
if (notNotFoundError) {
|
|
169
169
|
throw notNotFoundError;
|
|
170
170
|
}
|
|
171
|
-
return
|
|
171
|
+
return undefined;
|
|
172
172
|
}
|
|
173
173
|
/**
|
|
174
174
|
* Returns an array of app access tokens.
|
|
@@ -183,9 +183,9 @@ class GithubAppsCredentialManager {
|
|
|
183
183
|
(credentials2) => ({
|
|
184
184
|
appId: app.getAppId(),
|
|
185
185
|
credentials: credentials2,
|
|
186
|
-
error:
|
|
186
|
+
error: undefined
|
|
187
187
|
}),
|
|
188
|
-
(error) => ({ appId: app.getAppId(), credentials:
|
|
188
|
+
(error) => ({ appId: app.getAppId(), credentials: undefined, error })
|
|
189
189
|
)
|
|
190
190
|
)
|
|
191
191
|
);
|
|
@@ -250,7 +250,7 @@ class CustomSingleInstanceGithubCredentialsProvider {
|
|
|
250
250
|
token = this.token;
|
|
251
251
|
}
|
|
252
252
|
return {
|
|
253
|
-
headers: token ? { Authorization: `Bearer ${token}` } :
|
|
253
|
+
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
|
|
254
254
|
token,
|
|
255
255
|
type
|
|
256
256
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GithubAppManager.cjs.js","sources":["../../src/github/GithubAppManager.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 * Base code taken from upstream https://github.com/backstage/backstage/blob/master/packages/integration/src/github/SingleInstanceGithubCredentialsProvider.ts\n * due to them not exporting the `GithubAppManager` class. Modifications were made to grab access tokens from all apps scoped to a repository/organization/user\n */\nimport type {\n GithubAppConfig,\n GithubCredentials,\n GithubCredentialType,\n GithubIntegrationConfig,\n ScmIntegrationRegistry,\n} from '@backstage/integration';\n\nimport { createAppAuth } from '@octokit/auth-app';\nimport { Octokit, type RestEndpointMethodTypes } from '@octokit/rest';\nimport gitUrlParse from 'git-url-parse';\nimport { DateTime } from 'luxon';\n\nimport type {\n AppCredentialFetchResult,\n ExtendedGithubCredentials,\n ExtendedGithubCredentialsProvider,\n} from './types';\n\n/**\n * The Cache and GithubAppManager classes in this file were directly taken from the\n * upstream at https://github.com/backstage/backstage/blob/master/packages/integration/src/github/SingleInstanceGithubCredentialsProvider.ts\n * as they were not exported but were required when extending the GithubAppCredentialsMux.\n */\n\ntype InstallationData = {\n installationId: number;\n accountLogin?: string;\n suspended: boolean;\n};\n\ntype InstallationTokenData = {\n token: string;\n expiresAt: DateTime;\n repositories?: string[];\n installationAccountLogin?: string;\n};\nclass Cache {\n private readonly tokenCache = new Map<string, InstallationTokenData>();\n\n private isExpired(date: DateTime) {\n return DateTime.local() > date;\n }\n\n async getOrCreateToken(\n key: string,\n supplier: () => Promise<InstallationTokenData>,\n ): Promise<{ accessToken: string; installationAccountLogin?: string }> {\n let existingInstallationData = this.tokenCache.get(key);\n\n if (\n !existingInstallationData ||\n this.isExpired(existingInstallationData.expiresAt)\n ) {\n existingInstallationData = await supplier();\n // Allow 10 minutes grace to account for clock skew\n existingInstallationData.expiresAt =\n existingInstallationData.expiresAt.minus({ minutes: 10 });\n this.tokenCache.set(key, existingInstallationData);\n }\n\n return {\n accessToken: existingInstallationData.token,\n installationAccountLogin:\n existingInstallationData.installationAccountLogin,\n };\n }\n}\n\n/**\n * This accept header is required when calling App APIs in GitHub Enterprise.\n * It has no effect on calls to github.com and can probably be removed entirely\n * once GitHub Apps is out of preview.\n */\nconst HEADERS = {\n Accept: 'application/vnd.github.machine-man-preview+json',\n};\n\n/**\n * GithubAppManager issues and caches tokens for a specific GitHub App.\n */\nclass GithubAppManager {\n private readonly appClient: Octokit;\n private readonly baseUrl?: string;\n private readonly baseAuthConfig: { appId: number; privateKey: string };\n private readonly cache = new Cache();\n private readonly allowedInstallationOwners: string[] | undefined; // undefined allows all installations\n\n constructor(config: GithubAppConfig, baseUrl?: string) {\n this.allowedInstallationOwners = config.allowedInstallationOwners;\n this.baseUrl = baseUrl;\n this.baseAuthConfig = {\n appId: config.appId,\n privateKey: config.privateKey.replace(/\\\\n/gm, '\\n'),\n };\n this.appClient = new Octokit({\n baseUrl,\n headers: HEADERS,\n authStrategy: createAppAuth,\n auth: this.baseAuthConfig,\n });\n }\n getAppId(): number {\n return this.baseAuthConfig.appId;\n }\n\n async getInstallationCredentials(\n host: string,\n ): Promise<\n { accessToken: string | undefined; installationAccountLogin?: string }[]\n > {\n const creds: {\n accessToken: string | undefined;\n installationAccountLogin?: string;\n }[] = [];\n const installationData = await this.getInstallationData();\n let installationDataFiltered: InstallationData[] = [];\n if (this.allowedInstallationOwners) {\n for (const installation of installationData) {\n if (\n installation.accountLogin &&\n !this.allowedInstallationOwners.includes(installation.accountLogin)\n ) {\n continue;\n }\n installationDataFiltered.push(installation);\n }\n } else {\n installationDataFiltered = installationData;\n }\n\n if (installationDataFiltered.length === 0) {\n return Array.of({ accessToken: undefined }); // An empty token allows anonymous access to public repos\n }\n\n for (const installation of installationDataFiltered) {\n const installationId = installation.installationId;\n if (installation.suspended) {\n throw new Error(\n `The GitHub application for ${installationId} is suspended`,\n );\n }\n const cred = await this.cache.getOrCreateToken(\n `${host}-${installationId}`,\n async () => {\n const result =\n await this.appClient.apps.createInstallationAccessToken({\n installation_id: installationId,\n headers: HEADERS,\n });\n\n if (!result) {\n return {\n token: '',\n expiresAt: DateTime.now().plus({ minutes: 1 }),\n repositories: [],\n installationAccountLogin: installation.accountLogin,\n };\n }\n\n let repositoryNames;\n\n if (result.data.repository_selection === 'selected') {\n const installationClient = new Octokit({\n baseUrl: this.baseUrl,\n auth: result.data.token,\n });\n const repos = await installationClient.paginate(\n installationClient.apps.listReposAccessibleToInstallation,\n );\n // The return type of the paginate method is incorrect.\n const repositories: RestEndpointMethodTypes['apps']['listReposAccessibleToInstallation']['response']['data']['repositories'] =\n repos.repositories ?? repos;\n\n repositoryNames = repositories.map(repository => repository.name);\n }\n return {\n token: result.data.token,\n expiresAt: DateTime.fromISO(result.data.expires_at),\n repositories: repositoryNames,\n installationAccountLogin: installation.accountLogin,\n };\n },\n );\n creds.push(cred);\n }\n\n return creds;\n }\n\n getInstallations(): Promise<\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data']\n > {\n return this.appClient.paginate(this.appClient.apps.listInstallations);\n }\n\n private async getInstallationData(): Promise<InstallationData[]> {\n const allInstallations = await this.getInstallations();\n return allInstallations.map(installation => {\n return {\n installationId: installation.id,\n accountLogin: installation.account?.login,\n suspended: Boolean(installation.suspended_by),\n } as InstallationData;\n });\n }\n}\n\n/**\n * Manages all the github apps in the github integration configurations\n */\nexport class GithubAppsCredentialManager {\n private readonly apps: GithubAppManager[];\n\n constructor(config: GithubIntegrationConfig) {\n this.apps =\n config.apps?.map(ac => new GithubAppManager(ac, config.apiBaseUrl)) ?? [];\n }\n\n async getAllInstallations(): Promise<\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data']\n > {\n if (!this.apps.length) {\n return [];\n }\n\n const installs = await Promise.all(\n this.apps.map(app => app.getInstallations()),\n );\n\n return installs.flat();\n }\n\n async getAppToken(host: string): Promise<string | undefined> {\n if (this.apps.length === 0) {\n return undefined;\n }\n\n const results = await Promise.all(\n this.apps.map(app =>\n app.getInstallationCredentials(host).then(\n credentials => ({ credentials, error: undefined }),\n error => ({ credentials: undefined, error }),\n ),\n ),\n );\n\n const result = results.find(\n resultItem =>\n resultItem.credentials &&\n resultItem.credentials!.length !== 0 &&\n resultItem.credentials[0]?.accessToken,\n );\n if (result?.credentials) {\n return result.credentials[0].accessToken;\n }\n\n const errors = results.map(r => r.error);\n const notNotFoundError = errors.find(err => err?.name !== 'NotFoundError');\n if (notNotFoundError) {\n throw notNotFoundError;\n }\n\n return undefined;\n }\n\n /**\n * Returns an array of app access tokens.\n *\n * Some values in the array might not contain a token and will have an error field instead. This will need to be resolved on the user side\n */\n async getAllAppTokens(host: string): Promise<AppCredentialFetchResult[]> {\n if (this.apps.length === 0) return [];\n\n const appCredentials = await Promise.all(\n this.apps.map(app =>\n app.getInstallationCredentials(host).then(\n credentials => ({\n appId: app.getAppId(),\n credentials,\n error: undefined,\n }),\n error => ({ appId: app.getAppId(), credentials: undefined, error }),\n ),\n ),\n );\n const credentials: AppCredentialFetchResult[] = [];\n for (const cred of appCredentials) {\n if (cred.credentials) {\n for (const credElement of cred.credentials) {\n credentials.push({\n appId: cred.appId,\n accessToken: credElement.accessToken,\n installationAccountLogin: credElement.installationAccountLogin,\n });\n }\n } else {\n credentials.push({\n appId: cred.appId,\n error: cred.error,\n });\n }\n }\n return credentials;\n }\n}\n\nexport class CustomSingleInstanceGithubCredentialsProvider\n implements ExtendedGithubCredentialsProvider\n{\n static readonly create: (\n config: GithubIntegrationConfig,\n ) => ExtendedGithubCredentialsProvider = config => {\n return new CustomSingleInstanceGithubCredentialsProvider(\n new GithubAppsCredentialManager(config),\n config.token,\n );\n };\n\n private constructor(\n private readonly githubAppsCredentialManager: GithubAppsCredentialManager,\n private readonly token?: string,\n ) {}\n\n /**\n * Returns {@link GithubCredentials} for a given URL.\n *\n * @remarks\n *\n * Consecutive calls to this method with the same URL will return cached\n * credentials.\n *\n * The shortest lifetime for a token returned is 10 minutes.\n *\n * @example\n * ```ts\n * const { token, headers } = await getCredentials({\n * url: 'github.com/backstage/foobar'\n * })\n * ```\n *\n * @param opts - The organization or repository URL\n * @returns A promise of {@link GithubCredentials}.\n */\n async getCredentials(opts: { url: string }): Promise<GithubCredentials> {\n const parsed = gitUrlParse(opts.url);\n const owner = parsed.owner || parsed.name;\n\n let type: GithubCredentialType = 'app';\n let token = await this.githubAppsCredentialManager.getAppToken(owner);\n if (!token) {\n type = 'token';\n token = this.token;\n }\n\n return {\n headers: token ? { Authorization: `Bearer ${token}` } : undefined,\n token,\n type,\n };\n }\n\n /**\n * Returns {@link ExtendedGithubCredentials[]} for a given URL.\n *\n * @remarks\n *\n * Consecutive calls to this method with the same URL will return cached\n * credentials.\n *\n * The shortest lifetime for a token returned is 10 minutes.\n *\n * Errors may be included in the returned array if the app credentials could not be fetched\n * These need to be dealt with by the user.\n *\n * @example\n * ```ts\n * const credentialList = await getCredentials({\n * url: 'github.com/backstage/foobar'\n * })\n * for (const credential of credentialList){\n * if (credential.type === 'app'){\n * // Deal with the error if it exists\n * if (credentials.error){\n * console.error(`Error generating credential for ${credential.appId}: ${credential.error}`)\n * }\n * else {\n * // Do something with the token\n * }\n * }\n * else{\n * // Do something with the token\n * }\n *\n * }\n * ```\n *\n * @param opts - The organization or repository URL\n * @returns A promise of {@link ExtendedGithubCredentials[]}.\n */\n async getAllCredentials(opts: {\n host: string;\n }): Promise<ExtendedGithubCredentials[]> {\n const appCredentials =\n await this.githubAppsCredentialManager.getAllAppTokens(opts.host);\n\n const credentials: ExtendedGithubCredentials[] = [];\n if (this.token) {\n credentials.push({\n headers: { Authorization: `Bearer ${this.token}` },\n token: this.token,\n type: 'token',\n });\n }\n for (const app of appCredentials) {\n if ('accessToken' in app) {\n credentials.push({\n headers: { Authorization: `Bearer ${app.accessToken}` },\n token: app.accessToken,\n type: 'app',\n appId: app.appId,\n accountLogin: app.installationAccountLogin,\n });\n }\n // Add the app credentials with their errors as well so that user can deal with them\n else {\n credentials.push({\n type: 'app',\n error: app.error,\n appId: app.appId,\n });\n }\n }\n\n return credentials;\n }\n}\n\nexport class CustomGithubCredentialsProvider\n implements ExtendedGithubCredentialsProvider\n{\n static fromIntegrations(integrations: ScmIntegrationRegistry) {\n const credentialsProviders: Map<string, ExtendedGithubCredentialsProvider> =\n new Map<string, ExtendedGithubCredentialsProvider>();\n\n integrations.github.list().forEach(integration => {\n const credentialsProvider =\n CustomSingleInstanceGithubCredentialsProvider.create(\n integration.config,\n );\n credentialsProviders.set(integration.config.host, credentialsProvider);\n });\n return new CustomGithubCredentialsProvider(credentialsProviders);\n }\n\n private constructor(\n private readonly providers: Map<string, ExtendedGithubCredentialsProvider>,\n ) {}\n\n /**\n * Returns {@link GithubCredentials} for a given URL.\n *\n * @remarks\n *\n * Consecutive calls to this method with the same URL will return cached\n * credentials.\n *\n * The shortest lifetime for a token returned is 10 minutes.\n *\n * @example\n * ```ts\n * const { token, headers } = await getCredentials({\n * url: 'https://github.com/backstage/foobar'\n * })\n *\n * const { token, headers } = await getCredentials({\n * url: 'https://github.com/backstage'\n * })\n * ```\n *\n * @param opts - The organization or repository URL\n * @returns A promise of {@link GithubCredentials}.\n */\n async getCredentials(opts: { url: string }): Promise<GithubCredentials> {\n const parsed = new URL(opts.url);\n const provider = this.providers.get(parsed.host);\n\n if (!provider) {\n throw new Error(\n `There is no GitHub integration that matches ${opts.url}. Please add a configuration for an integration.`,\n );\n }\n\n return provider.getCredentials(opts);\n }\n\n async getAllCredentials(opts: {\n host: string;\n }): Promise<ExtendedGithubCredentials[]> {\n const provider = this.providers.get(opts.host);\n\n if (!provider) {\n throw new Error(\n `There is no GitHub integration that matches ${opts.host}. Please add a configuration for an integration.`,\n );\n }\n return provider.getAllCredentials(opts);\n }\n\n async getAllAppInstallations(config: GithubIntegrationConfig) {\n return new GithubAppsCredentialManager(config).getAllInstallations();\n }\n\n async getAppInstallationsForOrg(\n config: GithubIntegrationConfig,\n org: string,\n ) {\n const all = await this.getAllAppInstallations(config);\n return all.filter(install => install.account?.login === org);\n }\n}\n"],"names":["DateTime","Octokit","createAppAuth","credentials","gitUrlParse"],"mappings":";;;;;;;;;;;AAyDA,MAAM,KAAM,CAAA;AAAA,EACO,UAAA,uBAAiB,GAAmC,EAAA;AAAA,EAE7D,UAAU,IAAgB,EAAA;AAChC,IAAO,OAAAA,cAAA,CAAS,OAAU,GAAA,IAAA;AAAA;AAC5B,EAEA,MAAM,gBACJ,CAAA,GAAA,EACA,QACqE,EAAA;AACrE,IAAA,IAAI,wBA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AAA;AAGF,IAAO,OAAA,QAAA,CAAS,eAAe,IAAI,CAAA;AAAA;AACrC,EAEA,MAAM,kBAAkB,IAEiB,EAAA;AACvC,IAAA,MAAM,QAAW,GAAA,IAAA,CAAK,SAAU,CAAA,GAAA,CAAI,KAAK,IAAI,CAAA;AAE7C,IAAA,IAAI,CAAC,QAAU,EAAA;AACb,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,4CAAA,EAA+C,KAAK,IAAI,CAAA,gDAAA;AAAA,OAC1D;AAAA;AAEF,IAAO,OAAA,QAAA,CAAS,kBAAkB,IAAI,CAAA;AAAA;AACxC,EAEA,MAAM,uBAAuB,MAAiC,EAAA;AAC5D,IAAA,OAAO,IAAI,2BAAA,CAA4B,MAAM,CAAA,CAAE,mBAAoB,EAAA;AAAA;AACrE,EAEA,MAAM,yBACJ,CAAA,MAAA,EACA,GACA,EAAA;AACA,IAAA,MAAM,GAAM,GAAA,MAAM,IAAK,CAAA,sBAAA,CAAuB,MAAM,CAAA;AACpD,IAAA,OAAO,IAAI,MAAO,CAAA,CAAA,OAAA,KAAW,OAAQ,CAAA,OAAA,EAAS,UAAU,GAAG,CAAA;AAAA;AAE/D;;;;;;"}
|
|
1
|
+
{"version":3,"file":"GithubAppManager.cjs.js","sources":["../../src/github/GithubAppManager.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 * Base code taken from upstream https://github.com/backstage/backstage/blob/master/packages/integration/src/github/SingleInstanceGithubCredentialsProvider.ts\n * due to them not exporting the `GithubAppManager` class. Modifications were made to grab access tokens from all apps scoped to a repository/organization/user\n */\nimport type {\n GithubAppConfig,\n GithubCredentials,\n GithubCredentialType,\n GithubIntegrationConfig,\n ScmIntegrationRegistry,\n} from '@backstage/integration';\n\nimport { createAppAuth } from '@octokit/auth-app';\nimport { Octokit, type RestEndpointMethodTypes } from '@octokit/rest';\nimport gitUrlParse from 'git-url-parse';\nimport { DateTime } from 'luxon';\n\nimport type {\n AppCredentialFetchResult,\n ExtendedGithubCredentials,\n ExtendedGithubCredentialsProvider,\n} from './types';\n\n/**\n * The Cache and GithubAppManager classes in this file were directly taken from the\n * upstream at https://github.com/backstage/backstage/blob/master/packages/integration/src/github/SingleInstanceGithubCredentialsProvider.ts\n * as they were not exported but were required when extending the GithubAppCredentialsMux.\n */\n\ntype InstallationData = {\n installationId: number;\n accountLogin?: string;\n suspended: boolean;\n};\n\ntype InstallationTokenData = {\n token: string;\n expiresAt: DateTime;\n repositories?: string[];\n installationAccountLogin?: string;\n};\nclass Cache {\n private readonly tokenCache = new Map<string, InstallationTokenData>();\n\n private isExpired(date: DateTime) {\n return DateTime.local() > date;\n }\n\n async getOrCreateToken(\n key: string,\n supplier: () => Promise<InstallationTokenData>,\n ): Promise<{ accessToken: string; installationAccountLogin?: string }> {\n let existingInstallationData = this.tokenCache.get(key);\n\n if (\n !existingInstallationData ||\n this.isExpired(existingInstallationData.expiresAt)\n ) {\n existingInstallationData = await supplier();\n // Allow 10 minutes grace to account for clock skew\n existingInstallationData.expiresAt =\n existingInstallationData.expiresAt.minus({ minutes: 10 });\n this.tokenCache.set(key, existingInstallationData);\n }\n\n return {\n accessToken: existingInstallationData.token,\n installationAccountLogin:\n existingInstallationData.installationAccountLogin,\n };\n }\n}\n\n/**\n * This accept header is required when calling App APIs in GitHub Enterprise.\n * It has no effect on calls to github.com and can probably be removed entirely\n * once GitHub Apps is out of preview.\n */\nconst HEADERS = {\n Accept: 'application/vnd.github.machine-man-preview+json',\n};\n\n/**\n * GithubAppManager issues and caches tokens for a specific GitHub App.\n */\nclass GithubAppManager {\n private readonly appClient: Octokit;\n private readonly baseUrl?: string;\n private readonly baseAuthConfig: { appId: number; privateKey: string };\n private readonly cache = new Cache();\n private readonly allowedInstallationOwners: string[] | undefined; // undefined allows all installations\n\n constructor(config: GithubAppConfig, baseUrl?: string) {\n this.allowedInstallationOwners = config.allowedInstallationOwners;\n this.baseUrl = baseUrl;\n this.baseAuthConfig = {\n appId: config.appId,\n privateKey: config.privateKey.replace(/\\\\n/gm, '\\n'),\n };\n this.appClient = new Octokit({\n baseUrl,\n headers: HEADERS,\n authStrategy: createAppAuth,\n auth: this.baseAuthConfig,\n });\n }\n getAppId(): number {\n return this.baseAuthConfig.appId;\n }\n\n async getInstallationCredentials(\n host: string,\n ): Promise<\n { accessToken: string | undefined; installationAccountLogin?: string }[]\n > {\n const creds: {\n accessToken: string | undefined;\n installationAccountLogin?: string;\n }[] = [];\n const installationData = await this.getInstallationData();\n let installationDataFiltered: InstallationData[] = [];\n if (this.allowedInstallationOwners) {\n for (const installation of installationData) {\n if (\n installation.accountLogin &&\n !this.allowedInstallationOwners.includes(installation.accountLogin)\n ) {\n continue;\n }\n installationDataFiltered.push(installation);\n }\n } else {\n installationDataFiltered = installationData;\n }\n\n if (installationDataFiltered.length === 0) {\n return Array.of({ accessToken: undefined }); // An empty token allows anonymous access to public repos\n }\n\n for (const installation of installationDataFiltered) {\n const installationId = installation.installationId;\n if (installation.suspended) {\n throw new Error(\n `The GitHub application for ${installationId} is suspended`,\n );\n }\n const cred = await this.cache.getOrCreateToken(\n `${host}-${installationId}`,\n async () => {\n const result =\n await this.appClient.apps.createInstallationAccessToken({\n installation_id: installationId,\n headers: HEADERS,\n });\n\n if (!result) {\n return {\n token: '',\n expiresAt: DateTime.now().plus({ minutes: 1 }),\n repositories: [],\n installationAccountLogin: installation.accountLogin,\n };\n }\n\n let repositoryNames;\n\n if (result.data.repository_selection === 'selected') {\n const installationClient = new Octokit({\n baseUrl: this.baseUrl,\n auth: result.data.token,\n });\n const repos = await installationClient.paginate(\n installationClient.apps.listReposAccessibleToInstallation,\n );\n // The return type of the paginate method is incorrect.\n const repositories: RestEndpointMethodTypes['apps']['listReposAccessibleToInstallation']['response']['data']['repositories'] =\n repos.repositories ?? repos;\n\n repositoryNames = repositories.map(repository => repository.name);\n }\n return {\n token: result.data.token,\n expiresAt: DateTime.fromISO(result.data.expires_at),\n repositories: repositoryNames,\n installationAccountLogin: installation.accountLogin,\n };\n },\n );\n creds.push(cred);\n }\n\n return creds;\n }\n\n getInstallations(): Promise<\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data']\n > {\n return this.appClient.paginate(this.appClient.apps.listInstallations);\n }\n\n private async getInstallationData(): Promise<InstallationData[]> {\n const allInstallations = await this.getInstallations();\n return allInstallations.map(installation => {\n return {\n installationId: installation.id,\n accountLogin: installation.account?.login,\n suspended: Boolean(installation.suspended_by),\n } as InstallationData;\n });\n }\n}\n\n/**\n * Manages all the github apps in the github integration configurations\n */\nexport class GithubAppsCredentialManager {\n private readonly apps: GithubAppManager[];\n\n constructor(config: GithubIntegrationConfig) {\n this.apps =\n config.apps?.map(ac => new GithubAppManager(ac, config.apiBaseUrl)) ?? [];\n }\n\n async getAllInstallations(): Promise<\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data']\n > {\n if (!this.apps.length) {\n return [];\n }\n\n const installs = await Promise.all(\n this.apps.map(app => app.getInstallations()),\n );\n\n return installs.flat();\n }\n\n async getAppToken(host: string): Promise<string | undefined> {\n if (this.apps.length === 0) {\n return undefined;\n }\n\n const results = await Promise.all(\n this.apps.map(app =>\n app.getInstallationCredentials(host).then(\n credentials => ({ credentials, error: undefined }),\n error => ({ credentials: undefined, error }),\n ),\n ),\n );\n\n const result = results.find(\n resultItem =>\n resultItem.credentials &&\n resultItem.credentials!.length !== 0 &&\n resultItem.credentials[0]?.accessToken,\n );\n if (result?.credentials) {\n return result.credentials[0].accessToken;\n }\n\n const errors = results.map(r => r.error);\n const notNotFoundError = errors.find(err => err?.name !== 'NotFoundError');\n if (notNotFoundError) {\n throw notNotFoundError;\n }\n\n return undefined;\n }\n\n /**\n * Returns an array of app access tokens.\n *\n * Some values in the array might not contain a token and will have an error field instead. This will need to be resolved on the user side\n */\n async getAllAppTokens(host: string): Promise<AppCredentialFetchResult[]> {\n if (this.apps.length === 0) return [];\n\n const appCredentials = await Promise.all(\n this.apps.map(app =>\n app.getInstallationCredentials(host).then(\n credentials => ({\n appId: app.getAppId(),\n credentials,\n error: undefined,\n }),\n error => ({ appId: app.getAppId(), credentials: undefined, error }),\n ),\n ),\n );\n const credentials: AppCredentialFetchResult[] = [];\n for (const cred of appCredentials) {\n if (cred.credentials) {\n for (const credElement of cred.credentials) {\n credentials.push({\n appId: cred.appId,\n accessToken: credElement.accessToken,\n installationAccountLogin: credElement.installationAccountLogin,\n });\n }\n } else {\n credentials.push({\n appId: cred.appId,\n error: cred.error,\n });\n }\n }\n return credentials;\n }\n}\n\nexport class CustomSingleInstanceGithubCredentialsProvider\n implements ExtendedGithubCredentialsProvider\n{\n static readonly create: (\n config: GithubIntegrationConfig,\n ) => ExtendedGithubCredentialsProvider = config => {\n return new CustomSingleInstanceGithubCredentialsProvider(\n new GithubAppsCredentialManager(config),\n config.token,\n );\n };\n\n private constructor(\n private readonly githubAppsCredentialManager: GithubAppsCredentialManager,\n private readonly token?: string,\n ) {}\n\n /**\n * Returns {@link GithubCredentials} for a given URL.\n *\n * @remarks\n *\n * Consecutive calls to this method with the same URL will return cached\n * credentials.\n *\n * The shortest lifetime for a token returned is 10 minutes.\n *\n * @example\n * ```ts\n * const { token, headers } = await getCredentials({\n * url: 'github.com/backstage/foobar'\n * })\n * ```\n *\n * @param opts - The organization or repository URL\n * @returns A promise of {@link GithubCredentials}.\n */\n async getCredentials(opts: { url: string }): Promise<GithubCredentials> {\n const parsed = gitUrlParse(opts.url);\n const owner = parsed.owner || parsed.name;\n\n let type: GithubCredentialType = 'app';\n let token = await this.githubAppsCredentialManager.getAppToken(owner);\n if (!token) {\n type = 'token';\n token = this.token;\n }\n\n return {\n headers: token ? { Authorization: `Bearer ${token}` } : undefined,\n token,\n type,\n };\n }\n\n /**\n * Returns {@link ExtendedGithubCredentials[]} for a given URL.\n *\n * @remarks\n *\n * Consecutive calls to this method with the same URL will return cached\n * credentials.\n *\n * The shortest lifetime for a token returned is 10 minutes.\n *\n * Errors may be included in the returned array if the app credentials could not be fetched\n * These need to be dealt with by the user.\n *\n * @example\n * ```ts\n * const credentialList = await getCredentials({\n * url: 'github.com/backstage/foobar'\n * })\n * for (const credential of credentialList){\n * if (credential.type === 'app'){\n * // Deal with the error if it exists\n * if (credentials.error){\n * console.error(`Error generating credential for ${credential.appId}: ${credential.error}`)\n * }\n * else {\n * // Do something with the token\n * }\n * }\n * else{\n * // Do something with the token\n * }\n *\n * }\n * ```\n *\n * @param opts - The organization or repository URL\n * @returns A promise of {@link ExtendedGithubCredentials[]}.\n */\n async getAllCredentials(opts: {\n host: string;\n }): Promise<ExtendedGithubCredentials[]> {\n const appCredentials =\n await this.githubAppsCredentialManager.getAllAppTokens(opts.host);\n\n const credentials: ExtendedGithubCredentials[] = [];\n if (this.token) {\n credentials.push({\n headers: { Authorization: `Bearer ${this.token}` },\n token: this.token,\n type: 'token',\n });\n }\n for (const app of appCredentials) {\n if ('accessToken' in app) {\n credentials.push({\n headers: { Authorization: `Bearer ${app.accessToken}` },\n token: app.accessToken,\n type: 'app',\n appId: app.appId,\n accountLogin: app.installationAccountLogin,\n });\n }\n // Add the app credentials with their errors as well so that user can deal with them\n else {\n credentials.push({\n type: 'app',\n error: app.error,\n appId: app.appId,\n });\n }\n }\n\n return credentials;\n }\n}\n\nexport class CustomGithubCredentialsProvider\n implements ExtendedGithubCredentialsProvider\n{\n static fromIntegrations(integrations: ScmIntegrationRegistry) {\n const credentialsProviders: Map<string, ExtendedGithubCredentialsProvider> =\n new Map<string, ExtendedGithubCredentialsProvider>();\n\n integrations.github.list().forEach(integration => {\n const credentialsProvider =\n CustomSingleInstanceGithubCredentialsProvider.create(\n integration.config,\n );\n credentialsProviders.set(integration.config.host, credentialsProvider);\n });\n return new CustomGithubCredentialsProvider(credentialsProviders);\n }\n\n private constructor(\n private readonly providers: Map<string, ExtendedGithubCredentialsProvider>,\n ) {}\n\n /**\n * Returns {@link GithubCredentials} for a given URL.\n *\n * @remarks\n *\n * Consecutive calls to this method with the same URL will return cached\n * credentials.\n *\n * The shortest lifetime for a token returned is 10 minutes.\n *\n * @example\n * ```ts\n * const { token, headers } = await getCredentials({\n * url: 'https://github.com/backstage/foobar'\n * })\n *\n * const { token, headers } = await getCredentials({\n * url: 'https://github.com/backstage'\n * })\n * ```\n *\n * @param opts - The organization or repository URL\n * @returns A promise of {@link GithubCredentials}.\n */\n async getCredentials(opts: { url: string }): Promise<GithubCredentials> {\n const parsed = new URL(opts.url);\n const provider = this.providers.get(parsed.host);\n\n if (!provider) {\n throw new Error(\n `There is no GitHub integration that matches ${opts.url}. Please add a configuration for an integration.`,\n );\n }\n\n return provider.getCredentials(opts);\n }\n\n async getAllCredentials(opts: {\n host: string;\n }): Promise<ExtendedGithubCredentials[]> {\n const provider = this.providers.get(opts.host);\n\n if (!provider) {\n throw new Error(\n `There is no GitHub integration that matches ${opts.host}. Please add a configuration for an integration.`,\n );\n }\n return provider.getAllCredentials(opts);\n }\n\n async getAllAppInstallations(config: GithubIntegrationConfig) {\n return new GithubAppsCredentialManager(config).getAllInstallations();\n }\n\n async getAppInstallationsForOrg(\n config: GithubIntegrationConfig,\n org: string,\n ) {\n const all = await this.getAllAppInstallations(config);\n return all.filter(install => install.account?.login === org);\n }\n}\n"],"names":["DateTime","Octokit","createAppAuth","credentials","gitUrlParse"],"mappings":";;;;;;;;;;;AAyDA,MAAM,KAAM,CAAA;AAAA,EACO,UAAA,uBAAiB,GAAmC,EAAA;AAAA,EAE7D,UAAU,IAAgB,EAAA;AAChC,IAAO,OAAAA,cAAA,CAAS,OAAU,GAAA,IAAA;AAAA;AAC5B,EAEA,MAAM,gBACJ,CAAA,GAAA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D;AAAA;AAGF,IAAO,OAAA,QAAA,CAAS,eAAe,IAAI,CAAA;AAAA;AACrC,EAEA,MAAM,kBAAkB,IAEiB,EAAA;AACvC,IAAA,MAAM,QAAW,GAAA,IAAA,CAAK,SAAU,CAAA,GAAA,CAAI,KAAK,IAAI,CAAA;AAE7C,IAAA,IAAI,CAAC,QAAU,EAAA;AACb,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,4CAAA,EAA+C,KAAK,IAAI,CAAA,gDAAA;AAAA,OAC1D;AAAA;AAEF,IAAO,OAAA,QAAA,CAAS,kBAAkB,IAAI,CAAA;AAAA;AACxC,EAEA,MAAM,uBAAuB,MAAiC,EAAA;AAC5D,IAAA,OAAO,IAAI,2BAAA,CAA4B,MAAM,CAAA,CAAE,mBAAoB,EAAA;AAAA;AACrE,EAEA,MAAM,yBACJ,CAAA,MAAA,EACA,GACA,EAAA;AACA,IAAA,MAAM,GAAM,GAAA,MAAM,IAAK,CAAA,sBAAA,CAAuB,MAAM,CAAA;AACpD,IAAA,OAAO,IAAI,MAAO,CAAA,CAAA,OAAA,KAAW,OAAQ,CAAA,OAAA,EAAS,UAAU,GAAG,CAAA;AAAA;AAE/D;;;;;;"}
|
|
@@ -47,7 +47,7 @@ class GithubApiService {
|
|
|
47
47
|
ghConfig
|
|
48
48
|
);
|
|
49
49
|
const errors = /* @__PURE__ */ new Map();
|
|
50
|
-
let repository =
|
|
50
|
+
let repository = undefined;
|
|
51
51
|
for (const credential of credentials) {
|
|
52
52
|
const octokit = ghUtils.buildOcto(
|
|
53
53
|
{
|
|
@@ -538,14 +538,14 @@ class GithubApiService {
|
|
|
538
538
|
input.fileName,
|
|
539
539
|
input.defaultBranch
|
|
540
540
|
);
|
|
541
|
-
if (exists ===
|
|
541
|
+
if (exists === undefined) {
|
|
542
542
|
return { successful: false };
|
|
543
543
|
}
|
|
544
544
|
return { successful: true, result: exists };
|
|
545
545
|
}
|
|
546
546
|
}
|
|
547
547
|
);
|
|
548
|
-
if (fileExists ===
|
|
548
|
+
if (fileExists === undefined) {
|
|
549
549
|
throw new Error(
|
|
550
550
|
`Could not determine if repo at ${input.repoUrl} already has a file named ${input.fileName} in its default branch (${input.defaultBranch})`
|
|
551
551
|
);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"githubApiService.cjs.js","sources":["../../src/github/githubApiService.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n CacheService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport type { Config } from '@backstage/config';\nimport {\n GithubIntegrationConfig,\n ScmIntegrations,\n} from '@backstage/integration';\n\nimport { Octokit } from '@octokit/rest';\nimport gitUrlParse from 'git-url-parse';\n\nimport { getBranchName, getCatalogFilename } from '../catalog/catalogUtils';\nimport { logErrorIfNeeded } from '../helpers';\nimport {\n DefaultPageNumber,\n DefaultPageSize,\n} from '../service/handlers/handlers';\nimport { CustomGithubCredentialsProvider } from './GithubAppManager';\nimport {\n isGithubAppCredential,\n type ExtendedGithubCredentials,\n type GithubFetchError,\n type GithubOrganization,\n type GithubOrganizationResponse,\n type GithubRepository,\n type GithubRepositoryResponse,\n} from './types';\nimport { buildOcto } from './utils/ghUtils';\nimport {\n addGithubAppOrgs,\n addGithubTokenOrgs,\n getAllAppOrgs,\n} from './utils/orgUtils';\nimport { closePRWithComment, findOpenPRForBranch } from './utils/prUtils';\nimport {\n addGithubAppRepositories,\n addGithubTokenOrgRepositories,\n addGithubTokenRepositories,\n createOrUpdateFileInBranch,\n fileExistsInDefaultBranch,\n type ValidatedRepo,\n} from './utils/repoUtils';\nimport {\n computeTotalCount,\n executeFunctionOnFirstSuccessfulIntegration,\n extractLocationOwnerMap,\n fetchFromAllIntegrations,\n getCredentialsForConfig,\n} from './utils/utils';\n\nexport class GithubApiService {\n private readonly logger: LoggerService;\n private readonly integrations: ScmIntegrations;\n private readonly githubCredentialsProvider: CustomGithubCredentialsProvider;\n private readonly config: Config;\n // Cache for storing ETags (used for efficient caching of unchanged data returned by GitHub)\n private readonly cache: CacheService;\n\n constructor(\n logger: LoggerService,\n config: Config,\n cacheService: CacheService,\n ) {\n this.logger = logger;\n this.config = config;\n this.integrations = ScmIntegrations.fromConfig(config);\n this.githubCredentialsProvider =\n CustomGithubCredentialsProvider.fromIntegrations(this.integrations);\n this.cache = cacheService;\n }\n\n async getRepositoryFromIntegrations(repoUrl: string): Promise<{\n repository?: GithubRepository;\n errors?: GithubFetchError[];\n }> {\n const gitUrl = gitUrlParse(repoUrl);\n\n const ghConfig = this.integrations.github.byUrl(repoUrl)?.config;\n if (!ghConfig) {\n throw new Error(\n `No GitHub integration config found for repo ${repoUrl}. Please add a configuration entry under 'integrations.github`,\n );\n }\n\n const credentials = await getCredentialsForConfig(\n this.githubCredentialsProvider,\n ghConfig,\n );\n const errors = new Map<number, GithubFetchError>();\n let repository: GithubRepository | undefined = undefined;\n for (const credential of credentials) {\n const octokit = buildOcto(\n {\n logger: this.logger,\n cache: this.cache,\n },\n { credential, errors, owner: gitUrl.owner },\n ghConfig.apiBaseUrl,\n );\n if (!octokit) {\n continue;\n }\n const resp = await octokit.rest.repos.get({\n owner: gitUrl.owner,\n repo: gitUrl.name,\n });\n const repo = resp?.data;\n if (!repo) {\n continue;\n }\n repository = {\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 break;\n }\n\n return {\n repository,\n errors: Array.from(errors.values()),\n };\n }\n\n async getOrganizationsFromIntegrations(\n search?: string,\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n ): Promise<GithubOrganizationResponse> {\n const orgs = new Map<string, GithubOrganization>();\n const result = await fetchFromAllIntegrations(\n {\n logger: this.logger,\n cache: this.cache,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n const dataFetchErrors = new Map<number, GithubFetchError>();\n const resp = isGithubAppCredential(credential)\n ? await addGithubAppOrgs(\n {\n logger: this.logger,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n octokit,\n ghConfig,\n {\n credentialAccountLogin: credential.accountLogin,\n search,\n orgs,\n errors: dataFetchErrors,\n },\n )\n : await addGithubTokenOrgs(\n {\n logger: this.logger,\n },\n octokit,\n credential,\n {\n search,\n orgs,\n pageNumber,\n pageSize,\n errors: dataFetchErrors,\n },\n );\n\n this.logger.debug(\n `Got ${resp.totalCount} org(s) for ${ghConfig.host}`,\n );\n return {\n result: resp.totalCount ?? 0,\n errors: Array.from(dataFetchErrors.values()),\n };\n },\n },\n );\n\n const orgList = Array.from(orgs.values());\n const totalCount = computeTotalCount(orgList, result.data, pageSize);\n return {\n organizations: orgList,\n errors: Array.from(result.errors?.values() ?? []),\n totalCount,\n };\n }\n\n async getOrgRepositoriesFromIntegrations(\n orgName: string,\n search?: string,\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n ): Promise<GithubRepositoryResponse> {\n const repositories = new Map<string, GithubRepository>();\n const result = await fetchFromAllIntegrations(\n {\n logger: this.logger,\n cache: this.cache,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n const dataFetchErrors = new Map<number, GithubFetchError>();\n let resp: { totalCount?: number };\n if (isGithubAppCredential(credential)) {\n if (credential.accountLogin !== orgName) {\n return {};\n }\n resp = await addGithubAppRepositories(\n {\n logger: this.logger,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n octokit,\n credential,\n ghConfig,\n repositories,\n dataFetchErrors,\n {\n search,\n pageNumber,\n pageSize,\n },\n );\n } else {\n resp = await addGithubTokenOrgRepositories(\n {\n logger: this.logger,\n },\n octokit,\n credential,\n orgName,\n repositories,\n dataFetchErrors,\n {\n search,\n pageNumber,\n pageSize,\n },\n );\n }\n this.logger.debug(\n `Got ${resp.totalCount} org repo(s) for ${ghConfig.host}`,\n );\n return {\n stopFetchingData: true,\n result: resp.totalCount ?? 0,\n errors: Array.from(dataFetchErrors.values()),\n };\n },\n },\n );\n\n const repoList = Array.from(repositories.values());\n const totalCount = computeTotalCount(repoList, result.data, pageSize);\n return {\n repositories: repoList,\n errors: Array.from(result.errors?.values() ?? []),\n totalCount,\n };\n }\n\n /**\n * Returns GithubRepositoryResponse containing:\n * - a list of unique repositories the github integrations have access to\n * - a list of errors encountered by each app and/or token (if any exist)\n */\n async getRepositoriesFromIntegrations(\n search?: string,\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n ): Promise<GithubRepositoryResponse> {\n const repositories = new Map<string, GithubRepository>();\n const result = await fetchFromAllIntegrations(\n {\n logger: this.logger,\n cache: this.cache,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n const dataFetchErrors = new Map<number, GithubFetchError>();\n const resp = isGithubAppCredential(credential)\n ? await addGithubAppRepositories(\n {\n logger: this.logger,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n octokit,\n credential,\n ghConfig,\n repositories,\n dataFetchErrors,\n {\n search,\n pageNumber,\n pageSize,\n },\n )\n : await addGithubTokenRepositories(\n {\n logger: this.logger,\n },\n octokit,\n credential,\n repositories,\n dataFetchErrors,\n {\n search,\n pageNumber,\n pageSize,\n },\n );\n this.logger.debug(\n `Got ${resp.totalCount} repo(s) for ${ghConfig.host}`,\n );\n return {\n result: resp.totalCount ?? 0,\n errors: Array.from(dataFetchErrors.values()),\n };\n },\n },\n );\n\n const repoList = Array.from(repositories.values());\n const totalCount = computeTotalCount(repoList, result.data, pageSize);\n return {\n repositories: repoList,\n errors: Array.from(result.errors?.values() ?? []),\n totalCount,\n };\n }\n\n async filterLocationsAccessibleFromIntegrations(\n locationUrls: string[],\n ): Promise<string[]> {\n const locationGitOwnerMap = extractLocationOwnerMap(locationUrls);\n\n const allAccessibleAppOrgs = new Set<string>();\n const allAccessibleTokenOrgs = new Set<string>();\n const allAccessibleUsernames = new Set<string>();\n await fetchFromAllIntegrations(\n {\n logger: this.logger,\n cache: this.cache,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n if (isGithubAppCredential(credential)) {\n const appOrgMap = await getAllAppOrgs(\n this.githubCredentialsProvider,\n ghConfig,\n credential.accountLogin,\n );\n for (const [_, ghOrg] of appOrgMap) {\n allAccessibleAppOrgs.add(ghOrg.name);\n }\n } else {\n // find authenticated GitHub owner...\n const username = (await octokit.rest.users.getAuthenticated())?.data\n ?.login;\n if (username) {\n allAccessibleUsernames.add(username);\n }\n // ... along with orgs accessible from the token auth\n (await octokit.paginate(octokit.rest.orgs.listForAuthenticatedUser))\n ?.map(org => org.login)\n ?.forEach(orgName => allAccessibleTokenOrgs.add(orgName));\n }\n return {};\n },\n },\n );\n\n return locationUrls.filter(loc => {\n if (!locationGitOwnerMap.has(loc)) {\n return false;\n }\n const owner = locationGitOwnerMap.get(loc)!;\n return (\n allAccessibleAppOrgs.has(owner) ||\n allAccessibleTokenOrgs.has(owner) ||\n allAccessibleUsernames.has(owner)\n );\n });\n }\n\n async findImportOpenPr(\n logger: LoggerService,\n input: {\n repoUrl: string;\n includeCatalogInfoContent?: boolean;\n },\n ): Promise<{\n prNum?: number;\n prUrl?: string;\n prTitle?: string;\n prBody?: string;\n prCatalogInfoContent?: string;\n lastUpdate?: string;\n }> {\n const ghConfig = this.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 this.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(this.config);\n for (const credential of credentials) {\n const octo = buildOcto(\n {\n logger: this.logger,\n cache: this.cache,\n },\n { credential, owner },\n ghConfig.apiBaseUrl,\n );\n if (!octo) {\n continue;\n }\n try {\n return await findOpenPRForBranch(\n logger,\n this.config,\n octo,\n owner,\n repo,\n branchName,\n input.includeCatalogInfoContent,\n );\n } catch (error: any) {\n logErrorIfNeeded(this.logger, 'Error fetching pull requests', error);\n }\n }\n return {};\n }\n\n async submitPrToRepo(\n logger: LoggerService,\n input: {\n repoUrl: string;\n gitUrl: gitUrlParse.GitUrl;\n defaultBranch?: string;\n prTitle: string;\n prBody: string;\n catalogInfoContent: string;\n },\n ): Promise<{\n prUrl?: string;\n prNumber?: number;\n hasChanges?: boolean;\n lastUpdate?: string;\n errors?: string[];\n }> {\n const fileName = getCatalogFilename(this.config);\n const errors: any[] = [];\n\n const result = await executeFunctionOnFirstSuccessfulIntegration(\n {\n logger: this.logger,\n cache: this.cache,\n config: this.config,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (\n validatedRepo: ValidatedRepo,\n octo: Octokit,\n ): Promise<{\n successful: boolean;\n result?: {\n prUrl?: string;\n prNumber?: number;\n hasChanges?: boolean;\n lastUpdate?: string;\n };\n }> => {\n const { owner, repo, branchName } = validatedRepo;\n try {\n // Check if there is already a catalogInfo in the default branch\n const catalogInfoFileExists = await fileExistsInDefaultBranch(\n logger,\n octo,\n owner,\n repo,\n fileName,\n input.defaultBranch,\n );\n if (catalogInfoFileExists) {\n // No need to create a PR => component will be imported as is\n return {\n successful: true,\n result: {\n hasChanges: false,\n },\n };\n }\n\n const existingPrForBranch = await findOpenPRForBranch(\n logger,\n this.config,\n octo,\n owner,\n repo,\n branchName,\n );\n\n const repoData = await octo.rest.repos.get({\n owner,\n repo,\n });\n const parentRef = await octo.rest.git.getRef({\n owner,\n repo,\n ref: `heads/${repoData.data.default_branch}`,\n });\n if (existingPrForBranch.prNum) {\n await createOrUpdateFileInBranch(\n octo,\n owner,\n repo,\n branchName,\n fileName,\n input.catalogInfoContent,\n );\n const pullRequestResponse = await octo.rest.pulls.update({\n owner,\n repo,\n pull_number: existingPrForBranch.prNum,\n title: input.prTitle,\n body: input.prBody,\n head: branchName,\n base: repoData.data.default_branch,\n });\n return {\n successful: true,\n result: {\n prNumber: existingPrForBranch.prNum,\n prUrl: pullRequestResponse.data.html_url,\n lastUpdate: pullRequestResponse.data.updated_at,\n },\n };\n }\n\n let branchExists = false;\n try {\n await octo.rest.git.getRef({\n owner,\n repo,\n ref: `heads/${branchName}`,\n });\n branchExists = true;\n } catch (error: any) {\n if (error.status === 404) {\n await octo.rest.git.createRef({\n owner,\n repo,\n ref: `refs/heads/${branchName}`,\n sha: parentRef.data.object.sha,\n });\n } else {\n throw error;\n }\n }\n\n if (branchExists) {\n // update it in case it is outdated compared to the base branch\n try {\n await octo.repos.merge({\n owner: owner,\n repo: repo,\n base: branchName,\n head: repoData.data.default_branch,\n });\n } catch (error: any) {\n logErrorIfNeeded(\n this.logger,\n `Could not merge default branch ${repoData.data.default_branch} into import branch ${branchName}`,\n error,\n );\n }\n }\n\n await createOrUpdateFileInBranch(\n octo,\n owner,\n repo,\n branchName,\n fileName,\n input.catalogInfoContent,\n );\n\n const pullRequestResponse = await octo.rest.pulls.create({\n owner,\n repo,\n title: input.prTitle,\n body: input.prBody,\n head: branchName,\n base: repoData.data.default_branch,\n });\n return {\n successful: true,\n result: {\n prNumber: pullRequestResponse.data.number,\n prUrl: pullRequestResponse.data.html_url,\n lastUpdate: pullRequestResponse.data.updated_at,\n hasChanges: true,\n },\n };\n } catch (e: any) {\n logErrorIfNeeded(\n this.logger,\n `Couldn't create PR in ${input.repoUrl}`,\n e,\n );\n errors.push(e.message);\n return { successful: false };\n }\n },\n },\n );\n\n if (result) {\n return result;\n }\n\n logger.warn(\n `Tried all possible GitHub credentials, but could not create PR in ${input.repoUrl}. Please try again later...`,\n );\n\n return {\n errors: errors,\n };\n }\n\n async hasFileInRepo(input: {\n repoUrl: string;\n defaultBranch?: string;\n fileName: string;\n }) {\n const fileExists = await executeFunctionOnFirstSuccessfulIntegration(\n {\n logger: this.logger,\n cache: this.cache,\n config: this.config,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo } = validatedRepo;\n const exists = await fileExistsInDefaultBranch(\n this.logger,\n octo,\n owner,\n repo,\n input.fileName,\n input.defaultBranch,\n );\n if (exists === undefined) {\n return { successful: false };\n }\n return { successful: true, result: exists };\n },\n },\n );\n\n if (fileExists === undefined) {\n throw new Error(\n `Could not determine if repo at ${input.repoUrl} already has a file named ${input.fileName} in its default branch (${input.defaultBranch})`,\n );\n }\n\n return fileExists;\n }\n\n async closeImportPR(\n logger: LoggerService,\n input: {\n repoUrl: string;\n gitUrl: gitUrlParse.GitUrl;\n comment: string;\n },\n ) {\n await executeFunctionOnFirstSuccessfulIntegration(\n {\n logger: this.logger,\n cache: this.cache,\n config: this.config,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo, branchName } = validatedRepo;\n try {\n const existingPrForBranch = await findOpenPRForBranch(\n logger,\n this.config,\n octo,\n owner,\n repo,\n branchName,\n );\n if (existingPrForBranch.prNum) {\n await closePRWithComment(\n octo,\n owner,\n repo,\n existingPrForBranch.prNum,\n input.comment,\n );\n }\n return { successful: true };\n } catch (e: any) {\n logErrorIfNeeded(\n this.logger,\n `Couldn't close PR in ${input.repoUrl}`,\n e,\n );\n return { successful: false };\n }\n },\n },\n );\n }\n\n async deleteImportBranch(input: {\n repoUrl: string;\n gitUrl: gitUrlParse.GitUrl;\n }) {\n await executeFunctionOnFirstSuccessfulIntegration(\n {\n logger: this.logger,\n cache: this.cache,\n config: this.config,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo, branchName } = validatedRepo;\n try {\n await octo.git.deleteRef({\n owner: owner,\n repo: repo,\n ref: `heads/${branchName}`,\n });\n return { successful: true };\n } catch (e: any) {\n logErrorIfNeeded(\n this.logger,\n `Couldn't close import PR and/or delete import branch in ${input.repoUrl}`,\n e,\n );\n return { successful: false };\n }\n },\n },\n );\n }\n\n async isRepoEmpty(input: { repoUrl: string }) {\n return await executeFunctionOnFirstSuccessfulIntegration(\n {\n logger: this.logger,\n cache: this.cache,\n config: this.config,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo } = validatedRepo;\n const resp = await octo.rest.repos.listContributors({\n owner: owner,\n repo: repo,\n page: 1,\n per_page: 1,\n });\n const status = resp.status as 200 | 204;\n return { successful: true, result: status === 204 };\n },\n },\n );\n }\n}\n"],"names":["ScmIntegrations","CustomGithubCredentialsProvider","gitUrlParse","getCredentialsForConfig","buildOcto","DefaultPageNumber","DefaultPageSize","fetchFromAllIntegrations","isGithubAppCredential","addGithubAppOrgs","addGithubTokenOrgs","computeTotalCount","addGithubAppRepositories","addGithubTokenOrgRepositories","addGithubTokenRepositories","extractLocationOwnerMap","getAllAppOrgs","getBranchName","findOpenPRForBranch","logErrorIfNeeded","getCatalogFilename","executeFunctionOnFirstSuccessfulIntegration","fileExistsInDefaultBranch","createOrUpdateFileInBranch","pullRequestResponse","closePRWithComment"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoEO,MAAM,gBAAiB,CAAA;AAAA,EACX,MAAA;AAAA,EACA,YAAA;AAAA,EACA,yBAAA;AAAA,EACA,MAAA;AAAA;AAAA,EAEA,KAAA;AAAA,EAEjB,WAAA,CACE,MACA,EAAA,MAAA,EACA,YACA,EAAA;AACA,IAAA,IAAA,CAAK,MAAS,GAAA,MAAA;AACd,IAAA,IAAA,CAAK,MAAS,GAAA,MAAA;AACd,IAAK,IAAA,CAAA,YAAA,GAAeA,2BAAgB,CAAA,UAAA,CAAW,MAAM,CAAA;AACrD,IAAA,IAAA,CAAK,yBACH,GAAAC,gDAAA,CAAgC,gBAAiB,CAAA,IAAA,CAAK,YAAY,CAAA;AACpE,IAAA,IAAA,CAAK,KAAQ,GAAA,YAAA;AAAA;AACf,EAEA,MAAM,8BAA8B,OAGjC,EAAA;AACD,IAAM,MAAA,MAAA,GAASC,6BAAY,OAAO,CAAA;AAElC,IAAA,MAAM,WAAW,IAAK,CAAA,YAAA,CAAa,MAAO,CAAA,KAAA,CAAM,OAAO,CAAG,EAAA,MAAA;AAC1D,IAAA,IAAI,CAAC,QAAU,EAAA;AACb,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,+CAA+C,OAAO,CAAA,6DAAA;AAAA,OACxD;AAAA;AAGF,IAAA,MAAM,cAAc,MAAMC,6BAAA;AAAA,MACxB,IAAK,CAAA,yBAAA;AAAA,MACL;AAAA,KACF;AACA,IAAM,MAAA,MAAA,uBAAa,GAA8B,EAAA;AACjD,IAAA,IAAI,UAA2C,GAAA,KAAA,CAAA;AAC/C,IAAA,KAAA,MAAW,cAAc,WAAa,EAAA;AACpC,MAAA,MAA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AAA,cACvB,KAAA;AAAA,cACA,IAAA;AAAA,cACA,GAAA,EAAK,SAAS,UAAU,CAAA;AAAA,aACzB,CAAA;AACD,YAAO,OAAA,EAAE,YAAY,IAAK,EAAA;AAAA,mBACnB,CAAQ,EAAA;AACf,YAAAF,6BAAA;AAAA,cACE,IAAK,CAAA,MAAA;AAAA,cACL,CAAA,wDAAA,EAA2D,MAAM,OAAO,CAAA,CAAA;AAAA,cACxE;AAAA,aACF;AACA,YAAO,OAAA,EAAE,YAAY,KAAM,EAAA;AAAA;AAC7B;AACF;AACF,KACF;AAAA;AACF,EAEA,MAAM,YAAY,KAA4B,EAAA;AAC5C,IAAA,OAAO,MAAME,iDAAA;AAAA,MACX;AAAA,QACE,QAAQ,IAAK,CAAA,MAAA;AAAA,QACb,OAAO,IAAK,CAAA,KAAA;AAAA,QACZ,QAAQ,IAAK,CAAA,MAAA;AAAA,QACb,2BAA2B,IAAK,CAAA;AAAA,OAClC;AAAA,MACA,IAAK,CAAA,YAAA;AAAA,MACL;AAAA,QACE,SAAS,KAAM,CAAA,OAAA;AAAA,QACf,EAAA,EAAI,OAAO,aAAA,EAA8B,IAAkB,KAAA;AACzD,UAAM,MAAA,EAAE,KAAO,EAAA,IAAA,EAAS,GAAA,aAAA;AACxB,UAAA,MAAM,IAAO,GAAA,MAAM,IAAK,CAAA,IAAA,CAAK,MAAM,gBAAiB,CAAA;AAAA,YAClD,KAAA;AAAA,YACA,IAAA;AAAA,YACA,IAAM,EAAA,CAAA;AAAA,YACN,QAAU,EAAA;AAAA,WACX,CAAA;AACD,UAAA,MAAM,SAAS,IAAK,CAAA,MAAA;AACpB,UAAA,OAAO,EAAE,UAAA,EAAY,IAAM,EAAA,MAAA,EAAQ,WAAW,GAAI,EAAA;AAAA;AACpD;AACF,KACF;AAAA;AAEJ;;;;"}
|
|
1
|
+
{"version":3,"file":"githubApiService.cjs.js","sources":["../../src/github/githubApiService.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n CacheService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport type { Config } from '@backstage/config';\nimport {\n GithubIntegrationConfig,\n ScmIntegrations,\n} from '@backstage/integration';\n\nimport { Octokit } from '@octokit/rest';\nimport gitUrlParse from 'git-url-parse';\n\nimport { getBranchName, getCatalogFilename } from '../catalog/catalogUtils';\nimport { logErrorIfNeeded } from '../helpers';\nimport {\n DefaultPageNumber,\n DefaultPageSize,\n} from '../service/handlers/handlers';\nimport { CustomGithubCredentialsProvider } from './GithubAppManager';\nimport {\n isGithubAppCredential,\n type ExtendedGithubCredentials,\n type GithubFetchError,\n type GithubOrganization,\n type GithubOrganizationResponse,\n type GithubRepository,\n type GithubRepositoryResponse,\n} from './types';\nimport { buildOcto } from './utils/ghUtils';\nimport {\n addGithubAppOrgs,\n addGithubTokenOrgs,\n getAllAppOrgs,\n} from './utils/orgUtils';\nimport { closePRWithComment, findOpenPRForBranch } from './utils/prUtils';\nimport {\n addGithubAppRepositories,\n addGithubTokenOrgRepositories,\n addGithubTokenRepositories,\n createOrUpdateFileInBranch,\n fileExistsInDefaultBranch,\n type ValidatedRepo,\n} from './utils/repoUtils';\nimport {\n computeTotalCount,\n executeFunctionOnFirstSuccessfulIntegration,\n extractLocationOwnerMap,\n fetchFromAllIntegrations,\n getCredentialsForConfig,\n} from './utils/utils';\n\nexport class GithubApiService {\n private readonly logger: LoggerService;\n private readonly integrations: ScmIntegrations;\n private readonly githubCredentialsProvider: CustomGithubCredentialsProvider;\n private readonly config: Config;\n // Cache for storing ETags (used for efficient caching of unchanged data returned by GitHub)\n private readonly cache: CacheService;\n\n constructor(\n logger: LoggerService,\n config: Config,\n cacheService: CacheService,\n ) {\n this.logger = logger;\n this.config = config;\n this.integrations = ScmIntegrations.fromConfig(config);\n this.githubCredentialsProvider =\n CustomGithubCredentialsProvider.fromIntegrations(this.integrations);\n this.cache = cacheService;\n }\n\n async getRepositoryFromIntegrations(repoUrl: string): Promise<{\n repository?: GithubRepository;\n errors?: GithubFetchError[];\n }> {\n const gitUrl = gitUrlParse(repoUrl);\n\n const ghConfig = this.integrations.github.byUrl(repoUrl)?.config;\n if (!ghConfig) {\n throw new Error(\n `No GitHub integration config found for repo ${repoUrl}. Please add a configuration entry under 'integrations.github`,\n );\n }\n\n const credentials = await getCredentialsForConfig(\n this.githubCredentialsProvider,\n ghConfig,\n );\n const errors = new Map<number, GithubFetchError>();\n let repository: GithubRepository | undefined = undefined;\n for (const credential of credentials) {\n const octokit = buildOcto(\n {\n logger: this.logger,\n cache: this.cache,\n },\n { credential, errors, owner: gitUrl.owner },\n ghConfig.apiBaseUrl,\n );\n if (!octokit) {\n continue;\n }\n const resp = await octokit.rest.repos.get({\n owner: gitUrl.owner,\n repo: gitUrl.name,\n });\n const repo = resp?.data;\n if (!repo) {\n continue;\n }\n repository = {\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 break;\n }\n\n return {\n repository,\n errors: Array.from(errors.values()),\n };\n }\n\n async getOrganizationsFromIntegrations(\n search?: string,\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n ): Promise<GithubOrganizationResponse> {\n const orgs = new Map<string, GithubOrganization>();\n const result = await fetchFromAllIntegrations(\n {\n logger: this.logger,\n cache: this.cache,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n const dataFetchErrors = new Map<number, GithubFetchError>();\n const resp = isGithubAppCredential(credential)\n ? await addGithubAppOrgs(\n {\n logger: this.logger,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n octokit,\n ghConfig,\n {\n credentialAccountLogin: credential.accountLogin,\n search,\n orgs,\n errors: dataFetchErrors,\n },\n )\n : await addGithubTokenOrgs(\n {\n logger: this.logger,\n },\n octokit,\n credential,\n {\n search,\n orgs,\n pageNumber,\n pageSize,\n errors: dataFetchErrors,\n },\n );\n\n this.logger.debug(\n `Got ${resp.totalCount} org(s) for ${ghConfig.host}`,\n );\n return {\n result: resp.totalCount ?? 0,\n errors: Array.from(dataFetchErrors.values()),\n };\n },\n },\n );\n\n const orgList = Array.from(orgs.values());\n const totalCount = computeTotalCount(orgList, result.data, pageSize);\n return {\n organizations: orgList,\n errors: Array.from(result.errors?.values() ?? []),\n totalCount,\n };\n }\n\n async getOrgRepositoriesFromIntegrations(\n orgName: string,\n search?: string,\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n ): Promise<GithubRepositoryResponse> {\n const repositories = new Map<string, GithubRepository>();\n const result = await fetchFromAllIntegrations(\n {\n logger: this.logger,\n cache: this.cache,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n const dataFetchErrors = new Map<number, GithubFetchError>();\n let resp: { totalCount?: number };\n if (isGithubAppCredential(credential)) {\n if (credential.accountLogin !== orgName) {\n return {};\n }\n resp = await addGithubAppRepositories(\n {\n logger: this.logger,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n octokit,\n credential,\n ghConfig,\n repositories,\n dataFetchErrors,\n {\n search,\n pageNumber,\n pageSize,\n },\n );\n } else {\n resp = await addGithubTokenOrgRepositories(\n {\n logger: this.logger,\n },\n octokit,\n credential,\n orgName,\n repositories,\n dataFetchErrors,\n {\n search,\n pageNumber,\n pageSize,\n },\n );\n }\n this.logger.debug(\n `Got ${resp.totalCount} org repo(s) for ${ghConfig.host}`,\n );\n return {\n stopFetchingData: true,\n result: resp.totalCount ?? 0,\n errors: Array.from(dataFetchErrors.values()),\n };\n },\n },\n );\n\n const repoList = Array.from(repositories.values());\n const totalCount = computeTotalCount(repoList, result.data, pageSize);\n return {\n repositories: repoList,\n errors: Array.from(result.errors?.values() ?? []),\n totalCount,\n };\n }\n\n /**\n * Returns GithubRepositoryResponse containing:\n * - a list of unique repositories the github integrations have access to\n * - a list of errors encountered by each app and/or token (if any exist)\n */\n async getRepositoriesFromIntegrations(\n search?: string,\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n ): Promise<GithubRepositoryResponse> {\n const repositories = new Map<string, GithubRepository>();\n const result = await fetchFromAllIntegrations(\n {\n logger: this.logger,\n cache: this.cache,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n const dataFetchErrors = new Map<number, GithubFetchError>();\n const resp = isGithubAppCredential(credential)\n ? await addGithubAppRepositories(\n {\n logger: this.logger,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n octokit,\n credential,\n ghConfig,\n repositories,\n dataFetchErrors,\n {\n search,\n pageNumber,\n pageSize,\n },\n )\n : await addGithubTokenRepositories(\n {\n logger: this.logger,\n },\n octokit,\n credential,\n repositories,\n dataFetchErrors,\n {\n search,\n pageNumber,\n pageSize,\n },\n );\n this.logger.debug(\n `Got ${resp.totalCount} repo(s) for ${ghConfig.host}`,\n );\n return {\n result: resp.totalCount ?? 0,\n errors: Array.from(dataFetchErrors.values()),\n };\n },\n },\n );\n\n const repoList = Array.from(repositories.values());\n const totalCount = computeTotalCount(repoList, result.data, pageSize);\n return {\n repositories: repoList,\n errors: Array.from(result.errors?.values() ?? []),\n totalCount,\n };\n }\n\n async filterLocationsAccessibleFromIntegrations(\n locationUrls: string[],\n ): Promise<string[]> {\n const locationGitOwnerMap = extractLocationOwnerMap(locationUrls);\n\n const allAccessibleAppOrgs = new Set<string>();\n const allAccessibleTokenOrgs = new Set<string>();\n const allAccessibleUsernames = new Set<string>();\n await fetchFromAllIntegrations(\n {\n logger: this.logger,\n cache: this.cache,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n if (isGithubAppCredential(credential)) {\n const appOrgMap = await getAllAppOrgs(\n this.githubCredentialsProvider,\n ghConfig,\n credential.accountLogin,\n );\n for (const [_, ghOrg] of appOrgMap) {\n allAccessibleAppOrgs.add(ghOrg.name);\n }\n } else {\n // find authenticated GitHub owner...\n const username = (await octokit.rest.users.getAuthenticated())?.data\n ?.login;\n if (username) {\n allAccessibleUsernames.add(username);\n }\n // ... along with orgs accessible from the token auth\n (await octokit.paginate(octokit.rest.orgs.listForAuthenticatedUser))\n ?.map(org => org.login)\n ?.forEach(orgName => allAccessibleTokenOrgs.add(orgName));\n }\n return {};\n },\n },\n );\n\n return locationUrls.filter(loc => {\n if (!locationGitOwnerMap.has(loc)) {\n return false;\n }\n const owner = locationGitOwnerMap.get(loc)!;\n return (\n allAccessibleAppOrgs.has(owner) ||\n allAccessibleTokenOrgs.has(owner) ||\n allAccessibleUsernames.has(owner)\n );\n });\n }\n\n async findImportOpenPr(\n logger: LoggerService,\n input: {\n repoUrl: string;\n includeCatalogInfoContent?: boolean;\n },\n ): Promise<{\n prNum?: number;\n prUrl?: string;\n prTitle?: string;\n prBody?: string;\n prCatalogInfoContent?: string;\n lastUpdate?: string;\n }> {\n const ghConfig = this.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 this.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(this.config);\n for (const credential of credentials) {\n const octo = buildOcto(\n {\n logger: this.logger,\n cache: this.cache,\n },\n { credential, owner },\n ghConfig.apiBaseUrl,\n );\n if (!octo) {\n continue;\n }\n try {\n return await findOpenPRForBranch(\n logger,\n this.config,\n octo,\n owner,\n repo,\n branchName,\n input.includeCatalogInfoContent,\n );\n } catch (error: any) {\n logErrorIfNeeded(this.logger, 'Error fetching pull requests', error);\n }\n }\n return {};\n }\n\n async submitPrToRepo(\n logger: LoggerService,\n input: {\n repoUrl: string;\n gitUrl: gitUrlParse.GitUrl;\n defaultBranch?: string;\n prTitle: string;\n prBody: string;\n catalogInfoContent: string;\n },\n ): Promise<{\n prUrl?: string;\n prNumber?: number;\n hasChanges?: boolean;\n lastUpdate?: string;\n errors?: string[];\n }> {\n const fileName = getCatalogFilename(this.config);\n const errors: any[] = [];\n\n const result = await executeFunctionOnFirstSuccessfulIntegration(\n {\n logger: this.logger,\n cache: this.cache,\n config: this.config,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (\n validatedRepo: ValidatedRepo,\n octo: Octokit,\n ): Promise<{\n successful: boolean;\n result?: {\n prUrl?: string;\n prNumber?: number;\n hasChanges?: boolean;\n lastUpdate?: string;\n };\n }> => {\n const { owner, repo, branchName } = validatedRepo;\n try {\n // Check if there is already a catalogInfo in the default branch\n const catalogInfoFileExists = await fileExistsInDefaultBranch(\n logger,\n octo,\n owner,\n repo,\n fileName,\n input.defaultBranch,\n );\n if (catalogInfoFileExists) {\n // No need to create a PR => component will be imported as is\n return {\n successful: true,\n result: {\n hasChanges: false,\n },\n };\n }\n\n const existingPrForBranch = await findOpenPRForBranch(\n logger,\n this.config,\n octo,\n owner,\n repo,\n branchName,\n );\n\n const repoData = await octo.rest.repos.get({\n owner,\n repo,\n });\n const parentRef = await octo.rest.git.getRef({\n owner,\n repo,\n ref: `heads/${repoData.data.default_branch}`,\n });\n if (existingPrForBranch.prNum) {\n await createOrUpdateFileInBranch(\n octo,\n owner,\n repo,\n branchName,\n fileName,\n input.catalogInfoContent,\n );\n const pullRequestResponse = await octo.rest.pulls.update({\n owner,\n repo,\n pull_number: existingPrForBranch.prNum,\n title: input.prTitle,\n body: input.prBody,\n head: branchName,\n base: repoData.data.default_branch,\n });\n return {\n successful: true,\n result: {\n prNumber: existingPrForBranch.prNum,\n prUrl: pullRequestResponse.data.html_url,\n lastUpdate: pullRequestResponse.data.updated_at,\n },\n };\n }\n\n let branchExists = false;\n try {\n await octo.rest.git.getRef({\n owner,\n repo,\n ref: `heads/${branchName}`,\n });\n branchExists = true;\n } catch (error: any) {\n if (error.status === 404) {\n await octo.rest.git.createRef({\n owner,\n repo,\n ref: `refs/heads/${branchName}`,\n sha: parentRef.data.object.sha,\n });\n } else {\n throw error;\n }\n }\n\n if (branchExists) {\n // update it in case it is outdated compared to the base branch\n try {\n await octo.repos.merge({\n owner: owner,\n repo: repo,\n base: branchName,\n head: repoData.data.default_branch,\n });\n } catch (error: any) {\n logErrorIfNeeded(\n this.logger,\n `Could not merge default branch ${repoData.data.default_branch} into import branch ${branchName}`,\n error,\n );\n }\n }\n\n await createOrUpdateFileInBranch(\n octo,\n owner,\n repo,\n branchName,\n fileName,\n input.catalogInfoContent,\n );\n\n const pullRequestResponse = await octo.rest.pulls.create({\n owner,\n repo,\n title: input.prTitle,\n body: input.prBody,\n head: branchName,\n base: repoData.data.default_branch,\n });\n return {\n successful: true,\n result: {\n prNumber: pullRequestResponse.data.number,\n prUrl: pullRequestResponse.data.html_url,\n lastUpdate: pullRequestResponse.data.updated_at,\n hasChanges: true,\n },\n };\n } catch (e: any) {\n logErrorIfNeeded(\n this.logger,\n `Couldn't create PR in ${input.repoUrl}`,\n e,\n );\n errors.push(e.message);\n return { successful: false };\n }\n },\n },\n );\n\n if (result) {\n return result;\n }\n\n logger.warn(\n `Tried all possible GitHub credentials, but could not create PR in ${input.repoUrl}. Please try again later...`,\n );\n\n return {\n errors: errors,\n };\n }\n\n async hasFileInRepo(input: {\n repoUrl: string;\n defaultBranch?: string;\n fileName: string;\n }) {\n const fileExists = await executeFunctionOnFirstSuccessfulIntegration(\n {\n logger: this.logger,\n cache: this.cache,\n config: this.config,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo } = validatedRepo;\n const exists = await fileExistsInDefaultBranch(\n this.logger,\n octo,\n owner,\n repo,\n input.fileName,\n input.defaultBranch,\n );\n if (exists === undefined) {\n return { successful: false };\n }\n return { successful: true, result: exists };\n },\n },\n );\n\n if (fileExists === undefined) {\n throw new Error(\n `Could not determine if repo at ${input.repoUrl} already has a file named ${input.fileName} in its default branch (${input.defaultBranch})`,\n );\n }\n\n return fileExists;\n }\n\n async closeImportPR(\n logger: LoggerService,\n input: {\n repoUrl: string;\n gitUrl: gitUrlParse.GitUrl;\n comment: string;\n },\n ) {\n await executeFunctionOnFirstSuccessfulIntegration(\n {\n logger: this.logger,\n cache: this.cache,\n config: this.config,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo, branchName } = validatedRepo;\n try {\n const existingPrForBranch = await findOpenPRForBranch(\n logger,\n this.config,\n octo,\n owner,\n repo,\n branchName,\n );\n if (existingPrForBranch.prNum) {\n await closePRWithComment(\n octo,\n owner,\n repo,\n existingPrForBranch.prNum,\n input.comment,\n );\n }\n return { successful: true };\n } catch (e: any) {\n logErrorIfNeeded(\n this.logger,\n `Couldn't close PR in ${input.repoUrl}`,\n e,\n );\n return { successful: false };\n }\n },\n },\n );\n }\n\n async deleteImportBranch(input: {\n repoUrl: string;\n gitUrl: gitUrlParse.GitUrl;\n }) {\n await executeFunctionOnFirstSuccessfulIntegration(\n {\n logger: this.logger,\n cache: this.cache,\n config: this.config,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo, branchName } = validatedRepo;\n try {\n await octo.git.deleteRef({\n owner: owner,\n repo: repo,\n ref: `heads/${branchName}`,\n });\n return { successful: true };\n } catch (e: any) {\n logErrorIfNeeded(\n this.logger,\n `Couldn't close import PR and/or delete import branch in ${input.repoUrl}`,\n e,\n );\n return { successful: false };\n }\n },\n },\n );\n }\n\n async isRepoEmpty(input: { repoUrl: string }) {\n return await executeFunctionOnFirstSuccessfulIntegration(\n {\n logger: this.logger,\n cache: this.cache,\n config: this.config,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo } = validatedRepo;\n const resp = await octo.rest.repos.listContributors({\n owner: owner,\n repo: repo,\n page: 1,\n per_page: 1,\n });\n const status = resp.status as 200 | 204;\n return { successful: true, result: status === 204 };\n },\n },\n );\n }\n}\n"],"names":["ScmIntegrations","CustomGithubCredentialsProvider","gitUrlParse","getCredentialsForConfig","buildOcto","DefaultPageNumber","DefaultPageSize","fetchFromAllIntegrations","isGithubAppCredential","addGithubAppOrgs","addGithubTokenOrgs","computeTotalCount","addGithubAppRepositories","addGithubTokenOrgRepositories","addGithubTokenRepositories","extractLocationOwnerMap","getAllAppOrgs","getBranchName","findOpenPRForBranch","logErrorIfNeeded","getCatalogFilename","executeFunctionOnFirstSuccessfulIntegration","fileExistsInDefaultBranch","createOrUpdateFileInBranch","pullRequestResponse","closePRWithComment"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoEO,MAAM,gBAAiB,CAAA;AAAA,EACX,MAAA;AAAA,EACA,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,YAAO,OAAA,EAAE,YAAY,KAAM,EAAA;AAAA;AAC7B;AACF;AACF,KACF;AAAA;AACF,EAEA,MAAM,YAAY,KAA4B,EAAA;AAC5C,IAAA,OAAO,MAAME,iDAAA;AAAA,MACX;AAAA,QACE,QAAQ,IAAK,CAAA,MAAA;AAAA,QACb,OAAO,IAAK,CAAA,KAAA;AAAA,QACZ,QAAQ,IAAK,CAAA,MAAA;AAAA,QACb,2BAA2B,IAAK,CAAA;AAAA,OAClC;AAAA,MACA,IAAK,CAAA,YAAA;AAAA,MACL;AAAA,QACE,SAAS,KAAM,CAAA,OAAA;AAAA,QACf,EAAA,EAAI,OAAO,aAAA,EAA8B,IAAkB,KAAA;AACzD,UAAM,MAAA,EAAE,KAAO,EAAA,IAAA,EAAS,GAAA,aAAA;AACxB,UAAA,MAAM,IAAO,GAAA,MAAM,IAAK,CAAA,IAAA,CAAK,MAAM,gBAAiB,CAAA;AAAA,YAClD,KAAA;AAAA,YACA,IAAA;AAAA,YACA,IAAM,EAAA,CAAA;AAAA,YACN,QAAU,EAAA;AAAA,WACX,CAAA;AACD,UAAA,MAAM,SAAS,IAAK,CAAA,MAAA;AACpB,UAAA,OAAO,EAAE,UAAA,EAAY,IAAM,EAAA,MAAA,EAAQ,WAAW,GAAI,EAAA;AAAA;AACpD;AACF,KACF;AAAA;AAEJ;;;;"}
|
|
@@ -20,10 +20,10 @@ function buildOcto(deps, input, apiBaseUrl = GITHUB_DEFAULT_API_ENDPOINT) {
|
|
|
20
20
|
}
|
|
21
21
|
}
|
|
22
22
|
}
|
|
23
|
-
return
|
|
23
|
+
return undefined;
|
|
24
24
|
}
|
|
25
25
|
if (types.isGithubAppCredential(input.credential) && input.owner && input.credential.accountLogin !== input.owner) {
|
|
26
|
-
return
|
|
26
|
+
return undefined;
|
|
27
27
|
}
|
|
28
28
|
const octokit = new rest.Octokit({
|
|
29
29
|
baseUrl: apiBaseUrl,
|
|
@@ -78,7 +78,7 @@ function tryReplacingPlaceholdersInUrl(options) {
|
|
|
78
78
|
let startIdx = 0;
|
|
79
79
|
const url = options.url;
|
|
80
80
|
if (!url) {
|
|
81
|
-
return
|
|
81
|
+
return undefined;
|
|
82
82
|
}
|
|
83
83
|
while (startIdx < url.length) {
|
|
84
84
|
const openBraceIdx = url.indexOf("{", startIdx);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ghUtils.cjs.js","sources":["../../../src/github/utils/ghUtils.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n CacheService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\n\nimport { Octokit } from '@octokit/rest';\n\nimport {\n isGithubAppCredential,\n type ExtendedGithubCredentials,\n type GithubFetchError,\n} from '../types';\nimport { createCredentialError } from './utils';\n\nconst GITHUB_DEFAULT_API_ENDPOINT = 'https://api.github.com';\n\n// Cache TTL per entry added, based on the lower values of rate limits imposed by GH,\n// i.e., 5K requests per hour for requests using a personal token.\n// GitHub Apps owned by enterprises have a higher limit of 15K per hour.\n// See https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api?apiVersion=2022-11-28\nconst RESPONSE_CACHE_TTL_MILLIS = 60 * 60 * 1000;\n\nexport function buildOcto(\n deps: {\n logger: LoggerService;\n cache: CacheService;\n },\n input: {\n credential: ExtendedGithubCredentials;\n owner?: string;\n errors?: Map<number, GithubFetchError>;\n },\n apiBaseUrl: string = GITHUB_DEFAULT_API_ENDPOINT,\n): Octokit | undefined {\n if ('error' in input.credential) {\n if (input.credential.error?.name !== 'NotFoundError') {\n deps.logger.error(\n `Obtaining the Access Token Github App with appId: ${input.credential.appId} failed with ${input.credential.error}`,\n );\n const credentialError = createCredentialError(input.credential);\n if (credentialError) {\n deps.logger.debug(`${input.credential.appId}: ${credentialError}`);\n if (input.errors) {\n input.errors.set(input.credential.appId, credentialError);\n }\n }\n }\n return undefined;\n }\n if (\n isGithubAppCredential(input.credential) &&\n input.owner &&\n input.credential.accountLogin !== input.owner\n ) {\n return undefined;\n }\n const octokit = new Octokit({\n baseUrl: apiBaseUrl,\n auth: input.credential.token,\n });\n registerHooks(deps, octokit);\n return octokit;\n}\n\nfunction registerHooks(\n deps: {\n logger: LoggerService;\n cache: CacheService;\n },\n octokit: Octokit,\n) {\n const extractCacheKey = (options: any) =>\n `${options.method}--${tryReplacingPlaceholdersInUrl(options)}`;\n\n octokit.hook.before('request', async options => {\n if (!options.headers) {\n options.headers = {\n accept: 'application/json',\n 'user-agent': 'rhdh/bulk-import',\n };\n }\n // Use ETag from in-memory cache if available\n const cacheKey = extractCacheKey(options);\n const existingEtag = await deps.cache\n .get(cacheKey)\n ?.then((val?: any) => val?.etag);\n if (existingEtag) {\n options.headers['If-None-Match'] = existingEtag;\n } else {\n deps.logger.debug(`cache miss for key \"${cacheKey}\"`);\n }\n });\n\n octokit.hook.after('request', async (response, options) => {\n deps.logger.debug(\n `[GH API] ${options.method} ${tryReplacingPlaceholdersInUrl(options)}: ${\n response.status\n }`,\n );\n // If we get a successful response, the resource has changed, so update the in-memory cache\n const cacheKey = extractCacheKey(options);\n await deps.cache.set(\n cacheKey,\n {\n etag: response.headers.etag,\n ...response,\n },\n { ttl: RESPONSE_CACHE_TTL_MILLIS },\n );\n });\n\n octokit.hook.error('request', async (error: any, options) => {\n deps.logger.debug(\n `[GH API] ${options.method} ${tryReplacingPlaceholdersInUrl(options)}: ${\n error.status\n }`,\n );\n if (error.status !== 304) {\n throw error;\n }\n // \"304 Not Modified\" means that the resource hasn't changed,\n // and we should have a version of it in the cache\n return await deps.cache.get(extractCacheKey(options));\n });\n}\n\nfunction tryReplacingPlaceholdersInUrl(options: any) {\n // options.url might contain placeholders => need to replace them with their actual values to not get colliding keys\n\n let result = '';\n let startIdx = 0;\n\n const url = options.url as string | undefined;\n if (!url) {\n return undefined;\n }\n while (startIdx < url.length) {\n const openBraceIdx = url.indexOf('{', startIdx);\n if (openBraceIdx === -1) {\n // no '{' => append the rest of the string\n result += url.slice(startIdx);\n break;\n }\n\n // append part of the string before '{'\n result += url.slice(startIdx, openBraceIdx);\n\n const closeBraceIdx = url.indexOf('}', openBraceIdx);\n if (closeBraceIdx === -1) {\n // no '}' => append the rest of the string\n result += url.slice(openBraceIdx);\n break;\n }\n\n const key = url.slice(openBraceIdx + 1, closeBraceIdx);\n result += options[key] ?? `{${key}}`;\n\n startIdx = closeBraceIdx + 1;\n }\n\n return result;\n}\n"],"names":["createCredentialError","isGithubAppCredential","Octokit"],"mappings":";;;;;;AA8BA,MAAM,2BAA8B,GAAA,wBAAA;AAMpC,MAAM,yBAAA,GAA4B,KAAK,EAAK,GAAA,GAAA;AAErC,SAAS,SACd,CAAA,IAAA,EAIA,KAKA,EAAA,UAAA,GAAqB,2BACA,EAAA;AACrB,EAAI,IAAA,OAAA,IAAW,MAAM,UAAY,EAAA;AAC/B,IAAA,IAAI,KAAM,CAAA,UAAA,CAAW,KAAO,EAAA,IAAA,KAAS,eAAiB,EAAA;AACpD,MAAA,IAAA,CAAK,MAAO,CAAA,KAAA;AAAA,QACV,qDAAqD,KAAM,CAAA,UAAA,CAAW,KAAK,CAAgB,aAAA,EAAA,KAAA,CAAM,WAAW,KAAK,CAAA;AAAA,OACnH;AACA,MAAM,MAAA,eAAA,GAAkBA,2BAAsB,CAAA,KAAA,CAAM,UAAU,CAAA;AAC9D,MAAA,IAAI,eAAiB,EAAA;AACnB,QAAK,IAAA,CAAA,MAAA,CAAO,MAAM,CAAG,EAAA,KAAA,CAAM,WAAW,KAAK,CAAA,EAAA,EAAK,eAAe,CAAE,CAAA,CAAA;AACjE,QAAA,IAAI,MAAM,MAAQ,EAAA;AAChB,UAAA,KAAA,CAAM,MAAO,CAAA,GAAA,CAAI,KAAM,CAAA,UAAA,CAAW,OAAO,eAAe,CAAA;AAAA;AAC1D;AACF;AAEF,IAAO,OAAA,
|
|
1
|
+
{"version":3,"file":"ghUtils.cjs.js","sources":["../../../src/github/utils/ghUtils.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n CacheService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\n\nimport { Octokit } from '@octokit/rest';\n\nimport {\n isGithubAppCredential,\n type ExtendedGithubCredentials,\n type GithubFetchError,\n} from '../types';\nimport { createCredentialError } from './utils';\n\nconst GITHUB_DEFAULT_API_ENDPOINT = 'https://api.github.com';\n\n// Cache TTL per entry added, based on the lower values of rate limits imposed by GH,\n// i.e., 5K requests per hour for requests using a personal token.\n// GitHub Apps owned by enterprises have a higher limit of 15K per hour.\n// See https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api?apiVersion=2022-11-28\nconst RESPONSE_CACHE_TTL_MILLIS = 60 * 60 * 1000;\n\nexport function buildOcto(\n deps: {\n logger: LoggerService;\n cache: CacheService;\n },\n input: {\n credential: ExtendedGithubCredentials;\n owner?: string;\n errors?: Map<number, GithubFetchError>;\n },\n apiBaseUrl: string = GITHUB_DEFAULT_API_ENDPOINT,\n): Octokit | undefined {\n if ('error' in input.credential) {\n if (input.credential.error?.name !== 'NotFoundError') {\n deps.logger.error(\n `Obtaining the Access Token Github App with appId: ${input.credential.appId} failed with ${input.credential.error}`,\n );\n const credentialError = createCredentialError(input.credential);\n if (credentialError) {\n deps.logger.debug(`${input.credential.appId}: ${credentialError}`);\n if (input.errors) {\n input.errors.set(input.credential.appId, credentialError);\n }\n }\n }\n return undefined;\n }\n if (\n isGithubAppCredential(input.credential) &&\n input.owner &&\n input.credential.accountLogin !== input.owner\n ) {\n return undefined;\n }\n const octokit = new Octokit({\n baseUrl: apiBaseUrl,\n auth: input.credential.token,\n });\n registerHooks(deps, octokit);\n return octokit;\n}\n\nfunction registerHooks(\n deps: {\n logger: LoggerService;\n cache: CacheService;\n },\n octokit: Octokit,\n) {\n const extractCacheKey = (options: any) =>\n `${options.method}--${tryReplacingPlaceholdersInUrl(options)}`;\n\n octokit.hook.before('request', async options => {\n if (!options.headers) {\n options.headers = {\n accept: 'application/json',\n 'user-agent': 'rhdh/bulk-import',\n };\n }\n // Use ETag from in-memory cache if available\n const cacheKey = extractCacheKey(options);\n const existingEtag = await deps.cache\n .get(cacheKey)\n ?.then((val?: any) => val?.etag);\n if (existingEtag) {\n options.headers['If-None-Match'] = existingEtag;\n } else {\n deps.logger.debug(`cache miss for key \"${cacheKey}\"`);\n }\n });\n\n octokit.hook.after('request', async (response, options) => {\n deps.logger.debug(\n `[GH API] ${options.method} ${tryReplacingPlaceholdersInUrl(options)}: ${\n response.status\n }`,\n );\n // If we get a successful response, the resource has changed, so update the in-memory cache\n const cacheKey = extractCacheKey(options);\n await deps.cache.set(\n cacheKey,\n {\n etag: response.headers.etag,\n ...response,\n },\n { ttl: RESPONSE_CACHE_TTL_MILLIS },\n );\n });\n\n octokit.hook.error('request', async (error: any, options) => {\n deps.logger.debug(\n `[GH API] ${options.method} ${tryReplacingPlaceholdersInUrl(options)}: ${\n error.status\n }`,\n );\n if (error.status !== 304) {\n throw error;\n }\n // \"304 Not Modified\" means that the resource hasn't changed,\n // and we should have a version of it in the cache\n return await deps.cache.get(extractCacheKey(options));\n });\n}\n\nfunction tryReplacingPlaceholdersInUrl(options: any) {\n // options.url might contain placeholders => need to replace them with their actual values to not get colliding keys\n\n let result = '';\n let startIdx = 0;\n\n const url = options.url as string | undefined;\n if (!url) {\n return undefined;\n }\n while (startIdx < url.length) {\n const openBraceIdx = url.indexOf('{', startIdx);\n if (openBraceIdx === -1) {\n // no '{' => append the rest of the string\n result += url.slice(startIdx);\n break;\n }\n\n // append part of the string before '{'\n result += url.slice(startIdx, openBraceIdx);\n\n const closeBraceIdx = url.indexOf('}', openBraceIdx);\n if (closeBraceIdx === -1) {\n // no '}' => append the rest of the string\n result += url.slice(openBraceIdx);\n break;\n }\n\n const key = url.slice(openBraceIdx + 1, closeBraceIdx);\n result += options[key] ?? `{${key}}`;\n\n startIdx = closeBraceIdx + 1;\n }\n\n return result;\n}\n"],"names":["createCredentialError","isGithubAppCredential","Octokit"],"mappings":";;;;;;AA8BA,MAAM,2BAA8B,GAAA,wBAAA;AAMpC,MAAM,yBAAA,GAA4B,KAAK,EAAK,GAAA,GAAA;AAErC,SAAS,SACd,CAAA,IAAA,EAIA,KAKA,EAAA,UAAA,GAAqB,2BACA,EAAA;AACrB,EAAI,IAAA,OAAA,IAAW,MAAM,UAAY,EAAA;AAC/B,IAAA,IAAI,KAAM,CAAA,UAAA,CAAW,KAAO,EAAA,IAAA,KAAS,eAAiB,EAAA;AACpD,MAAA,IAAA,CAAK,MAAO,CAAA,KAAA;AAAA,QACV,qDAAqD,KAAM,CAAA,UAAA,CAAW,KAAK,CAAgB,aAAA,EAAA,KAAA,CAAM,WAAW,KAAK,CAAA;AAAA,OACnH;AACA,MAAM,MAAA,eAAA,GAAkBA,2BAAsB,CAAA,KAAA,CAAM,UAAU,CAAA;AAC9D,MAAA,IAAI,eAAiB,EAAA;AACnB,QAAK,IAAA,CAAA,MAAA,CAAO,MAAM,CAAG,EAAA,KAAA,CAAM,WAAW,KAAK,CAAA,EAAA,EAAK,eAAe,CAAE,CAAA,CAAA;AACjE,QAAA,IAAI,MAAM,MAAQ,EAAA;AAChB,UAAA,KAAA,CAAM,MAAO,CAAA,G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A;AACR,IAAO,OAAA,SAAA;AAAA;AAET,EAAO,OAAA,QAAA,GAAW,IAAI,MAAQ,EAAA;AAC5B,IAAA,MAAM,YAAe,GAAA,GAAA,CAAI,OAAQ,CAAA,GAAA,EAAK,QAAQ,CAAA;AAC9C,IAAA,IAAI,iBAAiB,EAAI,EAAA;AAEvB,MAAU,MAAA,IAAA,GAAA,CAAI,MAAM,QAAQ,CAAA;AAC5B,MAAA;AAAA;AAIF,IAAU,MAAA,IAAA,GAAA,CAAI,KAAM,CAAA,QAAA,EAAU,YAAY,CAAA;AAE1C,IAAA,MAAM,aAAgB,GAAA,GAAA,CAAI,OAAQ,CAAA,GAAA,EAAK,YAAY,CAAA;AACnD,IAAA,IAAI,kBAAkB,EAAI,EAAA;AAExB,MAAU,MAAA,IAAA,GAAA,CAAI,MAAM,YAAY,CAAA;AAChC,MAAA;AAAA;AAGF,IAAA,MAAM,GAAM,GAAA,GAAA,CAAI,KAAM,CAAA,YAAA,GAAe,GAAG,aAAa,CAAA;AACrD,IAAA,MAAA,IAAU,OAAQ,CAAA,GAAG,CAAK,IAAA,CAAA,CAAA,EAAI,GAAG,CAAA,CAAA,CAAA;AAEjC,IAAA,QAAA,GAAW,aAAgB,GAAA,CAAA;AAAA;AAG7B,EAAO,OAAA,MAAA;AACT;;;;"}
|
|
@@ -21,7 +21,7 @@ async function getAllAppOrgs(githubCredentialsProvider, ghConfig, credentialAcco
|
|
|
21
21
|
}
|
|
22
22
|
result.set(acc.url, {
|
|
23
23
|
id: acc.id,
|
|
24
|
-
description: acc.description ??
|
|
24
|
+
description: acc.description ?? undefined,
|
|
25
25
|
name: acc.login,
|
|
26
26
|
url: acc.html_url,
|
|
27
27
|
html_url: acc.html_url,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orgUtils.cjs.js","sources":["../../../src/github/utils/orgUtils.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 {\n GithubCredentials,\n GithubIntegrationConfig,\n} from '@backstage/integration';\n\nimport { Octokit } from '@octokit/rest';\n\nimport { logErrorIfNeeded, paginateArray } from '../../helpers';\nimport {\n DefaultPageNumber,\n DefaultPageSize,\n} from '../../service/handlers/handlers';\nimport type { CustomGithubCredentialsProvider } from '../GithubAppManager';\nimport type { GithubFetchError, GithubOrganization } from '../types';\nimport { computeTotalCountFromGitHubToken, handleError } from './utils';\n\nexport async function getAllAppOrgs(\n githubCredentialsProvider: CustomGithubCredentialsProvider,\n ghConfig: GithubIntegrationConfig,\n credentialAccountLogin?: string,\n) {\n const result = new Map<string, GithubOrganization>();\n const resp = await githubCredentialsProvider.getAllAppInstallations(ghConfig);\n for (const installation of resp ?? []) {\n if (\n !(\n installation.account &&\n installation.target_type?.toLowerCase() === 'organization'\n )\n ) {\n continue;\n }\n const acc = installation.account!;\n if (credentialAccountLogin !== acc.login) {\n continue;\n }\n result.set(acc.url, {\n id: acc.id,\n description: acc.description ?? undefined,\n name: acc.login,\n url: acc.html_url,\n html_url: acc.html_url,\n repos_url: acc.repos_url,\n events_url: acc.events_url,\n });\n }\n return result;\n}\n\nexport async function addGithubAppOrgs(\n deps: {\n logger: LoggerService;\n githubCredentialsProvider: CustomGithubCredentialsProvider;\n },\n octokit: Octokit,\n ghConfig: GithubIntegrationConfig,\n params: {\n credentialAccountLogin: string | undefined;\n search: string | undefined;\n orgs: Map<string, GithubOrganization>;\n errors: Map<number, GithubFetchError>;\n },\n): Promise<{ totalCount?: number }> {\n const credentialAccountLogin = params.credentialAccountLogin;\n const search = params.search;\n const orgs = params.orgs;\n const errors = params.errors;\n let totalCount = 0;\n try {\n const resp = await getAllAppOrgs(\n deps.githubCredentialsProvider,\n ghConfig,\n credentialAccountLogin,\n );\n for (const [orgUrl, ghOrg] of resp) {\n if (search && !ghOrg.name.toLowerCase().includes(search.toLowerCase())) {\n continue;\n }\n const orgData = await octokit.request(\n orgUrl.replace('/users/', '/orgs/'),\n );\n orgs.set(ghOrg.name, {\n ...ghOrg,\n public_repos: orgData?.data?.public_repos,\n total_private_repos: orgData?.data?.total_private_repos,\n owned_private_repos: orgData?.data?.owned_private_repos,\n });\n totalCount++;\n }\n } catch (err: any) {\n logErrorIfNeeded(\n deps.logger,\n `Fetching organizations with access token for github app`,\n err,\n );\n errors.set(-1, err.message);\n }\n return { totalCount };\n}\n\nexport async function addGithubTokenOrgs(\n deps: {\n logger: LoggerService;\n },\n octokit: Octokit,\n credential: GithubCredentials,\n params: {\n search: string | undefined;\n orgs: Map<string, GithubOrganization>;\n errors: Map<number, GithubFetchError>;\n pageNumber: number;\n pageSize: number;\n },\n): Promise<{ totalCount?: number }> {\n const search = params.search;\n const orgs = params.orgs;\n const errors = params.errors;\n const pageNumber = params.pageNumber ?? DefaultPageNumber;\n const pageSize = params.pageSize ?? DefaultPageSize;\n\n let totalCount: number | undefined;\n try {\n let matchingOrgs;\n if (search) {\n // Initial idea was to leverage octokit.rest.search.users({q: `${search} type:org`}),\n // but this searches across all of GitHub, not only the orgs accessible by the current creds.\n // That's why we are searching in everything, hoping the list of organizations to not be that big in size\n const resp = await octokit.paginate(\n octokit.rest.orgs.listForAuthenticatedUser,\n {\n sort: 'full_name',\n direction: 'asc',\n },\n );\n const allMatchingOrgs =\n resp?.filter(org =>\n org.login.toLowerCase().includes(search.toLowerCase()),\n ) ?? [];\n const matchingOrgsPage = paginateArray(\n allMatchingOrgs,\n pageNumber,\n pageSize,\n );\n matchingOrgs = matchingOrgsPage.result;\n totalCount = matchingOrgsPage.totalCount;\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.orgs.listForAuthenticatedUser({\n page: pageNumber,\n per_page: pageSize,\n sort: 'full_name',\n direction: 'asc',\n });\n matchingOrgs = resp?.data ?? [];\n\n totalCount = await computeTotalCountFromGitHubToken(\n deps,\n async (lastPageNumber: number) =>\n octokit.orgs\n .listForAuthenticatedUser({\n page: lastPageNumber,\n per_page: 100,\n })\n .then(lastPageResp => lastPageResp.data.length),\n 'orgs.listForAuthenticatedUser',\n resp?.data?.length,\n resp?.headers?.link,\n );\n }\n\n for (const org of matchingOrgs) {\n const orgData = await octokit.request(org.url);\n const ghOrg: GithubOrganization = {\n id: org.id,\n name: org.login,\n description: org.description ?? undefined,\n url: orgData?.data?.html_url ?? org.url,\n repos_url: org.repos_url,\n hooks_url: org.hooks_url,\n issues_url: org.issues_url,\n members_url: org.members_url,\n public_members_url: org.public_members_url,\n avatar_url: org.avatar_url,\n public_repos: orgData?.data?.public_repos,\n total_private_repos: orgData?.data?.total_private_repos,\n owned_private_repos: orgData?.data?.owned_private_repos,\n };\n orgs.set(org.login, ghOrg);\n }\n } catch (err) {\n handleError(\n { logger: deps.logger },\n 'Fetching orgs with token from token',\n credential,\n errors,\n err,\n );\n }\n return { totalCount };\n}\n"],"names":["logErrorIfNeeded","DefaultPageNumber","DefaultPageSize","paginateArray","computeTotalCountFromGitHubToken","handleError"],"mappings":";;;;;;;;;;AAiCsB,eAAA,aAAA,CACpB,yBACA,EAAA,QAAA,EACA,sBACA,EAAA;AACA,EAAM,MAAA,MAAA,uBAAa,GAAgC,EAAA;AACnD,EAAA,MAAM,IAAO,GAAA,MAAM,yBAA0B,CAAA,sBAAA,CAAuB,QAAQ,CAAA;AAC5E,EAAW,KAAA,MAAA,YAAA,IAAgB,IAAQ,IAAA,EAAI,EAAA;AACrC,IAAA,IACE,EACE,YAAa,CAAA,OAAA,IACb,aAA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AA,IAAY,GAAI,CAAA,GAAA;AAAA,QACpC,WAAW,GAAI,CAAA,SAAA;AAAA,QACf,WAAW,GAAI,CAAA,SAAA;AAAA,QACf,YAAY,GAAI,CAAA,UAAA;AAAA,QAChB,aAAa,GAAI,CAAA,WAAA;AAAA,QACjB,oBAAoB,GAAI,CAAA,kBAAA;AAAA,QACxB,YAAY,GAAI,CAAA,UAAA;AAAA,QAChB,YAAA,EAAc,SAAS,IAAM,EAAA,YAAA;AAAA,QAC7B,mBAAA,EAAqB,SAAS,IAAM,EAAA,mBAAA;AAAA,QACpC,mBAAA,EAAqB,SAAS,IAAM,EAAA;AAAA,OACtC;AACA,MAAK,IAAA,CAAA,GAAA,CAAI,GAAI,CAAA,KAAA,EAAO,KAAK,CAAA;AAAA;AAC3B,WACO,GAAK,EAAA;AACZ,IAAAC,iBAAA;AAAA,MACE,EAAE,MAAQ,EAAA,IAAA,CAAK,MAAO,EAAA;AAAA,MACtB,qCAAA;AAAA,MACA,UAAA;AAAA,MACA,MAAA;AAAA,MACA;AAAA,KACF;AAAA;AAEF,EAAA,OAAO,EAAE,UAAW,EAAA;AACtB;;;;;;"}
|
|
1
|
+
{"version":3,"file":"orgUtils.cjs.js","sources":["../../../src/github/utils/orgUtils.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 {\n GithubCredentials,\n GithubIntegrationConfig,\n} from '@backstage/integration';\n\nimport { Octokit } from '@octokit/rest';\n\nimport { logErrorIfNeeded, paginateArray } from '../../helpers';\nimport {\n DefaultPageNumber,\n DefaultPageSize,\n} from '../../service/handlers/handlers';\nimport type { CustomGithubCredentialsProvider } from '../GithubAppManager';\nimport type { GithubFetchError, GithubOrganization } from '../types';\nimport { computeTotalCountFromGitHubToken, handleError } from './utils';\n\nexport async function getAllAppOrgs(\n githubCredentialsProvider: CustomGithubCredentialsProvider,\n ghConfig: GithubIntegrationConfig,\n credentialAccountLogin?: string,\n) {\n const result = new Map<string, GithubOrganization>();\n const resp = await githubCredentialsProvider.getAllAppInstallations(ghConfig);\n for (const installation of resp ?? []) {\n if (\n !(\n installation.account &&\n installation.target_type?.toLowerCase() === 'organization'\n )\n ) {\n continue;\n }\n const acc = installation.account!;\n if (credentialAccountLogin !== acc.login) {\n continue;\n }\n result.set(acc.url, {\n id: acc.id,\n description: acc.description ?? undefined,\n name: acc.login,\n url: acc.html_url,\n html_url: acc.html_url,\n repos_url: acc.repos_url,\n events_url: acc.events_url,\n });\n }\n return result;\n}\n\nexport async function addGithubAppOrgs(\n deps: {\n logger: LoggerService;\n githubCredentialsProvider: CustomGithubCredentialsProvider;\n },\n octokit: Octokit,\n ghConfig: GithubIntegrationConfig,\n params: {\n credentialAccountLogin: string | undefined;\n search: string | undefined;\n orgs: Map<string, GithubOrganization>;\n errors: Map<number, GithubFetchError>;\n },\n): Promise<{ totalCount?: number }> {\n const credentialAccountLogin = params.credentialAccountLogin;\n const search = params.search;\n const orgs = params.orgs;\n const errors = params.errors;\n let totalCount = 0;\n try {\n const resp = await getAllAppOrgs(\n deps.githubCredentialsProvider,\n ghConfig,\n credentialAccountLogin,\n );\n for (const [orgUrl, ghOrg] of resp) {\n if (search && !ghOrg.name.toLowerCase().includes(search.toLowerCase())) {\n continue;\n }\n const orgData = await octokit.request(\n orgUrl.replace('/users/', '/orgs/'),\n );\n orgs.set(ghOrg.name, {\n ...ghOrg,\n public_repos: orgData?.data?.public_repos,\n total_private_repos: orgData?.data?.total_private_repos,\n owned_private_repos: orgData?.data?.owned_private_repos,\n });\n totalCount++;\n }\n } catch (err: any) {\n logErrorIfNeeded(\n deps.logger,\n `Fetching organizations with access token for github app`,\n err,\n );\n errors.set(-1, err.message);\n }\n return { totalCount };\n}\n\nexport async function addGithubTokenOrgs(\n deps: {\n logger: LoggerService;\n },\n octokit: Octokit,\n credential: GithubCredentials,\n params: {\n search: string | undefined;\n orgs: Map<string, GithubOrganization>;\n errors: Map<number, GithubFetchError>;\n pageNumber: number;\n pageSize: number;\n },\n): Promise<{ totalCount?: number }> {\n const search = params.search;\n const orgs = params.orgs;\n const errors = params.errors;\n const pageNumber = params.pageNumber ?? DefaultPageNumber;\n const pageSize = params.pageSize ?? DefaultPageSize;\n\n let totalCount: number | undefined;\n try {\n let matchingOrgs;\n if (search) {\n // Initial idea was to leverage octokit.rest.search.users({q: `${search} type:org`}),\n // but this searches across all of GitHub, not only the orgs accessible by the current creds.\n // That's why we are searching in everything, hoping the list of organizations to not be that big in size\n const resp = await octokit.paginate(\n octokit.rest.orgs.listForAuthenticatedUser,\n {\n sort: 'full_name',\n direction: 'asc',\n },\n );\n const allMatchingOrgs =\n resp?.filter(org =>\n org.login.toLowerCase().includes(search.toLowerCase()),\n ) ?? [];\n const matchingOrgsPage = paginateArray(\n allMatchingOrgs,\n pageNumber,\n pageSize,\n );\n matchingOrgs = matchingOrgsPage.result;\n totalCount = matchingOrgsPage.totalCount;\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.orgs.listForAuthenticatedUser({\n page: pageNumber,\n per_page: pageSize,\n sort: 'full_name',\n direction: 'asc',\n });\n matchingOrgs = resp?.data ?? [];\n\n totalCount = await computeTotalCountFromGitHubToken(\n deps,\n async (lastPageNumber: number) =>\n octokit.orgs\n .listForAuthenticatedUser({\n page: lastPageNumber,\n per_page: 100,\n })\n .then(lastPageResp => lastPageResp.data.length),\n 'orgs.listForAuthenticatedUser',\n resp?.data?.length,\n resp?.headers?.link,\n );\n }\n\n for (const org of matchingOrgs) {\n const orgData = await octokit.request(org.url);\n const ghOrg: GithubOrganization = {\n id: org.id,\n name: org.login,\n description: org.description ?? undefined,\n url: orgData?.data?.html_url ?? org.url,\n repos_url: org.repos_url,\n hooks_url: org.hooks_url,\n issues_url: org.issues_url,\n members_url: org.members_url,\n public_members_url: org.public_members_url,\n avatar_url: org.avatar_url,\n public_repos: orgData?.data?.public_repos,\n total_private_repos: orgData?.data?.total_private_repos,\n owned_private_repos: orgData?.data?.owned_private_repos,\n };\n orgs.set(org.login, ghOrg);\n }\n } catch (err) {\n handleError(\n { logger: deps.logger },\n 'Fetching orgs with token from token',\n credential,\n errors,\n err,\n );\n }\n return { totalCount };\n}\n"],"names":["logErrorIfNeeded","DefaultPageNumber","DefaultPageSize","paginateArray","computeTotalCountFromGitHubToken","handleError"],"mappings":";;;;;;;;;;AAiCsB,eAAA,aAAA,CACpB,yBACA,EAAA,QAAA,EACA,sBACA,EAAA;AACA,EAAM,MAAA,MAAA,uBAAa,GAAgC,EAAA;AACnD,EAAA,MAAM,IAAO,GAAA,MAAM,yBAA0B,CAAA,sBAAA,CAAuB,QAAQ,CAAA;AAC5E,EAAW,KAAA,MAAA,YAAA,IAAgB,IAAQ,IAAA,EAAI,EAAA;AACrC,IAAA,IACE,EACE,YAAa,CAAA,OAAA,IACb,aAAa,WAAa,EAAA,WAAA,OAAkB,cAE9C,CAAA,EAAA;AACA,MAAA;AAAA;AAEF,IAAA,MAAM,MAAM,YAAa,CAAA,OAAA;AACzB,IAAI,IAAA,sBAAA,KAA2B,IAAI,KAAO,EAAA;AACxC,MAAA;AAAA;AAEF,IAAO,MAAA,CAAA,GAAA,CAAI,IAAI,GAAK,EAAA;AAAA,MAClB,IAAI,GAAI,CAAA,EAAA;AAAA,MACR,WAAA,EAAa,IAAI,WAAe,IAAA,SAAA;AAAA,MAChC,MAAM,GAAI,CAAA,KAAA;AAAA,MACV,KAAK,GAAI,CAAA,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A;AAAA,OACtC;AACA,MAAK,IAAA,CAAA,GAAA,CAAI,GAAI,CAAA,KAAA,EAAO,KAAK,CAAA;AAAA;AAC3B,WACO,GAAK,EAAA;AACZ,IAAAC,iBAAA;AAAA,MACE,EAAE,MAAQ,EAAA,IAAA,CAAK,MAAO,EAAA;AAAA,MACtB,qCAAA;AAAA,MACA,UAAA;AAAA,MACA,MAAA;AAAA,MACA;AAAA,KACF;AAAA;AAEF,EAAA,OAAO,EAAE,UAAW,EAAA;AACtB;;;;;;"}
|
|
@@ -62,7 +62,7 @@ async function getCatalogInfoContentFromPR(logger, config, octo, owner, repo, pr
|
|
|
62
62
|
`Error fetching catalog-info content from PR ${prNumber}`,
|
|
63
63
|
error
|
|
64
64
|
);
|
|
65
|
-
return
|
|
65
|
+
return undefined;
|
|
66
66
|
}
|
|
67
67
|
}
|
|
68
68
|
async function closePRWithComment(octo, owner, repo, prNum, comment) {
|