]> source.dussan.org Git - sonarqube.git/blob
68641432c544f981f19b639762263e7814842ae9
[sonarqube.git] /
1 /*
2  * SonarQube
3  * Copyright (C) 2009-2024 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.bitbucketserver;
21
22 import java.util.Optional;
23 import javax.annotation.Nullable;
24 import javax.inject.Inject;
25 import org.sonar.alm.client.bitbucketserver.BitbucketServerRestClient;
26 import org.sonar.alm.client.bitbucketserver.Branch;
27 import org.sonar.alm.client.bitbucketserver.BranchesList;
28 import org.sonar.alm.client.bitbucketserver.Repository;
29 import org.sonar.api.server.ws.Change;
30 import org.sonar.api.server.ws.Request;
31 import org.sonar.api.server.ws.Response;
32 import org.sonar.api.server.ws.WebService;
33 import org.sonar.db.DbClient;
34 import org.sonar.db.DbSession;
35 import org.sonar.db.alm.pat.AlmPatDto;
36 import org.sonar.db.alm.setting.ALM;
37 import org.sonar.db.alm.setting.AlmSettingDto;
38 import org.sonar.db.alm.setting.ProjectAlmSettingDto;
39 import org.sonar.db.component.BranchDto;
40 import org.sonar.db.project.ProjectDto;
41 import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction;
42 import org.sonar.server.almintegration.ws.ImportHelper;
43 import org.sonar.server.common.almintegration.ProjectKeyGenerator;
44 import org.sonar.server.common.component.ComponentCreationParameters;
45 import org.sonar.server.common.component.ComponentUpdater;
46 import org.sonar.server.common.component.NewComponent;
47 import org.sonar.server.common.newcodeperiod.NewCodeDefinitionResolver;
48 import org.sonar.server.component.ComponentCreationData;
49 import org.sonar.server.project.DefaultBranchNameResolver;
50 import org.sonar.server.project.ProjectDefaultVisibility;
51 import org.sonar.server.user.UserSession;
52 import org.sonarqube.ws.Projects;
53
54 import static java.util.Objects.requireNonNull;
55 import static org.sonar.api.resources.Qualifiers.PROJECT;
56 import static org.sonar.db.project.CreationMethod.getCreationMethod;
57 import static org.sonar.db.project.CreationMethod.Category.ALM_IMPORT;
58 import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING;
59 import static org.sonar.server.almintegration.ws.ImportHelper.toCreateResponse;
60 import static org.sonar.server.common.component.NewComponent.newComponentBuilder;
61 import static org.sonar.server.common.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION;
62 import static org.sonar.server.common.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION;
63 import static org.sonar.server.common.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam;
64 import static org.sonar.server.ws.WsUtils.writeProtobuf;
65 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE;
66 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE;
67
68 public class ImportBitbucketServerProjectAction implements AlmIntegrationsWsAction {
69
70   private static final String PARAM_PROJECT_KEY = "projectKey";
71   private static final String PARAM_REPO_SLUG = "repositorySlug";
72
73   private final DbClient dbClient;
74   private final UserSession userSession;
75   private final BitbucketServerRestClient bitbucketServerRestClient;
76   private final ProjectDefaultVisibility projectDefaultVisibility;
77   private final ComponentUpdater componentUpdater;
78   private final ImportHelper importHelper;
79   private final ProjectKeyGenerator projectKeyGenerator;
80
81   private final NewCodeDefinitionResolver newCodeDefinitionResolver;
82
83   private final DefaultBranchNameResolver defaultBranchNameResolver;
84
85   @Inject
86   public ImportBitbucketServerProjectAction(DbClient dbClient, UserSession userSession, BitbucketServerRestClient bitbucketServerRestClient,
87     ProjectDefaultVisibility projectDefaultVisibility, ComponentUpdater componentUpdater,
88     ImportHelper importHelper, ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver,
89     DefaultBranchNameResolver defaultBranchNameResolver) {
90     this.dbClient = dbClient;
91     this.userSession = userSession;
92     this.bitbucketServerRestClient = bitbucketServerRestClient;
93     this.projectDefaultVisibility = projectDefaultVisibility;
94     this.componentUpdater = componentUpdater;
95     this.importHelper = importHelper;
96     this.projectKeyGenerator = projectKeyGenerator;
97     this.newCodeDefinitionResolver = newCodeDefinitionResolver;
98     this.defaultBranchNameResolver = defaultBranchNameResolver;
99   }
100
101   @Override
102   public void define(WebService.NewController context) {
103     WebService.NewAction action = context.createAction("import_bitbucketserver_project")
104       .setDescription("Create a SonarQube project with the information from the provided BitbucketServer project.<br/>" +
105                       "Autoconfigure pull request decoration mechanism.<br/>" +
106                       "Requires the 'Create Projects' permission")
107       .setPost(true)
108       .setSince("8.2")
109       .setHandler(this)
110       .setChangelog(
111         new Change("10.5", "This endpoint is deprecated, please use its API v2 version /api/v2/dop-translation/bound-projects"),
112         new Change("10.3", String.format("Parameter %s becomes optional if you have only one configuration for BitBucket Server", PARAM_ALM_SETTING)),
113         new Change("10.3", "Endpoint visibility change from internal to public"))
114       .setDeprecatedSince("10.5");
115
116     action.createParam(PARAM_ALM_SETTING)
117       .setMaximumLength(200)
118       .setDescription("DevOps Platform configuration key. This parameter is optional if you have only one BitBucket Server integration.");
119
120     action.createParam(PARAM_PROJECT_KEY)
121       .setRequired(true)
122       .setMaximumLength(200)
123       .setDescription("BitbucketServer project key");
124
125     action.createParam(PARAM_REPO_SLUG)
126       .setRequired(true)
127       .setMaximumLength(200)
128       .setDescription("BitbucketServer repository slug");
129
130
131     action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
132       .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
133       .setSince("10.1");
134
135     action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
136       .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
137       .setSince("10.1");
138   }
139
140   @Override
141   public void handle(Request request, Response response) {
142     Projects.CreateWsResponse createResponse = doHandle(request);
143     writeProtobuf(createResponse, request, response);
144   }
145
146   private Projects.CreateWsResponse doHandle(Request request) {
147     importHelper.checkProvisionProjectPermission();
148     AlmSettingDto almSettingDto = importHelper.getAlmSettingDtoForAlm(request, ALM.BITBUCKET);
149
150     String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE);
151     String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE);
152     try (DbSession dbSession = dbClient.openSession(false)) {
153
154       String pat = getPat(dbSession, almSettingDto);
155
156       String projectKey = request.mandatoryParam(PARAM_PROJECT_KEY);
157       String repoSlug = request.mandatoryParam(PARAM_REPO_SLUG);
158
159       String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null");
160       Repository repo = bitbucketServerRestClient.getRepo(url, pat, projectKey, repoSlug);
161
162       String defaultBranchName = getDefaultBranchName(pat, projectKey, repoSlug, url);
163
164       ComponentCreationData componentCreationData = createProject(dbSession, repo, defaultBranchName);
165       ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
166       BranchDto mainBranchDto = Optional.ofNullable(componentCreationData.mainBranchDto()).orElseThrow();
167
168       populatePRSetting(dbSession, repo, projectDto, almSettingDto);
169
170       checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
171
172       if (newCodeDefinitionType != null) {
173         newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), mainBranchDto.getUuid(),
174           Optional.ofNullable(defaultBranchName).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()),
175           newCodeDefinitionType, newCodeDefinitionValue);
176       }
177
178       componentUpdater.commitAndIndex(dbSession, componentCreationData);
179
180       return toCreateResponse(projectDto);
181     }
182   }
183
184   private String getPat(DbSession dbSession, AlmSettingDto almSettingDto) {
185     String userUuid = importHelper.getUserUuid();
186
187     Optional<AlmPatDto> almPatDot = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
188     return almPatDot.map(AlmPatDto::getPersonalAccessToken)
189       .orElseThrow(() -> new IllegalArgumentException(String.format("personal access token for '%s' is missing",
190         almSettingDto.getKey())));
191   }
192
193   private String getDefaultBranchName(String pat, String projectKey, String repoSlug, String url) {
194     BranchesList branches = bitbucketServerRestClient.getBranches(url, pat, projectKey, repoSlug);
195     Optional<Branch> defaultBranch = branches.findDefaultBranch();
196     return defaultBranch.map(Branch::getName).orElse(null);
197   }
198
199   private ComponentCreationData createProject(DbSession dbSession, Repository repo, @Nullable String defaultBranchName) {
200     boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate();
201     String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(repo.getProject().getKey(), repo.getSlug());
202     NewComponent newProject = newComponentBuilder()
203       .setKey(uniqueProjectKey)
204       .setName(repo.getName())
205       .setPrivate(visibility)
206       .setQualifier(PROJECT)
207       .build();
208     ComponentCreationParameters componentCreationParameters = ComponentCreationParameters.builder()
209       .newComponent(newProject)
210       .userUuid(userSession.getUuid())
211       .userLogin(userSession.getLogin())
212       .mainBranchName(defaultBranchName)
213       .creationMethod(getCreationMethod(ALM_IMPORT, userSession.isAuthenticatedBrowserSession()))
214       .build();
215     return componentUpdater.createWithoutCommit(dbSession, componentCreationParameters);
216   }
217
218   private void populatePRSetting(DbSession dbSession, Repository repo, ProjectDto componentDto, AlmSettingDto almSettingDto) {
219     ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto()
220       .setAlmSettingUuid(almSettingDto.getUuid())
221       .setAlmRepo(repo.getProject().getKey())
222       .setAlmSlug(repo.getSlug())
223       .setProjectUuid(componentDto.getUuid())
224       .setMonorepo(false);
225     dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(),
226       componentDto.getName(), componentDto.getKey());
227   }
228
229 }