3 * Copyright (C) 2009-2016 SonarSource SA
4 * mailto:contact 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.server.computation.task.projectanalysis.qualitymodel;
22 import com.google.common.base.Optional;
24 import java.util.stream.Collectors;
25 import org.sonar.api.measures.CoreMetrics;
26 import org.sonar.api.utils.KeyValueFormat;
27 import org.sonar.api.utils.log.Logger;
28 import org.sonar.api.utils.log.Loggers;
29 import org.sonar.server.computation.task.projectanalysis.component.Component;
30 import org.sonar.server.computation.task.projectanalysis.component.CrawlerDepthLimit;
31 import org.sonar.server.computation.task.projectanalysis.component.PathAwareVisitorAdapter;
32 import org.sonar.server.computation.task.projectanalysis.formula.counter.LongValue;
33 import org.sonar.server.computation.task.projectanalysis.issue.IntegrateIssuesVisitor;
34 import org.sonar.server.computation.task.projectanalysis.measure.Measure;
35 import org.sonar.server.computation.task.projectanalysis.measure.MeasureRepository;
36 import org.sonar.server.computation.task.projectanalysis.metric.Metric;
37 import org.sonar.server.computation.task.projectanalysis.metric.MetricRepository;
38 import org.sonar.server.computation.task.projectanalysis.period.Period;
39 import org.sonar.server.computation.task.projectanalysis.period.PeriodsHolder;
40 import org.sonar.server.computation.task.projectanalysis.scm.Changeset;
41 import org.sonar.server.computation.task.projectanalysis.scm.ScmInfo;
42 import org.sonar.server.computation.task.projectanalysis.scm.ScmInfoRepository;
44 import static org.sonar.api.measures.CoreMetrics.NCLOC_DATA_KEY;
45 import static org.sonar.api.measures.CoreMetrics.NEW_MAINTAINABILITY_RATING_KEY;
46 import static org.sonar.api.measures.CoreMetrics.NEW_SQALE_DEBT_RATIO_KEY;
47 import static org.sonar.api.measures.CoreMetrics.NEW_TECHNICAL_DEBT_KEY;
48 import static org.sonar.api.utils.KeyValueFormat.newIntegerConverter;
49 import static org.sonar.server.computation.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER;
50 import static org.sonar.server.computation.task.projectanalysis.measure.Measure.newMeasureBuilder;
53 * This visitor depends on {@link IntegrateIssuesVisitor} for the computation of
54 * metric {@link CoreMetrics#NEW_TECHNICAL_DEBT}.
56 * Compute following measure :
57 * {@link CoreMetrics#NEW_SQALE_DEBT_RATIO_KEY}
58 * {@link CoreMetrics#NEW_MAINTAINABILITY_RATING_KEY}
60 public class NewMaintainabilityMeasuresVisitor extends PathAwareVisitorAdapter<NewMaintainabilityMeasuresVisitor.Counter> {
61 private static final Logger LOG = Loggers.get(NewMaintainabilityMeasuresVisitor.class);
63 private final ScmInfoRepository scmInfoRepository;
64 private final MeasureRepository measureRepository;
65 private final PeriodsHolder periodsHolder;
66 private final RatingSettings ratingSettings;
67 private final RatingGrid ratingGrid;
69 private final Metric newDebtMetric;
70 private final Metric nclocDataMetric;
72 private final Metric newDebtRatioMetric;
73 private final Metric newMaintainabilityRatingMetric;
75 public NewMaintainabilityMeasuresVisitor(MetricRepository metricRepository, MeasureRepository measureRepository, ScmInfoRepository scmInfoRepository,
76 PeriodsHolder periodsHolder, RatingSettings ratingSettings) {
77 super(CrawlerDepthLimit.FILE, POST_ORDER, CounterFactory.INSTANCE);
78 this.measureRepository = measureRepository;
79 this.scmInfoRepository = scmInfoRepository;
80 this.periodsHolder = periodsHolder;
81 this.ratingSettings = ratingSettings;
82 this.ratingGrid = ratingSettings.getRatingGrid();
84 // computed by NewDebtAggregator which is executed by IntegrateIssuesVisitor
85 this.newDebtMetric = metricRepository.getByKey(NEW_TECHNICAL_DEBT_KEY);
86 // which line is ncloc and which isn't
87 this.nclocDataMetric = metricRepository.getByKey(NCLOC_DATA_KEY);
90 this.newDebtRatioMetric = metricRepository.getByKey(NEW_SQALE_DEBT_RATIO_KEY);
91 this.newMaintainabilityRatingMetric = metricRepository.getByKey(NEW_MAINTAINABILITY_RATING_KEY);
95 public void visitProject(Component project, Path<Counter> path) {
96 computeAndSaveNewDebtRatioMeasure(project, path);
100 public void visitModule(Component module, Path<Counter> path) {
101 computeAndSaveNewDebtRatioMeasure(module, path);
102 increaseNewDebtAndDevCostOfParent(path);
106 public void visitDirectory(Component directory, Path<Counter> path) {
107 computeAndSaveNewDebtRatioMeasure(directory, path);
108 increaseNewDebtAndDevCostOfParent(path);
112 public void visitFile(Component file, Path<Counter> path) {
113 initNewDebtRatioCounter(file, path);
114 computeAndSaveNewDebtRatioMeasure(file, path);
115 increaseNewDebtAndDevCostOfParent(path);
118 private void computeAndSaveNewDebtRatioMeasure(Component component, Path<Counter> path) {
119 if (!periodsHolder.hasPeriod()) {
122 double density = computeDensity(path.current());
123 double newDebtRatio = 100.0 * density;
124 double newMaintainability = ratingGrid.getRatingForDensity(density).getIndex();
125 measureRepository.add(component, this.newDebtRatioMetric, newMeasureBuilder().setVariation(newDebtRatio).createNoValue());
126 measureRepository.add(component, this.newMaintainabilityRatingMetric, newMeasureBuilder().setVariation(newMaintainability).createNoValue());
129 private static double computeDensity(Counter counter) {
130 LongValue newDebt = counter.getNewDebt();
131 if (newDebt.isSet()) {
132 long developmentCost = counter.getDevCost().getValue();
133 if (developmentCost != 0L) {
134 return newDebt.getValue() / (double) developmentCost;
140 private static long getLongValue(Optional<Measure> measure) {
141 if (!measure.isPresent()) {
144 return getLongValue(measure.get());
147 private static long getLongValue(Measure measure) {
148 if (measure.hasVariation()) {
149 return (long) measure.getVariation();
154 private void initNewDebtRatioCounter(Component file, Path<Counter> path) {
155 // first analysis, no period, no differential value to compute, save processing time and return now
156 if (!periodsHolder.hasPeriod()) {
160 Optional<Measure> nclocDataMeasure = measureRepository.getRawMeasure(file, this.nclocDataMetric);
161 if (!nclocDataMeasure.isPresent()) {
165 Optional<ScmInfo> scmInfoOptional = scmInfoRepository.getScmInfo(file);
166 if (!scmInfoOptional.isPresent()) {
167 LOG.trace(String.format("No changeset for file %s. Dev cost will be zero.", file.getKey()));
171 ScmInfo scmInfo = scmInfoOptional.get();
172 initNewDebtRatioCounter(path.current(), file, nclocDataMeasure.get(), scmInfo);
175 private void initNewDebtRatioCounter(Counter devCostCounter, Component file, Measure nclocDataMeasure, ScmInfo scmInfo) {
176 boolean hasDevCost = false;
178 long lineDevCost = ratingSettings.getDevCost(file.getFileAttributes().getLanguageKey());
179 for (Integer nclocLineIndex : nclocLineIndexes(nclocDataMeasure)) {
180 Changeset changeset = scmInfo.getChangesetForLine(nclocLineIndex);
181 Period period = periodsHolder.getPeriod();
182 if (isLineInPeriod(changeset.getDate(), period)) {
183 devCostCounter.incrementDevCost(lineDevCost);
188 long newDebt = getLongValue(measureRepository.getRawMeasure(file, this.newDebtMetric));
189 devCostCounter.incrementNewDebt(newDebt);
193 private static void increaseNewDebtAndDevCostOfParent(Path<Counter> path) {
194 path.parent().add(path.current());
198 * A line belongs to a Period if its date is older than the SNAPSHOT's date of the period.
200 private static boolean isLineInPeriod(long lineDate, Period period) {
201 return lineDate > period.getSnapshotDate();
205 * NCLOC_DATA contains Key-value pairs, where key - is a number of line, and value - is an indicator of whether line
206 * contains code (1) or not (0).
208 * This method parses the value of the NCLOC_DATA measure and return the line numbers of lines which contain code.
210 private static Iterable<Integer> nclocLineIndexes(Measure nclocDataMeasure) {
211 Map<Integer, Integer> parsedNclocData = KeyValueFormat.parse(nclocDataMeasure.getData(), newIntegerConverter(), newIntegerConverter());
212 return parsedNclocData.entrySet()
214 .filter(entry -> entry.getValue() == 1)
215 .map(Map.Entry::getKey)
216 .collect(Collectors.toList());
219 public static final class Counter {
220 private final LongValue newDebt = new LongValue();
221 private final LongValue devCost = new LongValue();
223 public void add(Counter counter) {
224 this.newDebt.increment(counter.newDebt);
225 this.devCost.increment(counter.devCost);
228 LongValue incrementNewDebt(long value) {
229 return newDebt.increment(value);
232 LongValue incrementDevCost(long value) {
233 return devCost.increment(value);
236 LongValue getNewDebt() {
240 LongValue getDevCost() {
245 private static class CounterFactory extends SimpleStackElementFactory<Counter> {
246 public static final CounterFactory INSTANCE = new CounterFactory();
249 public Counter createForAny(Component component) {
250 return new Counter();