3 * Copyright (C) 2009-2021 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.api.utils.System2;
31 import org.sonar.ce.task.log.CeTaskMessages;
32 import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
33 import org.sonar.ce.task.projectanalysis.component.Component;
34 import org.sonar.ce.task.projectanalysis.component.ComponentVisitor;
35 import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
36 import org.sonar.ce.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
37 import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
38 import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
39 import org.sonar.ce.task.step.ComputationStep;
40 import org.sonar.db.DbClient;
41 import org.sonar.db.DbSession;
42 import org.sonar.db.component.BranchDto;
43 import org.sonar.db.component.ComponentDao;
44 import org.sonar.db.component.ComponentDto;
45 import org.sonar.db.component.SnapshotDto;
47 import static com.google.common.base.Preconditions.checkState;
48 import static java.lang.String.format;
49 import static org.sonar.api.utils.DateUtils.formatDateTime;
50 import static org.sonar.core.component.ComponentKeys.ALLOWED_CHARACTERS_MESSAGE;
51 import static org.sonar.core.component.ComponentKeys.isValidProjectKey;
53 public class ValidateProjectStep implements ComputationStep {
55 private static final Joiner MESSAGES_JOINER = Joiner.on("\n o ");
57 private final DbClient dbClient;
58 private final TreeRootHolder treeRootHolder;
59 private final AnalysisMetadataHolder analysisMetadataHolder;
61 public ValidateProjectStep(DbClient dbClient, TreeRootHolder treeRootHolder, AnalysisMetadataHolder analysisMetadataHolder, CeTaskMessages taskMessages, System2 system2) {
62 this.dbClient = dbClient;
63 this.treeRootHolder = treeRootHolder;
64 this.analysisMetadataHolder = analysisMetadataHolder;
68 public void execute(ComputationStep.Context context) {
69 try (DbSession dbSession = dbClient.openSession(false)) {
70 validateTargetBranch(dbSession);
71 Component root = treeRootHolder.getRoot();
72 // FIXME if module have really be dropped, no more need to load them
73 List<ComponentDto> baseModules = dbClient.componentDao().selectEnabledModulesFromProjectKey(dbSession, root.getDbKey());
74 Map<String, ComponentDto> baseModulesByKey = baseModules.stream().collect(Collectors.toMap(ComponentDto::getDbKey, x -> x));
75 ValidateProjectsVisitor visitor = new ValidateProjectsVisitor(dbSession, dbClient.componentDao(), baseModulesByKey);
76 new DepthTraversalTypeAwareCrawler(visitor).visit(root);
78 if (!visitor.validationMessages.isEmpty()) {
79 throw MessageException.of("Validation of project failed:\n o " + MESSAGES_JOINER.join(visitor.validationMessages));
84 private void validateTargetBranch(DbSession session) {
85 if (!analysisMetadataHolder.isPullRequest()) {
88 String referenceBranchUuid = analysisMetadataHolder.getBranch().getReferenceBranchUuid();
89 int moduleCount = dbClient.componentDao().countEnabledModulesByProjectUuid(session, referenceBranchUuid);
90 if (moduleCount > 0) {
91 Optional<BranchDto> opt = dbClient.branchDao().selectByUuid(session, referenceBranchUuid);
92 checkState(opt.isPresent(), "Reference branch '%s' does not exist", referenceBranchUuid);
93 throw MessageException.of(String.format(
94 "Due to an upgrade, you need first to re-analyze the target branch '%s' before analyzing this pull request.", opt.get().getKey()));
99 public String getDescription() {
100 return "Validate project";
103 private class ValidateProjectsVisitor extends TypeAwareVisitorAdapter {
104 private final DbSession session;
105 private final ComponentDao componentDao;
106 private final Map<String, ComponentDto> baseModulesByKey;
107 private final List<String> validationMessages = new ArrayList<>();
109 public ValidateProjectsVisitor(DbSession session, ComponentDao componentDao, Map<String, ComponentDto> baseModulesByKey) {
110 super(CrawlerDepthLimit.PROJECT, ComponentVisitor.Order.PRE_ORDER);
111 this.session = session;
112 this.componentDao = componentDao;
113 this.baseModulesByKey = baseModulesByKey;
117 public void visitProject(Component rawProject) {
118 String rawProjectKey = rawProject.getDbKey();
119 Optional<ComponentDto> baseProjectOpt = loadBaseComponent(rawProjectKey);
120 if (baseProjectOpt.isPresent()) {
121 ComponentDto baseProject = baseProjectOpt.get();
122 validateAnalysisDate(baseProject);
123 validateProjectKey(baseProject);
127 private void validateProjectKey(ComponentDto baseProject) {
128 if (!isValidProjectKey(baseProject.getKey())) {
129 validationMessages.add(format("The project key ā%sā contains invalid characters. %s. You should update the project key with the expected format.", baseProject.getKey(),
130 ALLOWED_CHARACTERS_MESSAGE));
134 private void validateAnalysisDate(ComponentDto baseProject) {
135 Optional<SnapshotDto> snapshotDto = dbClient.snapshotDao().selectLastAnalysisByRootComponentUuid(session, baseProject.uuid());
136 long currentAnalysisDate = analysisMetadataHolder.getAnalysisDate();
137 Long lastAnalysisDate = snapshotDto.map(SnapshotDto::getCreatedAt).orElse(null);
138 if (lastAnalysisDate != null && currentAnalysisDate <= lastAnalysisDate) {
139 validationMessages.add(format("Date of analysis cannot be older than the date of the last known analysis on this project. Value: \"%s\". " +
140 "Latest analysis: \"%s\". It's only possible to rebuild the past in a chronological order.",
141 formatDateTime(new Date(currentAnalysisDate)), formatDateTime(new Date(lastAnalysisDate))));
145 private Optional<ComponentDto> loadBaseComponent(String rawComponentKey) {
146 ComponentDto baseComponent = baseModulesByKey.get(rawComponentKey);
147 if (baseComponent == null) {
148 // Load component from key to be able to detect issue (try to analyze a module, etc.)
149 return componentDao.selectByKey(session, rawComponentKey);
151 return Optional.of(baseComponent);