3 * Copyright (C) 2009-2024 SonarSource SA
4 * mailto:info AT sonarsource DOT com
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.
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.
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.
20 package org.sonar.server.common.almsettings.gitlab;
22 import java.util.Optional;
23 import org.jetbrains.annotations.Nullable;
24 import org.sonar.alm.client.gitlab.GitLabBranch;
25 import org.sonar.alm.client.gitlab.GitlabApplicationClient;
26 import org.sonar.alm.client.gitlab.GitlabServerException;
27 import org.sonar.alm.client.gitlab.Project;
28 import org.sonar.db.DbClient;
29 import org.sonar.db.DbSession;
30 import org.sonar.db.alm.pat.AlmPatDto;
31 import org.sonar.db.alm.setting.AlmSettingDto;
32 import org.sonar.db.alm.setting.ProjectAlmSettingDto;
33 import org.sonar.db.project.CreationMethod;
34 import org.sonar.db.project.ProjectDto;
35 import org.sonar.server.common.almintegration.ProjectKeyGenerator;
36 import org.sonar.server.common.almsettings.DevOpsProjectCreator;
37 import org.sonar.server.common.almsettings.DevOpsProjectDescriptor;
38 import org.sonar.server.common.project.ProjectCreator;
39 import org.sonar.server.component.ComponentCreationData;
40 import org.sonar.server.user.UserSession;
42 import static java.lang.String.format;
43 import static java.util.Objects.requireNonNull;
45 public class GitlabProjectCreator implements DevOpsProjectCreator {
47 private final DbClient dbClient;
48 private final ProjectKeyGenerator projectKeyGenerator;
49 private final ProjectCreator projectCreator;
50 private final AlmSettingDto almSettingDto;
51 private final DevOpsProjectDescriptor devOpsProjectDescriptor;
52 private final GitlabApplicationClient gitlabApplicationClient;
53 private final UserSession userSession;
55 public GitlabProjectCreator(DbClient dbClient, ProjectKeyGenerator projectKeyGenerator, ProjectCreator projectCreator, AlmSettingDto almSettingDto,
56 DevOpsProjectDescriptor devOpsProjectDescriptor, GitlabApplicationClient gitlabApplicationClient, UserSession userSession) {
57 this.dbClient = dbClient;
58 this.projectKeyGenerator = projectKeyGenerator;
59 this.projectCreator = projectCreator;
60 this.almSettingDto = almSettingDto;
61 this.devOpsProjectDescriptor = devOpsProjectDescriptor;
62 this.gitlabApplicationClient = gitlabApplicationClient;
63 this.userSession = userSession;
67 public boolean isScanAllowedUsingPermissionsFromDevopsPlatform() {
68 throw new UnsupportedOperationException("Not Implemented");
72 public ComponentCreationData createProjectAndBindToDevOpsPlatform(DbSession dbSession, CreationMethod creationMethod, Boolean monorepo, @Nullable String projectKey,
73 @Nullable String projectName) {
75 String pat = findPersonalAccessTokenOrThrow(dbSession, almSettingDto);
77 String gitlabUrl = requireNonNull(almSettingDto.getUrl(), "DevOps Platform gitlabUrl cannot be null");
79 Long gitlabProjectId = getGitlabProjectId();
80 Project gitlabProject = fetchGitlabProject(gitlabUrl, pat, gitlabProjectId);
82 Optional<String> almDefaultBranch = getDefaultBranchOnGitlab(gitlabUrl, pat, gitlabProjectId);
83 ComponentCreationData componentCreationData = projectCreator.createProject(
85 getProjectKey(projectKey, gitlabProject),
86 getProjectName(projectName, gitlabProject),
87 almDefaultBranch.orElse(null),
89 ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
91 createProjectAlmSettingDto(dbSession, gitlabProjectId.toString(), projectDto, almSettingDto, monorepo);
92 return componentCreationData;
95 private String findPersonalAccessTokenOrThrow(DbSession dbSession, AlmSettingDto almSettingDto) {
96 String userUuid = requireNonNull(userSession.getUuid(), "User UUID cannot be null.");
97 Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
98 return almPatDto.map(AlmPatDto::getPersonalAccessToken)
99 .orElseThrow(() -> new IllegalArgumentException(format("personal access token for '%s' is missing", almSettingDto.getKey())));
102 private Long getGitlabProjectId() {
104 return Long.parseLong(devOpsProjectDescriptor.repositoryIdentifier());
105 } catch (NumberFormatException e) {
106 throw new IllegalArgumentException(format("GitLab project identifier must be a number, was '%s'", devOpsProjectDescriptor.repositoryIdentifier()));
110 private Project fetchGitlabProject(String gitlabUrl, String pat, Long gitlabProjectId) {
112 return gitlabApplicationClient.getProject(
116 } catch (GitlabServerException e) {
117 throw new IllegalStateException(format("Failed to fetch GitLab project with ID '%s' from '%s'", gitlabProjectId, gitlabUrl), e);
121 private Optional<String> getDefaultBranchOnGitlab(String gitlabUrl, String pat, long gitlabProjectId) {
122 Optional<GitLabBranch> almMainBranch = gitlabApplicationClient.getBranches(gitlabUrl, pat, gitlabProjectId).stream().filter(GitLabBranch::isDefault).findFirst();
123 return almMainBranch.map(GitLabBranch::getName);
126 private String getProjectKey(@Nullable String projectKey, Project gitlabProject) {
127 return Optional.ofNullable(projectKey).orElseGet(() -> projectKeyGenerator.generateUniqueProjectKey(gitlabProject.getPathWithNamespace()));
130 private static String getProjectName(@Nullable String projectName, Project gitlabProject) {
131 return Optional.ofNullable(projectName).orElse(gitlabProject.getName());
134 private void createProjectAlmSettingDto(DbSession dbSession, String gitlabProjectId, ProjectDto projectDto, AlmSettingDto almSettingDto, Boolean monorepo) {
135 ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto()
136 .setAlmSettingUuid(almSettingDto.getUuid())
137 .setAlmRepo(gitlabProjectId)
139 .setProjectUuid(projectDto.getUuid())
140 .setSummaryCommentEnabled(true)
141 .setMonorepo(monorepo);
142 dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(), projectDto.getName(), projectDto.getKey());