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.duplication;
22 import com.google.common.collect.ImmutableList;
23 import java.util.Arrays;
24 import java.util.HashSet;
25 import java.util.Optional;
27 import javax.annotation.CheckForNull;
28 import javax.annotation.Nullable;
29 import org.sonar.ce.task.projectanalysis.component.Component;
30 import org.sonar.ce.task.projectanalysis.component.PathAwareCrawler;
31 import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
32 import org.sonar.ce.task.projectanalysis.formula.Counter;
33 import org.sonar.ce.task.projectanalysis.formula.CounterInitializationContext;
34 import org.sonar.ce.task.projectanalysis.formula.CreateMeasureContext;
35 import org.sonar.ce.task.projectanalysis.formula.Formula;
36 import org.sonar.ce.task.projectanalysis.formula.FormulaExecutorComponentVisitor;
37 import org.sonar.ce.task.projectanalysis.measure.Measure;
38 import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
39 import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
41 import static com.google.common.collect.Iterables.isEmpty;
42 import static java.util.Objects.requireNonNull;
43 import static org.sonar.api.measures.CoreMetrics.DUPLICATED_BLOCKS_KEY;
44 import static org.sonar.api.measures.CoreMetrics.DUPLICATED_FILES_KEY;
45 import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES_DENSITY_KEY;
46 import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES_KEY;
47 import static org.sonar.api.measures.CoreMetrics.LINES_KEY;
49 public class DuplicationMeasures {
50 protected final ImmutableList<Formula> formulas;
51 protected final TreeRootHolder treeRootHolder;
52 protected final MetricRepository metricRepository;
53 protected final MeasureRepository measureRepository;
54 private final DuplicationRepository duplicationRepository;
56 public DuplicationMeasures(TreeRootHolder treeRootHolder, MetricRepository metricRepository, MeasureRepository measureRepository,
57 @Nullable DuplicationRepository duplicationRepository) {
58 this.treeRootHolder = treeRootHolder;
59 this.metricRepository = metricRepository;
60 this.measureRepository = measureRepository;
61 // will be null for views
62 this.duplicationRepository = duplicationRepository;
63 this.formulas = ImmutableList.of(new DuplicationFormula());
67 * Constructor used by Pico in Views where no DuplicationRepository is available.
69 public DuplicationMeasures(TreeRootHolder treeRootHolder, MetricRepository metricRepository, MeasureRepository measureRepository) {
70 this(treeRootHolder, metricRepository, measureRepository, null);
73 public void execute() {
74 new PathAwareCrawler<>(
75 FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository).buildFor(formulas))
76 .visit(treeRootHolder.getReportTreeRoot());
79 protected DuplicationCounter createCounter() {
80 return new DuplicationCounter(duplicationRepository);
83 protected static class DuplicationCounter implements Counter<DuplicationCounter> {
85 private final DuplicationRepository duplicationRepository;
86 protected int fileCount = 0;
87 protected int blockCount = 0;
88 protected int dupLineCount = 0;
89 protected int lineCount = 0;
91 private DuplicationCounter(@Nullable DuplicationRepository duplicationRepository) {
92 this.duplicationRepository = duplicationRepository;
96 public void aggregate(DuplicationCounter counter) {
97 this.fileCount += counter.fileCount;
98 this.blockCount += counter.blockCount;
99 this.dupLineCount += counter.dupLineCount;
100 this.lineCount += counter.lineCount;
104 public void initialize(CounterInitializationContext context) {
105 Component leaf = context.getLeaf();
106 if (leaf.getType() == Component.Type.FILE && !leaf.getFileAttributes().isUnitTest()) {
107 initializeForFile(leaf);
108 } else if (leaf.getType() == Component.Type.PROJECT_VIEW) {
109 initializeForProjectView(context);
113 protected void initializeForFile(Component file) {
114 // don't use measure since it won't be available for some files in the report tree in PRs
115 this.lineCount = file.getFileAttributes().getLines();
116 Iterable<Duplication> duplications = requireNonNull(this.duplicationRepository, "DuplicationRepository missing")
117 .getDuplications(file);
118 if (isEmpty(duplications)) {
122 // use a set to count lines only once
123 Set<Integer> duplicatedLineNumbers = new HashSet<>();
125 for (Duplication duplication : duplications) {
127 addLines(duplication.getOriginal(), duplicatedLineNumbers);
128 InnerDuplicate[] innerDuplicates = Arrays.stream(duplication.getDuplicates())
129 .filter(x -> x instanceof InnerDuplicate)
130 .map(d -> (InnerDuplicate) d)
131 .toArray(InnerDuplicate[]::new);
133 for (InnerDuplicate innerDuplicate : innerDuplicates) {
135 addLines(innerDuplicate.getTextBlock(), duplicatedLineNumbers);
140 this.blockCount += blocks;
141 this.dupLineCount += duplicatedLineNumbers.size();
145 private static void addLines(TextBlock textBlock, Set<Integer> duplicatedLineNumbers) {
146 for (int i = textBlock.getStart(); i <= textBlock.getEnd(); i++) {
147 duplicatedLineNumbers.add(i);
151 private void initializeForProjectView(CounterInitializationContext context) {
152 fileCount += getMeasure(context, DUPLICATED_FILES_KEY);
153 blockCount += getMeasure(context, DUPLICATED_BLOCKS_KEY);
154 dupLineCount += getMeasure(context, DUPLICATED_LINES_KEY);
155 lineCount += getMeasure(context, LINES_KEY);
158 private static int getMeasure(CounterInitializationContext context, String metricKey) {
159 Optional<Measure> files = context.getMeasure(metricKey);
160 return files.map(Measure::getIntValue).orElse(0);
164 private final class DuplicationFormula implements Formula<DuplicationCounter> {
166 public DuplicationCounter createNewCounter() {
167 return createCounter();
171 public Optional<Measure> createMeasure(DuplicationCounter counter, CreateMeasureContext context) {
172 switch (context.getMetric().getKey()) {
173 case DUPLICATED_FILES_KEY:
174 return Optional.of(Measure.newMeasureBuilder().create(counter.fileCount));
175 case DUPLICATED_LINES_KEY:
176 return Optional.of(Measure.newMeasureBuilder().create(counter.dupLineCount));
177 case DUPLICATED_LINES_DENSITY_KEY:
178 return createDuplicatedLinesDensityMeasure(counter, context);
179 case DUPLICATED_BLOCKS_KEY:
180 return Optional.of(Measure.newMeasureBuilder().create(counter.blockCount));
182 throw new IllegalArgumentException("Unsupported metric " + context.getMetric());
186 private Optional<Measure> createDuplicatedLinesDensityMeasure(DuplicationCounter counter, CreateMeasureContext context) {
187 int duplicatedLines = counter.dupLineCount;
188 int nbLines = counter.lineCount;
190 double density = Math.min(100.0, 100.0 * duplicatedLines / nbLines);
191 return Optional.of(Measure.newMeasureBuilder().create(density, context.getMetric().getDecimalScale()));
193 return Optional.empty();
197 public String[] getOutputMetricKeys() {
198 return new String[] {DUPLICATED_FILES_KEY, DUPLICATED_LINES_KEY, DUPLICATED_LINES_DENSITY_KEY, DUPLICATED_BLOCKS_KEY};