]> source.dussan.org Git - sonarqube.git/blob
56fbda880083bbecf8201be3b7ac4eccbc5a1e9e
[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.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.exceptions.NotFoundException;
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 ImportGithubProjectAction implements AlmIntegrationsWsAction {
63
64   public static final String PARAM_ORGANIZATION = "organization";
65   public static final String PARAM_REPOSITORY_KEY = "repositoryKey";
66
67   private final DbClient dbClient;
68   private final UserSession userSession;
69   private final ProjectDefaultVisibility projectDefaultVisibility;
70   private final GithubApplicationClient githubApplicationClient;
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 ImportGithubProjectAction(DbClient dbClient, UserSession userSession, ProjectDefaultVisibility projectDefaultVisibility,
81     GithubApplicationClientImpl githubApplicationClient, ComponentUpdater componentUpdater, ImportHelper importHelper,
82     ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver,
83     DefaultBranchNameResolver defaultBranchNameResolver) {
84     this.dbClient = dbClient;
85     this.userSession = userSession;
86     this.projectDefaultVisibility = projectDefaultVisibility;
87     this.githubApplicationClient = githubApplicationClient;
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_github_project")
98       .setDescription("Create a SonarQube project with the information from the provided GitHub repository.<br/>" +
99         "Autoconfigure pull request decoration mechanism.<br/>" +
100         "Requires the 'Create Projects' permission")
101       .setPost(true)
102       .setInternal(true)
103       .setSince("8.4")
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_ORGANIZATION)
112       .setRequired(true)
113       .setMaximumLength(200)
114       .setDescription("GitHub organization");
115
116     action.createParam(PARAM_REPOSITORY_KEY)
117       .setRequired(true)
118       .setMaximumLength(256)
119       .setDescription("GitHub repository key");
120
121     action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
122       .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
123       .setSince("10.1");
124
125     action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
126       .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
127       .setSince("10.1");
128   }
129
130   @Override
131   public void handle(Request request, Response response) {
132     Projects.CreateWsResponse createResponse = doHandle(request);
133     writeProtobuf(createResponse, request, response);
134   }
135
136   private Projects.CreateWsResponse doHandle(Request request) {
137     importHelper.checkProvisionProjectPermission();
138     AlmSettingDto almSettingDto = importHelper.getAlmSetting(request);
139
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       AccessToken accessToken = getAccessToken(dbSession, almSettingDto);
146
147       String githubOrganization = request.mandatoryParam(PARAM_ORGANIZATION);
148       String repositoryKey = request.mandatoryParam(PARAM_REPOSITORY_KEY);
149
150       String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null");
151       Repository repository = githubApplicationClient.getRepository(url, accessToken, githubOrganization, repositoryKey)
152         .orElseThrow(() -> new NotFoundException(String.format("GitHub repository '%s' not found", repositoryKey)));
153
154       ComponentCreationData componentCreationData = createProject(dbSession, repository, repository.getDefaultBranch());
155       ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
156
157       populatePRSetting(dbSession, repository, projectDto, almSettingDto);
158
159       checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
160
161       if (newCodeDefinitionType != null) {
162         newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(),
163           Optional.ofNullable(repository.getDefaultBranch()).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()),
164           newCodeDefinitionType, newCodeDefinitionValue);
165       }
166
167       componentUpdater.commitAndIndex(dbSession, componentCreationData.mainBranchComponent());
168
169       return toCreateResponse(projectDto);
170     }
171   }
172
173   private AccessToken getAccessToken(DbSession dbSession, AlmSettingDto almSettingDto) {
174     String userUuid = importHelper.getUserUuid();
175     return dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto)
176       .map(AlmPatDto::getPersonalAccessToken)
177       .map(UserAccessToken::new)
178       .orElseThrow(() -> new IllegalArgumentException("No personal access token found"));
179   }
180
181   private ComponentCreationData createProject(DbSession dbSession, Repository repo, String mainBranchName) {
182     boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate();
183     String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(repo.getFullName());
184     return componentUpdater.createWithoutCommit(dbSession, newComponentBuilder()
185         .setKey(uniqueProjectKey)
186         .setName(repo.getName())
187         .setPrivate(visibility)
188         .setQualifier(PROJECT)
189         .build(),
190       userSession.getUuid(), userSession.getLogin(), mainBranchName, s -> {
191       });
192   }
193
194   private void populatePRSetting(DbSession dbSession, Repository repo, ProjectDto projectDto, AlmSettingDto almSettingDto) {
195     ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto()
196       .setAlmSettingUuid(almSettingDto.getUuid())
197       .setAlmRepo(repo.getFullName())
198       .setAlmSlug(null)
199       .setProjectUuid(projectDto.getUuid())
200       .setSummaryCommentEnabled(true)
201       .setMonorepo(false);
202     dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(),
203       projectDto.getName(), projectDto.getKey());
204   }
205 }