| 1 |
#!/usr/bin/env python3 |
| 2 |
""" |
| 3 |
Script to save coverage info for C source files in JSON for coveralls.io |
| 4 |
|
| 5 |
When C code compiled with --coverage flag, for each object files *.gcno is |
| 6 |
generated, it contains information to reconstruct the basic block graphs and |
| 7 |
assign source line numbers to blocks |
| 8 |
|
| 9 |
When binary executed *.gcda file is written on exit, with same base name as |
| 10 |
corresponding *.gcno file. It contains some summary information, counters, e.t.c. |
| 11 |
|
| 12 |
gcov(1) utility can be used to get information from *.gcda file and write text |
| 13 |
reports to *.gocov file (one file for each source file from which object was compiled). |
| 14 |
|
| 15 |
The script finds *.gcno files, uses gcov to generate *.gcov files, parses them |
| 16 |
and accumulates statistics for all source files. |
| 17 |
|
| 18 |
This script was written with quite a few assumptions: |
| 19 |
|
| 20 |
* Code was build using absolute path to source directory (and absolute path |
| 21 |
stored in object file debug symbols). |
| 22 |
|
| 23 |
* Current directory is writable and there is no useful *.gcov files in it |
| 24 |
(because they will be deleted). |
| 25 |
|
| 26 |
* Object file has same base name as *.gcno file (e. g. foo.c.gcno and foo.c.o). |
| 27 |
This is the case for cmake builds, but probably not for other build systems |
| 28 |
|
| 29 |
* Source file names contain only ASCII characters. |
| 30 |
""" |
| 31 |
|
| 32 |
import argparse |
| 33 |
from collections import defaultdict |
| 34 |
from glob import glob |
| 35 |
import hashlib |
| 36 |
import json |
| 37 |
import os |
| 38 |
from os.path import isabs, join, normpath, relpath |
| 39 |
import os.path |
| 40 |
import subprocess |
| 41 |
import sys |
| 42 |
|
| 43 |
|
| 44 |
def warn(*args, **kwargs): |
| 45 |
print(*args, file=sys.stderr, **kwargs) |
| 46 |
|
| 47 |
|
| 48 |
def parse_gcov_file(gcov_file): |
| 49 |
"""Parses the content of .gcov file written by gcov -i |
| 50 |
|
| 51 |
Returns: |
| 52 |
str: Source file name |
| 53 |
dict: coverage info { line_number: hits } |
| 54 |
""" |
| 55 |
count = {} |
| 56 |
with open(gcov_file) as fh: |
| 57 |
for line in fh: |
| 58 |
tag, value = line.split(':') |
| 59 |
if tag == 'file': |
| 60 |
src_file = value.rstrip() |
| 61 |
elif tag == 'lcount': |
| 62 |
line_num, exec_count = value.split(',') |
| 63 |
count[int(line_num)] = int(exec_count) |
| 64 |
|
| 65 |
return src_file, count |
| 66 |
|
| 67 |
|
| 68 |
def run_gcov(filename, coverage, args): |
| 69 |
""" * run gcov on given file |
| 70 |
* parse generated .gcov files and update coverage structure |
| 71 |
* store source file md5 (if not yet stored) |
| 72 |
* delete .gcov files |
| 73 |
""" |
| 74 |
if args.verbose: |
| 75 |
warn("calling:", 'gcov', '-i', filename) |
| 76 |
stdout = None |
| 77 |
else: |
| 78 |
# gcov is noisy and don't have quit flag so redirect stdout to /dev/null |
| 79 |
stdout = subprocess.DEVNULL |
| 80 |
|
| 81 |
subprocess.check_call(['gcov', '-i', filename], stdout=stdout) |
| 82 |
|
| 83 |
for gcov_file in glob('*.gcov'): |
| 84 |
if args.verbose: |
| 85 |
warn('parsing', gcov_file) |
| 86 |
src_file, count = parse_gcov_file(gcov_file) |
| 87 |
os.remove(gcov_file) |
| 88 |
|
| 89 |
if src_file not in coverage: |
| 90 |
coverage[src_file] = defaultdict(int, count) |
| 91 |
else: |
| 92 |
# sum execution counts |
| 93 |
for line, exe_cnt in count.items(): |
| 94 |
coverage[src_file][line] += exe_cnt |
| 95 |
|
| 96 |
|
| 97 |
def main(): |
| 98 |
parser = argparse.ArgumentParser( |
| 99 |
description='Save gcov coverage results in JSON file for coveralls.io.') |
| 100 |
parser.add_argument( |
| 101 |
'-v', |
| 102 |
'--verbose', |
| 103 |
action="store_true", |
| 104 |
help='Display additional information and gcov command output.') |
| 105 |
parser.add_argument( |
| 106 |
'-e', |
| 107 |
'--exclude', |
| 108 |
action='append', |
| 109 |
metavar='DIR', |
| 110 |
help= |
| 111 |
("Don't look for .gcno/.gcda files in this directories (repeat option to skip several directories). " |
| 112 |
"Path is relative to the directory where script was started, e. g. '.git'")) |
| 113 |
parser.add_argument( |
| 114 |
'-p', |
| 115 |
'--prefix', |
| 116 |
action='append', |
| 117 |
help= |
| 118 |
("Strip this prefix from absolute path to source file. " |
| 119 |
"If this option is provided, then only files with given prefixes in absolute path " |
| 120 |
"will be added to coverage (option can be repeated).")) |
| 121 |
parser.add_argument( |
| 122 |
'--out', |
| 123 |
type=argparse.FileType('w'), |
| 124 |
required=True, |
| 125 |
metavar='FILE', |
| 126 |
help='Save JSON payload to this file') |
| 127 |
args = parser.parse_args() |
| 128 |
|
| 129 |
# ensure that there is no unrelated .gcov files in current directory |
| 130 |
for gcov_file in glob('*.gcov'): |
| 131 |
os.remove(gcov_file) |
| 132 |
warn("Warning: {} deleted".format(gcov_file)) |
| 133 |
|
| 134 |
# dict { src_file_name: {line1: exec_count1, line2: exec_count2, ...} } |
| 135 |
coverage = {} |
| 136 |
|
| 137 |
# find . -name '*.gcno' (respecting args.exclude) |
| 138 |
for root, dirs, files in os.walk('.'): |
| 139 |
for f in files: |
| 140 |
# Usually gcov called with a source file as an argument, but this |
| 141 |
# name used only to find .gcno and .gcda files. To find source |
| 142 |
# file information from debug symbols is used. So we can call gcov |
| 143 |
# on .gcno file. |
| 144 |
if f.endswith('.gcno'): |
| 145 |
run_gcov(join(root, f), coverage, args) |
| 146 |
|
| 147 |
# don't look into excluded dirs |
| 148 |
for subdir in dirs: |
| 149 |
# path relative to start dir |
| 150 |
path = normpath(join(root, subdir)) |
| 151 |
if path in args.exclude: |
| 152 |
if args.verbose: |
| 153 |
warn('directory "{}" excluded'.format(path)) |
| 154 |
dirs.remove(subdir) |
| 155 |
|
| 156 |
# prepare JSON pyload for coveralls.io API |
| 157 |
# https://docs.coveralls.io/api-introduction |
| 158 |
coveralls_data = {'source_files': []} |
| 159 |
|
| 160 |
for src_file in coverage: |
| 161 |
# filter by prefix and save path with stripped prefix |
| 162 |
src_file_rel = src_file |
| 163 |
if args.prefix and isabs(src_file): |
| 164 |
for prefix in args.prefix: |
| 165 |
if src_file.startswith(prefix): |
| 166 |
src_file_rel = relpath(src_file, start=prefix) |
| 167 |
break |
| 168 |
else: |
| 169 |
# skip file outside given prefixes |
| 170 |
# it can be e. g. library include file |
| 171 |
if args.verbose: |
| 172 |
warn('file "{}" is not matched by prefix, skipping'.format(src_file)) |
| 173 |
continue |
| 174 |
|
| 175 |
try: |
| 176 |
with open(src_file, mode='rb') as fh: |
| 177 |
line_count = sum(1 for _ in fh) |
| 178 |
fh.seek(0) |
| 179 |
md5 = hashlib.md5(fh.read()).hexdigest() |
| 180 |
except OSError as err: |
| 181 |
# skip files for which source file is not available |
| 182 |
warn(err, 'not adding to coverage') |
| 183 |
continue |
| 184 |
|
| 185 |
coverage_array = [None] * line_count |
| 186 |
|
| 187 |
for line_num, exe_cnt in coverage[src_file].items(): |
| 188 |
# item at index 0 representing the coverage for line 1 of the source code |
| 189 |
assert 1 <= line_num <= line_count |
| 190 |
coverage_array[line_num - 1] = exe_cnt |
| 191 |
|
| 192 |
coveralls_data['source_files'].append({ |
| 193 |
'name': src_file_rel, |
| 194 |
'coverage': coverage_array, |
| 195 |
'source_digest': md5 |
| 196 |
}) |
| 197 |
|
| 198 |
args.out.write(json.dumps(coveralls_data)) |
| 199 |
|
| 200 |
if args.verbose: |
| 201 |
warn('Coverage for {} source files was written'.format( |
| 202 |
len(coveralls_data['source_files']))) |
| 203 |
|
| 204 |
|
| 205 |
if __name__ == '__main__': |
| 206 |
main() |