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