@backstage/plugin-catalog-backend-module-gitlab 0.7.7 → 0.8.0-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 CHANGED
@@ -1,5 +1,38 @@
1
1
  # @backstage/plugin-catalog-backend-module-gitlab
2
2
 
3
+ ## 0.8.0-next.1
4
+
5
+ ### Minor Changes
6
+
7
+ - 2f51676: allow entity discoverability via gitlab search API
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies
12
+ - @backstage/integration@1.20.0-next.1
13
+ - @backstage/backend-plugin-api@1.7.0-next.1
14
+ - @backstage/backend-defaults@0.15.2-next.1
15
+
16
+ ## 0.8.0-next.0
17
+
18
+ ### Minor Changes
19
+
20
+ - ff07934: Added the `{gitlab-integration-host}/user-id` annotation to store GitLab's user ID (immutable) in user entities. Also includes addition of the `userIdMatchingUserEntityAnnotation` sign-in resolver that matches users by the new ID.
21
+
22
+ ### Patch Changes
23
+
24
+ - cfd8103: Updated imports to use stable catalog extension points from `@backstage/plugin-catalog-node` instead of the deprecated alpha exports.
25
+ - 7455dae: Use node prefix on native imports
26
+ - Updated dependencies
27
+ - @backstage/plugin-catalog-node@1.21.0-next.0
28
+ - @backstage/backend-plugin-api@1.7.0-next.0
29
+ - @backstage/backend-defaults@0.15.1-next.0
30
+ - @backstage/integration@1.19.3-next.0
31
+ - @backstage/plugin-events-node@0.4.19-next.0
32
+ - @backstage/catalog-model@1.7.6
33
+ - @backstage/config@1.3.6
34
+ - @backstage/plugin-catalog-common@1.1.8-next.0
35
+
3
36
  ## 0.7.7
4
37
 
5
38
  ### Patch Changes
package/dist/index.d.ts CHANGED
@@ -79,6 +79,13 @@ declare class GitlabDiscoveryEntityProvider implements EntityProvider {
79
79
  * @param logger - The logger instance for logging.
80
80
  */
81
81
  refresh(logger: LoggerService): Promise<void>;
82
+ /**
83
+ * Determine the location on GitLab to be ingested.
84
+ * Uses GitLab's search API to find projects matching provided configuration.
85
+ *
86
+ * @returns A list of location to be ingested
87
+ */
88
+ private searchEntities;
82
89
  /**
83
90
  * Determine the location on GitLab to be ingested base on configured groups and filters.
84
91
  *
@@ -99,6 +106,7 @@ declare class GitlabDiscoveryEntityProvider implements EntityProvider {
99
106
  * @returns An array of project to be processed and the number of project scanned
100
107
  */
101
108
  private getProjectsToProcess;
109
+ private createLocationSpecFromParams;
102
110
  private createLocationSpec;
103
111
  /**
104
112
  * Handles the "gitlab.push" event.
@@ -131,7 +139,9 @@ declare class GitlabDiscoveryEntityProvider implements EntityProvider {
131
139
  */
132
140
  private toLocationSpec;
133
141
  private toDeferredEntities;
142
+ private isProjectCompliant;
134
143
  private shouldProcessProject;
144
+ private isGroupCompliant;
135
145
  }
136
146
 
137
147
  /**
@@ -231,6 +241,10 @@ type GitlabProviderConfig = {
231
241
  * @deprecated Use the `relations` array to configure group membership relations instead.
232
242
  **/
233
243
  allowInherited?: boolean;
