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.Change;
31 import org.sonar.api.server.ws.Request;
32 import org.sonar.api.server.ws.Response;
33 import org.sonar.api.server.ws.WebService;
34 import org.sonar.auth.github.GitHubSettings;
35 import org.sonar.db.DbClient;
36 import org.sonar.db.DbSession;
37 import org.sonar.db.alm.pat.AlmPatDto;
38 import org.sonar.db.alm.setting.AlmSettingDto;
39 import org.sonar.db.alm.setting.ProjectAlmSettingDto;
40 import org.sonar.db.component.BranchDto;
41 import org.sonar.db.project.ProjectDto;
42 import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction;
43 import org.sonar.server.almintegration.ws.ImportHelper;
44 import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
45 import org.sonar.server.component.ComponentCreationData;
46 import org.sonar.server.component.ComponentCreationParameters;
47 import org.sonar.server.component.ComponentUpdater;
48 import org.sonar.server.component.NewComponent;
49 import org.sonar.server.exceptions.NotFoundException;
50 import org.sonar.server.management.ManagedProjectService;
51 import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver;
52 import org.sonar.server.project.DefaultBranchNameResolver;
53 import org.sonar.server.project.ProjectDefaultVisibility;
54 import org.sonar.server.user.UserSession;
55 import org.sonarqube.ws.Projects;
57 import static java.util.Objects.requireNonNull;
58 import static org.sonar.api.resources.Qualifiers.PROJECT;
59 import static org.sonar.db.project.CreationMethod.Category.ALM_IMPORT;
60 import static org.sonar.db.project.CreationMethod.getCreationMethod;
61 import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING;
62 import static org.sonar.server.almintegration.ws.ImportHelper.toCreateResponse;
63 import static org.sonar.server.component.NewComponent.newComponentBuilder;
64 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION;
65 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION;
66 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam;
67 import static org.sonar.server.ws.WsUtils.writeProtobuf;
68 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE;
69 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE;
71 public class ImportGithubProjectAction implements AlmIntegrationsWsAction {
73 public static final String PARAM_ORGANIZATION = "organization";
74 public static final String PARAM_REPOSITORY_KEY = "repositoryKey";
76 private final DbClient dbClient;
78 private final ManagedProjectService managedProjectService;
79 private final UserSession userSession;
80 private final ProjectDefaultVisibility projectDefaultVisibility;
81 private final GithubApplicationClient githubApplicationClient;
82 private final ComponentUpdater componentUpdater;
83 private final ImportHelper importHelper;
84 private final ProjectKeyGenerator projectKeyGenerator;
86 private final NewCodeDefinitionResolver newCodeDefinitionResolver;
88 private final DefaultBranchNameResolver defaultBranchNameResolver;
90 private final GitHubSettings gitHubSettings;
93 public ImportGithubProjectAction(DbClient dbClient, ManagedProjectService managedProjectService, UserSession userSession, ProjectDefaultVisibility projectDefaultVisibility,
94 GithubApplicationClientImpl githubApplicationClient, ComponentUpdater componentUpdater, ImportHelper importHelper,
95 ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver,
96 DefaultBranchNameResolver defaultBranchNameResolver, GitHubSettings gitHubSettings) {
97 this.dbClient = dbClient;
98 this.managedProjectService = managedProjectService;
99 this.userSession = userSession;
100 this.projectDefaultVisibility = projectDefaultVisibility;
101 this.githubApplicationClient = githubApplicationClient;
102 this.componentUpdater = componentUpdater;
103 this.importHelper = importHelper;
104 this.projectKeyGenerator = projectKeyGenerator;
105 this.newCodeDefinitionResolver = newCodeDefinitionResolver;
106 this.defaultBranchNameResolver = defaultBranchNameResolver;
107 this.gitHubSettings = gitHubSettings;
111 public void define(WebService.NewController context) {
112 WebService.NewAction action = context.createAction("import_github_project")
113 .setDescription("Create a SonarQube project with the information from the provided GitHub repository.<br/>" +
114 "Autoconfigure pull request decoration mechanism. If Automatic Provisioning is enable for GitHub, it will also synchronize permissions from the repository.<br/>" +
115 "Requires the 'Create Projects' permission")
120 new Change("10.3", "Endpoint visibility change from internal to public"));
122 action.createParam(PARAM_ALM_SETTING)
124 .setMaximumLength(200)
125 .setDescription("DevOps Platform setting key");
127 action.createParam(PARAM_ORGANIZATION)
129 .setMaximumLength(200)
130 .setDescription("GitHub organization");
132 action.createParam(PARAM_REPOSITORY_KEY)
134 .setMaximumLength(256)
135 .setDescription("GitHub repository key");
137 action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
138 .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
141 action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
142 .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
147 public void handle(Request request, Response response) {
148 Projects.CreateWsResponse createResponse = doHandle(request);
149 writeProtobuf(createResponse, request, response);
152 private Projects.CreateWsResponse doHandle(Request request) {
153 importHelper.checkProvisionProjectPermission();
154 AlmSettingDto almSettingDto = importHelper.getAlmSetting(request);
156 String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE);
157 String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE);
158 try (DbSession dbSession = dbClient.openSession(false)) {
160 AccessToken accessToken = getAccessToken(dbSession, almSettingDto);
162 String githubOrganization = request.mandatoryParam(PARAM_ORGANIZATION);
163 String repositoryKey = request.mandatoryParam(PARAM_REPOSITORY_KEY);
165 String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null");
166 Repository repository = githubApplicationClient.getRepository(url, accessToken, githubOrganization, repositoryKey)
167 .orElseThrow(() -> new NotFoundException(String.format("GitHub repository '%s' not found", repositoryKey)));
169 ComponentCreationData componentCreationData = createProject(dbSession, repository, repository.getDefaultBranch());
170 ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
171 BranchDto mainBranchDto = Optional.ofNullable(componentCreationData.mainBranchDto()).orElseThrow();
173 populatePRSetting(dbSession, repository, projectDto, almSettingDto);
175 checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
177 if (newCodeDefinitionType != null) {
178 newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), mainBranchDto.getUuid(),
179 Optional.ofNullable(repository.getDefaultBranch()).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()),
180 newCodeDefinitionType, newCodeDefinitionValue);
183 componentUpdater.commitAndIndex(dbSession, componentCreationData);
185 String userUuid = Objects.requireNonNull(userSession.getUuid());
186 managedProjectService.queuePermissionSyncTask(userUuid, mainBranchDto.getUuid(), projectDto.getUuid());
188 return toCreateResponse(projectDto);
192 private AccessToken getAccessToken(DbSession dbSession, AlmSettingDto almSettingDto) {
193 String userUuid = importHelper.getUserUuid();
194 return dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto)
195 .map(AlmPatDto::getPersonalAccessToken)
196 .map(UserAccessToken::new)
197 .orElseThrow(() -> new IllegalArgumentException("No personal access token found"));
200 private ComponentCreationData createProject(DbSession dbSession, Repository repo, String mainBranchName) {
201 boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate();
202 String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(repo.getFullName());
203 NewComponent projectComponent = newComponentBuilder()
204 .setKey(uniqueProjectKey)
205 .setName(repo.getName())
206 .setPrivate(visibility)
207 .setQualifier(PROJECT)
209 ComponentCreationParameters componentCreationParameters = ComponentCreationParameters.builder()
210 .newComponent(projectComponent)
211 .userLogin(userSession.getLogin())
212 .userUuid(userSession.getUuid())
213 .mainBranchName(mainBranchName)
214 .isManaged(gitHubSettings.isProvisioningEnabled())
215 .creationMethod(getCreationMethod(ALM_IMPORT, userSession.isAuthenticatedBrowserSession()))
217 return componentUpdater.createWithoutCommit(dbSession, componentCreationParameters);
220 private void populatePRSetting(DbSession dbSession, Repository repo, ProjectDto projectDto, AlmSettingDto almSettingDto) {
221 ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto()
222 .setAlmSettingUuid(almSettingDto.getUuid())
223 .setAlmRepo(repo.getFullName())
225 .setProjectUuid(projectDto.getUuid())
226 .setSummaryCommentEnabled(true)
228 dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(),
229 projectDto.getName(), projectDto.getKey());