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.ProjectDto;
37 import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction;
38 import org.sonar.server.almintegration.ws.ImportHelper;
39 import org.sonar.server.almsettings.ws.DevOpsProjectDescriptor;
40 import org.sonar.server.almsettings.ws.GitHubDevOpsPlatformService;
41 import org.sonar.server.component.ComponentCreationData;
42 import org.sonar.server.component.ComponentUpdater;
43 import org.sonar.server.management.ManagedProjectService;
44 import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver;
45 import org.sonar.server.project.DefaultBranchNameResolver;
46 import org.sonar.server.user.UserSession;
47 import org.sonarqube.ws.Projects;
49 import static java.util.Objects.requireNonNull;
50 import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING;
51 import static org.sonar.server.almintegration.ws.ImportHelper.toCreateResponse;
52 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION;
53 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION;
54 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam;
55 import static org.sonar.server.ws.WsUtils.writeProtobuf;
56 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE;
57 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE;
59 public class ImportGithubProjectAction implements AlmIntegrationsWsAction {
60 public static final String PARAM_REPOSITORY_KEY = "repositoryKey";
62 private final DbClient dbClient;
64 private final ManagedProjectService managedProjectService;
65 private final UserSession userSession;
66 private final ComponentUpdater componentUpdater;
67 private final ImportHelper importHelper;
69 private final NewCodeDefinitionResolver newCodeDefinitionResolver;
71 private final DefaultBranchNameResolver defaultBranchNameResolver;
73 private final GitHubDevOpsPlatformService gitHubDevOpsPlatformService;
76 public ImportGithubProjectAction(DbClient dbClient, ManagedProjectService managedProjectService, UserSession userSession,
77 ComponentUpdater componentUpdater, ImportHelper importHelper,
78 NewCodeDefinitionResolver newCodeDefinitionResolver,
79 DefaultBranchNameResolver defaultBranchNameResolver, GitHubDevOpsPlatformService gitHubDevOpsPlatformService) {
80 this.dbClient = dbClient;
81 this.managedProjectService = managedProjectService;
82 this.userSession = userSession;
83 this.componentUpdater = componentUpdater;
84 this.importHelper = importHelper;
85 this.newCodeDefinitionResolver = newCodeDefinitionResolver;
86 this.defaultBranchNameResolver = defaultBranchNameResolver;
87 this.gitHubDevOpsPlatformService = gitHubDevOpsPlatformService;
91 public void define(WebService.NewController context) {
92 WebService.NewAction action = context.createAction("import_github_project")
93 .setDescription("Create a SonarQube project with the information from the provided GitHub repository.<br/>" +
94 "Autoconfigure pull request decoration mechanism. If Automatic Provisioning is enable for GitHub, " +
95 "it will also synchronize permissions from the repository.<br/>" +
96 "Requires the 'Create Projects' permission")
101 new Change("10.3", "Parameter organization is not necessary anymore"),
102 new Change("10.3", String.format("Parameter %s becomes optional if you have only one configuration for GitHub", PARAM_ALM_SETTING)),
103 new Change("10.3", "Endpoint visibility change from internal to public"));
105 action.createParam(PARAM_ALM_SETTING)
106 .setMaximumLength(200)
107 .setDescription("DevOps Platform configuration key. This parameter is optional if you have only one GitHub integration.");
109 action.createParam(PARAM_REPOSITORY_KEY)
111 .setMaximumLength(256)
112 .setDescription("GitHub repository key (organization/repoSlug");
114 action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
115 .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
118 action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
119 .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
124 public void handle(Request request, Response response) {
125 Projects.CreateWsResponse createResponse = doHandle(request);
126 writeProtobuf(createResponse, request, response);
129 private Projects.CreateWsResponse doHandle(Request request) {
130 importHelper.checkProvisionProjectPermission();
131 AlmSettingDto almSettingDto = importHelper.getAlmSettingDtoForAlm(request, ALM.GITHUB);
133 String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE);
134 String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE);
135 try (DbSession dbSession = dbClient.openSession(false)) {
137 AccessToken accessToken = getAccessToken(dbSession, almSettingDto);
139 String repositoryKey = request.mandatoryParam(PARAM_REPOSITORY_KEY);
141 String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null");
142 DevOpsProjectDescriptor devOpsProjectDescriptor = new DevOpsProjectDescriptor(ALM.GITHUB, url, repositoryKey);
143 ComponentCreationData componentCreationData = gitHubDevOpsPlatformService.createProjectAndBindToDevOpsPlatform(dbSession, almSettingDto, accessToken,
144 devOpsProjectDescriptor);
146 checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
148 ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
149 BranchDto mainBranchDto = Optional.ofNullable(componentCreationData.mainBranchDto()).orElseThrow();
151 if (newCodeDefinitionType != null) {
152 newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), mainBranchDto.getUuid(),
153 Optional.ofNullable(mainBranchDto.getKey()).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()),
154 newCodeDefinitionType, newCodeDefinitionValue);
157 componentUpdater.commitAndIndex(dbSession, componentCreationData);
159 String userUuid = requireNonNull(userSession.getUuid());
160 managedProjectService.queuePermissionSyncTask(userUuid, mainBranchDto.getUuid(), projectDto.getUuid());
162 return toCreateResponse(projectDto);
166 private AccessToken getAccessToken(DbSession dbSession, AlmSettingDto almSettingDto) {
167 String userUuid = importHelper.getUserUuid();
168 return dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto)
169 .map(AlmPatDto::getPersonalAccessToken)
170 .map(UserAccessToken::new)
171 .orElseThrow(() -> new IllegalArgumentException("No personal access token found"));