Debian Codegraph @

tools/c_coverage/c_coverage_report.py

raw
1 #!/usr/bin/env python3
2 """
3 A script to create C code-coverage reports based on the output of
4 valgrind's callgrind tool.
5
6 """
7 import os
8 import re
9 import sys
10 from xml.sax.saxutils import escape, quoteattr
11
12 try:
13 import pygments
14 if tuple(int(x) for x in pygments.__version__.split('.')) < (0, 11):
15 raise ImportError
16 from pygments import highlight
17 from pygments.formatters import HtmlFormatter
18 from pygments.lexers import CLexer
19 has_pygments = True
20 except ImportError:
21 print("This script requires pygments 0.11 or greater to generate HTML")
22 has_pygments = False
23
24
25 class FunctionHtmlFormatter(HtmlFormatter):
26 """Custom HTML formatter to insert extra information with the lines."""
27 def __init__(self, lines, **kwargs):
28 HtmlFormatter.__init__(self, **kwargs)
29 self.lines = lines
30
31 def wrap(self, source, outfile):
32 for i, (c, t) in enumerate(HtmlFormatter.wrap(self, source, outfile)):
33 as_functions = self.lines.get(i - 1, None)
34 if as_functions is not None:
35 yield 0, ('<div title=%s style="background: #ccffcc">[%2d]' %
36 (quoteattr('as ' + ', '.join(as_functions)),
37 len(as_functions)))
38 else:
39 yield 0, ' '
40 yield c, t
41 if as_functions is not None:
42 yield 0, '</div>'
43
44
45 class SourceFile:
46 def __init__(self, path):
47 self.path = path
48 self.lines = {}
49
50 def mark_line(self, lineno, as_func=None):
51 line = self.lines.setdefault(lineno, set())
52 if as_func is not None:
53 as_func = as_func.split("'", 1)[0]
54 line.add(as_func)
55
56 def write_text(self, fd):
57 with open(self.path, "r") as source:
58 for i, line in enumerate(source):
59 if i + 1 in self.lines:
60 fd.write("> ")
61 else:
62 fd.write("! ")
63 fd.write(line)
64
65 def write_html(self, fd):
66 with open(self.path, 'r') as source:
67 code = source.read()
68 lexer = CLexer()
69 formatter = FunctionHtmlFormatter(
70 self.lines,
71 full=True,
72 linenos='inline')
73 fd.write(highlight(code, lexer, formatter))
74
75
76 class SourceFiles:
77 def __init__(self):
78 self.files = {}
79 self.prefix = None
80
81 def get_file(self, path):
82 if path not in self.files:
83 self.files[path] = SourceFile(path)
84 if self.prefix is None:
85 self.prefix = path
86 else:
87 self.prefix = os.path.commonprefix([self.prefix, path])
88 return self.files[path]
89
90 def clean_path(self, path):
91 path = path[len(self.prefix):]
92 return re.sub(r"[^A-Za-z0-9\.]", '_', path)
93
94 def write_text(self, root):
95 for path, source in self.files.items():
96 with open(os.path.join(root, self.clean_path(path)), "w") as fd:
97 source.write_text(fd)
98
99 def write_html(self, root):
100 for path, source in self.files.items():
101 with open(
102 os.path.join(root, self.clean_path(path) + ".html"), "w"
103 ) as fd:
104 source.write_html(fd)
105
106 with open(os.path.join(root, 'index.html'), 'w') as fd:
107 fd.write("<html>")
108 paths = sorted(self.files.keys())
109 for path in paths:
110 fd.write('<p><a href="%s.html">%s</a></p>' %
111 (self.clean_path(path),
112 escape(path[len(self.prefix):])))
113 fd.write("</html>")
114
115
116 def collect_stats(files, fd, pattern):
117 # TODO: Handle compressed callgrind files
118 line_regexs = [
119 re.compile(r"(?P<lineno>[0-9]+)(\s[0-9]+)+"),
120 re.compile(r"((jump)|(jcnd))=([0-9]+)\s(?P<lineno>[0-9]+)")
121 ]
122
123 current_file = None
124 current_function = None
125 for line in fd:
126 if re.match(r"f[lie]=.+", line):
127 path = line.split('=', 2)[1].strip()
128 if os.path.exists(path) and re.search(pattern, path):
129 current_file = files.get_file(path)
130 else:
131 current_file = None
132 elif re.match(r"fn=.+", line):
133 current_function = line.split('=', 2)[1].strip()
134 elif current_file is not None:
135 for regex in line_regexs:
136 match = regex.match(line)
137 if match:
138 lineno = int(match.group('lineno'))
139 current_file.mark_line(lineno, current_function)
140
141
142 if __name__ == '__main__':
143 import argparse
144
145 parser = argparse.ArgumentParser(description=__doc__)
146 parser.add_argument(
147 'callgrind_file', nargs='+',
148 help='One or more callgrind files')
149 parser.add_argument(
150 '-d', '--directory', default='coverage',
151 help='Destination directory for output (default: %(default)s)')
152 parser.add_argument(
153 '-p', '--pattern', default='numpy',
154 help='Regex pattern to match against source file paths '
155 '(default: %(default)s)')
156 parser.add_argument(
157 '-f', '--format', action='append', default=[],
158 choices=['text', 'html'],
159 help="Output format(s) to generate. "
160 "If option not provided, both will be generated.")
161 args = parser.parse_args()
162
163 files = SourceFiles()
164 for log_file in args.callgrind_file:
165 with open(log_file, 'r') as log_fd:
166 collect_stats(files, log_fd, args.pattern)
167
168 if not os.path.exists(args.directory):
169 os.makedirs(args.directory)
170
171 if args.format == []:
172 formats = ['text', 'html']
173 else:
174 formats = args.format
175 if 'text' in formats:
176 files.write_text(args.directory)
177 if 'html' in formats:
178 if not has_pygments:
179 print("Pygments 0.11 or later is required to generate HTML")
180 sys.exit(1)
181 files.write_html(args.directory)