3 * Copyright (C) 2009-2023 SonarSource SA
4 * mailto:info AT sonarsource DOT com
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.
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.
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.
20 package org.sonar.server.almintegration.ws.github;
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;
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;
62 public class ImportGithubProjectAction implements AlmIntegrationsWsAction {
64 public static final String PARAM_ORGANIZATION = "organization";
65 public static final String PARAM_REPOSITORY_KEY = "repositoryKey";
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;
75 private final NewCodeDefinitionResolver newCodeDefinitionResolver;
77 private final DefaultBranchNameResolver defaultBranchNameResolver;
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;
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")
106 action.createParam(PARAM_ALM_SETTING)
108 .setMaximumLength(200)
109 .setDescription("DevOps Platform setting key");
111 action.createParam(PARAM_ORGANIZATION)
113 .setMaximumLength(200)
114 .setDescription("GitHub organization");
116 action.createParam(PARAM_REPOSITORY_KEY)
118 .setMaximumLength(256)
119 .setDescription("GitHub repository key");
121 action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
122 .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
125 action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
126 .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
131 public void handle(Request request, Response response) {
132 Projects.CreateWsResponse createResponse = doHandle(request);
133 writeProtobuf(createResponse, request, response);
136 private Projects.CreateWsResponse doHandle(Request request) {
137 importHelper.checkProvisionProjectPermission();
138 AlmSettingDto almSettingDto = importHelper.getAlmSetting(request);
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)) {
145 AccessToken accessToken = getAccessToken(dbSession, almSettingDto);
147 String githubOrganization = request.mandatoryParam(PARAM_ORGANIZATION);
148 String repositoryKey = request.mandatoryParam(PARAM_REPOSITORY_KEY);
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)));
154 ComponentCreationData componentCreationData = createProject(dbSession, repository, repository.getDefaultBranch());
155 ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
157 populatePRSetting(dbSession, repository, projectDto, almSettingDto);
159 checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
161 if (newCodeDefinitionType != null) {
162 newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(),
163 Optional.ofNullable(repository.getDefaultBranch()).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()),
164 newCodeDefinitionType, newCodeDefinitionValue);
167 componentUpdater.commitAndIndex(dbSession, componentCreationData.mainBranchComponent());
169 return toCreateResponse(projectDto);
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"));
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)
190 userSession.getUuid(), userSession.getLogin(), mainBranchName, s -> {
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())
199 .setProjectUuid(projectDto.getUuid())
200 .setSummaryCommentEnabled(true)
202 dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(),
203 projectDto.getName(), projectDto.getKey());