You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SearchGitlabReposAction.java 8.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2023 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. package org.sonar.server.almintegration.ws.gitlab;
  21. import java.util.List;
  22. import java.util.Map;
  23. import java.util.Optional;
  24. import java.util.Set;
  25. import java.util.function.BinaryOperator;
  26. import java.util.function.Function;
  27. import java.util.stream.Collectors;
  28. import org.sonar.alm.client.gitlab.GitlabHttpClient;
  29. import org.sonar.alm.client.gitlab.Project;
  30. import org.sonar.alm.client.gitlab.ProjectList;
  31. import org.sonar.api.server.ws.Request;
  32. import org.sonar.api.server.ws.Response;
  33. import org.sonar.api.server.ws.WebService;
  34. import org.sonar.db.DbClient;
  35. import org.sonar.db.DbSession;
  36. import org.sonar.db.alm.pat.AlmPatDto;
  37. import org.sonar.db.alm.setting.AlmSettingDto;
  38. import org.sonar.db.alm.setting.ProjectAlmSettingDto;
  39. import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction;
  40. import org.sonar.server.exceptions.NotFoundException;
  41. import org.sonar.server.user.UserSession;
  42. import org.sonarqube.ws.AlmIntegrations;
  43. import org.sonarqube.ws.AlmIntegrations.GitlabRepository;
  44. import org.sonarqube.ws.Common.Paging;
  45. import static java.util.Objects.requireNonNull;
  46. import static java.util.stream.Collectors.toSet;
  47. import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS;
  48. import static org.sonar.server.ws.WsUtils.writeProtobuf;
  49. public class SearchGitlabReposAction implements AlmIntegrationsWsAction {
  50. private static final String PARAM_ALM_SETTING = "almSetting";
  51. private static final String PARAM_PROJECT_NAME = "projectName";
  52. private static final int DEFAULT_PAGE_SIZE = 20;
  53. private static final int MAX_PAGE_SIZE = 500;
  54. private final DbClient dbClient;
  55. private final UserSession userSession;
  56. private final GitlabHttpClient gitlabHttpClient;
  57. public SearchGitlabReposAction(DbClient dbClient, UserSession userSession, GitlabHttpClient gitlabHttpClient) {
  58. this.dbClient = dbClient;
  59. this.userSession = userSession;
  60. this.gitlabHttpClient = gitlabHttpClient;
  61. }
  62. @Override
  63. public void define(WebService.NewController context) {
  64. WebService.NewAction action = context.createAction("search_gitlab_repos")
  65. .setDescription("Search the GitLab projects.<br/>" +
  66. "Requires the 'Create Projects' permission")
  67. .setPost(false)
  68. .setSince("8.5")
  69. .setHandler(this);
  70. action.createParam(PARAM_ALM_SETTING)
  71. .setRequired(true)
  72. .setMaximumLength(200)
  73. .setDescription("DevOps Platform setting key");
  74. action.createParam(PARAM_PROJECT_NAME)
  75. .setRequired(false)
  76. .setMaximumLength(200)
  77. .setDescription("Project name filter");
  78. action.addPagingParams(DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE);
  79. action.setResponseExample(getClass().getResource("search_gitlab_repos.json"));
  80. }
  81. @Override
  82. public void handle(Request request, Response response) {
  83. AlmIntegrations.SearchGitlabReposWsResponse wsResponse = doHandle(request);
  84. writeProtobuf(wsResponse, request, response);
  85. }
  86. private AlmIntegrations.SearchGitlabReposWsResponse doHandle(Request request) {
  87. String almSettingKey = request.mandatoryParam(PARAM_ALM_SETTING);
  88. String projectName = request.param(PARAM_PROJECT_NAME);
  89. int pageNumber = request.mandatoryParamAsInt("p");
  90. int pageSize = request.mandatoryParamAsInt("ps");
  91. try (DbSession dbSession = dbClient.openSession(false)) {
  92. userSession.checkLoggedIn().checkPermission(PROVISION_PROJECTS);
  93. String userUuid = requireNonNull(userSession.getUuid(), "User UUID cannot be null");
  94. AlmSettingDto almSettingDto = dbClient.almSettingDao().selectByKey(dbSession, almSettingKey)
  95. .orElseThrow(() -> new NotFoundException(String.format("DevOps Platform Setting '%s' not found", almSettingKey)));
  96. Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
  97. String personalAccessToken = almPatDto.map(AlmPatDto::getPersonalAccessToken).orElseThrow(() -> new IllegalArgumentException("No personal access token found"));
  98. String gitlabUrl = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null");
  99. ProjectList gitlabProjectList = gitlabHttpClient
  100. .searchProjects(gitlabUrl, personalAccessToken, projectName, pageNumber, pageSize);
  101. Map<String, ProjectKeyName> sqProjectsKeyByGitlabProjectId = getSqProjectsKeyByGitlabProjectId(dbSession, almSettingDto, gitlabProjectList);
  102. List<GitlabRepository> gitlabRepositories = gitlabProjectList.getProjects().stream()
  103. .map(project -> toGitlabRepository(project, sqProjectsKeyByGitlabProjectId))
  104. .toList();
  105. Paging.Builder pagingBuilder = Paging.newBuilder()
  106. .setPageIndex(gitlabProjectList.getPageNumber())
  107. .setPageSize(gitlabProjectList.getPageSize());
  108. Integer gitlabProjectListTotal = gitlabProjectList.getTotal();
  109. if (gitlabProjectListTotal != null) {
  110. pagingBuilder.setTotal(gitlabProjectListTotal);
  111. }
  112. return AlmIntegrations.SearchGitlabReposWsResponse.newBuilder()
  113. .addAllRepositories(gitlabRepositories)
  114. .setPaging(pagingBuilder.build())
  115. .build();
  116. }
  117. }
  118. private Map<String, ProjectKeyName> getSqProjectsKeyByGitlabProjectId(DbSession dbSession, AlmSettingDto almSettingDto,
  119. ProjectList gitlabProjectList) {
  120. Set<String> gitlabProjectIds = gitlabProjectList.getProjects().stream().map(Project::getId).map(String::valueOf)
  121. .collect(toSet());
  122. Map<String, ProjectAlmSettingDto> projectAlmSettingDtos = dbClient.projectAlmSettingDao()
  123. .selectByAlmSettingAndRepos(dbSession, almSettingDto, gitlabProjectIds)
  124. .stream().collect(Collectors.toMap(ProjectAlmSettingDto::getProjectUuid, Function.identity()));
  125. return dbClient.projectDao().selectByUuids(dbSession, projectAlmSettingDtos.keySet())
  126. .stream()
  127. .collect(Collectors.toMap(projectDto -> projectAlmSettingDtos.get(projectDto.getUuid()).getAlmRepo(),
  128. p -> new ProjectKeyName(p.getKey(), p.getName()), resolveNameCollisionOperatorByNaturalOrder()));
  129. }
  130. private static BinaryOperator<ProjectKeyName> resolveNameCollisionOperatorByNaturalOrder() {
  131. return (a, b) -> b.key.compareTo(a.key) > 0 ? a : b;
  132. }
  133. private static GitlabRepository toGitlabRepository(Project project, Map<String, ProjectKeyName> sqProjectsKeyByGitlabProjectId) {
  134. String name = project.getName();
  135. String pathName = removeLastOccurrenceOfString(project.getNameWithNamespace(), " / " + name);
  136. String slug = project.getPath();
  137. String pathSlug = removeLastOccurrenceOfString(project.getPathWithNamespace(), "/" + slug);
  138. GitlabRepository.Builder builder = GitlabRepository.newBuilder()
  139. .setId(project.getId())
  140. .setName(name)
  141. .setPathName(pathName)
  142. .setSlug(slug)
  143. .setPathSlug(pathSlug)
  144. .setUrl(project.getWebUrl());
  145. String projectIdAsString = String.valueOf(project.getId());
  146. Optional.ofNullable(sqProjectsKeyByGitlabProjectId.get(projectIdAsString))
  147. .ifPresent(p -> builder
  148. .setSqProjectKey(p.key)
  149. .setSqProjectName(p.name));
  150. return builder.build();
  151. }
  152. private static String removeLastOccurrenceOfString(String string, String stringToRemove) {
  153. StringBuilder resultString = new StringBuilder(string);
  154. int index = resultString.lastIndexOf(stringToRemove);
  155. if (index > -1) {
  156. resultString.delete(index, string.length() + index);
  157. }
  158. return resultString.toString();
  159. }
  160. static class ProjectKeyName {
  161. String key;
  162. String name;
  163. ProjectKeyName(String key, String name) {
  164. this.key = key;
  165. this.name = name;
  166. }
  167. }
  168. }