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