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.period;
22 import java.time.Duration;
23 import java.time.Instant;
24 import java.time.temporal.ChronoUnit;
25 import java.util.List;
26 import java.util.Optional;
27 import java.util.function.Supplier;
28 import javax.annotation.CheckForNull;
29 import javax.annotation.Nullable;
30 import org.sonar.api.utils.DateUtils;
31 import org.sonar.api.utils.MessageException;
32 import org.sonar.api.utils.log.Logger;
33 import org.sonar.api.utils.log.Loggers;
34 import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
35 import org.sonar.db.DbClient;
36 import org.sonar.db.DbSession;
37 import org.sonar.db.component.SnapshotDto;
38 import org.sonar.db.component.SnapshotQuery;
39 import org.sonar.db.event.EventDto;
40 import org.sonar.db.newcodeperiod.NewCodePeriodDto;
41 import org.sonar.db.newcodeperiod.NewCodePeriodParser;
42 import org.sonar.db.newcodeperiod.NewCodePeriodType;
44 import static com.google.common.base.Preconditions.checkNotNull;
45 import static com.google.common.base.Preconditions.checkState;
46 import static java.lang.String.format;
47 import static org.sonar.db.component.SnapshotDto.STATUS_PROCESSED;
48 import static org.sonar.db.component.SnapshotQuery.SORT_FIELD.BY_DATE;
49 import static org.sonar.db.component.SnapshotQuery.SORT_ORDER.ASC;
51 public class NewCodePeriodResolver {
52 private static final Logger LOG = Loggers.get(NewCodePeriodResolver.class);
54 private final DbClient dbClient;
55 private final AnalysisMetadataHolder analysisMetadataHolder;
57 public NewCodePeriodResolver(DbClient dbClient, AnalysisMetadataHolder analysisMetadataHolder) {
58 this.dbClient = dbClient;
59 this.analysisMetadataHolder = analysisMetadataHolder;
63 public Period resolve(DbSession dbSession, String branchUuid, NewCodePeriodDto newCodePeriodDto, String projectVersion) {
64 return toPeriod(newCodePeriodDto.getType(), newCodePeriodDto.getValue(), dbSession, projectVersion, branchUuid);
68 private Period toPeriod(NewCodePeriodType type, @Nullable String value, DbSession dbSession, String projectVersion, String rootUuid) {
71 checkNotNullValue(value, type);
72 Integer days = NewCodePeriodParser.parseDays(value);
73 return resolveByDays(dbSession, rootUuid, days, value, analysisMetadataHolder.getAnalysisDate());
74 case PREVIOUS_VERSION:
75 return resolveByPreviousVersion(dbSession, rootUuid, projectVersion);
76 case SPECIFIC_ANALYSIS:
77 checkNotNullValue(value, type);
78 return resolveBySpecificAnalysis(dbSession, rootUuid, value);
79 case REFERENCE_BRANCH:
80 checkNotNullValue(value, type);
81 return resolveByReferenceBranch(value);
83 throw new IllegalStateException("Unexpected type: " + type);
87 private Period resolveByReferenceBranch(String value) {
88 return newPeriod(NewCodePeriodType.REFERENCE_BRANCH, value, null);
91 private Period resolveBySpecificAnalysis(DbSession dbSession, String rootUuid, String value) {
92 SnapshotDto baseline = dbClient.snapshotDao().selectByUuid(dbSession, value)
93 .filter(t -> t.getComponentUuid().equals(rootUuid))
94 .orElseThrow(() -> new IllegalStateException("Analysis '" + value + "' of project '" + rootUuid
95 + "' defined as the baseline does not exist"));
96 LOG.debug("Resolving new code period with a specific analysis");
97 return newPeriod(NewCodePeriodType.SPECIFIC_ANALYSIS, value, baseline.getCreatedAt());
100 private Period resolveByPreviousVersion(DbSession dbSession, String projectUuid, String projectVersion) {
101 List<EventDto> versions = dbClient.eventDao().selectVersionsByMostRecentFirst(dbSession, projectUuid);
102 if (versions.isEmpty()) {
103 return findOldestAnalysis(dbSession, projectUuid);
106 String mostRecentVersion = Optional.ofNullable(versions.iterator().next().getName())
107 .orElseThrow(() -> new IllegalStateException("selectVersionsByMostRecentFirst returned a DTO which didn't have a name"));
109 if (versions.size() == 1 && projectVersion.equals(mostRecentVersion)) {
110 return findOldestAnalysis(dbSession, projectUuid);
113 return resolvePreviousVersion(dbSession, projectVersion, versions, mostRecentVersion);
116 private Period resolveByDays(DbSession dbSession, String rootUuid, Integer days, String value, long referenceDate) {
117 checkPeriodProperty(days > 0, value, "number of days is <= 0");
118 List<SnapshotDto> snapshots = dbClient.snapshotDao().selectAnalysesByQuery(dbSession, createCommonQuery(rootUuid)
119 .setCreatedBefore(referenceDate).setSort(BY_DATE, ASC));
121 Instant targetDate = DateUtils.addDays(Instant.ofEpochMilli(referenceDate), -days);
122 LOG.debug("Resolving new code period by {} days: {}", days, supplierToString(() -> logDate(targetDate)));
123 SnapshotDto snapshot = findNearestSnapshotToTargetDate(snapshots, targetDate);
124 return newPeriod(NewCodePeriodType.NUMBER_OF_DAYS, String.valueOf((int) days), snapshot.getCreatedAt());
127 private Period resolvePreviousVersion(DbSession dbSession, String currentVersion, List<EventDto> versions, String mostRecentVersion) {
128 EventDto previousVersion = versions.get(currentVersion.equals(mostRecentVersion) ? 1 : 0);
129 LOG.debug("Resolving new code period by previous version: {}", previousVersion.getName());
130 return newPeriod(dbSession, previousVersion);
133 private Period findOldestAnalysis(DbSession dbSession, String projectUuid) {
134 LOG.debug("Resolving first analysis as new code period as there is only one existing version");
135 Optional<Period> period = dbClient.snapshotDao().selectOldestSnapshot(dbSession, projectUuid)
136 .map(dto -> newPeriod(NewCodePeriodType.PREVIOUS_VERSION, null, dto.getCreatedAt()));
137 ensureNotOnFirstAnalysis(period.isPresent());
141 private Period newPeriod(DbSession dbSession, EventDto previousVersion) {
142 Optional<Period> period = dbClient.snapshotDao().selectByUuid(dbSession, previousVersion.getAnalysisUuid())
143 .map(dto -> newPeriod(NewCodePeriodType.PREVIOUS_VERSION, dto.getProjectVersion(), dto.getCreatedAt()));
144 if (!period.isPresent()) {
145 throw new IllegalStateException(format("Analysis '%s' for version event '%s' has been deleted",
146 previousVersion.getAnalysisUuid(), previousVersion.getName()));
151 private static Period newPeriod(NewCodePeriodType type, @Nullable String value, @Nullable Long date) {
152 return new Period(type.name(), value, date);
155 private static Object supplierToString(Supplier<String> s) {
156 return new Object() {
158 public String toString() {
164 private static SnapshotQuery createCommonQuery(String projectUuid) {
165 return new SnapshotQuery().setComponentUuid(projectUuid).setStatus(STATUS_PROCESSED);
168 private static SnapshotDto findNearestSnapshotToTargetDate(List<SnapshotDto> snapshots, Instant targetDate) {
169 // FIXME shouldn't this be the first analysis after targetDate?
170 Duration bestDuration = null;
171 SnapshotDto nearest = null;
173 ensureNotOnFirstAnalysis(!snapshots.isEmpty());
175 for (SnapshotDto snapshot : snapshots) {
176 Instant createdAt = Instant.ofEpochMilli(snapshot.getCreatedAt());
177 Duration duration = Duration.between(targetDate, createdAt).abs();
178 if (bestDuration == null || duration.compareTo(bestDuration) <= 0) {
179 bestDuration = duration;
186 private static void checkPeriodProperty(boolean test, String propertyValue, String testDescription, Object... args) {
188 LOG.debug("Invalid code period '{}': {}", propertyValue, supplierToString(() -> format(testDescription, args)));
189 throw MessageException.of(format("Invalid new code period. '%s' is not one of: " +
190 "integer > 0, date before current analysis j, \"previous_version\", or version string that exists in the project' \n" +
191 "Please contact a project administrator to correct this setting", propertyValue));
195 private static void ensureNotOnFirstAnalysis(boolean expression) {
196 checkState(expression, "Attempting to resolve period while no analysis exist for project");
199 private static void checkNotNullValue(@Nullable String value, NewCodePeriodType type) {
200 checkNotNull(value, "Value can't be null with type %s", type);
203 private static String logDate(Instant instant) {
204 return DateUtils.formatDate(instant.truncatedTo(ChronoUnit.SECONDS));