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.bitbucketcloud;
22 import java.util.Optional;
23 import javax.annotation.Nullable;
24 import javax.inject.Inject;
25 import org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClient;
26 import org.sonar.alm.client.bitbucket.bitbucketcloud.Repository;
27 import org.sonar.api.server.ws.Change;
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.component.BranchDto;
37 import org.sonar.db.project.ProjectDto;
38 import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction;
39 import org.sonar.server.almintegration.ws.ImportHelper;
40 import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
41 import org.sonar.server.component.ComponentCreationData;
42 import org.sonar.server.component.ComponentCreationParameters;
43 import org.sonar.server.component.ComponentUpdater;
44 import org.sonar.server.component.NewComponent;
45 import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver;
46 import org.sonar.server.project.DefaultBranchNameResolver;
47 import org.sonar.server.project.ProjectDefaultVisibility;
48 import org.sonar.server.user.UserSession;
49 import org.sonarqube.ws.Projects;
51 import static java.util.Optional.ofNullable;
52 import static org.sonar.api.resources.Qualifiers.PROJECT;
53 import static org.sonar.db.project.CreationMethod.Category.ALM_IMPORT;
54 import static org.sonar.db.project.CreationMethod.getCreationMethod;
55 import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING;
56 import static org.sonar.server.almintegration.ws.ImportHelper.toCreateResponse;
57 import static org.sonar.server.component.NewComponent.newComponentBuilder;
58 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION;
59 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION;
60 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam;
61 import static org.sonar.server.ws.WsUtils.writeProtobuf;
62 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE;
63 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE;
65 public class ImportBitbucketCloudRepoAction implements AlmIntegrationsWsAction {
67 private static final String PARAM_REPO_SLUG = "repositorySlug";
69 private final DbClient dbClient;
70 private final UserSession userSession;
71 private final BitbucketCloudRestClient bitbucketCloudRestClient;
72 private final ProjectDefaultVisibility projectDefaultVisibility;
73 private final ComponentUpdater componentUpdater;
74 private final ImportHelper importHelper;
75 private final ProjectKeyGenerator projectKeyGenerator;
76 private final NewCodeDefinitionResolver newCodeDefinitionResolver;
77 private final DefaultBranchNameResolver defaultBranchNameResolver;
80 public ImportBitbucketCloudRepoAction(DbClient dbClient, UserSession userSession, BitbucketCloudRestClient bitbucketCloudRestClient,
81 ProjectDefaultVisibility projectDefaultVisibility, ComponentUpdater componentUpdater, ImportHelper importHelper,
82 ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver,
83 DefaultBranchNameResolver defaultBranchNameResolver) {
84 this.dbClient = dbClient;
85 this.userSession = userSession;
86 this.bitbucketCloudRestClient = bitbucketCloudRestClient;
87 this.projectDefaultVisibility = projectDefaultVisibility;
88 this.componentUpdater = componentUpdater;
89 this.importHelper = importHelper;
90 this.projectKeyGenerator = projectKeyGenerator;
91 this.newCodeDefinitionResolver = newCodeDefinitionResolver;
92 this.defaultBranchNameResolver = defaultBranchNameResolver;
96 public void define(WebService.NewController context) {
97 WebService.NewAction action = context.createAction("import_bitbucketcloud_repo")
98 .setDescription("Create a SonarQube project with the information from the provided Bitbucket Cloud repository.<br/>" +
99 "Autoconfigure pull request decoration mechanism.<br/>" +
100 "Requires the 'Create Projects' permission")
105 new Change("10.3", "Endpoint visibility change from internal to public"));
107 action.createParam(PARAM_REPO_SLUG)
109 .setMaximumLength(200)
110 .setDescription("Bitbucket Cloud repository slug");
112 action.createParam(PARAM_ALM_SETTING)
114 .setMaximumLength(200)
115 .setDescription("DevOps Platform setting key");
117 action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
118 .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
121 action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
122 .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
128 public void handle(Request request, Response response) {
129 Projects.CreateWsResponse createResponse = doHandle(request);
130 writeProtobuf(createResponse, request, response);
133 private Projects.CreateWsResponse doHandle(Request request) {
134 importHelper.checkProvisionProjectPermission();
136 String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE);
137 String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE);
139 String repoSlug = request.mandatoryParam(PARAM_REPO_SLUG);
140 AlmSettingDto almSettingDto = importHelper.getAlmSetting(request);
141 String workspace = ofNullable(almSettingDto.getAppId())
142 .orElseThrow(() -> new IllegalArgumentException(String.format("workspace for alm setting %s is missing", almSettingDto.getKey())));
144 try (DbSession dbSession = dbClient.openSession(false)) {
145 String pat = getPat(dbSession, almSettingDto);
147 Repository repo = bitbucketCloudRestClient.getRepo(pat, workspace, repoSlug);
149 ComponentCreationData componentCreationData = createProject(dbSession, workspace, repo, repo.getMainBranch().getName());
150 ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
151 BranchDto mainBranchDto = Optional.ofNullable(componentCreationData.mainBranchDto()).orElseThrow();
153 populatePRSetting(dbSession, repo, projectDto, almSettingDto);
155 checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
157 if (newCodeDefinitionType != null) {
158 newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), mainBranchDto.getUuid(),
159 Optional.ofNullable(repo.getMainBranch().getName()).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()),
160 newCodeDefinitionType, newCodeDefinitionValue);
163 componentUpdater.commitAndIndex(dbSession, componentCreationData);
165 return toCreateResponse(projectDto);
169 private String getPat(DbSession dbSession, AlmSettingDto almSettingDto) {
170 String userUuid = importHelper.getUserUuid();
172 return dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto)
173 .map(AlmPatDto::getPersonalAccessToken)
174 .orElseThrow(() -> new IllegalArgumentException(String.format("Username and App Password for '%s' is missing",
175 almSettingDto.getKey())));
178 private ComponentCreationData createProject(DbSession dbSession, String workspace, Repository repo, @Nullable String defaultBranchName) {
179 boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate();
180 String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(workspace, repo.getSlug());
181 NewComponent newProject = newComponentBuilder()
182 .setKey(uniqueProjectKey)
183 .setName(repo.getName())
184 .setPrivate(visibility)
185 .setQualifier(PROJECT)
187 ComponentCreationParameters componentCreationParameters = ComponentCreationParameters.builder()
188 .newComponent(newProject)
189 .userUuid(userSession.getUuid())
190 .userLogin(userSession.getLogin())
191 .mainBranchName(defaultBranchName)
192 .creationMethod(getCreationMethod(ALM_IMPORT, userSession.isAuthenticatedBrowserSession()))
194 return componentUpdater.createWithoutCommit(dbSession, componentCreationParameters);
197 private void populatePRSetting(DbSession dbSession, Repository repo, ProjectDto projectDto, AlmSettingDto almSettingDto) {
198 ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto()
199 .setAlmSettingUuid(almSettingDto.getUuid())
200 // Bitbucket Cloud PR decoration reads almRepo
201 .setAlmRepo(repo.getSlug())
202 .setProjectUuid(projectDto.getUuid())
204 dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(),
205 projectDto.getName(), projectDto.getKey());