You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

QualityProfileEventsStep.java 7.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2020 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.step;
  21. import com.google.common.collect.ImmutableSortedMap;
  22. import java.util.Collections;
  23. import java.util.Date;
  24. import java.util.Map;
  25. import java.util.Optional;
  26. import javax.annotation.Nullable;
  27. import org.apache.commons.lang.time.DateUtils;
  28. import org.sonar.api.measures.CoreMetrics;
  29. import org.sonar.api.resources.Language;
  30. import org.sonar.api.utils.KeyValueFormat;
  31. import org.sonar.ce.task.projectanalysis.component.Component;
  32. import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
  33. import org.sonar.ce.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
  34. import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
  35. import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
  36. import org.sonar.ce.task.projectanalysis.event.Event;
  37. import org.sonar.ce.task.projectanalysis.event.EventRepository;
  38. import org.sonar.ce.task.projectanalysis.language.LanguageRepository;
  39. import org.sonar.ce.task.projectanalysis.measure.Measure;
  40. import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
  41. import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
  42. import org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository;
  43. import org.sonar.ce.task.step.ComputationStep;
  44. import org.sonar.core.util.UtcDateUtils;
  45. import org.sonar.server.qualityprofile.QPMeasureData;
  46. import org.sonar.server.qualityprofile.QualityProfile;
  47. import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER;
  48. import static org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository.Status.ADDED;
  49. import static org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository.Status.REMOVED;
  50. import static org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository.Status.UPDATED;
  51. /**
  52. * Computation of quality profile events
  53. *
  54. * As it depends upon {@link CoreMetrics#QUALITY_PROFILES_KEY}, it must be executed after {@link ComputeQProfileMeasureStep}
  55. */
  56. public class QualityProfileEventsStep implements ComputationStep {
  57. private final TreeRootHolder treeRootHolder;
  58. private final MetricRepository metricRepository;
  59. private final MeasureRepository measureRepository;
  60. private final EventRepository eventRepository;
  61. private final LanguageRepository languageRepository;
  62. private QProfileStatusRepository qProfileStatusRepository;
  63. public QualityProfileEventsStep(TreeRootHolder treeRootHolder,
  64. MetricRepository metricRepository, MeasureRepository measureRepository, LanguageRepository languageRepository,
  65. EventRepository eventRepository, QProfileStatusRepository qProfileStatusRepository) {
  66. this.treeRootHolder = treeRootHolder;
  67. this.metricRepository = metricRepository;
  68. this.measureRepository = measureRepository;
  69. this.eventRepository = eventRepository;
  70. this.languageRepository = languageRepository;
  71. this.qProfileStatusRepository = qProfileStatusRepository;
  72. }
  73. @Override
  74. public void execute(ComputationStep.Context context) {
  75. new DepthTraversalTypeAwareCrawler(
  76. new TypeAwareVisitorAdapter(CrawlerDepthLimit.PROJECT, POST_ORDER) {
  77. @Override
  78. public void visitProject(Component tree) {
  79. executeForProject(tree);
  80. }
  81. }).visit(treeRootHolder.getRoot());
  82. }
  83. private void executeForProject(Component projectComponent) {
  84. Optional<Measure> baseMeasure = measureRepository.getBaseMeasure(projectComponent, metricRepository.getByKey(CoreMetrics.QUALITY_PROFILES_KEY));
  85. if (!baseMeasure.isPresent()) {
  86. // first analysis -> do not generate events
  87. return;
  88. }
  89. // Load profiles used in current analysis for which at least one file of the corresponding language exists
  90. Optional<Measure> rawMeasure = measureRepository.getRawMeasure(projectComponent, metricRepository.getByKey(CoreMetrics.QUALITY_PROFILES_KEY));
  91. if (!rawMeasure.isPresent()) {
  92. // No qualify profile computed on the project
  93. return;
  94. }
  95. Map<String, QualityProfile> rawProfiles = QPMeasureData.fromJson(rawMeasure.get().getStringValue()).getProfilesByKey();
  96. Map<String, QualityProfile> baseProfiles = parseJsonData(baseMeasure.get());
  97. detectNewOrUpdatedProfiles(projectComponent, baseProfiles, rawProfiles);
  98. detectNoMoreUsedProfiles(projectComponent, baseProfiles);
  99. }
  100. private static Map<String, QualityProfile> parseJsonData(Measure measure) {
  101. String data = measure.getStringValue();
  102. if (data == null) {
  103. return Collections.emptyMap();
  104. }
  105. return QPMeasureData.fromJson(data).getProfilesByKey();
  106. }
  107. private void detectNoMoreUsedProfiles(Component context, Map<String, QualityProfile> baseProfiles) {
  108. for (QualityProfile baseProfile : baseProfiles.values()) {
  109. if (qProfileStatusRepository.get(baseProfile.getQpKey()).filter(REMOVED::equals).isPresent()) {
  110. markAsRemoved(context, baseProfile);
  111. }
  112. }
  113. }
  114. private void detectNewOrUpdatedProfiles(Component component, Map<String, QualityProfile> baseProfiles, Map<String, QualityProfile> rawProfiles) {
  115. for (QualityProfile profile : rawProfiles.values()) {
  116. qProfileStatusRepository.get(profile.getQpKey()).ifPresent(status -> {
  117. if (status.equals(ADDED)) {
  118. markAsAdded(component, profile);
  119. } else if (status.equals(UPDATED)) {
  120. markAsChanged(component, baseProfiles.get(profile.getQpKey()), profile);
  121. }
  122. });
  123. }
  124. }
  125. private void markAsChanged(Component component, QualityProfile baseProfile, QualityProfile profile) {
  126. Date from = baseProfile.getRulesUpdatedAt();
  127. String data = KeyValueFormat.format(ImmutableSortedMap.of(
  128. "key", profile.getQpKey(),
  129. "from", UtcDateUtils.formatDateTime(fixDate(from)),
  130. "to", UtcDateUtils.formatDateTime(fixDate(profile.getRulesUpdatedAt()))));
  131. eventRepository.add(component, createQProfileEvent(profile, "Changes in %s", data));
  132. }
  133. private void markAsRemoved(Component component, QualityProfile profile) {
  134. eventRepository.add(component, createQProfileEvent(profile, "Stop using %s"));
  135. }
  136. private void markAsAdded(Component component, QualityProfile profile) {
  137. eventRepository.add(component, createQProfileEvent(profile, "Use %s"));
  138. }
  139. private Event createQProfileEvent(QualityProfile profile, String namePattern) {
  140. return createQProfileEvent(profile, namePattern, null);
  141. }
  142. private Event createQProfileEvent(QualityProfile profile, String namePattern, @Nullable String data) {
  143. return Event.createProfile(String.format(namePattern, profileLabel(profile)), data, null);
  144. }
  145. private String profileLabel(QualityProfile profile) {
  146. Optional<Language> language = languageRepository.find(profile.getLanguageKey());
  147. String languageName = language.isPresent() ? language.get().getName() : profile.getLanguageKey();
  148. return String.format("'%s' (%s)", profile.getQpName(), languageName);
  149. }
  150. /**
  151. * This hack must be done because date precision is millisecond in db/es and date format is select only
  152. */
  153. private static Date fixDate(Date date) {
  154. return DateUtils.addSeconds(date, 1);
  155. }
  156. @Override
  157. public String getDescription() {
  158. return "Generate Quality profile events";
  159. }
  160. }