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