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.

GitlabProjectCreator.java 6.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2024 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.common.almsettings.gitlab;
  21. import java.util.Optional;
  22. import org.jetbrains.annotations.Nullable;
  23. import org.sonar.alm.client.gitlab.GitLabBranch;
  24. import org.sonar.alm.client.gitlab.GitlabApplicationClient;
  25. import org.sonar.alm.client.gitlab.GitlabServerException;
  26. import org.sonar.alm.client.gitlab.Project;
  27. import org.sonar.db.DbClient;
  28. import org.sonar.db.DbSession;
  29. import org.sonar.db.alm.pat.AlmPatDto;
  30. import org.sonar.db.alm.setting.AlmSettingDto;
  31. import org.sonar.db.alm.setting.ProjectAlmSettingDto;
  32. import org.sonar.db.project.CreationMethod;
  33. import org.sonar.db.project.ProjectDto;
  34. import org.sonar.server.common.almintegration.ProjectKeyGenerator;
  35. import org.sonar.server.common.almsettings.DevOpsProjectCreator;
  36. import org.sonar.server.common.almsettings.DevOpsProjectDescriptor;
  37. import org.sonar.server.common.project.ProjectCreator;
  38. import org.sonar.server.component.ComponentCreationData;
  39. import org.sonar.server.user.UserSession;
  40. import static java.lang.String.format;
  41. import static java.util.Objects.requireNonNull;
  42. public class GitlabProjectCreator implements DevOpsProjectCreator {
  43. private final DbClient dbClient;
  44. private final ProjectKeyGenerator projectKeyGenerator;
  45. private final ProjectCreator projectCreator;
  46. private final AlmSettingDto almSettingDto;
  47. private final DevOpsProjectDescriptor devOpsProjectDescriptor;
  48. private final GitlabApplicationClient gitlabApplicationClient;
  49. private final UserSession userSession;
  50. public GitlabProjectCreator(DbClient dbClient, ProjectKeyGenerator projectKeyGenerator, ProjectCreator projectCreator, AlmSettingDto almSettingDto,
  51. DevOpsProjectDescriptor devOpsProjectDescriptor, GitlabApplicationClient gitlabApplicationClient, UserSession userSession) {
  52. this.dbClient = dbClient;
  53. this.projectKeyGenerator = projectKeyGenerator;
  54. this.projectCreator = projectCreator;
  55. this.almSettingDto = almSettingDto;
  56. this.devOpsProjectDescriptor = devOpsProjectDescriptor;
  57. this.gitlabApplicationClient = gitlabApplicationClient;
  58. this.userSession = userSession;
  59. }
  60. @Override
  61. public boolean isScanAllowedUsingPermissionsFromDevopsPlatform() {
  62. throw new UnsupportedOperationException("Not Implemented");
  63. }
  64. @Override
  65. public ComponentCreationData createProjectAndBindToDevOpsPlatform(DbSession dbSession, CreationMethod creationMethod, Boolean monorepo, @Nullable String projectKey,
  66. @Nullable String projectName) {
  67. String pat = findPersonalAccessTokenOrThrow(dbSession, almSettingDto);
  68. String gitlabUrl = requireNonNull(almSettingDto.getUrl(), "DevOps Platform gitlabUrl cannot be null");
  69. Long gitlabProjectId = getGitlabProjectId();
  70. Project gitlabProject = fetchGitlabProject(gitlabUrl, pat, gitlabProjectId);
  71. Optional<String> almDefaultBranch = getDefaultBranchOnGitlab(gitlabUrl, pat, gitlabProjectId);
  72. ComponentCreationData componentCreationData = projectCreator.createProject(
  73. dbSession,
  74. getProjectKey(projectKey, gitlabProject),
  75. getProjectName(projectName, gitlabProject),
  76. almDefaultBranch.orElse(null),
  77. creationMethod);
  78. ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
  79. createProjectAlmSettingDto(dbSession, gitlabProjectId.toString(), projectDto, almSettingDto, monorepo);
  80. return componentCreationData;
  81. }
  82. private String findPersonalAccessTokenOrThrow(DbSession dbSession, AlmSettingDto almSettingDto) {
  83. String userUuid = requireNonNull(userSession.getUuid(), "User UUID cannot be null.");
  84. Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
  85. return almPatDto.map(AlmPatDto::getPersonalAccessToken)
  86. .orElseThrow(() -> new IllegalArgumentException(format("personal access token for '%s' is missing", almSettingDto.getKey())));
  87. }
  88. private Long getGitlabProjectId() {
  89. try {
  90. return Long.parseLong(devOpsProjectDescriptor.repositoryIdentifier());
  91. } catch (NumberFormatException e) {
  92. throw new IllegalArgumentException(format("GitLab project identifier must be a number, was '%s'", devOpsProjectDescriptor.repositoryIdentifier()));
  93. }
  94. }
  95. private Project fetchGitlabProject(String gitlabUrl, String pat, Long gitlabProjectId) {
  96. try {
  97. return gitlabApplicationClient.getProject(
  98. gitlabUrl,
  99. pat,
  100. gitlabProjectId);
  101. } catch (GitlabServerException e) {
  102. throw new IllegalStateException(format("Failed to fetch GitLab project with ID '%s' from '%s'", gitlabProjectId, gitlabUrl), e);
  103. }
  104. }
  105. private Optional<String> getDefaultBranchOnGitlab(String gitlabUrl, String pat, long gitlabProjectId) {
  106. Optional<GitLabBranch> almMainBranch = gitlabApplicationClient.getBranches(gitlabUrl, pat, gitlabProjectId).stream().filter(GitLabBranch::isDefault).findFirst();
  107. return almMainBranch.map(GitLabBranch::getName);
  108. }
  109. private String getProjectKey(@Nullable String projectKey, Project gitlabProject) {
  110. return Optional.ofNullable(projectKey).orElseGet(() -> projectKeyGenerator.generateUniqueProjectKey(gitlabProject.getPathWithNamespace()));
  111. }
  112. private static String getProjectName(@Nullable String projectName, Project gitlabProject) {
  113. return Optional.ofNullable(projectName).orElse(gitlabProject.getName());
  114. }
  115. private void createProjectAlmSettingDto(DbSession dbSession, String gitlabProjectId, ProjectDto projectDto, AlmSettingDto almSettingDto, Boolean monorepo) {
  116. ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto()
  117. .setAlmSettingUuid(almSettingDto.getUuid())
  118. .setAlmRepo(gitlabProjectId)
  119. .setAlmSlug(null)
  120. .setProjectUuid(projectDto.getUuid())
  121. .setSummaryCommentEnabled(true)
  122. .setMonorepo(monorepo);
  123. dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(), projectDto.getName(), projectDto.getKey());
  124. }
  125. }