3 * Copyright (C) 2009-2023 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.qualitymodel;
23 import java.util.Optional;
25 import java.util.stream.Collectors;
26 import org.sonar.api.measures.CoreMetrics;
27 import org.sonar.api.utils.KeyValueFormat;
28 import org.sonar.api.utils.log.Logger;
29 import org.sonar.api.utils.log.Loggers;
30 import org.sonar.ce.task.projectanalysis.component.Component;
31 import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
32 import org.sonar.ce.task.projectanalysis.component.PathAwareVisitorAdapter;
33 import org.sonar.ce.task.projectanalysis.formula.counter.LongValue;
34 import org.sonar.ce.task.projectanalysis.issue.IntegrateIssuesVisitor;
35 import org.sonar.ce.task.projectanalysis.measure.Measure;
36 import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
37 import org.sonar.ce.task.projectanalysis.metric.Metric;
38 import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
39 import org.sonar.ce.task.projectanalysis.source.NewLinesRepository;
41 import static org.sonar.api.measures.CoreMetrics.NCLOC_DATA_KEY;
42 import static org.sonar.api.measures.CoreMetrics.NEW_DEVELOPMENT_COST_KEY;
43 import static org.sonar.api.measures.CoreMetrics.NEW_MAINTAINABILITY_RATING_KEY;
44 import static org.sonar.api.measures.CoreMetrics.NEW_SQALE_DEBT_RATIO_KEY;
45 import static org.sonar.api.measures.CoreMetrics.NEW_TECHNICAL_DEBT_KEY;
46 import static org.sonar.api.utils.KeyValueFormat.newIntegerConverter;
47 import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER;
48 import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder;
51 * This visitor depends on {@link IntegrateIssuesVisitor} for the computation of
52 * metric {@link CoreMetrics#NEW_TECHNICAL_DEBT}.
53 * Compute following measure :
54 * {@link CoreMetrics#NEW_SQALE_DEBT_RATIO_KEY}
55 * {@link CoreMetrics#NEW_MAINTAINABILITY_RATING_KEY}
57 public class NewMaintainabilityMeasuresVisitor extends PathAwareVisitorAdapter<NewMaintainabilityMeasuresVisitor.Counter> {
58 private static final Logger LOG = Loggers.get(NewMaintainabilityMeasuresVisitor.class);
60 private final MeasureRepository measureRepository;
61 private final NewLinesRepository newLinesRepository;
62 private final RatingSettings ratingSettings;
64 private final Metric newDebtMetric;
65 private final Metric nclocDataMetric;
67 private final Metric newDevelopmentCostMetric;
68 private final Metric newDebtRatioMetric;
69 private final Metric newMaintainabilityRatingMetric;
71 public NewMaintainabilityMeasuresVisitor(MetricRepository metricRepository, MeasureRepository measureRepository, NewLinesRepository newLinesRepository,
72 RatingSettings ratingSettings) {
73 super(CrawlerDepthLimit.FILE, POST_ORDER, CounterFactory.INSTANCE);
74 this.measureRepository = measureRepository;
75 this.newLinesRepository = newLinesRepository;
76 this.ratingSettings = ratingSettings;
78 // computed by NewDebtAggregator which is executed by IntegrateIssuesVisitor
79 this.newDebtMetric = metricRepository.getByKey(NEW_TECHNICAL_DEBT_KEY);
80 // which line is ncloc and which isn't
81 this.nclocDataMetric = metricRepository.getByKey(NCLOC_DATA_KEY);
84 this.newDevelopmentCostMetric = metricRepository.getByKey(NEW_DEVELOPMENT_COST_KEY);
85 this.newDebtRatioMetric = metricRepository.getByKey(NEW_SQALE_DEBT_RATIO_KEY);
86 this.newMaintainabilityRatingMetric = metricRepository.getByKey(NEW_MAINTAINABILITY_RATING_KEY);
90 public void visitProject(Component project, Path<Counter> path) {
91 computeAndSaveNewDebtRatioMeasure(project, path);
95 public void visitDirectory(Component directory, Path<Counter> path) {
96 computeAndSaveNewDebtRatioMeasure(directory, path);
97 increaseNewDebtAndDevCostOfParent(path);
101 public void visitFile(Component file, Path<Counter> path) {
102 initNewDebtRatioCounter(file, path);
103 computeAndSaveNewDebtRatioMeasure(file, path);
104 increaseNewDebtAndDevCostOfParent(path);
107 private void computeAndSaveNewDebtRatioMeasure(Component component, Path<Counter> path) {
108 if (!newLinesRepository.newLinesAvailable()) {
111 double density = computeDensity(path.current());
112 double newDebtRatio = 100.0 * density;
113 int newMaintainability = ratingSettings.getDebtRatingGrid().getRatingForDensity(density).getIndex();
114 float newDevelopmentCost = path.current().getDevCost().getValue();
115 measureRepository.add(component, this.newDevelopmentCostMetric, newMeasureBuilder().create(newDevelopmentCost));
116 measureRepository.add(component, this.newDebtRatioMetric, newMeasureBuilder().create(newDebtRatio));
117 measureRepository.add(component, this.newMaintainabilityRatingMetric, newMeasureBuilder().create(newMaintainability));
120 private static double computeDensity(Counter counter) {
121 LongValue newDebt = counter.getNewDebt();
122 if (newDebt.isSet()) {
123 long developmentCost = counter.getDevCost().getValue();
124 if (developmentCost != 0L) {
125 return newDebt.getValue() / (double) developmentCost;
131 private static long getLongValue(Optional<Measure> measure) {
132 return measure.map(NewMaintainabilityMeasuresVisitor::getLongValue).orElse(0L);
135 private static long getLongValue(Measure measure) {
136 return measure.getLongValue();
139 private void initNewDebtRatioCounter(Component file, Path<Counter> path) {
140 // first analysis, no period, no differential value to compute, save processing time and return now
141 if (!newLinesRepository.newLinesAvailable()) {
145 Optional<Set<Integer>> changedLines = newLinesRepository.getNewLines(file);
147 if (!changedLines.isPresent()) {
148 LOG.trace(String.format("No information about changed lines is available for file '%s'. Dev cost will be zero.", file.getKey()));
152 Optional<Measure> nclocDataMeasure = measureRepository.getRawMeasure(file, this.nclocDataMetric);
153 if (!nclocDataMeasure.isPresent()) {
157 initNewDebtRatioCounter(path.current(), file, nclocDataMeasure.get(), changedLines.get());
160 private void initNewDebtRatioCounter(Counter devCostCounter, Component file, Measure nclocDataMeasure, Set<Integer> changedLines) {
161 boolean hasDevCost = false;
163 long lineDevCost = ratingSettings.getDevCost(file.getFileAttributes().getLanguageKey());
164 for (Integer nclocLineIndex : nclocLineIndexes(nclocDataMeasure)) {
165 if (changedLines.contains(nclocLineIndex)) {
166 devCostCounter.incrementDevCost(lineDevCost);
171 long newDebt = getLongValue(measureRepository.getRawMeasure(file, this.newDebtMetric));
172 devCostCounter.incrementNewDebt(newDebt);
176 private static void increaseNewDebtAndDevCostOfParent(Path<Counter> path) {
177 path.parent().add(path.current());
181 * NCLOC_DATA contains Key-value pairs, where key - is a number of line, and value - is an indicator of whether line
182 * contains code (1) or not (0).
183 * This method parses the value of the NCLOC_DATA measure and return the line numbers of lines which contain code.
185 private static Iterable<Integer> nclocLineIndexes(Measure nclocDataMeasure) {
186 Map<Integer, Integer> parsedNclocData = KeyValueFormat.parse(nclocDataMeasure.getData(), newIntegerConverter(), newIntegerConverter());
187 return parsedNclocData.entrySet()
189 .filter(entry -> entry.getValue() == 1)
190 .map(Map.Entry::getKey)
191 .collect(Collectors.toList());
194 public static final class Counter {
195 private final LongValue newDebt = new LongValue();
196 private final LongValue devCost = new LongValue();
198 public void add(Counter counter) {
199 this.newDebt.increment(counter.newDebt);
200 this.devCost.increment(counter.devCost);
203 LongValue incrementNewDebt(long value) {
204 return newDebt.increment(value);
207 LongValue incrementDevCost(long value) {
208 return devCost.increment(value);
211 LongValue getNewDebt() {
215 LongValue getDevCost() {
220 private static class CounterFactory extends SimpleStackElementFactory<Counter> {
221 public static final CounterFactory INSTANCE = new CounterFactory();
224 public Counter createForAny(Component component) {
225 return new Counter();