Debian Codegraph @

mesonbuild/scripts/coverage.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2017 The Meson development team
3
4 from __future__ import annotations
5
6 from mesonbuild import tooldetect, mesonlib
7
8 import argparse, re, sys, os, subprocess, pathlib, stat, shutil
9 import typing as T
10
11 def coverage(outputs: T.List[str], source_root: str, subproject_root: str, build_root: str, log_dir: str, use_llvm_cov: bool,
12 gcovr_exe: str, llvm_cov_exe: str) -> int:
13 outfiles = []
14 exitcode = 0
15
16 if gcovr_exe == '':
17 gcovr_exe = None
18 else:
19 gcovr_exe, gcovr_version = tooldetect.detect_gcovr(gcovr_exe)
20 if llvm_cov_exe == '' or shutil.which(llvm_cov_exe) is None:
21 llvm_cov_exe = None
22
23 lcov_exe, lcov_version, genhtml_exe = tooldetect.detect_lcov_genhtml()
24
25 # load config files for tools if available in the source tree
26 # - lcov requires manually specifying a per-project config
27 # - gcovr picks up the per-project config, and also supports filtering files
28 # so don't exclude subprojects ourselves, if the project has a config,
29 # because they either don't want that, or should set it themselves
30 lcovrc = os.path.join(source_root, '.lcovrc')
31 if os.path.exists(lcovrc):
32 lcov_config = ['--config-file', lcovrc]
33 else:
34 lcov_config = []
35
36 if lcov_exe and mesonlib.version_compare(lcov_version, '>=2.0'):
37 lcov_exe_rc_branch_coverage = ['--rc', 'branch_coverage=1']
38 else:
39 lcov_exe_rc_branch_coverage = ['--rc', 'lcov_branch_coverage=1']
40
41 gcovr_config = ['-e', re.escape(subproject_root)]
42
43 # gcovr >= 4.2 requires a different syntax for out of source builds
44 if gcovr_exe and mesonlib.version_compare(gcovr_version, '>=4.2'):
45 gcovr_base_cmd = [gcovr_exe, '-r', source_root, build_root]
46 # it also started supporting the config file
47 if os.path.exists(os.path.join(source_root, 'gcovr.cfg')):
48 gcovr_config = []
49 else:
50 gcovr_base_cmd = [gcovr_exe, '-r', build_root]
51
52 if use_llvm_cov:
53 gcov_exe_args = ['--gcov-executable', llvm_cov_exe + ' gcov']
54 else:
55 gcov_exe_args = []
56
57 if not outputs or 'xml' in outputs:
58 if gcovr_exe and mesonlib.version_compare(gcovr_version, '>=3.3'):
59 subprocess.check_call(gcovr_base_cmd + gcovr_config +
60 ['-x',
61 '-o', os.path.join(log_dir, 'coverage.xml')
62 ] + gcov_exe_args)
63 outfiles.append(('Xml', pathlib.Path(log_dir, 'coverage.xml')))
64 elif outputs:
65 print('gcovr >= 3.3 needed to generate Xml coverage report')
66 exitcode = 1
67
68 if not outputs or 'sonarqube' in outputs:
69 if gcovr_exe and mesonlib.version_compare(gcovr_version, '>=4.2'):
70 subprocess.check_call(gcovr_base_cmd + gcovr_config +
71 ['--sonarqube',
72 '-o', os.path.join(log_dir, 'sonarqube.xml'),
73 ] + gcov_exe_args)
74 outfiles.append(('Sonarqube', pathlib.Path(log_dir, 'sonarqube.xml')))
75 elif outputs:
76 print('gcovr >= 4.2 needed to generate Xml coverage report')
77 exitcode = 1
78
79 if not outputs or 'text' in outputs:
80 if gcovr_exe and mesonlib.version_compare(gcovr_version, '>=3.3'):
81 subprocess.check_call(gcovr_base_cmd + gcovr_config +
82 ['-o', os.path.join(log_dir, 'coverage.txt')] +
83 gcov_exe_args)
84 outfiles.append(('Text', pathlib.Path(log_dir, 'coverage.txt')))
85 elif outputs:
86 print('gcovr >= 3.3 needed to generate text coverage report')
87 exitcode = 1
88
89 if not outputs or 'html' in outputs:
90 if lcov_exe and genhtml_exe:
91 htmloutdir = os.path.join(log_dir, 'coveragereport')
92 covinfo = os.path.join(log_dir, 'coverage.info')
93 initial_tracefile = covinfo + '.initial'
94 run_tracefile = covinfo + '.run'
95 raw_tracefile = covinfo + '.raw'
96 lcov_subpoject_exclude = []
97 if os.path.exists(subproject_root):
98 lcov_subpoject_exclude.append(os.path.join(subproject_root, '*'))
99 if use_llvm_cov:
100 # Create a shim to allow using llvm-cov as a gcov tool.
101 if mesonlib.is_windows():
102 llvm_cov_shim_path = os.path.join(log_dir, 'llvm-cov.bat')
103 with open(llvm_cov_shim_path, 'w', encoding='utf-8') as llvm_cov_bat:
104 llvm_cov_bat.write(f'@"{llvm_cov_exe}" gcov %*')
105 else:
106 llvm_cov_shim_path = os.path.join(log_dir, 'llvm-cov.sh')
107 with open(llvm_cov_shim_path, 'w', encoding='utf-8') as llvm_cov_sh:
108 llvm_cov_sh.write(f'#!/usr/bin/env sh\nexec "{llvm_cov_exe}" gcov $@')
109 os.chmod(llvm_cov_shim_path, os.stat(llvm_cov_shim_path).st_mode | stat.S_IEXEC)
110 gcov_tool_args = ['--gcov-tool', llvm_cov_shim_path]
111 else:
112 gcov_tool_args = []
113 subprocess.check_call([lcov_exe,
114 '--directory', build_root,
115 '--capture',
116 '--initial',
117 '--output-file',
118 initial_tracefile] +
119 lcov_config +
120 gcov_tool_args)
121 subprocess.check_call([lcov_exe,
122 '--directory', build_root,
123 '--capture',
124 '--output-file', run_tracefile,
125 '--no-checksum',
126 *lcov_exe_rc_branch_coverage] +
127 lcov_config +
128 gcov_tool_args)
129 # Join initial and test results.
130 subprocess.check_call([lcov_exe,
131 '-a', initial_tracefile,
132 '-a', run_tracefile,
133 *lcov_exe_rc_branch_coverage,
134 '-o', raw_tracefile] + lcov_config)
135 # Remove all directories outside the source_root from the covinfo
136 subprocess.check_call([lcov_exe,
137 '--extract', raw_tracefile,
138 os.path.join(source_root, '*'),
139 *lcov_exe_rc_branch_coverage,
140 '--output-file', covinfo] + lcov_config)
141 # Remove all directories inside subproject dir
142 subprocess.check_call([lcov_exe,
143 '--remove', covinfo,
144 *lcov_subpoject_exclude,
145 *lcov_exe_rc_branch_coverage,
146 '--ignore-errors', 'unused',
147 '--output-file', covinfo] + lcov_config)
148 subprocess.check_call([genhtml_exe,
149 '--prefix', build_root,
150 '--prefix', source_root,
151 '--output-directory', htmloutdir,
152 '--title', 'Code coverage',
153 '--legend',
154 '--show-details',
155 '--branch-coverage',
156 covinfo] + lcov_config)
157 outfiles.append(('Html', pathlib.Path(htmloutdir, 'index.html')))
158 elif gcovr_exe and mesonlib.version_compare(gcovr_version, '>=3.3'):
159 htmloutdir = os.path.join(log_dir, 'coveragereport')
160 if not os.path.isdir(htmloutdir):
161 os.mkdir(htmloutdir)
162 # Use `--html-details` if gcovr version < 6.0, otherwise
163 # use `--html-nested`.
164 html_arg = '--html-details'
165 if mesonlib.version_compare(gcovr_version, '>=6.0'):
166 html_arg = '--html-nested'
167 subprocess.check_call(gcovr_base_cmd + gcovr_config +
168 ['--html',
169 html_arg,
170 '--print-summary',
171 '-o', os.path.join(htmloutdir, 'index.html'),
172 ] + gcov_exe_args)
173 outfiles.append(('Html', pathlib.Path(htmloutdir, 'index.html')))
174 elif outputs:
175 print('lcov/genhtml or gcovr >= 3.3 needed to generate Html coverage report')
176 exitcode = 1
177
178 if not outputs and not outfiles:
179 print('Need gcovr or lcov/genhtml to generate any coverage reports')
180 exitcode = 1
181
182 if outfiles:
183 print('')
184 for (filetype, path) in outfiles:
185 print(filetype + ' coverage report can be found at', path.as_uri())
186
187 return exitcode
188
189 def run(args: T.List[str]) -> int:
190 if not os.path.isfile('build.ninja'):
191 print('Coverage currently only works with the Ninja backend.')
192 return 1
193 parser = argparse.ArgumentParser(description='Generate coverage reports')
194 parser.add_argument('--text', dest='outputs', action='append_const',
195 const='text', help='generate Text report')
196 parser.add_argument('--xml', dest='outputs', action='append_const',
197 const='xml', help='generate Xml report')
198 parser.add_argument('--sonarqube', dest='outputs', action='append_const',
199 const='sonarqube', help='generate Sonarqube Xml report')
200 parser.add_argument('--html', dest='outputs', action='append_const',
201 const='html', help='generate Html report')
202 parser.add_argument('--use-llvm-cov', action='store_true',
203 help='use llvm-cov')
204 parser.add_argument('--gcovr', action='store', default='',
205 help='The gcovr executable to use if specified')
206 parser.add_argument('--llvm-cov', action='store', default='',
207 help='The llvm-cov executable to use if specified')
208 parser.add_argument('source_root')
209 parser.add_argument('subproject_root')
210 parser.add_argument('build_root')
211 parser.add_argument('log_dir')
212 options = parser.parse_args(args)
213 return coverage(options.outputs, options.source_root,
214 options.subproject_root, options.build_root,
215 options.log_dir, options.use_llvm_cov,
216 options.gcovr, options.llvm_cov)
217
218 if __name__ == '__main__':
219 sys.exit(run(sys.argv[1:]))