244
+ /**
245
+ * If true, use the GitLab search API to find projects locations.
246
+ */
247
+ useSearch?: boolean;
234
248
  /**
235
249
  * Specifies the types of group membership relations that should be included when ingesting data.
236
250
  *
@@ -81,6 +81,20 @@ class GitLabClient {
81
81
  async listGroups(options) {
82
82
  return this.pagedRequest(`/groups`, options);
83
83
  }
84
+ async listFiles(options) {
85
+ if (options?.group && options?.search) {
86
+ return this.pagedRequest(
87
+ `/groups/${encodeURIComponent(options?.group)}/search`,
88
+ {
89
+ ...options,
90
+ scope: "blob"
91
+ }
92
+ );
93
+ }
94
+ return {
95
+ items: []
96
+ };
97
+ }
84
98
  // https://docs.gitlab.com/ee/api/groups.html#list-group-details
85
99
  // id can either be group id or encoded full path
86
100
  async getGroupByPath(groupPath, options) {
@@ -1 +1 @@
1
- {"version":3,"file":"client.cjs.js","sources":["../../src/lib/client.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\n// NOTE(freben): Intentionally uses node-fetch because of https://github.com/backstage/backstage/issues/28190\nimport fetch from 'node-fetch';\n\nimport {\n getGitLabRequestOptions,\n GitLabIntegrationConfig,\n} from '@backstage/integration';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport {\n GitLabDescendantGroupsResponse,\n GitLabGroup,\n GitLabGroupMembersResponse,\n GitLabProject,\n GitLabUser,\n PagedResponse,\n} 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 archived?: boolean;\n group?: string;\n membership?: boolean;\n topics?: string;\n simple?: boolean;\n}\n\ninterface UserListOptions extends CommonListOptions {\n without_project_bots?: boolean | undefined;\n exclude_internal?: boolean | undefined;\n}\n\nexport class GitLabClient {\n private readonly config: GitLabIntegrationConfig;\n private readonly logger: LoggerService;\n\n constructor(options: {\n config: GitLabIntegrationConfig;\n logger: LoggerService;\n }) {\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 getProjectById(\n projectId: number,\n options?: CommonListOptions,\n ): Promise<GitLabProject> {\n // Make the request to the GitLab API\n const response = await this.nonPagedRequest(\n `/projects/${projectId}`,\n options,\n );\n\n return response;\n }\n\n async getGroupById(\n groupId: number,\n options?: CommonListOptions,\n ): Promise<GitLabGroup> {\n // Make the request to the GitLab API\n const response = await this.nonPagedRequest(`/groups/${groupId}`, options);\n\n return response;\n }\n\n async getUserById(\n userId: number,\n options?: CommonListOptions,\n ): Promise<GitLabUser> {\n // Make the request to the GitLab API\n const response = await this.nonPagedRequest(`/users/${userId}`, options);\n\n return response;\n }\n\n async listGroupMembers(\n groupPath: string,\n options?: CommonListOptions,\n ): Promise<PagedResponse<GitLabUser>> {\n return this.pagedRequest(\n `/groups/${encodeURIComponent(groupPath)}/members/all`,\n options,\n );\n }\n\n async listUsers(\n options?: UserListOptions,\n ): Promise<PagedResponse<GitLabUser>> {\n return this.pagedRequest(`/users?`, {\n ...options,\n without_project_bots: true,\n exclude_internal: true,\n });\n }\n\n async listSaaSUsers(\n groupPath: string,\n options?: CommonListOptions,\n includeUsersWithoutSeat?: boolean,\n ): Promise<PagedResponse<GitLabUser>> {\n const botFilterRegex = /^(?:project|group)_(\\w+)_bot_(\\w+)$/;\n\n return this.listGroupMembers(groupPath, {\n ...options,\n active: true, // Users with seat are always active but for users without seat we need to filter\n show_seat_info: true,\n }).then(resp => {\n // Filter is optional to allow to import Gitlab Free users without seats\n // https://github.com/backstage/backstage/issues/26438\n // Filter out API tokens https://docs.gitlab.com/ee/user/project/settings/project_access_tokens.html#bot-users-for-projects\n if (includeUsersWithoutSeat) {\n resp.items = resp.items.filter(user => {\n return !botFilterRegex.test(user.username);\n });\n } else {\n resp.items = resp.items.filter(user => user.is_using_seat);\n }\n return resp;\n });\n }\n\n async listGroups(\n options?: CommonListOptions,\n ): Promise<PagedResponse<GitLabGroup>> {\n return this.pagedRequest(`/groups`, options);\n }\n\n // https://docs.gitlab.com/ee/api/groups.html#list-group-details\n // id can either be group id or encoded full path\n async getGroupByPath(\n groupPath: string,\n options?: CommonListOptions,\n ): Promise<GitLabGroup> {\n return this.nonPagedRequest(\n `/groups/${encodeURIComponent(groupPath)}`,\n options,\n );\n }\n\n async listDescendantGroups(\n groupPath: string,\n ): Promise<PagedResponse<GitLabGroup>> {\n const items: GitLabGroup[] = [];\n let hasNextPage: boolean = false;\n let endCursor: string | null = null;\n\n do {\n const response: GitLabDescendantGroupsResponse =\n await this.fetchWithRetry(`${this.config.baseUrl}/api/graphql`, {\n method: 'POST',\n headers: {\n ...getGitLabRequestOptions(this.config).headers,\n ['Content-Type']: 'application/json',\n },\n body: JSON.stringify({\n variables: { group: groupPath, endCursor },\n query: /* GraphQL */ `\n query listDescendantGroups($group: ID!, $endCursor: String) {\n group(fullPath: $group) {\n descendantGroups(first: 100, after: $endCursor) {\n nodes {\n id\n name\n description\n fullPath\n visibility\n parent {\n id\n }\n }\n pageInfo {\n endCursor\n hasNextPage\n }\n }\n }\n }\n `,\n }),\n }).then(r => r.json());\n if (response.errors) {\n throw new Error(`GraphQL errors: ${JSON.stringify(response.errors)}`);\n }\n\n if (!response.data.group?.descendantGroups?.nodes) {\n this.logger.warn(\n `Couldn't get groups under ${groupPath}. The provided token might not have sufficient permissions`,\n );\n continue;\n }\n\n for (const groupItem of response.data.group.descendantGroups.nodes.filter(\n group => group?.id,\n )) {\n const formattedGroupResponse = {\n id: Number(groupItem.id.replace(/^gid:\\/\\/gitlab\\/Group\\//, '')),\n name: groupItem.name,\n description: groupItem.description,\n full_path: groupItem.fullPath,\n visibility: groupItem.visibility,\n parent_id: Number(\n groupItem.parent.id.replace(/^gid:\\/\\/gitlab\\/Group\\//, ''),\n ),\n };\n\n items.push(formattedGroupResponse);\n }\n ({ hasNextPage, endCursor } =\n response.data.group.descendantGroups.pageInfo);\n } while (hasNextPage);\n return { items };\n }\n\n async getGroupMembers(\n groupPath: string,\n relations: string[],\n ): Promise<PagedResponse<GitLabUser>> {\n const items: GitLabUser[] = [];\n let hasNextPage: boolean = false;\n let endCursor: string | null = null;\n do {\n const response: GitLabGroupMembersResponse = await this.fetchWithRetry(\n `${this.config.baseUrl}/api/graphql`,\n {\n method: 'POST',\n headers: {\n ...getGitLabRequestOptions(this.config).headers,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n variables: { group: groupPath, relations: relations, endCursor },\n query: /* GraphQL */ `\n query getGroupMembers(\n $group: ID!\n $relations: [GroupMemberRelation!]\n $endCursor: String\n ) {\n group(fullPath: $group) {\n groupMembers(\n first: 100\n relations: $relations\n after: $endCursor\n ) {\n nodes {\n user {\n id\n username\n publicEmail\n name\n state\n webUrl\n avatarUrl\n }\n }\n pageInfo {\n endCursor\n hasNextPage\n }\n }\n }\n }\n `,\n }),\n },\n ).then(r => r.json());\n if (response.errors) {\n throw new Error(`GraphQL errors: ${JSON.stringify(response.errors)}`);\n }\n\n if (!response.data.group?.groupMembers?.nodes) {\n this.logger.warn(\n `Couldn't get members for group ${groupPath}. The provided token might not have sufficient permissions`,\n );\n continue;\n }\n\n for (const userItem of response.data.group.groupMembers.nodes.filter(\n user => user.user?.id,\n )) {\n const formattedUserResponse = {\n id: Number(userItem.user.id.replace(/^gid:\\/\\/gitlab\\/User\\//, '')),\n username: userItem.user.username,\n email: userItem.user.publicEmail,\n name: userItem.user.name,\n state: userItem.user.state,\n web_url: userItem.user.webUrl,\n avatar_url: userItem.user.avatarUrl,\n };\n\n items.push(formattedUserResponse);\n }\n ({ hasNextPage, endCursor } = response.data.group.groupMembers.pageInfo);\n } while (hasNextPage);\n return { items };\n }\n\n /**\n * General existence check.\n * @see {@link https://docs.gitlab.com/api/repository_files/#get-file-from-repository | GitLab Repository Files API}\n *\n * @param projectIdentifier - The identifier of the project, either the numeric ID or the namespaced path.\n * @param branch - The branch used to search\n * @param filePath - The path to the file\n */\n async hasFile(\n projectIdentifier: string | number,\n branch: string,\n filePath: string,\n ): Promise<boolean> {\n const endpoint: string = `/projects/${encodeURIComponent(\n projectIdentifier,\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 this.fetchWithRetry(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\n for (const key in options) {\n if (options.hasOwnProperty(key)) {\n const value = options[key];\n if (value !== undefined && value !== '') {\n request.searchParams.append(key, value.toString());\n }\n }\n }\n\n this.logger.debug(`Fetching: ${request.toString()}`);\n const response = await this.fetchWithRetry(\n request.toString(),\n getGitLabRequestOptions(this.config),\n );\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\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 async nonPagedRequest<T = any>(\n endpoint: string,\n options?: CommonListOptions,\n ): Promise<T> {\n const request = new URL(`${this.config.apiBaseUrl}${endpoint}`);\n\n for (const key in options) {\n if (options.hasOwnProperty(key)) {\n const value = options[key];\n if (value !== undefined && value !== '') {\n request.searchParams.append(key, value.toString());\n }\n }\n }\n\n const response = await this.fetchWithRetry(\n request.toString(),\n getGitLabRequestOptions(this.config),\n );\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\n return response.json();\n }\n\n /**\n * Performs a fetch request with retry logic for rate limiting (429 errors)\n * @param url - The URL to fetch\n * @param options - Fetch options\n * @param retries - Maximum number of retries\n * @param initialBackoff - Initial backoff time in ms\n */\n async fetchWithRetry(\n url: string,\n options: fetch.RequestInit,\n retries = 5,\n initialBackoff = 100,\n ): Promise<fetch.Response> {\n let currentRetry = 0;\n let backoff = initialBackoff;\n\n for (;;) {\n const response = await fetch(url, options);\n\n if (response.status !== 429 || currentRetry >= retries) {\n return response;\n }\n\n // Get retry-after header if available, or use exponential backoff\n const retryAfter = response.headers.get('Retry-After');\n const waitTime = retryAfter ? parseInt(retryAfter, 10) * 1000 : backoff;\n\n this.logger.warn(\n `GitLab API rate limit exceeded, retrying in ${waitTime}ms (retry ${\n currentRetry + 1\n }/${retries})`,\n );\n\n // Wait before retrying\n await new Promise(resolve => setTimeout(resolve, waitTime));\n\n // Exponential backoff with jitter\n backoff = backoff * 2 * (0.8 + Math.random() * 0.4);\n currentRetry++;\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"],"names":["getGitLabRequestOptions","fetch"],"mappings":";;;;;;;;;AAqDO,MAAM,YAAA,CAAa;AAAA,EACP,MAAA;AAAA,EACA,MAAA;AAAA,EAEjB,YAAY,OAAA,EAGT;AACD,IAAA,IAAA,CAAK,SAAS,OAAA,CAAQ,MAAA;AACtB,IAAA,IAAA,CAAK,SAAS,OAAA,CA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AAI,QAAA;AACf;;;;;"}
1
+ {"version":3,"file":"client.cjs.js","sources":["../../src/lib/client.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\n// NOTE(freben): Intentionally uses node-fetch because of https://github.com/backstage/backstage/issues/28190\nimport fetch from 'node-fetch';\n\nimport {\n getGitLabRequestOptions,\n GitLabIntegrationConfig,\n} from '@backstage/integration';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport {\n GitLabDescendantGroupsResponse,\n GitLabFile,\n GitLabGroup,\n GitLabGroupMembersResponse,\n GitLabProject,\n GitLabUser,\n PagedResponse,\n} 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 archived?: boolean;\n group?: string;\n membership?: boolean;\n topics?: string;\n simple?: boolean;\n}\n\ninterface ListFilesOptions extends CommonListOptions {\n group?: string;\n search?: string;\n}\n\ninterface UserListOptions extends CommonListOptions {\n without_project_bots?: boolean | undefined;\n exclude_internal?: boolean | undefined;\n}\n\nexport class GitLabClient {\n private readonly config: GitLabIntegrationConfig;\n private readonly logger: LoggerService;\n\n constructor(options: {\n config: GitLabIntegrationConfig;\n logger: LoggerService;\n }) {\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 getProjectById(\n projectId: number,\n options?: CommonListOptions,\n ): Promise<GitLabProject> {\n // Make the request to the GitLab API\n const response = await this.nonPagedRequest(\n `/projects/${projectId}`,\n options,\n );\n\n return response;\n }\n\n async getGroupById(\n groupId: number,\n options?: CommonListOptions,\n ): Promise<GitLabGroup> {\n // Make the request to the GitLab API\n const response = await this.nonPagedRequest(`/groups/${groupId}`, options);\n\n return response;\n }\n\n async getUserById(\n userId: number,\n options?: CommonListOptions,\n ): Promise<GitLabUser> {\n // Make the request to the GitLab API\n const response = await this.nonPagedRequest(`/users/${userId}`, options);\n\n return response;\n }\n\n async listGroupMembers(\n groupPath: string,\n options?: CommonListOptions,\n ): Promise<PagedResponse<GitLabUser>> {\n return this.pagedRequest(\n `/groups/${encodeURIComponent(groupPath)}/members/all`,\n options,\n );\n }\n\n async listUsers(\n options?: UserListOptions,\n ): Promise<PagedResponse<GitLabUser>> {\n return this.pagedRequest(`/users?`, {\n ...options,\n without_project_bots: true,\n exclude_internal: true,\n });\n }\n\n async listSaaSUsers(\n groupPath: string,\n options?: CommonListOptions,\n includeUsersWithoutSeat?: boolean,\n ): Promise<PagedResponse<GitLabUser>> {\n const botFilterRegex = /^(?:project|group)_(\\w+)_bot_(\\w+)$/;\n\n return this.listGroupMembers(groupPath, {\n ...options,\n active: true, // Users with seat are always active but for users without seat we need to filter\n show_seat_info: true,\n }).then(resp => {\n // Filter is optional to allow to import Gitlab Free users without seats\n // https://github.com/backstage/backstage/issues/26438\n // Filter out API tokens https://docs.gitlab.com/ee/user/project/settings/project_access_tokens.html#bot-users-for-projects\n if (includeUsersWithoutSeat) {\n resp.items = resp.items.filter(user => {\n return !botFilterRegex.test(user.username);\n });\n } else {\n resp.items = resp.items.filter(user => user.is_using_seat);\n }\n return resp;\n });\n }\n\n async listGroups(\n options?: CommonListOptions,\n ): Promise<PagedResponse<GitLabGroup>> {\n return this.pagedRequest(`/groups`, options);\n }\n\n async listFiles(\n options?: ListFilesOptions,\n ): Promise<PagedResponse<GitLabFile>> {\n if (options?.group && options?.search) {\n return this.pagedRequest(\n `/groups/${encodeURIComponent(options?.group)}/search`,\n {\n ...options,\n scope: 'blob',\n },\n );\n }\n\n return {\n items: [],\n };\n }\n\n // https://docs.gitlab.com/ee/api/groups.html#list-group-details\n // id can either be group id or encoded full path\n async getGroupByPath(\n groupPath: string,\n options?: CommonListOptions,\n ): Promise<GitLabGroup> {\n return this.nonPagedRequest(\n `/groups/${encodeURIComponent(groupPath)}`,\n options,\n );\n }\n\n async listDescendantGroups(\n groupPath: string,\n ): Promise<PagedResponse<GitLabGroup>> {\n const items: GitLabGroup[] = [];\n let hasNextPage: boolean = false;\n let endCursor: string | null = null;\n\n do {\n const response: GitLabDescendantGroupsResponse =\n await this.fetchWithRetry(`${this.config.baseUrl}/api/graphql`, {\n method: 'POST',\n headers: {\n ...getGitLabRequestOptions(this.config).headers,\n ['Content-Type']: 'application/json',\n },\n body: JSON.stringify({\n variables: { group: groupPath, endCursor },\n query: /* GraphQL */ `\n query listDescendantGroups($group: ID!, $endCursor: String) {\n group(fullPath: $group) {\n descendantGroups(first: 100, after: $endCursor) {\n nodes {\n id\n name\n description\n fullPath\n visibility\n parent {\n id\n }\n }\n pageInfo {\n endCursor\n hasNextPage\n }\n }\n }\n }\n `,\n }),\n }).then(r => r.json());\n if (response.errors) {\n throw new Error(`GraphQL errors: ${JSON.stringify(response.errors)}`);\n }\n\n if (!response.data.group?.descendantGroups?.nodes) {\n this.logger.warn(\n `Couldn't get groups under ${groupPath}. The provided token might not have sufficient permissions`,\n );\n continue;\n }\n\n for (const groupItem of response.data.group.descendantGroups.nodes.filter(\n group => group?.id,\n )) {\n const formattedGroupResponse = {\n id: Number(groupItem.id.replace(/^gid:\\/\\/gitlab\\/Group\\//, '')),\n name: groupItem.name,\n description: groupItem.description,\n full_path: groupItem.fullPath,\n visibility: groupItem.visibility,\n parent_id: Number(\n groupItem.parent.id.replace(/^gid:\\/\\/gitlab\\/Group\\//, ''),\n ),\n };\n\n items.push(formattedGroupResponse);\n }\n ({ hasNextPage, endCursor } =\n response.data.group.descendantGroups.pageInfo);\n } while (hasNextPage);\n return { items };\n }\n\n async getGroupMembers(\n groupPath: string,\n relations: string[],\n ): Promise<PagedResponse<GitLabUser>> {\n const items: GitLabUser[] = [];\n let hasNextPage: boolean = false;\n let endCursor: string | null = null;\n do {\n const response: GitLabGroupMembersResponse = await this.fetchWithRetry(\n `${this.config.baseUrl}/api/graphql`,\n {\n method: 'POST',\n headers: {\n ...getGitLabRequestOptions(this.config).headers,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n variables: { group: groupPath, relations: relations, endCursor },\n query: /* GraphQL */ `\n query getGroupMembers(\n $group: ID!\n $relations: [GroupMemberRelation!]\n $endCursor: String\n ) {\n group(fullPath: $group) {\n groupMembers(\n first: 100\n relations: $relations\n after: $endCursor\n ) {\n nodes {\n user {\n id\n username\n publicEmail\n name\n state\n webUrl\n avatarUrl\n }\n }\n pageInfo {\n endCursor\n hasNextPage\n }\n }\n }\n }\n `,\n }),\n },\n ).then(r => r.json());\n if (response.errors) {\n throw new Error(`GraphQL errors: ${JSON.stringify(response.errors)}`);\n }\n\n if (!response.data.group?.groupMembers?.nodes) {\n this.logger.warn(\n `Couldn't get members for group ${groupPath}. The provided token might not have sufficient permissions`,\n );\n continue;\n }\n\n for (const userItem of response.data.group.groupMembers.nodes.filter(\n user => user.user?.id,\n )) {\n const formattedUserResponse = {\n id: Number(userItem.user.id.replace(/^gid:\\/\\/gitlab\\/User\\//, '')),\n username: userItem.user.username,\n email: userItem.user.publicEmail,\n name: userItem.user.name,\n state: userItem.user.state,\n web_url: userItem.user.webUrl,\n avatar_url: userItem.user.avatarUrl,\n };\n\n items.push(formattedUserResponse);\n }\n ({ hasNextPage, endCursor } = response.data.group.groupMembers.pageInfo);\n } while (hasNextPage);\n return { items };\n }\n\n /**\n * General existence check.\n * @see {@link https://docs.gitlab.com/api/repository_files/#get-file-from-repository | GitLab Repository Files API}\n *\n * @param projectIdentifier - The identifier of the project, either the numeric ID or the namespaced path.\n * @param branch - The branch used to search\n * @param filePath - The path to the file\n */\n async hasFile(\n projectIdentifier: string | number,\n branch: string,\n filePath: string,\n ): Promise<boolean> {\n const endpoint: string = `/projects/${encodeURIComponent(\n projectIdentifier,\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 this.fetchWithRetry(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\n for (const key in options) {\n if (options.hasOwnProperty(key)) {\n const value = options[key];\n if (value !== undefined && value !== '') {\n request.searchParams.append(key, value.toString());\n }\n }\n }\n\n this.logger.debug(`Fetching: ${request.toString()}`);\n const response = await this.fetchWithRetry(\n request.toString(),\n getGitLabRequestOptions(this.config),\n );\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\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 async nonPagedRequest<T = any>(\n endpoint: string,\n options?: CommonListOptions,\n ): Promise<T> {\n const request = new URL(`${this.config.apiBaseUrl}${endpoint}`);\n\n for (const key in options) {\n if (options.hasOwnProperty(key)) {\n const value = options[key];\n if (value !== undefined && value !== '') {\n request.searchParams.append(key, value.toString());\n }\n }\n }\n\n const response = await this.fetchWithRetry(\n request.toString(),\n getGitLabRequestOptions(this.config),\n );\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\n return response.json();\n }\n\n /**\n * Performs a fetch request with retry logic for rate limiting (429 errors)\n * @param url - The URL to fetch\n * @param options - Fetch options\n * @param retries - Maximum number of retries\n * @param initialBackoff - Initial backoff time in ms\n */\n async fetchWithRetry(\n url: string,\n options: fetch.RequestInit,\n retries = 5,\n initialBackoff = 100,\n ): Promise<fetch.Response> {\n let currentRetry = 0;\n let backoff = initialBackoff;\n\n for (;;) {\n const response = await fetch(url, options);\n\n if (response.status !== 429 || currentRetry >= retries) {\n return response;\n }\n\n // Get retry-after header if available, or use exponential backoff\n const retryAfter = response.headers.get('Retry-After');\n const waitTime = retryAfter ? parseInt(retryAfter, 10) * 1000 : backoff;\n\n this.logger.warn(\n `GitLab API rate limit exceeded, retrying in ${waitTime}ms (retry ${\n currentRetry + 1\n }/${retries})`,\n );\n\n // Wait before retrying\n await new Promise(resolve => setTimeout(resolve, waitTime));\n\n // Exponential backoff with jitter\n backoff = backoff * 2 * (0.8 + Math.random() * 0.4);\n currentRetry++;\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"],"names":["getGitLabRequestOptions","fetch"],"mappings":";;;;;;;;;AA2DO,MAAM,YAAA,CAAa;AAAA,EACP,MAAA;AAAA,EACA,MAAA;AAAA,EAEjB,YAAY,OAAA,EAGT;AACD,IAAA,IAAA,CAAK,SAAS,OAAA,CAAQ,MAAA;AACtB,IAAA,IAAA,CAAK,SAAS,OAAA,CAAQ,MAAA;AAAA,EACxB;AAAA;AAAA;AAAA;AAAA,EAKA,aAAA,GAAyB;AACvB,IAAA,OAAO,IAAA,CAAK,OAAO,IAAA,KAAS,YAAA;AAAA,EAC9B;AAAA,EAEA,MAAM,aACJ,OAAA,EAC6B;AAC7B,IAAA,IAAI,SAAS,KAAA,EAAO;AAClB,MAAA,OAAO,IAAA,CAAK,YAAA;AAAA,QACV,CAAA,QAAA,EAAW,kBAAA,CAAmB,OAAA,EAAS,KAAK,CAAC,CAAA,SAAA,CAAA;AAAA,QAC7C;AAAA,UACE,GAAG,OAAA;AAAA,UACH,iBAAA,EAAmB;AAAA;AACrB,OACF;AAAA,IACF;AAEA,IAAA,OAAO,IAAA,CAAK,YAAA,CAAa,CAAA,SAAA,CAAA,EAAa,OAAO,CAAA;AAAA,EAC/C;AAAA,EAEA,MAAM,cAAA,CACJ,SAAA,EACA,OAAA,EACwB;AAExB,IAAA,MAAM,QAAA,GAAW,MAAM,IAAA,CAAK,eAAA;AAAA,MAC1B,aAAa,SAAS,CAAA,CAAA;AAAA,MACtB;AAAA,KACF;AAEA,IAAA,OAAO,QAAA;AAAA,EACT;AAAA,EAEA,MAAM,YAAA,CACJ,OAAA,EACA,OAAA,EACsB;AAEtB,IAAA,MAAM,WAAW,MAAM,IAAA,CAAK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AI,aAAa,CAAA;AACrD,MAAA,MAAM,WAAW,UAAA,GAAa,QAAA,CAAS,UAAA,EAAY,EAAE,IAAI,GAAA,GAAO,OAAA;AAEhE,MAAA,IAAA,CAAK,MAAA,CAAO,IAAA;AAAA,QACV,+CAA+C,QAAQ,CAAA,UAAA,EACrD,YAAA,GAAe,CACjB,IAAI,OAAO,CAAA,CAAA;AAAA,OACb;AAGA,MAAA,MAAM,IAAI,OAAA,CAAQ,CAAA,OAAA,KAAW,UAAA,CAAW,OAAA,EAAS,QAAQ,CAAC,CAAA;AAG1D,MAAA,OAAA,GAAU,OAAA,GAAU,CAAA,IAAK,GAAA,GAAM,IAAA,CAAK,QAAO,GAAI,GAAA,CAAA;AAC/C,MAAA,YAAA,EAAA;AAAA,IACF;AAAA,EACF;AACF;AAcA,gBAAuB,SAAA,CACrB,SACA,OAAA,EACA;AACA,EAAA,IAAI,GAAA;AACJ,EAAA,GAAG;AACD,IAAA,GAAA,GAAM,MAAM,QAAQ,OAAO,CAAA;AAC3B,IAAA,OAAA,CAAQ,OAAO,GAAA,CAAI,QAAA;AACnB,IAAA,KAAA,MAAW,IAAA,IAAQ,IAAI,KAAA,EAAO;AAC5B,MAAA,MAAM,IAAA;AAAA,IACR;AAAA,EACF,SAAS,GAAA,CAAI,QAAA;AACf;;;;;"}
@@ -52,6 +52,7 @@ function defaultGroupEntitiesTransformer(options) {
52
52
  function defaultUserTransformer(options) {
53
53
  const annotations = {};
54
54
  annotations[`${options.integrationConfig.host}/user-login`] = options.user.web_url;
55
+ annotations[`${options.integrationConfig.host}/user-id`] = options.user.id.toString();
55
56
  if (options.user?.group_saml_identity?.extern_uid) {
56
57
  annotations[`${options.integrationConfig.host}/saml-external-uid`] = options.user.group_saml_identity.extern_uid;
57
58
  }
@@ -1 +1 @@
1
- {"version":3,"file":"defaultTransformers.cjs.js","sources":["../../src/lib/defaultTransformers.ts"],"sourcesContent":["/*\n * Copyright 2023 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 */\nimport { GroupEntity, UserEntity } from '@backstage/catalog-model';\nimport {\n GitLabGroup,\n GroupNameTransformerOptions,\n GroupTransformerOptions,\n UserTransformerOptions,\n} from './types';\n\nexport function defaultGroupNameTransformer(\n options: GroupNameTransformerOptions,\n): string {\n if (\n options.providerConfig.group &&\n options.group.full_path.startsWith(`${options.providerConfig.group}/`)\n ) {\n return options.group.full_path\n .replace(`${options.providerConfig.group}/`, '')\n .replaceAll('/', '-');\n }\n return options.group.full_path.replaceAll('/', '-');\n}\n\nexport function defaultGroupEntitiesTransformer(\n options: GroupTransformerOptions,\n): GroupEntity[] {\n const idMapped: { [groupId: number]: GitLabGroup } = {};\n const entities: GroupEntity[] = [];\n\n for (const group of options.groups) {\n idMapped[group.id] = group;\n }\n\n for (const group of options.groups) {\n const annotations: { [annotationName: string]: string } = {};\n\n annotations[`${options.providerConfig.host}/team-path`] = group.full_path;\n if (group.visibility !== undefined) {\n annotations[`${options.providerConfig.host}/visibility`] =\n group.visibility;\n }\n\n const entity: GroupEntity = {\n apiVersion: 'backstage.io/v1alpha1',\n kind: 'Group',\n metadata: {\n name: options.groupNameTransformer({\n group,\n providerConfig: options.providerConfig,\n }),\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 if (group.parent_id && idMapped.hasOwnProperty(group.parent_id)) {\n entity.spec.parent = options.groupNameTransformer({\n group: idMapped[group.parent_id],\n providerConfig: options.providerConfig,\n });\n }\n\n entities.push(entity);\n }\n\n return entities;\n}\n\n/**\n * The default implementation of the transformation from a graph user entry to\n * a User entity.\n *\n * @public\n */\nexport function defaultUserTransformer(\n options: UserTransformerOptions,\n): UserEntity {\n const annotations: { [annotationName: string]: string } = {};\n\n annotations[`${options.integrationConfig.host}/user-login`] =\n options.user.web_url;\n if (options.user?.group_saml_identity?.extern_uid) {\n annotations[`${options.integrationConfig.host}/saml-external-uid`] =\n options.user.group_saml_identity.extern_uid;\n }\n\n const entity: UserEntity = {\n apiVersion: 'backstage.io/v1alpha1',\n kind: 'User',\n metadata: {\n name: options.user.username,\n annotations: annotations,\n },\n spec: {\n profile: {\n displayName: options.user.name || undefined,\n picture: options.user.avatar_url || undefined,\n },\n memberOf: [],\n },\n };\n\n if (options.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 = options.user.email;\n }\n\n if (options.user.groups) {\n for (const group of options.user.groups) {\n if (!entity.spec.memberOf) {\n entity.spec.memberOf = [];\n }\n entity.spec.memberOf.push(\n options.groupNameTransformer({\n group,\n providerConfig: options.providerConfig,\n }),\n );\n }\n }\n\n return entity;\n}\n"],"names":[],"mappings":";;AAuBO,SAAS,4BACd,OAAA,EACQ;AACR,EAAA,IACE,OAAA,CAAQ,cAAA,CAAe,KAAA,IACvB,OAAA,CAAQ,KAAA,CAAM,SAAA,CAAU,UAAA,CAAW,CAAA,EAAG,OAAA,CAAQ,cAAA,CAAe,KAAK,CAAA,CAAA,CAAG,CAAA,EACrE;AACA,IAAA,OAAO,OAAA,CAAQ,KAAA,CAAM,SAAA,CAClB,OAAA,CAAQ,CAAA,EAAG,OAAA,CAAQ,cAAA,CAAe,KAAK,CAAA,CAAA,CAAA,EAAK,EAAE,CAAA,CAC9C,UAAA,CAAW,KAAK,GAAG,CAAA;AAAA,EACxB;AACA,EAAA,OAAO,OAAA,CAAQ,KAAA,CAAM,SAAA,CAAU,UAAA,CAAW,KAAK,GAAG,CAAA;AACpD;AAEO,SAAS,gCACd,OA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K,UAAU,EAAC;AAAA,IACzB;AAEA,IAAA,MAAA,CAAO,IAAA,CAAK,OAAA,CAAQ,KAAA,GAAQ,OAAA,CAAQ,IAAA,CAAK,KAAA;AAAA,EAC3C;AAEA,EAAA,IAAI,OAAA,CAAQ,KAAK,MAAA,EAAQ;AACvB,IAAA,KAAA,MAAW,KAAA,IAAS,OAAA,CAAQ,IAAA,CAAK,MAAA,EAAQ;AACvC,MAAA,IAAI,CAAC,MAAA,CAAO,IAAA,CAAK,QAAA,EAAU;AACzB,QAAA,MAAA,CAAO,IAAA,CAAK,WAAW,EAAC;AAAA,MAC1B;AACA,MAAA,MAAA,CAAO,KAAK,QAAA,CAAS,IAAA;AAAA,QACnB,QAAQ,oBAAA,CAAqB;AAAA,UAC3B,KAAA;AAAA,UACA,gBAAgB,OAAA,CAAQ;AAAA,SACzB;AAAA,OACH;AAAA,IACF;AAAA,EACF;AAEA,EAAA,OAAO,MAAA;AACT;;;;;;"}
1
+ {"version":3,"file":"defaultTransformers.cjs.js","sources":["../../src/lib/defaultTransformers.ts"],"sourcesContent":["/*\n * Copyright 2023 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 */\nimport { GroupEntity, UserEntity } from '@backstage/catalog-model';\nimport {\n GitLabGroup,\n GroupNameTransformerOptions,\n GroupTransformerOptions,\n UserTransformerOptions,\n} from './types';\n\nexport function defaultGroupNameTransformer(\n options: GroupNameTransformerOptions,\n): string {\n if (\n options.providerConfig.group &&\n options.group.full_path.startsWith(`${options.providerConfig.group}/`)\n ) {\n return options.group.full_path\n .replace(`${options.providerConfig.group}/`, '')\n .replaceAll('/', '-');\n }\n return options.group.full_path.replaceAll('/', '-');\n}\n\nexport function defaultGroupEntitiesTransformer(\n options: GroupTransformerOptions,\n): GroupEntity[] {\n const idMapped: { [groupId: number]: GitLabGroup } = {};\n const entities: GroupEntity[] = [];\n\n for (const group of options.groups) {\n idMapped[group.id] = group;\n }\n\n for (const group of options.groups) {\n const annotations: { [annotationName: string]: string } = {};\n\n annotations[`${options.providerConfig.host}/team-path`] = group.full_path;\n if (group.visibility !== undefined) {\n annotations[`${options.providerConfig.host}/visibility`] =\n group.visibility;\n }\n\n const entity: GroupEntity = {\n apiVersion: 'backstage.io/v1alpha1',\n kind: 'Group',\n metadata: {\n name: options.groupNameTransformer({\n group,\n providerConfig: options.providerConfig,\n }),\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 if (group.parent_id && idMapped.hasOwnProperty(group.parent_id)) {\n entity.spec.parent = options.groupNameTransformer({\n group: idMapped[group.parent_id],\n providerConfig: options.providerConfig,\n });\n }\n\n entities.push(entity);\n }\n\n return entities;\n}\n\n/**\n * The default implementation of the transformation from a graph user entry to\n * a User entity.\n *\n * @public\n */\nexport function defaultUserTransformer(\n options: UserTransformerOptions,\n): UserEntity {\n const annotations: { [annotationName: string]: string } = {};\n\n annotations[`${options.integrationConfig.host}/user-login`] =\n options.user.web_url;\n annotations[`${options.integrationConfig.host}/user-id`] =\n options.user.id.toString();\n if (options.user?.group_saml_identity?.extern_uid) {\n annotations[`${options.integrationConfig.host}/saml-external-uid`] =\n options.user.group_saml_identity.extern_uid;\n }\n\n const entity: UserEntity = {\n apiVersion: 'backstage.io/v1alpha1',\n kind: 'User',\n metadata: {\n name: options.user.username,\n annotations: annotations,\n },\n spec: {\n profile: {\n displayName: options.user.name || undefined,\n picture: options.user.avatar_url || undefined,\n },\n memberOf: [],\n },\n };\n\n if (options.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 = options.user.email;\n }\n\n if (options.user.groups) {\n for (const group of options.user.groups) {\n if (!entity.spec.memberOf) {\n entity.spec.memberOf = [];\n }\n entity.spec.memberOf.push(\n options.groupNameTransformer({\n group,\n providerConfig: options.providerConfig,\n }),\n );\n }\n }\n\n return entity;\n}\n"],"names":[],"mappings":";;AAuBO,SAAS,4BACd,OAAA,EACQ;AACR,EAAA,IACE,OAAA,CAAQ,cAAA,CAAe,KAAA,IACvB,OAAA,CAAQ,KAAA,CAAM,SAAA,CAAU,UAAA,CAAW,CAAA,EAAG,OAAA,CAAQ,cAAA,CAAe,KAAK,CAAA,CAAA,CAAG,CAAA,EACrE;AACA,IAAA,OAAO,OAAA,CAAQ,KAAA,CAAM,SAAA,CAClB,OAAA,CAAQ,CAAA,EAAG,OAAA,CAAQ,cAAA,CAAe,KAAK,CAAA,CAAA,CAAA,EAAK,EAAE,CAAA,CAC9C,UAAA,CAAW,KAAK,GAAG,CAAA;AAAA,EACxB;AACA,EAAA,OAAO,OAAA,CAAQ,KAAA,CAAM,SAAA,CAAU,UAAA,CAAW,KAAK,GAAG,CAAA;AACpD;AAEO,SAAS,gCACd,OAAA,EACe;AACf,EAAA,MAAM,WAA+C,EAAC;AACtD,EAAA,MAAM,WAA0B,EAAC;AAEjC,EAAA,KAAA,MAAW,KAAA,IAAS,QAAQ,MAAA,EAAQ;AAClC,IAAA,QAAA,CAAS,KAAA,CAAM,EAAE,CAAA,GAAI,KAAA;AAAA,EACvB;AAEA,EAAA,KAAA,MAAW,KAAA,IAAS,QAAQ,MAAA,EAAQ;AAClC,IAAA,MAAM,cAAoD,EAAC;AAE3D,IAAA,WAAA,CAAY,GAAG,OAAA,CAAQ,cAAA,CAAe,IAAI,CAAA,UAAA,CAAY,IAAI,KAAA,CAAM,SAAA;AAChE,IAAA,IAAI,KAAA,CAAM,eAAe,MAAA,EAAW;AAClC,MAAA,WAAA,CAAY,GAAG,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AAO,IAAA,CAAK,WAAW,EAAC;AAAA,MAC1B;AACA,MAAA,MAAA,CAAO,KAAK,QAAA,CAAS,IAAA;AAAA,QACnB,QAAQ,oBAAA,CAAqB;AAAA,UAC3B,KAAA;AAAA,UACA,gBAAgB,OAAA,CAAQ;AAAA,SACzB;AAAA,OACH;AAAA,IACF;AAAA,EACF;AAEA,EAAA,OAAO,MAAA;AACT;;;;;;"}
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var backendPluginApi = require('@backstage/backend-plugin-api');
4
- var alpha = require('@backstage/plugin-catalog-node/alpha');
4
+ var pluginCatalogNode = require('@backstage/plugin-catalog-node');
5
5
  var pluginEventsNode = require('@backstage/plugin-events-node');
6
6
  var GitlabDiscoveryEntityProvider = require('../providers/GitlabDiscoveryEntityProvider.cjs.js');
7
7
  require('@backstage/catalog-model');
@@ -17,7 +17,7 @@ const catalogModuleGitlabDiscoveryEntityProvider = backendPluginApi.createBacken
17
17
  env.registerInit({
18
18
  deps: {
19
19
  config: backendPluginApi.coreServices.rootConfig,
20
- catalog: alpha.catalogProcessingExtensionPoint,
20
+ catalog: pluginCatalogNode.catalogProcessingExtensionPoint,
21
21
  logger: backendPluginApi.coreServices.logger,
22
22
  scheduler: backendPluginApi.coreServices.scheduler,
23
23
  events: pluginEventsNode.eventsServiceRef
@@ -1 +1 @@
1
- {"version":3,"file":"catalogModuleGitlabDiscoveryEntityProvider.cjs.js","sources":["../../src/module/catalogModuleGitlabDiscoveryEntityProvider.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createBackendModule,\n} from '@backstage/backend-plugin-api';\nimport { catalogProcessingExtensionPoint } from '@backstage/plugin-catalog-node/alpha';\nimport { eventsServiceRef } from '@backstage/plugin-events-node';\nimport { GitlabDiscoveryEntityProvider } from '../providers';\n\n/**\n * Registers the GitlabDiscoveryEntityProvider with the catalog processing extension point.\n *\n * @public\n */\n\nexport const catalogModuleGitlabDiscoveryEntityProvider = createBackendModule({\n pluginId: 'catalog',\n moduleId: 'gitlab-discovery-entity-provider',\n register(env) {\n env.registerInit({\n deps: {\n config: coreServices.rootConfig,\n catalog: catalogProcessingExtensionPoint,\n logger: coreServices.logger,\n scheduler: coreServices.scheduler,\n events: eventsServiceRef,\n },\n async init({ config, catalog, logger, scheduler, events }) {\n const gitlabDiscoveryEntityProvider =\n GitlabDiscoveryEntityProvider.fromConfig(config, {\n logger,\n events,\n scheduler,\n });\n catalog.addEntityProvider(gitlabDiscoveryEntityProvider);\n },\n });\n },\n});\n"],"names":["createBackendModule","coreServices","catalogProcessingExtensionPoint","eventsServiceRef","GitlabDiscoveryEntityProvider"],"mappings":";;;;;;;;;;;;AA8BO,MAAM,6CAA6CA,oCAAA,CAAoB;AAAA,EAC5E,QAAA,EAAU,SAAA;AAAA,EACV,QAAA,EAAU,kCAAA;AAAA,EACV,SAAS,GAAA,EAAK;AACZ,IAAA,GAAA,CAAI,YAAA,CAAa;AAAA,MACf,IAAA,EAAM;AAAA,QACJ,QAAQC,6BAAA,CAAa,UAAA;AAAA,QACrB,OAAA,EAASC,qCAAA;AAAA,QACT,QAAQD,6BAAA,CAAa,MAAA;AAAA,QACrB,WAAWA,6BAAA,CAAa,SAAA;AAAA,QACxB,MAAA,EAAQE;AAAA,OACV;AAAA,MACA,MAAM,KAAK,EAAE,MAAA,EAAQ,SAAS,MAAA,EAAQ,SAAA,EAAW,QAAO,EAAG;AACzD,QAAA,MAAM,6BAAA,GACJC,2DAAA,CAA8B,UAAA,CAAW,MAAA,EAAQ;AAAA,UAC/C,MAAA;AAAA,UACA,MAAA;AAAA,UACA;AAAA,SACD,CAAA;AACH,QAAA,OAAA,CAAQ,kBAAkB,6BAA6B,CAAA;AAAA,MACzD;AAAA,KACD,CAAA;AAAA,EACH;AACF,CAAC;;;;"}
1
+ {"version":3,"file":"catalogModuleGitlabDiscoveryEntityProvider.cjs.js","sources":["../../src/module/catalogModuleGitlabDiscoveryEntityProvider.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createBackendModule,\n} from '@backstage/backend-plugin-api';\nimport { catalogProcessingExtensionPoint } from '@backstage/plugin-catalog-node';\nimport { eventsServiceRef } from '@backstage/plugin-events-node';\nimport { GitlabDiscoveryEntityProvider } from '../providers';\n\n/**\n * Registers the GitlabDiscoveryEntityProvider with the catalog processing extension point.\n *\n * @public\n */\n\nexport const catalogModuleGitlabDiscoveryEntityProvider = createBackendModule({\n pluginId: 'catalog',\n moduleId: 'gitlab-discovery-entity-provider',\n register(env) {\n env.registerInit({\n deps: {\n config: coreServices.rootConfig,\n catalog: catalogProcessingExtensionPoint,\n logger: coreServices.logger,\n scheduler: coreServices.scheduler,\n events: eventsServiceRef,\n },\n async init({ config, catalog, logger, scheduler, events }) {\n const gitlabDiscoveryEntityProvider =\n GitlabDiscoveryEntityProvider.fromConfig(config, {\n logger,\n events,\n scheduler,\n });\n catalog.addEntityProvider(gitlabDiscoveryEntityProvider);\n },\n });\n },\n});\n"],"names":["createBackendModule","coreServices","catalogProcessingExtensionPoint","eventsServiceRef","GitlabDiscoveryEntityProvider"],"mappings":";;;;;;;;;;;;AA8BO,MAAM,6CAA6CA,oCAAA,CAAoB;AAAA,EAC5E,QAAA,EAAU,SAAA;AAAA,EACV,QAAA,EAAU,kCAAA;AAAA,EACV,SAAS,GAAA,EAAK;AACZ,IAAA,GAAA,CAAI,YAAA,CAAa;AAAA,MACf,IAAA,EAAM;AAAA,QACJ,QAAQC,6BAAA,CAAa,UAAA;AAAA,QACrB,OAAA,EAASC,iDAAA;AAAA,QACT,QAAQD,6BAAA,CAAa,MAAA;AAAA,QACrB,WAAWA,6BAAA,CAAa,SAAA;AAAA,QACxB,MAAA,EAAQE;AAAA,OACV;AAAA,MACA,MAAM,KAAK,EAAE,MAAA,EAAQ,SAAS,MAAA,EAAQ,SAAA,EAAW,QAAO,EAAG;AACzD,QAAA,MAAM,6BAAA,GACJC,2DAAA,CAA8B,UAAA,CAAW,MAAA,EAAQ;AAAA,UAC/C,MAAA;AAAA,UACA,MAAA;AAAA,UACA;AAAA,SACD,CAAA;AACH,QAAA,OAAA,CAAQ,kBAAkB,6BAA6B,CAAA;AAAA,MACzD;AAAA,KACD,CAAA;AAAA,EACH;AACF,CAAC;;;;"}
@@ -5,7 +5,7 @@ var pluginCatalogNode = require('@backstage/plugin-catalog-node');
5
5
  var uuid = require('uuid');
6
6
  var config = require('./config.cjs.js');
7
7
  var client = require('../lib/client.cjs.js');
8
- var path = require('path');
8
+ var path = require('node:path');
9
9
 
10
10
  function _interopNamespaceCompat(e) {
11
11
  if (e && typeof e === 'object' && 'default' in e) return e;
@@ -145,7 +145,10 @@ class GitlabDiscoveryEntityProvider {
145
145
  `Gitlab discovery connection not initialized for ${this.getProviderName()}`
146
146
  );
147
147
  }
148
- const locations = await this.getEntities();
148
+ this.logger.info(
149
+ `Refreshing Gitlab entity discovery using ${this.config.useSearch ? "search" : "discovery"} mode`
150
+ );
151
+ const locations = this.config.useSearch ? await this.searchEntities() : await this.getEntities();
149
152
  await this.connection.applyMutation({
150
153
  type: "full",
151
154
  entities: locations.map((location) => ({
@@ -155,6 +158,45 @@ class GitlabDiscoveryEntityProvider {
155
158
  });
156
159
  logger.info(`Processed ${locations.length} locations`);
157
160
  }
161
+ /**
162
+ * Determine the location on GitLab to be ingested.
163
+ * Uses GitLab's search API to find projects matching provided configuration.
164
+ *
165
+ * @returns A list of location to be ingested
166
+ */
167
+ async searchEntities() {
168
+ const locations = [];
169
+ let foundProjects = 0;
170
+ this.logger.info(`Using gitlab search API to lookup projects`);
171
+ const foundFiles = client.paginated(
172
+ (options) => this.gitLabClient.listFiles(options),
173
+ {
174
+ group: this.config.group,
175
+ search: `filename:${this.config.catalogFile}`,
176
+ page: 1,
177
+ per_page: 50
178
+ }
179
+ );
180
+ for await (const foundFile of foundFiles) {
181
+ const project = await this.gitLabClient.getProjectById(
182
+ foundFile.project_id
183
+ );
184
+ foundProjects++;
185
+ if (project && this.isProjectCompliant(project) && this.isGroupCompliant(project.path_with_namespace)) {
186
+ locations.push(
187
+ this.createLocationSpecFromParams(
188
+ project.web_url,
189
+ foundFile.ref,
190
+ foundFile.path
191
+ )
192
+ );
193
+ }
194
+ }
195
+ this.logger.info(
196
+ `Processed ${locations.length} from ${foundProjects} found projects on API.`
197
+ );
198
+ return locations;
199
+ }
158
200
  /**
159
201
  * Determine the location on GitLab to be ingested base on configured groups and filters.
160
202
  *
@@ -254,14 +296,21 @@ class GitlabDiscoveryEntityProvider {
254
296
  }
255
297
  return res;
256
298
  }
257
- createLocationSpec(project) {
258
- const project_branch = this.config.branch ?? project.default_branch ?? this.config.fallbackBranch;
299
+ createLocationSpecFromParams(projectURL, branch, catalogFile) {
259
300
  return {
260
301
  type: "url",
261
- target: `${project.web_url}/-/blob/${project_branch}/${this.config.catalogFile}`,
302
+ target: `${projectURL}/-/blob/${branch}/${catalogFile}`,
262
303
  presence: "optional"
263
304
  };
264
305
  }
306
+ createLocationSpec(project) {
307
+ const project_branch = this.config.branch ?? project.default_branch ?? this.config.fallbackBranch;
308
+ return this.createLocationSpecFromParams(
309
+ project.web_url,
310
+ project_branch,
311
+ this.config.catalogFile
312
+ );
313
+ }
265
314
  /**
266
315
  * Handles the "gitlab.push" event.
267
316
  *
@@ -405,7 +454,7 @@ class GitlabDiscoveryEntityProvider {
405
454
  };
406
455
  });
407
456
  }
408
- async shouldProcessProject(project, client) {
457
+ isProjectCompliant(project) {
409
458
  if (!this.config.projectPattern.test(project.path_with_namespace ?? "")) {
410
459
  this.logger.debug(
411
460
  `Skipping project ${project.path_with_namespace} as it does not match the project pattern ${this.config.projectPattern}.`
@@ -430,6 +479,12 @@ class GitlabDiscoveryEntityProvider {
430
479
  );
431
480
  return false;
432
481
  }
482
+ return true;
483
+ }
484
+ async shouldProcessProject(project, client) {
485
+ if (!this.isProjectCompliant(project)) {
486
+ return false;
487
+ }
433
488
  const project_branch = this.config.branch ?? project.default_branch ?? this.config.fallbackBranch;
434
489
  const hasFile = await client.hasFile(
435
490
  project.id,
@@ -438,6 +493,13 @@ class GitlabDiscoveryEntityProvider {
438
493
  );
439
494
  return hasFile;
440
495
  }
496
+ isGroupCompliant(name) {
497
+ const groupRegexes = Array.isArray(this.config.groupPattern) ? this.config.groupPattern : [this.config.groupPattern];
498
+ if (name) {
499
+ return groupRegexes.some((reg) => reg.test(name));
500
+ }
501
+ return false;
502
+ }
441
503
  }
442
504
 
443
505
  exports.GitlabDiscoveryEntityProvider = GitlabDiscoveryEntityProvider;
@@ -1 +1 @@
1
- {"version":3,"file":"GitlabDiscoveryEntityProvider.cjs.js","sources":["../../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 {\n LoggerService,\n SchedulerService,\n SchedulerServiceTaskRunner,\n} from '@backstage/backend-plugin-api';\nimport { Config } from '@backstage/config';\nimport { GitLabIntegration, ScmIntegrations } from '@backstage/integration';\nimport { LocationSpec } from '@backstage/plugin-catalog-common';\nimport {\n DeferredEntity,\n EntityProvider,\n EntityProviderConnection,\n locationSpecToLocationEntity,\n} from '@backstage/plugin-catalog-node';\nimport { EventsService } from '@backstage/plugin-events-node';\nimport { WebhookProjectSchema, WebhookPushEventSchema } from '@gitbeaker/rest';\nimport * as uuid from 'uuid';\nimport {\n GitLabClient,\n GitLabGroup,\n GitLabProject,\n GitlabProviderConfig,\n paginated,\n readGitlabConfigs,\n} from '../lib';\n\nimport * as path from 'path';\n\nconst TOPIC_REPO_PUSH = 'gitlab.push';\n\ntype Result = {\n scanned: number;\n matches: GitLabProject[];\n};\n\n/**\n * Discovers catalog files located in your GitLab instance.\n * The provider will search your GitLab instance's projects and register catalog files matching the configured path\n * as Location entity and via following processing steps add all contained catalog entities.\n * This can be useful as an alternative to static locations or manually adding things to the catalog.\n *\n * @public\n */\n// <<< EventSupportChange: implemented EventSubscriber interface\nexport class GitlabDiscoveryEntityProvider implements EntityProvider {\n private readonly config: GitlabProviderConfig;\n private readonly integration: GitLabIntegration;\n private readonly logger: LoggerService;\n private readonly scheduleFn: () => Promise<void>;\n private connection?: EntityProviderConnection;\n private readonly events?: EventsService;\n private readonly gitLabClient: GitLabClient;\n\n static fromConfig(\n config: Config,\n options: {\n logger: LoggerService;\n events?: EventsService;\n schedule?: SchedulerServiceTaskRunner;\n scheduler?: SchedulerService;\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\n return providers;\n }\n\n /**\n * Constructs a GitlabDiscoveryEntityProvider instance.\n *\n * @param options - Configuration options including config, integration, logger, and taskRunner.\n */\n private constructor(options: {\n config: GitlabProviderConfig;\n integration: GitLabIntegration;\n logger: LoggerService;\n events?: EventsService;\n taskRunner: SchedulerServiceTaskRunner;\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 this.events = options.events;\n this.gitLabClient = new GitLabClient({\n config: this.integration.config,\n logger: this.logger,\n });\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 if (this.events) {\n await this.events.subscribe({\n id: this.getProviderName(),\n topics: [TOPIC_REPO_PUSH],\n onEvent: async params => {\n if (params.topic !== TOPIC_REPO_PUSH) {\n return;\n }\n\n await this.onRepoPush(params.eventPayload as WebhookPushEventSchema);\n },\n });\n }\n }\n\n /**\n * Creates a scheduled task runner for refreshing the entity provider.\n *\n * @param taskRunner - The task runner instance.\n * @returns The scheduled function.\n */\n private createScheduleFn(\n taskRunner: SchedulerServiceTaskRunner,\n ): () => 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(\n `${this.getProviderName()} refresh failed, ${error}`,\n error,\n );\n }\n },\n });\n };\n }\n\n /**\n * Performs a full scan on the GitLab instance searching for locations to be ingested\n *\n * @param logger - The logger instance for logging.\n */\n async refresh(logger: LoggerService): Promise<void> {\n if (!this.connection) {\n throw new Error(\n `Gitlab discovery connection not initialized for ${this.getProviderName()}`,\n );\n }\n\n const locations = await this.getEntities();\n\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 logger.info(`Processed ${locations.length} locations`);\n }\n\n /**\n * Determine the location on GitLab to be ingested base on configured groups and filters.\n *\n * @returns A list of location to be ingested\n */\n private async getEntities() {\n let res: Result = {\n scanned: 0,\n matches: [],\n };\n\n const groupToProcess = new Map<string, GitLabGroup>();\n let groupFilters;\n\n if (this.config.groupPattern !== undefined) {\n const patterns = Array.isArray(this.config.groupPattern)\n ? this.config.groupPattern\n : [this.config.groupPattern];\n\n if (patterns.length === 1 && patterns[0].source === '[\\\\s\\\\S]*') {\n // if the pattern is a catch-all, we don't need to filter groups\n groupFilters = new Array<RegExp>();\n } else {\n groupFilters = patterns;\n }\n }\n\n if (groupFilters && groupFilters.length > 0) {\n const groups = paginated<GitLabGroup>(\n options => this.gitLabClient.listGroups(options),\n {\n page: 1,\n per_page: 50,\n },\n );\n\n for await (const group of groups) {\n if (\n groupFilters.some(groupFilter => groupFilter.test(group.full_path)) &&\n !groupToProcess.has(group.full_path)\n ) {\n groupToProcess.set(group.full_path, group);\n }\n }\n\n for (const group of groupToProcess.values()) {\n const tmpRes = await this.getProjectsToProcess(group.full_path);\n res.scanned += tmpRes.scanned;\n // merge both arrays safely\n for (const project of tmpRes.matches) {\n res.matches.push(project);\n }\n }\n } else {\n res = await this.getProjectsToProcess(this.config.group);\n }\n\n const locations = this.deduplicateProjects(res.matches).map(p =>\n this.createLocationSpec(p),\n );\n\n this.logger.info(\n `Processed ${locations.length} from scanned ${res.scanned} projects.`,\n );\n\n return locations;\n }\n\n /**\n * Deduplicate a list of projects based on their id.\n *\n * @param projects - a list of projects to be deduplicated\n * @returns a list of projects with unique id\n */\n private deduplicateProjects(projects: GitLabProject[]): GitLabProject[] {\n const uniqueProjects = new Map<number, GitLabProject>();\n\n for (const project of projects) {\n uniqueProjects.set(project.id, project);\n }\n\n return Array.from(uniqueProjects.values());\n }\n\n /**\n * Retrieve a list of projects that match configuration.\n *\n * @param group - a full path of a GitLab group, can be empty\n * @returns An array of project to be processed and the number of project scanned\n */\n private async getProjectsToProcess(group: string) {\n const res: Result = {\n scanned: 0,\n matches: [],\n };\n\n const projects = paginated<GitLabProject>(\n options => this.gitLabClient.listProjects(options),\n {\n group: group,\n page: 1,\n per_page: 50,\n ...(!this.config.includeArchivedRepos && { archived: false }),\n ...(this.config.membership && { membership: true }),\n ...(this.config.topics && { topics: this.config.topics }),\n // Only use simple=true when we don't need to skip forked repos.\n // The simple=true parameter reduces response size by returning fewer fields,\n // but it excludes the 'forked_from_project' field which is required for fork detection.\n // Therefore, we can only optimize with simple=true when skipForkedRepos is false.\n ...(!this.config.skipForkedRepos && { simple: true }),\n },\n );\n\n for await (const project of projects) {\n res.scanned++;\n\n if (await this.shouldProcessProject(project, this.gitLabClient)) {\n res.matches.push(project);\n }\n }\n\n return res;\n }\n\n private createLocationSpec(project: GitLabProject): LocationSpec {\n const project_branch =\n this.config.branch ??\n project.default_branch ??\n this.config.fallbackBranch;\n\n return {\n type: 'url',\n target: `${project.web_url}/-/blob/${project_branch}/${this.config.catalogFile}`,\n presence: 'optional',\n };\n }\n\n /**\n * Handles the \"gitlab.push\" event.\n *\n * @param event - The push event payload.\n */\n private async onRepoPush(event: WebhookPushEventSchema): Promise<void> {\n if (!this.connection) {\n throw new Error(\n `Gitlab discovery connection not initialized for ${this.getProviderName()}`,\n );\n }\n this.logger.info(\n `Received push event for ${event.project.path_with_namespace}`,\n );\n\n const project = await this.gitLabClient.getProjectById(event.project_id);\n\n if (!project) {\n this.logger.debug(\n `Ignoring push event for ${event.project.path_with_namespace}`,\n );\n\n return;\n }\n\n if (!(await this.shouldProcessProject(project, this.gitLabClient))) {\n this.logger.debug(`Skipping event ${event.project.path_with_namespace}`);\n return;\n }\n\n // Get array of added, removed or modified files from the push event\n const added = this.getFilesMatchingConfig(\n event,\n 'added',\n this.config.catalogFile,\n );\n const removed = this.getFilesMatchingConfig(\n event,\n 'removed',\n this.config.catalogFile,\n );\n const modified = this.getFilesMatchingConfig(\n event,\n 'modified',\n this.config.catalogFile,\n );\n\n // Modified files will be scheduled to a refresh\n const addedEntities = this.createLocationSpecCommitedFiles(\n event.project,\n added,\n );\n\n const removedEntities = this.createLocationSpecCommitedFiles(\n event.project,\n removed,\n );\n\n if (addedEntities.length > 0 || removedEntities.length > 0) {\n await this.connection.applyMutation({\n type: 'delta',\n added: this.toDeferredEntities(\n addedEntities.map(entity => entity.target),\n ),\n removed: this.toDeferredEntities(\n removedEntities.map(entity => entity.target),\n ),\n });\n }\n\n if (modified.length > 0) {\n const projectBranch =\n this.config.branch ??\n event.project.default_branch ??\n this.config.fallbackBranch;\n\n // scheduling a refresh to both tree and blob (https://git-scm.com/book/en/v2/Git-Internals-Git-Objects)\n await this.connection.refresh({\n keys: [\n ...modified.map(\n filePath =>\n `url:${event.project.web_url}/-/tree/${projectBranch}/${filePath}`,\n ),\n ...modified.map(\n filePath =>\n `url:${event.project.web_url}/-/blob/${projectBranch}/${filePath}`,\n ),\n ],\n });\n }\n\n this.logger.info(\n `Processed GitLab push event from ${event.project.web_url}: added ${added.length} - removed ${removed.length} - modified ${modified.length}`,\n );\n }\n\n /**\n * Gets files matching the specified commit action and catalog file name.\n *\n * @param event - The push event payload.\n * @param action - The action type ('added', 'removed', or 'modified').\n * @param catalogFile - The catalog file name.\n * @returns An array of file paths.\n */\n private getFilesMatchingConfig(\n event: WebhookPushEventSchema,\n action: 'added' | 'removed' | 'modified',\n catalogFile: string,\n ): string[] {\n if (!event.commits) {\n return [];\n }\n\n const matchingFiles = event.commits.flatMap((element: any) =>\n element[action].filter(\n (file: string) => path.basename(file) === catalogFile,\n ),\n );\n\n if (matchingFiles.length === 0) {\n this.logger.debug(\n `No files matching '${catalogFile}' found in the commits.`,\n );\n }\n\n return matchingFiles;\n }\n\n /**\n * Creates Backstage location specs for committed files.\n *\n * @param project - The GitLab project information.\n * @param addedFiles - The array of added file paths.\n * @returns An array of location specs.\n */\n private createLocationSpecCommitedFiles(\n project: WebhookProjectSchema,\n addedFiles: string[],\n ): LocationSpec[] {\n const projectBranch =\n this.config.branch ??\n project.default_branch ??\n this.config.fallbackBranch;\n\n // Filter added files that match the catalog file pattern\n const matchingFiles = addedFiles.filter(\n file => path.basename(file) === this.config.catalogFile,\n );\n\n // Create a location spec for each matching file\n const locationSpecs: LocationSpec[] = matchingFiles.map(file => ({\n type: 'url',\n target: `${project.web_url}/-/blob/${projectBranch}/${file}`,\n presence: 'optional',\n }));\n\n return locationSpecs;\n }\n\n /**\n * Converts a target URL to a LocationSpec object.\n *\n * @param target - The target URL to be converted.\n * @returns The LocationSpec object representing the URL.\n */\n private toLocationSpec(target: string): LocationSpec {\n return {\n type: 'url',\n target: target,\n presence: 'optional',\n };\n }\n\n private toDeferredEntities(targets: string[]): DeferredEntity[] {\n return targets\n .map(target => {\n const location = this.toLocationSpec(target);\n\n return locationSpecToLocationEntity({ location });\n })\n .map(entity => {\n return {\n locationKey: this.getProviderName(),\n entity: entity,\n };\n });\n }\n\n private async shouldProcessProject(\n project: GitLabProject,\n client: GitLabClient,\n ): Promise<boolean> {\n if (!this.config.projectPattern.test(project.path_with_namespace ?? '')) {\n this.logger.debug(\n `Skipping project ${project.path_with_namespace} as it does not match the project pattern ${this.config.projectPattern}.`,\n );\n return false;\n }\n\n if (\n this.config.group &&\n !project.path_with_namespace!.startsWith(`${this.config.group}/`)\n ) {\n this.logger.debug(\n `Skipping project ${project.path_with_namespace} as it does not match the group pattern ${this.config.group}.`,\n );\n return false;\n }\n\n if (\n this.config.skipForkedRepos &&\n project.hasOwnProperty('forked_from_project')\n ) {\n this.logger.debug(\n `Skipping project ${project.path_with_namespace} as it is a forked project.`,\n );\n return false;\n }\n\n if (this.config.excludeRepos?.includes(project.path_with_namespace ?? '')) {\n this.logger.debug(\n `Skipping project ${project.path_with_namespace} as it is excluded.`,\n );\n return false;\n }\n\n const project_branch =\n this.config.branch ??\n project.default_branch ??\n this.config.fallbackBranch;\n\n const hasFile = await client.hasFile(\n project.id,\n project_branch,\n this.config.catalogFile,\n );\n\n return hasFile;\n }\n}\n"],"names":["config","readGitlabConfigs","ScmIntegrations","GitLabClient","uuid","locationSpecToLocationEntity","paginated","path"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,MAAM,eAAA,GAAkB,aAAA;AAgBjB,MAAM,6BAAA,CAAwD;AAAA,EAClD,MAAA;AAAA,EACA,WAAA;AAAA,EACA,MAAA;AAAA,EACA,UAAA;AAAA,EACT,UAAA;AAAA,EACS,MAAA;AAAA,EACA,YAAA;AAAA,EAEjB,OAAO,UAAA,CACLA,QAAA,EACA,OAAA,EAMiC;AACjC,IAAA,IAAI,CAAC,OAAA,CAAQ,QAAA,IAAY,CAAC,QAAQ,SAAA,EAAW;AAC3C,MAAA,MAAM,IAAI,MAAM,gDAAgD,CAAA;AAAA,IAClE;AAEA,IAAA,MAAM,eAAA,GAAkBC,yBAAkBD,QAAM,CAAA;AAChD,IAAA,MAAM,YAAA,GAAeE,2BAAA,CAAgB,UAAA,CAAWF,QAAM,CAAA,CAAE,MAAA;AACxD,IAAA,MAAM,YAA6C,EAAC;AAEpD,IAAA,eAAA,CAAgB,QAAQ,CAAA,cAAA,KAAkB;AACxC,MAAA,MAAM,WAAA,GAAc,YAAA,CAAa,MAAA,CAAO,cAAA,CAAe,IAAI,CAAA;AAC3D,MAAA,IAAI,CAAC,WAAA,E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iBAAA,EAAoB,QAAQ,mBAAmB,CAAA,2BAAA;AAAA,OACjD;AACA,MAAA,OAAO,KAAA;AAAA,IACT;AAEA,IAAA,IAAI,KAAK,MAAA,CAAO,YAAA,EAAc,SAAS,OAAA,CAAQ,mBAAA,IAAuB,EAAE,CAAA,EAAG;AACzE,MAAA,IAAA,CAAK,MAAA,CAAO,KAAA;AAAA,QACV,CAAA,iBAAA,EAAoB,QAAQ,mBAAmB,CAAA,mBAAA;AAAA,OACjD;AACA,MAAA,OAAO,KAAA;AAAA,IACT;AAEA,IAAA,MAAM,iBACJ,IAAA,CAAK,MAAA,CAAO,UACZ,OAAA,CAAQ,cAAA,IACR,KAAK,MAAA,CAAO,cAAA;AAEd,IAAA,MAAM,OAAA,GAAU,MAAM,MAAA,CAAO,OAAA;AAAA,MAC3B,OAAA,CAAQ,EAAA;AAAA,MACR,cAAA;AAAA,MACA,KAAK,MAAA,CAAO;AAAA,KACd;AAEA,IAAA,OAAO,OAAA;AAAA,EACT;AACF;;;;"}
1
+ {"version":3,"file":"GitlabDiscoveryEntityProvider.cjs.js","sources":["../../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 {\n LoggerService,\n SchedulerService,\n SchedulerServiceTaskRunner,\n} from '@backstage/backend-plugin-api';\nimport { Config } from '@backstage/config';\nimport { GitLabIntegration, ScmIntegrations } from '@backstage/integration';\nimport { LocationSpec } from '@backstage/plugin-catalog-common';\nimport {\n DeferredEntity,\n EntityProvider,\n EntityProviderConnection,\n locationSpecToLocationEntity,\n} from '@backstage/plugin-catalog-node';\nimport { EventsService } from '@backstage/plugin-events-node';\nimport { WebhookProjectSchema, WebhookPushEventSchema } from '@gitbeaker/rest';\nimport * as uuid from 'uuid';\nimport {\n GitLabClient,\n GitLabGroup,\n GitLabProject,\n GitlabProviderConfig,\n paginated,\n readGitlabConfigs,\n} from '../lib';\n\nimport * as path from 'node:path';\n\nconst TOPIC_REPO_PUSH = 'gitlab.push';\n\ntype Result = {\n scanned: number;\n matches: GitLabProject[];\n};\n\n/**\n * Discovers catalog files located in your GitLab instance.\n * The provider will search your GitLab instance's projects and register catalog files matching the configured path\n * as Location entity and via following processing steps add all contained catalog entities.\n * This can be useful as an alternative to static locations or manually adding things to the catalog.\n *\n * @public\n */\n// <<< EventSupportChange: implemented EventSubscriber interface\nexport class GitlabDiscoveryEntityProvider implements EntityProvider {\n private readonly config: GitlabProviderConfig;\n private readonly integration: GitLabIntegration;\n private readonly logger: LoggerService;\n private readonly scheduleFn: () => Promise<void>;\n private connection?: EntityProviderConnection;\n private readonly events?: EventsService;\n private readonly gitLabClient: GitLabClient;\n\n static fromConfig(\n config: Config,\n options: {\n logger: LoggerService;\n events?: EventsService;\n schedule?: SchedulerServiceTaskRunner;\n scheduler?: SchedulerService;\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\n return providers;\n }\n\n /**\n * Constructs a GitlabDiscoveryEntityProvider instance.\n *\n * @param options - Configuration options including config, integration, logger, and taskRunner.\n */\n private constructor(options: {\n config: GitlabProviderConfig;\n integration: GitLabIntegration;\n logger: LoggerService;\n events?: EventsService;\n taskRunner: SchedulerServiceTaskRunner;\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 this.events = options.events;\n this.gitLabClient = new GitLabClient({\n config: this.integration.config,\n logger: this.logger,\n });\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 if (this.events) {\n await this.events.subscribe({\n id: this.getProviderName(),\n topics: [TOPIC_REPO_PUSH],\n onEvent: async params => {\n if (params.topic !== TOPIC_REPO_PUSH) {\n return;\n }\n\n await this.onRepoPush(params.eventPayload as WebhookPushEventSchema);\n },\n });\n }\n }\n\n /**\n * Creates a scheduled task runner for refreshing the entity provider.\n *\n * @param taskRunner - The task runner instance.\n * @returns The scheduled function.\n */\n private createScheduleFn(\n taskRunner: SchedulerServiceTaskRunner,\n ): () => 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(\n `${this.getProviderName()} refresh failed, ${error}`,\n error,\n );\n }\n },\n });\n };\n }\n\n /**\n * Performs a full scan on the GitLab instance searching for locations to be ingested\n *\n * @param logger - The logger instance for logging.\n */\n async refresh(logger: LoggerService): Promise<void> {\n if (!this.connection) {\n throw new Error(\n `Gitlab discovery connection not initialized for ${this.getProviderName()}`,\n );\n }\n\n this.logger.info(\n `Refreshing Gitlab entity discovery using ${\n this.config.useSearch ? 'search' : 'discovery'\n } mode`,\n );\n\n const locations = this.config.useSearch\n ? await this.searchEntities()\n : await this.getEntities();\n\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 logger.info(`Processed ${locations.length} locations`);\n }\n\n /**\n * Determine the location on GitLab to be ingested.\n * Uses GitLab's search API to find projects matching provided configuration.\n *\n * @returns A list of location to be ingested\n */\n private async searchEntities() {\n const locations: LocationSpec[] = [];\n let foundProjects = 0;\n\n this.logger.info(`Using gitlab search API to lookup projects`);\n\n const foundFiles = paginated(\n options => this.gitLabClient.listFiles(options),\n {\n group: this.config.group,\n search: `filename:${this.config.catalogFile}`,\n page: 1,\n per_page: 50,\n },\n );\n\n for await (const foundFile of foundFiles) {\n const project = await this.gitLabClient.getProjectById(\n foundFile.project_id,\n );\n foundProjects++;\n\n if (\n project &&\n this.isProjectCompliant(project) &&\n this.isGroupCompliant(project.path_with_namespace)\n ) {\n locations.push(\n this.createLocationSpecFromParams(\n project.web_url,\n foundFile.ref,\n foundFile.path,\n ),\n );\n }\n }\n\n this.logger.info(\n `Processed ${locations.length} from ${foundProjects} found projects on API.`,\n );\n\n return locations;\n }\n\n /**\n * Determine the location on GitLab to be ingested base on configured groups and filters.\n *\n * @returns A list of location to be ingested\n */\n private async getEntities() {\n let res: Result = {\n scanned: 0,\n matches: [],\n };\n\n const groupToProcess = new Map<string, GitLabGroup>();\n let groupFilters;\n\n if (this.config.groupPattern !== undefined) {\n const patterns = Array.isArray(this.config.groupPattern)\n ? this.config.groupPattern\n : [this.config.groupPattern];\n\n if (patterns.length === 1 && patterns[0].source === '[\\\\s\\\\S]*') {\n // if the pattern is a catch-all, we don't need to filter groups\n groupFilters = new Array<RegExp>();\n } else {\n groupFilters = patterns;\n }\n }\n\n if (groupFilters && groupFilters.length > 0) {\n const groups = paginated<GitLabGroup>(\n options => this.gitLabClient.listGroups(options),\n {\n page: 1,\n per_page: 50,\n },\n );\n\n for await (const group of groups) {\n if (\n groupFilters.some(groupFilter => groupFilter.test(group.full_path)) &&\n !groupToProcess.has(group.full_path)\n ) {\n groupToProcess.set(group.full_path, group);\n }\n }\n\n for (const group of groupToProcess.values()) {\n const tmpRes = await this.getProjectsToProcess(group.full_path);\n res.scanned += tmpRes.scanned;\n // merge both arrays safely\n for (const project of tmpRes.matches) {\n res.matches.push(project);\n }\n }\n } else {\n res = await this.getProjectsToProcess(this.config.group);\n }\n\n const locations = this.deduplicateProjects(res.matches).map(p =>\n this.createLocationSpec(p),\n );\n\n this.logger.info(\n `Processed ${locations.length} from scanned ${res.scanned} projects.`,\n );\n\n return locations;\n }\n\n /**\n * Deduplicate a list of projects based on their id.\n *\n * @param projects - a list of projects to be deduplicated\n * @returns a list of projects with unique id\n */\n private deduplicateProjects(projects: GitLabProject[]): GitLabProject[] {\n const uniqueProjects = new Map<number, GitLabProject>();\n\n for (const project of projects) {\n uniqueProjects.set(project.id, project);\n }\n\n return Array.from(uniqueProjects.values());\n }\n\n /**\n * Retrieve a list of projects that match configuration.\n *\n * @param group - a full path of a GitLab group, can be empty\n * @returns An array of project to be processed and the number of project scanned\n */\n private async getProjectsToProcess(group: string) {\n const res: Result = {\n scanned: 0,\n matches: [],\n };\n\n const projects = paginated<GitLabProject>(\n options => this.gitLabClient.listProjects(options),\n {\n group: group,\n page: 1,\n per_page: 50,\n ...(!this.config.includeArchivedRepos && { archived: false }),\n ...(this.config.membership && { membership: true }),\n ...(this.config.topics && { topics: this.config.topics }),\n // Only use simple=true when we don't need to skip forked repos.\n // The simple=true parameter reduces response size by returning fewer fields,\n // but it excludes the 'forked_from_project' field which is required for fork detection.\n // Therefore, we can only optimize with simple=true when skipForkedRepos is false.\n ...(!this.config.skipForkedRepos && { simple: true }),\n },\n );\n\n for await (const project of projects) {\n res.scanned++;\n\n if (await this.shouldProcessProject(project, this.gitLabClient)) {\n res.matches.push(project);\n }\n }\n\n return res;\n }\n\n private createLocationSpecFromParams(\n projectURL: string,\n branch: string,\n catalogFile: string,\n ): LocationSpec {\n return {\n type: 'url',\n target: `${projectURL}/-/blob/${branch}/${catalogFile}`,\n presence: 'optional',\n };\n }\n\n private createLocationSpec(project: GitLabProject): LocationSpec {\n const project_branch =\n this.config.branch ??\n project.default_branch ??\n this.config.fallbackBranch;\n\n return this.createLocationSpecFromParams(\n project.web_url,\n project_branch,\n this.config.catalogFile,\n );\n }\n\n /**\n * Handles the \"gitlab.push\" event.\n *\n * @param event - The push event payload.\n */\n private async onRepoPush(event: WebhookPushEventSchema): Promise<void> {\n if (!this.connection) {\n throw new Error(\n `Gitlab discovery connection not initialized for ${this.getProviderName()}`,\n );\n }\n this.logger.info(\n `Received push event for ${event.project.path_with_namespace}`,\n );\n\n const project = await this.gitLabClient.getProjectById(event.project_id);\n\n if (!project) {\n this.logger.debug(\n `Ignoring push event for ${event.project.path_with_namespace}`,\n );\n\n return;\n }\n\n if (!(await this.shouldProcessProject(project, this.gitLabClient))) {\n this.logger.debug(`Skipping event ${event.project.path_with_namespace}`);\n return;\n }\n\n // Get array of added, removed or modified files from the push event\n const added = this.getFilesMatchingConfig(\n event,\n 'added',\n this.config.catalogFile,\n );\n const removed = this.getFilesMatchingConfig(\n event,\n 'removed',\n this.config.catalogFile,\n );\n const modified = this.getFilesMatchingConfig(\n event,\n 'modified',\n this.config.catalogFile,\n );\n\n // Modified files will be scheduled to a refresh\n const addedEntities = this.createLocationSpecCommitedFiles(\n event.project,\n added,\n );\n\n const removedEntities = this.createLocationSpecCommitedFiles(\n event.project,\n removed,\n );\n\n if (addedEntities.length > 0 || removedEntities.length > 0) {\n await this.connection.applyMutation({\n type: 'delta',\n added: this.toDeferredEntities(\n addedEntities.map(entity => entity.target),\n ),\n removed: this.toDeferredEntities(\n removedEntities.map(entity => entity.target),\n ),\n });\n }\n\n if (modified.length > 0) {\n const projectBranch =\n this.config.branch ??\n event.project.default_branch ??\n this.config.fallbackBranch;\n\n // scheduling a refresh to both tree and blob (https://git-scm.com/book/en/v2/Git-Internals-Git-Objects)\n await this.connection.refresh({\n keys: [\n ...modified.map(\n filePath =>\n `url:${event.project.web_url}/-/tree/${projectBranch}/${filePath}`,\n ),\n ...modified.map(\n filePath =>\n `url:${event.project.web_url}/-/blob/${projectBranch}/${filePath}`,\n ),\n ],\n });\n }\n\n this.logger.info(\n `Processed GitLab push event from ${event.project.web_url}: added ${added.length} - removed ${removed.length} - modified ${modified.length}`,\n );\n }\n\n /**\n * Gets files matching the specified commit action and catalog file name.\n *\n * @param event - The push event payload.\n * @param action - The action type ('added', 'removed', or 'modified').\n * @param catalogFile - The catalog file name.\n * @returns An array of file paths.\n */\n private getFilesMatchingConfig(\n event: WebhookPushEventSchema,\n action: 'added' | 'removed' | 'modified',\n catalogFile: string,\n ): string[] {\n if (!event.commits) {\n return [];\n }\n\n const matchingFiles = event.commits.flatMap((element: any) =>\n element[action].filter(\n (file: string) => path.basename(file) === catalogFile,\n ),\n );\n\n if (matchingFiles.length === 0) {\n this.logger.debug(\n `No files matching '${catalogFile}' found in the commits.`,\n );\n }\n\n return matchingFiles;\n }\n\n /**\n * Creates Backstage location specs for committed files.\n *\n * @param project - The GitLab project information.\n * @param addedFiles - The array of added file paths.\n * @returns An array of location specs.\n */\n private createLocationSpecCommitedFiles(\n project: WebhookProjectSchema,\n addedFiles: string[],\n ): LocationSpec[] {\n const projectBranch =\n this.config.branch ??\n project.default_branch ??\n this.config.fallbackBranch;\n\n // Filter added files that match the catalog file pattern\n const matchingFiles = addedFiles.filter(\n file => path.basename(file) === this.config.catalogFile,\n );\n\n // Create a location spec for each matching file\n const locationSpecs: LocationSpec[] = matchingFiles.map(file => ({\n type: 'url',\n target: `${project.web_url}/-/blob/${projectBranch}/${file}`,\n presence: 'optional',\n }));\n\n return locationSpecs;\n }\n\n /**\n * Converts a target URL to a LocationSpec object.\n *\n * @param target - The target URL to be converted.\n * @returns The LocationSpec object representing the URL.\n */\n private toLocationSpec(target: string): LocationSpec {\n return {\n type: 'url',\n target: target,\n presence: 'optional',\n };\n }\n\n private toDeferredEntities(targets: string[]): DeferredEntity[] {\n return targets\n .map(target => {\n const location = this.toLocationSpec(target);\n\n return locationSpecToLocationEntity({ location });\n })\n .map(entity => {\n return {\n locationKey: this.getProviderName(),\n entity: entity,\n };\n });\n }\n\n private isProjectCompliant(project: GitLabProject): boolean {\n if (!this.config.projectPattern.test(project.path_with_namespace ?? '')) {\n this.logger.debug(\n `Skipping project ${project.path_with_namespace} as it does not match the project pattern ${this.config.projectPattern}.`,\n );\n return false;\n }\n\n if (\n this.config.group &&\n !project.path_with_namespace!.startsWith(`${this.config.group}/`)\n ) {\n this.logger.debug(\n `Skipping project ${project.path_with_namespace} as it does not match the group pattern ${this.config.group}.`,\n );\n return false;\n }\n\n if (\n this.config.skipForkedRepos &&\n project.hasOwnProperty('forked_from_project')\n ) {\n this.logger.debug(\n `Skipping project ${project.path_with_namespace} as it is a forked project.`,\n );\n return false;\n }\n\n if (this.config.excludeRepos?.includes(project.path_with_namespace ?? '')) {\n this.logger.debug(\n `Skipping project ${project.path_with_namespace} as it is excluded.`,\n );\n return false;\n }\n\n return true;\n }\n\n private async shouldProcessProject(\n project: GitLabProject,\n client: GitLabClient,\n ): Promise<boolean> {\n if (!this.isProjectCompliant(project)) {\n return false;\n }\n\n const project_branch =\n this.config.branch ??\n project.default_branch ??\n this.config.fallbackBranch;\n\n const hasFile = await client.hasFile(\n project.id,\n project_branch,\n this.config.catalogFile,\n );\n\n return hasFile;\n }\n\n private isGroupCompliant(name: string | undefined) {\n const groupRegexes = Array.isArray(this.config.groupPattern)\n ? this.config.groupPattern\n : [this.config.groupPattern];\n\n if (name) {\n return groupRegexes.some(reg => reg.test(name));\n }\n\n return false;\n }\n}\n"],"names":["config","readGitlabConfigs","ScmIntegrations","G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mBAAA,IAAuB,EAAE,CAAA,EAAG;AACzE,MAAA,IAAA,CAAK,MAAA,CAAO,KAAA;AAAA,QACV,CAAA,iBAAA,EAAoB,QAAQ,mBAAmB,CAAA,mBAAA;AAAA,OACjD;AACA,MAAA,OAAO,KAAA;AAAA,IACT;AAEA,IAAA,OAAO,IAAA;AAAA,EACT;AAAA,EAEA,MAAc,oBAAA,CACZ,OAAA,EACA,MAAA,EACkB;AAClB,IAAA,IAAI,CAAC,IAAA,CAAK,kBAAA,CAAmB,OAAO,CAAA,EAAG;AACrC,MAAA,OAAO,KAAA;AAAA,IACT;AAEA,IAAA,MAAM,iBACJ,IAAA,CAAK,MAAA,CAAO,UACZ,OAAA,CAAQ,cAAA,IACR,KAAK,MAAA,CAAO,cAAA;AAEd,IAAA,MAAM,OAAA,GAAU,MAAM,MAAA,CAAO,OAAA;AAAA,MAC3B,OAAA,CAAQ,EAAA;AAAA,MACR,cAAA;AAAA,MACA,KAAK,MAAA,CAAO;AAAA,KACd;AAEA,IAAA,OAAO,OAAA;AAAA,EACT;AAAA,EAEQ,iBAAiB,IAAA,EAA0B;AACjD,IAAA,MAAM,YAAA,GAAe,KAAA,CAAM,OAAA,CAAQ,IAAA,CAAK,MAAA,CAAO,YAAY,CAAA,GACvD,IAAA,CAAK,MAAA,CAAO,YAAA,GACZ,CAAC,IAAA,CAAK,OAAO,YAAY,CAAA;AAE7B,IAAA,IAAI,IAAA,EAAM;AACR,MAAA,OAAO,aAAa,IAAA,CAAK,CAAA,GAAA,KAAO,GAAA,CAAI,IAAA,CAAK,IAAI,CAAC,CAAA;AAAA,IAChD;AAEA,IAAA,OAAO,KAAA;AAAA,EACT;AACF;;;;"}
@@ -26,6 +26,7 @@ function readGitlabConfig(id, config) {
26
26
  } else {
27
27
  groupPattern = new RegExp(/[\s\S]*/);
28
28
  }
29
+ const useSearch = config.getOptionalBoolean("useSearch") ?? false;
29
30
  const orgEnabled = config.getOptionalBoolean("orgEnabled") ?? false;
30
31
  const allowInherited = config.getOptionalBoolean("allowInherited") ?? false;
31
32
  const relations = config.getOptionalStringArray("relations") ?? [];
@@ -53,6 +54,7 @@ function readGitlabConfig(id, config) {
53
54
  schedule,
54
55
  orgEnabled,
55
56
  allowInherited,
57
+ useSearch,
56
58
  relations,
57
59
  skipForkedRepos,
58
60
  includeArchivedRepos,
@@ -1 +1 @@
1
- {"version":3,"file":"config.cjs.js","sources":["../../src/providers/config.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { readSchedulerServiceTaskScheduleDefinitionFromConfig } from '@backstage/backend-plugin-api';\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');\n const fallbackBranch = config.getOptionalString('fallbackBranch') ?? '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\n const configValue = config.getOptional('groupPattern');\n let groupPattern;\n\n if ((configValue && typeof configValue === 'string') || !configValue) {\n groupPattern = new RegExp(\n config.getOptionalString('groupPattern') ?? /[\\s\\S]*/,\n );\n } else if (configValue && Array.isArray(configValue)) {\n const configPattern = config.getOptionalStringArray('groupPattern') ?? [];\n groupPattern = configPattern.map(pattern => new RegExp(pattern));\n } else {\n groupPattern = new RegExp(/[\\s\\S]*/);\n }\n\n const orgEnabled: boolean = config.getOptionalBoolean('orgEnabled') ?? false;\n const allowInherited: boolean =\n config.getOptionalBoolean('allowInherited') ?? false;\n const relations: string[] = config.getOptionalStringArray('relations') ?? [];\n\n const skipForkedRepos: boolean =\n config.getOptionalBoolean('skipForkedRepos') ?? false;\n\n const includeArchivedRepos: boolean =\n config.getOptionalBoolean('includeArchivedRepos') ?? false;\n const excludeRepos: string[] =\n config.getOptionalStringArray('excludeRepos') ?? [];\n\n const schedule = config.has('schedule')\n ? readSchedulerServiceTaskScheduleDefinitionFromConfig(\n config.getConfig('schedule'),\n )\n : undefined;\n const restrictUsersToGroup =\n config.getOptionalBoolean('restrictUsersToGroup') ?? false;\n\n const includeUsersWithoutSeat =\n config.getOptionalBoolean('includeUsersWithoutSeat') ?? false;\n\n const membership = config.getOptionalBoolean('membership');\n\n const topicsArray = config.getOptionalStringArray('topics');\n const topics = topicsArray?.length ? topicsArray.join(',') : undefined;\n\n return {\n id,\n group,\n branch,\n fallbackBranch,\n host,\n catalogFile,\n projectPattern,\n userPattern,\n groupPattern,\n schedule,\n orgEnabled,\n allowInherited,\n relations,\n skipForkedRepos,\n includeArchivedRepos,\n excludeRepos,\n restrictUsersToGroup,\n includeUsersWithoutSeat,\n membership,\n topics,\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"],"names":["readSchedulerServiceTaskScheduleDefinitionFromConfig"],"mappings":";;;;AA4BA,SAA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ACA,QAAA;AAAA,IACA,UAAA;AAAA,IACA,cAAA;AAAA,IACA,SAAA;AAAA,IACA,eAAA;AAAA,IACA,oBAAA;AAAA,IACA,YAAA;AAAA,IACA,oBAAA;AAAA,IACA,uBAAA;AAAA,IACA,UAAA;AAAA,IACA;AAAA,GACF;AACF;AASO,SAAS,kBAAkB,MAAA,EAAwC;AACxE,EAAA,MAAM,UAAkC,EAAC;AAEzC,EAAA,MAAM,eAAA,GAAkB,MAAA,CAAO,iBAAA,CAAkB,0BAA0B,CAAA;AAE3E,EAAA,IAAI,CAAC,eAAA,EAAiB;AACpB,IAAA,OAAO,OAAA;AAAA,EACT;AAEA,EAAA,KAAA,MAAW,EAAA,IAAM,eAAA,CAAgB,IAAA,EAAK,EAAG;AACvC,IAAA,OAAA,CAAQ,KAAK,gBAAA,CAAiB,EAAA,EAAI,gBAAgB,SAAA,CAAU,EAAE,CAAC,CAAC,CAAA;AAAA,EAClE;AAEA,EAAA,OAAO,OAAA;AACT;;;;"}
1
+ {"version":3,"file":"config.cjs.js","sources":["../../src/providers/config.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { readSchedulerServiceTaskScheduleDefinitionFromConfig } from '@backstage/backend-plugin-api';\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');\n const fallbackBranch = config.getOptionalString('fallbackBranch') ?? '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\n const configValue = config.getOptional('groupPattern');\n let groupPattern;\n\n if ((configValue && typeof configValue === 'string') || !configValue) {\n groupPattern = new RegExp(\n config.getOptionalString('groupPattern') ?? /[\\s\\S]*/,\n );\n } else if (configValue && Array.isArray(configValue)) {\n const configPattern = config.getOptionalStringArray('groupPattern') ?? [];\n groupPattern = configPattern.map(pattern => new RegExp(pattern));\n } else {\n groupPattern = new RegExp(/[\\s\\S]*/);\n }\n\n const useSearch: boolean = config.getOptionalBoolean('useSearch') ?? false;\n const orgEnabled: boolean = config.getOptionalBoolean('orgEnabled') ?? false;\n const allowInherited: boolean =\n config.getOptionalBoolean('allowInherited') ?? false;\n const relations: string[] = config.getOptionalStringArray('relations') ?? [];\n\n const skipForkedRepos: boolean =\n config.getOptionalBoolean('skipForkedRepos') ?? false;\n\n const includeArchivedRepos: boolean =\n config.getOptionalBoolean('includeArchivedRepos') ?? false;\n const excludeRepos: string[] =\n config.getOptionalStringArray('excludeRepos') ?? [];\n\n const schedule = config.has('schedule')\n ? readSchedulerServiceTaskScheduleDefinitionFromConfig(\n config.getConfig('schedule'),\n )\n : undefined;\n const restrictUsersToGroup =\n config.getOptionalBoolean('restrictUsersToGroup') ?? false;\n\n const includeUsersWithoutSeat =\n config.getOptionalBoolean('includeUsersWithoutSeat') ?? false;\n\n const membership = config.getOptionalBoolean('membership');\n\n const topicsArray = config.getOptionalStringArray('topics');\n const topics = topicsArray?.length ? topicsArray.join(',') : undefined;\n\n return {\n id,\n group,\n branch,\n fallbackBranch,\n host,\n catalogFile,\n projectPattern,\n userPattern,\n groupPattern,\n schedule,\n orgEnabled,\n allowInherited,\n useSearch,\n relations,\n skipForkedRepos,\n includeArchivedRepos,\n excludeRepos,\n restrictUsersToGroup,\n includeUsersWithoutSeat,\n membership,\n topics,\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"],"names":["readSchedulerServiceTaskScheduleDefinitionFromConfig"],"mappings":";;;;AA4BA,SAAS,gBAAA,CAAiB,IAAY,MAAA,EAAsC;AAC1E,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,iBAAA,CAAkB,OAAO,CAAA,IAAK,EAAA;AACnD,EAAA,MAAM,IAAA,GAAO,MAAA,CAAO,SAAA,CAAU,MAAM,CAAA;AACpC,EAAA,MAAM,MAAA,GAAS,MAAA,CAAO,iBAAA,CAAkB,QAAQ,CAAA;AAChD,EAAA,MAAM,cAAA,GAAiB,MAAA,CAAO,iBAAA,CAAkB,gBAAgB,CAAA,IAAK,QAAA;AACrE,EAAA,MAAM,WAAA,GACJ,MAAA,CAAO,iBAAA,CAAkB,gBAAgB,CAAA,IAAK,mBAAA;AAChD,EAAA,MAAM,iBAAiB,IAAI,MAAA;AAAA,IACzB,MAAA,CAAO,iBAAA,CAAkB,gBAAgB,CAAA,IAAK;AAAA,GAChD;AACA,EAAA,MAAM,cAAc,IAAI,MAAA;AAAA,IACtB,MAAA,CAAO,iBAAA,CAAkB,aAAa,CAAA,IAAK;AAAA,GAC7C;AAEA,EAAA,MAAM,WAAA,GAAc,MAAA,CAAO,WAAA,CAAY,cAAc,CAAA;AACrD,EAAA,IAAI,YAAA;AAEJ,EAAA,IAAK,WAAA,IAAe,OAAO,WAAA,KAAgB,QAAA,I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backend-module-gitlab",
3
- "version": "0.7.7",
3
+ "version": "0.8.0-next.1",
4
4
  "description": "A Backstage catalog backend module that helps integrate towards GitLab",
5
5
  "backstage": {
6
6
  "role": "backend-plugin-module",
@@ -65,23 +65,23 @@
65
65
  "test": "backstage-cli package test"
66
66
  },
67
67
  "dependencies": {
68
- "@backstage/backend-defaults": "^0.15.0",
69
- "@backstage/backend-plugin-api": "^1.6.1",
70
- "@backstage/catalog-model": "^1.7.6",
71
- "@backstage/config": "^1.3.6",
72
- "@backstage/integration": "^1.19.2",
73
- "@backstage/plugin-catalog-common": "^1.1.7",
74
- "@backstage/plugin-catalog-node": "^1.20.1",
75
- "@backstage/plugin-events-node": "^0.4.18",
68
+ "@backstage/backend-defaults": "0.15.2-next.1",
69
+ "@backstage/backend-plugin-api": "1.7.0-next.1",
70
+ "@backstage/catalog-model": "1.7.6",
71
+ "@backstage/config": "1.3.6",
72
+ "@backstage/integration": "1.20.0-next.1",
73
+ "@backstage/plugin-catalog-common": "1.1.8-next.0",
74
+ "@backstage/plugin-catalog-node": "1.21.0-next.0",
75
+ "@backstage/plugin-events-node": "0.4.19-next.0",
76
76
  "@gitbeaker/rest": "^40.0.3",
77
77
  "lodash": "^4.17.21",
78
78
  "node-fetch": "^2.7.0",
79
79
  "uuid": "^11.0.0"
80
80
  },
81
81
  "devDependencies": {
82
- "@backstage/backend-test-utils": "^1.10.3",
83
- "@backstage/cli": "^0.35.2",
84
- "@backstage/plugin-events-backend-test-utils": "^0.1.51",
82
+ "@backstage/backend-test-utils": "1.10.5-next.0",
83
+ "@backstage/cli": "0.35.4-next.1",
84
+ "@backstage/plugin-events-backend-test-utils": "0.1.52-next.0",
85
85
  "@types/lodash": "^4.14.151",
86
86
  "msw": "^1.0.0"
87
87
  },