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.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.BranchDto;
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.component.NewComponent;
43 import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver;
44 import org.sonar.server.project.DefaultBranchNameResolver;
45 import org.sonar.server.project.ProjectDefaultVisibility;
46 import org.sonar.server.user.UserSession;
47 import org.sonarqube.ws.Projects;
49 import static java.util.Optional.ofNullable;
50 import static org.sonar.api.resources.Qualifiers.PROJECT;
51 import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING;
52 import static org.sonar.server.almintegration.ws.ImportHelper.toCreateResponse;
53 import static org.sonar.server.component.NewComponent.newComponentBuilder;
54 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION;
55 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION;
56 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam;
57 import static org.sonar.server.ws.WsUtils.writeProtobuf;
58 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE;
59 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE;
61 public class ImportBitbucketCloudRepoAction implements AlmIntegrationsWsAction {
63 private static final String PARAM_REPO_SLUG = "repositorySlug";
65 private final DbClient dbClient;
66 private final UserSession userSession;
67 private final BitbucketCloudRestClient bitbucketCloudRestClient;
68 private final ProjectDefaultVisibility projectDefaultVisibility;
69 private final ComponentUpdater componentUpdater;
70 private final ImportHelper importHelper;
71 private final ProjectKeyGenerator projectKeyGenerator;
72 private final NewCodeDefinitionResolver newCodeDefinitionResolver;
73 private final DefaultBranchNameResolver defaultBranchNameResolver;
76 public ImportBitbucketCloudRepoAction(DbClient dbClient, UserSession userSession, BitbucketCloudRestClient bitbucketCloudRestClient,
77 ProjectDefaultVisibility projectDefaultVisibility, ComponentUpdater componentUpdater, ImportHelper importHelper,
78 ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver,
79 DefaultBranchNameResolver defaultBranchNameResolver) {
80 this.dbClient = dbClient;
81 this.userSession = userSession;
82 this.bitbucketCloudRestClient = bitbucketCloudRestClient;
83 this.projectDefaultVisibility = projectDefaultVisibility;
84 this.componentUpdater = componentUpdater;
85 this.importHelper = importHelper;
86 this.projectKeyGenerator = projectKeyGenerator;
87 this.newCodeDefinitionResolver = newCodeDefinitionResolver;
88 this.defaultBranchNameResolver = defaultBranchNameResolver;
92 public void define(WebService.NewController context) {
93 WebService.NewAction action = context.createAction("import_bitbucketcloud_repo")
94 .setDescription("Create a SonarQube project with the information from the provided Bitbucket Cloud repository.<br/>" +
95 "Autoconfigure pull request decoration mechanism.<br/>" +
96 "Requires the 'Create Projects' permission")
102 action.createParam(PARAM_REPO_SLUG)
104 .setMaximumLength(200)
105 .setDescription("Bitbucket Cloud repository slug");
107 action.createParam(PARAM_ALM_SETTING)
109 .setMaximumLength(200)
110 .setDescription("DevOps Platform setting key");
112 action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
113 .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
116 action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
117 .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
123 public void handle(Request request, Response response) {
124 Projects.CreateWsResponse createResponse = doHandle(request);
125 writeProtobuf(createResponse, request, response);
128 private Projects.CreateWsResponse doHandle(Request request) {
129 importHelper.checkProvisionProjectPermission();
131 String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE);
132 String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE);
134 String repoSlug = request.mandatoryParam(PARAM_REPO_SLUG);
135 AlmSettingDto almSettingDto = importHelper.getAlmSetting(request);
136 String workspace = ofNullable(almSettingDto.getAppId())
137 .orElseThrow(() -> new IllegalArgumentException(String.format("workspace for alm setting %s is missing", almSettingDto.getKey())));
139 try (DbSession dbSession = dbClient.openSession(false)) {
140 String pat = getPat(dbSession, almSettingDto);
142 Repository repo = bitbucketCloudRestClient.getRepo(pat, workspace, repoSlug);
144 ComponentCreationData componentCreationData = createProject(dbSession, workspace, repo, repo.getMainBranch().getName());
145 ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
146 BranchDto mainBranchDto = Optional.ofNullable(componentCreationData.mainBranchDto()).orElseThrow();
148 populatePRSetting(dbSession, repo, projectDto, almSettingDto);
150 checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
152 if (newCodeDefinitionType != null) {
153 newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), mainBranchDto.getUuid(),
154 Optional.ofNullable(repo.getMainBranch().getName()).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()),
155 newCodeDefinitionType, newCodeDefinitionValue);
158 componentUpdater.commitAndIndex(dbSession, componentCreationData);
160 return toCreateResponse(projectDto);
164 private String getPat(DbSession dbSession, AlmSettingDto almSettingDto) {
165 String userUuid = importHelper.getUserUuid();
167 return dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto)
168 .map(AlmPatDto::getPersonalAccessToken)
169 .orElseThrow(() -> new IllegalArgumentException(String.format("Username and App Password for '%s' is missing",
170 almSettingDto.getKey())));
173 private ComponentCreationData createProject(DbSession dbSession, String workspace, Repository repo, @Nullable String defaultBranchName) {
174 boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate();
175 String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(workspace, repo.getSlug());
176 NewComponent mainBranch = newComponentBuilder()
177 .setKey(uniqueProjectKey)
178 .setName(repo.getName())
179 .setPrivate(visibility)
180 .setQualifier(PROJECT)
182 String userUuid = userSession.isLoggedIn() ? userSession.getUuid() : null;
183 String userLogin = userSession.isLoggedIn() ? userSession.getLogin() : null;
185 return componentUpdater.createWithoutCommit(dbSession, mainBranch, userUuid, userLogin, defaultBranchName);
188 private void populatePRSetting(DbSession dbSession, Repository repo, ProjectDto projectDto, AlmSettingDto almSettingDto) {
189 ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto()
190 .setAlmSettingUuid(almSettingDto.getUuid())
191 // Bitbucket Cloud PR decoration reads almRepo
192 .setAlmRepo(repo.getSlug())
193 .setProjectUuid(projectDto.getUuid())
195 dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(),
196 projectDto.getName(), projectDto.getKey());