3 * Copyright (C) 2009-2023 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.almintegration.ws.gitlab;
22 import java.util.Optional;
23 import javax.annotation.Nullable;
24 import javax.inject.Inject;
25 import org.sonar.alm.client.gitlab.GitLabBranch;
26 import org.sonar.alm.client.gitlab.GitlabHttpClient;
27 import org.sonar.alm.client.gitlab.Project;
28 import org.sonar.api.server.ws.Request;
29 import org.sonar.api.server.ws.Response;
30 import org.sonar.api.server.ws.WebService;
31 import org.sonar.db.DbClient;
32 import org.sonar.db.DbSession;
33 import org.sonar.db.alm.pat.AlmPatDto;
34 import org.sonar.db.alm.setting.AlmSettingDto;
35 import org.sonar.db.alm.setting.ProjectAlmSettingDto;
36 import org.sonar.db.project.ProjectDto;
37 import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction;
38 import org.sonar.server.almintegration.ws.ImportHelper;
39 import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
40 import org.sonar.server.component.ComponentCreationData;
41 import org.sonar.server.component.ComponentUpdater;
42 import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver;
43 import org.sonar.server.project.DefaultBranchNameResolver;
44 import org.sonar.server.project.ProjectDefaultVisibility;
45 import org.sonar.server.user.UserSession;
46 import org.sonarqube.ws.Projects.CreateWsResponse;
48 import static java.util.Objects.requireNonNull;
49 import static org.sonar.api.resources.Qualifiers.PROJECT;
50 import static org.sonar.server.component.NewComponent.newComponentBuilder;
51 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION;
52 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION;
53 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam;
54 import static org.sonar.server.ws.WsUtils.writeProtobuf;
55 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE;
56 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE;
58 public class ImportGitLabProjectAction implements AlmIntegrationsWsAction {
60 public static final String PARAM_GITLAB_PROJECT_ID = "gitlabProjectId";
62 private final DbClient dbClient;
63 private final UserSession userSession;
64 private final ProjectDefaultVisibility projectDefaultVisibility;
65 private final GitlabHttpClient gitlabHttpClient;
66 private final ComponentUpdater componentUpdater;
67 private final ImportHelper importHelper;
68 private final ProjectKeyGenerator projectKeyGenerator;
69 private final NewCodeDefinitionResolver newCodeDefinitionResolver;
70 private final DefaultBranchNameResolver defaultBranchNameResolver;
73 public ImportGitLabProjectAction(DbClient dbClient, UserSession userSession,
74 ProjectDefaultVisibility projectDefaultVisibility, GitlabHttpClient gitlabHttpClient,
75 ComponentUpdater componentUpdater, ImportHelper importHelper, ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver,
76 DefaultBranchNameResolver defaultBranchNameResolver) {
77 this.dbClient = dbClient;
78 this.userSession = userSession;
79 this.projectDefaultVisibility = projectDefaultVisibility;
80 this.gitlabHttpClient = gitlabHttpClient;
81 this.componentUpdater = componentUpdater;
82 this.importHelper = importHelper;
83 this.projectKeyGenerator = projectKeyGenerator;
84 this.newCodeDefinitionResolver = newCodeDefinitionResolver;
85 this.defaultBranchNameResolver = defaultBranchNameResolver;
89 public void define(WebService.NewController context) {
90 WebService.NewAction action = context.createAction("import_gitlab_project")
91 .setDescription("Import a GitLab project to SonarQube, creating a new project and configuring MR decoration<br/>" +
92 "Requires the 'Create Projects' permission")
97 action.createParam(ImportHelper.PARAM_ALM_SETTING)
99 .setDescription("DevOps Platform setting key");
100 action.createParam(PARAM_GITLAB_PROJECT_ID)
102 .setDescription("GitLab project ID");
104 action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
105 .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
108 action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
109 .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
114 public void handle(Request request, Response response) throws Exception {
115 CreateWsResponse createResponse = doHandle(request);
116 writeProtobuf(createResponse, request, response);
119 private CreateWsResponse doHandle(Request request) {
120 importHelper.checkProvisionProjectPermission();
122 String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE);
123 String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE);
125 try (DbSession dbSession = dbClient.openSession(false)) {
126 AlmSettingDto almSettingDto = importHelper.getAlmSetting(request);
127 String pat = getPat(dbSession, almSettingDto);
129 long gitlabProjectId = request.mandatoryParamAsLong(PARAM_GITLAB_PROJECT_ID);
131 String gitlabUrl = requireNonNull(almSettingDto.getUrl(), "DevOps Platform gitlabUrl cannot be null");
132 Project gitlabProject = gitlabHttpClient.getProject(gitlabUrl, pat, gitlabProjectId);
134 Optional<String> almMainBranchName = getAlmDefaultBranch(pat, gitlabProjectId, gitlabUrl);
136 ComponentCreationData componentCreationData = createProject(dbSession, gitlabProject, almMainBranchName.orElse(null));
137 ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
138 populateMRSetting(dbSession, gitlabProjectId, projectDto, almSettingDto);
140 checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
142 if (newCodeDefinitionType != null) {
143 newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), almMainBranchName.orElse(defaultBranchNameResolver.getEffectiveMainBranchName()),
144 newCodeDefinitionType, newCodeDefinitionValue);
147 componentUpdater.commitAndIndex(dbSession, componentCreationData.mainBranchComponent());
149 return ImportHelper.toCreateResponse(projectDto);
153 private String getPat(DbSession dbSession, AlmSettingDto almSettingDto) {
154 String userUuid = importHelper.getUserUuid();
155 Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
156 return almPatDto.map(AlmPatDto::getPersonalAccessToken)
157 .orElseThrow(() -> new IllegalArgumentException(String.format("personal access token for '%s' is missing", almSettingDto.getKey())));
160 private Optional<String> getAlmDefaultBranch(String pat, long gitlabProjectId, String gitlabUrl) {
161 Optional<GitLabBranch> almMainBranch = gitlabHttpClient.getBranches(gitlabUrl, pat, gitlabProjectId).stream().filter(GitLabBranch::isDefault).findFirst();
162 return almMainBranch.map(GitLabBranch::getName);
165 private void populateMRSetting(DbSession dbSession, Long gitlabProjectId, ProjectDto projectDto, AlmSettingDto almSettingDto) {
166 dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, new ProjectAlmSettingDto()
167 .setProjectUuid(projectDto.getUuid())
168 .setAlmSettingUuid(almSettingDto.getUuid())
169 .setAlmRepo(gitlabProjectId.toString())
172 almSettingDto.getKey(),
173 projectDto.getName(), projectDto.getKey());
176 private ComponentCreationData createProject(DbSession dbSession, Project gitlabProject, @Nullable String mainBranchName) {
177 boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate();
178 String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(gitlabProject.getPathWithNamespace());
180 return componentUpdater.createWithoutCommit(dbSession, newComponentBuilder()
181 .setKey(uniqueProjectKey)
182 .setName(gitlabProject.getName())
183 .setPrivate(visibility)
184 .setQualifier(PROJECT)
186 userSession.getUuid(), userSession.getLogin(), mainBranchName, s -> {