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