@backstage/plugin-catalog-backend-module-gitlab 0.1.13-next.0 → 0.1.13-next.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/alpha/package.json +1 -1
- package/config.d.ts +12 -0
- package/dist/index.alpha.d.ts +26 -0
- package/dist/index.beta.d.ts +26 -0
- package/dist/index.cjs.js +290 -4
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +26 -0
- package/package.json +8 -8
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# @backstage/plugin-catalog-backend-module-gitlab
|
|
2
2
|
|
|
3
|
+
## 0.1.13-next.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 85b04f659a: Internal refactor to not use deprecated `substr`
|
|
8
|
+
- 52c5685ceb: Implement Group and User Catalog Provider
|
|
9
|
+
- Updated dependencies
|
|
10
|
+
- @backstage/plugin-catalog-backend@1.7.2-next.1
|
|
11
|
+
- @backstage/backend-common@0.18.2-next.1
|
|
12
|
+
- @backstage/backend-plugin-api@0.3.2-next.1
|
|
13
|
+
- @backstage/backend-tasks@0.4.3-next.1
|
|
14
|
+
- @backstage/catalog-model@1.1.6-next.0
|
|
15
|
+
- @backstage/config@1.0.6
|
|
16
|
+
- @backstage/errors@1.1.4
|
|
17
|
+
- @backstage/integration@1.4.2
|
|
18
|
+
- @backstage/types@1.0.2
|
|
19
|
+
- @backstage/plugin-catalog-node@1.3.3-next.1
|
|
20
|
+
|
|
3
21
|
## 0.1.13-next.0
|
|
4
22
|
|
|
5
23
|
### Patch Changes
|
package/alpha/package.json
CHANGED
package/config.d.ts
CHANGED
|
@@ -48,6 +48,18 @@ export interface Config {
|
|
|
48
48
|
* (Optional) TaskScheduleDefinition for the refresh.
|
|
49
49
|
*/
|
|
50
50
|
schedule?: TaskScheduleDefinitionConfig;
|
|
51
|
+
/**
|
|
52
|
+
* (Optional) RegExp for the Project Name Pattern
|
|
53
|
+
*/
|
|
54
|
+
projectPattern?: RegExp;
|
|
55
|
+
/**
|
|
56
|
+
* (Optional) RegExp for the User Name Pattern
|
|
57
|
+
*/
|
|
58
|
+
userPattern?: RegExp;
|
|
59
|
+
/**
|
|
60
|
+
* (Optional) RegExp for the Group Name Pattern
|
|
61
|
+
*/
|
|
62
|
+
groupPattern?: RegExp;
|
|
51
63
|
}
|
|
52
64
|
>;
|
|
53
65
|
};
|
package/dist/index.alpha.d.ts
CHANGED
|
@@ -64,4 +64,30 @@ export declare class GitLabDiscoveryProcessor implements CatalogProcessor {
|
|
|
64
64
|
private getCacheKey;
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
+
/**
|
|
68
|
+
* Discovers users and groups from a Gitlab instance.
|
|
69
|
+
* @public
|
|
70
|
+
*/
|
|
71
|
+
export declare class GitlabOrgDiscoveryEntityProvider implements EntityProvider {
|
|
72
|
+
private readonly config;
|
|
73
|
+
private readonly integration;
|
|
74
|
+
private readonly logger;
|
|
75
|
+
private readonly scheduleFn;
|
|
76
|
+
private connection?;
|
|
77
|
+
static fromConfig(config: Config, options: {
|
|
78
|
+
logger: Logger;
|
|
79
|
+
schedule?: TaskRunner;
|
|
80
|
+
scheduler?: PluginTaskScheduler;
|
|
81
|
+
}): GitlabOrgDiscoveryEntityProvider[];
|
|
82
|
+
private constructor();
|
|
83
|
+
getProviderName(): string;
|
|
84
|
+
connect(connection: EntityProviderConnection): Promise<void>;
|
|
85
|
+
private createScheduleFn;
|
|
86
|
+
private refresh;
|
|
87
|
+
private createGroupEntities;
|
|
88
|
+
private withLocations;
|
|
89
|
+
private createUserEntity;
|
|
90
|
+
private createGroupEntity;
|
|
91
|
+
}
|
|
92
|
+
|
|
67
93
|
export { }
|
package/dist/index.beta.d.ts
CHANGED
|
@@ -59,4 +59,30 @@ export declare class GitLabDiscoveryProcessor implements CatalogProcessor {
|
|
|
59
59
|
private getCacheKey;
|
|
60
60
|
}
|
|
61
61
|
|
|
62
|
+
/**
|
|
63
|
+
* Discovers users and groups from a Gitlab instance.
|
|
64
|
+
* @public
|
|
65
|
+
*/
|
|
66
|
+
export declare class GitlabOrgDiscoveryEntityProvider implements EntityProvider {
|
|
67
|
+
private readonly config;
|
|
68
|
+
private readonly integration;
|
|
69
|
+
private readonly logger;
|
|
70
|
+
private readonly scheduleFn;
|
|
71
|
+
private connection?;
|
|
72
|
+
static fromConfig(config: Config, options: {
|
|
73
|
+
logger: Logger;
|
|
74
|
+
schedule?: TaskRunner;
|
|
75
|
+
scheduler?: PluginTaskScheduler;
|
|
76
|
+
}): GitlabOrgDiscoveryEntityProvider[];
|
|
77
|
+
private constructor();
|
|
78
|
+
getProviderName(): string;
|
|
79
|
+
connect(connection: EntityProviderConnection): Promise<void>;
|
|
80
|
+
private createScheduleFn;
|
|
81
|
+
private refresh;
|
|
82
|
+
private createGroupEntities;
|
|
83
|
+
private withLocations;
|
|
84
|
+
private createUserEntity;
|
|
85
|
+
private createGroupEntity;
|
|
86
|
+
}
|
|
87
|
+
|
|
62
88
|
export { }
|
package/dist/index.cjs.js
CHANGED
|
@@ -8,6 +8,8 @@ var pluginCatalogBackend = require('@backstage/plugin-catalog-backend');
|
|
|
8
8
|
var fetch = require('node-fetch');
|
|
9
9
|
var backendTasks = require('@backstage/backend-tasks');
|
|
10
10
|
var uuid = require('uuid');
|
|
11
|
+
var catalogModel = require('@backstage/catalog-model');
|
|
12
|
+
var lodash = require('lodash');
|
|
11
13
|
var backendPluginApi = require('@backstage/backend-plugin-api');
|
|
12
14
|
var pluginCatalogNode = require('@backstage/plugin-catalog-node');
|
|
13
15
|
|
|
@@ -57,6 +59,38 @@ class GitLabClient {
|
|
|
57
59
|
}
|
|
58
60
|
return this.pagedRequest(`/projects`, options);
|
|
59
61
|
}
|
|
62
|
+
async listUsers(options) {
|
|
63
|
+
let requestOptions = options;
|
|
64
|
+
if (!requestOptions) {
|
|
65
|
+
requestOptions = {};
|
|
66
|
+
}
|
|
67
|
+
requestOptions.without_project_bots = true;
|
|
68
|
+
requestOptions.exclude_internal = true;
|
|
69
|
+
return this.pagedRequest(`/users?`, requestOptions);
|
|
70
|
+
}
|
|
71
|
+
async listGroups(options) {
|
|
72
|
+
return this.pagedRequest(`/groups`, options);
|
|
73
|
+
}
|
|
74
|
+
async getUserMemberships(userId) {
|
|
75
|
+
const endpoint = `/users/${encodeURIComponent(userId)}/memberships`;
|
|
76
|
+
const request = new URL(`${this.config.apiBaseUrl}${endpoint}`);
|
|
77
|
+
request.searchParams.append("per_page", "100");
|
|
78
|
+
const response = await fetch__default["default"](request.toString(), {
|
|
79
|
+
headers: integration.getGitLabRequestOptions(this.config).headers,
|
|
80
|
+
method: "GET"
|
|
81
|
+
});
|
|
82
|
+
if (!response.ok) {
|
|
83
|
+
if (response.status >= 500) {
|
|
84
|
+
this.logger.debug(
|
|
85
|
+
`Unexpected response when fetching ${request.toString()}. Expected 200 but got ${response.status} - ${response.statusText}`
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
return [];
|
|
89
|
+
}
|
|
90
|
+
return response.json().then((items) => {
|
|
91
|
+
return items;
|
|
92
|
+
});
|
|
93
|
+
}
|
|
60
94
|
/**
|
|
61
95
|
* General existence check.
|
|
62
96
|
*
|
|
@@ -134,7 +168,7 @@ async function* paginated(request, options) {
|
|
|
134
168
|
}
|
|
135
169
|
|
|
136
170
|
function readGitlabConfig(id, config) {
|
|
137
|
-
var _a, _b, _c, _d;
|
|
171
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
138
172
|
const group = (_a = config.getOptionalString("group")) != null ? _a : "";
|
|
139
173
|
const host = config.getString("host");
|
|
140
174
|
const branch = (_b = config.getOptionalString("branch")) != null ? _b : "master";
|
|
@@ -142,6 +176,13 @@ function readGitlabConfig(id, config) {
|
|
|
142
176
|
const projectPattern = new RegExp(
|
|
143
177
|
(_d = config.getOptionalString("projectPattern")) != null ? _d : /[\s\S]*/
|
|
144
178
|
);
|
|
179
|
+
const userPattern = new RegExp(
|
|
180
|
+
(_e = config.getOptionalString("userPattern")) != null ? _e : /[\s\S]*/
|
|
181
|
+
);
|
|
182
|
+
const groupPattern = new RegExp(
|
|
183
|
+
(_f = config.getOptionalString("groupPattern")) != null ? _f : /[\s\S]*/
|
|
184
|
+
);
|
|
185
|
+
const orgEnabled = (_g = config.getOptionalBoolean("orgEnabled")) != null ? _g : false;
|
|
145
186
|
const schedule = config.has("schedule") ? backendTasks.readTaskScheduleDefinitionFromConfig(config.getConfig("schedule")) : void 0;
|
|
146
187
|
return {
|
|
147
188
|
id,
|
|
@@ -150,7 +191,10 @@ function readGitlabConfig(id, config) {
|
|
|
150
191
|
host,
|
|
151
192
|
catalogFile,
|
|
152
193
|
projectPattern,
|
|
153
|
-
|
|
194
|
+
userPattern,
|
|
195
|
+
groupPattern,
|
|
196
|
+
schedule,
|
|
197
|
+
orgEnabled
|
|
154
198
|
};
|
|
155
199
|
}
|
|
156
200
|
function readGitlabConfigs(config) {
|
|
@@ -188,7 +232,7 @@ class GitLabDiscoveryProcessor {
|
|
|
188
232
|
if (location.type !== "gitlab-discovery") {
|
|
189
233
|
return false;
|
|
190
234
|
}
|
|
191
|
-
const startTime = new Date();
|
|
235
|
+
const startTime = /* @__PURE__ */ new Date();
|
|
192
236
|
const { group, host, branch, catalogPath } = parseUrl(location.target);
|
|
193
237
|
const integration = this.integrations.gitlab.byUrl(`https://${host}`);
|
|
194
238
|
if (!integration) {
|
|
@@ -264,7 +308,7 @@ class GitLabDiscoveryProcessor {
|
|
|
264
308
|
}
|
|
265
309
|
function parseUrl(urlString) {
|
|
266
310
|
const url = new URL(urlString);
|
|
267
|
-
const path = url.pathname.
|
|
311
|
+
const path = url.pathname.slice(1).split("/");
|
|
268
312
|
const blobIndex = path.findIndex((p) => p === "blob");
|
|
269
313
|
if (blobIndex !== -1 && path.length > blobIndex + 2) {
|
|
270
314
|
const group = blobIndex > 0 ? path.slice(0, blobIndex).join("/") : void 0;
|
|
@@ -410,6 +454,247 @@ class GitlabDiscoveryEntityProvider {
|
|
|
410
454
|
}
|
|
411
455
|
}
|
|
412
456
|
|
|
457
|
+
class GitlabOrgDiscoveryEntityProvider {
|
|
458
|
+
static fromConfig(config, options) {
|
|
459
|
+
if (!options.schedule && !options.scheduler) {
|
|
460
|
+
throw new Error("Either schedule or scheduler must be provided.");
|
|
461
|
+
}
|
|
462
|
+
const providerConfigs = readGitlabConfigs(config);
|
|
463
|
+
const integrations = integration.ScmIntegrations.fromConfig(config).gitlab;
|
|
464
|
+
const providers = [];
|
|
465
|
+
providerConfigs.forEach((providerConfig) => {
|
|
466
|
+
var _a;
|
|
467
|
+
const integration = integrations.byHost(providerConfig.host);
|
|
468
|
+
if (!providerConfig.orgEnabled) {
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
if (!integration) {
|
|
472
|
+
throw new Error(
|
|
473
|
+
`No gitlab integration found that matches host ${providerConfig.host}`
|
|
474
|
+
);
|
|
475
|
+
}
|
|
476
|
+
if (!options.schedule && !providerConfig.schedule) {
|
|
477
|
+
throw new Error(
|
|
478
|
+
`No schedule provided neither via code nor config for GitlabOrgDiscoveryEntityProvider:${providerConfig.id}.`
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
const taskRunner = (_a = options.schedule) != null ? _a : options.scheduler.createScheduledTaskRunner(providerConfig.schedule);
|
|
482
|
+
providers.push(
|
|
483
|
+
new GitlabOrgDiscoveryEntityProvider({
|
|
484
|
+
...options,
|
|
485
|
+
config: providerConfig,
|
|
486
|
+
integration,
|
|
487
|
+
taskRunner
|
|
488
|
+
})
|
|
489
|
+
);
|
|
490
|
+
});
|
|
491
|
+
return providers;
|
|
492
|
+
}
|
|
493
|
+
constructor(options) {
|
|
494
|
+
this.config = options.config;
|
|
495
|
+
this.integration = options.integration;
|
|
496
|
+
this.logger = options.logger.child({
|
|
497
|
+
target: this.getProviderName()
|
|
498
|
+
});
|
|
499
|
+
this.scheduleFn = this.createScheduleFn(options.taskRunner);
|
|
500
|
+
}
|
|
501
|
+
getProviderName() {
|
|
502
|
+
return `GitlabOrgDiscoveryEntityProvider:${this.config.id}`;
|
|
503
|
+
}
|
|
504
|
+
async connect(connection) {
|
|
505
|
+
this.connection = connection;
|
|
506
|
+
await this.scheduleFn();
|
|
507
|
+
}
|
|
508
|
+
createScheduleFn(taskRunner) {
|
|
509
|
+
return async () => {
|
|
510
|
+
const taskId = `${this.getProviderName()}:refresh`;
|
|
511
|
+
return taskRunner.run({
|
|
512
|
+
id: taskId,
|
|
513
|
+
fn: async () => {
|
|
514
|
+
const logger = this.logger.child({
|
|
515
|
+
class: GitlabOrgDiscoveryEntityProvider.prototype.constructor.name,
|
|
516
|
+
taskId,
|
|
517
|
+
taskInstanceId: uuid__namespace.v4()
|
|
518
|
+
});
|
|
519
|
+
try {
|
|
520
|
+
await this.refresh(logger);
|
|
521
|
+
} catch (error) {
|
|
522
|
+
logger.error(`${this.getProviderName()} refresh failed`, error);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
});
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
async refresh(logger) {
|
|
529
|
+
var _a, _b, _c;
|
|
530
|
+
if (!this.connection) {
|
|
531
|
+
throw new Error(
|
|
532
|
+
`Gitlab discovery connection not initialized for ${this.getProviderName()}`
|
|
533
|
+
);
|
|
534
|
+
}
|
|
535
|
+
const client = new GitLabClient({
|
|
536
|
+
config: this.integration.config,
|
|
537
|
+
logger
|
|
538
|
+
});
|
|
539
|
+
const users = paginated((options) => client.listUsers(options), {
|
|
540
|
+
page: 1,
|
|
541
|
+
per_page: 100,
|
|
542
|
+
active: true
|
|
543
|
+
});
|
|
544
|
+
const groups = paginated(
|
|
545
|
+
(options) => client.listGroups(options),
|
|
546
|
+
{
|
|
547
|
+
page: 1,
|
|
548
|
+
per_page: 100
|
|
549
|
+
}
|
|
550
|
+
);
|
|
551
|
+
const idMappedGroup = {};
|
|
552
|
+
const res = {
|
|
553
|
+
scanned: 0,
|
|
554
|
+
matches: []
|
|
555
|
+
};
|
|
556
|
+
const groupRes = {
|
|
557
|
+
scanned: 0,
|
|
558
|
+
matches: []
|
|
559
|
+
};
|
|
560
|
+
for await (const group of groups) {
|
|
561
|
+
if (!this.config.groupPattern.test((_a = group.full_path) != null ? _a : "")) {
|
|
562
|
+
continue;
|
|
563
|
+
}
|
|
564
|
+
groupRes.scanned++;
|
|
565
|
+
groupRes.matches.push(group);
|
|
566
|
+
idMappedGroup[group.id] = group;
|
|
567
|
+
}
|
|
568
|
+
for await (const user of users) {
|
|
569
|
+
if (!this.config.userPattern.test((_c = (_b = user.email) != null ? _b : user.username) != null ? _c : "")) {
|
|
570
|
+
continue;
|
|
571
|
+
}
|
|
572
|
+
res.scanned++;
|
|
573
|
+
if (user.state !== "active") {
|
|
574
|
+
continue;
|
|
575
|
+
}
|
|
576
|
+
const memberships = await client.getUserMemberships(user.id);
|
|
577
|
+
const userGroups = [];
|
|
578
|
+
for (const i of memberships) {
|
|
579
|
+
if (i.source_type === "Namespace" && idMappedGroup.hasOwnProperty(i.source_id)) {
|
|
580
|
+
userGroups.push(idMappedGroup[i.source_id]);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
user.groups = userGroups;
|
|
584
|
+
res.matches.push(user);
|
|
585
|
+
}
|
|
586
|
+
const groupsWithUsers = groupRes.matches.filter((group) => {
|
|
587
|
+
return res.matches.filter((x) => {
|
|
588
|
+
var _a2;
|
|
589
|
+
return !!((_a2 = x.groups) == null ? void 0 : _a2.find((y) => y.id === group.id));
|
|
590
|
+
}).length > 0;
|
|
591
|
+
});
|
|
592
|
+
const userEntities = res.matches.map(
|
|
593
|
+
(p) => this.createUserEntity(p, this.integration.config.host)
|
|
594
|
+
);
|
|
595
|
+
const groupEntities = this.createGroupEntities(
|
|
596
|
+
groupsWithUsers,
|
|
597
|
+
this.integration.config.host
|
|
598
|
+
);
|
|
599
|
+
await this.connection.applyMutation({
|
|
600
|
+
type: "full",
|
|
601
|
+
entities: [...userEntities, ...groupEntities].map((entity) => ({
|
|
602
|
+
locationKey: this.getProviderName(),
|
|
603
|
+
entity: this.withLocations(this.integration.config.host, entity)
|
|
604
|
+
}))
|
|
605
|
+
});
|
|
606
|
+
}
|
|
607
|
+
createGroupEntities(groupResult, host) {
|
|
608
|
+
const idMapped = {};
|
|
609
|
+
const entities = [];
|
|
610
|
+
for (const group of groupResult) {
|
|
611
|
+
idMapped[group.id] = group;
|
|
612
|
+
}
|
|
613
|
+
for (const group of groupResult) {
|
|
614
|
+
const entity = this.createGroupEntity(group, host);
|
|
615
|
+
if (group.parent_id && idMapped.hasOwnProperty(group.parent_id)) {
|
|
616
|
+
entity.spec.parent = idMapped[group.parent_id].full_path;
|
|
617
|
+
}
|
|
618
|
+
entities.push(entity);
|
|
619
|
+
}
|
|
620
|
+
return entities;
|
|
621
|
+
}
|
|
622
|
+
withLocations(host, entity) {
|
|
623
|
+
const location = entity.kind === "Group" ? `url:${host}/teams/${entity.metadata.name}` : `url:${host}/${entity.metadata.name}`;
|
|
624
|
+
return lodash.merge(
|
|
625
|
+
{
|
|
626
|
+
metadata: {
|
|
627
|
+
annotations: {
|
|
628
|
+
[catalogModel.ANNOTATION_LOCATION]: location,
|
|
629
|
+
[catalogModel.ANNOTATION_ORIGIN_LOCATION]: location
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
},
|
|
633
|
+
entity
|
|
634
|
+
);
|
|
635
|
+
}
|
|
636
|
+
createUserEntity(user, host) {
|
|
637
|
+
const annotations = {};
|
|
638
|
+
annotations[`${host}/user-login`] = user.web_url;
|
|
639
|
+
const entity = {
|
|
640
|
+
apiVersion: "backstage.io/v1alpha1",
|
|
641
|
+
kind: "User",
|
|
642
|
+
metadata: {
|
|
643
|
+
name: user.username,
|
|
644
|
+
annotations
|
|
645
|
+
},
|
|
646
|
+
spec: {
|
|
647
|
+
profile: {
|
|
648
|
+
displayName: user.name,
|
|
649
|
+
picture: user.avatar_url
|
|
650
|
+
},
|
|
651
|
+
memberOf: []
|
|
652
|
+
}
|
|
653
|
+
};
|
|
654
|
+
if (user.email) {
|
|
655
|
+
if (!entity.spec) {
|
|
656
|
+
entity.spec = {};
|
|
657
|
+
}
|
|
658
|
+
if (!entity.spec.profile) {
|
|
659
|
+
entity.spec.profile = {};
|
|
660
|
+
}
|
|
661
|
+
entity.spec.profile.email = user.email;
|
|
662
|
+
}
|
|
663
|
+
if (user.groups) {
|
|
664
|
+
for (const group of user.groups) {
|
|
665
|
+
if (!entity.spec.memberOf) {
|
|
666
|
+
entity.spec.memberOf = [];
|
|
667
|
+
}
|
|
668
|
+
entity.spec.memberOf.push(group.full_path.replace("/", "-"));
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
return entity;
|
|
672
|
+
}
|
|
673
|
+
createGroupEntity(group, host) {
|
|
674
|
+
const annotations = {};
|
|
675
|
+
annotations[`${host}/team-path`] = group.full_path;
|
|
676
|
+
const entity = {
|
|
677
|
+
apiVersion: "backstage.io/v1alpha1",
|
|
678
|
+
kind: "Group",
|
|
679
|
+
metadata: {
|
|
680
|
+
name: group.full_path.replace("/", "-"),
|
|
681
|
+
annotations
|
|
682
|
+
},
|
|
683
|
+
spec: {
|
|
684
|
+
type: "team",
|
|
685
|
+
children: [],
|
|
686
|
+
profile: {
|
|
687
|
+
displayName: group.name
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
};
|
|
691
|
+
if (group.description) {
|
|
692
|
+
entity.metadata.description = group.description;
|
|
693
|
+
}
|
|
694
|
+
return entity;
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
|
|
413
698
|
const gitlabDiscoveryEntityProviderCatalogModule = backendPluginApi.createBackendModule({
|
|
414
699
|
pluginId: "catalog",
|
|
415
700
|
moduleId: "gitlabDiscoveryEntityProvider",
|
|
@@ -435,5 +720,6 @@ const gitlabDiscoveryEntityProviderCatalogModule = backendPluginApi.createBacken
|
|
|
435
720
|
|
|
436
721
|
exports.GitLabDiscoveryProcessor = GitLabDiscoveryProcessor;
|
|
437
722
|
exports.GitlabDiscoveryEntityProvider = GitlabDiscoveryEntityProvider;
|
|
723
|
+
exports.GitlabOrgDiscoveryEntityProvider = GitlabOrgDiscoveryEntityProvider;
|
|
438
724
|
exports.gitlabDiscoveryEntityProviderCatalogModule = gitlabDiscoveryEntityProviderCatalogModule;
|
|
439
725
|
//# sourceMappingURL=index.cjs.js.map
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../src/lib/client.ts","../src/providers/config.ts","../src/GitLabDiscoveryProcessor.ts","../src/providers/GitlabDiscoveryEntityProvider.ts","../src/service/GitlabDiscoveryEntityProviderCatalogModule.ts"],"sourcesContent":["/*\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 fetch from 'node-fetch';\nimport {\n getGitLabRequestOptions,\n GitLabIntegrationConfig,\n} from '@backstage/integration';\nimport { Logger } from 'winston';\n\nexport type ListOptions = {\n [key: string]: string | number | boolean | undefined;\n group?: string;\n per_page?: number | undefined;\n page?: number | undefined;\n};\n\nexport type PagedResponse<T> = {\n items: T[];\n nextPage?: number;\n};\n\nexport class GitLabClient {\n private readonly config: GitLabIntegrationConfig;\n private readonly logger: Logger;\n\n constructor(options: { config: GitLabIntegrationConfig; logger: Logger }) {\n this.config = options.config;\n this.logger = options.logger;\n }\n\n /**\n * Indicates whether the client is for a SaaS or self managed GitLab instance.\n */\n isSelfManaged(): boolean {\n return this.config.host !== 'gitlab.com';\n }\n\n async listProjects(options?: ListOptions): Promise<PagedResponse<any>> {\n if (options?.group) {\n return this.pagedRequest(\n `/groups/${encodeURIComponent(options?.group)}/projects`,\n {\n ...options,\n include_subgroups: true,\n },\n );\n }\n\n return this.pagedRequest(`/projects`, options);\n }\n\n /**\n * General existence check.\n *\n * @param projectPath - The path to the project\n * @param branch - The branch used to search\n * @param filePath - The path to the file\n */\n async hasFile(\n projectPath: string,\n branch: string,\n filePath: string,\n ): Promise<boolean> {\n const endpoint: string = `/projects/${encodeURIComponent(\n projectPath,\n )}/repository/files/${encodeURIComponent(filePath)}`;\n const request = new URL(`${this.config.apiBaseUrl}${endpoint}`);\n request.searchParams.append('ref', branch);\n\n const response = await fetch(request.toString(), {\n headers: getGitLabRequestOptions(this.config).headers,\n method: 'HEAD',\n });\n\n if (!response.ok) {\n if (response.status >= 500) {\n this.logger.debug(\n `Unexpected response when fetching ${request.toString()}. Expected 200 but got ${\n response.status\n } - ${response.statusText}`,\n );\n }\n return false;\n }\n\n return true;\n }\n\n /**\n * Performs a request against a given paginated GitLab endpoint.\n *\n * This method may be used to perform authenticated REST calls against any\n * paginated GitLab endpoint which uses X-NEXT-PAGE headers. The return value\n * can be be used with the {@link paginated} async-generator function to yield\n * each item from the paged request.\n *\n * @see {@link paginated}\n * @param endpoint - The request endpoint, e.g. /projects.\n * @param options - Request queryString options which may also include page variables.\n */\n async pagedRequest<T = any>(\n endpoint: string,\n options?: ListOptions,\n ): Promise<PagedResponse<T>> {\n const request = new URL(`${this.config.apiBaseUrl}${endpoint}`);\n for (const key in options) {\n if (options[key]) {\n request.searchParams.append(key, options[key]!.toString());\n }\n }\n\n this.logger.debug(`Fetching: ${request.toString()}`);\n const response = await fetch(\n request.toString(),\n getGitLabRequestOptions(this.config),\n );\n if (!response.ok) {\n throw new Error(\n `Unexpected response when fetching ${request.toString()}. Expected 200 but got ${\n response.status\n } - ${response.statusText}`,\n );\n }\n return response.json().then(items => {\n const nextPage = response.headers.get('x-next-page');\n\n return {\n items,\n nextPage: nextPage ? Number(nextPage) : null,\n } as PagedResponse<any>;\n });\n }\n}\n\n/**\n * Advances through each page and provides each item from a paginated request.\n *\n * The async generator function yields each item from repeated calls to the\n * provided request function. The generator walks through each available page by\n * setting the page key in the options passed into the request function and\n * making repeated calls until there are no more pages.\n *\n * @see {@link pagedRequest}\n * @param request - Function which returns a PagedResponse to walk through.\n * @param options - Initial ListOptions for the request function.\n */\nexport async function* paginated<T = any>(\n request: (options: ListOptions) => Promise<PagedResponse<T>>,\n options: ListOptions,\n) {\n let res;\n do {\n res = await request(options);\n options.page = res.nextPage;\n for (const item of res.items) {\n yield item;\n }\n } while (res.nextPage);\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 { readTaskScheduleDefinitionFromConfig } from '@backstage/backend-tasks';\nimport { Config } from '@backstage/config';\nimport { GitlabProviderConfig } from '../lib';\n\n/**\n * Extracts the gitlab config from a config object\n *\n * @public\n *\n * @param id - The provider key\n * @param config - The config object to extract from\n */\nfunction readGitlabConfig(id: string, config: Config): GitlabProviderConfig {\n const group = config.getOptionalString('group') ?? '';\n const host = config.getString('host');\n const branch = config.getOptionalString('branch') ?? 'master';\n const catalogFile =\n config.getOptionalString('entityFilename') ?? 'catalog-info.yaml';\n const projectPattern = new RegExp(\n config.getOptionalString('projectPattern') ?? /[\\s\\S]*/,\n );\n\n const schedule = config.has('schedule')\n ? readTaskScheduleDefinitionFromConfig(config.getConfig('schedule'))\n : undefined;\n\n return {\n id,\n group,\n branch,\n host,\n catalogFile,\n projectPattern,\n schedule,\n };\n}\n\n/**\n * Extracts the gitlab config from a config object array\n *\n * @public\n *\n * @param config - The config object to extract from\n */\nexport function readGitlabConfigs(config: Config): GitlabProviderConfig[] {\n const configs: GitlabProviderConfig[] = [];\n\n const providerConfigs = config.getOptionalConfig('catalog.providers.gitlab');\n\n if (!providerConfigs) {\n return configs;\n }\n\n for (const id of providerConfigs.keys()) {\n configs.push(readGitlabConfig(id, providerConfigs.getConfig(id)));\n }\n\n return configs;\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 CacheClient,\n CacheManager,\n PluginCacheManager,\n} from '@backstage/backend-common';\nimport { Config } from '@backstage/config';\nimport {\n ScmIntegrationRegistry,\n ScmIntegrations,\n} from '@backstage/integration';\nimport {\n CatalogProcessor,\n CatalogProcessorEmit,\n LocationSpec,\n processingResult,\n} from '@backstage/plugin-catalog-backend';\nimport { Logger } from 'winston';\nimport { GitLabClient, GitLabProject, paginated } from './lib';\n\n/**\n * Extracts repositories out of an GitLab instance.\n * @public\n */\nexport class GitLabDiscoveryProcessor implements CatalogProcessor {\n private readonly integrations: ScmIntegrationRegistry;\n private readonly logger: Logger;\n private readonly cache: CacheClient;\n private readonly skipReposWithoutExactFileMatch: boolean;\n\n static fromConfig(\n config: Config,\n options: { logger: Logger; skipReposWithoutExactFileMatch?: boolean },\n ): GitLabDiscoveryProcessor {\n const integrations = ScmIntegrations.fromConfig(config);\n const pluginCache =\n CacheManager.fromConfig(config).forPlugin('gitlab-discovery');\n\n return new GitLabDiscoveryProcessor({\n ...options,\n integrations,\n pluginCache,\n });\n }\n\n private constructor(options: {\n integrations: ScmIntegrationRegistry;\n pluginCache: PluginCacheManager;\n logger: Logger;\n skipReposWithoutExactFileMatch?: boolean;\n }) {\n this.integrations = options.integrations;\n this.cache = options.pluginCache.getClient();\n this.logger = options.logger;\n this.skipReposWithoutExactFileMatch =\n options.skipReposWithoutExactFileMatch || false;\n }\n\n getProcessorName(): string {\n return 'GitLabDiscoveryProcessor';\n }\n\n async readLocation(\n location: LocationSpec,\n _optional: boolean,\n emit: CatalogProcessorEmit,\n ): Promise<boolean> {\n if (location.type !== 'gitlab-discovery') {\n return false;\n }\n\n const startTime = new Date();\n const { group, host, branch, catalogPath } = parseUrl(location.target);\n\n const integration = this.integrations.gitlab.byUrl(`https://${host}`);\n if (!integration) {\n throw new Error(\n `There is no GitLab integration that matches ${host}. Please add a configuration entry for it under integrations.gitlab`,\n );\n }\n\n const client = new GitLabClient({\n config: integration.config,\n logger: this.logger,\n });\n this.logger.debug(`Reading GitLab projects from ${location.target}`);\n\n const lastActivity = (await this.cache.get(this.getCacheKey())) as string;\n const opts = {\n group,\n page: 1,\n // We check for the existence of lastActivity and only set it if it's present to ensure\n // that the options doesn't include the key so that the API doesn't receive an empty query parameter.\n ...(lastActivity && { last_activity_after: lastActivity }),\n };\n\n const projects = paginated(options => client.listProjects(options), opts);\n\n const res: Result = {\n scanned: 0,\n matches: [],\n };\n for await (const project of projects) {\n res.scanned++;\n\n if (project.archived) {\n continue;\n }\n\n if (branch === '*' && project.default_branch === undefined) {\n continue;\n }\n\n if (this.skipReposWithoutExactFileMatch) {\n const project_branch = branch === '*' ? project.default_branch : branch;\n\n const projectHasFile: boolean = await client.hasFile(\n project.path_with_namespace,\n project_branch,\n catalogPath,\n );\n\n if (!projectHasFile) {\n continue;\n }\n }\n\n res.matches.push(project);\n }\n\n for (const project of res.matches) {\n const project_branch = branch === '*' ? project.default_branch : branch;\n\n emit(\n processingResult.location({\n type: 'url',\n // The format expected by the GitLabUrlReader:\n // https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/filepath\n //\n // This unfortunately will trigger another API call in `getGitLabFileFetchUrl` to get the project ID.\n // The alternative is using the `buildRawUrl` function, which does not support subgroups, so providing a raw\n // URL here won't work either.\n target: `${project.web_url}/-/blob/${project_branch}/${catalogPath}`,\n presence: 'optional',\n }),\n );\n }\n\n // Save an ISO formatted string in the cache as that's what GitLab expects in the API request.\n await this.cache.set(this.getCacheKey(), startTime.toISOString());\n\n const duration = ((Date.now() - startTime.getTime()) / 1000).toFixed(1);\n this.logger.debug(\n `Read ${res.scanned} GitLab repositories in ${duration} seconds`,\n );\n\n return true;\n }\n\n private getCacheKey(): string {\n return `processors/${this.getProcessorName()}/last-activity`;\n }\n}\n\ntype Result = {\n scanned: number;\n matches: GitLabProject[];\n};\n\n/*\n * Helpers\n */\n\nexport function parseUrl(urlString: string): {\n group?: string;\n host: string;\n branch: string;\n catalogPath: string;\n} {\n const url = new URL(urlString);\n const path = url.pathname.substr(1).split('/');\n\n // (/group/subgroup)/blob/branch|*/filepath\n const blobIndex = path.findIndex(p => p === 'blob');\n if (blobIndex !== -1 && path.length > blobIndex + 2) {\n const group =\n blobIndex > 0 ? path.slice(0, blobIndex).join('/') : undefined;\n\n return {\n group,\n host: url.host,\n branch: decodeURIComponent(path[blobIndex + 1]),\n catalogPath: decodeURIComponent(path.slice(blobIndex + 2).join('/')),\n };\n }\n\n throw new Error(`Failed to parse ${urlString}`);\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 { PluginTaskScheduler, TaskRunner } from '@backstage/backend-tasks';\nimport { Config } from '@backstage/config';\nimport { GitLabIntegration, ScmIntegrations } from '@backstage/integration';\nimport {\n EntityProvider,\n EntityProviderConnection,\n LocationSpec,\n locationSpecToLocationEntity,\n} from '@backstage/plugin-catalog-backend';\nimport * as uuid from 'uuid';\nimport { Logger } from 'winston';\nimport {\n GitLabClient,\n GitLabProject,\n GitlabProviderConfig,\n paginated,\n readGitlabConfigs,\n} from '../lib';\n\ntype Result = {\n scanned: number;\n matches: GitLabProject[];\n};\n\n/**\n * Discovers entity definition files in the groups of a Gitlab instance.\n * @public\n */\nexport class GitlabDiscoveryEntityProvider implements EntityProvider {\n private readonly config: GitlabProviderConfig;\n private readonly integration: GitLabIntegration;\n private readonly logger: Logger;\n private readonly scheduleFn: () => Promise<void>;\n private connection?: EntityProviderConnection;\n\n static fromConfig(\n config: Config,\n options: {\n logger: Logger;\n schedule?: TaskRunner;\n scheduler?: PluginTaskScheduler;\n },\n ): GitlabDiscoveryEntityProvider[] {\n if (!options.schedule && !options.scheduler) {\n throw new Error('Either schedule or scheduler must be provided.');\n }\n\n const providerConfigs = readGitlabConfigs(config);\n const integrations = ScmIntegrations.fromConfig(config).gitlab;\n const providers: GitlabDiscoveryEntityProvider[] = [];\n\n providerConfigs.forEach(providerConfig => {\n const integration = integrations.byHost(providerConfig.host);\n if (!integration) {\n throw new Error(\n `No gitlab integration found that matches host ${providerConfig.host}`,\n );\n }\n\n if (!options.schedule && !providerConfig.schedule) {\n throw new Error(\n `No schedule provided neither via code nor config for GitlabDiscoveryEntityProvider:${providerConfig.id}.`,\n );\n }\n\n const taskRunner =\n options.schedule ??\n options.scheduler!.createScheduledTaskRunner(providerConfig.schedule!);\n\n providers.push(\n new GitlabDiscoveryEntityProvider({\n ...options,\n config: providerConfig,\n integration,\n taskRunner,\n }),\n );\n });\n return providers;\n }\n\n private constructor(options: {\n config: GitlabProviderConfig;\n integration: GitLabIntegration;\n logger: Logger;\n taskRunner: TaskRunner;\n }) {\n this.config = options.config;\n this.integration = options.integration;\n this.logger = options.logger.child({\n target: this.getProviderName(),\n });\n this.scheduleFn = this.createScheduleFn(options.taskRunner);\n }\n\n getProviderName(): string {\n return `GitlabDiscoveryEntityProvider:${this.config.id}`;\n }\n\n async connect(connection: EntityProviderConnection): Promise<void> {\n this.connection = connection;\n 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: GitlabDiscoveryEntityProvider.prototype.constructor.name,\n taskId,\n taskInstanceId: uuid.v4(),\n });\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): Promise<void> {\n if (!this.connection) {\n throw new Error(\n `Gitlab discovery connection not initialized for ${this.getProviderName()}`,\n );\n }\n\n const client = new GitLabClient({\n config: this.integration.config,\n logger: logger,\n });\n\n const projects = paginated<GitLabProject>(\n options => client.listProjects(options),\n {\n group: this.config.group,\n page: 1,\n per_page: 50,\n },\n );\n\n const res: Result = {\n scanned: 0,\n matches: [],\n };\n\n for await (const project of projects) {\n if (!this.config.projectPattern.test(project.path_with_namespace ?? '')) {\n continue;\n }\n\n res.scanned++;\n\n if (project.archived) {\n continue;\n }\n\n if (this.config.branch === '*' && project.default_branch === undefined) {\n continue;\n }\n\n const project_branch = project.default_branch ?? this.config.branch;\n\n const projectHasFile: boolean = await client.hasFile(\n project.path_with_namespace ?? '',\n project_branch,\n this.config.catalogFile,\n );\n if (projectHasFile) {\n res.matches.push(project);\n }\n }\n\n const locations = res.matches.map(p => this.createLocationSpec(p));\n await this.connection.applyMutation({\n type: 'full',\n entities: locations.map(location => ({\n locationKey: this.getProviderName(),\n entity: locationSpecToLocationEntity({ location }),\n })),\n });\n }\n\n private createLocationSpec(project: GitLabProject): LocationSpec {\n const project_branch = project.default_branch ?? this.config.branch;\n return {\n type: 'url',\n target: `${project.web_url}/-/blob/${project_branch}/${this.config.catalogFile}`,\n presence: 'optional',\n };\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 {\n createBackendModule,\n coreServices,\n} from '@backstage/backend-plugin-api';\nimport { loggerToWinstonLogger } from '@backstage/backend-common';\nimport { catalogProcessingExtensionPoint } from '@backstage/plugin-catalog-node';\nimport { GitlabDiscoveryEntityProvider } from '../providers';\n\n/**\n * Registers the GitlabDiscoveryEntityProvider with the catalog processing extension point.\n *\n * @alpha\n */\nexport const gitlabDiscoveryEntityProviderCatalogModule = createBackendModule({\n pluginId: 'catalog',\n moduleId: 'gitlabDiscoveryEntityProvider',\n register(env) {\n env.registerInit({\n deps: {\n config: coreServices.config,\n catalog: catalogProcessingExtensionPoint,\n logger: coreServices.logger,\n scheduler: coreServices.scheduler,\n },\n async init({ config, catalog, logger, scheduler }) {\n catalog.addEntityProvider(\n GitlabDiscoveryEntityProvider.fromConfig(config, {\n logger: loggerToWinstonLogger(logger),\n scheduler,\n }),\n );\n },\n });\n },\n});\n"],"names":["fetch","getGitLabRequestOptions","readTaskScheduleDefinitionFromConfig","ScmIntegrations","CacheManager","processingResult","uuid","locationSpecToLocationEntity","createBackendModule","coreServices","catalogProcessingExtensionPoint","loggerToWinstonLogger"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCO,MAAM,YAAa,CAAA;AAAA,EAIxB,YAAY,OAA8D,EAAA;AACxE,IAAA,IAAA,CAAK,SAAS,OAAQ,CAAA,MAAA,CAAA;AACtB,IAAA,IAAA,CAAK,SAAS,OAAQ,CAAA,MAAA,CAAA;AAA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,QACT,QAAQD,6BAAa,CAAA,MAAA;AAAA,QACrB,WAAWA,6BAAa,CAAA,SAAA;AAAA,OAC1B;AAAA,MACA,MAAM,IAAK,CAAA,EAAE,QAAQ,OAAS,EAAA,MAAA,EAAQ,WAAa,EAAA;AACjD,QAAQ,OAAA,CAAA,iBAAA;AAAA,UACN,6BAAA,CAA8B,WAAW,MAAQ,EAAA;AAAA,YAC/C,MAAA,EAAQE,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":"index.cjs.js","sources":["../src/lib/client.ts","../src/providers/config.ts","../src/GitLabDiscoveryProcessor.ts","../src/providers/GitlabDiscoveryEntityProvider.ts","../src/providers/GitlabOrgDiscoveryEntityProvider.ts","../src/service/GitlabDiscoveryEntityProviderCatalogModule.ts"],"sourcesContent":["/*\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 fetch from 'node-fetch';\nimport {\n getGitLabRequestOptions,\n GitLabIntegrationConfig,\n} from '@backstage/integration';\nimport { Logger } from 'winston';\nimport { GitLabGroup, GitLabMembership, GitLabUser } from './types';\n\nexport type CommonListOptions = {\n [key: string]: string | number | boolean | undefined;\n per_page?: number | undefined;\n page?: number | undefined;\n active?: boolean;\n};\n\ninterface ListProjectOptions extends CommonListOptions {\n group?: string;\n}\n\ninterface UserListOptions extends CommonListOptions {\n without_project_bots?: boolean | undefined;\n exclude_internal?: boolean | undefined;\n}\n\nexport type PagedResponse<T> = {\n items: T[];\n nextPage?: number;\n};\n\nexport class GitLabClient {\n private readonly config: GitLabIntegrationConfig;\n private readonly logger: Logger;\n\n constructor(options: { config: GitLabIntegrationConfig; logger: Logger }) {\n this.config = options.config;\n this.logger = options.logger;\n }\n\n /**\n * Indicates whether the client is for a SaaS or self managed GitLab instance.\n */\n isSelfManaged(): boolean {\n return this.config.host !== 'gitlab.com';\n }\n\n async listProjects(\n options?: ListProjectOptions,\n ): Promise<PagedResponse<any>> {\n if (options?.group) {\n return this.pagedRequest(\n `/groups/${encodeURIComponent(options?.group)}/projects`,\n {\n ...options,\n include_subgroups: true,\n },\n );\n }\n\n return this.pagedRequest(`/projects`, options);\n }\n\n async listUsers(\n options?: UserListOptions,\n ): Promise<PagedResponse<GitLabUser>> {\n let requestOptions = options;\n\n if (!requestOptions) {\n requestOptions = {};\n }\n\n requestOptions.without_project_bots = true;\n requestOptions.exclude_internal = true;\n\n return this.pagedRequest(`/users?`, requestOptions);\n }\n\n async listGroups(\n options?: CommonListOptions,\n ): Promise<PagedResponse<GitLabGroup>> {\n return this.pagedRequest(`/groups`, options);\n }\n\n async getUserMemberships(userId: number): Promise<GitLabMembership[]> {\n const endpoint: string = `/users/${encodeURIComponent(userId)}/memberships`;\n const request = new URL(`${this.config.apiBaseUrl}${endpoint}`);\n request.searchParams.append('per_page', '100');\n\n const response = await fetch(request.toString(), {\n headers: getGitLabRequestOptions(this.config).headers,\n method: 'GET',\n });\n\n if (!response.ok) {\n if (response.status >= 500) {\n this.logger.debug(\n `Unexpected response when fetching ${request.toString()}. Expected 200 but got ${\n response.status\n } - ${response.statusText}`,\n );\n }\n return [];\n }\n\n return response.json().then(items => {\n return items as GitLabMembership[];\n });\n }\n\n /**\n * General existence check.\n *\n * @param projectPath - The path to the project\n * @param branch - The branch used to search\n * @param filePath - The path to the file\n */\n async hasFile(\n projectPath: string,\n branch: string,\n filePath: string,\n ): Promise<boolean> {\n const endpoint: string = `/projects/${encodeURIComponent(\n projectPath,\n )}/repository/files/${encodeURIComponent(filePath)}`;\n const request = new URL(`${this.config.apiBaseUrl}${endpoint}`);\n request.searchParams.append('ref', branch);\n\n const response = await fetch(request.toString(), {\n headers: getGitLabRequestOptions(this.config).headers,\n method: 'HEAD',\n });\n\n if (!response.ok) {\n if (response.status >= 500) {\n this.logger.debug(\n `Unexpected response when fetching ${request.toString()}. Expected 200 but got ${\n response.status\n } - ${response.statusText}`,\n );\n }\n return false;\n }\n\n return true;\n }\n\n /**\n * Performs a request against a given paginated GitLab endpoint.\n *\n * This method may be used to perform authenticated REST calls against any\n * paginated GitLab endpoint which uses X-NEXT-PAGE headers. The return value\n * can be be used with the {@link paginated} async-generator function to yield\n * each item from the paged request.\n *\n * @see {@link paginated}\n * @param endpoint - The request endpoint, e.g. /projects.\n * @param options - Request queryString options which may also include page variables.\n */\n async pagedRequest<T = any>(\n endpoint: string,\n options?: CommonListOptions,\n ): Promise<PagedResponse<T>> {\n const request = new URL(`${this.config.apiBaseUrl}${endpoint}`);\n for (const key in options) {\n if (options[key]) {\n request.searchParams.append(key, options[key]!.toString());\n }\n }\n\n this.logger.debug(`Fetching: ${request.toString()}`);\n const response = await fetch(\n request.toString(),\n getGitLabRequestOptions(this.config),\n );\n if (!response.ok) {\n throw new Error(\n `Unexpected response when fetching ${request.toString()}. Expected 200 but got ${\n response.status\n } - ${response.statusText}`,\n );\n }\n return response.json().then(items => {\n const nextPage = response.headers.get('x-next-page');\n\n return {\n items,\n nextPage: nextPage ? Number(nextPage) : null,\n } as PagedResponse<any>;\n });\n }\n}\n\n/**\n * Advances through each page and provides each item from a paginated request.\n *\n * The async generator function yields each item from repeated calls to the\n * provided request function. The generator walks through each available page by\n * setting the page key in the options passed into the request function and\n * making repeated calls until there are no more pages.\n *\n * @see {@link pagedRequest}\n * @param request - Function which returns a PagedResponse to walk through.\n * @param options - Initial ListOptions for the request function.\n */\nexport async function* paginated<T = any>(\n request: (options: CommonListOptions) => Promise<PagedResponse<T>>,\n options: CommonListOptions,\n) {\n let res;\n do {\n res = await request(options);\n options.page = res.nextPage;\n for (const item of res.items) {\n yield item;\n }\n } while (res.nextPage);\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 { readTaskScheduleDefinitionFromConfig } from '@backstage/backend-tasks';\nimport { Config } from '@backstage/config';\nimport { GitlabProviderConfig } from '../lib';\n\n/**\n * Extracts the gitlab config from a config object\n *\n * @public\n *\n * @param id - The provider key\n * @param config - The config object to extract from\n */\nfunction readGitlabConfig(id: string, config: Config): GitlabProviderConfig {\n const group = config.getOptionalString('group') ?? '';\n const host = config.getString('host');\n const branch = config.getOptionalString('branch') ?? 'master';\n const catalogFile =\n config.getOptionalString('entityFilename') ?? 'catalog-info.yaml';\n const projectPattern = new RegExp(\n config.getOptionalString('projectPattern') ?? /[\\s\\S]*/,\n );\n const userPattern = new RegExp(\n config.getOptionalString('userPattern') ?? /[\\s\\S]*/,\n );\n const groupPattern = new RegExp(\n config.getOptionalString('groupPattern') ?? /[\\s\\S]*/,\n );\n const orgEnabled: boolean = config.getOptionalBoolean('orgEnabled') ?? false;\n\n const schedule = config.has('schedule')\n ? readTaskScheduleDefinitionFromConfig(config.getConfig('schedule'))\n : undefined;\n\n return {\n id,\n group,\n branch,\n host,\n catalogFile,\n projectPattern,\n userPattern,\n groupPattern,\n schedule,\n orgEnabled,\n };\n}\n\n/**\n * Extracts the gitlab config from a config object array\n *\n * @public\n *\n * @param config - The config object to extract from\n */\nexport function readGitlabConfigs(config: Config): GitlabProviderConfig[] {\n const configs: GitlabProviderConfig[] = [];\n\n const providerConfigs = config.getOptionalConfig('catalog.providers.gitlab');\n\n if (!providerConfigs) {\n return configs;\n }\n\n for (const id of providerConfigs.keys()) {\n configs.push(readGitlabConfig(id, providerConfigs.getConfig(id)));\n }\n\n return configs;\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 CacheClient,\n CacheManager,\n PluginCacheManager,\n} from '@backstage/backend-common';\nimport { Config } from '@backstage/config';\nimport {\n ScmIntegrationRegistry,\n ScmIntegrations,\n} from '@backstage/integration';\nimport {\n CatalogProcessor,\n CatalogProcessorEmit,\n LocationSpec,\n processingResult,\n} from '@backstage/plugin-catalog-backend';\nimport { Logger } from 'winston';\nimport { GitLabClient, GitLabProject, paginated } from './lib';\n\n/**\n * Extracts repositories out of an GitLab instance.\n * @public\n */\nexport class GitLabDiscoveryProcessor implements CatalogProcessor {\n private readonly integrations: ScmIntegrationRegistry;\n private readonly logger: Logger;\n private readonly cache: CacheClient;\n private readonly skipReposWithoutExactFileMatch: boolean;\n\n static fromConfig(\n config: Config,\n options: { logger: Logger; skipReposWithoutExactFileMatch?: boolean },\n ): GitLabDiscoveryProcessor {\n const integrations = ScmIntegrations.fromConfig(config);\n const pluginCache =\n CacheManager.fromConfig(config).forPlugin('gitlab-discovery');\n\n return new GitLabDiscoveryProcessor({\n ...options,\n integrations,\n pluginCache,\n });\n }\n\n private constructor(options: {\n integrations: ScmIntegrationRegistry;\n pluginCache: PluginCacheManager;\n logger: Logger;\n skipReposWithoutExactFileMatch?: boolean;\n }) {\n this.integrations = options.integrations;\n this.cache = options.pluginCache.getClient();\n this.logger = options.logger;\n this.skipReposWithoutExactFileMatch =\n options.skipReposWithoutExactFileMatch || false;\n }\n\n getProcessorName(): string {\n return 'GitLabDiscoveryProcessor';\n }\n\n async readLocation(\n location: LocationSpec,\n _optional: boolean,\n emit: CatalogProcessorEmit,\n ): Promise<boolean> {\n if (location.type !== 'gitlab-discovery') {\n return false;\n }\n\n const startTime = new Date();\n const { group, host, branch, catalogPath } = parseUrl(location.target);\n\n const integration = this.integrations.gitlab.byUrl(`https://${host}`);\n if (!integration) {\n throw new Error(\n `There is no GitLab integration that matches ${host}. Please add a configuration entry for it under integrations.gitlab`,\n );\n }\n\n const client = new GitLabClient({\n config: integration.config,\n logger: this.logger,\n });\n this.logger.debug(`Reading GitLab projects from ${location.target}`);\n\n const lastActivity = (await this.cache.get(this.getCacheKey())) as string;\n const opts = {\n group,\n page: 1,\n // We check for the existence of lastActivity and only set it if it's present to ensure\n // that the options doesn't include the key so that the API doesn't receive an empty query parameter.\n ...(lastActivity && { last_activity_after: lastActivity }),\n };\n\n const projects = paginated(options => client.listProjects(options), opts);\n\n const res: Result = {\n scanned: 0,\n matches: [],\n };\n for await (const project of projects) {\n res.scanned++;\n\n if (project.archived) {\n continue;\n }\n\n if (branch === '*' && project.default_branch === undefined) {\n continue;\n }\n\n if (this.skipReposWithoutExactFileMatch) {\n const project_branch = branch === '*' ? project.default_branch : branch;\n\n const projectHasFile: boolean = await client.hasFile(\n project.path_with_namespace,\n project_branch,\n catalogPath,\n );\n\n if (!projectHasFile) {\n continue;\n }\n }\n\n res.matches.push(project);\n }\n\n for (const project of res.matches) {\n const project_branch = branch === '*' ? project.default_branch : branch;\n\n emit(\n processingResult.location({\n type: 'url',\n // The format expected by the GitLabUrlReader:\n // https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/filepath\n //\n // This unfortunately will trigger another API call in `getGitLabFileFetchUrl` to get the project ID.\n // The alternative is using the `buildRawUrl` function, which does not support subgroups, so providing a raw\n // URL here won't work either.\n target: `${project.web_url}/-/blob/${project_branch}/${catalogPath}`,\n presence: 'optional',\n }),\n );\n }\n\n // Save an ISO formatted string in the cache as that's what GitLab expects in the API request.\n await this.cache.set(this.getCacheKey(), startTime.toISOString());\n\n const duration = ((Date.now() - startTime.getTime()) / 1000).toFixed(1);\n this.logger.debug(\n `Read ${res.scanned} GitLab repositories in ${duration} seconds`,\n );\n\n return true;\n }\n\n private getCacheKey(): string {\n return `processors/${this.getProcessorName()}/last-activity`;\n }\n}\n\ntype Result = {\n scanned: number;\n matches: GitLabProject[];\n};\n\n/*\n * Helpers\n */\n\nexport function parseUrl(urlString: string): {\n group?: string;\n host: string;\n branch: string;\n catalogPath: string;\n} {\n const url = new URL(urlString);\n const path = url.pathname.slice(1).split('/');\n\n // (/group/subgroup)/blob/branch|*/filepath\n const blobIndex = path.findIndex(p => p === 'blob');\n if (blobIndex !== -1 && path.length > blobIndex + 2) {\n const group =\n blobIndex > 0 ? path.slice(0, blobIndex).join('/') : undefined;\n\n return {\n group,\n host: url.host,\n branch: decodeURIComponent(path[blobIndex + 1]),\n catalogPath: decodeURIComponent(path.slice(blobIndex + 2).join('/')),\n };\n }\n\n throw new Error(`Failed to parse ${urlString}`);\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 { PluginTaskScheduler, TaskRunner } from '@backstage/backend-tasks';\nimport { Config } from '@backstage/config';\nimport { GitLabIntegration, ScmIntegrations } from '@backstage/integration';\nimport {\n EntityProvider,\n EntityProviderConnection,\n LocationSpec,\n locationSpecToLocationEntity,\n} from '@backstage/plugin-catalog-backend';\nimport * as uuid from 'uuid';\nimport { Logger } from 'winston';\nimport {\n GitLabClient,\n GitLabProject,\n GitlabProviderConfig,\n paginated,\n readGitlabConfigs,\n} from '../lib';\n\ntype Result = {\n scanned: number;\n matches: GitLabProject[];\n};\n\n/**\n * Discovers entity definition files in the groups of a Gitlab instance.\n * @public\n */\nexport class GitlabDiscoveryEntityProvider implements EntityProvider {\n private readonly config: GitlabProviderConfig;\n private readonly integration: GitLabIntegration;\n private readonly logger: Logger;\n private readonly scheduleFn: () => Promise<void>;\n private connection?: EntityProviderConnection;\n\n static fromConfig(\n config: Config,\n options: {\n logger: Logger;\n schedule?: TaskRunner;\n scheduler?: PluginTaskScheduler;\n },\n ): GitlabDiscoveryEntityProvider[] {\n if (!options.schedule && !options.scheduler) {\n throw new Error('Either schedule or scheduler must be provided.');\n }\n\n const providerConfigs = readGitlabConfigs(config);\n const integrations = ScmIntegrations.fromConfig(config).gitlab;\n const providers: GitlabDiscoveryEntityProvider[] = [];\n\n providerConfigs.forEach(providerConfig => {\n const integration = integrations.byHost(providerConfig.host);\n if (!integration) {\n throw new Error(\n `No gitlab integration found that matches host ${providerConfig.host}`,\n );\n }\n\n if (!options.schedule && !providerConfig.schedule) {\n throw new Error(\n `No schedule provided neither via code nor config for GitlabDiscoveryEntityProvider:${providerConfig.id}.`,\n );\n }\n\n const taskRunner =\n options.schedule ??\n options.scheduler!.createScheduledTaskRunner(providerConfig.schedule!);\n\n providers.push(\n new GitlabDiscoveryEntityProvider({\n ...options,\n config: providerConfig,\n integration,\n taskRunner,\n }),\n );\n });\n return providers;\n }\n\n private constructor(options: {\n config: GitlabProviderConfig;\n integration: GitLabIntegration;\n logger: Logger;\n taskRunner: TaskRunner;\n }) {\n this.config = options.config;\n this.integration = options.integration;\n this.logger = options.logger.child({\n target: this.getProviderName(),\n });\n this.scheduleFn = this.createScheduleFn(options.taskRunner);\n }\n\n getProviderName(): string {\n return `GitlabDiscoveryEntityProvider:${this.config.id}`;\n }\n\n async connect(connection: EntityProviderConnection): Promise<void> {\n this.connection = connection;\n 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: GitlabDiscoveryEntityProvider.prototype.constructor.name,\n taskId,\n taskInstanceId: uuid.v4(),\n });\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): Promise<void> {\n if (!this.connection) {\n throw new Error(\n `Gitlab discovery connection not initialized for ${this.getProviderName()}`,\n );\n }\n\n const client = new GitLabClient({\n config: this.integration.config,\n logger: logger,\n });\n\n const projects = paginated<GitLabProject>(\n options => client.listProjects(options),\n {\n group: this.config.group,\n page: 1,\n per_page: 50,\n },\n );\n\n const res: Result = {\n scanned: 0,\n matches: [],\n };\n\n for await (const project of projects) {\n if (!this.config.projectPattern.test(project.path_with_namespace ?? '')) {\n continue;\n }\n\n res.scanned++;\n\n if (project.archived) {\n continue;\n }\n\n if (this.config.branch === '*' && project.default_branch === undefined) {\n continue;\n }\n\n const project_branch = project.default_branch ?? this.config.branch;\n\n const projectHasFile: boolean = await client.hasFile(\n project.path_with_namespace ?? '',\n project_branch,\n this.config.catalogFile,\n );\n if (projectHasFile) {\n res.matches.push(project);\n }\n }\n\n const locations = res.matches.map(p => this.createLocationSpec(p));\n await this.connection.applyMutation({\n type: 'full',\n entities: locations.map(location => ({\n locationKey: this.getProviderName(),\n entity: locationSpecToLocationEntity({ location }),\n })),\n });\n }\n\n private createLocationSpec(project: GitLabProject): LocationSpec {\n const project_branch = project.default_branch ?? this.config.branch;\n return {\n type: 'url',\n target: `${project.web_url}/-/blob/${project_branch}/${this.config.catalogFile}`,\n presence: 'optional',\n };\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 { PluginTaskScheduler, TaskRunner } from '@backstage/backend-tasks';\nimport { Config } from '@backstage/config';\nimport { GitLabIntegration, ScmIntegrations } from '@backstage/integration';\nimport {\n EntityProvider,\n EntityProviderConnection,\n} from '@backstage/plugin-catalog-backend';\nimport * as uuid from 'uuid';\nimport { Logger } from 'winston';\nimport {\n GitLabClient,\n GitlabProviderConfig,\n paginated,\n readGitlabConfigs,\n} from '../lib';\nimport { GitLabGroup, GitLabUser } from '../lib/types';\nimport {\n ANNOTATION_LOCATION,\n ANNOTATION_ORIGIN_LOCATION,\n Entity,\n UserEntity,\n GroupEntity,\n} from '@backstage/catalog-model';\nimport { merge } from 'lodash';\n\ntype Result = {\n scanned: number;\n matches: GitLabUser[];\n};\n\ntype GroupResult = {\n scanned: number;\n matches: GitLabGroup[];\n};\n\n/**\n * Discovers users and groups from a Gitlab instance.\n * @public\n */\nexport class GitlabOrgDiscoveryEntityProvider implements EntityProvider {\n private readonly config: GitlabProviderConfig;\n private readonly integration: GitLabIntegration;\n private readonly logger: Logger;\n private readonly scheduleFn: () => Promise<void>;\n private connection?: EntityProviderConnection;\n\n static fromConfig(\n config: Config,\n options: {\n logger: Logger;\n schedule?: TaskRunner;\n scheduler?: PluginTaskScheduler;\n },\n ): GitlabOrgDiscoveryEntityProvider[] {\n if (!options.schedule && !options.scheduler) {\n throw new Error('Either schedule or scheduler must be provided.');\n }\n\n const providerConfigs = readGitlabConfigs(config);\n const integrations = ScmIntegrations.fromConfig(config).gitlab;\n const providers: GitlabOrgDiscoveryEntityProvider[] = [];\n\n providerConfigs.forEach(providerConfig => {\n const integration = integrations.byHost(providerConfig.host);\n\n if (!providerConfig.orgEnabled) {\n return;\n }\n\n if (!integration) {\n throw new Error(\n `No gitlab integration found that matches host ${providerConfig.host}`,\n );\n }\n\n if (!options.schedule && !providerConfig.schedule) {\n throw new Error(\n `No schedule provided neither via code nor config for GitlabOrgDiscoveryEntityProvider:${providerConfig.id}.`,\n );\n }\n\n const taskRunner =\n options.schedule ??\n options.scheduler!.createScheduledTaskRunner(providerConfig.schedule!);\n\n providers.push(\n new GitlabOrgDiscoveryEntityProvider({\n ...options,\n config: providerConfig,\n integration,\n taskRunner,\n }),\n );\n });\n return providers;\n }\n\n private constructor(options: {\n config: GitlabProviderConfig;\n integration: GitLabIntegration;\n logger: Logger;\n taskRunner: TaskRunner;\n }) {\n this.config = options.config;\n this.integration = options.integration;\n this.logger = options.logger.child({\n target: this.getProviderName(),\n });\n this.scheduleFn = this.createScheduleFn(options.taskRunner);\n }\n\n getProviderName(): string {\n return `GitlabOrgDiscoveryEntityProvider:${this.config.id}`;\n }\n\n async connect(connection: EntityProviderConnection): Promise<void> {\n this.connection = connection;\n 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: GitlabOrgDiscoveryEntityProvider.prototype.constructor.name,\n taskId,\n taskInstanceId: uuid.v4(),\n });\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 private async refresh(logger: Logger): Promise<void> {\n if (!this.connection) {\n throw new Error(\n `Gitlab discovery connection not initialized for ${this.getProviderName()}`,\n );\n }\n\n const client = new GitLabClient({\n config: this.integration.config,\n logger: logger,\n });\n\n const users = paginated<GitLabUser>(options => client.listUsers(options), {\n page: 1,\n per_page: 100,\n active: true,\n });\n\n const groups = paginated<GitLabGroup>(\n options => client.listGroups(options),\n {\n page: 1,\n per_page: 100,\n },\n );\n\n const idMappedGroup: { [groupId: number]: GitLabGroup } = {};\n\n const res: Result = {\n scanned: 0,\n matches: [],\n };\n\n const groupRes: GroupResult = {\n scanned: 0,\n matches: [],\n };\n\n for await (const group of groups) {\n if (!this.config.groupPattern.test(group.full_path ?? '')) {\n continue;\n }\n\n groupRes.scanned++;\n groupRes.matches.push(group);\n\n idMappedGroup[group.id] = group;\n }\n\n for await (const user of users) {\n if (!this.config.userPattern.test(user.email ?? user.username ?? '')) {\n continue;\n }\n\n res.scanned++;\n\n if (user.state !== 'active') {\n continue;\n }\n\n const memberships = await client.getUserMemberships(user.id);\n const userGroups: GitLabGroup[] = [];\n\n for (const i of memberships) {\n if (\n i.source_type === 'Namespace' &&\n idMappedGroup.hasOwnProperty(i.source_id)\n ) {\n userGroups.push(idMappedGroup[i.source_id]);\n }\n }\n\n user.groups = userGroups;\n\n res.matches.push(user);\n }\n\n const groupsWithUsers = groupRes.matches.filter(group => {\n return (\n res.matches.filter(x => {\n return !!x.groups?.find(y => y.id === group.id);\n }).length > 0\n );\n });\n\n const userEntities = res.matches.map(p =>\n this.createUserEntity(p, this.integration.config.host),\n );\n const groupEntities = this.createGroupEntities(\n groupsWithUsers,\n this.integration.config.host,\n );\n\n await this.connection.applyMutation({\n type: 'full',\n entities: [...userEntities, ...groupEntities].map(entity => ({\n locationKey: this.getProviderName(),\n entity: this.withLocations(this.integration.config.host, entity),\n })),\n });\n }\n\n private createGroupEntities(\n groupResult: GitLabGroup[],\n host: string,\n ): GroupEntity[] {\n const idMapped: { [groupId: number]: GitLabGroup } = {};\n const entities: GroupEntity[] = [];\n\n for (const group of groupResult) {\n idMapped[group.id] = group;\n }\n\n for (const group of groupResult) {\n const entity = this.createGroupEntity(group, host);\n\n if (group.parent_id && idMapped.hasOwnProperty(group.parent_id)) {\n entity.spec.parent = idMapped[group.parent_id].full_path;\n }\n\n entities.push(entity);\n }\n\n return entities;\n }\n\n private withLocations(host: string, entity: Entity): Entity {\n const location =\n entity.kind === 'Group'\n ? `url:${host}/teams/${entity.metadata.name}`\n : `url:${host}/${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 private createUserEntity(user: GitLabUser, host: string): UserEntity {\n const annotations: { [annotationName: string]: string } = {};\n\n annotations[`${host}/user-login`] = user.web_url;\n\n const entity: UserEntity = {\n apiVersion: 'backstage.io/v1alpha1',\n kind: 'User',\n metadata: {\n name: user.username,\n annotations: annotations,\n },\n spec: {\n profile: {\n displayName: user.name,\n picture: user.avatar_url,\n },\n memberOf: [],\n },\n };\n\n if (user.email) {\n if (!entity.spec) {\n entity.spec = {};\n }\n\n if (!entity.spec.profile) {\n entity.spec.profile = {};\n }\n\n entity.spec.profile.email = user.email;\n }\n\n if (user.groups) {\n for (const group of user.groups) {\n if (!entity.spec.memberOf) {\n entity.spec.memberOf = [];\n }\n entity.spec.memberOf.push(group.full_path.replace('/', '-'));\n }\n }\n\n return entity;\n }\n\n private createGroupEntity(group: GitLabGroup, host: string): GroupEntity {\n const annotations: { [annotationName: string]: string } = {};\n\n annotations[`${host}/team-path`] = group.full_path;\n\n const entity: GroupEntity = {\n apiVersion: 'backstage.io/v1alpha1',\n kind: 'Group',\n metadata: {\n name: group.full_path.replace('/', '-'),\n annotations: annotations,\n },\n spec: {\n type: 'team',\n children: [],\n profile: {\n displayName: group.name,\n },\n },\n };\n\n if (group.description) {\n entity.metadata.description = group.description;\n }\n\n return entity;\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 {\n createBackendModule,\n coreServices,\n} from '@backstage/backend-plugin-api';\nimport { loggerToWinstonLogger } from '@backstage/backend-common';\nimport { catalogProcessingExtensionPoint } from '@backstage/plugin-catalog-node';\nimport { GitlabDiscoveryEntityProvider } from '../providers';\n\n/**\n * Registers the GitlabDiscoveryEntityProvider with the catalog processing extension point.\n *\n * @alpha\n */\nexport const gitlabDiscoveryEntityProviderCatalogModule = createBackendModule({\n pluginId: 'catalog',\n moduleId: 'gitlabDiscoveryEntityProvider',\n register(env) {\n env.registerInit({\n deps: {\n config: coreServices.config,\n catalog: catalogProcessingExtensionPoint,\n logger: coreServices.logger,\n scheduler: coreServices.scheduler,\n },\n async init({ config, catalog, logger, scheduler }) {\n catalog.addEntityProvider(\n GitlabDiscoveryEntityProvider.fromConfig(config, {\n logger: loggerToWinstonLogger(logger),\n scheduler,\n }),\n );\n },\n });\n },\n});\n"],"names":["fetch","getGitLabRequestOptions","readTaskScheduleDefinitionFromConfig","ScmIntegrations","CacheManager","processingResult","uuid","locationSpecToLocationEntity","_a","merge","ANNOTATION_LOCATION","ANNOTATION_ORIGIN_LOCATION","createBackendModule","coreServices","catalogProcessingExtensionPoint","loggerToWinstonLogger"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CO,MAAM,YAAa,CAAA;AAAA,EAIxB,YAAY,OAA8D,EAAA;AACxE,IAAA,IAAA,CAAK,SAAS,OAAQ,CAAA,MAAA,CAAA;AACtB,IAAA,IAAA,CAAK,SAAS,OAAQ,CAAA,MAAA,CAAA;AAAA,GACxB;AAAA;AAAA;AAAA;AAAA,EAKA,aAAyB,GAAA;AACvB,IAAO,OAAA,IAAA,CAAK,OAAO,IAAS,KAAA,YAAA,CAAA;AAAA,GAC9B;AAAA,EAEA,MAAM,aACJ,OAC6B,EAAA;AAC7B,IAAA,IAAI,mCAAS,KAAO,EAAA;AAClB,MAAA,OAAO,IAAK,CAAA,YAAA;A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A;AAAA,EACV,QAAU,EAAA,+BAAA;AAAA,EACV,SAAS,GAAK,EAAA;AACZ,IAAA,GAAA,CAAI,YAAa,CAAA;AAAA,MACf,IAAM,EAAA;AAAA,QACJ,QAAQC,6BAAa,CAAA,MAAA;AAAA,QACrB,OAAS,EAAAC,iDAAA;AAAA,QACT,QAAQD,6BAAa,CAAA,MAAA;AAAA,QACrB,WAAWA,6BAAa,CAAA,SAAA;AAAA,OAC1B;AAAA,MACA,MAAM,IAAK,CAAA,EAAE,QAAQ,OAAS,EAAA,MAAA,EAAQ,WAAa,EAAA;AACjD,QAAQ,OAAA,CAAA,iBAAA;AAAA,UACN,6BAAA,CAA8B,WAAW,MAAQ,EAAA;AAAA,YAC/C,MAAA,EAAQE,oCAAsB,MAAM,CAAA;AAAA,YACpC,SAAA;AAAA,WACD,CAAA;AAAA,SACH,CAAA;AAAA,OACF;AAAA,KACD,CAAA,CAAA;AAAA,GACH;AACF,CAAC;;;;;;;"}
|
package/dist/index.d.ts
CHANGED
|
@@ -59,4 +59,30 @@ export declare class GitLabDiscoveryProcessor implements CatalogProcessor {
|
|
|
59
59
|
private getCacheKey;
|
|
60
60
|
}
|
|
61
61
|
|
|
62
|
+
/**
|
|
63
|
+
* Discovers users and groups from a Gitlab instance.
|
|
64
|
+
* @public
|
|
65
|
+
*/
|
|
66
|
+
export declare class GitlabOrgDiscoveryEntityProvider implements EntityProvider {
|
|
67
|
+
private readonly config;
|
|
68
|
+
private readonly integration;
|
|
69
|
+
private readonly logger;
|
|
70
|
+
private readonly scheduleFn;
|
|
71
|
+
private connection?;
|
|
72
|
+
static fromConfig(config: Config, options: {
|
|
73
|
+
logger: Logger;
|
|
74
|
+
schedule?: TaskRunner;
|
|
75
|
+
scheduler?: PluginTaskScheduler;
|
|
76
|
+
}): GitlabOrgDiscoveryEntityProvider[];
|
|
77
|
+
private constructor();
|
|
78
|
+
getProviderName(): string;
|
|
79
|
+
connect(connection: EntityProviderConnection): Promise<void>;
|
|
80
|
+
private createScheduleFn;
|
|
81
|
+
private refresh;
|
|
82
|
+
private createGroupEntities;
|
|
83
|
+
private withLocations;
|
|
84
|
+
private createUserEntity;
|
|
85
|
+
private createGroupEntity;
|
|
86
|
+
}
|
|
87
|
+
|
|
62
88
|
export { }
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@backstage/plugin-catalog-backend-module-gitlab",
|
|
3
3
|
"description": "A Backstage catalog backend module that helps integrate towards GitLab",
|
|
4
|
-
"version": "0.1.13-next.
|
|
4
|
+
"version": "0.1.13-next.1",
|
|
5
5
|
"main": "dist/index.cjs.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
7
7
|
"license": "Apache-2.0",
|
|
@@ -33,15 +33,15 @@
|
|
|
33
33
|
"clean": "backstage-cli package clean"
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
|
-
"@backstage/backend-common": "^0.18.2-next.
|
|
37
|
-
"@backstage/backend-plugin-api": "^0.3.2-next.
|
|
38
|
-
"@backstage/backend-tasks": "^0.4.3-next.
|
|
36
|
+
"@backstage/backend-common": "^0.18.2-next.1",
|
|
37
|
+
"@backstage/backend-plugin-api": "^0.3.2-next.1",
|
|
38
|
+
"@backstage/backend-tasks": "^0.4.3-next.1",
|
|
39
39
|
"@backstage/catalog-model": "^1.1.6-next.0",
|
|
40
40
|
"@backstage/config": "^1.0.6",
|
|
41
41
|
"@backstage/errors": "^1.1.4",
|
|
42
42
|
"@backstage/integration": "^1.4.2",
|
|
43
|
-
"@backstage/plugin-catalog-backend": "^1.7.2-next.
|
|
44
|
-
"@backstage/plugin-catalog-node": "^1.3.3-next.
|
|
43
|
+
"@backstage/plugin-catalog-backend": "^1.7.2-next.1",
|
|
44
|
+
"@backstage/plugin-catalog-node": "^1.3.3-next.1",
|
|
45
45
|
"@backstage/types": "^1.0.2",
|
|
46
46
|
"lodash": "^4.17.21",
|
|
47
47
|
"node-fetch": "^2.6.7",
|
|
@@ -49,8 +49,8 @@
|
|
|
49
49
|
"winston": "^3.2.1"
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
52
|
-
"@backstage/backend-test-utils": "^0.1.34-next.
|
|
53
|
-
"@backstage/cli": "^0.22.
|
|
52
|
+
"@backstage/backend-test-utils": "^0.1.34-next.1",
|
|
53
|
+
"@backstage/cli": "^0.22.2-next.0",
|
|
54
54
|
"@types/lodash": "^4.14.151",
|
|
55
55
|
"@types/uuid": "^8.0.0",
|
|
56
56
|
"luxon": "^3.0.0",
|