3 * Copyright (C) 2009-2020 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.ce.task.projectanalysis.step;
22 import com.google.common.base.Joiner;
23 import java.util.ArrayList;
24 import java.util.Date;
25 import java.util.List;
27 import java.util.Optional;
28 import java.util.stream.Collectors;
29 import org.sonar.api.utils.MessageException;
30 import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
31 import org.sonar.ce.task.projectanalysis.component.Component;
32 import org.sonar.ce.task.projectanalysis.component.ComponentVisitor;
33 import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
34 import org.sonar.ce.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
35 import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
36 import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
37 import org.sonar.ce.task.step.ComputationStep;
38 import org.sonar.db.DbClient;
39 import org.sonar.db.DbSession;
40 import org.sonar.db.component.BranchDto;
41 import org.sonar.db.component.ComponentDao;
42 import org.sonar.db.component.ComponentDto;
43 import org.sonar.db.component.SnapshotDto;
45 import static com.google.common.base.Preconditions.checkState;
46 import static java.lang.String.format;
47 import static org.sonar.api.utils.DateUtils.formatDateTime;
50 * Validate project and modules. It will fail in the following cases :
52 * <li>module key is not valid</li>
53 * <li>module key already exists in another project (same module key cannot exists in different projects)</li>
54 * <li>module key is already used as a project key</li>
55 * <li>date of the analysis is before last analysis</li>
56 * <li>PR targets a branch that still contains modules</li>
59 public class ValidateProjectStep implements ComputationStep {
61 private static final Joiner MESSAGES_JOINER = Joiner.on("\n o ");
63 private final DbClient dbClient;
64 private final TreeRootHolder treeRootHolder;
65 private final AnalysisMetadataHolder analysisMetadataHolder;
67 public ValidateProjectStep(DbClient dbClient, TreeRootHolder treeRootHolder, AnalysisMetadataHolder analysisMetadataHolder) {
68 this.dbClient = dbClient;
69 this.treeRootHolder = treeRootHolder;
70 this.analysisMetadataHolder = analysisMetadataHolder;
74 public void execute(ComputationStep.Context context) {
75 try (DbSession dbSession = dbClient.openSession(false)) {
76 validateTargetBranch(dbSession);
77 Component root = treeRootHolder.getRoot();
78 List<ComponentDto> baseModules = dbClient.componentDao().selectEnabledModulesFromProjectKey(dbSession, root.getDbKey());
79 Map<String, ComponentDto> baseModulesByKey = baseModules.stream().collect(Collectors.toMap(ComponentDto::getDbKey, x -> x));
80 ValidateProjectsVisitor visitor = new ValidateProjectsVisitor(dbSession, dbClient.componentDao(), baseModulesByKey);
81 new DepthTraversalTypeAwareCrawler(visitor).visit(root);
83 if (!visitor.validationMessages.isEmpty()) {
84 throw MessageException.of("Validation of project failed:\n o " + MESSAGES_JOINER.join(visitor.validationMessages));
89 private void validateTargetBranch(DbSession session) {
90 if (!analysisMetadataHolder.isPullRequest()) {
93 String referenceBranchUuid = analysisMetadataHolder.getBranch().getReferenceBranchUuid();
94 int moduleCount = dbClient.componentDao().countEnabledModulesByProjectUuid(session, referenceBranchUuid);
95 if (moduleCount > 0) {
96 Optional<BranchDto> opt = dbClient.branchDao().selectByUuid(session, referenceBranchUuid);
97 checkState(opt.isPresent(), "Reference branch '%s' does not exist", referenceBranchUuid);
98 throw MessageException.of(String.format(
99 "Due to an upgrade, you need first to re-analyze the target branch '%s' before analyzing this pull request.", opt.get().getKey()));
104 public String getDescription() {
105 return "Validate project";
108 private class ValidateProjectsVisitor extends TypeAwareVisitorAdapter {
109 private final DbSession session;
110 private final ComponentDao componentDao;
111 private final Map<String, ComponentDto> baseModulesByKey;
112 private final List<String> validationMessages = new ArrayList<>();
114 public ValidateProjectsVisitor(DbSession session, ComponentDao componentDao, Map<String, ComponentDto> baseModulesByKey) {
115 super(CrawlerDepthLimit.PROJECT, ComponentVisitor.Order.PRE_ORDER);
116 this.session = session;
117 this.componentDao = componentDao;
118 this.baseModulesByKey = baseModulesByKey;
122 public void visitProject(Component rawProject) {
123 String rawProjectKey = rawProject.getDbKey();
124 Optional<ComponentDto> baseProject = loadBaseComponent(rawProjectKey);
125 validateAnalysisDate(baseProject);
128 private void validateAnalysisDate(Optional<ComponentDto> baseProject) {
129 if (baseProject.isPresent()) {
130 Optional<SnapshotDto> snapshotDto = dbClient.snapshotDao().selectLastAnalysisByRootComponentUuid(session, baseProject.get().uuid());
131 long currentAnalysisDate = analysisMetadataHolder.getAnalysisDate();
132 Long lastAnalysisDate = snapshotDto.map(SnapshotDto::getCreatedAt).orElse(null);
133 if (lastAnalysisDate != null && currentAnalysisDate <= lastAnalysisDate) {
134 validationMessages.add(format("Date of analysis cannot be older than the date of the last known analysis on this project. Value: \"%s\". " +
135 "Latest analysis: \"%s\". It's only possible to rebuild the past in a chronological order.",
136 formatDateTime(new Date(currentAnalysisDate)), formatDateTime(new Date(lastAnalysisDate))));
141 private Optional<ComponentDto> loadBaseComponent(String rawComponentKey) {
142 ComponentDto baseComponent = baseModulesByKey.get(rawComponentKey);
143 if (baseComponent == null) {
144 // Load component from key to be able to detect issue (try to analyze a module, etc.)
145 return componentDao.selectByKey(session, rawComponentKey);
147 return Optional.of(baseComponent);