Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

NewCodePeriodResolver.java 9.2KB

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