]> source.dussan.org Git - sonarqube.git/blob
f29477995f37a10c1c380f388f6c5f532626631f
[sonarqube.git] /
1 /*
2  * SonarQube
3  * Copyright (C) 2009-2019 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.duplication;
21
22 import com.google.common.collect.ImmutableList;
23 import java.util.HashSet;
24 import java.util.Optional;
25 import java.util.Set;
26 import javax.annotation.CheckForNull;
27 import javax.annotation.Nullable;
28 import org.sonar.ce.task.projectanalysis.component.Component;
29 import org.sonar.ce.task.projectanalysis.component.PathAwareCrawler;
30 import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
31 import org.sonar.ce.task.projectanalysis.formula.Counter;
32 import org.sonar.ce.task.projectanalysis.formula.CounterInitializationContext;
33 import org.sonar.ce.task.projectanalysis.formula.CreateMeasureContext;
34 import org.sonar.ce.task.projectanalysis.formula.Formula;
35 import org.sonar.ce.task.projectanalysis.formula.FormulaExecutorComponentVisitor;
36 import org.sonar.ce.task.projectanalysis.measure.Measure;
37 import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
38 import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
39
40 import static com.google.common.collect.FluentIterable.from;
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;
48
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;
55
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());
64   }
65
66   /**
67    * Constructor used by Pico in Views where no DuplicationRepository is available.
68    */
69   public DuplicationMeasures(TreeRootHolder treeRootHolder, MetricRepository metricRepository, MeasureRepository measureRepository) {
70     this(treeRootHolder, metricRepository, measureRepository, null);
71   }
72
73   public void execute() {
74     new PathAwareCrawler<>(
75       FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository).buildFor(formulas))
76       .visit(treeRootHolder.getReportTreeRoot());
77   }
78
79   protected DuplicationCounter createCounter() {
80     return new DuplicationCounter(duplicationRepository);
81   }
82
83   protected static class DuplicationCounter implements Counter<DuplicationCounter> {
84     @CheckForNull
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;
90
91     protected DuplicationCounter() {
92       this(null);
93     }
94
95     private DuplicationCounter(@Nullable DuplicationRepository duplicationRepository) {
96       this.duplicationRepository = duplicationRepository;
97     }
98
99     @Override
100     public void aggregate(DuplicationCounter counter) {
101       this.fileCount += counter.fileCount;
102       this.blockCount += counter.blockCount;
103       this.dupLineCount += counter.dupLineCount;
104       this.lineCount += counter.lineCount;
105     }
106
107     @Override
108     public void initialize(CounterInitializationContext context) {
109       Component leaf = context.getLeaf();
110       if (leaf.getType() == Component.Type.FILE) {
111         initializeForFile(leaf);
112       } else if (leaf.getType() == Component.Type.PROJECT_VIEW) {
113         initializeForProjectView(context);
114       }
115     }
116
117     protected void initializeForFile(Component file) {
118       // don't use measure since it won't be available for some files in the report tree in SLB
119       this.lineCount = file.getFileAttributes().getLines();
120       Iterable<Duplication> duplications = requireNonNull(this.duplicationRepository, "DuplicationRepository missing")
121         .getDuplications(file);
122       if (isEmpty(duplications)) {
123         return;
124       }
125
126       // use a set to count lines only once
127       Set<Integer> duplicatedLineNumbers = new HashSet<>();
128       int blocks = 0;
129       for (Duplication duplication : duplications) {
130         blocks++;
131         addLines(duplication.getOriginal(), duplicatedLineNumbers);
132         for (InnerDuplicate innerDuplicate : from(duplication.getDuplicates()).filter(InnerDuplicate.class)) {
133           blocks++;
134           addLines(innerDuplicate.getTextBlock(), duplicatedLineNumbers);
135         }
136       }
137
138       this.fileCount += 1;
139       this.blockCount += blocks;
140       this.dupLineCount += duplicatedLineNumbers.size();
141
142     }
143
144     private static void addLines(TextBlock textBlock, Set<Integer> duplicatedLineNumbers) {
145       for (int i = textBlock.getStart(); i <= textBlock.getEnd(); i++) {
146         duplicatedLineNumbers.add(i);
147       }
148     }
149
150     private void initializeForProjectView(CounterInitializationContext context) {
151       fileCount += getMeasure(context, DUPLICATED_FILES_KEY);
152       blockCount += getMeasure(context, DUPLICATED_BLOCKS_KEY);
153       dupLineCount += getMeasure(context, DUPLICATED_LINES_KEY);
154       lineCount += getMeasure(context, LINES_KEY);
155     }
156
157     private static int getMeasure(CounterInitializationContext context, String metricKey) {
158       Optional<Measure> files = context.getMeasure(metricKey);
159       return files.map(Measure::getIntValue).orElse(0);
160     }
161   }
162
163   private final class DuplicationFormula implements Formula<DuplicationCounter> {
164     @Override
165     public DuplicationCounter createNewCounter() {
166       return createCounter();
167     }
168
169     @Override
170     public Optional<Measure> createMeasure(DuplicationCounter counter, CreateMeasureContext context) {
171       switch (context.getMetric().getKey()) {
172         case DUPLICATED_FILES_KEY:
173           return Optional.of(Measure.newMeasureBuilder().create(counter.fileCount));
174         case DUPLICATED_LINES_KEY:
175           return Optional.of(Measure.newMeasureBuilder().create(counter.dupLineCount));
176         case DUPLICATED_LINES_DENSITY_KEY:
177           return createDuplicatedLinesDensityMeasure(counter, context);
178         case DUPLICATED_BLOCKS_KEY:
179           return Optional.of(Measure.newMeasureBuilder().create(counter.blockCount));
180         default:
181           throw new IllegalArgumentException("Unsupported metric " + context.getMetric());
182       }
183     }
184
185     private Optional<Measure> createDuplicatedLinesDensityMeasure(DuplicationCounter counter, CreateMeasureContext context) {
186       int duplicatedLines = counter.dupLineCount;
187       int nbLines = counter.lineCount;
188       if (nbLines > 0) {
189         double density = Math.min(100.0, 100.0 * duplicatedLines / nbLines);
190         return Optional.of(Measure.newMeasureBuilder().create(density, context.getMetric().getDecimalScale()));
191       }
192       return Optional.empty();
193     }
194
195     @Override
196     public String[] getOutputMetricKeys() {
197       return new String[] {DUPLICATED_FILES_KEY, DUPLICATED_LINES_KEY, DUPLICATED_LINES_DENSITY_KEY, DUPLICATED_BLOCKS_KEY};
198     }
199   }
200 }