@backstage/plugin-catalog-backend-module-gitlab 0.1.4-next.2 → 0.1.4

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 CHANGED
@@ -1,5 +1,90 @@
1
1
  # @backstage/plugin-catalog-backend-module-gitlab
2
2
 
3
+ ## 0.1.4
4
+
5
+ ### Patch Changes
6
+
7
+ - eea8126171: Add a new provider `GitlabDiscoveryEntityProvider` as replacement for `GitlabDiscoveryProcessor`
8
+
9
+ In order to migrate from the `GitlabDiscoveryProcessor` you need to apply
10
+ the following changes:
11
+
12
+ **Before:**
13
+
14
+ ```yaml
15
+ # app-config.yaml
16
+
17
+ catalog:
18
+ locations:
19
+ - type: gitlab-discovery
20
+ target: https://company.gitlab.com/prefix/*/catalog-info.yaml
21
+ ```
22
+
23
+ ```ts
24
+ /* packages/backend/src/plugins/catalog.ts */
25
+
26
+ import { GitlabDiscoveryProcessor } from '@backstage/plugin-catalog-backend-module-gitlab';
27
+
28
+ const builder = await CatalogBuilder.create(env);
29
+ /** ... other processors ... */
30
+ builder.addProcessor(
31
+ GitLabDiscoveryProcessor.fromConfig(env.config, { logger: env.logger }),
32
+ );
33
+ ```
34
+
35
+ **After:**
36
+
37
+ ```yaml
38
+ # app-config.yaml
39
+
40
+ catalog:
41
+ providers:
42
+ gitlab:
43
+ yourProviderId: # identifies your dataset / provider independent of config changes
44
+ host: gitlab-host # Identifies one of the hosts set up in the integrations
45
+ branch: main # Optional. Uses `master` as default
46
+ group: example-group # Group and subgroup (if needed) to look for repositories
47
+ entityFilename: catalog-info.yaml # Optional. Defaults to `catalog-info.yaml`
48
+ ```
49
+
50
+ ```ts
51
+ /* packages/backend/src/plugins/catalog.ts */
52
+
53
+ import { GitlabDiscoveryEntityProvider } from '@backstage/plugin-catalog-backend-module-gitlab';
54
+
55
+ const builder = await CatalogBuilder.create(env);
56
+ /** ... other processors and/or providers ... */
57
+ builder.addEntityProvider(
58
+ ...GitlabDiscoveryEntityProvider.fromConfig(env.config, {
59
+ logger: env.logger,
60
+ schedule: env.scheduler.createScheduledTaskRunner({
61
+ frequency: { minutes: 30 },
62
+ timeout: { minutes: 3 },
63
+ }),
64
+ }),
65
+ );
66
+ ```
67
+
68
+ - bad907d794: The `last_activity_after` timestamp is now being omitted when querying the GitLab API for the first time.
69
+ - 3ac4522537: do not create location object if file with component definition do not exists in project, that decrease count of request to gitlab with 404 status code. Now we can create processor with new flag to enable this logic:
70
+
71
+ ```ts
72
+ const processor = GitLabDiscoveryProcessor.fromConfig(config, {
73
+ logger,
74
+ skipReposWithoutExactFileMatch: true,
75
+ });
76
+ ```
77
+
78
+ **WARNING:** This new functionality does not support globs in the repo file path
79
+
80
+ - 8f7b1835df: Updated dependency `msw` to `^0.41.0`.
81
+ - Updated dependencies
82
+ - @backstage/plugin-catalog-backend@1.2.0
83
+ - @backstage/backend-tasks@0.3.2
84
+ - @backstage/backend-common@0.14.0
85
+ - @backstage/integration@1.2.1
86
+ - @backstage/catalog-model@1.0.3
87
+
3
88
  ## 0.1.4-next.2
4
89
 
5
90
  ### Patch Changes
package/dist/index.cjs.js CHANGED
@@ -6,10 +6,30 @@ var backendCommon = require('@backstage/backend-common');
6
6
  var integration = require('@backstage/integration');
7
7
  var pluginCatalogBackend = require('@backstage/plugin-catalog-backend');
8
8
  var fetch = require('node-fetch');
9
+ var uuid = require('uuid');
9
10
 
10
11
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
11
12
 
