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.security.AccessToken;
25 import org.sonar.alm.client.github.security.UserAccessToken;
26 import org.sonar.api.server.ws.Change;
27 import org.sonar.api.server.ws.Request;
28 import org.sonar.api.server.ws.Response;
29 import org.sonar.api.server.ws.WebService;
30 import org.sonar.db.DbClient;
31 import org.sonar.db.DbSession;
32 import org.sonar.db.alm.pat.AlmPatDto;
33 import org.sonar.db.alm.setting.ALM;
34 import org.sonar.db.alm.setting.AlmSettingDto;
35 import org.sonar.db.component.BranchDto;
36 import org.sonar.db.project.CreationMethod;
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.almsettings.ws.DevOpsProjectCreator;
41 import org.sonar.server.almsettings.ws.DevOpsProjectDescriptor;
42 import org.sonar.server.almsettings.ws.GithubProjectCreatorFactory;
43 import org.sonar.server.component.ComponentCreationData;
44 import org.sonar.server.component.ComponentUpdater;
45 import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver;
46 import org.sonar.server.project.DefaultBranchNameResolver;
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.db.project.CreationMethod.Category.ALM_IMPORT;
52 import static org.sonar.db.project.CreationMethod.getCreationMethod;
53 import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING;
54 import static org.sonar.server.almintegration.ws.ImportHelper.toCreateResponse;
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 {
63 public static final String PARAM_REPOSITORY_KEY = "repositoryKey";
65 private final DbClient dbClient;
67 private final UserSession userSession;
68 private final ComponentUpdater componentUpdater;
69 private final ImportHelper importHelper;
71 private final NewCodeDefinitionResolver newCodeDefinitionResolver;
73 private final DefaultBranchNameResolver defaultBranchNameResolver;
75 private final GithubProjectCreatorFactory githubProjectCreatorFactory;
78 public ImportGithubProjectAction(DbClient dbClient, UserSession userSession,
79 ComponentUpdater componentUpdater, ImportHelper importHelper,
80 NewCodeDefinitionResolver newCodeDefinitionResolver,
81 DefaultBranchNameResolver defaultBranchNameResolver, GithubProjectCreatorFactory githubProjectCreatorFactory) {
82 this.dbClient = dbClient;
83 this.userSession = userSession;
84 this.componentUpdater = componentUpdater;
85 this.importHelper = importHelper;
86 this.newCodeDefinitionResolver = newCodeDefinitionResolver;
87 this.defaultBranchNameResolver = defaultBranchNameResolver;
88 this.githubProjectCreatorFactory = githubProjectCreatorFactory;
92 public void define(WebService.NewController context) {
93 WebService.NewAction action = context.createAction("import_github_project")
94 .setDescription("Create a SonarQube project with the information from the provided GitHub repository.<br/>" +
95 "Autoconfigure pull request decoration mechanism. If Automatic Provisioning is enable for GitHub, " +
96 "it will also synchronize permissions from the repository.<br/>" +
97 "Requires the 'Create Projects' permission")
102 new Change("10.3", "Parameter organization is not necessary anymore"),
103 new Change("10.3", String.format("Parameter %s becomes optional if you have only one configuration for GitHub", PARAM_ALM_SETTING)),
104 new Change("10.3", "Endpoint visibility change from internal to public"));
106 action.createParam(PARAM_ALM_SETTING)
107 .setMaximumLength(200)
108 .setDescription("DevOps Platform configuration key. This parameter is optional if you have only one GitHub integration.");
110 action.createParam(PARAM_REPOSITORY_KEY)
112 .setMaximumLength(256)
113 .setDescription("GitHub repository key (organization/repoSlug");
115 action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
116 .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
119 action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
120 .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
125 public void handle(Request request, Response response) {
126 Projects.CreateWsResponse createResponse = doHandle(request);
127 writeProtobuf(createResponse, request, response);
130 private Projects.CreateWsResponse doHandle(Request request) {
131 importHelper.checkProvisionProjectPermission();
132 AlmSettingDto almSettingDto = importHelper.getAlmSettingDtoForAlm(request, ALM.GITHUB);
134 String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE);
135 String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE);
136 try (DbSession dbSession = dbClient.openSession(false)) {
138 AccessToken accessToken = getAccessToken(dbSession, almSettingDto);
140 String repositoryKey = request.mandatoryParam(PARAM_REPOSITORY_KEY);
142 String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null");
143 DevOpsProjectDescriptor devOpsProjectDescriptor = new DevOpsProjectDescriptor(ALM.GITHUB, url, repositoryKey);
145 DevOpsProjectCreator devOpsProjectCreator = githubProjectCreatorFactory.getDevOpsProjectCreator(dbSession, almSettingDto, accessToken, devOpsProjectDescriptor);
146 CreationMethod creationMethod = getCreationMethod(ALM_IMPORT, userSession.isAuthenticatedBrowserSession());
147 ComponentCreationData componentCreationData = devOpsProjectCreator.createProjectAndBindToDevOpsPlatform(dbSession, creationMethod, null);
149 checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
151 ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
152 BranchDto mainBranchDto = Optional.ofNullable(componentCreationData.mainBranchDto()).orElseThrow();
154 if (newCodeDefinitionType != null) {
155 newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), mainBranchDto.getUuid(),
156 Optional.ofNullable(mainBranchDto.getKey()).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()),
157 newCodeDefinitionType, newCodeDefinitionValue);
160 componentUpdater.commitAndIndex(dbSession, componentCreationData);
161 return toCreateResponse(projectDto);
165 private AccessToken getAccessToken(DbSession dbSession, AlmSettingDto almSettingDto) {
166 String userUuid = importHelper.getUserUuid();
167 return dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto)
168 .map(AlmPatDto::getPersonalAccessToken)
169 .map(UserAccessToken::new)
170 .orElseThrow(() -> new IllegalArgumentException("No personal access token found"));