]> source.dussan.org Git - sonarqube.git/blob
793fc5b4299d5c2e9577f10217208ac07715674b
[sonarqube.git] /
1 /*
2  * SonarQube
3  * Copyright (C) 2009-2023 SonarSource SA
4  * mailto:info AT sonarsource DOT com
5  *
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.
10  *
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.
15  *
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.
19  */
20 package org.sonar.server.almintegration.ws.bitbucketcloud;
21
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;
47
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;
59
60 public class ImportBitbucketCloudRepoAction implements AlmIntegrationsWsAction {
61
62   private static final String PARAM_REPO_SLUG = "repositorySlug";
63
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;
73
74   @Inject
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;
88   }
89
90   @Override
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")
96       .setPost(true)
97       .setInternal(true)
98       .setSince("9.0")
99       .setHandler(this);
100
101     action.createParam(PARAM_REPO_SLUG)
102       .setRequired(true)
103       .setMaximumLength(200)
104       .setDescription("Bitbucket Cloud repository slug");
105
106     action.createParam(PARAM_ALM_SETTING)
107       .setRequired(true)
108       .setMaximumLength(200)
109       .setDescription("DevOps Platform setting key");
110
111     action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
112       .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
113       .setSince("10.1");
114
115     action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
116       .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
117       .setSince("10.1");
118
119   }
120
121   @Override
122   public void handle(Request request, Response response) {
123     Projects.CreateWsResponse createResponse = doHandle(request);
124     writeProtobuf(createResponse, request, response);
125   }
126
127   private Projects.CreateWsResponse doHandle(Request request) {
128     importHelper.checkProvisionProjectPermission();
129
130     String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE);
131     String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE);
132
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())));
137
138     try (DbSession dbSession = dbClient.openSession(false)) {
139       String pat = getPat(dbSession, almSettingDto);
140
141       Repository repo = bitbucketCloudRestClient.getRepo(pat, workspace, repoSlug);
142
143       ComponentCreationData componentCreationData = createProject(dbSession, workspace, repo, repo.getMainBranch().getName());
144       ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
145
146       populatePRSetting(dbSession, repo, projectDto, almSettingDto);
147
148       checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
149
150       if (newCodeDefinitionType != null) {
151         newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(),
152           Optional.ofNullable(repo.getMainBranch().getName()).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()),
153           newCodeDefinitionType, newCodeDefinitionValue);
154       }
155
156       componentUpdater.commitAndIndex(dbSession, componentCreationData);
157
158       return toCreateResponse(projectDto);
159     }
160   }
161
162   private String getPat(DbSession dbSession, AlmSettingDto almSettingDto) {
163     String userUuid = importHelper.getUserUuid();
164
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())));
169   }
170
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)
179       .build();
180     String userUuid = userSession.isLoggedIn() ? userSession.getUuid() : null;
181     String userLogin = userSession.isLoggedIn() ? userSession.getLogin() : null;
182
183     return componentUpdater.createWithoutCommit(dbSession, mainBranch, userUuid, userLogin, defaultBranchName);
184   }
185
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())
192       .setMonorepo(false);
193     dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(),
194       projectDto.getName(), projectDto.getKey());
195   }
196
197 }