3 * Copyright (C) 2009-2022 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;
48 import static org.sonar.core.component.ComponentKeys.ALLOWED_CHARACTERS_MESSAGE;
49 import static org.sonar.core.component.ComponentKeys.isValidProjectKey;
51 public class ValidateProjectStep implements ComputationStep {
52 private static final Joiner MESSAGES_JOINER = Joiner.on("\n o ");
54 private final DbClient dbClient;
55 private final TreeRootHolder treeRootHolder;
56 private final AnalysisMetadataHolder analysisMetadataHolder;
58 public ValidateProjectStep(DbClient dbClient, TreeRootHolder treeRootHolder, AnalysisMetadataHolder analysisMetadataHolder) {
59 this.dbClient = dbClient;
60 this.treeRootHolder = treeRootHolder;
61 this.analysisMetadataHolder = analysisMetadataHolder;
65 public void execute(ComputationStep.Context context) {
66 try (DbSession dbSession = dbClient.openSession(false)) {
67 validateTargetBranch(dbSession);
68 Component root = treeRootHolder.getRoot();
69 // FIXME if module have really be dropped, no more need to load them
70 List<ComponentDto> baseModules = dbClient.componentDao().selectEnabledModulesFromProjectKey(dbSession, root.getDbKey());
71 Map<String, ComponentDto> baseModulesByKey = baseModules.stream().collect(Collectors.toMap(ComponentDto::getDbKey, x -> x));
72 ValidateProjectsVisitor visitor = new ValidateProjectsVisitor(dbSession, dbClient.componentDao(), baseModulesByKey);
73 new DepthTraversalTypeAwareCrawler(visitor).visit(root);
75 if (!visitor.validationMessages.isEmpty()) {
76 throw MessageException.of("Validation of project failed:\n o " + MESSAGES_JOINER.join(visitor.validationMessages));
81 private void validateTargetBranch(DbSession session) {
82 if (!analysisMetadataHolder.isPullRequest()) {
85 String referenceBranchUuid = analysisMetadataHolder.getBranch().getReferenceBranchUuid();
86 int moduleCount = dbClient.componentDao().countEnabledModulesByProjectUuid(session, referenceBranchUuid);
87 if (moduleCount > 0) {
88 Optional<BranchDto> opt = dbClient.branchDao().selectByUuid(session, referenceBranchUuid);
89 checkState(opt.isPresent(), "Reference branch '%s' does not exist", referenceBranchUuid);
90 throw MessageException.of(String.format(
91 "Due to an upgrade, you need first to re-analyze the target branch '%s' before analyzing this pull request.", opt.get().getKey()));
96 public String getDescription() {
97 return "Validate project";
100 private class ValidateProjectsVisitor extends TypeAwareVisitorAdapter {
101 private final DbSession session;
102 private final ComponentDao componentDao;
103 private final Map<String, ComponentDto> baseModulesByKey;
104 private final List<String> validationMessages = new ArrayList<>();
106 public ValidateProjectsVisitor(DbSession session, ComponentDao componentDao, Map<String, ComponentDto> baseModulesByKey) {
107 super(CrawlerDepthLimit.PROJECT, ComponentVisitor.Order.PRE_ORDER);
108 this.session = session;
109 this.componentDao = componentDao;
110 this.baseModulesByKey = baseModulesByKey;
114 public void visitProject(Component rawProject) {
115 String rawProjectKey = rawProject.getDbKey();
116 Optional<ComponentDto> baseProjectOpt = loadBaseComponent(rawProjectKey);
117 if (baseProjectOpt.isPresent()) {
118 ComponentDto baseProject = baseProjectOpt.get();
119 validateAnalysisDate(baseProject);
120 validateProjectKey(baseProject);
124 private void validateProjectKey(ComponentDto baseProject) {
125 if (!isValidProjectKey(baseProject.getKey())) {
126 validationMessages.add(format("The project key ā%sā contains invalid characters. %s. You should update the project key with the expected format.", baseProject.getKey(),
127 ALLOWED_CHARACTERS_MESSAGE));
131 private void validateAnalysisDate(ComponentDto baseProject) {
132 Optional<SnapshotDto> snapshotDto = dbClient.snapshotDao().selectLastAnalysisByRootComponentUuid(session, baseProject.uuid());
133 long currentAnalysisDate = analysisMetadataHolder.getAnalysisDate();
134 Long lastAnalysisDate = snapshotDto.map(SnapshotDto::getCreatedAt).orElse(null);
135 if (lastAnalysisDate != null && currentAnalysisDate <= lastAnalysisDate) {
136 validationMessages.add(format("Date of analysis cannot be older than the date of the last known analysis on this project. Value: \"%s\". " +
137 "Latest analysis: \"%s\". It's only possible to rebuild the past in a chronological order.",
138 formatDateTime(new Date(currentAnalysisDate)), formatDateTime(new Date(lastAnalysisDate))));
142 private Optional<ComponentDto> loadBaseComponent(String rawComponentKey) {
143 ComponentDto baseComponent = baseModulesByKey.get(rawComponentKey);
144 if (baseComponent == null) {
145 // Load component from key to be able to detect issue (try to analyze a module, etc.)
146 return componentDao.selectByKey(session, rawComponentKey);
148 return Optional.of(baseComponent);