/
LCOVParser.java
229 lines (194 loc) · 7.79 KB
/
LCOVParser.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
/*
* SonarQube JavaScript Plugin
* Copyright (C) 2011-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plugins.javascript.lcov;
import com.google.common.base.MoreObjects;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.CheckForNull;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.coverage.NewCoverage;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
/**
* http://ltp.sourceforge.net/coverage/lcov/geninfo.1.php
*/
public final class LCOVParser {
private static final String SF = "SF:";
private static final String DA = "DA:";
private static final String BRDA = "BRDA:";
private final Map<InputFile, NewCoverage> coverageByFile;
private final SensorContext context;
private final List<String> unresolvedPaths = Lists.newArrayList();
private static final Logger LOG = Loggers.get(LCOVParser.class);
private LCOVParser(List<String> lines, SensorContext context) {
this.context = context;
this.coverageByFile = parse(lines);
}
static LCOVParser create(SensorContext context, File... files) {
final List<String> lines=new LinkedList<>();
for(File file: files) {
try (Stream<String> fileLines = Files.lines(file.toPath())){
lines.addAll(fileLines.collect(Collectors.toList()));
} catch (IOException e) {
throw new IllegalArgumentException("Could not read content from file: " + file, e);
}
}
return new LCOVParser(lines, context);
}
Map<InputFile, NewCoverage> coverageByFile() {
return coverageByFile;
}
List<String> unresolvedPaths() {
return unresolvedPaths;
}
private Map<InputFile, NewCoverage> parse(List<String> lines) {
final Map<InputFile, FileData> files = Maps.newHashMap();
FileData fileData = null;
int reportLineNum = 0;
for (String line : lines) {
reportLineNum++;
if (line.startsWith(SF)) {
fileData = loadCurrentFileData(files, line);
} else if (fileData != null) {
if (line.startsWith(DA)) {
parseLineCoverage(fileData, reportLineNum, line);
} else if (line.startsWith(BRDA)) {
parseBranchCoverage(fileData, reportLineNum, line);
}
}
}
Map<InputFile, NewCoverage> coveredFiles = Maps.newHashMap();
for (Map.Entry<InputFile, FileData> e : files.entrySet()) {
NewCoverage newCoverage = context.newCoverage().onFile(e.getKey());
e.getValue().save(newCoverage);
coveredFiles.put(e.getKey(), newCoverage);
}
return coveredFiles;
}
private static void parseBranchCoverage(FileData fileData, int reportLineNum, String line) {
try {
// BRDA:<line number>,<block number>,<branch number>,<taken>
String[] tokens = line.substring(BRDA.length()).trim().split(",");
String lineNumber = tokens[0];
String branchNumber = tokens[1] + tokens[2];
String taken = tokens[3];
fileData.addBranch(Integer.valueOf(lineNumber), branchNumber, "-".equals(taken) ? 0 : Integer.valueOf(taken));
} catch (Exception e) {
logWrongDataWarning("BRDA", reportLineNum, e);
}
}
private static void parseLineCoverage(FileData fileData, int reportLineNum, String line) {
try {
// DA:<line number>,<execution count>[,<checksum>]
String execution = line.substring(DA.length());
String executionCount = execution.substring(execution.indexOf(',') + 1);
String lineNumber = execution.substring(0, execution.indexOf(','));
fileData.addLine(Integer.valueOf(lineNumber), Integer.valueOf(executionCount));
} catch (Exception e) {
logWrongDataWarning("DA", reportLineNum, e);
}
}
private static void logWrongDataWarning(String dataType, int reportLineNum, Exception e) {
LOG.warn(String.format("Problem during processing LCOV report: can't save %s data for line %s of coverage report file (%s).", dataType, reportLineNum, e.toString()));
}
@CheckForNull
private FileData loadCurrentFileData(final Map<InputFile, FileData> files, String line) {
// SF:<absolute path to the source file>
String filePath = line.substring(SF.length());
FileData fileData = null;
// some tools (like Istanbul, Karma) provide relative paths, so let's consider them relative to project directory
InputFile inputFile = context.fileSystem().inputFile(context.fileSystem().predicates().hasPath(filePath));
if (inputFile != null) {
fileData = files.get(inputFile);
if (fileData == null) {
fileData = new FileData(inputFile);
files.put(inputFile, fileData);
}
} else {
unresolvedPaths.add(filePath);
}
return fileData;
}
private static class FileData {
/**
* line number -> branch number -> taken
*/
private Map<Integer, Map<String, Integer>> branches = Maps.newHashMap();
/**
* line number -> execution count
*/
private Map<Integer, Integer> hits = Maps.newHashMap();
/**
* Number of lines in the file
* Required to check if line exist in a file, see {@link #checkLine(Integer)}
*/
private final int linesInFile;
private final String filename;
private static final String WRONG_LINE_EXCEPTION_MESSAGE = "Line with number %s doesn't belong to file %s";
FileData(InputFile inputFile) {
linesInFile = inputFile.lines();
filename = inputFile.relativePath();
}
void addBranch(Integer lineNumber, String branchNumber, Integer taken) {
checkLine(lineNumber);
Map<String, Integer> branchesForLine = branches.get(lineNumber);
if (branchesForLine == null) {
branchesForLine = Maps.newHashMap();
branches.put(lineNumber, branchesForLine);
}
Integer currentValue = branchesForLine.get(branchNumber);
branchesForLine.put(branchNumber, MoreObjects.firstNonNull(currentValue, 0) + taken);
}
void addLine(Integer lineNumber, Integer executionCount) {
checkLine(lineNumber);
Integer currentValue = hits.get(lineNumber);
hits.put(lineNumber, MoreObjects.firstNonNull(currentValue, 0) + executionCount);
}
void save(NewCoverage newCoverage) {
for (Map.Entry<Integer, Integer> e : hits.entrySet()) {
newCoverage.lineHits(e.getKey(), e.getValue());
}
for (Map.Entry<Integer, Map<String, Integer>> e : branches.entrySet()) {
int conditions = e.getValue().size();
int covered = 0;
for (Integer taken : e.getValue().values()) {
if (taken > 0) {
covered++;
}
}
newCoverage.conditions(e.getKey(), conditions, covered);
}
}
private void checkLine(Integer lineNumber) {
if (lineNumber < 1 || lineNumber > linesInFile) {
throw new IllegalArgumentException(String.format(WRONG_LINE_EXCEPTION_MESSAGE, lineNumber, filename));
}
}
}
}