3 * Copyright (C) 2009-2022 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 org.sonar.alm.client.gitlab.GitLabBranch;
25 import org.sonar.alm.client.gitlab.GitlabHttpClient;
26 import org.sonar.alm.client.gitlab.Project;
27 import org.sonar.api.server.ws.Request;
28 import org.sonar.api.server.ws.Response;
29 import org.sonar.api.server.ws.WebService;
30 import org.sonar.db.DbClient;
31 import org.sonar.db.DbSession;
32 import org.sonar.db.alm.pat.AlmPatDto;
33 import org.sonar.db.alm.setting.AlmSettingDto;
34 import org.sonar.db.alm.setting.ProjectAlmSettingDto;
35 import org.sonar.db.component.ComponentDto;
36 import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction;
37 import org.sonar.server.almintegration.ws.ImportHelper;
38 import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
39 import org.sonar.server.component.ComponentUpdater;
40 import org.sonar.server.project.ProjectDefaultVisibility;
41 import org.sonar.server.user.UserSession;
42 import org.sonarqube.ws.Projects.CreateWsResponse;
44 import static java.util.Objects.requireNonNull;
45 import static org.sonar.api.resources.Qualifiers.PROJECT;
46 import static org.sonar.server.component.NewComponent.newComponentBuilder;
47 import static org.sonar.server.ws.WsUtils.writeProtobuf;
49 public class ImportGitLabProjectAction implements AlmIntegrationsWsAction {
51 public static final String PARAM_GITLAB_PROJECT_ID = "gitlabProjectId";
53 private final DbClient dbClient;
54 private final UserSession userSession;
55 private final ProjectDefaultVisibility projectDefaultVisibility;
56 private final GitlabHttpClient gitlabHttpClient;
57 private final ComponentUpdater componentUpdater;
58 private final ImportHelper importHelper;
59 private final ProjectKeyGenerator projectKeyGenerator;
61 public ImportGitLabProjectAction(DbClient dbClient, UserSession userSession,
62 ProjectDefaultVisibility projectDefaultVisibility, GitlabHttpClient gitlabHttpClient,
63 ComponentUpdater componentUpdater, ImportHelper importHelper, ProjectKeyGenerator projectKeyGenerator) {
64 this.dbClient = dbClient;
65 this.userSession = userSession;
66 this.projectDefaultVisibility = projectDefaultVisibility;
67 this.gitlabHttpClient = gitlabHttpClient;
68 this.componentUpdater = componentUpdater;
69 this.importHelper = importHelper;
70 this.projectKeyGenerator = projectKeyGenerator;
74 public void define(WebService.NewController context) {
75 WebService.NewAction action = context.createAction("import_gitlab_project")
76 .setDescription("Import a GitLab project to SonarQube, creating a new project and configuring MR decoration<br/>" +
77 "Requires the 'Create Projects' permission")
82 action.createParam(ImportHelper.PARAM_ALM_SETTING)
84 .setDescription("ALM setting key");
85 action.createParam(PARAM_GITLAB_PROJECT_ID)
87 .setDescription("GitLab project ID");
91 public void handle(Request request, Response response) throws Exception {
92 CreateWsResponse createResponse = doHandle(request);
93 writeProtobuf(createResponse, request, response);
96 private CreateWsResponse doHandle(Request request) {
97 importHelper.checkProvisionProjectPermission();
98 AlmSettingDto almSettingDto = importHelper.getAlmSetting(request);
99 String userUuid = importHelper.getUserUuid();
100 try (DbSession dbSession = dbClient.openSession(false)) {
101 Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
102 String pat = almPatDto.map(AlmPatDto::getPersonalAccessToken)
103 .orElseThrow(() -> new IllegalArgumentException(String.format("personal access token for '%s' is missing", almSettingDto.getKey())));
105 long gitlabProjectId = request.mandatoryParamAsLong(PARAM_GITLAB_PROJECT_ID);
107 String gitlabUrl = requireNonNull(almSettingDto.getUrl(), "ALM gitlabUrl cannot be null");
108 Project gitlabProject = gitlabHttpClient.getProject(gitlabUrl, pat, gitlabProjectId);
110 Optional<String> almMainBranchName = getAlmDefaultBranch(pat, gitlabProjectId, gitlabUrl);
111 ComponentDto componentDto = createProject(dbSession, gitlabProject, almMainBranchName.orElse(null));
112 populateMRSetting(dbSession, gitlabProjectId, componentDto, almSettingDto);
113 componentUpdater.commitAndIndex(dbSession, componentDto);
115 return ImportHelper.toCreateResponse(componentDto);
119 private Optional<String> getAlmDefaultBranch(String pat, long gitlabProjectId, String gitlabUrl) {
120 Optional<GitLabBranch> almMainBranch = gitlabHttpClient.getBranches(gitlabUrl, pat, gitlabProjectId).stream().filter(GitLabBranch::isDefault).findFirst();
121 return almMainBranch.map(GitLabBranch::getName);
124 private void populateMRSetting(DbSession dbSession, Long gitlabProjectId, ComponentDto componentDto, AlmSettingDto almSettingDto) {
125 dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, new ProjectAlmSettingDto()
126 .setProjectUuid(componentDto.projectUuid())
127 .setAlmSettingUuid(almSettingDto.getUuid())
128 .setAlmRepo(gitlabProjectId.toString())
131 almSettingDto.getKey(),
132 componentDto.name(), componentDto.getKey());
135 private ComponentDto createProject(DbSession dbSession, Project gitlabProject, @Nullable String mainBranchName) {
136 boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate();
137 String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(gitlabProject.getPathWithNamespace());
139 return componentUpdater.createWithoutCommit(dbSession, newComponentBuilder()
140 .setKey(uniqueProjectKey)
141 .setName(gitlabProject.getName())
142 .setPrivate(visibility)
143 .setQualifier(PROJECT)
145 userSession.getUuid(), userSession.getLogin(), mainBranchName, s -> {