@backstage/plugin-catalog-backend-module-github 0.2.6-next.2 → 0.2.7-next.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 +43 -0
- package/alpha/package.json +1 -1
- package/dist/alpha.cjs.js +5 -5
- package/dist/alpha.cjs.js.map +1 -1
- package/dist/alpha.d.ts +2 -2
- package/dist/index.cjs.js +9 -9
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/package.json +15 -15
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,48 @@
|
|
|
1
1
|
# @backstage/plugin-catalog-backend-module-github
|
|
2
2
|
|
|
3
|
+
## 0.2.7-next.0
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies
|
|
8
|
+
- @backstage/plugin-catalog-backend@1.8.1-next.0
|
|
9
|
+
- @backstage/backend-common@0.18.4-next.0
|
|
10
|
+
- @backstage/config@1.0.7
|
|
11
|
+
- @backstage/integration@1.4.3
|
|
12
|
+
- @backstage/backend-plugin-api@0.5.1-next.0
|
|
13
|
+
- @backstage/backend-tasks@0.5.1-next.0
|
|
14
|
+
- @backstage/catalog-client@1.4.0
|
|
15
|
+
- @backstage/catalog-model@1.2.1
|
|
16
|
+
- @backstage/errors@1.1.5
|
|
17
|
+
- @backstage/types@1.0.2
|
|
18
|
+
- @backstage/plugin-catalog-common@1.0.12
|
|
19
|
+
- @backstage/plugin-catalog-node@1.3.5-next.0
|
|
20
|
+
- @backstage/plugin-events-node@0.2.5-next.0
|
|
21
|
+
|
|
22
|
+
## 0.2.6
|
|
23
|
+
|
|
24
|
+
### Patch Changes
|
|
25
|
+
|
|
26
|
+
- 65454876fb2: Minor API report tweaks
|
|
27
|
+
- 90469c02c8c: Renamed `githubEntityProviderCatalogModule` to `catalogModuleGithubEntityProvider` to match the [recommended naming patterns](https://backstage.io/docs/backend-system/architecture/naming-patterns).
|
|
28
|
+
- e675f902980: Make sure to not use deprecated exports from `@backstage/plugin-catalog-backend`
|
|
29
|
+
- 928a12a9b3e: Internal refactor of `/alpha` exports.
|
|
30
|
+
- 52b0022dab7: Updated dependency `msw` to `^1.0.0`.
|
|
31
|
+
- Updated dependencies
|
|
32
|
+
- @backstage/plugin-catalog-backend@1.8.0
|
|
33
|
+
- @backstage/catalog-client@1.4.0
|
|
34
|
+
- @backstage/backend-tasks@0.5.0
|
|
35
|
+
- @backstage/backend-common@0.18.3
|
|
36
|
+
- @backstage/errors@1.1.5
|
|
37
|
+
- @backstage/plugin-catalog-node@1.3.4
|
|
38
|
+
- @backstage/backend-plugin-api@0.5.0
|
|
39
|
+
- @backstage/catalog-model@1.2.1
|
|
40
|
+
- @backstage/plugin-catalog-common@1.0.12
|
|
41
|
+
- @backstage/plugin-events-node@0.2.4
|
|
42
|
+
- @backstage/integration@1.4.3
|
|
43
|
+
- @backstage/config@1.0.7
|
|
44
|
+
- @backstage/types@1.0.2
|
|
45
|
+
|
|
3
46
|
## 0.2.6-next.2
|
|
4
47
|
|
|
5
48
|
### Patch Changes
|
package/alpha/package.json
CHANGED
package/dist/alpha.cjs.js
CHANGED
|
@@ -6,7 +6,7 @@ var backendPluginApi = require('@backstage/backend-plugin-api');
|
|
|
6
6
|
var backendCommon = require('@backstage/backend-common');
|
|
7
7
|
var alpha = require('@backstage/plugin-catalog-node/alpha');
|
|
8
8
|
var integration = require('@backstage/integration');
|
|
9
|
-
var
|
|
9
|
+
var pluginCatalogNode = require('@backstage/plugin-catalog-node');
|
|
10
10
|
var graphql = require('@octokit/graphql');
|
|
11
11
|
var uuid = require('uuid');
|
|
12
12
|
var backendTasks = require('@backstage/backend-tasks');
|
|
@@ -309,7 +309,7 @@ class GithubEntityProvider {
|
|
|
309
309
|
const entities = matchingTargets.map((repository) => this.createLocationUrl(repository)).map(GithubEntityProvider.toLocationSpec).map((location) => {
|
|
310
310
|
return {
|
|
311
311
|
locationKey: this.getProviderName(),
|
|
312
|
-
entity:
|
|
312
|
+
entity: pluginCatalogNode.locationSpecToLocationEntity({ location })
|
|
313
313
|
};
|
|
314
314
|
});
|
|
315
315
|
await this.connection.applyMutation({
|
|
@@ -478,7 +478,7 @@ class GithubEntityProvider {
|
|
|
478
478
|
toDeferredEntities(targets) {
|
|
479
479
|
return targets.map((target) => {
|
|
480
480
|
const location = GithubEntityProvider.toLocationSpec(target);
|
|
481
|
-
return
|
|
481
|
+
return pluginCatalogNode.locationSpecToLocationEntity({ location });
|
|
482
482
|
}).map((entity) => {
|
|
483
483
|
return {
|
|
484
484
|
locationKey: this.getProviderName(),
|
|
@@ -488,7 +488,7 @@ class GithubEntityProvider {
|
|
|
488
488
|
}
|
|
489
489
|
}
|
|
490
490
|
|
|
491
|
-
const
|
|
491
|
+
const catalogModuleGithubEntityProvider = backendPluginApi.createBackendModule({
|
|
492
492
|
pluginId: "catalog",
|
|
493
493
|
moduleId: "githubEntityProvider",
|
|
494
494
|
register(env) {
|
|
@@ -511,5 +511,5 @@ const githubEntityProviderCatalogModule = backendPluginApi.createBackendModule({
|
|
|
511
511
|
}
|
|
512
512
|
});
|
|
513
513
|
|
|
514
|
-
exports.
|
|
514
|
+
exports.catalogModuleGithubEntityProvider = catalogModuleGithubEntityProvider;
|
|
515
515
|
//# sourceMappingURL=alpha.cjs.js.map
|
package/dist/alpha.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"alpha.cjs.js","sources":["../src/providers/GithubEntityProviderConfig.ts","../src/lib/util.ts","../src/lib/github.ts","../src/providers/GithubEntityProvider.ts","../src/service/GithubEntityProviderCatalogModule.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n readTaskScheduleDefinitionFromConfig,\n TaskScheduleDefinition,\n} from '@backstage/backend-tasks';\nimport { Config } from '@backstage/config';\n\nconst DEFAULT_CATALOG_PATH = '/catalog-info.yaml';\nconst DEFAULT_PROVIDER_ID = 'default';\n\nexport type GithubEntityProviderConfig = {\n id: string;\n catalogPath: string;\n organization: string;\n host: string;\n filters?: {\n repository?: RegExp;\n branch?: string;\n topic?: GithubTopicFilters;\n allowForks?: boolean;\n };\n validateLocationsExist: boolean;\n schedule?: TaskScheduleDefinition;\n};\n\nexport type GithubTopicFilters = {\n exclude?: string[];\n include?: string[];\n};\n\nexport function readProviderConfigs(\n config: Config,\n): GithubEntityProviderConfig[] {\n const providersConfig = config.getOptionalConfig('catalog.providers.github');\n if (!providersConfig) {\n return [];\n }\n\n if (providersConfig.has('organization')) {\n // simple/single config variant\n return [readProviderConfig(DEFAULT_PROVIDER_ID, providersConfig)];\n }\n\n return providersConfig.keys().map(id => {\n const providerConfig = providersConfig.getConfig(id);\n\n return readProviderConfig(id, providerConfig);\n });\n}\n\nfunction readProviderConfig(\n id: string,\n config: Config,\n): GithubEntityProviderConfig {\n const organization = config.getString('organization');\n const catalogPath =\n config.getOptionalString('catalogPath') ?? DEFAULT_CATALOG_PATH;\n const host = config.getOptionalString('host') ?? 'github.com';\n const repositoryPattern = config.getOptionalString('filters.repository');\n const branchPattern = config.getOptionalString('filters.branch');\n const allowForks = config.getOptionalBoolean('filters.allowForks') ?? true;\n const topicFilterInclude = config?.getOptionalStringArray(\n 'filters.topic.include',\n );\n const topicFilterExclude = config?.getOptionalStringArray(\n 'filters.topic.exclude',\n );\n const validateLocationsExist =\n config?.getOptionalBoolean('validateLocationsExist') ?? false;\n\n const catalogPathContainsWildcard = catalogPath.includes('*');\n\n if (validateLocationsExist && catalogPathContainsWildcard) {\n throw Error(\n `Error while processing GitHub provider config. The catalog path ${catalogPath} contains a wildcard, which is incompatible with validation of locations existing before emitting them. Ensure that validateLocationsExist is set to false.`,\n );\n }\n\n const schedule = config.has('schedule')\n ? readTaskScheduleDefinitionFromConfig(config.getConfig('schedule'))\n : undefined;\n\n return {\n id,\n catalogPath,\n organization,\n host,\n filters: {\n repository: repositoryPattern\n ? compileRegExp(repositoryPattern)\n : undefined,\n branch: branchPattern || undefined,\n allowForks: allowForks,\n topic: {\n include: topicFilterInclude,\n exclude: topicFilterExclude,\n },\n },\n schedule,\n validateLocationsExist,\n };\n}\n\n/**\n * Compiles a RegExp while enforcing the pattern to contain\n * the start-of-line and end-of-line anchors.\n *\n * @param pattern\n */\nfunction compileRegExp(pattern: string): RegExp {\n let fullLinePattern = pattern;\n if (!fullLinePattern.startsWith('^')) {\n fullLinePattern = `^${fullLinePattern}`;\n }\n if (!fullLinePattern.endsWith('$')) {\n fullLinePattern = `${fullLinePattern}$`;\n }\n\n return new RegExp(fullLinePattern);\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GithubTopicFilters } from '../providers/GithubEntityProviderConfig';\n\nexport function parseGithubOrgUrl(urlString: string): { org: string } {\n const path = new URL(urlString).pathname.slice(1).split('/');\n\n // /backstage\n if (path.length === 1 && path[0].length) {\n return { org: decodeURIComponent(path[0]) };\n }\n\n throw new Error(`Expected a URL pointing to /<org>`);\n}\n\nexport function satisfiesTopicFilter(\n topics: string[],\n topicFilter: GithubTopicFilters | undefined,\n): Boolean {\n // We don't want to do anything if a filter is not configured (or configured but empty)\n if (!topicFilter) return true;\n if (!topicFilter.include && !topicFilter.exclude) return true;\n if (!topicFilter.include?.length && !topicFilter.exclude?.length) return true;\n // If topic.include is in use, a topic MUST be set that matches the inclusion\n // filter in order for a repository to be ingested\n if (topicFilter.include?.length && !topicFilter.exclude) {\n for (const topic of topics) {\n if (topicFilter.include.includes(topic)) return true;\n }\n return false;\n }\n // If topic.exclude is in use, all topics are included by default\n // with anything matching the filter being discarded. It is technically\n // possible for the filter to be explicitly empty meaning all repositories\n // are ingested although doing so would be pointless.\n if (!topicFilter.include && topicFilter.exclude?.length) {\n if (!topics.length) return true;\n for (const topic of topics) {\n if (topicFilter.exclude.includes(topic)) return false;\n }\n return true;\n }\n // Now the tricky part is where we have both include and exclude configured.\n // In this case, exclude wins out so we take everything matching the initial\n // inclusion filter and from that group, we further discard anything matching\n // the exclusion filter. If an item were to have a topic set in both filters,\n // we expect it to be discarded in the end. The use case here is that is that\n // you may want to retrieve all repos with the topic of team-a while excluding\n // matching repos that are marked as experiments.\n if (topicFilter.include && topicFilter.exclude) {\n const matchesInclude = satisfiesTopicFilter(topics, {\n include: topicFilter.include,\n });\n const matchesExclude = !satisfiesTopicFilter(topics, {\n exclude: topicFilter.exclude,\n });\n if (matchesExclude) return false;\n return matchesInclude;\n }\n\n // If the topic filter is somehow ever in a state that is not covered here, we\n // will fail \"open\" so that Backstage is still usable as if the filter was\n // not configured at all.\n return true;\n}\n\nexport function satisfiesForkFilter(\n allowForks: boolean | true,\n isFork: boolean | false,\n): Boolean {\n // we don't want to include forks if forks are not allowed\n if (!allowForks && isFork) return false;\n\n // if forks are allowed, allow all repos through\n return true;\n}\n\n// Given the github organisation team slug, returns a tuple containing [organisation, team]\nexport function splitTeamSlug(slug: string): [string, string] {\n const parts = slug.split('/');\n if (parts.length !== 2) {\n throw new Error(\n `Github team slug '${slug}' was not in the expected format <organisation>/<team>`,\n );\n }\n return [parts[0], parts[1]];\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Entity, GroupEntity, UserEntity } from '@backstage/catalog-model';\nimport { GithubCredentialType } from '@backstage/integration';\nimport { graphql } from '@octokit/graphql';\nimport {\n defaultOrganizationTeamTransformer,\n defaultUserTransformer,\n TeamTransformer,\n TransformerContext,\n UserTransformer,\n} from './defaultTransformers';\nimport { withLocations } from '../providers/GithubOrgEntityProvider';\n\nimport { DeferredEntity } from '@backstage/plugin-catalog-backend';\n\n// Graphql types\n\nexport type QueryResponse = {\n organization?: OrganizationResponse;\n repositoryOwner?: RepositoryOwnerResponse;\n};\n\ntype RepositoryOwnerResponse = {\n repositories?: Connection<RepositoryResponse>;\n};\n\nexport type OrganizationResponse = {\n membersWithRole?: Connection<GithubUser>;\n team?: GithubTeamResponse;\n teams?: Connection<GithubTeamResponse>;\n repositories?: Connection<RepositoryResponse>;\n};\n\nexport type PageInfo = {\n hasNextPage: boolean;\n endCursor?: string;\n};\n\n/**\n * Github User\n *\n * @public\n */\nexport type GithubUser = {\n login: string;\n bio?: string;\n avatarUrl?: string;\n email?: string;\n name?: string;\n organizationVerifiedDomainEmails?: string[];\n};\n\n/**\n * Github Team\n *\n * @public\n */\nexport type GithubTeam = {\n slug: string;\n combinedSlug: string;\n name?: string;\n description?: string;\n avatarUrl?: string;\n editTeamUrl?: string;\n parentTeam?: GithubTeam;\n members: GithubUser[];\n};\n\nexport type GithubTeamResponse = Omit<GithubTeam, 'members'> & {\n members: Connection<GithubUser>;\n};\n\nexport type RepositoryResponse = {\n name: string;\n url: string;\n isArchived: boolean;\n isFork: boolean;\n repositoryTopics: RepositoryTopics;\n defaultBranchRef: {\n name: string;\n } | null;\n catalogInfoFile: {\n __typename: string;\n id: string;\n text: string;\n } | null;\n};\n\ntype RepositoryTopics = {\n nodes: TopicNodes[];\n};\n\ntype TopicNodes = {\n topic: {\n name: string;\n };\n};\n\nexport type Connection<T> = {\n pageInfo: PageInfo;\n nodes: T[];\n};\n\n/**\n * Gets all the users out of a Github organization.\n *\n * Note that the users will not have their memberships filled in.\n *\n * @param client - An octokit graphql client\n * @param org - The slug of the org to read\n */\nexport async function getOrganizationUsers(\n client: typeof graphql,\n org: string,\n tokenType: GithubCredentialType,\n userTransformer: UserTransformer = defaultUserTransformer,\n): Promise<{ users: UserEntity[] }> {\n const query = `\n query users($org: String!, $email: Boolean!, $cursor: String) {\n organization(login: $org) {\n membersWithRole(first: 100, after: $cursor) {\n pageInfo { hasNextPage, endCursor }\n nodes {\n avatarUrl,\n bio,\n email @include(if: $email),\n login,\n name,\n organizationVerifiedDomainEmails(login: $org)\n }\n }\n }\n }`;\n\n // There is no user -> teams edge, so we leave the memberships empty for\n // now and let the team iteration handle it instead\n\n const users = await queryWithPaging(\n client,\n query,\n org,\n r => r.organization?.membersWithRole,\n userTransformer,\n {\n org,\n email: tokenType === 'token',\n },\n );\n\n return { users };\n}\n\n/**\n * Gets all the teams out of a Github organization.\n *\n * Note that the teams will not have any relations apart from parent filled in.\n *\n * @param client - An octokit graphql client\n * @param org - The slug of the org to read\n */\nexport async function getOrganizationTeams(\n client: typeof graphql,\n org: string,\n teamTransformer: TeamTransformer = defaultOrganizationTeamTransformer,\n): Promise<{\n groups: GroupEntity[];\n}> {\n const query = `\n query teams($org: String!, $cursor: String) {\n organization(login: $org) {\n teams(first: 100, after: $cursor) {\n pageInfo { hasNextPage, endCursor }\n nodes {\n slug\n combinedSlug\n name\n description\n avatarUrl\n editTeamUrl\n parentTeam { slug }\n members(first: 100, membership: IMMEDIATE) {\n pageInfo { hasNextPage }\n nodes { \n avatarUrl,\n bio,\n email,\n login,\n name,\n organizationVerifiedDomainEmails(login: $org)\n }\n }\n }\n }\n }\n }`;\n\n const materialisedTeams = async (\n item: GithubTeamResponse,\n ctx: TransformerContext,\n ): Promise<GroupEntity | undefined> => {\n const memberNames: GithubUser[] = [];\n\n if (!item.members.pageInfo.hasNextPage) {\n // We got all the members in one go, run the fast path\n for (const user of item.members.nodes) {\n memberNames.push(user);\n }\n } else {\n // There were more than a hundred immediate members - run the slow\n // path of fetching them explicitly\n const { members } = await getTeamMembers(ctx.client, ctx.org, item.slug);\n for (const userLogin of members) {\n memberNames.push(userLogin);\n }\n }\n\n const team: GithubTeam = {\n ...item,\n members: memberNames,\n };\n\n return await teamTransformer(team, ctx);\n };\n\n const groups = await queryWithPaging(\n client,\n query,\n org,\n r => r.organization?.teams,\n materialisedTeams,\n { org },\n );\n\n return { groups };\n}\n\nexport async function getOrganizationTeamsFromUsers(\n client: typeof graphql,\n org: string,\n userLogins: string[],\n teamTransformer: TeamTransformer = defaultOrganizationTeamTransformer,\n): Promise<{\n groups: GroupEntity[];\n}> {\n const query = `\n query teams($org: String!, $cursor: String, $userLogins: [String!] = \"\") {\n organization(login: $org) {\n teams(first: 100, after: $cursor, userLogins: $userLogins) {\n pageInfo {\n hasNextPage\n endCursor\n }\n nodes {\n slug\n combinedSlug\n name\n description\n avatarUrl\n editTeamUrl\n parentTeam {\n slug\n }\n members(first: 100, membership: IMMEDIATE) {\n pageInfo {\n hasNextPage\n }\n nodes {\n avatarUrl,\n bio,\n email,\n login,\n name,\n organizationVerifiedDomainEmails(login: $org)\n }\n }\n }\n }\n }\n}`;\n\n const materialisedTeams = async (\n item: GithubTeamResponse,\n ctx: TransformerContext,\n ): Promise<GroupEntity | undefined> => {\n const memberNames: GithubUser[] = [];\n\n if (!item.members.pageInfo.hasNextPage) {\n // We got all the members in one go, run the fast path\n for (const user of item.members.nodes) {\n memberNames.push(user);\n }\n } else {\n // There were more than a hundred immediate members - run the slow\n // path of fetching them explicitly\n const { members } = await getTeamMembers(ctx.client, ctx.org, item.slug);\n for (const userLogin of members) {\n memberNames.push(userLogin);\n }\n }\n\n const team: GithubTeam = {\n ...item,\n members: memberNames,\n };\n\n return await teamTransformer(team, ctx);\n };\n\n const groups = await queryWithPaging(\n client,\n query,\n org,\n r => r.organization?.teams,\n materialisedTeams,\n { org, userLogins },\n );\n\n return { groups };\n}\n\nexport async function getOrganizationTeam(\n client: typeof graphql,\n org: string,\n teamSlug: string,\n teamTransformer: TeamTransformer = defaultOrganizationTeamTransformer,\n): Promise<{\n group: GroupEntity;\n}> {\n const query = `\n query teams($org: String!, $teamSlug: String!) {\n organization(login: $org) {\n team(slug:$teamSlug) {\n slug\n combinedSlug\n name\n description\n avatarUrl\n editTeamUrl\n parentTeam { slug }\n members(first: 100, membership: IMMEDIATE) {\n pageInfo { hasNextPage }\n nodes { login }\n }\n }\n }\n }`;\n\n const materialisedTeam = async (\n item: GithubTeamResponse,\n ctx: TransformerContext,\n ): Promise<GroupEntity | undefined> => {\n const memberNames: GithubUser[] = [];\n\n if (!item.members.pageInfo.hasNextPage) {\n // We got all the members in one go, run the fast path\n for (const user of item.members.nodes) {\n memberNames.push(user);\n }\n } else {\n // There were more than a hundred immediate members - run the slow\n // path of fetching them explicitly\n const { members } = await getTeamMembers(ctx.client, ctx.org, item.slug);\n for (const userLogin of members) {\n memberNames.push(userLogin);\n }\n }\n\n const team: GithubTeam = {\n ...item,\n members: memberNames,\n };\n\n return await teamTransformer(team, ctx);\n };\n\n const response: QueryResponse = await client(query, {\n org,\n teamSlug,\n });\n\n if (!response.organization?.team)\n throw new Error(`Found no match for group ${teamSlug}`);\n\n const group = await materialisedTeam(response.organization?.team, {\n query,\n client,\n org,\n });\n\n if (!group) throw new Error(`Can't transform for group ${teamSlug}`);\n\n return { group };\n}\n\nexport async function getOrganizationRepositories(\n client: typeof graphql,\n org: string,\n catalogPath: string,\n): Promise<{ repositories: RepositoryResponse[] }> {\n let relativeCatalogPathRef: string;\n // We must strip the leading slash or the query for objects does not work\n if (catalogPath.startsWith('/')) {\n relativeCatalogPathRef = catalogPath.substring(1);\n } else {\n relativeCatalogPathRef = catalogPath;\n }\n const catalogPathRef = `HEAD:${relativeCatalogPathRef}`;\n const query = `\n query repositories($org: String!, $catalogPathRef: String!, $cursor: String) {\n repositoryOwner(login: $org) {\n login\n repositories(first: 100, after: $cursor) {\n nodes {\n name\n catalogInfoFile: object(expression: $catalogPathRef) {\n __typename\n ... on Blob {\n id\n text\n }\n }\n url\n isArchived\n isFork\n repositoryTopics(first: 100) {\n nodes {\n ... on RepositoryTopic {\n topic {\n name\n }\n }\n }\n }\n defaultBranchRef {\n name\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n }`;\n\n const repositories = await queryWithPaging(\n client,\n query,\n org,\n r => r.repositoryOwner?.repositories,\n async x => x,\n { org, catalogPathRef },\n );\n\n return { repositories };\n}\n\n/**\n * Gets all the users out of a Github organization.\n *\n * Note that the users will not have their memberships filled in.\n *\n * @param client - An octokit graphql client\n * @param org - The slug of the org to read\n * @param teamSlug - The slug of the team to read\n */\nexport async function getTeamMembers(\n client: typeof graphql,\n org: string,\n teamSlug: string,\n): Promise<{ members: GithubUser[] }> {\n const query = `\n query members($org: String!, $teamSlug: String!, $cursor: String) {\n organization(login: $org) {\n team(slug: $teamSlug) {\n members(first: 100, after: $cursor, membership: IMMEDIATE) {\n pageInfo { hasNextPage, endCursor }\n nodes { login }\n }\n }\n }\n }`;\n\n const members = await queryWithPaging(\n client,\n query,\n org,\n r => r.organization?.team?.members,\n async user => user,\n { org, teamSlug },\n );\n\n return { members };\n}\n\n//\n// Helpers\n//\n\n/**\n * Assists in repeatedly executing a query with a paged response.\n *\n * Requires that the query accepts a $cursor variable.\n *\n * @param client - The octokit client\n * @param query - The query to execute\n * @param org - The slug of the org to read\n * @param connection - A function that, given the response, picks out the actual\n * Connection object that's being iterated\n * @param transformer - A function that, given one of the nodes in the Connection,\n * returns the model mapped form of it\n * @param variables - The variable values that the query needs, minus the cursor\n */\nexport async function queryWithPaging<\n GraphqlType,\n OutputType,\n Variables extends {},\n Response = QueryResponse,\n>(\n client: typeof graphql,\n query: string,\n org: string,\n connection: (response: Response) => Connection<GraphqlType> | undefined,\n transformer: (\n item: GraphqlType,\n ctx: TransformerContext,\n ) => Promise<OutputType | undefined>,\n variables: Variables,\n): Promise<OutputType[]> {\n const result: OutputType[] = [];\n\n let cursor: string | undefined = undefined;\n for (let j = 0; j < 1000 /* just for sanity */; ++j) {\n const response: Response = await client(query, {\n ...variables,\n cursor,\n });\n\n const conn = connection(response);\n if (!conn) {\n throw new Error(`Found no match for ${JSON.stringify(variables)}`);\n }\n\n for (const node of conn.nodes) {\n const transformedNode = await transformer(node, {\n client,\n query,\n org,\n });\n\n if (transformedNode) {\n result.push(transformedNode);\n }\n }\n\n if (!conn.pageInfo.hasNextPage) {\n break;\n } else {\n cursor = conn.pageInfo.endCursor;\n }\n }\n\n return result;\n}\n\nexport type DeferredEntitiesBuilder = (\n org: string,\n entities: Entity[],\n) => { added: DeferredEntity[]; removed: DeferredEntity[] };\n\nexport const createAddEntitiesOperation =\n (id: string, host: string) => (org: string, entities: Entity[]) => ({\n removed: [],\n added: entities.map(entity => ({\n locationKey: `github-org-provider:${id}`,\n entity: withLocations(`https://${host}`, org, entity),\n })),\n });\n\nexport const createRemoveEntitiesOperation =\n (id: string, host: string) => (org: string, entities: Entity[]) => ({\n added: [],\n removed: entities.map(entity => ({\n locationKey: `github-org-provider:${id}`,\n entity: withLocations(`https://${host}`, org, entity),\n })),\n });\n\nexport const createReplaceEntitiesOperation =\n (id: string, host: string) => (org: string, entities: Entity[]) => {\n const entitiesToReplace = entities.map(entity => ({\n locationKey: `github-org-provider:${id}`,\n entity: withLocations(`https://${host}`, org, entity),\n }));\n\n return {\n removed: entitiesToReplace,\n added: entitiesToReplace,\n };\n };\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PluginTaskScheduler, TaskRunner } from '@backstage/backend-tasks';\nimport { Config } from '@backstage/config';\nimport {\n GithubCredentialsProvider,\n ScmIntegrations,\n GithubIntegrationConfig,\n GithubIntegration,\n SingleInstanceGithubCredentialsProvider,\n} from '@backstage/integration';\nimport {\n DeferredEntity,\n EntityProvider,\n EntityProviderConnection,\n locationSpecToLocationEntity,\n} from '@backstage/plugin-catalog-backend';\n\nimport { LocationSpec } from '@backstage/plugin-catalog-common';\n\nimport { graphql } from '@octokit/graphql';\nimport * as uuid from 'uuid';\nimport { Logger } from 'winston';\nimport {\n readProviderConfigs,\n GithubEntityProviderConfig,\n} from './GithubEntityProviderConfig';\nimport { getOrganizationRepositories } from '../lib/github';\nimport { satisfiesTopicFilter, satisfiesForkFilter } from '../lib/util';\n\nimport { EventParams, EventSubscriber } from '@backstage/plugin-events-node';\nimport { PushEvent, Commit } from '@octokit/webhooks-types';\nimport { Minimatch } from 'minimatch';\n\nconst TOPIC_REPO_PUSH = 'github.push';\n\ntype Repository = {\n name: string;\n url: string;\n isArchived: boolean;\n isFork: boolean;\n repositoryTopics: string[];\n defaultBranchRef?: string;\n isCatalogInfoFilePresent: boolean;\n};\n\n/**\n * Discovers catalog files located in [GitHub](https://github.com).\n * The provider will search your GitHub account and register catalog files matching the configured path\n * as Location entity and via following processing steps add all contained catalog entities.\n * This can be useful as an alternative to static locations or manually adding things to the catalog.\n *\n * @public\n */\nexport class GithubEntityProvider implements EntityProvider, EventSubscriber {\n private readonly config: GithubEntityProviderConfig;\n private readonly logger: Logger;\n private readonly integration: GithubIntegrationConfig;\n private readonly scheduleFn: () => Promise<void>;\n private connection?: EntityProviderConnection;\n private readonly githubCredentialsProvider: GithubCredentialsProvider;\n\n static fromConfig(\n config: Config,\n options: {\n logger: Logger;\n schedule?: TaskRunner;\n scheduler?: PluginTaskScheduler;\n },\n ): GithubEntityProvider[] {\n if (!options.schedule && !options.scheduler) {\n throw new Error('Either schedule or scheduler must be provided.');\n }\n\n const integrations = ScmIntegrations.fromConfig(config);\n\n return readProviderConfigs(config).map(providerConfig => {\n const integrationHost = providerConfig.host;\n const integration = integrations.github.byHost(integrationHost);\n\n if (!integration) {\n throw new Error(\n `There is no GitHub config that matches host ${integrationHost}. Please add a configuration entry for it under integrations.github`,\n );\n }\n\n if (!options.schedule && !providerConfig.schedule) {\n throw new Error(\n `No schedule provided neither via code nor config for github-provider:${providerConfig.id}.`,\n );\n }\n\n const taskRunner =\n options.schedule ??\n options.scheduler!.createScheduledTaskRunner(providerConfig.schedule!);\n\n return new GithubEntityProvider(\n providerConfig,\n integration,\n options.logger,\n taskRunner,\n );\n });\n }\n\n private constructor(\n config: GithubEntityProviderConfig,\n integration: GithubIntegration,\n logger: Logger,\n taskRunner: TaskRunner,\n ) {\n this.config = config;\n this.integration = integration.config;\n this.logger = logger.child({\n target: this.getProviderName(),\n });\n this.scheduleFn = this.createScheduleFn(taskRunner);\n this.githubCredentialsProvider =\n SingleInstanceGithubCredentialsProvider.create(integration.config);\n }\n\n /** {@inheritdoc @backstage/plugin-catalog-backend#EntityProvider.getProviderName} */\n getProviderName(): string {\n return `github-provider:${this.config.id}`;\n }\n\n /** {@inheritdoc @backstage/plugin-catalog-backend#EntityProvider.connect} */\n async connect(connection: EntityProviderConnection): Promise<void> {\n this.connection = connection;\n return await this.scheduleFn();\n }\n\n private createScheduleFn(taskRunner: TaskRunner): () => Promise<void> {\n return async () => {\n const taskId = `${this.getProviderName()}:refresh`;\n return taskRunner.run({\n id: taskId,\n fn: async () => {\n const logger = this.logger.child({\n class: GithubEntityProvider.prototype.constructor.name,\n taskId,\n taskInstanceId: uuid.v4(),\n });\n try {\n await this.refresh(logger);\n } catch (error) {\n logger.error(`${this.getProviderName()} refresh failed`, error);\n }\n },\n });\n };\n }\n\n async refresh(logger: Logger) {\n if (!this.connection) {\n throw new Error('Not initialized');\n }\n\n const targets = await this.findCatalogFiles();\n const matchingTargets = this.matchesFilters(targets);\n const entities = matchingTargets\n .map(repository => this.createLocationUrl(repository))\n .map(GithubEntityProvider.toLocationSpec)\n .map(location => {\n return {\n locationKey: this.getProviderName(),\n entity: locationSpecToLocationEntity({ location }),\n };\n });\n\n await this.connection.applyMutation({\n type: 'full',\n entities,\n });\n\n logger.info(\n `Read ${targets.length} GitHub repositories (${entities.length} matching the pattern)`,\n );\n }\n\n // go to the server and get all of the repositories\n private async findCatalogFiles(): Promise<Repository[]> {\n const organization = this.config.organization;\n const host = this.integration.host;\n const catalogPath = this.config.catalogPath;\n const orgUrl = `https://${host}/${organization}`;\n\n const { headers } = await this.githubCredentialsProvider.getCredentials({\n url: orgUrl,\n });\n\n const client = graphql.defaults({\n baseUrl: this.integration.apiBaseUrl,\n headers,\n });\n\n const { repositories: repositoriesFromGithub } =\n await getOrganizationRepositories(client, organization, catalogPath);\n const repositories = repositoriesFromGithub.map(r => {\n return {\n url: r.url,\n name: r.name,\n defaultBranchRef: r.defaultBranchRef?.name,\n repositoryTopics: r.repositoryTopics.nodes.map(t => t.topic.name),\n isArchived: r.isArchived,\n isFork: r.isFork,\n isCatalogInfoFilePresent:\n r.catalogInfoFile?.__typename === 'Blob' &&\n r.catalogInfoFile.text !== '',\n };\n });\n\n if (this.config.validateLocationsExist) {\n return repositories.filter(\n repository => repository.isCatalogInfoFilePresent,\n );\n }\n\n return repositories;\n }\n\n private matchesFilters(repositories: Repository[]) {\n const repositoryFilter = this.config.filters?.repository;\n const topicFilters = this.config.filters?.topic;\n const allowForks = this.config.filters?.allowForks ?? true;\n\n const matchingRepositories = repositories.filter(r => {\n const repoTopics: string[] = r.repositoryTopics;\n return (\n !r.isArchived &&\n (!repositoryFilter || repositoryFilter.test(r.name)) &&\n satisfiesTopicFilter(repoTopics, topicFilters) &&\n satisfiesForkFilter(allowForks, r.isFork) &&\n r.defaultBranchRef\n );\n });\n return matchingRepositories;\n }\n\n private createLocationUrl(repository: Repository): string {\n const branch =\n this.config.filters?.branch || repository.defaultBranchRef || '-';\n const catalogFile = this.config.catalogPath.startsWith('/')\n ? this.config.catalogPath.substring(1)\n : this.config.catalogPath;\n return `${repository.url}/blob/${branch}/${catalogFile}`;\n }\n\n private static toLocationSpec(target: string): LocationSpec {\n return {\n type: 'url',\n target: target,\n presence: 'optional',\n };\n }\n\n /** {@inheritdoc @backstage/plugin-events-node#EventSubscriber.onEvent} */\n async onEvent(params: EventParams): Promise<void> {\n this.logger.debug(`Received event from ${params.topic}`);\n if (params.topic !== TOPIC_REPO_PUSH) {\n return;\n }\n\n await this.onRepoPush(params.eventPayload as PushEvent);\n }\n\n /** {@inheritdoc @backstage/plugin-events-node#EventSubscriber.supportsEventTopics} */\n supportsEventTopics(): string[] {\n return [TOPIC_REPO_PUSH];\n }\n\n private async onRepoPush(event: PushEvent) {\n if (!this.connection) {\n throw new Error('Not initialized');\n }\n\n const repoName = event.repository.name;\n const repoUrl = event.repository.url;\n this.logger.debug(`handle github:push event for ${repoName} - ${repoUrl}`);\n\n const branch =\n this.config.filters?.branch || event.repository.default_branch;\n\n if (!event.ref.includes(branch)) {\n this.logger.debug(`skipping push event from ref ${event.ref}`);\n return;\n }\n\n const repository: Repository = {\n url: event.repository.url,\n name: event.repository.name,\n defaultBranchRef: event.repository.default_branch,\n repositoryTopics: event.repository.topics,\n isArchived: event.repository.archived,\n isFork: event.repository.fork,\n // we can consider this file present because\n // only the catalog file will be recovered from the commits\n isCatalogInfoFilePresent: true,\n };\n\n const matchingTargets = this.matchesFilters([repository]);\n if (matchingTargets.length === 0) {\n this.logger.debug(\n `skipping push event from repository ${repoName} because didn't match provider filters`,\n );\n return;\n }\n\n // the commit has information about the files (added,removed,modified)\n // so we will process the change based in this data\n // https://docs.github.com/en/developers/webhooks-and-events/webhooks/webhook-events-and-payloads#push\n const added = this.collectDeferredEntitiesFromCommit(\n event.repository.url,\n branch,\n event.commits,\n (commit: Commit) => [...commit.added],\n );\n const removed = this.collectDeferredEntitiesFromCommit(\n event.repository.url,\n branch,\n event.commits,\n (commit: Commit) => [...commit.removed],\n );\n const modified = this.collectFilesFromCommit(\n event.commits,\n (commit: Commit) => [...commit.modified],\n );\n\n if (modified.length > 0) {\n await this.connection.refresh({\n keys: [\n ...modified.map(\n filePath =>\n `url:${event.repository.url}/tree/${branch}/${filePath}`,\n ),\n ...modified.map(\n filePath =>\n `url:${event.repository.url}/blob/${branch}/${filePath}`,\n ),\n ],\n });\n }\n\n if (added.length > 0 || removed.length > 0) {\n await this.connection.applyMutation({\n type: 'delta',\n added: added,\n removed: removed,\n });\n }\n\n this.logger.info(\n `Processed Github push event: added ${added.length} - removed ${removed.length} - modified ${modified.length}`,\n );\n }\n\n private collectDeferredEntitiesFromCommit(\n repositoryUrl: string,\n branch: string,\n commits: Commit[],\n transformOperation: (commit: Commit) => string[],\n ): DeferredEntity[] {\n const catalogFiles = this.collectFilesFromCommit(\n commits,\n transformOperation,\n );\n return this.toDeferredEntities(\n catalogFiles.map(\n filePath => `${repositoryUrl}/blob/${branch}/${filePath}`,\n ),\n );\n }\n\n private collectFilesFromCommit(\n commits: Commit[],\n transformOperation: (commit: Commit) => string[],\n ): string[] {\n const catalogFile = this.config.catalogPath.startsWith('/')\n ? this.config.catalogPath.substring(1)\n : this.config.catalogPath;\n\n const matcher = new Minimatch(catalogFile);\n return commits\n .map(transformOperation)\n .flat()\n .filter(file => matcher.match(file));\n }\n\n private toDeferredEntities(targets: string[]): DeferredEntity[] {\n return targets\n .map(target => {\n const location = GithubEntityProvider.toLocationSpec(target);\n\n return locationSpecToLocationEntity({ location });\n })\n .map(entity => {\n return {\n locationKey: this.getProviderName(),\n entity: entity,\n };\n });\n }\n}\n\n/*\n * Helpers\n */\n\nexport function parseUrl(urlString: string): {\n org: string;\n repoSearchPath: RegExp;\n catalogPath: string;\n branch: string;\n host: string;\n} {\n const url = new URL(urlString);\n const path = url.pathname.slice(1).split('/');\n\n // /backstage/techdocs-*/blob/master/catalog-info.yaml\n // can also be\n // /backstage\n if (path.length > 2 && path[0].length && path[1].length) {\n return {\n org: decodeURIComponent(path[0]),\n repoSearchPath: escapeRegExp(decodeURIComponent(path[1])),\n catalogPath: `/${decodeURIComponent(path.slice(4).join('/'))}`,\n branch: decodeURIComponent(path[3]),\n host: url.host,\n };\n } else if (path.length === 1 && path[0].length) {\n return {\n org: decodeURIComponent(path[0]),\n repoSearchPath: escapeRegExp('*'),\n catalogPath: '/catalog-info.yaml',\n branch: '-',\n host: url.host,\n };\n }\n\n throw new Error(`Failed to parse ${urlString}`);\n}\n\nexport function escapeRegExp(str: string): RegExp {\n return new RegExp(`^${str.replace(/\\*/g, '.*')}$`);\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createBackendModule,\n coreServices,\n} from '@backstage/backend-plugin-api';\nimport { loggerToWinstonLogger } from '@backstage/backend-common';\nimport { catalogProcessingExtensionPoint } from '@backstage/plugin-catalog-node/alpha';\nimport { GithubEntityProvider } from '../providers/GithubEntityProvider';\n\n/**\n * Registers the `GithubEntityProvider` with the catalog processing extension point.\n *\n * @alpha\n */\nexport const githubEntityProviderCatalogModule = createBackendModule({\n pluginId: 'catalog',\n moduleId: 'githubEntityProvider',\n register(env) {\n env.registerInit({\n deps: {\n catalog: catalogProcessingExtensionPoint,\n config: coreServices.config,\n logger: coreServices.logger,\n scheduler: coreServices.scheduler,\n },\n async init({ catalog, config, logger, scheduler }) {\n catalog.addEntityProvider(\n GithubEntityProvider.fromConfig(config, {\n logger: loggerToWinstonLogger(logger),\n scheduler,\n }),\n );\n },\n });\n },\n});\n"],"names":["readTaskScheduleDefinitionFromConfig","ScmIntegrations","integration","SingleInstanceGithubCredentialsProvider","uuid","locationSpecToLocationEntity","graphql","Minimatch","createBackendModule","catalogProcessingExtensionPoint","coreServices","loggerToWinstonLogger"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,MAAM,oBAAuB,GAAA,oBAAA,CAAA;AAC7B,MAAM,mBAAsB,GAAA,SAAA,CAAA;AAsBrB,SAAS,oBACd,MAC8B,EAAA;AAC9B,EAAM,MAAA,eAAA,GAAkB,MAAO,CAAA,iBAAA,CAAkB,0BAA0B,CAAA,CAAA;AAC3E,EAAA,IAAI,CAAC,eAAiB,EAAA;AACpB,IAAA,OAAO,EAAC,CAAA;AAAA,GACV;AAEA,EAAI,IAAA,eAAA,CAAgB,GAAI,CAAA,cAAc,CAAG,EAAA;AAEvC,IAAA,OAAO,CAAC,kBAAA,CAAmB,mBAAqB,EAAA,eAAe,CAAC,CAAA,CAAA;AAAA,GAClE;AAEA,EAAA,OAAO,eAAgB,CAAA,IAAA,EAAO,CAAA,GAAA,CAAI,CAAM,EAAA,KAAA;AACtC,IAAM,MAAA,cAAA,GAAiB,eAAgB,CAAA,SAAA,CAAU,EAAE,CAAA,CAAA;AAEnD,IAAO,OAAA,kBAAA,CAAmB,IAAI,cAAc,CAAA,CAAA;AAAA,GAC7C,CAAA,CAAA;AACH,CAAA;AAEA,SAAS,kBAAA,CACP,IACA,MAC4B,EAAA;AApE9B,EAAA,IAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,CAAA;AAqEE,EAAM,MAAA,YAAA,GAAe,MAAO,CAAA,SAAA,CAAU,cAAc,CAAA,CAAA;AACpD,EAAA,MAAM,WACJ,GAAA,CAAA,EAAA,GAAA,MAAA,CAAO,iBAAkB,CAAA,aAAa,MAAtC,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AAU,MAAA,KAAA;AACb,MAAM,MAAA,QAAA,GAAW,oBAAqB,CAAA,cAAA,CAAe,MAAM,CAAA,CAAA;AAE3D,MAAO,OAAAF,iDAAA,CAA6B,EAAE,QAAA,EAAU,CAAA,CAAA;AAAA,KACjD,CACA,CAAA,GAAA,CAAI,CAAU,MAAA,KAAA;AACb,MAAO,OAAA;AAAA,QACL,WAAA,EAAa,KAAK,eAAgB,EAAA;AAAA,QAClC,MAAA;AAAA,OACF,CAAA;AAAA,KACD,CAAA,CAAA;AAAA,GACL;AACF;;ACnYO,MAAM,oCAAoCG,oCAAoB,CAAA;AAAA,EACnE,QAAU,EAAA,SAAA;AAAA,EACV,QAAU,EAAA,sBAAA;AAAA,EACV,SAAS,GAAK,EAAA;AACZ,IAAA,GAAA,CAAI,YAAa,CAAA;AAAA,MACf,IAAM,EAAA;AAAA,QACJ,OAAS,EAAAC,qCAAA;AAAA,QACT,QAAQC,6BAAa,CAAA,MAAA;AAAA,QACrB,QAAQA,6BAAa,CAAA,MAAA;AAAA,QACrB,WAAWA,6BAAa,CAAA,SAAA;AAAA,OAC1B;AAAA,MACA,MAAM,IAAK,CAAA,EAAE,SAAS,MAAQ,EAAA,MAAA,EAAQ,WAAa,EAAA;AACjD,QAAQ,OAAA,CAAA,iBAAA;AAAA,UACN,oBAAA,CAAqB,WAAW,MAAQ,EAAA;AAAA,YACtC,MAAA,EAAQC,oCAAsB,MAAM,CAAA;AAAA,YACpC,SAAA;AAAA,WACD,CAAA;AAAA,SACH,CAAA;AAAA,OACF;AAAA,KACD,CAAA,CAAA;AAAA,GACH;AACF,CAAC;;;;"}
|
|
1
|
+
{"version":3,"file":"alpha.cjs.js","sources":["../src/providers/GithubEntityProviderConfig.ts","../src/lib/util.ts","../src/lib/github.ts","../src/providers/GithubEntityProvider.ts","../src/module/catalogModuleGithubEntityProvider.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n readTaskScheduleDefinitionFromConfig,\n TaskScheduleDefinition,\n} from '@backstage/backend-tasks';\nimport { Config } from '@backstage/config';\n\nconst DEFAULT_CATALOG_PATH = '/catalog-info.yaml';\nconst DEFAULT_PROVIDER_ID = 'default';\n\nexport type GithubEntityProviderConfig = {\n id: string;\n catalogPath: string;\n organization: string;\n host: string;\n filters?: {\n repository?: RegExp;\n branch?: string;\n topic?: GithubTopicFilters;\n allowForks?: boolean;\n };\n validateLocationsExist: boolean;\n schedule?: TaskScheduleDefinition;\n};\n\nexport type GithubTopicFilters = {\n exclude?: string[];\n include?: string[];\n};\n\nexport function readProviderConfigs(\n config: Config,\n): GithubEntityProviderConfig[] {\n const providersConfig = config.getOptionalConfig('catalog.providers.github');\n if (!providersConfig) {\n return [];\n }\n\n if (providersConfig.has('organization')) {\n // simple/single config variant\n return [readProviderConfig(DEFAULT_PROVIDER_ID, providersConfig)];\n }\n\n return providersConfig.keys().map(id => {\n const providerConfig = providersConfig.getConfig(id);\n\n return readProviderConfig(id, providerConfig);\n });\n}\n\nfunction readProviderConfig(\n id: string,\n config: Config,\n): GithubEntityProviderConfig {\n const organization = config.getString('organization');\n const catalogPath =\n config.getOptionalString('catalogPath') ?? DEFAULT_CATALOG_PATH;\n const host = config.getOptionalString('host') ?? 'github.com';\n const repositoryPattern = config.getOptionalString('filters.repository');\n const branchPattern = config.getOptionalString('filters.branch');\n const allowForks = config.getOptionalBoolean('filters.allowForks') ?? true;\n const topicFilterInclude = config?.getOptionalStringArray(\n 'filters.topic.include',\n );\n const topicFilterExclude = config?.getOptionalStringArray(\n 'filters.topic.exclude',\n );\n const validateLocationsExist =\n config?.getOptionalBoolean('validateLocationsExist') ?? false;\n\n const catalogPathContainsWildcard = catalogPath.includes('*');\n\n if (validateLocationsExist && catalogPathContainsWildcard) {\n throw Error(\n `Error while processing GitHub provider config. The catalog path ${catalogPath} contains a wildcard, which is incompatible with validation of locations existing before emitting them. Ensure that validateLocationsExist is set to false.`,\n );\n }\n\n const schedule = config.has('schedule')\n ? readTaskScheduleDefinitionFromConfig(config.getConfig('schedule'))\n : undefined;\n\n return {\n id,\n catalogPath,\n organization,\n host,\n filters: {\n repository: repositoryPattern\n ? compileRegExp(repositoryPattern)\n : undefined,\n branch: branchPattern || undefined,\n allowForks: allowForks,\n topic: {\n include: topicFilterInclude,\n exclude: topicFilterExclude,\n },\n },\n schedule,\n validateLocationsExist,\n };\n}\n\n/**\n * Compiles a RegExp while enforcing the pattern to contain\n * the start-of-line and end-of-line anchors.\n *\n * @param pattern\n */\nfunction compileRegExp(pattern: string): RegExp {\n let fullLinePattern = pattern;\n if (!fullLinePattern.startsWith('^')) {\n fullLinePattern = `^${fullLinePattern}`;\n }\n if (!fullLinePattern.endsWith('$')) {\n fullLinePattern = `${fullLinePattern}$`;\n }\n\n return new RegExp(fullLinePattern);\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GithubTopicFilters } from '../providers/GithubEntityProviderConfig';\n\nexport function parseGithubOrgUrl(urlString: string): { org: string } {\n const path = new URL(urlString).pathname.slice(1).split('/');\n\n // /backstage\n if (path.length === 1 && path[0].length) {\n return { org: decodeURIComponent(path[0]) };\n }\n\n throw new Error(`Expected a URL pointing to /<org>`);\n}\n\nexport function satisfiesTopicFilter(\n topics: string[],\n topicFilter: GithubTopicFilters | undefined,\n): Boolean {\n // We don't want to do anything if a filter is not configured (or configured but empty)\n if (!topicFilter) return true;\n if (!topicFilter.include && !topicFilter.exclude) return true;\n if (!topicFilter.include?.length && !topicFilter.exclude?.length) return true;\n // If topic.include is in use, a topic MUST be set that matches the inclusion\n // filter in order for a repository to be ingested\n if (topicFilter.include?.length && !topicFilter.exclude) {\n for (const topic of topics) {\n if (topicFilter.include.includes(topic)) return true;\n }\n return false;\n }\n // If topic.exclude is in use, all topics are included by default\n // with anything matching the filter being discarded. It is technically\n // possible for the filter to be explicitly empty meaning all repositories\n // are ingested although doing so would be pointless.\n if (!topicFilter.include && topicFilter.exclude?.length) {\n if (!topics.length) return true;\n for (const topic of topics) {\n if (topicFilter.exclude.includes(topic)) return false;\n }\n return true;\n }\n // Now the tricky part is where we have both include and exclude configured.\n // In this case, exclude wins out so we take everything matching the initial\n // inclusion filter and from that group, we further discard anything matching\n // the exclusion filter. If an item were to have a topic set in both filters,\n // we expect it to be discarded in the end. The use case here is that is that\n // you may want to retrieve all repos with the topic of team-a while excluding\n // matching repos that are marked as experiments.\n if (topicFilter.include && topicFilter.exclude) {\n const matchesInclude = satisfiesTopicFilter(topics, {\n include: topicFilter.include,\n });\n const matchesExclude = !satisfiesTopicFilter(topics, {\n exclude: topicFilter.exclude,\n });\n if (matchesExclude) return false;\n return matchesInclude;\n }\n\n // If the topic filter is somehow ever in a state that is not covered here, we\n // will fail \"open\" so that Backstage is still usable as if the filter was\n // not configured at all.\n return true;\n}\n\nexport function satisfiesForkFilter(\n allowForks: boolean | true,\n isFork: boolean | false,\n): Boolean {\n // we don't want to include forks if forks are not allowed\n if (!allowForks && isFork) return false;\n\n // if forks are allowed, allow all repos through\n return true;\n}\n\n// Given the github organisation team slug, returns a tuple containing [organisation, team]\nexport function splitTeamSlug(slug: string): [string, string] {\n const parts = slug.split('/');\n if (parts.length !== 2) {\n throw new Error(\n `Github team slug '${slug}' was not in the expected format <organisation>/<team>`,\n );\n }\n return [parts[0], parts[1]];\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Entity, GroupEntity, UserEntity } from '@backstage/catalog-model';\nimport { GithubCredentialType } from '@backstage/integration';\nimport { graphql } from '@octokit/graphql';\nimport {\n defaultOrganizationTeamTransformer,\n defaultUserTransformer,\n TeamTransformer,\n TransformerContext,\n UserTransformer,\n} from './defaultTransformers';\nimport { withLocations } from '../providers/GithubOrgEntityProvider';\n\nimport { DeferredEntity } from '@backstage/plugin-catalog-node';\n\n// Graphql types\n\nexport type QueryResponse = {\n organization?: OrganizationResponse;\n repositoryOwner?: RepositoryOwnerResponse;\n};\n\ntype RepositoryOwnerResponse = {\n repositories?: Connection<RepositoryResponse>;\n};\n\nexport type OrganizationResponse = {\n membersWithRole?: Connection<GithubUser>;\n team?: GithubTeamResponse;\n teams?: Connection<GithubTeamResponse>;\n repositories?: Connection<RepositoryResponse>;\n};\n\nexport type PageInfo = {\n hasNextPage: boolean;\n endCursor?: string;\n};\n\n/**\n * Github User\n *\n * @public\n */\nexport type GithubUser = {\n login: string;\n bio?: string;\n avatarUrl?: string;\n email?: string;\n name?: string;\n organizationVerifiedDomainEmails?: string[];\n};\n\n/**\n * Github Team\n *\n * @public\n */\nexport type GithubTeam = {\n slug: string;\n combinedSlug: string;\n name?: string;\n description?: string;\n avatarUrl?: string;\n editTeamUrl?: string;\n parentTeam?: GithubTeam;\n members: GithubUser[];\n};\n\nexport type GithubTeamResponse = Omit<GithubTeam, 'members'> & {\n members: Connection<GithubUser>;\n};\n\nexport type RepositoryResponse = {\n name: string;\n url: string;\n isArchived: boolean;\n isFork: boolean;\n repositoryTopics: RepositoryTopics;\n defaultBranchRef: {\n name: string;\n } | null;\n catalogInfoFile: {\n __typename: string;\n id: string;\n text: string;\n } | null;\n};\n\ntype RepositoryTopics = {\n nodes: TopicNodes[];\n};\n\ntype TopicNodes = {\n topic: {\n name: string;\n };\n};\n\nexport type Connection<T> = {\n pageInfo: PageInfo;\n nodes: T[];\n};\n\n/**\n * Gets all the users out of a Github organization.\n *\n * Note that the users will not have their memberships filled in.\n *\n * @param client - An octokit graphql client\n * @param org - The slug of the org to read\n */\nexport async function getOrganizationUsers(\n client: typeof graphql,\n org: string,\n tokenType: GithubCredentialType,\n userTransformer: UserTransformer = defaultUserTransformer,\n): Promise<{ users: UserEntity[] }> {\n const query = `\n query users($org: String!, $email: Boolean!, $cursor: String) {\n organization(login: $org) {\n membersWithRole(first: 100, after: $cursor) {\n pageInfo { hasNextPage, endCursor }\n nodes {\n avatarUrl,\n bio,\n email @include(if: $email),\n login,\n name,\n organizationVerifiedDomainEmails(login: $org)\n }\n }\n }\n }`;\n\n // There is no user -> teams edge, so we leave the memberships empty for\n // now and let the team iteration handle it instead\n\n const users = await queryWithPaging(\n client,\n query,\n org,\n r => r.organization?.membersWithRole,\n userTransformer,\n {\n org,\n email: tokenType === 'token',\n },\n );\n\n return { users };\n}\n\n/**\n * Gets all the teams out of a Github organization.\n *\n * Note that the teams will not have any relations apart from parent filled in.\n *\n * @param client - An octokit graphql client\n * @param org - The slug of the org to read\n */\nexport async function getOrganizationTeams(\n client: typeof graphql,\n org: string,\n teamTransformer: TeamTransformer = defaultOrganizationTeamTransformer,\n): Promise<{\n groups: GroupEntity[];\n}> {\n const query = `\n query teams($org: String!, $cursor: String) {\n organization(login: $org) {\n teams(first: 100, after: $cursor) {\n pageInfo { hasNextPage, endCursor }\n nodes {\n slug\n combinedSlug\n name\n description\n avatarUrl\n editTeamUrl\n parentTeam { slug }\n members(first: 100, membership: IMMEDIATE) {\n pageInfo { hasNextPage }\n nodes {\n avatarUrl,\n bio,\n email,\n login,\n name,\n organizationVerifiedDomainEmails(login: $org)\n }\n }\n }\n }\n }\n }`;\n\n const materialisedTeams = async (\n item: GithubTeamResponse,\n ctx: TransformerContext,\n ): Promise<GroupEntity | undefined> => {\n const memberNames: GithubUser[] = [];\n\n if (!item.members.pageInfo.hasNextPage) {\n // We got all the members in one go, run the fast path\n for (const user of item.members.nodes) {\n memberNames.push(user);\n }\n } else {\n // There were more than a hundred immediate members - run the slow\n // path of fetching them explicitly\n const { members } = await getTeamMembers(ctx.client, ctx.org, item.slug);\n for (const userLogin of members) {\n memberNames.push(userLogin);\n }\n }\n\n const team: GithubTeam = {\n ...item,\n members: memberNames,\n };\n\n return await teamTransformer(team, ctx);\n };\n\n const groups = await queryWithPaging(\n client,\n query,\n org,\n r => r.organization?.teams,\n materialisedTeams,\n { org },\n );\n\n return { groups };\n}\n\nexport async function getOrganizationTeamsFromUsers(\n client: typeof graphql,\n org: string,\n userLogins: string[],\n teamTransformer: TeamTransformer = defaultOrganizationTeamTransformer,\n): Promise<{\n groups: GroupEntity[];\n}> {\n const query = `\n query teams($org: String!, $cursor: String, $userLogins: [String!] = \"\") {\n organization(login: $org) {\n teams(first: 100, after: $cursor, userLogins: $userLogins) {\n pageInfo {\n hasNextPage\n endCursor\n }\n nodes {\n slug\n combinedSlug\n name\n description\n avatarUrl\n editTeamUrl\n parentTeam {\n slug\n }\n members(first: 100, membership: IMMEDIATE) {\n pageInfo {\n hasNextPage\n }\n nodes {\n avatarUrl,\n bio,\n email,\n login,\n name,\n organizationVerifiedDomainEmails(login: $org)\n }\n }\n }\n }\n }\n}`;\n\n const materialisedTeams = async (\n item: GithubTeamResponse,\n ctx: TransformerContext,\n ): Promise<GroupEntity | undefined> => {\n const memberNames: GithubUser[] = [];\n\n if (!item.members.pageInfo.hasNextPage) {\n // We got all the members in one go, run the fast path\n for (const user of item.members.nodes) {\n memberNames.push(user);\n }\n } else {\n // There were more than a hundred immediate members - run the slow\n // path of fetching them explicitly\n const { members } = await getTeamMembers(ctx.client, ctx.org, item.slug);\n for (const userLogin of members) {\n memberNames.push(userLogin);\n }\n }\n\n const team: GithubTeam = {\n ...item,\n members: memberNames,\n };\n\n return await teamTransformer(team, ctx);\n };\n\n const groups = await queryWithPaging(\n client,\n query,\n org,\n r => r.organization?.teams,\n materialisedTeams,\n { org, userLogins },\n );\n\n return { groups };\n}\n\nexport async function getOrganizationTeam(\n client: typeof graphql,\n org: string,\n teamSlug: string,\n teamTransformer: TeamTransformer = defaultOrganizationTeamTransformer,\n): Promise<{\n group: GroupEntity;\n}> {\n const query = `\n query teams($org: String!, $teamSlug: String!) {\n organization(login: $org) {\n team(slug:$teamSlug) {\n slug\n combinedSlug\n name\n description\n avatarUrl\n editTeamUrl\n parentTeam { slug }\n members(first: 100, membership: IMMEDIATE) {\n pageInfo { hasNextPage }\n nodes { login }\n }\n }\n }\n }`;\n\n const materialisedTeam = async (\n item: GithubTeamResponse,\n ctx: TransformerContext,\n ): Promise<GroupEntity | undefined> => {\n const memberNames: GithubUser[] = [];\n\n if (!item.members.pageInfo.hasNextPage) {\n // We got all the members in one go, run the fast path\n for (const user of item.members.nodes) {\n memberNames.push(user);\n }\n } else {\n // There were more than a hundred immediate members - run the slow\n // path of fetching them explicitly\n const { members } = await getTeamMembers(ctx.client, ctx.org, item.slug);\n for (const userLogin of members) {\n memberNames.push(userLogin);\n }\n }\n\n const team: GithubTeam = {\n ...item,\n members: memberNames,\n };\n\n return await teamTransformer(team, ctx);\n };\n\n const response: QueryResponse = await client(query, {\n org,\n teamSlug,\n });\n\n if (!response.organization?.team)\n throw new Error(`Found no match for group ${teamSlug}`);\n\n const group = await materialisedTeam(response.organization?.team, {\n query,\n client,\n org,\n });\n\n if (!group) throw new Error(`Can't transform for group ${teamSlug}`);\n\n return { group };\n}\n\nexport async function getOrganizationRepositories(\n client: typeof graphql,\n org: string,\n catalogPath: string,\n): Promise<{ repositories: RepositoryResponse[] }> {\n let relativeCatalogPathRef: string;\n // We must strip the leading slash or the query for objects does not work\n if (catalogPath.startsWith('/')) {\n relativeCatalogPathRef = catalogPath.substring(1);\n } else {\n relativeCatalogPathRef = catalogPath;\n }\n const catalogPathRef = `HEAD:${relativeCatalogPathRef}`;\n const query = `\n query repositories($org: String!, $catalogPathRef: String!, $cursor: String) {\n repositoryOwner(login: $org) {\n login\n repositories(first: 100, after: $cursor) {\n nodes {\n name\n catalogInfoFile: object(expression: $catalogPathRef) {\n __typename\n ... on Blob {\n id\n text\n }\n }\n url\n isArchived\n isFork\n repositoryTopics(first: 100) {\n nodes {\n ... on RepositoryTopic {\n topic {\n name\n }\n }\n }\n }\n defaultBranchRef {\n name\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n }`;\n\n const repositories = await queryWithPaging(\n client,\n query,\n org,\n r => r.repositoryOwner?.repositories,\n async x => x,\n { org, catalogPathRef },\n );\n\n return { repositories };\n}\n\n/**\n * Gets all the users out of a Github organization.\n *\n * Note that the users will not have their memberships filled in.\n *\n * @param client - An octokit graphql client\n * @param org - The slug of the org to read\n * @param teamSlug - The slug of the team to read\n */\nexport async function getTeamMembers(\n client: typeof graphql,\n org: string,\n teamSlug: string,\n): Promise<{ members: GithubUser[] }> {\n const query = `\n query members($org: String!, $teamSlug: String!, $cursor: String) {\n organization(login: $org) {\n team(slug: $teamSlug) {\n members(first: 100, after: $cursor, membership: IMMEDIATE) {\n pageInfo { hasNextPage, endCursor }\n nodes { login }\n }\n }\n }\n }`;\n\n const members = await queryWithPaging(\n client,\n query,\n org,\n r => r.organization?.team?.members,\n async user => user,\n { org, teamSlug },\n );\n\n return { members };\n}\n\n//\n// Helpers\n//\n\n/**\n * Assists in repeatedly executing a query with a paged response.\n *\n * Requires that the query accepts a $cursor variable.\n *\n * @param client - The octokit client\n * @param query - The query to execute\n * @param org - The slug of the org to read\n * @param connection - A function that, given the response, picks out the actual\n * Connection object that's being iterated\n * @param transformer - A function that, given one of the nodes in the Connection,\n * returns the model mapped form of it\n * @param variables - The variable values that the query needs, minus the cursor\n */\nexport async function queryWithPaging<\n GraphqlType,\n OutputType,\n Variables extends {},\n Response = QueryResponse,\n>(\n client: typeof graphql,\n query: string,\n org: string,\n connection: (response: Response) => Connection<GraphqlType> | undefined,\n transformer: (\n item: GraphqlType,\n ctx: TransformerContext,\n ) => Promise<OutputType | undefined>,\n variables: Variables,\n): Promise<OutputType[]> {\n const result: OutputType[] = [];\n\n let cursor: string | undefined = undefined;\n for (let j = 0; j < 1000 /* just for sanity */; ++j) {\n const response: Response = await client(query, {\n ...variables,\n cursor,\n });\n\n const conn = connection(response);\n if (!conn) {\n throw new Error(`Found no match for ${JSON.stringify(variables)}`);\n }\n\n for (const node of conn.nodes) {\n const transformedNode = await transformer(node, {\n client,\n query,\n org,\n });\n\n if (transformedNode) {\n result.push(transformedNode);\n }\n }\n\n if (!conn.pageInfo.hasNextPage) {\n break;\n } else {\n cursor = conn.pageInfo.endCursor;\n }\n }\n\n return result;\n}\n\nexport type DeferredEntitiesBuilder = (\n org: string,\n entities: Entity[],\n) => { added: DeferredEntity[]; removed: DeferredEntity[] };\n\nexport const createAddEntitiesOperation =\n (id: string, host: string) => (org: string, entities: Entity[]) => ({\n removed: [],\n added: entities.map(entity => ({\n locationKey: `github-org-provider:${id}`,\n entity: withLocations(`https://${host}`, org, entity),\n })),\n });\n\nexport const createRemoveEntitiesOperation =\n (id: string, host: string) => (org: string, entities: Entity[]) => ({\n added: [],\n removed: entities.map(entity => ({\n locationKey: `github-org-provider:${id}`,\n entity: withLocations(`https://${host}`, org, entity),\n })),\n });\n\nexport const createReplaceEntitiesOperation =\n (id: string, host: string) => (org: string, entities: Entity[]) => {\n const entitiesToReplace = entities.map(entity => ({\n locationKey: `github-org-provider:${id}`,\n entity: withLocations(`https://${host}`, org, entity),\n }));\n\n return {\n removed: entitiesToReplace,\n added: entitiesToReplace,\n };\n };\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PluginTaskScheduler, TaskRunner } from '@backstage/backend-tasks';\nimport { Config } from '@backstage/config';\nimport {\n GithubCredentialsProvider,\n ScmIntegrations,\n GithubIntegrationConfig,\n GithubIntegration,\n SingleInstanceGithubCredentialsProvider,\n} from '@backstage/integration';\nimport {\n DeferredEntity,\n EntityProvider,\n EntityProviderConnection,\n locationSpecToLocationEntity,\n} from '@backstage/plugin-catalog-node';\n\nimport { LocationSpec } from '@backstage/plugin-catalog-common';\n\nimport { graphql } from '@octokit/graphql';\nimport * as uuid from 'uuid';\nimport { Logger } from 'winston';\nimport {\n readProviderConfigs,\n GithubEntityProviderConfig,\n} from './GithubEntityProviderConfig';\nimport { getOrganizationRepositories } from '../lib/github';\nimport { satisfiesTopicFilter, satisfiesForkFilter } from '../lib/util';\n\nimport { EventParams, EventSubscriber } from '@backstage/plugin-events-node';\nimport { PushEvent, Commit } from '@octokit/webhooks-types';\nimport { Minimatch } from 'minimatch';\n\nconst TOPIC_REPO_PUSH = 'github.push';\n\ntype Repository = {\n name: string;\n url: string;\n isArchived: boolean;\n isFork: boolean;\n repositoryTopics: string[];\n defaultBranchRef?: string;\n isCatalogInfoFilePresent: boolean;\n};\n\n/**\n * Discovers catalog files located in [GitHub](https://github.com).\n * The provider will search your GitHub account and register catalog files matching the configured path\n * as Location entity and via following processing steps add all contained catalog entities.\n * This can be useful as an alternative to static locations or manually adding things to the catalog.\n *\n * @public\n */\nexport class GithubEntityProvider implements EntityProvider, EventSubscriber {\n private readonly config: GithubEntityProviderConfig;\n private readonly logger: Logger;\n private readonly integration: GithubIntegrationConfig;\n private readonly scheduleFn: () => Promise<void>;\n private connection?: EntityProviderConnection;\n private readonly githubCredentialsProvider: GithubCredentialsProvider;\n\n static fromConfig(\n config: Config,\n options: {\n logger: Logger;\n schedule?: TaskRunner;\n scheduler?: PluginTaskScheduler;\n },\n ): GithubEntityProvider[] {\n if (!options.schedule && !options.scheduler) {\n throw new Error('Either schedule or scheduler must be provided.');\n }\n\n const integrations = ScmIntegrations.fromConfig(config);\n\n return readProviderConfigs(config).map(providerConfig => {\n const integrationHost = providerConfig.host;\n const integration = integrations.github.byHost(integrationHost);\n\n if (!integration) {\n throw new Error(\n `There is no GitHub config that matches host ${integrationHost}. Please add a configuration entry for it under integrations.github`,\n );\n }\n\n if (!options.schedule && !providerConfig.schedule) {\n throw new Error(\n `No schedule provided neither via code nor config for github-provider:${providerConfig.id}.`,\n );\n }\n\n const taskRunner =\n options.schedule ??\n options.scheduler!.createScheduledTaskRunner(providerConfig.schedule!);\n\n return new GithubEntityProvider(\n providerConfig,\n integration,\n options.logger,\n taskRunner,\n );\n });\n }\n\n private constructor(\n config: GithubEntityProviderConfig,\n integration: GithubIntegration,\n logger: Logger,\n taskRunner: TaskRunner,\n ) {\n this.config = config;\n this.integration = integration.config;\n this.logger = logger.child({\n target: this.getProviderName(),\n });\n this.scheduleFn = this.createScheduleFn(taskRunner);\n this.githubCredentialsProvider =\n SingleInstanceGithubCredentialsProvider.create(integration.config);\n }\n\n /** {@inheritdoc @backstage/plugin-catalog-backend#EntityProvider.getProviderName} */\n getProviderName(): string {\n return `github-provider:${this.config.id}`;\n }\n\n /** {@inheritdoc @backstage/plugin-catalog-backend#EntityProvider.connect} */\n async connect(connection: EntityProviderConnection): Promise<void> {\n this.connection = connection;\n return await this.scheduleFn();\n }\n\n private createScheduleFn(taskRunner: TaskRunner): () => Promise<void> {\n return async () => {\n const taskId = `${this.getProviderName()}:refresh`;\n return taskRunner.run({\n id: taskId,\n fn: async () => {\n const logger = this.logger.child({\n class: GithubEntityProvider.prototype.constructor.name,\n taskId,\n taskInstanceId: uuid.v4(),\n });\n try {\n await this.refresh(logger);\n } catch (error) {\n logger.error(`${this.getProviderName()} refresh failed`, error);\n }\n },\n });\n };\n }\n\n async refresh(logger: Logger) {\n if (!this.connection) {\n throw new Error('Not initialized');\n }\n\n const targets = await this.findCatalogFiles();\n const matchingTargets = this.matchesFilters(targets);\n const entities = matchingTargets\n .map(repository => this.createLocationUrl(repository))\n .map(GithubEntityProvider.toLocationSpec)\n .map(location => {\n return {\n locationKey: this.getProviderName(),\n entity: locationSpecToLocationEntity({ location }),\n };\n });\n\n await this.connection.applyMutation({\n type: 'full',\n entities,\n });\n\n logger.info(\n `Read ${targets.length} GitHub repositories (${entities.length} matching the pattern)`,\n );\n }\n\n // go to the server and get all of the repositories\n private async findCatalogFiles(): Promise<Repository[]> {\n const organization = this.config.organization;\n const host = this.integration.host;\n const catalogPath = this.config.catalogPath;\n const orgUrl = `https://${host}/${organization}`;\n\n const { headers } = await this.githubCredentialsProvider.getCredentials({\n url: orgUrl,\n });\n\n const client = graphql.defaults({\n baseUrl: this.integration.apiBaseUrl,\n headers,\n });\n\n const { repositories: repositoriesFromGithub } =\n await getOrganizationRepositories(client, organization, catalogPath);\n const repositories = repositoriesFromGithub.map(r => {\n return {\n url: r.url,\n name: r.name,\n defaultBranchRef: r.defaultBranchRef?.name,\n repositoryTopics: r.repositoryTopics.nodes.map(t => t.topic.name),\n isArchived: r.isArchived,\n isFork: r.isFork,\n isCatalogInfoFilePresent:\n r.catalogInfoFile?.__typename === 'Blob' &&\n r.catalogInfoFile.text !== '',\n };\n });\n\n if (this.config.validateLocationsExist) {\n return repositories.filter(\n repository => repository.isCatalogInfoFilePresent,\n );\n }\n\n return repositories;\n }\n\n private matchesFilters(repositories: Repository[]) {\n const repositoryFilter = this.config.filters?.repository;\n const topicFilters = this.config.filters?.topic;\n const allowForks = this.config.filters?.allowForks ?? true;\n\n const matchingRepositories = repositories.filter(r => {\n const repoTopics: string[] = r.repositoryTopics;\n return (\n !r.isArchived &&\n (!repositoryFilter || repositoryFilter.test(r.name)) &&\n satisfiesTopicFilter(repoTopics, topicFilters) &&\n satisfiesForkFilter(allowForks, r.isFork) &&\n r.defaultBranchRef\n );\n });\n return matchingRepositories;\n }\n\n private createLocationUrl(repository: Repository): string {\n const branch =\n this.config.filters?.branch || repository.defaultBranchRef || '-';\n const catalogFile = this.config.catalogPath.startsWith('/')\n ? this.config.catalogPath.substring(1)\n : this.config.catalogPath;\n return `${repository.url}/blob/${branch}/${catalogFile}`;\n }\n\n private static toLocationSpec(target: string): LocationSpec {\n return {\n type: 'url',\n target: target,\n presence: 'optional',\n };\n }\n\n /** {@inheritdoc @backstage/plugin-events-node#EventSubscriber.onEvent} */\n async onEvent(params: EventParams): Promise<void> {\n this.logger.debug(`Received event from ${params.topic}`);\n if (params.topic !== TOPIC_REPO_PUSH) {\n return;\n }\n\n await this.onRepoPush(params.eventPayload as PushEvent);\n }\n\n /** {@inheritdoc @backstage/plugin-events-node#EventSubscriber.supportsEventTopics} */\n supportsEventTopics(): string[] {\n return [TOPIC_REPO_PUSH];\n }\n\n private async onRepoPush(event: PushEvent) {\n if (!this.connection) {\n throw new Error('Not initialized');\n }\n\n const repoName = event.repository.name;\n const repoUrl = event.repository.url;\n this.logger.debug(`handle github:push event for ${repoName} - ${repoUrl}`);\n\n const branch =\n this.config.filters?.branch || event.repository.default_branch;\n\n if (!event.ref.includes(branch)) {\n this.logger.debug(`skipping push event from ref ${event.ref}`);\n return;\n }\n\n const repository: Repository = {\n url: event.repository.url,\n name: event.repository.name,\n defaultBranchRef: event.repository.default_branch,\n repositoryTopics: event.repository.topics,\n isArchived: event.repository.archived,\n isFork: event.repository.fork,\n // we can consider this file present because\n // only the catalog file will be recovered from the commits\n isCatalogInfoFilePresent: true,\n };\n\n const matchingTargets = this.matchesFilters([repository]);\n if (matchingTargets.length === 0) {\n this.logger.debug(\n `skipping push event from repository ${repoName} because didn't match provider filters`,\n );\n return;\n }\n\n // the commit has information about the files (added,removed,modified)\n // so we will process the change based in this data\n // https://docs.github.com/en/developers/webhooks-and-events/webhooks/webhook-events-and-payloads#push\n const added = this.collectDeferredEntitiesFromCommit(\n event.repository.url,\n branch,\n event.commits,\n (commit: Commit) => [...commit.added],\n );\n const removed = this.collectDeferredEntitiesFromCommit(\n event.repository.url,\n branch,\n event.commits,\n (commit: Commit) => [...commit.removed],\n );\n const modified = this.collectFilesFromCommit(\n event.commits,\n (commit: Commit) => [...commit.modified],\n );\n\n if (modified.length > 0) {\n await this.connection.refresh({\n keys: [\n ...modified.map(\n filePath =>\n `url:${event.repository.url}/tree/${branch}/${filePath}`,\n ),\n ...modified.map(\n filePath =>\n `url:${event.repository.url}/blob/${branch}/${filePath}`,\n ),\n ],\n });\n }\n\n if (added.length > 0 || removed.length > 0) {\n await this.connection.applyMutation({\n type: 'delta',\n added: added,\n removed: removed,\n });\n }\n\n this.logger.info(\n `Processed Github push event: added ${added.length} - removed ${removed.length} - modified ${modified.length}`,\n );\n }\n\n private collectDeferredEntitiesFromCommit(\n repositoryUrl: string,\n branch: string,\n commits: Commit[],\n transformOperation: (commit: Commit) => string[],\n ): DeferredEntity[] {\n const catalogFiles = this.collectFilesFromCommit(\n commits,\n transformOperation,\n );\n return this.toDeferredEntities(\n catalogFiles.map(\n filePath => `${repositoryUrl}/blob/${branch}/${filePath}`,\n ),\n );\n }\n\n private collectFilesFromCommit(\n commits: Commit[],\n transformOperation: (commit: Commit) => string[],\n ): string[] {\n const catalogFile = this.config.catalogPath.startsWith('/')\n ? this.config.catalogPath.substring(1)\n : this.config.catalogPath;\n\n const matcher = new Minimatch(catalogFile);\n return commits\n .map(transformOperation)\n .flat()\n .filter(file => matcher.match(file));\n }\n\n private toDeferredEntities(targets: string[]): DeferredEntity[] {\n return targets\n .map(target => {\n const location = GithubEntityProvider.toLocationSpec(target);\n\n return locationSpecToLocationEntity({ location });\n })\n .map(entity => {\n return {\n locationKey: this.getProviderName(),\n entity: entity,\n };\n });\n }\n}\n\n/*\n * Helpers\n */\n\nexport function parseUrl(urlString: string): {\n org: string;\n repoSearchPath: RegExp;\n catalogPath: string;\n branch: string;\n host: string;\n} {\n const url = new URL(urlString);\n const path = url.pathname.slice(1).split('/');\n\n // /backstage/techdocs-*/blob/master/catalog-info.yaml\n // can also be\n // /backstage\n if (path.length > 2 && path[0].length && path[1].length) {\n return {\n org: decodeURIComponent(path[0]),\n repoSearchPath: escapeRegExp(decodeURIComponent(path[1])),\n catalogPath: `/${decodeURIComponent(path.slice(4).join('/'))}`,\n branch: decodeURIComponent(path[3]),\n host: url.host,\n };\n } else if (path.length === 1 && path[0].length) {\n return {\n org: decodeURIComponent(path[0]),\n repoSearchPath: escapeRegExp('*'),\n catalogPath: '/catalog-info.yaml',\n branch: '-',\n host: url.host,\n };\n }\n\n throw new Error(`Failed to parse ${urlString}`);\n}\n\nexport function escapeRegExp(str: string): RegExp {\n return new RegExp(`^${str.replace(/\\*/g, '.*')}$`);\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createBackendModule,\n coreServices,\n} from '@backstage/backend-plugin-api';\nimport { loggerToWinstonLogger } from '@backstage/backend-common';\nimport { catalogProcessingExtensionPoint } from '@backstage/plugin-catalog-node/alpha';\nimport { GithubEntityProvider } from '../providers/GithubEntityProvider';\n\n/**\n * Registers the `GithubEntityProvider` with the catalog processing extension point.\n *\n * @alpha\n */\nexport const catalogModuleGithubEntityProvider = createBackendModule({\n pluginId: 'catalog',\n moduleId: 'githubEntityProvider',\n register(env) {\n env.registerInit({\n deps: {\n catalog: catalogProcessingExtensionPoint,\n config: coreServices.config,\n logger: coreServices.logger,\n scheduler: coreServices.scheduler,\n },\n async init({ catalog, config, logger, scheduler }) {\n catalog.addEntityProvider(\n GithubEntityProvider.fromConfig(config, {\n logger: loggerToWinstonLogger(logger),\n scheduler,\n }),\n );\n },\n });\n },\n});\n"],"names":["readTaskScheduleDefinitionFromConfig","ScmIntegrations","integration","SingleInstanceGithubCredentialsProvider","uuid","locationSpecToLocationEntity","graphql","Minimatch","createBackendModule","catalogProcessingExtensionPoint","coreServices","loggerToWinstonLogger"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,MAAM,oBAAuB,GAAA,oBAAA,CAAA;AAC7B,MAAM,mBAAsB,GAAA,SAAA,CAAA;AAsBrB,SAAS,oBACd,MAC8B,EAAA;AAC9B,EAAM,MAAA,eAAA,GAAkB,MAAO,CAAA,iBAAA,CAAkB,0BAA0B,CAAA,CAAA;AAC3E,EAAA,IAAI,CAAC,eAAiB,EAAA;AACpB,IAAA,OAAO,EAAC,CAAA;AAAA,GACV;AAEA,EAAI,IAAA,eAAA,CAAgB,GAAI,CAAA,cAAc,CAAG,EAAA;AAEvC,IAAA,OAAO,CAAC,kBAAA,CAAmB,mBAAqB,EAAA,eAAe,CAAC,CAAA,CAAA;AAAA,GAClE;AAEA,EAAA,OAAO,eAAgB,CAAA,IAAA,EAAO,CAAA,GAAA,CAAI,CAAM,EAAA,KAAA;AACtC,IAAM,MAAA,cAAA,GAAiB,eAAgB,CAAA,SAAA,CAAU,EAAE,CAAA,CAAA;AAEnD,IAAO,OAAA,kBAAA,CAAmB,IAAI,cAAc,CAAA,CAAA;AAAA,GAC7C,CAAA,CAAA;AACH,CAAA;AAEA,SAAS,kBAAA,CACP,IACA,MAC4B,EAAA;AApE9B,EAAA,IAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,CAAA;AAqEE,EAAM,MAAA,YAAA,GAAe,MAAO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
|
|
6
6
|
* @alpha
|
|
7
7
|
*/
|
|
8
|
-
declare const
|
|
8
|
+
declare const catalogModuleGithubEntityProvider: () => _backstage_backend_plugin_api.BackendFeature;
|
|
9
9
|
|
|
10
|
-
export {
|
|
10
|
+
export { catalogModuleGithubEntityProvider };
|
package/dist/index.cjs.js
CHANGED
|
@@ -7,7 +7,7 @@ var integration = require('@backstage/integration');
|
|
|
7
7
|
var rest = require('@octokit/rest');
|
|
8
8
|
var lodash = require('lodash');
|
|
9
9
|
var parseGitUrl = require('git-url-parse');
|
|
10
|
-
var
|
|
10
|
+
var pluginCatalogNode = require('@backstage/plugin-catalog-node');
|
|
11
11
|
var graphql = require('@octokit/graphql');
|
|
12
12
|
var catalogModel = require('@backstage/catalog-model');
|
|
13
13
|
var uuid = require('uuid');
|
|
@@ -660,7 +660,7 @@ async function getOrganizationTeams(client, org, teamTransformer = defaultOrgani
|
|
|
660
660
|
parentTeam { slug }
|
|
661
661
|
members(first: 100, membership: IMMEDIATE) {
|
|
662
662
|
pageInfo { hasNextPage }
|
|
663
|
-
nodes {
|
|
663
|
+
nodes {
|
|
664
664
|
avatarUrl,
|
|
665
665
|
bio,
|
|
666
666
|
email,
|
|
@@ -1076,7 +1076,7 @@ class GithubDiscoveryProcessor {
|
|
|
1076
1076
|
}
|
|
1077
1077
|
const path = `/blob/${branchName}${catalogPath}`;
|
|
1078
1078
|
emit(
|
|
1079
|
-
|
|
1079
|
+
pluginCatalogNode.processingResult.location({
|
|
1080
1080
|
type: "url",
|
|
1081
1081
|
target: `${repository.url}${path}`,
|
|
1082
1082
|
// Not all locations may actually exist, since the user defined them as a wildcard pattern.
|
|
@@ -1207,7 +1207,7 @@ class GithubMultiOrgReaderProcessor {
|
|
|
1207
1207
|
assignGroupsToUsers(pendingUsers, groups);
|
|
1208
1208
|
buildOrgHierarchy(groups);
|
|
1209
1209
|
for (const group of groups) {
|
|
1210
|
-
emit(
|
|
1210
|
+
emit(pluginCatalogNode.processingResult.entity(location, group));
|
|
1211
1211
|
}
|
|
1212
1212
|
} catch (e) {
|
|
1213
1213
|
this.logger.error(
|
|
@@ -1217,7 +1217,7 @@ class GithubMultiOrgReaderProcessor {
|
|
|
1217
1217
|
}
|
|
1218
1218
|
const allUsers = Array.from(allUsersMap.values());
|
|
1219
1219
|
for (const user of allUsers) {
|
|
1220
|
-
emit(
|
|
1220
|
+
emit(pluginCatalogNode.processingResult.entity(location, user));
|
|
1221
1221
|
}
|
|
1222
1222
|
return true;
|
|
1223
1223
|
}
|
|
@@ -1267,10 +1267,10 @@ class GithubOrgReaderProcessor {
|
|
|
1267
1267
|
assignGroupsToUsers(users, groups);
|
|
1268
1268
|
buildOrgHierarchy(groups);
|
|
1269
1269
|
for (const group of groups) {
|
|
1270
|
-
emit(
|
|
1270
|
+
emit(pluginCatalogNode.processingResult.entity(location, group));
|
|
1271
1271
|
}
|
|
1272
1272
|
for (const user of users) {
|
|
1273
|
-
emit(
|
|
1273
|
+
emit(pluginCatalogNode.processingResult.entity(location, user));
|
|
1274
1274
|
}
|
|
1275
1275
|
return true;
|
|
1276
1276
|
}
|
|
@@ -1436,7 +1436,7 @@ class GithubEntityProvider {
|
|
|
1436
1436
|
const entities = matchingTargets.map((repository) => this.createLocationUrl(repository)).map(GithubEntityProvider.toLocationSpec).map((location) => {
|
|
1437
1437
|
return {
|
|
1438
1438
|
locationKey: this.getProviderName(),
|
|
1439
|
-
entity:
|
|
1439
|
+
entity: pluginCatalogNode.locationSpecToLocationEntity({ location })
|
|
1440
1440
|
};
|
|
1441
1441
|
});
|
|
1442
1442
|
await this.connection.applyMutation({
|
|
@@ -1605,7 +1605,7 @@ class GithubEntityProvider {
|
|
|
1605
1605
|
toDeferredEntities(targets) {
|
|
1606
1606
|
return targets.map((target) => {
|
|
1607
1607
|
const location = GithubEntityProvider.toLocationSpec(target);
|
|
1608
|
-
return
|
|
1608
|
+
return pluginCatalogNode.locationSpecToLocationEntity({ location });
|
|
1609
1609
|
}).map((entity) => {
|
|
1610
1610
|
return {
|
|
1611
1611
|
locationKey: this.getProviderName(),
|