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.Objects;
23 import java.util.Optional;
24 import javax.inject.Inject;
25 import org.sonar.alm.client.github.GithubApplicationClient;
26 import org.sonar.alm.client.github.GithubApplicationClient.Repository;
27 import org.sonar.alm.client.github.GithubApplicationClientImpl;
28 import org.sonar.alm.client.github.security.AccessToken;
29 import org.sonar.alm.client.github.security.UserAccessToken;
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.auth.github.GitHubSettings;
34 import org.sonar.db.DbClient;
35 import org.sonar.db.DbSession;
36 import org.sonar.db.alm.pat.AlmPatDto;
37 import org.sonar.db.alm.setting.AlmSettingDto;
38 import org.sonar.db.alm.setting.ProjectAlmSettingDto;
39 import org.sonar.db.component.BranchDto;
40 import org.sonar.db.project.ProjectDto;
41 import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction;
42 import org.sonar.server.almintegration.ws.ImportHelper;
43 import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
44 import org.sonar.server.component.ComponentCreationData;
45 import org.sonar.server.component.ComponentUpdater;
46 import org.sonar.server.component.NewComponent;
47 import org.sonar.server.exceptions.NotFoundException;
48 import org.sonar.server.management.ManagedProjectService;
49 import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver;
50 import org.sonar.server.project.DefaultBranchNameResolver;
51 import org.sonar.server.project.ProjectDefaultVisibility;
52 import org.sonar.server.user.UserSession;
53 import org.sonarqube.ws.Projects;
55 import static java.util.Objects.requireNonNull;
56 import static org.sonar.api.resources.Qualifiers.PROJECT;
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;
67 public class ImportGithubProjectAction implements AlmIntegrationsWsAction {
69 public static final String PARAM_ORGANIZATION = "organization";
70 public static final String PARAM_REPOSITORY_KEY = "repositoryKey";
72 private final DbClient dbClient;
74 private final ManagedProjectService managedProjectService;
75 private final UserSession userSession;
76 private final ProjectDefaultVisibility projectDefaultVisibility;
77 private final GithubApplicationClient githubApplicationClient;
78 private final ComponentUpdater componentUpdater;
79 private final ImportHelper importHelper;
80 private final ProjectKeyGenerator projectKeyGenerator;
82 private final NewCodeDefinitionResolver newCodeDefinitionResolver;
84 private final DefaultBranchNameResolver defaultBranchNameResolver;
86 private final GitHubSettings gitHubSettings;
89 public ImportGithubProjectAction(DbClient dbClient, ManagedProjectService managedProjectService, UserSession userSession, ProjectDefaultVisibility projectDefaultVisibility,
90 GithubApplicationClientImpl githubApplicationClient, ComponentUpdater componentUpdater, ImportHelper importHelper,
91 ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver,
92 DefaultBranchNameResolver defaultBranchNameResolver, GitHubSettings gitHubSettings) {
93 this.dbClient = dbClient;
94 this.managedProjectService = managedProjectService;
95 this.userSession = userSession;
96 this.projectDefaultVisibility = projectDefaultVisibility;
97 this.githubApplicationClient = githubApplicationClient;
98 this.componentUpdater = componentUpdater;
99 this.importHelper = importHelper;
100 this.projectKeyGenerator = projectKeyGenerator;
101 this.newCodeDefinitionResolver = newCodeDefinitionResolver;
102 this.defaultBranchNameResolver = defaultBranchNameResolver;
103 this.gitHubSettings = gitHubSettings;
107 public void define(WebService.NewController context) {
108 WebService.NewAction action = context.createAction("import_github_project")
109 .setDescription("Create a SonarQube project with the information from the provided GitHub repository.<br/>" +
110 "Autoconfigure pull request decoration mechanism.<br/>" +
111 "Requires the 'Create Projects' permission")
117 action.createParam(PARAM_ALM_SETTING)
119 .setMaximumLength(200)
120 .setDescription("DevOps Platform setting key");
122 action.createParam(PARAM_ORGANIZATION)
124 .setMaximumLength(200)
125 .setDescription("GitHub organization");
127 action.createParam(PARAM_REPOSITORY_KEY)
129 .setMaximumLength(256)
130 .setDescription("GitHub repository key");
132 action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
133 .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
136 action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
137 .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
142 public void handle(Request request, Response response) {
143 Projects.CreateWsResponse createResponse = doHandle(request);
144 writeProtobuf(createResponse, request, response);
147 private Projects.CreateWsResponse doHandle(Request request) {
148 importHelper.checkProvisionProjectPermission();
149 AlmSettingDto almSettingDto = importHelper.getAlmSetting(request);
151 String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE);
152 String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE);
153 try (DbSession dbSession = dbClient.openSession(false)) {
155 AccessToken accessToken = getAccessToken(dbSession, almSettingDto);
157 String githubOrganization = request.mandatoryParam(PARAM_ORGANIZATION);
158 String repositoryKey = request.mandatoryParam(PARAM_REPOSITORY_KEY);
160 String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null");
161 Repository repository = githubApplicationClient.getRepository(url, accessToken, githubOrganization, repositoryKey)
162 .orElseThrow(() -> new NotFoundException(String.format("GitHub repository '%s' not found", repositoryKey)));
164 ComponentCreationData componentCreationData = createProject(dbSession, repository, repository.getDefaultBranch());
165 ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
166 BranchDto mainBranchDto = Optional.ofNullable(componentCreationData.mainBranchDto()).orElseThrow();
168 populatePRSetting(dbSession, repository, projectDto, almSettingDto);
170 checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
172 if (newCodeDefinitionType != null) {
173 newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), mainBranchDto.getUuid(),
174 Optional.ofNullable(repository.getDefaultBranch()).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()),
175 newCodeDefinitionType, newCodeDefinitionValue);
178 componentUpdater.commitAndIndex(dbSession, componentCreationData);
180 String userUuid = Objects.requireNonNull(userSession.getUuid());
181 managedProjectService.queuePermissionSyncTask(userUuid, mainBranchDto.getUuid(), projectDto.getUuid());
183 return toCreateResponse(projectDto);
187 private AccessToken getAccessToken(DbSession dbSession, AlmSettingDto almSettingDto) {
188 String userUuid = importHelper.getUserUuid();
189 return dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto)
190 .map(AlmPatDto::getPersonalAccessToken)
191 .map(UserAccessToken::new)
192 .orElseThrow(() -> new IllegalArgumentException("No personal access token found"));
195 private ComponentCreationData createProject(DbSession dbSession, Repository repo, String mainBranchName) {
196 boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate();
197 String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(repo.getFullName());
198 NewComponent projectComponent = newComponentBuilder()
199 .setKey(uniqueProjectKey)
200 .setName(repo.getName())
201 .setPrivate(visibility)
202 .setQualifier(PROJECT)
204 return componentUpdater.createWithoutCommit(
207 userSession.getUuid(),
208 userSession.getLogin(),
210 gitHubSettings.isProvisioningEnabled());
213 private void populatePRSetting(DbSession dbSession, Repository repo, ProjectDto projectDto, AlmSettingDto almSettingDto) {
214 ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto()
215 .setAlmSettingUuid(almSettingDto.getUuid())
216 .setAlmRepo(repo.getFullName())
218 .setProjectUuid(projectDto.getUuid())
219 .setSummaryCommentEnabled(true)
221 dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(),
222 projectDto.getName(), projectDto.getKey());