coverage-info.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. import argparse
  2. import os
  3. import sys
  4. import tarfile
  5. import collections
  6. import subprocess
  7. import re
  8. GCDA_EXT = '.gcda'
  9. GCNO_EXT = '.gcno'
  10. def suffixes(path):
  11. """
  12. >>> list(suffixes('/a/b/c'))
  13. ['c', 'b/c', '/a/b/c']
  14. >>> list(suffixes('/a/b/c/'))
  15. ['c', 'b/c', '/a/b/c']
  16. >>> list(suffixes('/a'))
  17. ['/a']
  18. >>> list(suffixes('/a/'))
  19. ['/a']
  20. >>> list(suffixes('/'))
  21. []
  22. """
  23. path = os.path.normpath(path)
  24. def up_dirs(cur_path):
  25. while os.path.dirname(cur_path) != cur_path:
  26. cur_path = os.path.dirname(cur_path)
  27. yield cur_path
  28. for x in up_dirs(path):
  29. yield path.replace(x + os.path.sep, '')
  30. def recast(in_file, out_file, probe_path, update_stat):
  31. PREFIX = 'SF:'
  32. probed_path = None
  33. any_payload = False
  34. with open(in_file, 'r') as input, open(out_file, 'w') as output:
  35. active = True
  36. for line in input:
  37. line = line.rstrip('\n')
  38. if line.startswith('TN:'):
  39. output.write(line + '\n')
  40. elif line.startswith(PREFIX):
  41. path = line[len(PREFIX):]
  42. probed_path = probe_path(path)
  43. if probed_path:
  44. output.write(PREFIX + probed_path + '\n')
  45. active = bool(probed_path)
  46. else:
  47. if active:
  48. update_stat(probed_path, line)
  49. output.write(line + '\n')
  50. any_payload = True
  51. return any_payload
  52. def print_stat(da, fnda, teamcity_stat_output):
  53. lines_hit = sum(map(bool, da.values()))
  54. lines_total = len(da.values())
  55. lines_coverage = 100.0 * lines_hit / lines_total if lines_total else 0
  56. func_hit = sum(map(bool, fnda.values()))
  57. func_total = len(fnda.values())
  58. func_coverage = 100.0 * func_hit / func_total if func_total else 0
  59. print >>sys.stderr, '[[imp]]Lines[[rst]] {: >16} {: >16} {: >16.1f}%'.format(lines_hit, lines_total, lines_coverage)
  60. print >>sys.stderr, '[[imp]]Functions[[rst]] {: >16} {: >16} {: >16.1f}%'.format(func_hit, func_total, func_coverage)
  61. if teamcity_stat_output:
  62. with open(teamcity_stat_output, 'w') as tc_file:
  63. tc_file.write("##teamcity[blockOpened name='Code Coverage Summary']\n")
  64. tc_file.write("##teamcity[buildStatisticValue key=\'CodeCoverageAbsLTotal\' value='{}']\n".format(lines_total))
  65. tc_file.write("##teamcity[buildStatisticValue key=\'CodeCoverageAbsLCovered\' value='{}']\n".format(lines_hit))
  66. tc_file.write("##teamcity[buildStatisticValue key=\'CodeCoverageAbsMTotal\' value='{}']\n".format(func_total))
  67. tc_file.write("##teamcity[buildStatisticValue key=\'CodeCoverageAbsMCovered\' value='{}']\n".format(func_hit))
  68. tc_file.write("##teamcity[blockClosed name='Code Coverage Summary']\n")
  69. def chunks(l, n):
  70. """
  71. >>> list(chunks(range(10), 3))
  72. [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
  73. >>> list(chunks(range(10), 5))
  74. [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
  75. """
  76. for i in xrange(0, len(l), n):
  77. yield l[i:i + n]
  78. def combine_info_files(lcov, files, out_file):
  79. chunk_size = 50
  80. files = list(set(files))
  81. for chunk in chunks(files, chunk_size):
  82. combine_cmd = [lcov]
  83. if os.path.exists(out_file):
  84. chunk.append(out_file)
  85. for trace in chunk:
  86. assert os.path.exists(trace), "Trace file does not exist: {} (cwd={})".format(trace, os.getcwd())
  87. combine_cmd += ["-a", os.path.abspath(trace)]
  88. print >>sys.stderr, '## lcov', ' '.join(combine_cmd[1:])
  89. out_file_tmp = "combined.tmp"
  90. with open(out_file_tmp, "w") as stdout:
  91. subprocess.check_call(combine_cmd, stdout=stdout)
  92. if os.path.exists(out_file):
  93. os.remove(out_file)
  94. os.rename(out_file_tmp, out_file)
  95. def probe_path_global(path, source_root, prefix_filter, exclude_files):
  96. if path.endswith('_ut.cpp'):
  97. return None
  98. for suff in reversed(list(suffixes(path))):
  99. if (not prefix_filter or suff.startswith(prefix_filter)) and (not exclude_files or not exclude_files.match(suff)):
  100. full_path = source_root + os.sep + suff
  101. if os.path.isfile(full_path):
  102. return full_path
  103. return None
  104. def update_stat_global(src_file, line, fnda, da):
  105. if line.startswith("FNDA:"):
  106. visits, func_name = line[len("FNDA:"):].split(',')
  107. fnda[src_file + func_name] += int(visits)
  108. if line.startswith("DA"):
  109. line_number, visits = line[len("DA:"):].split(',')
  110. if visits == '=====':
  111. visits = 0
  112. da[src_file + line_number] += int(visits)
  113. def gen_info_global(cmd, cov_info, probe_path, update_stat, lcov_args):
  114. print >>sys.stderr, '## geninfo', ' '.join(cmd)
  115. subprocess.check_call(cmd)
  116. if recast(cov_info + '.tmp', cov_info, probe_path, update_stat):
  117. lcov_args.append(cov_info)
  118. def init_all_coverage_files(gcno_archive, fname2gcno, fname2info, geninfo_executable, gcov_tool, gen_info, prefix_filter, exclude_files):
  119. with tarfile.open(gcno_archive) as gcno_tf:
  120. for gcno_item in gcno_tf:
  121. if gcno_item.isfile() and gcno_item.name.endswith(GCNO_EXT):
  122. gcno_tf.extract(gcno_item)
  123. gcno_name = gcno_item.name
  124. source_fname = gcno_name[:-len(GCNO_EXT)]
  125. if prefix_filter and not source_fname.startswith(prefix_filter):
  126. sys.stderr.write("Skipping {} (doesn't match prefix '{}')\n".format(source_fname, prefix_filter))
  127. continue
  128. if exclude_files and exclude_files.search(source_fname):
  129. sys.stderr.write("Skipping {} (matched exclude pattern '{}')\n".format(source_fname, exclude_files.pattern))
  130. continue
  131. fname2gcno[source_fname] = gcno_name
  132. if os.path.getsize(gcno_name) > 0:
  133. coverage_info = source_fname + '.' + str(len(fname2info[source_fname])) + '.info'
  134. fname2info[source_fname].append(coverage_info)
  135. geninfo_cmd = [
  136. geninfo_executable,
  137. '--gcov-tool', gcov_tool,
  138. '-i', gcno_name,
  139. '-o', coverage_info + '.tmp'
  140. ]
  141. gen_info(geninfo_cmd, coverage_info)
  142. def process_all_coverage_files(gcda_archive, fname2gcno, fname2info, geninfo_executable, gcov_tool, gen_info):
  143. with tarfile.open(gcda_archive) as gcda_tf:
  144. for gcda_item in gcda_tf:
  145. if gcda_item.isfile() and gcda_item.name.endswith(GCDA_EXT):
  146. gcda_name = gcda_item.name
  147. source_fname = gcda_name[:-len(GCDA_EXT)]
  148. for suff in suffixes(source_fname):
  149. if suff in fname2gcno:
  150. gcda_new_name = suff + GCDA_EXT
  151. gcda_item.name = gcda_new_name
  152. gcda_tf.extract(gcda_item)
  153. if os.path.getsize(gcda_new_name) > 0:
  154. coverage_info = suff + '.' + str(len(fname2info[suff])) + '.info'
  155. fname2info[suff].append(coverage_info)
  156. geninfo_cmd = [
  157. geninfo_executable,
  158. '--gcov-tool', gcov_tool,
  159. gcda_new_name,
  160. '-o', coverage_info + '.tmp'
  161. ]
  162. gen_info(geninfo_cmd, coverage_info)
  163. def gen_cobertura(tool, output, combined_info):
  164. cmd = [
  165. tool,
  166. combined_info,
  167. '-b', '#hamster#',
  168. '-o', output
  169. ]
  170. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  171. out, err = p.communicate()
  172. if p.returncode:
  173. raise Exception('lcov_cobertura failed with exit code {}\nstdout: {}\nstderr: {}'.format(p.returncode, out, err))
  174. def main(source_root, output, gcno_archive, gcda_archive, gcov_tool, prefix_filter, exclude_regexp, teamcity_stat_output, coverage_report_path, gcov_report, lcov_cobertura):
  175. exclude_files = re.compile(exclude_regexp) if exclude_regexp else None
  176. fname2gcno = {}
  177. fname2info = collections.defaultdict(list)
  178. lcov_args = []
  179. geninfo_executable = os.path.join(source_root, 'devtools', 'lcov', 'geninfo')
  180. def probe_path(path):
  181. return probe_path_global(path, source_root, prefix_filter, exclude_files)
  182. fnda = collections.defaultdict(int)
  183. da = collections.defaultdict(int)
  184. def update_stat(src_file, line):
  185. update_stat_global(src_file, line, da, fnda)
  186. def gen_info(cmd, cov_info):
  187. gen_info_global(cmd, cov_info, probe_path, update_stat, lcov_args)
  188. init_all_coverage_files(gcno_archive, fname2gcno, fname2info, geninfo_executable, gcov_tool, gen_info, prefix_filter, exclude_files)
  189. process_all_coverage_files(gcda_archive, fname2gcno, fname2info, geninfo_executable, gcov_tool, gen_info)
  190. if coverage_report_path:
  191. output_dir = coverage_report_path
  192. else:
  193. output_dir = output + '.dir'
  194. if not os.path.exists(output_dir):
  195. os.makedirs(output_dir)
  196. teamcity_stat_file = None
  197. if teamcity_stat_output:
  198. teamcity_stat_file = os.path.join(output_dir, 'teamcity.out')
  199. print_stat(da, fnda, teamcity_stat_file)
  200. if lcov_args:
  201. output_trace = "combined.info"
  202. combine_info_files(os.path.join(source_root, 'devtools', 'lcov', 'lcov'), lcov_args, output_trace)
  203. cmd = [os.path.join(source_root, 'devtools', 'lcov', 'genhtml'), '-p', source_root, '--ignore-errors', 'source', '-o', output_dir, output_trace]
  204. print >>sys.stderr, '## genhtml', ' '.join(cmd)
  205. subprocess.check_call(cmd)
  206. if lcov_cobertura:
  207. gen_cobertura(lcov_cobertura, gcov_report, output_trace)
  208. with tarfile.open(output, 'w') as tar:
  209. tar.add(output_dir, arcname='.')
  210. if __name__ == '__main__':
  211. parser = argparse.ArgumentParser()
  212. parser.add_argument('--source-root', action='store')
  213. parser.add_argument('--output', action='store')
  214. parser.add_argument('--gcno-archive', action='store')
  215. parser.add_argument('--gcda-archive', action='store')
  216. parser.add_argument('--gcov-tool', action='store')
  217. parser.add_argument('--prefix-filter', action='store')
  218. parser.add_argument('--exclude-regexp', action='store')
  219. parser.add_argument('--teamcity-stat-output', action='store_const', const=True)
  220. parser.add_argument('--coverage-report-path', action='store')
  221. parser.add_argument('--gcov-report', action='store')
  222. parser.add_argument('--lcov-cobertura', action='store')
  223. args = parser.parse_args()
  224. main(**vars(args))