@backstage/plugin-catalog-backend-module-github 0.0.0-nightly-20220311022539

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 ADDED
@@ -0,0 +1,22 @@
1
+ # @backstage/plugin-catalog-backend-module-github
2
+
3
+ ## 0.0.0-nightly-20220311022539
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies
8
+ - @backstage/catalog-model@0.0.0-nightly-20220311022539
9
+ - @backstage/plugin-catalog-backend@0.0.0-nightly-20220311022539
10
+
11
+ ## 0.1.0
12
+
13
+ ### Minor Changes
14
+
15
+ - d4934e19b1: Added package, moving out GitHub specific functionality from the catalog-backend
16
+
17
+ ### Patch Changes
18
+
19
+ - Updated dependencies
20
+ - @backstage/backend-common@0.13.0
21
+ - @backstage/plugin-catalog-backend@0.24.0
22
+ - @backstage/catalog-model@0.13.0
package/README.md ADDED
@@ -0,0 +1,8 @@
1
+ # Catalog Backend Module for GitHub
2
+
3
+ This is an extension module to the plugin-catalog-backend plugin, providing extensions targeted at GitHub offerings.
4
+
5
+ ## Getting started
6
+
7
+ See [Backstage documentation](https://backstage.io/docs/integrations/github/discovery) for details on how to install
8
+ and configure the plugin.
@@ -0,0 +1,571 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var integration = require('@backstage/integration');
6
+ var pluginCatalogBackend = require('@backstage/plugin-catalog-backend');
7
+ var graphql = require('@octokit/graphql');
8
+ var catalogModel = require('@backstage/catalog-model');
9
+ var lodash = require('lodash');
10
+
11
+ function readGithubMultiOrgConfig(config) {
12
+ var _a;
13
+ const orgConfigs = (_a = config.getOptionalConfigArray("orgs")) != null ? _a : [];
14
+ return orgConfigs.map((c) => {
15
+ var _a2, _b;
16
+ return {
17
+ name: c.getString("name"),
18
+ groupNamespace: ((_a2 = c.getOptionalString("groupNamespace")) != null ? _a2 : c.getString("name")).toLowerCase(),
19
+ userNamespace: (_b = c.getOptionalString("userNamespace")) != null ? _b : void 0
20
+ };
21
+ });
22
+ }
23
+
24
+ async function getOrganizationUsers(client, org, tokenType, userNamespace) {
25
+ const query = `
26
+ query users($org: String!, $email: Boolean!, $cursor: String) {
27
+ organization(login: $org) {
28
+ membersWithRole(first: 100, after: $cursor) {
29
+ pageInfo { hasNextPage, endCursor }
30
+ nodes {
31
+ avatarUrl,
32
+ bio,
33
+ email @include(if: $email),
34
+ login,
35
+ name
36
+ }
37
+ }
38
+ }
39
+ }`;
40
+ const mapper = (user) => {
41
+ const entity = {
42
+ apiVersion: "backstage.io/v1alpha1",
43
+ kind: "User",
44
+ metadata: {
45
+ name: user.login,
46
+ annotations: {
47
+ "github.com/user-login": user.login
48
+ }
49
+ },
50
+ spec: {
51
+ profile: {},
52
+ memberOf: []
53
+ }
54
+ };
55
+ if (userNamespace)
56
+ entity.metadata.namespace = userNamespace;
57
+ if (user.bio)
58
+ entity.metadata.description = user.bio;
59
+ if (user.name)
60
+ entity.spec.profile.displayName = user.name;
61
+ if (user.email)
62
+ entity.spec.profile.email = user.email;
63
+ if (user.avatarUrl)
64
+ entity.spec.profile.picture = user.avatarUrl;
65
+ return entity;
66
+ };
67
+ const users = await queryWithPaging(client, query, (r) => {
68
+ var _a;
69
+ return (_a = r.organization) == null ? void 0 : _a.membersWithRole;
70
+ }, mapper, { org, email: tokenType === "token" });
71
+ return { users };
72
+ }
73
+ async function getOrganizationTeams(client, org, orgNamespace) {
74
+ const query = `
75
+ query teams($org: String!, $cursor: String) {
76
+ organization(login: $org) {
77
+ teams(first: 100, after: $cursor) {
78
+ pageInfo { hasNextPage, endCursor }
79
+ nodes {
80
+ slug
81
+ combinedSlug
82
+ name
83
+ description
84
+ avatarUrl
85
+ parentTeam { slug }
86
+ members(first: 100, membership: IMMEDIATE) {
87
+ pageInfo { hasNextPage }
88
+ nodes { login }
89
+ }
90
+ }
91
+ }
92
+ }
93
+ }`;
94
+ const groupMemberUsers = /* @__PURE__ */ new Map();
95
+ const mapper = async (team) => {
96
+ const entity = {
97
+ apiVersion: "backstage.io/v1alpha1",
98
+ kind: "Group",
99
+ metadata: {
100
+ name: team.slug,
101
+ annotations: {
102
+ "github.com/team-slug": team.combinedSlug
103
+ }
104
+ },
105
+ spec: {
106
+ type: "team",
107
+ profile: {},
108
+ children: []
109
+ }
110
+ };
111
+ if (orgNamespace) {
112
+ entity.metadata.namespace = orgNamespace;
113
+ }
114
+ if (team.description) {
115
+ entity.metadata.description = team.description;
116
+ }
117
+ if (team.name) {
118
+ entity.spec.profile.displayName = team.name;
119
+ }
120
+ if (team.avatarUrl) {
121
+ entity.spec.profile.picture = team.avatarUrl;
122
+ }
123
+ if (team.parentTeam) {
124
+ entity.spec.parent = team.parentTeam.slug;
125
+ }
126
+ const memberNames = [];
127
+ const groupKey = orgNamespace ? `${orgNamespace}/${team.slug}` : team.slug;
128
+ groupMemberUsers.set(groupKey, memberNames);
129
+ if (!team.members.pageInfo.hasNextPage) {
130
+ for (const user of team.members.nodes) {
131
+ memberNames.push(user.login);
132
+ }
133
+ } else {
134
+ const { members } = await getTeamMembers(client, org, team.slug);
135
+ for (const userLogin of members) {
136
+ memberNames.push(userLogin);
137
+ }
138
+ }
139
+ return entity;
140
+ };
141
+ const groups = await queryWithPaging(client, query, (r) => {
142
+ var _a;
143
+ return (_a = r.organization) == null ? void 0 : _a.teams;
144
+ }, mapper, { org });
145
+ return { groups, groupMemberUsers };
146
+ }
147
+ async function getOrganizationRepositories(client, org) {
148
+ const query = `
149
+ query repositories($org: String!, $cursor: String) {
150
+ repositoryOwner(login: $org) {
151
+ login
152
+ repositories(first: 100, after: $cursor) {
153
+ nodes {
154
+ name
155
+ url
156
+ isArchived
157
+ defaultBranchRef {
158
+ name
159
+ }
160
+ }
161
+ pageInfo {
162
+ hasNextPage
163
+ endCursor
164
+ }
165
+ }
166
+ }
167
+ }`;
168
+ const repositories = await queryWithPaging(client, query, (r) => {
169
+ var _a;
170
+ return (_a = r.repositoryOwner) == null ? void 0 : _a.repositories;
171
+ }, (x) => x, { org });
172
+ return { repositories };
173
+ }
174
+ async function getTeamMembers(client, org, teamSlug) {
175
+ const query = `
176
+ query members($org: String!, $teamSlug: String!, $cursor: String) {
177
+ organization(login: $org) {
178
+ team(slug: $teamSlug) {
179
+ members(first: 100, after: $cursor, membership: IMMEDIATE) {
180
+ pageInfo { hasNextPage, endCursor }
181
+ nodes { login }
182
+ }
183
+ }
184
+ }
185
+ }`;
186
+ const members = await queryWithPaging(client, query, (r) => {
187
+ var _a, _b;
188
+ return (_b = (_a = r.organization) == null ? void 0 : _a.team) == null ? void 0 : _b.members;
189
+ }, (user) => user.login, { org, teamSlug });
190
+ return { members };
191
+ }
192
+ async function queryWithPaging(client, query, connection, mapper, variables) {
193
+ const result = [];
194
+ let cursor = void 0;
195
+ for (let j = 0; j < 1e3; ++j) {
196
+ const response = await client(query, {
197
+ ...variables,
198
+ cursor
199
+ });
200
+ const conn = connection(response);
201
+ if (!conn) {
202
+ throw new Error(`Found no match for ${JSON.stringify(variables)}`);
203
+ }
204
+ for (const node of conn.nodes) {
205
+ result.push(await mapper(node));
206
+ }
207
+ if (!conn.pageInfo.hasNextPage) {
208
+ break;
209
+ } else {
210
+ cursor = conn.pageInfo.endCursor;
211
+ }
212
+ }
213
+ return result;
214
+ }
215
+
216
+ function buildOrgHierarchy(groups) {
217
+ const groupsByName = new Map(groups.map((g) => [g.metadata.name, g]));
218
+ for (const group of groups) {
219
+ const selfName = group.metadata.name;
220
+ const parentName = group.spec.parent;
221
+ if (parentName) {
222
+ const parent = groupsByName.get(parentName);
223
+ if (parent && !parent.spec.children.includes(selfName)) {
224
+ parent.spec.children.push(selfName);
225
+ }
226
+ }
227
+ }
228
+ for (const group of groups) {
229
+ const selfName = group.metadata.name;
230
+ for (const childName of group.spec.children) {
231
+ const child = groupsByName.get(childName);
232
+ if (child && !child.spec.parent) {
233
+ child.spec.parent = selfName;
234
+ }
235
+ }
236
+ }
237
+ }
238
+ function assignGroupsToUsers(users, groupMemberUsers) {
239
+ const usersByName = new Map(users.map((u) => [u.metadata.name, u]));
240
+ for (const [groupName, userNames] of groupMemberUsers.entries()) {
241
+ for (const userName of userNames) {
242
+ const user = usersByName.get(userName);
243
+ if (user && !user.spec.memberOf.includes(groupName)) {
244
+ user.spec.memberOf.push(groupName);
245
+ }
246
+ }
247
+ }
248
+ }
249
+
250
+ function parseGitHubOrgUrl(urlString) {
251
+ const path = new URL(urlString).pathname.substr(1).split("/");
252
+ if (path.length === 1 && path[0].length) {
253
+ return { org: decodeURIComponent(path[0]) };
254
+ }
255
+ throw new Error(`Expected a URL pointing to /<org>`);
256
+ }
257
+
258
+ class GithubDiscoveryProcessor {
259
+ static fromConfig(config, options) {
260
+ const integrations = integration.ScmIntegrations.fromConfig(config);
261
+ return new GithubDiscoveryProcessor({
262
+ ...options,
263
+ integrations
264
+ });
265
+ }
266
+ constructor(options) {
267
+ this.integrations = options.integrations;
268
+ this.logger = options.logger;
269
+ this.githubCredentialsProvider = options.githubCredentialsProvider || integration.DefaultGithubCredentialsProvider.fromIntegrations(this.integrations);
270
+ }
271
+ getProcessorName() {
272
+ return "GithubDiscoveryProcessor";
273
+ }
274
+ async readLocation(location, _optional, emit) {
275
+ var _a, _b;
276
+ if (location.type !== "github-discovery") {
277
+ return false;
278
+ }
279
+ const gitHubConfig = (_a = this.integrations.github.byUrl(location.target)) == null ? void 0 : _a.config;
280
+ if (!gitHubConfig) {
281
+ throw new Error(`There is no GitHub integration that matches ${location.target}. Please add a configuration entry for it under integrations.github`);
282
+ }
283
+ const { org, repoSearchPath, catalogPath, branch, host } = parseUrl(location.target);
284
+ const orgUrl = `https://${host}/${org}`;
285
+ const { headers } = await this.githubCredentialsProvider.getCredentials({
286
+ url: orgUrl
287
+ });
288
+ const client = graphql.graphql.defaults({
289
+ baseUrl: gitHubConfig.apiBaseUrl,
290
+ headers
291
+ });
292
+ const startTimestamp = Date.now();
293
+ this.logger.info(`Reading GitHub repositories from ${location.target}`);
294
+ const { repositories } = await getOrganizationRepositories(client, org);
295
+ const matching = repositories.filter((r) => !r.isArchived && repoSearchPath.test(r.name));
296
+ const duration = ((Date.now() - startTimestamp) / 1e3).toFixed(1);
297
+ this.logger.debug(`Read ${repositories.length} GitHub repositories (${matching.length} matching the pattern) in ${duration} seconds`);
298
+ for (const repository of matching) {
299
+ const branchName = branch === "-" ? (_b = repository.defaultBranchRef) == null ? void 0 : _b.name : branch;
300
+ if (!branchName) {
301
+ this.logger.info(`the repository ${repository.url} does not have a default branch, skipping`);
302
+ continue;
303
+ }
304
+ const path = `/blob/${branchName}${catalogPath}`;
305
+ emit(pluginCatalogBackend.processingResult.location({
306
+ type: "url",
307
+ target: `${repository.url}${path}`,
308
+ presence: "optional"
309
+ }));
310
+ }
311
+ return true;
312
+ }
313
+ }
314
+ function parseUrl(urlString) {
315
+ const url = new URL(urlString);
316
+ const path = url.pathname.substr(1).split("/");
317
+ if (path.length > 2 && path[0].length && path[1].length) {
318
+ return {
319
+ org: decodeURIComponent(path[0]),
320
+ repoSearchPath: escapeRegExp(decodeURIComponent(path[1])),
321
+ branch: decodeURIComponent(path[3]),
322
+ catalogPath: `/${decodeURIComponent(path.slice(4).join("/"))}`,
323
+ host: url.host
324
+ };
325
+ } else if (path.length === 1 && path[0].length) {
326
+ return {
327
+ org: decodeURIComponent(path[0]),
328
+ host: url.host,
329
+ repoSearchPath: escapeRegExp("*"),
330
+ catalogPath: "/catalog-info.yaml",
331
+ branch: "-"
332
+ };
333
+ }
334
+ throw new Error(`Failed to parse ${urlString}`);
335
+ }
336
+ function escapeRegExp(str) {
337
+ return new RegExp(`^${str.replace(/\*/g, ".*")}$`);
338
+ }
339
+
340
+ class GithubMultiOrgReaderProcessor {
341
+ static fromConfig(config, options) {
342
+ const c = config.getOptionalConfig("catalog.processors.githubMultiOrg");
343
+ const integrations = integration.ScmIntegrations.fromConfig(config);
344
+ return new GithubMultiOrgReaderProcessor({
345
+ ...options,
346
+ integrations,
347
+ orgs: c ? readGithubMultiOrgConfig(c) : []
348
+ });
349
+ }
350
+ constructor(options) {
351
+ this.integrations = options.integrations;
352
+ this.logger = options.logger;
353
+ this.orgs = options.orgs;
354
+ this.githubCredentialsProvider = options.githubCredentialsProvider || integration.DefaultGithubCredentialsProvider.fromIntegrations(this.integrations);
355
+ }
356
+ getProcessorName() {
357
+ return "GithubMultiOrgReaderProcessor";
358
+ }
359
+ async readLocation(location, _optional, emit) {
360
+ var _a, _b;
361
+ if (location.type !== "github-multi-org") {
362
+ return false;
363
+ }
364
+ const gitHubConfig = (_a = this.integrations.github.byUrl(location.target)) == null ? void 0 : _a.config;
365
+ if (!gitHubConfig) {
366
+ throw new Error(`There is no GitHub integration that matches ${location.target}. Please add a configuration entry for it under integrations.github`);
367
+ }
368
+ const allUsersMap = /* @__PURE__ */ new Map();
369
+ const baseUrl = new URL(location.target).origin;
370
+ const orgsToProcess = this.orgs.length ? this.orgs : await this.getAllOrgs(gitHubConfig);
371
+ for (const orgConfig of orgsToProcess) {
372
+ try {
373
+ const { headers, type: tokenType } = await this.githubCredentialsProvider.getCredentials({
374
+ url: `${baseUrl}/${orgConfig.name}`
375
+ });
376
+ const client = graphql.graphql.defaults({
377
+ baseUrl: gitHubConfig.apiBaseUrl,
378
+ headers
379
+ });
380
+ const startTimestamp = Date.now();
381
+ this.logger.info(`Reading GitHub users and teams for org: ${orgConfig.name}`);
382
+ const { users } = await getOrganizationUsers(client, orgConfig.name, tokenType, orgConfig.userNamespace);
383
+ const { groups, groupMemberUsers } = await getOrganizationTeams(client, orgConfig.name, orgConfig.groupNamespace);
384
+ const duration = ((Date.now() - startTimestamp) / 1e3).toFixed(1);
385
+ this.logger.debug(`Read ${users.length} GitHub users and ${groups.length} GitHub teams from ${orgConfig.name} in ${duration} seconds`);
386
+ let prefix = (_b = orgConfig.userNamespace) != null ? _b : "";
387
+ if (prefix.length > 0)
388
+ prefix += "/";
389
+ users.forEach((u) => {
390
+ if (!allUsersMap.has(prefix + u.metadata.name)) {
391
+ allUsersMap.set(prefix + u.metadata.name, u);
392
+ }
393
+ });
394
+ for (const [groupName, userNames] of groupMemberUsers.entries()) {
395
+ for (const userName of userNames) {
396
+ const user = allUsersMap.get(prefix + userName);
397
+ if (user && !user.spec.memberOf.includes(groupName)) {
398
+ user.spec.memberOf.push(groupName);
399
+ }
400
+ }
401
+ }
402
+ buildOrgHierarchy(groups);
403
+ for (const group of groups) {
404
+ emit(pluginCatalogBackend.processingResult.entity(location, group));
405
+ }
406
+ } catch (e) {
407
+ this.logger.error(`Failed to read GitHub org data for ${orgConfig.name}: ${e}`);
408
+ }
409
+ }
410
+ const allUsers = Array.from(allUsersMap.values());
411
+ for (const user of allUsers) {
412
+ emit(pluginCatalogBackend.processingResult.entity(location, user));
413
+ }
414
+ return true;
415
+ }
416
+ async getAllOrgs(gitHubConfig) {
417
+ const githubAppMux = new integration.GithubAppCredentialsMux(gitHubConfig);
418
+ const installs = await githubAppMux.getAllInstallations();
419
+ return installs.map((install) => install.target_type === "Organization" && install.account && install.account.login ? {
420
+ name: install.account.login,
421
+ groupNamespace: install.account.login.toLowerCase()
422
+ } : void 0).filter(Boolean);
423
+ }
424
+ }
425
+
426
+ class GitHubOrgEntityProvider {
427
+ constructor(options) {
428
+ this.options = options;
429
+ this.githubCredentialsProvider = options.githubCredentialsProvider || integration.SingleInstanceGithubCredentialsProvider.create(options.gitHubConfig);
430
+ }
431
+ static fromConfig(config, options) {
432
+ var _a;
433
+ const integrations = integration.ScmIntegrations.fromConfig(config);
434
+ const gitHubConfig = (_a = integrations.github.byUrl(options.orgUrl)) == null ? void 0 : _a.config;
435
+ if (!gitHubConfig) {
436
+ throw new Error(`There is no GitHub Org provider that matches ${options.orgUrl}. Please add a configuration for an integration.`);
437
+ }
438
+ const logger = options.logger.child({
439
+ target: options.orgUrl
440
+ });
441
+ return new GitHubOrgEntityProvider({
442
+ id: options.id,
443
+ orgUrl: options.orgUrl,
444
+ logger,
445
+ gitHubConfig,
446
+ githubCredentialsProvider: options.githubCredentialsProvider || integration.DefaultGithubCredentialsProvider.fromIntegrations(integrations)
447
+ });
448
+ }
449
+ getProviderName() {
450
+ return `GitHubOrgEntityProvider:${this.options.id}`;
451
+ }
452
+ async connect(connection) {
453
+ this.connection = connection;
454
+ }
455
+ async read() {
456
+ if (!this.connection) {
457
+ throw new Error("Not initialized");
458
+ }
459
+ const { markReadComplete } = trackProgress(this.options.logger);
460
+ const { headers, type: tokenType } = await this.githubCredentialsProvider.getCredentials({
461
+ url: this.options.orgUrl
462
+ });
463
+ const client = graphql.graphql.defaults({
464
+ baseUrl: this.options.gitHubConfig.apiBaseUrl,
465
+ headers
466
+ });
467
+ const { org } = parseGitHubOrgUrl(this.options.orgUrl);
468
+ const { users } = await getOrganizationUsers(client, org, tokenType);
469
+ const { groups, groupMemberUsers } = await getOrganizationTeams(client, org);
470
+ assignGroupsToUsers(users, groupMemberUsers);
471
+ buildOrgHierarchy(groups);
472
+ const { markCommitComplete } = markReadComplete({ users, groups });
473
+ await this.connection.applyMutation({
474
+ type: "full",
475
+ entities: [...users, ...groups].map((entity) => ({
476
+ locationKey: `github-org-provider:${this.options.id}`,
477
+ entity: withLocations(`https://${this.options.gitHubConfig.host}`, org, entity)
478
+ }))
479
+ });
480
+ markCommitComplete();
481
+ }
482
+ }
483
+ function trackProgress(logger) {
484
+ let timestamp = Date.now();
485
+ let summary;
486
+ logger.info("Reading GitHub users and groups");
487
+ function markReadComplete(read) {
488
+ summary = `${read.users.length} GitHub users and ${read.groups.length} GitHub groups`;
489
+ const readDuration = ((Date.now() - timestamp) / 1e3).toFixed(1);
490
+ timestamp = Date.now();
491
+ logger.info(`Read ${summary} in ${readDuration} seconds. Committing...`);
492
+ return { markCommitComplete };
493
+ }
494
+ function markCommitComplete() {
495
+ const commitDuration = ((Date.now() - timestamp) / 1e3).toFixed(1);
496
+ logger.info(`Committed ${summary} in ${commitDuration} seconds.`);
497
+ }
498
+ return { markReadComplete };
499
+ }
500
+ function withLocations(baseUrl, org, entity) {
501
+ const location = entity.kind === "Group" ? `url:${baseUrl}/orgs/${org}/teams/${entity.metadata.name}` : `url:${baseUrl}/${entity.metadata.name}`;
502
+ return lodash.merge({
503
+ metadata: {
504
+ annotations: {
505
+ [catalogModel.ANNOTATION_LOCATION]: location,
506
+ [catalogModel.ANNOTATION_ORIGIN_LOCATION]: location
507
+ }
508
+ }
509
+ }, entity);
510
+ }
511
+
512
+ class GithubOrgReaderProcessor {
513
+ static fromConfig(config, options) {
514
+ const integrations = integration.ScmIntegrations.fromConfig(config);
515
+ return new GithubOrgReaderProcessor({
516
+ ...options,
517
+ integrations
518
+ });
519
+ }
520
+ constructor(options) {
521
+ this.integrations = options.integrations;
522
+ this.githubCredentialsProvider = options.githubCredentialsProvider || integration.DefaultGithubCredentialsProvider.fromIntegrations(this.integrations);
523
+ this.logger = options.logger;
524
+ }
525
+ getProcessorName() {
526
+ return "GithubOrgReaderProcessor";
527
+ }
528
+ async readLocation(location, _optional, emit) {
529
+ if (location.type !== "github-org") {
530
+ return false;
531
+ }
532
+ const { client, tokenType } = await this.createClient(location.target);
533
+ const { org } = parseGitHubOrgUrl(location.target);
534
+ const startTimestamp = Date.now();
535
+ this.logger.info("Reading GitHub users and groups");
536
+ const { users } = await getOrganizationUsers(client, org, tokenType);
537
+ const { groups, groupMemberUsers } = await getOrganizationTeams(client, org);
538
+ const duration = ((Date.now() - startTimestamp) / 1e3).toFixed(1);
539
+ this.logger.debug(`Read ${users.length} GitHub users and ${groups.length} GitHub groups in ${duration} seconds`);
540
+ assignGroupsToUsers(users, groupMemberUsers);
541
+ buildOrgHierarchy(groups);
542
+ for (const group of groups) {
543
+ emit(pluginCatalogBackend.processingResult.entity(location, group));
544
+ }
545
+ for (const user of users) {
546
+ emit(pluginCatalogBackend.processingResult.entity(location, user));
547
+ }
548
+ return true;
549
+ }
550
+ async createClient(orgUrl) {
551
+ var _a;
552
+ const gitHubConfig = (_a = this.integrations.github.byUrl(orgUrl)) == null ? void 0 : _a.config;
553
+ if (!gitHubConfig) {
554
+ throw new Error(`There is no GitHub Org provider that matches ${orgUrl}. Please add a configuration for an integration.`);
555
+ }
556
+ const { headers, type: tokenType } = await this.githubCredentialsProvider.getCredentials({
557
+ url: orgUrl
558
+ });
559
+ const client = graphql.graphql.defaults({
560
+ baseUrl: gitHubConfig.apiBaseUrl,
561
+ headers
562
+ });
563
+ return { client, tokenType };
564
+ }
565
+ }
566
+
567
+ exports.GitHubOrgEntityProvider = GitHubOrgEntityProvider;
568
+ exports.GithubDiscoveryProcessor = GithubDiscoveryProcessor;
569
+ exports.GithubMultiOrgReaderProcessor = GithubMultiOrgReaderProcessor;
570
+ exports.GithubOrgReaderProcessor = GithubOrgReaderProcessor;
571
+ //# sourceMappingURL=index.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs.js","sources":["../src/lib/config.ts","../src/lib/github.ts","../src/lib/org.ts","../src/lib/util.ts","../src/GithubDiscoveryProcessor.ts","../src/GithubMultiOrgReaderProcessor.ts","../src/GitHubOrgEntityProvider.ts","../src/GithubOrgReaderProcessor.ts"],"sourcesContent":["/*\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 { Config } from '@backstage/config';\n\n/**\n * The configuration parameters for a multi-org GitHub processor.\n * @public\n */\nexport type GithubMultiOrgConfig = Array<{\n /**\n * The name of the GitHub org to process.\n */\n name: string;\n /**\n * The namespace of the group created for this org.\n */\n groupNamespace: string;\n /**\n * The namespace of the users created for this org. If not specified defaults to undefined.\n */\n userNamespace: string | undefined;\n}>;\n\nexport function readGithubMultiOrgConfig(config: Config): GithubMultiOrgConfig {\n const orgConfigs = config.getOptionalConfigArray('orgs') ?? [];\n return orgConfigs.map(c => ({\n name: c.getString('name'),\n groupNamespace: (\n c.getOptionalString('groupNamespace') ?? c.getString('name')\n ).toLowerCase(),\n userNamespace: c.getOptionalString('userNamespace') ?? undefined,\n }));\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 { GroupEntity, UserEntity } from '@backstage/catalog-model';\nimport { GithubCredentialType } from '@backstage/integration';\nimport { graphql } from '@octokit/graphql';\n\n// Graphql types\n\nexport type QueryResponse = {\n organization?: Organization;\n repositoryOwner?: Organization | User;\n};\n\nexport type Organization = {\n membersWithRole?: Connection<User>;\n team?: Team;\n teams?: Connection<Team>;\n repositories?: Connection<Repository>;\n};\n\nexport type PageInfo = {\n hasNextPage: boolean;\n endCursor?: string;\n};\n\nexport type User = {\n login: string;\n bio?: string;\n avatarUrl?: string;\n email?: string;\n name?: string;\n repositories?: Connection<Repository>;\n};\n\nexport type Team = {\n slug: string;\n combinedSlug: string;\n name?: string;\n description?: string;\n avatarUrl?: string;\n parentTeam?: Team;\n members: Connection<User>;\n};\n\nexport type Repository = {\n name: string;\n url: string;\n isArchived: boolean;\n defaultBranchRef: {\n name: string;\n } | null;\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 userNamespace?: string,\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 }\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 const mapper = (user: User) => {\n const entity: UserEntity = {\n apiVersion: 'backstage.io/v1alpha1',\n kind: 'User',\n metadata: {\n name: user.login,\n annotations: {\n 'github.com/user-login': user.login,\n },\n },\n spec: {\n profile: {},\n memberOf: [],\n },\n };\n\n if (userNamespace) entity.metadata.namespace = userNamespace;\n if (user.bio) entity.metadata.description = user.bio;\n if (user.name) entity.spec.profile!.displayName = user.name;\n if (user.email) entity.spec.profile!.email = user.email;\n if (user.avatarUrl) entity.spec.profile!.picture = user.avatarUrl;\n\n return entity;\n };\n\n const users = await queryWithPaging(\n client,\n query,\n r => r.organization?.membersWithRole,\n mapper,\n { org, email: tokenType === 'token' },\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 orgNamespace?: string,\n): Promise<{\n groups: GroupEntity[];\n groupMemberUsers: Map<string, string[]>;\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 parentTeam { slug }\n members(first: 100, membership: IMMEDIATE) {\n pageInfo { hasNextPage }\n nodes { login }\n }\n }\n }\n }\n }`;\n\n // Gets populated inside the mapper below\n const groupMemberUsers = new Map<string, string[]>();\n\n const mapper = async (team: Team) => {\n const entity: GroupEntity = {\n apiVersion: 'backstage.io/v1alpha1',\n kind: 'Group',\n metadata: {\n name: team.slug,\n annotations: {\n 'github.com/team-slug': team.combinedSlug,\n },\n },\n spec: {\n type: 'team',\n profile: {},\n children: [],\n },\n };\n\n if (orgNamespace) {\n entity.metadata.namespace = orgNamespace;\n }\n\n if (team.description) {\n entity.metadata.description = team.description;\n }\n if (team.name) {\n entity.spec.profile!.displayName = team.name;\n }\n if (team.avatarUrl) {\n entity.spec.profile!.picture = team.avatarUrl;\n }\n if (team.parentTeam) {\n entity.spec.parent = team.parentTeam.slug;\n }\n\n const memberNames: string[] = [];\n const groupKey = orgNamespace ? `${orgNamespace}/${team.slug}` : team.slug;\n groupMemberUsers.set(groupKey, memberNames);\n\n if (!team.members.pageInfo.hasNextPage) {\n // We got all the members in one go, run the fast path\n for (const user of team.members.nodes) {\n memberNames.push(user.login);\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(client, org, team.slug);\n for (const userLogin of members) {\n memberNames.push(userLogin);\n }\n }\n\n return entity;\n };\n\n const groups = await queryWithPaging(\n client,\n query,\n r => r.organization?.teams,\n mapper,\n { org },\n );\n\n return { groups, groupMemberUsers };\n}\n\nexport async function getOrganizationRepositories(\n client: typeof graphql,\n org: string,\n): Promise<{ repositories: Repository[] }> {\n const query = `\n query repositories($org: String!, $cursor: String) {\n repositoryOwner(login: $org) {\n login\n repositories(first: 100, after: $cursor) {\n nodes {\n name\n url\n isArchived\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 r => r.repositoryOwner?.repositories,\n x => x,\n { org },\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: string[] }> {\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 r => r.organization?.team?.members,\n user => user.login,\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 connection - A function that, given the response, picks out the actual\n * Connection object that's being iterated\n * @param mapper - 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 connection: (response: Response) => Connection<GraphqlType> | undefined,\n mapper: (item: GraphqlType) => Promise<OutputType> | OutputType,\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 result.push(await mapper(node));\n }\n\n if (!conn.pageInfo.hasNextPage) {\n break;\n } else {\n cursor = conn.pageInfo.endCursor;\n }\n }\n\n return result;\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 { GroupEntity, UserEntity } from '@backstage/catalog-model';\n\nexport function buildOrgHierarchy(groups: GroupEntity[]) {\n const groupsByName = new Map(groups.map(g => [g.metadata.name, g]));\n\n //\n // Make sure that g.parent.children contain g\n //\n\n for (const group of groups) {\n const selfName = group.metadata.name;\n const parentName = group.spec.parent;\n if (parentName) {\n const parent = groupsByName.get(parentName);\n if (parent && !parent.spec.children.includes(selfName)) {\n parent.spec.children.push(selfName);\n }\n }\n }\n\n //\n // Make sure that g.children.parent is g\n //\n\n for (const group of groups) {\n const selfName = group.metadata.name;\n for (const childName of group.spec.children) {\n const child = groupsByName.get(childName);\n if (child && !child.spec.parent) {\n child.spec.parent = selfName;\n }\n }\n }\n}\n\n// Ensure that users have their direct group memberships.\nexport function assignGroupsToUsers(\n users: UserEntity[],\n groupMemberUsers: Map<string, string[]>,\n) {\n const usersByName = new Map(users.map(u => [u.metadata.name, u]));\n for (const [groupName, userNames] of groupMemberUsers.entries()) {\n for (const userName of userNames) {\n const user = usersByName.get(userName);\n if (user && !user.spec.memberOf.includes(groupName)) {\n user.spec.memberOf.push(groupName);\n }\n }\n }\n}\n\n// Ensure that users have their transitive group memberships. Requires that\n// the groups were previously processed with buildOrgHierarchy()\nexport function buildMemberOf(groups: GroupEntity[], users: UserEntity[]) {\n const groupsByName = new Map(groups.map(g => [g.metadata.name, g]));\n\n users.forEach(user => {\n const transitiveMemberOf = new Set<string>();\n\n const todo = [\n ...user.spec.memberOf,\n ...groups\n .filter(g => g.spec.members?.includes(user.metadata.name))\n .map(g => g.metadata.name),\n ];\n\n for (;;) {\n const current = todo.pop();\n if (!current) {\n break;\n }\n\n if (!transitiveMemberOf.has(current)) {\n transitiveMemberOf.add(current);\n const group = groupsByName.get(current);\n if (group?.spec.parent) {\n todo.push(group.spec.parent);\n }\n }\n }\n\n user.spec.memberOf = [...transitiveMemberOf];\n });\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\nexport function parseGitHubOrgUrl(urlString: string): { org: string } {\n const path = new URL(urlString).pathname.substr(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","/*\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 { Config } from '@backstage/config';\nimport {\n DefaultGithubCredentialsProvider,\n GithubCredentialsProvider,\n ScmIntegrationRegistry,\n ScmIntegrations,\n} from '@backstage/integration';\nimport {\n CatalogProcessor,\n CatalogProcessorEmit,\n LocationSpec,\n processingResult,\n} from '@backstage/plugin-catalog-backend';\nimport { graphql } from '@octokit/graphql';\nimport { Logger } from 'winston';\nimport { getOrganizationRepositories } from './lib';\n\n/**\n * Extracts repositories out of a GitHub org.\n *\n * The following will create locations for all projects which have a catalog-info.yaml\n * on the default branch. The first is shorthand for the second.\n *\n * target: \"https://github.com/backstage\"\n * or\n * target: https://github.com/backstage/*\\/blob/-/catalog-info.yaml\n *\n * You may also explicitly specify the source branch:\n *\n * target: https://github.com/backstage/*\\/blob/main/catalog-info.yaml\n *\n * @public\n **/\nexport class GithubDiscoveryProcessor implements CatalogProcessor {\n private readonly integrations: ScmIntegrationRegistry;\n private readonly logger: Logger;\n private readonly githubCredentialsProvider: GithubCredentialsProvider;\n\n static fromConfig(\n config: Config,\n options: {\n logger: Logger;\n githubCredentialsProvider?: GithubCredentialsProvider;\n },\n ) {\n const integrations = ScmIntegrations.fromConfig(config);\n\n return new GithubDiscoveryProcessor({\n ...options,\n integrations,\n });\n }\n\n constructor(options: {\n integrations: ScmIntegrationRegistry;\n logger: Logger;\n githubCredentialsProvider?: GithubCredentialsProvider;\n }) {\n this.integrations = options.integrations;\n this.logger = options.logger;\n this.githubCredentialsProvider =\n options.githubCredentialsProvider ||\n DefaultGithubCredentialsProvider.fromIntegrations(this.integrations);\n }\n getProcessorName(): string {\n return 'GithubDiscoveryProcessor';\n }\n\n async readLocation(\n location: LocationSpec,\n _optional: boolean,\n emit: CatalogProcessorEmit,\n ): Promise<boolean> {\n if (location.type !== 'github-discovery') {\n return false;\n }\n\n const gitHubConfig = this.integrations.github.byUrl(\n location.target,\n )?.config;\n if (!gitHubConfig) {\n throw new Error(\n `There is no GitHub integration that matches ${location.target}. Please add a configuration entry for it under integrations.github`,\n );\n }\n\n const { org, repoSearchPath, catalogPath, branch, host } = parseUrl(\n location.target,\n );\n\n // Building the org url here so that the github creds provider doesn't need to know\n // about how to handle the wild card which is special for this processor.\n const orgUrl = `https://${host}/${org}`;\n\n const { headers } = await this.githubCredentialsProvider.getCredentials({\n url: orgUrl,\n });\n\n const client = graphql.defaults({\n baseUrl: gitHubConfig.apiBaseUrl,\n headers,\n });\n\n // Read out all of the raw data\n const startTimestamp = Date.now();\n this.logger.info(`Reading GitHub repositories from ${location.target}`);\n\n const { repositories } = await getOrganizationRepositories(client, org);\n const matching = repositories.filter(\n r => !r.isArchived && repoSearchPath.test(r.name),\n );\n\n const duration = ((Date.now() - startTimestamp) / 1000).toFixed(1);\n this.logger.debug(\n `Read ${repositories.length} GitHub repositories (${matching.length} matching the pattern) in ${duration} seconds`,\n );\n\n for (const repository of matching) {\n const branchName =\n branch === '-' ? repository.defaultBranchRef?.name : branch;\n\n if (!branchName) {\n this.logger.info(\n `the repository ${repository.url} does not have a default branch, skipping`,\n );\n continue;\n }\n\n const path = `/blob/${branchName}${catalogPath}`;\n\n emit(\n processingResult.location({\n type: 'url',\n target: `${repository.url}${path}`,\n // Not all locations may actually exist, since the user defined them as a wildcard pattern.\n // Thus, we emit them as optional and let the downstream processor find them while not outputting\n // an error if it couldn't.\n presence: 'optional',\n }),\n );\n }\n\n return true;\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.substr(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 branch: decodeURIComponent(path[3]),\n catalogPath: `/${decodeURIComponent(path.slice(4).join('/'))}`,\n host: url.host,\n };\n } else if (path.length === 1 && path[0].length) {\n return {\n org: decodeURIComponent(path[0]),\n host: url.host,\n repoSearchPath: escapeRegExp('*'),\n catalogPath: '/catalog-info.yaml',\n branch: '-',\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 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 { Config } from '@backstage/config';\nimport {\n DefaultGithubCredentialsProvider,\n GithubAppCredentialsMux,\n GithubCredentialsProvider,\n GitHubIntegrationConfig,\n ScmIntegrationRegistry,\n ScmIntegrations,\n} from '@backstage/integration';\nimport {\n CatalogProcessor,\n CatalogProcessorEmit,\n LocationSpec,\n processingResult,\n} from '@backstage/plugin-catalog-backend';\nimport { graphql } from '@octokit/graphql';\nimport { Logger } from 'winston';\nimport {\n buildOrgHierarchy,\n getOrganizationTeams,\n getOrganizationUsers,\n GithubMultiOrgConfig,\n readGithubMultiOrgConfig,\n} from './lib';\n\n/**\n * Extracts teams and users out of a multiple GitHub orgs namespaced per org.\n *\n * Be aware that this processor may not be compatible with future org structures in the catalog.\n *\n * @public\n */\nexport class GithubMultiOrgReaderProcessor implements CatalogProcessor {\n private readonly integrations: ScmIntegrationRegistry;\n private readonly orgs: GithubMultiOrgConfig;\n private readonly logger: Logger;\n private readonly githubCredentialsProvider: GithubCredentialsProvider;\n\n static fromConfig(\n config: Config,\n options: {\n logger: Logger;\n githubCredentialsProvider?: GithubCredentialsProvider;\n },\n ) {\n const c = config.getOptionalConfig('catalog.processors.githubMultiOrg');\n const integrations = ScmIntegrations.fromConfig(config);\n\n return new GithubMultiOrgReaderProcessor({\n ...options,\n integrations,\n orgs: c ? readGithubMultiOrgConfig(c) : [],\n });\n }\n\n constructor(options: {\n integrations: ScmIntegrationRegistry;\n logger: Logger;\n orgs: GithubMultiOrgConfig;\n githubCredentialsProvider?: GithubCredentialsProvider;\n }) {\n this.integrations = options.integrations;\n this.logger = options.logger;\n this.orgs = options.orgs;\n this.githubCredentialsProvider =\n options.githubCredentialsProvider ||\n DefaultGithubCredentialsProvider.fromIntegrations(this.integrations);\n }\n getProcessorName(): string {\n return 'GithubMultiOrgReaderProcessor';\n }\n\n async readLocation(\n location: LocationSpec,\n _optional: boolean,\n emit: CatalogProcessorEmit,\n ): Promise<boolean> {\n if (location.type !== 'github-multi-org') {\n return false;\n }\n\n const gitHubConfig = this.integrations.github.byUrl(\n location.target,\n )?.config;\n if (!gitHubConfig) {\n throw new Error(\n `There is no GitHub integration that matches ${location.target}. Please add a configuration entry for it under integrations.github`,\n );\n }\n\n const allUsersMap = new Map();\n const baseUrl = new URL(location.target).origin;\n\n const orgsToProcess = this.orgs.length\n ? this.orgs\n : await this.getAllOrgs(gitHubConfig);\n\n for (const orgConfig of orgsToProcess) {\n try {\n const { headers, type: tokenType } =\n await this.githubCredentialsProvider.getCredentials({\n url: `${baseUrl}/${orgConfig.name}`,\n });\n const client = graphql.defaults({\n baseUrl: gitHubConfig.apiBaseUrl,\n headers,\n });\n\n const startTimestamp = Date.now();\n this.logger.info(\n `Reading GitHub users and teams for org: ${orgConfig.name}`,\n );\n const { users } = await getOrganizationUsers(\n client,\n orgConfig.name,\n tokenType,\n orgConfig.userNamespace,\n );\n const { groups, groupMemberUsers } = await getOrganizationTeams(\n client,\n orgConfig.name,\n orgConfig.groupNamespace,\n );\n\n const duration = ((Date.now() - startTimestamp) / 1000).toFixed(1);\n this.logger.debug(\n `Read ${users.length} GitHub users and ${groups.length} GitHub teams from ${orgConfig.name} in ${duration} seconds`,\n );\n\n let prefix: string = orgConfig.userNamespace ?? '';\n if (prefix.length > 0) prefix += '/';\n\n users.forEach(u => {\n if (!allUsersMap.has(prefix + u.metadata.name)) {\n allUsersMap.set(prefix + u.metadata.name, u);\n }\n });\n\n for (const [groupName, userNames] of groupMemberUsers.entries()) {\n for (const userName of userNames) {\n const user = allUsersMap.get(prefix + userName);\n if (user && !user.spec.memberOf.includes(groupName)) {\n user.spec.memberOf.push(groupName);\n }\n }\n }\n buildOrgHierarchy(groups);\n\n for (const group of groups) {\n emit(processingResult.entity(location, group));\n }\n } catch (e) {\n this.logger.error(\n `Failed to read GitHub org data for ${orgConfig.name}: ${e}`,\n );\n }\n }\n\n const allUsers = Array.from(allUsersMap.values());\n for (const user of allUsers) {\n emit(processingResult.entity(location, user));\n }\n\n return true;\n }\n\n // Note: Does not support usage of PATs\n private async getAllOrgs(\n gitHubConfig: GitHubIntegrationConfig,\n ): Promise<GithubMultiOrgConfig> {\n const githubAppMux = new GithubAppCredentialsMux(gitHubConfig);\n const installs = await githubAppMux.getAllInstallations();\n\n return installs\n .map(install =>\n install.target_type === 'Organization' &&\n install.account &&\n install.account.login\n ? {\n name: install.account.login,\n groupNamespace: install.account.login.toLowerCase(),\n }\n : undefined,\n )\n .filter(Boolean) as GithubMultiOrgConfig;\n }\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 {\n ANNOTATION_LOCATION,\n ANNOTATION_ORIGIN_LOCATION,\n Entity,\n} from '@backstage/catalog-model';\nimport { Config } from '@backstage/config';\nimport {\n DefaultGithubCredentialsProvider,\n GithubCredentialsProvider,\n GitHubIntegrationConfig,\n ScmIntegrations,\n SingleInstanceGithubCredentialsProvider,\n} from '@backstage/integration';\nimport {\n EntityProvider,\n EntityProviderConnection,\n} from '@backstage/plugin-catalog-backend';\nimport { graphql } from '@octokit/graphql';\nimport { merge } from 'lodash';\nimport { Logger } from 'winston';\nimport {\n assignGroupsToUsers,\n buildOrgHierarchy,\n getOrganizationTeams,\n getOrganizationUsers,\n parseGitHubOrgUrl,\n} from './lib';\n\n// TODO: Consider supporting an (optional) webhook that reacts on org changes\n/** @public */\nexport class GitHubOrgEntityProvider implements EntityProvider {\n private connection?: EntityProviderConnection;\n private githubCredentialsProvider: GithubCredentialsProvider;\n\n static fromConfig(\n config: Config,\n options: {\n id: string;\n orgUrl: string;\n logger: Logger;\n githubCredentialsProvider?: GithubCredentialsProvider;\n },\n ) {\n const integrations = ScmIntegrations.fromConfig(config);\n const gitHubConfig = integrations.github.byUrl(options.orgUrl)?.config;\n\n if (!gitHubConfig) {\n throw new Error(\n `There is no GitHub Org provider that matches ${options.orgUrl}. Please add a configuration for an integration.`,\n );\n }\n\n const logger = options.logger.child({\n target: options.orgUrl,\n });\n\n return new GitHubOrgEntityProvider({\n id: options.id,\n orgUrl: options.orgUrl,\n logger,\n gitHubConfig,\n githubCredentialsProvider:\n options.githubCredentialsProvider ||\n DefaultGithubCredentialsProvider.fromIntegrations(integrations),\n });\n }\n\n constructor(\n private options: {\n id: string;\n orgUrl: string;\n gitHubConfig: GitHubIntegrationConfig;\n logger: Logger;\n githubCredentialsProvider?: GithubCredentialsProvider;\n },\n ) {\n this.githubCredentialsProvider =\n options.githubCredentialsProvider ||\n SingleInstanceGithubCredentialsProvider.create(options.gitHubConfig);\n }\n\n getProviderName() {\n return `GitHubOrgEntityProvider:${this.options.id}`;\n }\n\n async connect(connection: EntityProviderConnection) {\n this.connection = connection;\n }\n\n async read() {\n if (!this.connection) {\n throw new Error('Not initialized');\n }\n\n const { markReadComplete } = trackProgress(this.options.logger);\n\n const { headers, type: tokenType } =\n await this.githubCredentialsProvider.getCredentials({\n url: this.options.orgUrl,\n });\n const client = graphql.defaults({\n baseUrl: this.options.gitHubConfig.apiBaseUrl,\n headers,\n });\n\n const { org } = parseGitHubOrgUrl(this.options.orgUrl);\n const { users } = await getOrganizationUsers(client, org, tokenType);\n const { groups, groupMemberUsers } = await getOrganizationTeams(\n client,\n org,\n );\n assignGroupsToUsers(users, groupMemberUsers);\n buildOrgHierarchy(groups);\n\n const { markCommitComplete } = markReadComplete({ users, groups });\n\n await this.connection.applyMutation({\n type: 'full',\n entities: [...users, ...groups].map(entity => ({\n locationKey: `github-org-provider:${this.options.id}`,\n entity: withLocations(\n `https://${this.options.gitHubConfig.host}`,\n org,\n entity,\n ),\n })),\n });\n\n markCommitComplete();\n }\n}\n\n// Helps wrap the timing and logging behaviors\nfunction trackProgress(logger: Logger) {\n let timestamp = Date.now();\n let summary: string;\n\n logger.info('Reading GitHub users and groups');\n\n function markReadComplete(read: { users: unknown[]; groups: unknown[] }) {\n summary = `${read.users.length} GitHub users and ${read.groups.length} GitHub groups`;\n const readDuration = ((Date.now() - timestamp) / 1000).toFixed(1);\n timestamp = Date.now();\n logger.info(`Read ${summary} in ${readDuration} seconds. Committing...`);\n return { markCommitComplete };\n }\n\n function markCommitComplete() {\n const commitDuration = ((Date.now() - timestamp) / 1000).toFixed(1);\n logger.info(`Committed ${summary} in ${commitDuration} seconds.`);\n }\n\n return { markReadComplete };\n}\n\n// Makes sure that emitted entities have a proper location\nexport function withLocations(\n baseUrl: string,\n org: string,\n entity: Entity,\n): Entity {\n const location =\n entity.kind === 'Group'\n ? `url:${baseUrl}/orgs/${org}/teams/${entity.metadata.name}`\n : `url:${baseUrl}/${entity.metadata.name}`;\n return merge(\n {\n metadata: {\n annotations: {\n [ANNOTATION_LOCATION]: location,\n [ANNOTATION_ORIGIN_LOCATION]: location,\n },\n },\n },\n entity,\n ) as Entity;\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 { Config } from '@backstage/config';\nimport {\n DefaultGithubCredentialsProvider,\n GithubCredentialsProvider,\n GithubCredentialType,\n ScmIntegrationRegistry,\n ScmIntegrations,\n} from '@backstage/integration';\nimport {\n CatalogProcessor,\n CatalogProcessorEmit,\n LocationSpec,\n processingResult,\n} from '@backstage/plugin-catalog-backend';\nimport { graphql } from '@octokit/graphql';\nimport { Logger } from 'winston';\nimport {\n assignGroupsToUsers,\n buildOrgHierarchy,\n getOrganizationTeams,\n getOrganizationUsers,\n parseGitHubOrgUrl,\n} from './lib';\n\ntype GraphQL = typeof graphql;\n\n/**\n * Extracts teams and users out of a GitHub org.\n * @public\n */\nexport class GithubOrgReaderProcessor implements CatalogProcessor {\n private readonly integrations: ScmIntegrationRegistry;\n private readonly logger: Logger;\n private readonly githubCredentialsProvider: GithubCredentialsProvider;\n\n static fromConfig(\n config: Config,\n options: {\n logger: Logger;\n githubCredentialsProvider?: GithubCredentialsProvider;\n },\n ) {\n const integrations = ScmIntegrations.fromConfig(config);\n\n return new GithubOrgReaderProcessor({\n ...options,\n integrations,\n });\n }\n\n constructor(options: {\n integrations: ScmIntegrationRegistry;\n logger: Logger;\n githubCredentialsProvider?: GithubCredentialsProvider;\n }) {\n this.integrations = options.integrations;\n this.githubCredentialsProvider =\n options.githubCredentialsProvider ||\n DefaultGithubCredentialsProvider.fromIntegrations(this.integrations);\n this.logger = options.logger;\n }\n getProcessorName(): string {\n return 'GithubOrgReaderProcessor';\n }\n\n async readLocation(\n location: LocationSpec,\n _optional: boolean,\n emit: CatalogProcessorEmit,\n ): Promise<boolean> {\n if (location.type !== 'github-org') {\n return false;\n }\n\n const { client, tokenType } = await this.createClient(location.target);\n const { org } = parseGitHubOrgUrl(location.target);\n\n // Read out all of the raw data\n const startTimestamp = Date.now();\n this.logger.info('Reading GitHub users and groups');\n\n const { users } = await getOrganizationUsers(client, org, tokenType);\n const { groups, groupMemberUsers } = await getOrganizationTeams(\n client,\n org,\n );\n\n const duration = ((Date.now() - startTimestamp) / 1000).toFixed(1);\n this.logger.debug(\n `Read ${users.length} GitHub users and ${groups.length} GitHub groups in ${duration} seconds`,\n );\n\n assignGroupsToUsers(users, groupMemberUsers);\n buildOrgHierarchy(groups);\n\n // Done!\n for (const group of groups) {\n emit(processingResult.entity(location, group));\n }\n for (const user of users) {\n emit(processingResult.entity(location, user));\n }\n\n return true;\n }\n\n private async createClient(\n orgUrl: string,\n ): Promise<{ client: GraphQL; tokenType: GithubCredentialType }> {\n const gitHubConfig = this.integrations.github.byUrl(orgUrl)?.config;\n\n if (!gitHubConfig) {\n throw new Error(\n `There is no GitHub Org provider that matches ${orgUrl}. Please add a configuration for an integration.`,\n );\n }\n\n const { headers, type: tokenType } =\n await this.githubCredentialsProvider.getCredentials({\n url: orgUrl,\n });\n\n const client = graphql.defaults({\n baseUrl: gitHubConfig.apiBaseUrl,\n headers,\n });\n\n return { client, tokenType };\n }\n}\n"],"names":["ScmIntegrations","DefaultGithubCredentialsProvider","graphql","processingResult","GithubAppCredentialsMux","SingleInstanceGithubCredentialsProvider","merge","ANNOTATION_LOCATION","ANNOTATION_ORIGIN_LOCATION"],"mappings":";;;;;;;;;;kCAqCyC,QAAsC;AArC/E;AAsCE,QAAM,aAAa,aAAO,uBAAuB,YAA9B,YAAyC;AAC5D,SAAO,WAAW,IAAI,OAAE;AAvC1B;AAuC8B;AAAA,MAC1B,MAAM,EAAE,UAAU;AAAA,MAClB,gBACE,UAAE,kBAAkB,sBAApB,aAAyC,EAAE,UAAU,SACrD;AAAA,MACF,eAAe,QAAE,kBAAkB,qBAApB,YAAwC;AAAA;AAAA;AAAA;;oCCqCzD,QACA,KACA,WACA,eACkC;AAClC,QAAM,QAAQ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkBd,QAAM,SAAS,CAAC,SAAe;AAC7B,UAAM,SAAqB;AAAA,MACzB,YAAY;AAAA,MACZ,MAAM;AAAA,MACN,UAAU;AAAA,QACR,MAAM,KAAK;AAAA,QACX,aAAa;AAAA,UACX,yBAAyB,KAAK;AAAA;AAAA;AAAA,MAGlC,MAAM;AAAA,QACJ,SAAS;AAAA,QACT,UAAU;AAAA;AAAA;AAId,QAAI;AAAe,aAAO,SAAS,YAAY;AAC/C,QAAI,KAAK;AAAK,aAAO,SAAS,cAAc,KAAK;AACjD,QAAI,KAAK;AAAM,aAAO,KAAK,QAAS,cAAc,KAAK;AACvD,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e,WAAK,aAAa,OAAO,MAAM,YAA/B,mBAAwC;AAE7D,QAAI,CAAC,cAAc;AACjB,YAAM,IAAI,MACR,gDAAgD;AAAA;AAIpD,UAAM,EAAE,SAAS,MAAM,cACrB,MAAM,KAAK,0BAA0B,eAAe;AAAA,MAClD,KAAK;AAAA;AAGT,UAAM,SAASD,gBAAQ,SAAS;AAAA,MAC9B,SAAS,aAAa;AAAA,MACtB;AAAA;AAGF,WAAO,EAAE,QAAQ;AAAA;AAAA;;;;;;;"}
@@ -0,0 +1,130 @@
1
+ import { Config } from '@backstage/config';
2
+ import { GithubCredentialsProvider, ScmIntegrationRegistry, GitHubIntegrationConfig } from '@backstage/integration';
3
+ import { CatalogProcessor, LocationSpec, CatalogProcessorEmit, EntityProvider, EntityProviderConnection } from '@backstage/plugin-catalog-backend';
4
+ import { Logger } from 'winston';
5
+
6
+ /**
7
+ * Extracts repositories out of a GitHub org.
8
+ *
9
+ * The following will create locations for all projects which have a catalog-info.yaml
10
+ * on the default branch. The first is shorthand for the second.
11
+ *
12
+ * target: "https://github.com/backstage"
13
+ * or
14
+ * target: https://github.com/backstage/*\/blob/-/catalog-info.yaml
15
+ *
16
+ * You may also explicitly specify the source branch:
17
+ *
18
+ * target: https://github.com/backstage/*\/blob/main/catalog-info.yaml
19
+ *
20
+ * @public
21
+ **/
22
+ declare class GithubDiscoveryProcessor implements CatalogProcessor {
23
+ private readonly integrations;
24
+ private readonly logger;
25
+ private readonly githubCredentialsProvider;
26
+ static fromConfig(config: Config, options: {
27
+ logger: Logger;
28
+ githubCredentialsProvider?: GithubCredentialsProvider;
29
+ }): GithubDiscoveryProcessor;
30
+ constructor(options: {
31
+ integrations: ScmIntegrationRegistry;
32
+ logger: Logger;
33
+ githubCredentialsProvider?: GithubCredentialsProvider;
34
+ });
35
+ getProcessorName(): string;
36
+ readLocation(location: LocationSpec, _optional: boolean, emit: CatalogProcessorEmit): Promise<boolean>;
37
+ }
38
+
39
+ /**
40
+ * The configuration parameters for a multi-org GitHub processor.
41
+ * @public
42
+ */
43
+ declare type GithubMultiOrgConfig = Array<{
44
+ /**
45
+ * The name of the GitHub org to process.
46
+ */
47
+ name: string;
48
+ /**
49
+ * The namespace of the group created for this org.
50
+ */
51
+ groupNamespace: string;
52
+ /**
53
+ * The namespace of the users created for this org. If not specified defaults to undefined.
54
+ */
55
+ userNamespace: string | undefined;
56
+ }>;
57
+
58
+ /**
59
+ * Extracts teams and users out of a multiple GitHub orgs namespaced per org.
60
+ *
61
+ * Be aware that this processor may not be compatible with future org structures in the catalog.
62
+ *
63
+ * @public
64
+ */
65
+ declare class GithubMultiOrgReaderProcessor implements CatalogProcessor {
66
+ private readonly integrations;
67
+ private readonly orgs;
68
+ private readonly logger;
69
+ private readonly githubCredentialsProvider;
70
+ static fromConfig(config: Config, options: {
71
+ logger: Logger;
72
+ githubCredentialsProvider?: GithubCredentialsProvider;
73
+ }): GithubMultiOrgReaderProcessor;
74
+ constructor(options: {
75
+ integrations: ScmIntegrationRegistry;
76
+ logger: Logger;
77
+ orgs: GithubMultiOrgConfig;
78
+ githubCredentialsProvider?: GithubCredentialsProvider;
79
+ });
80
+ getProcessorName(): string;
81
+ readLocation(location: LocationSpec, _optional: boolean, emit: CatalogProcessorEmit): Promise<boolean>;
82
+ private getAllOrgs;
83
+ }
84
+
85
+ /** @public */
86
+ declare class GitHubOrgEntityProvider implements EntityProvider {
87
+ private options;
88
+ private connection?;
89
+ private githubCredentialsProvider;
90
+ static fromConfig(config: Config, options: {
91
+ id: string;
92
+ orgUrl: string;
93
+ logger: Logger;
94
+ githubCredentialsProvider?: GithubCredentialsProvider;
95
+ }): GitHubOrgEntityProvider;
96
+ constructor(options: {
97
+ id: string;
98
+ orgUrl: string;
99
+ gitHubConfig: GitHubIntegrationConfig;
100
+ logger: Logger;
101
+ githubCredentialsProvider?: GithubCredentialsProvider;
102
+ });
103
+ getProviderName(): string;
104
+ connect(connection: EntityProviderConnection): Promise<void>;
105
+ read(): Promise<void>;
106
+ }
107
+
108
+ /**
109
+ * Extracts teams and users out of a GitHub org.
110
+ * @public
111
+ */
112
+ declare class GithubOrgReaderProcessor implements CatalogProcessor {
113
+ private readonly integrations;
114
+ private readonly logger;
115
+ private readonly githubCredentialsProvider;
116
+ static fromConfig(config: Config, options: {
117
+ logger: Logger;
118
+ githubCredentialsProvider?: GithubCredentialsProvider;
119
+ }): GithubOrgReaderProcessor;
120
+ constructor(options: {
121
+ integrations: ScmIntegrationRegistry;
122
+ logger: Logger;
123
+ githubCredentialsProvider?: GithubCredentialsProvider;
124
+ });
125
+ getProcessorName(): string;
126
+ readLocation(location: LocationSpec, _optional: boolean, emit: CatalogProcessorEmit): Promise<boolean>;
127
+ private createClient;
128
+ }
129
+
130
+ export { GitHubOrgEntityProvider, GithubDiscoveryProcessor, GithubMultiOrgConfig, GithubMultiOrgReaderProcessor, GithubOrgReaderProcessor };
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@backstage/plugin-catalog-backend-module-github",
3
+ "description": "A Backstage catalog backend module that helps integrate towards GitHub",
4
+ "version": "0.0.0-nightly-20220311022539",
5
+ "main": "dist/index.cjs.js",
6
+ "types": "dist/index.d.ts",
7
+ "license": "Apache-2.0",
8
+ "private": false,
9
+ "publishConfig": {
10
+ "access": "public",
11
+ "main": "dist/index.cjs.js",
12
+ "types": "dist/index.d.ts"
13
+ },
14
+ "backstage": {
15
+ "role": "backend-plugin-module"
16
+ },
17
+ "homepage": "https://backstage.io",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "https://github.com/backstage/backstage",
21
+ "directory": "plugins/catalog-backend-module-github"
22
+ },
23
+ "keywords": [
24
+ "backstage"
25
+ ],
26
+ "scripts": {
27
+ "build": "backstage-cli package build",
28
+ "lint": "backstage-cli package lint",
29
+ "test": "backstage-cli package test",
30
+ "prepack": "backstage-cli package prepack",
31
+ "postpack": "backstage-cli package postpack",
32
+ "clean": "backstage-cli package clean",
33
+ "start": "backstage-cli package start"
34
+ },
35
+ "dependencies": {
36
+ "@backstage/backend-common": "^0.13.0",
37
+ "@backstage/catalog-model": "^0.0.0-nightly-20220311022539",
38
+ "@backstage/config": "^0.1.15",
39
+ "@backstage/errors": "^0.2.2",
40
+ "@backstage/integration": "^0.8.0",
41
+ "@backstage/plugin-catalog-backend": "^0.0.0-nightly-20220311022539",
42
+ "@backstage/types": "^0.1.3",
43
+ "@octokit/graphql": "^4.5.8",
44
+ "lodash": "^4.17.21",
45
+ "msw": "^0.35.0",
46
+ "node-fetch": "^2.6.7",
47
+ "winston": "^3.2.1"
48
+ },
49
+ "devDependencies": {
50
+ "@backstage/backend-test-utils": "^0.1.21",
51
+ "@backstage/cli": "^0.15.2",
52
+ "@types/lodash": "^4.14.151"
53
+ },
54
+ "files": [
55
+ "dist"
56
+ ]
57
+ }