coverage-info.py 11 KB

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