coverage.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. #!/usr/bin/env python3
  2. #
  3. # Parse and report coverage info from .info files generated by lcov
  4. #
  5. import os
  6. import glob
  7. import csv
  8. import re
  9. import collections as co
  10. import bisect as b
  11. INFO_PATHS = ['tests/*.toml.info']
  12. def collect(paths, **args):
  13. file = None
  14. funcs = []
  15. lines = co.defaultdict(lambda: 0)
  16. pattern = re.compile(
  17. '^(?P<file>SF:/?(?P<file_name>.*))$'
  18. '|^(?P<func>FN:(?P<func_lineno>[0-9]*),(?P<func_name>.*))$'
  19. '|^(?P<line>DA:(?P<line_lineno>[0-9]*),(?P<line_hits>[0-9]*))$')
  20. for path in paths:
  21. with open(path) as f:
  22. for line in f:
  23. m = pattern.match(line)
  24. if m and m.group('file'):
  25. file = m.group('file_name')
  26. elif m and file and m.group('func'):
  27. funcs.append((file, int(m.group('func_lineno')),
  28. m.group('func_name')))
  29. elif m and file and m.group('line'):
  30. lines[(file, int(m.group('line_lineno')))] += (
  31. int(m.group('line_hits')))
  32. # map line numbers to functions
  33. funcs.sort()
  34. def func_from_lineno(file, lineno):
  35. i = b.bisect(funcs, (file, lineno))
  36. if i and funcs[i-1][0] == file:
  37. return funcs[i-1][2]
  38. else:
  39. return None
  40. # reduce to function info
  41. reduced_funcs = co.defaultdict(lambda: (0, 0))
  42. for (file, line_lineno), line_hits in lines.items():
  43. func = func_from_lineno(file, line_lineno)
  44. if not func:
  45. continue
  46. hits, count = reduced_funcs[(file, func)]
  47. reduced_funcs[(file, func)] = (hits + (line_hits > 0), count + 1)
  48. results = []
  49. for (file, func), (hits, count) in reduced_funcs.items():
  50. # discard internal/testing functions (test_* injected with
  51. # internal testing)
  52. if not args.get('everything'):
  53. if func.startswith('__') or func.startswith('test_'):
  54. continue
  55. # discard .8449 suffixes created by optimizer
  56. func = re.sub('\.[0-9]+', '', func)
  57. results.append((file, func, hits, count))
  58. return results
  59. def main(**args):
  60. # find coverage
  61. if not args.get('use'):
  62. # find *.info files
  63. paths = []
  64. for path in args['info_paths']:
  65. if os.path.isdir(path):
  66. path = path + '/*.gcov'
  67. for path in glob.glob(path):
  68. paths.append(path)
  69. if not paths:
  70. print('no .info files found in %r?' % args['info_paths'])
  71. sys.exit(-1)
  72. results = collect(paths, **args)
  73. else:
  74. with open(args['use']) as f:
  75. r = csv.DictReader(f)
  76. results = [
  77. ( result['file'],
  78. result['function'],
  79. int(result['coverage_hits']),
  80. int(result['coverage_count']))
  81. for result in r]
  82. total_hits, total_count = 0, 0
  83. for _, _, hits, count in results:
  84. total_hits += hits
  85. total_count += count
  86. # find previous results?
  87. if args.get('diff'):
  88. try:
  89. with open(args['diff']) as f:
  90. r = csv.DictReader(f)
  91. prev_results = [
  92. ( result['file'],
  93. result['function'],
  94. int(result['coverage_hits']),
  95. int(result['coverage_count']))
  96. for result in r]
  97. except FileNotFoundError:
  98. prev_results = []
  99. prev_total_hits, prev_total_count = 0, 0
  100. for _, _, hits, count in prev_results:
  101. prev_total_hits += hits
  102. prev_total_count += count
  103. # write results to CSV
  104. if args.get('output'):
  105. with open(args['output'], 'w') as f:
  106. w = csv.writer(f)
  107. w.writerow(['file', 'function', 'coverage_hits', 'coverage_count'])
  108. for file, func, hits, count in sorted(results):
  109. w.writerow((file, func, hits, count))
  110. # print results
  111. def dedup_entries(results, by='function'):
  112. entries = co.defaultdict(lambda: (0, 0))
  113. for file, func, hits, count in results:
  114. entry = (file if by == 'file' else func)
  115. entry_hits, entry_count = entries[entry]
  116. entries[entry] = (entry_hits + hits, entry_count + count)
  117. return entries
  118. def diff_entries(olds, news):
  119. diff = co.defaultdict(lambda: (0, 0, 0, 0, 0, 0, 0))
  120. for name, (new_hits, new_count) in news.items():
  121. diff[name] = (
  122. 0, 0,
  123. new_hits, new_count,
  124. new_hits, new_count,
  125. (new_hits/new_count if new_count else 1.0) - 1.0)
  126. for name, (old_hits, old_count) in olds.items():
  127. _, _, new_hits, new_count, _, _, _ = diff[name]
  128. diff[name] = (
  129. old_hits, old_count,
  130. new_hits, new_count,
  131. new_hits-old_hits, new_count-old_count,
  132. ((new_hits/new_count if new_count else 1.0)
  133. - (old_hits/old_count if old_count else 1.0)))
  134. return diff
  135. def sorted_entries(entries):
  136. if args.get('coverage_sort'):
  137. return sorted(entries, key=lambda x: (-(x[1][0]/x[1][1] if x[1][1] else -1), x))
  138. elif args.get('reverse_coverage_sort'):
  139. return sorted(entries, key=lambda x: (+(x[1][0]/x[1][1] if x[1][1] else -1), x))
  140. else:
  141. return sorted(entries)
  142. def sorted_diff_entries(entries):
  143. if args.get('coverage_sort'):
  144. return sorted(entries, key=lambda x: (-(x[1][2]/x[1][3] if x[1][3] else -1), x))
  145. elif args.get('reverse_coverage_sort'):
  146. return sorted(entries, key=lambda x: (+(x[1][2]/x[1][3] if x[1][3] else -1), x))
  147. else:
  148. return sorted(entries, key=lambda x: (-x[1][6], x))
  149. def print_header(by=''):
  150. if not args.get('diff'):
  151. print('%-36s %19s' % (by, 'hits/line'))
  152. else:
  153. print('%-36s %19s %19s %11s' % (by, 'old', 'new', 'diff'))
  154. def print_entry(name, hits, count):
  155. print("%-36s %11s %7s" % (name,
  156. '%d/%d' % (hits, count)
  157. if count else '-',
  158. '%.1f%%' % (100*hits/count)
  159. if count else '-'))
  160. def print_diff_entry(name,
  161. old_hits, old_count,
  162. new_hits, new_count,
  163. diff_hits, diff_count,
  164. ratio):
  165. print("%-36s %11s %7s %11s %7s %11s%s" % (name,
  166. '%d/%d' % (old_hits, old_count)
  167. if old_count else '-',
  168. '%.1f%%' % (100*old_hits/old_count)
  169. if old_count else '-',
  170. '%d/%d' % (new_hits, new_count)
  171. if new_count else '-',
  172. '%.1f%%' % (100*new_hits/new_count)
  173. if new_count else '-',
  174. '%+d/%+d' % (diff_hits, diff_count),
  175. ' (%+.1f%%)' % (100*ratio) if ratio else ''))
  176. def print_entries(by='function'):
  177. entries = dedup_entries(results, by=by)
  178. if not args.get('diff'):
  179. print_header(by=by)
  180. for name, (hits, count) in sorted_entries(entries.items()):
  181. print_entry(name, hits, count)
  182. else:
  183. prev_entries = dedup_entries(prev_results, by=by)
  184. diff = diff_entries(prev_entries, entries)
  185. print_header(by='%s (%d added, %d removed)' % (by,
  186. sum(1 for _, old, _, _, _, _, _ in diff.values() if not old),
  187. sum(1 for _, _, _, new, _, _, _ in diff.values() if not new)))
  188. for name, (
  189. old_hits, old_count,
  190. new_hits, new_count,
  191. diff_hits, diff_count, ratio) in sorted_diff_entries(
  192. diff.items()):
  193. if ratio or args.get('all'):
  194. print_diff_entry(name,
  195. old_hits, old_count,
  196. new_hits, new_count,
  197. diff_hits, diff_count,
  198. ratio)
  199. def print_totals():
  200. if not args.get('diff'):
  201. print_entry('TOTAL', total_hits, total_count)
  202. else:
  203. ratio = ((total_hits/total_count
  204. if total_count else 1.0)
  205. - (prev_total_hits/prev_total_count
  206. if prev_total_count else 1.0))
  207. print_diff_entry('TOTAL',
  208. prev_total_hits, prev_total_count,
  209. total_hits, total_count,
  210. total_hits-prev_total_hits, total_count-prev_total_count,
  211. ratio)
  212. if args.get('quiet'):
  213. pass
  214. elif args.get('summary'):
  215. print_header()
  216. print_totals()
  217. elif args.get('files'):
  218. print_entries(by='file')
  219. print_totals()
  220. else:
  221. print_entries(by='function')
  222. print_totals()
  223. if __name__ == "__main__":
  224. import argparse
  225. import sys
  226. parser = argparse.ArgumentParser(
  227. description="Parse and report coverage info from .info files \
  228. generated by lcov")
  229. parser.add_argument('info_paths', nargs='*', default=INFO_PATHS,
  230. help="Description of where to find *.info files. May be a directory \
  231. or list of paths. *.info files will be merged to show the total \
  232. coverage. Defaults to %r." % INFO_PATHS)
  233. parser.add_argument('-v', '--verbose', action='store_true',
  234. help="Output commands that run behind the scenes.")
  235. parser.add_argument('-o', '--output',
  236. help="Specify CSV file to store results.")
  237. parser.add_argument('-u', '--use',
  238. help="Don't do any work, instead use this CSV file.")
  239. parser.add_argument('-d', '--diff',
  240. help="Specify CSV file to diff code size against.")
  241. parser.add_argument('-a', '--all', action='store_true',
  242. help="Show all functions, not just the ones that changed.")
  243. parser.add_argument('-A', '--everything', action='store_true',
  244. help="Include builtin and libc specific symbols.")
  245. parser.add_argument('-s', '--coverage-sort', action='store_true',
  246. help="Sort by coverage.")
  247. parser.add_argument('-S', '--reverse-coverage-sort', action='store_true',
  248. help="Sort by coverage, but backwards.")
  249. parser.add_argument('--files', action='store_true',
  250. help="Show file-level coverage.")
  251. parser.add_argument('--summary', action='store_true',
  252. help="Only show the total coverage.")
  253. parser.add_argument('-q', '--quiet', action='store_true',
  254. help="Don't show anything, useful with -o.")
  255. parser.add_argument('--build-dir',
  256. help="Specify the relative build directory. Used to map object files \
  257. to the correct source files.")
  258. sys.exit(main(**vars(parser.parse_args())))