13
+ function _interopNamespace(e) {
14
+ if (e && e.__esModule) return e;
15
+ var n = Object.create(null);
16
+ if (e) {
17
+ Object.keys(e).forEach(function (k) {
18
+ if (k !== 'default') {
19
+ var d = Object.getOwnPropertyDescriptor(e, k);
20
+ Object.defineProperty(n, k, d.get ? d : {
21
+ enumerable: true,
22
+ get: function () { return e[k]; }
23
+ });
24
+ }
25
+ });
26
+ }
27
+ n["default"] = e;
28
+ return Object.freeze(n);
29
+ }
30
+
12
31
  var fetch__default = /*#__PURE__*/_interopDefaultLegacy(fetch);
32
+ var uuid__namespace = /*#__PURE__*/_interopNamespace(uuid);
13
33
 
14
34
  class GitLabClient {
15
35
  constructor(options) {
@@ -76,6 +96,32 @@ async function* paginated(request, options) {
76
96
  } while (res.nextPage);
77
97
  }
78
98
 
99
+ function readGitlabConfig(id, config) {
100
+ var _a, _b;
101
+ const group = config.getString("group");
102
+ const host = config.getString("host");
103
+ const branch = (_a = config.getOptionalString("branch")) != null ? _a : "master";
104
+ const catalogFile = (_b = config.getOptionalString("entityFilename")) != null ? _b : "catalog-info.yaml";
105
+ return {
106
+ id,
107
+ group,
108
+ branch,
109
+ host,
110
+ catalogFile
111
+ };
112
+ }
113
+ function readGitlabConfigs(config) {
114
+ const configs = [];
115
+ const providerConfigs = config.getOptionalConfig("catalog.providers.gitlab");
116
+ if (!providerConfigs) {
117
+ return configs;
118
+ }
119
+ for (const id of providerConfigs.keys()) {
120
+ configs.push(readGitlabConfig(id, providerConfigs.getConfig(id)));
121
+ }
122
+ return configs;
123
+ }
124
+
79
125
  class GitLabDiscoveryProcessor {
80
126
  static fromConfig(config, options) {
81
127
  const integrations = integration.ScmIntegrations.fromConfig(config);
@@ -99,6 +145,7 @@ class GitLabDiscoveryProcessor {
99
145
  if (location.type !== "gitlab-discovery") {
100
146
  return false;
101
147
  }
148
+ const startTime = new Date();
102
149
  const { group, host, branch, catalogPath } = parseUrl(location.target);
103
150
  const integration = this.integrations.gitlab.byUrl(`https://${host}`);
104
151
  if (!integration) {
@@ -108,13 +155,14 @@ class GitLabDiscoveryProcessor {
108
155
  config: integration.config,
109
156
  logger: this.logger
110
157
  });
111
- const startTimestamp = Date.now();
112
158
  this.logger.debug(`Reading GitLab projects from ${location.target}`);
113
- const projects = paginated((options) => client.listProjects(options), {
159
+ const lastActivity = await this.cache.get(this.getCacheKey());
160
+ const opts = {
114
161
  group,
115
- last_activity_after: await this.updateLastActivity(),
116
- page: 1
117
- });
162
+ page: 1,
163
+ ...lastActivity && { last_activity_after: lastActivity }
164
+ };
165
+ const projects = paginated((options) => client.listProjects(options), opts);
118
166
  const res = {
119
167
  scanned: 0,
120
168
  matches: []
@@ -144,15 +192,13 @@ class GitLabDiscoveryProcessor {
144
192
  presence: "optional"
145
193
  }));
146
194
  }
147
- const duration = ((Date.now() - startTimestamp) / 1e3).toFixed(1);
195
+ await this.cache.set(this.getCacheKey(), startTime.toISOString());
196
+ const duration = ((Date.now() - startTime.getTime()) / 1e3).toFixed(1);
148
197
  this.logger.debug(`Read ${res.scanned} GitLab repositories in ${duration} seconds`);
149
198
  return true;
150
199
  }
151
- async updateLastActivity() {
152
- const cacheKey = `processors/${this.getProcessorName()}/last-activity`;
153
- const lastActivity = await this.cache.get(cacheKey);
154
- await this.cache.set(cacheKey, new Date().toISOString());
155
- return lastActivity;
200
+ getCacheKey() {
201
+ return `processors/${this.getProcessorName()}/last-activity`;
156
202
  }
157
203
  }
158
204
  function parseUrl(urlString) {
@@ -171,5 +217,111 @@ function parseUrl(urlString) {
171
217
  throw new Error(`Failed to parse ${urlString}`);
172
218
  }
173
219
 
220
+ class GitlabDiscoveryEntityProvider {
221
+ static fromConfig(config, options) {
222
+ const providerConfigs = readGitlabConfigs(config);
223
+ const integrations = integration.ScmIntegrations.fromConfig(config).gitlab;
224
+ const providers = [];
225
+ providerConfigs.forEach((providerConfig) => {
226
+ const integration = integrations.byHost(providerConfig.host);
227
+ if (!integration) {
228
+ throw new Error(`No gitlab integration found that matches host ${providerConfig.host}`);
229
+ }
230
+ providers.push(new GitlabDiscoveryEntityProvider({
231
+ ...options,
232
+ config: providerConfig,
233
+ integration
234
+ }));
235
+ });
236
+ return providers;
237
+ }
238
+ constructor(options) {
239
+ this.config = options.config;
240
+ this.integration = options.integration;
241
+ this.logger = options.logger.child({
242
+ target: this.getProviderName()
243
+ });
244
+ this.scheduleFn = this.createScheduleFn(options.schedule);
245
+ }
246
+ getProviderName() {
247
+ return `GitlabDiscoveryEntityProvider:${this.config.id}`;
248
+ }
249
+ async connect(connection) {
250
+ this.connection = connection;
251
+ await this.scheduleFn();
252
+ }
253
+ createScheduleFn(schedule) {
254
+ return async () => {
255
+ const taskId = `${this.getProviderName()}:refresh`;
256
+ return schedule.run({
257
+ id: taskId,
258
+ fn: async () => {
259
+ const logger = this.logger.child({
260
+ class: GitlabDiscoveryEntityProvider.prototype.constructor.name,
261
+ taskId,
262
+ taskInstanceId: uuid__namespace.v4()
263
+ });
264
+ try {
265
+ await this.refresh(logger);
266
+ } catch (error) {
267
+ logger.error(error);
268
+ }
269
+ }
270
+ });
271
+ };
272
+ }
273
+ async refresh(logger) {
274
+ var _a, _b;
275
+ if (!this.connection) {
276
+ throw new Error(`Gitlab discovery connection not initialized for ${this.getProviderName()}`);
277
+ }
278
+ const client = new GitLabClient({
279
+ config: this.integration.config,
280
+ logger
281
+ });
282
+ const projects = paginated((options) => client.listProjects(options), {
283
+ group: this.config.group,
284
+ page: 1,
285
+ per_page: 50
286
+ });
287
+ const res = {
288
+ scanned: 0,
289
+ matches: []
290
+ };
291
+ for await (const project of projects) {
292
+ res.scanned++;
293
+ if (project.archived) {
294
+ continue;
295
+ }
296
+ if (this.config.branch === "*" && project.default_branch === void 0) {
297
+ continue;
298
+ }
299
+ const project_branch = (_a = project.default_branch) != null ? _a : this.config.branch;
300
+ const projectHasFile = await client.hasFile((_b = project.path_with_namespace) != null ? _b : "", project_branch, this.config.catalogFile);
301
+ if (projectHasFile) {
302
+ res.matches.push(project);
303
+ }
304
+ }
305
+ const locations = res.matches.map((p) => this.createLocationSpec(p));
306
+ await this.connection.applyMutation({
307
+ type: "full",
308
+ entities: locations.map((location) => ({
309
+ locationKey: this.getProviderName(),
310
+ entity: pluginCatalogBackend.locationSpecToLocationEntity({ location })
311
+ }))
312
+ });
313
+ }
314
+ createLocationSpec(project) {
315
+ var _a;
316
+ const project_branch = (_a = project.default_branch) != null ? _a : this.config.branch;
317
+ return {
318
+ type: "url",
319
+ target: `${project.web_url}/-/blob/${project_branch}/${this.config.catalogFile}`,
320
+ presence: "optional"
321
+ };
322
+ }
323
+ }
324
+
174
325
  exports.GitLabDiscoveryProcessor = GitLabDiscoveryProcessor;
326
+ exports.GitlabDiscoveryEntityProvider = GitlabDiscoveryEntityProvider;
175
327
  //# sourceMappingURL=index.cjs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs.js","sources":["../src/lib/client.ts","../src/GitLabDiscoveryProcessor.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 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 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 { 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 const startTimestamp = Date.now();\n this.logger.debug(`Reading GitLab projects from ${location.target}`);\n\n const projects = paginated(options => client.listProjects(options), {\n group,\n last_activity_after: await this.updateLastActivity(),\n page: 1,\n });\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 const duration = ((Date.now() - startTimestamp) / 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 async updateLastActivity(): Promise<string | undefined> {\n const cacheKey = `processors/${this.getProcessorName()}/last-activity`;\n const lastActivity = await this.cache.get(cacheKey);\n await this.cache.set(cacheKey, new Date().toISOString());\n return lastActivity as string | undefined;\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"],"names":["fetch","getGitLabRequestOptions","ScmIntegrations","CacheManager","processingResult"],"mappings":";;;;;;;;;;;;;AAIO,MAAM,YAAY,CAAC;AAC1B,EAAE,WAAW,CAAC,OAAO,EAAE;AACvB,IAAI,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;AACjC,IAAI,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;AACjC,GAAG;AACH,EAAE,aAAa,GAAG;AAClB,IAAI,OAAO,IAAI,CAAC,MAAM,CAAC,IAAI,KAAK,YAAY,CAAC;AAC7C,GAAG;AACH,EAAE,MAAM,YAAY,CAAC,OAAO,EAAE;AAC9B,IAAI,IAAI,OAAO,IAAI,IAAI,GAAG,KAAK,CAAC,GAAG,OAAO,CAAC,KAAK,EAAE;AAClD,MAAM,OAAO,IAAI,CAAC,YAAY,CAAC,CAAC,QAAQ,EAAE,kBAAkB,CAAC,OAAO,IAAI,IAAI,GAAG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AI,EAAE,GAAG,CAAC,IAAI;AACpB,MAAM,MAAM,EAAE,kBAAkB,CAAC,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC;AACrD,MAAM,WAAW,EAAE,kBAAkB,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC1E,KAAK,CAAC;AACN,GAAG;AACH,EAAE,MAAM,IAAI,KAAK,CAAC,CAAC,gBAAgB,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC;AAClD;;;;"}
1
+ {"version":3,"file":"index.cjs.js","sources":["../src/lib/client.ts","../src/providers/config.ts","../src/GitLabDiscoveryProcessor.ts","../src/providers/GitlabDiscoveryEntityProvider.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 { Config } from '@backstage/config';\nimport { GitlabProviderConfig } from '../lib/types';\n\n/**\n * Extracts the gitlab config from a config object\n *\n * @public\n *\n * @param config - The config object to extract from\n */\nfunction readGitlabConfig(id: string, config: Config): GitlabProviderConfig {\n const group = config.getString('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\n return {\n id,\n group,\n branch,\n host,\n catalogFile,\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 { 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 { LocationSpec } from '@backstage/plugin-catalog-backend';\nimport { Logger } from 'winston';\nimport {\n GitLabClient,\n GitLabProject,\n GitlabProviderConfig,\n paginated,\n readGitlabConfigs,\n} from '../lib';\nimport * as uuid from 'uuid';\nimport { locationSpecToLocationEntity } from '@backstage/plugin-catalog-backend';\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: { logger: Logger; schedule: TaskRunner },\n ): GitlabDiscoveryEntityProvider[] {\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 providers.push(\n new GitlabDiscoveryEntityProvider({\n ...options,\n config: providerConfig,\n integration,\n }),\n );\n });\n return providers;\n }\n\n private constructor(options: {\n config: GitlabProviderConfig;\n integration: GitLabIntegration;\n logger: Logger;\n schedule: 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.schedule);\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(schedule: TaskRunner): () => Promise<void> {\n return async () => {\n const taskId = `${this.getProviderName()}:refresh`;\n return schedule.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(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 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"],"names":["fetch","getGitLabRequestOptions","ScmIntegrations","CacheManager","processingResult","uuid","locationSpecToLocationEntity"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIO,MAAM,YAAY,CAAC;AAC1B,EAAE,WAAW,CAAC,OAAO,EAAE;AACvB,IAAI,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;AACjC,IAAI,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;AACjC,GAAG;AACH,EAAE,aAAa,GAAG;AAClB,IAAI,OAAO,IAAI,CAAC,MAAM,CAAC,IAAI,KAAK,YAAY,CAAC;AAC7C,GAAG;AACH,EAAE,MAAM,YAAY,CAAC,OAAO,EAAE;AAC9B,IAAI,IAAI,OAAO,IAAI,IAAI,GAAG,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C,CAAC;AACtF,MAAM,QAAQ,EAAE,UAAU;AAC1B,KAAK,CAAC;AACN,GAAG;AACH;;;;;"}
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Config } from '@backstage/config';
2
- import { CatalogProcessor, LocationSpec, CatalogProcessorEmit } from '@backstage/plugin-catalog-backend';
2
+ import { CatalogProcessor, LocationSpec, CatalogProcessorEmit, EntityProvider, EntityProviderConnection } from '@backstage/plugin-catalog-backend';
3
3
  import { Logger } from 'winston';
4
+ import { TaskRunner } from '@backstage/backend-tasks';
4
5
 
5
6
  /**
6
7
  * Extracts repositories out of an GitLab instance.
@@ -18,7 +19,29 @@ declare class GitLabDiscoveryProcessor implements CatalogProcessor {
18
19
  private constructor();
19
20
  getProcessorName(): string;
20
21
  readLocation(location: LocationSpec, _optional: boolean, emit: CatalogProcessorEmit): Promise<boolean>;
21
- private updateLastActivity;
22
+ private getCacheKey;
22
23
  }
23
24
 
24
- export { GitLabDiscoveryProcessor };
25
+ /**
26
+ * Discovers entity definition files in the groups of a Gitlab instance.
27
+ * @public
28
+ */
29
+ declare class GitlabDiscoveryEntityProvider implements EntityProvider {
30
+ private readonly config;
31
+ private readonly integration;
32
+ private readonly logger;
33
+ private readonly scheduleFn;
34
+ private connection?;
35
+ static fromConfig(config: Config, options: {
36
+ logger: Logger;
37
+ schedule: TaskRunner;
38
+ }): GitlabDiscoveryEntityProvider[];
39
+ private constructor();
40
+ getProviderName(): string;
41
+ connect(connection: EntityProviderConnection): Promise<void>;
42
+ private createScheduleFn;
43
+ refresh(logger: Logger): Promise<void>;
44
+ private createLocationSpec;
45
+ }
46
+
47
+ export { GitLabDiscoveryProcessor, GitlabDiscoveryEntityProvider };
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.4-next.2",
4
+ "version": "0.1.4",
5
5
  "main": "dist/index.cjs.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "license": "Apache-2.0",
@@ -33,25 +33,28 @@
33
33
  "start": "backstage-cli package start"
34
34
  },
35
35
  "dependencies": {
36
- "@backstage/backend-common": "^0.14.0-next.2",
37
- "@backstage/catalog-model": "^1.0.3-next.0",
36
+ "@backstage/backend-common": "^0.14.0",
37
+ "@backstage/backend-tasks": "^0.3.2",
38
+ "@backstage/catalog-model": "^1.0.3",
38
39
  "@backstage/config": "^1.0.1",
39
40
  "@backstage/errors": "^1.0.0",
40
- "@backstage/integration": "^1.2.1-next.2",
41
- "@backstage/plugin-catalog-backend": "^1.2.0-next.2",
41
+ "@backstage/integration": "^1.2.1",
42
+ "@backstage/plugin-catalog-backend": "^1.2.0",
42
43
  "@backstage/types": "^1.0.0",
43
44
  "lodash": "^4.17.21",
44
45
  "msw": "^0.42.0",
45
46
  "node-fetch": "^2.6.7",
47
+ "uuid": "^8.0.0",
46
48
  "winston": "^3.2.1"
47
49
  },
48
50
  "devDependencies": {
49
- "@backstage/backend-test-utils": "^0.1.25-next.2",
50
- "@backstage/cli": "^0.17.2-next.2",
51
- "@types/lodash": "^4.14.151"
51
+ "@backstage/backend-test-utils": "^0.1.25",
52
+ "@backstage/cli": "^0.17.2",
53
+ "@types/lodash": "^4.14.151",
54
+ "@types/uuid": "^8.0.0"
52
55
  },
53
56
  "files": [
54
57
  "dist"
55
58
  ],
56
- "gitHead": "afc672d59763a835574e6c47819107d22cfd1ad7"
59
+ "gitHead": "e42cb3887e41f756c16380d757d93feda27f40ee"
57
60
  }