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 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
|
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.coverageoutputgenerator;
import static com.google.devtools.coverageoutputgenerator.Constants.CC_EXTENSIONS;
import static com.google.devtools.coverageoutputgenerator.Constants.GCOV_EXTENSION;
import static com.google.devtools.coverageoutputgenerator.Constants.GCOV_JSON_EXTENSION;
import static com.google.devtools.coverageoutputgenerator.Constants.PROFDATA_EXTENSION;
import static com.google.devtools.coverageoutputgenerator.Constants.TRACEFILE_EXTENSION;
import static java.lang.Math.max;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/** Command line utility to convert raw coverage files to lcov (text) format. */
public class Main {
private static final Logger logger = Logger.getLogger(Main.class.getName());
public static void main(String... args) {
try {
int exitCode = runWithArgs(args);
System.exit(exitCode);
} catch (Exception e) {
logger.log(Level.SEVERE, "Unhandled exception on lcov tool: " + e.getMessage(), e);
System.exit(1);
}
}
static int runWithArgs(String... args) throws ExecutionException, InterruptedException {
LcovMergerFlags flags = null;
try {
flags = LcovMergerFlags.parseFlags(args);
} catch (IllegalArgumentException e) {
logger.log(Level.SEVERE, e.getMessage());
return 1;
}
File outputFile = new File(flags.outputFile());
List<File> filesInCoverageDir =
flags.coverageDir() != null
? getCoverageFilesInDir(flags.coverageDir())
: Collections.emptyList();
Coverage coverage =
Coverage.merge(
parseFiles(
getTracefiles(flags, filesInCoverageDir),
LcovParser::parse,
flags.parseParallelism()),
parseFiles(
getGcovInfoFiles(filesInCoverageDir), GcovParser::parse, flags.parseParallelism()),
parseFiles(
getGcovJsonInfoFiles(filesInCoverageDir),
GcovJsonParser::parse,
flags.parseParallelism()));
if (flags.sourcesToReplaceFile() != null) {
coverage.maybeReplaceSourceFileNames(getMapFromFile(flags.sourcesToReplaceFile()));
}
File profdataFile = getProfdataFileOrNull(filesInCoverageDir);
if (coverage.isEmpty()) {
int exitStatus = 0;
if (profdataFile == null) {
try {
logger.log(Level.WARNING, "There was no coverage found.");
if (!Files.exists(outputFile.toPath())) {
Files.createFile(outputFile.toPath()); // Generate empty declared output
}
exitStatus = 0;
} catch (IOException e) {
logger.log(
Level.SEVERE,
"Could not create empty output file "
+ outputFile.getName()
+ " due to: "
+ e.getMessage());
exitStatus = 1;
}
} else {
// Bazel doesn't support yet converting profdata files to lcov. We still want to output a
// coverage report so we copy the content of the profdata file to the output file. This is
// not ideal but it unblocks some Bazel C++
// coverage users.
// TODO(#5881): Add support for profdata files.
try {
Files.copy(profdataFile.toPath(), outputFile.toPath(), REPLACE_EXISTING);
} catch (IOException e) {
logger.log(
Level.SEVERE,
"Could not copy file "
+ profdataFile.getName()
+ " to output file "
+ outputFile.getName()
+ " due to: "
+ e.getMessage());
exitStatus = 1;
}
}
return exitStatus;
}
if (!coverage.isEmpty() && profdataFile != null) {
// If there is one profdata file then there can't be other types of reports because there is
// no way to merge them.
// TODO(#5881): Add support for profdata files.
logger.log(
Level.WARNING,
"Bazel doesn't support LLVM profdata coverage amongst other coverage formats.");
return 0;
}
if (!flags.filterSources().isEmpty()) {
coverage = Coverage.filterOutMatchingSources(coverage, flags.filterSources());
}
if (flags.hasSourceFileManifest()) {
// The source file manifest is only required for C++ code coverage.
Set<String> ccSources = getCcSourcesFromSourceFileManifest(flags.sourceFileManifest());
if (!ccSources.isEmpty()) {
// Only filter out coverage if there were C++ sources found in the coverage manifest.
coverage = Coverage.getOnlyTheseCcSources(coverage, ccSources);
}
}
if (coverage.isEmpty()) {
try {
logger.log(Level.WARNING, "There was no coverage found.");
if (!Files.exists(outputFile.toPath())) {
Files.createFile(outputFile.toPath()); // Generate empty declared output
}
return 0;
} catch (IOException e) {
logger.log(
Level.SEVERE,
"Could not create empty output file "
+ outputFile.getName()
+ " due to: "
+ e.getMessage());
return 1;
}
}
int exitStatus = 0;
try {
LcovPrinter.print(new FileOutputStream(outputFile), coverage);
} catch (IOException e) {
logger.log(
Level.SEVERE,
"Could not write to output file " + outputFile + " due to " + e.getMessage());
exitStatus = 1;
}
return exitStatus;
}
/**
* Returns a set of source file names from the given manifest.
*
* <p>The manifest contains file names line by line. Each file can either be a source file (e.g.
* .java, .cc) or a coverage metadata file (e.g. .gcno, .em).
*
* <p>This method only returns the C++ source files, ignoring the other files as they are not
* necessary when putting together the final coverage report.
*/
private static Set<String> getCcSourcesFromSourceFileManifest(String sourceFileManifest) {
Set<String> sourceFiles = new HashSet<>();
try (FileInputStream inputStream = new FileInputStream(new File(sourceFileManifest));
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, UTF_8);
BufferedReader reader = new BufferedReader(inputStreamReader)) {
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
if (!isMetadataFile(line) && isCcFile(line)) {
sourceFiles.add(line);
}
}
} catch (IOException e) {
logger.log(Level.SEVERE, "Error reading file " + sourceFileManifest + ": " + e.getMessage());
}
return sourceFiles;
}
private static boolean isMetadataFile(String filename) {
return filename.endsWith(".gcno") || filename.endsWith(".em");
}
private static boolean isCcFile(String filename) {
for (String ccExtension : CC_EXTENSIONS) {
if (filename.endsWith(ccExtension)) {
return true;
}
}
return false;
}
private static List<File> getGcovInfoFiles(List<File> filesInCoverageDir) {
List<File> gcovFiles = getFilesWithExtension(filesInCoverageDir, GCOV_EXTENSION);
if (gcovFiles.isEmpty()) {
logger.log(Level.INFO, "No gcov info file found.");
} else {
logger.log(Level.INFO, "Found " + gcovFiles.size() + " gcov info files.");
}
return gcovFiles;
}
private static List<File> getGcovJsonInfoFiles(List<File> filesInCoverageDir) {
List<File> gcovJsonFiles = getFilesWithExtension(filesInCoverageDir, GCOV_JSON_EXTENSION);
if (gcovJsonFiles.isEmpty()) {
logger.log(Level.INFO, "No gcov json file found.");
} else {
logger.log(Level.INFO, "Found " + gcovJsonFiles.size() + " gcov json files.");
}
return gcovJsonFiles;
}
/**
* Returns a .profdata file from the given files or null if none or more profdata files were
* found.
*/
private static File getProfdataFileOrNull(List<File> files) {
List<File> profdataFiles = getFilesWithExtension(files, PROFDATA_EXTENSION);
if (profdataFiles.isEmpty()) {
logger.log(Level.INFO, "No .profdata file found.");
return null;
}
if (profdataFiles.size() > 1) {
logger.log(
Level.SEVERE,
"Bazel currently supports only one profdata file per test. "
+ profdataFiles.size()
+ " .profadata files were found instead.");
return null;
}
logger.log(Level.INFO, "Found one .profdata file.");
return profdataFiles.get(0);
}
private static List<File> getTracefiles(LcovMergerFlags flags, List<File> filesInCoverageDir) {
List<File> lcovTracefiles = new ArrayList<>();
if (flags.reportsFile() != null) {
lcovTracefiles = getTracefilesFromFile(flags.reportsFile());
} else if (flags.coverageDir() != null) {
lcovTracefiles = getFilesWithExtension(filesInCoverageDir, TRACEFILE_EXTENSION);
}
if (lcovTracefiles.isEmpty()) {
logger.log(Level.INFO, "No lcov file found.");
} else {
logger.log(Level.INFO, "Found " + lcovTracefiles.size() + " tracefiles.");
}
return lcovTracefiles;
}
/**
* Reads the content of the given file and returns a matching map.
*
* <p>It assumes the file contains lines in the form key:value. For each line it creates an entry
* in the map with the corresponding key and value.
*/
private static ImmutableMap<String, String> getMapFromFile(String file) {
ImmutableMap.Builder<String, String> mapBuilder = ImmutableMap.builder();
try (FileInputStream inputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, UTF_8);
BufferedReader reader = new BufferedReader(inputStreamReader)) {
for (String keyToValueLine = reader.readLine();
keyToValueLine != null;
keyToValueLine = reader.readLine()) {
String[] keyAndValue = keyToValueLine.split(":");
if (keyAndValue.length == 2) {
mapBuilder.put(keyAndValue[0], keyAndValue[1]);
}
}
} catch (IOException e) {
logger.log(Level.SEVERE, "Error reading file " + file + ": " + e.getMessage());
}
return mapBuilder.build();
}
static Coverage parseFiles(List<File> files, Parser parser, int parallelism)
throws ExecutionException, InterruptedException {
if (parallelism == 1) {
return parseFilesSequentially(files, parser);
} else {
return parseFilesInParallel(files, parser, parallelism);
}
}
static Coverage parseFilesSequentially(List<File> files, Parser parser) {
Coverage coverage = new Coverage();
for (File file : files) {
try {
logger.log(Level.INFO, "Parsing file " + file);
List<SourceFileCoverage> sourceFilesCoverage = parser.parse(new FileInputStream(file));
for (SourceFileCoverage sourceFileCoverage : sourceFilesCoverage) {
coverage.add(sourceFileCoverage);
}
} catch (IOException e) {
logger.log(
Level.SEVERE,
"File " + file.getAbsolutePath() + " could not be parsed due to: " + e.getMessage(),
e);
System.exit(1);
}
}
return coverage;
}
static Coverage parseFilesInParallel(List<File> files, Parser parser, int parallelism)
throws ExecutionException, InterruptedException {
ForkJoinPool pool = new ForkJoinPool(parallelism);
int partitionSize = max(1, files.size() / parallelism);
List<List<File>> partitions = Lists.partition(files, partitionSize);
return pool.submit(
() ->
partitions.parallelStream()
.map((p) -> parseFilesSequentially(p, parser))
.reduce((c1, c2) -> Coverage.merge(c1, c2))
.orElse(Coverage.create()))
.get();
}
/**
* Returns a list of all the files with the given extension found recursively under the given dir.
*/
@VisibleForTesting
static List<File> getCoverageFilesInDir(String dir) {
List<File> files = new ArrayList<>();
try (Stream<Path> stream = Files.walk(Paths.get(dir))) {
files =
stream
.filter(
p ->
p.toString().endsWith(TRACEFILE_EXTENSION)
|| p.toString().endsWith(GCOV_EXTENSION)
|| p.toString().endsWith(GCOV_JSON_EXTENSION)
|| p.toString().endsWith(PROFDATA_EXTENSION))
.map(path -> path.toFile())
.collect(Collectors.toList());
} catch (IOException ex) {
logger.log(Level.SEVERE, "Error reading folder " + dir + ": " + ex.getMessage());
}
return files;
}
static List<File> getFilesWithExtension(List<File> files, String extension) {
return files.stream()
.filter(file -> file.toString().endsWith(extension))
.collect(Collectors.toList());
}
static List<File> getTracefilesFromFile(String reportsFile) {
List<File> datFiles = new ArrayList<>();
try (FileInputStream inputStream = new FileInputStream(reportsFile)) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, UTF_8);
BufferedReader reader = new BufferedReader(inputStreamReader);
for (String tracefile = reader.readLine(); tracefile != null; tracefile = reader.readLine()) {
// TODO(elenairina): baseline coverage contains some file names that need to be modified
if (!tracefile.endsWith("baseline_coverage.dat")) {
datFiles.add(new File(tracefile));
}
}
} catch (IOException e) {
logger.log(Level.SEVERE, "Error reading file " + reportsFile + ": " + e.getMessage());
}
return datFiles;
}
}
|