Debian Codegraph @

test/common/lcov.py

raw
1 #!/usr/bin/python3 -cimport os, sys; os.execv(os.path.dirname(sys.argv[1]) + "/pywrap", sys.argv)
2
3 #
4 # Copyright (C) 2022 Red Hat, Inc.
5 # SPDX-License-Identifier: LGPL-2.1-or-later
6
7
8 # This module can convert profile data from CDP to LCOV, produce a
9 # HTML report, and post review comments.
10 #
11 # - write_lcov (coverage_data, outlabel)
12 # - create_coverage_report()
13
14 import glob
15 import gzip
16 import itertools
17 import json
18 import os
19 import re
20 import shutil
21 import subprocess
22 import sys
23 import urllib.parse
24 from bisect import bisect_left
25 from typing import Any, Mapping, Sequence
26
27 BASE_DIR = os.path.realpath(f'{__file__}/../../..')
28
29 debug = False
30
31 # parse_vlq and parse_sourcemap are based on
32 # https://github.com/mattrobenolt/python-sourcemap, licensed with
33 # "BSD-2-Clause License"
34
35 # Mapping of base64 letter -> integer value.
36 B64 = {c: i for i, c in
37 enumerate('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
38 '0123456789+/')}
39
40
41 def parse_vlq(segment):
42 """Parse a string of VLQ-encoded data.
43 Returns:
44 a list of integers.
45 """
46
47 values = []
48
49 cur, shift = 0, 0
50 for c in segment:
51 val = B64[c]
52 # Each character is 6 bits:
53 # 5 of value and the high bit is the continuation.
54 val, cont = val & 0b11111, val >> 5
55 cur += val << shift
56 shift += 5
57
58 if not cont:
59 # The low bit of the unpacked value is the sign.
60 cur, sign = cur >> 1, cur & 1
61 if sign:
62 cur = -cur
63 values.append(cur)
64 cur, shift = 0, 0
65
66 if cur or shift:
67 raise Exception('leftover cur/shift in vlq decode')
68
69 return values
70
71
72 def parse_sourcemap(f, line_starts, dir_name):
73 smap = json.load(f)
74 sources = smap['sources']
75 mappings = smap['mappings']
76 lines = mappings.split(';')
77
78 our_map = []
79
80 our_sources = set()
81 for s in sources:
82 # reject any absolute paths or URLs (like webpack://)
83 if not s.startswith('../'):
84 continue
85 # don't generate coverage for node_modules/ code
86 if "node_modules" in s:
87 continue
88 # and only for these file types...
89 if not s.endswith(('.js', '.jsx', '.ts', '.tsx')):
90 continue
91 our_sources.add(s)
92
93 dst_col, src_id, src_line = 0, 0, 0
94 for dst_line, line in enumerate(lines):
95 segments = line.split(',')
96 dst_col = 0
97 for segment in segments:
98 if not segment:
99 continue
100 parse = parse_vlq(segment)
101 dst_col += parse[0]
102
103 src = None
104 if len(parse) > 1:
105 src_id += parse[1]
106 src = sources[src_id]
107 src_line += parse[2]
108
109 if src in our_sources:
110 norm_src = os.path.normpath(os.path.join(dir_name, src))
111 our_map.append((line_starts[dst_line] + dst_col, norm_src, src_line))
112
113 return our_map
114
115
116 class DistFile:
117 def __init__(self, path):
118 line_starts = [0]
119 with open(path, newline='') as f:
120 for line in f.readlines():
121 line_starts.append(line_starts[-1] + len(line))
122 with open(path + ".map") as f:
123 self.smap = parse_sourcemap(f, line_starts, os.path.relpath(os.path.dirname(path), BASE_DIR))
124
125 def find_sources_slow(self, start, end):
126 res = []
127 for m in self.smap:
128 if m[0] >= start and m[0] < end:
129 res.append(m)
130 return res
131
132 def find_sources(self, start, end):
133 res = []
134 i = bisect_left(self.smap, start, key=lambda m: m[0])
135 while i < len(self.smap) and self.smap[i][0] < end:
136 res.append(self.smap[i])
137 i += 1
138 if debug and res != self.find_sources_slow(start, end):
139 raise RuntimeError("Bug in find_sources")
140 return res
141
142
143 def get_dist_map(package):
144 dmap = {}
145 for manifest_json in glob.glob(f"{BASE_DIR}/dist/*/manifest.json") + glob.glob(f"{BASE_DIR}/dist/manifest.json"):
146 with open(manifest_json) as f:
147 m = json.load(f)
148 if "name" in m:
149 dmap[m["name"]] = os.path.dirname(manifest_json)
150 elif manifest_json == f"{BASE_DIR}/dist/manifest.json":
151 if "name" in package:
152 dmap[package["name"]] = os.path.dirname(manifest_json)
153 return dmap
154
155
156 def get_distfile(url, dist_map):
157 path = urllib.parse.urlparse(url).path
158 if path.startswith('/qunit/'):
159 relpath = path[1:]
160 if os.path.exists(relpath) and os.path.exists(f'{relpath}.map'):
161 return DistFile(path[1:])
162
163 parts = url.split("/")
164 if len(parts) < 3 or "cockpit" not in parts:
165 return None
166
167 base = parts[-2]
168 file = parts[-1]
169 if file == "manifests.js":
170 return None
171 if base in dist_map:
172 path = dist_map[base] + "/" + file
173 else:
174 path = f"{BASE_DIR}/dist/" + base + "/" + file
175 if os.path.exists(path) and os.path.exists(path + ".map"):
176 return DistFile(path)
177 else:
178 sys.stderr.write(f"SKIP {url} -> {path}\n")
179 return None
180
181
182 def grow_array(arr, size, val):
183 if len(arr) < size:
184 arr.extend([val] * (size - len(arr)))
185
186
187 def record_covered(file_hits, src, line, hits):
188 if src in file_hits:
189 line_hits = file_hits[src]
190 else:
191 line_hits = []
192 grow_array(line_hits, line + 1, None)
193 line_hits[line] = hits
194 file_hits[src] = line_hits
195
196
197 def record_range(file_hits, r, distfile):
198 sources = distfile.find_sources(r['startOffset'], r['endOffset'])
199 for src in sources:
200 record_covered(file_hits, src[1], src[2], r['count'])
201
202
203 def merge_hits(file_hits, hits):
204 for src in hits:
205 if src not in file_hits:
206 file_hits[src] = hits[src]
207 else:
208 lines = file_hits[src]
209 merge_lines = hits[src]
210 grow_array(lines, len(merge_lines), None)
211 for i in range(len(merge_lines)):
212 if lines[i] is None:
213 lines[i] = merge_lines[i]
214 elif merge_lines[i] is not None:
215 lines[i] += merge_lines[i]
216
217
218 def print_file_coverage(path, line_hits, out):
219 lines_found = 0
220 lines_hit = 0
221 src = f"{BASE_DIR}/{path}"
222 out.write(f"SF:{src}\n")
223 for i in range(len(line_hits)):
224 if line_hits[i] is not None:
225 lines_found += 1
226 out.write(f"DA:{i + 1},{line_hits[i]}\n")
227 if line_hits[i] > 0:
228 lines_hit += 1
229 out.write(f"LH:{lines_hit}\n")
230 out.write(f"LF:{lines_found}\n")
231 out.write("end_of_record\n")
232
233
234 class DiffMap:
235 # Parse a unified diff and make a index for the added lines
236 def __init__(self, diff):
237 self.map = {}
238 self.source_map = {}
239 plus_name = None
240 diff_line = 0
241 with open(diff) as f:
242 for line in f.readlines():
243 diff_line += 1
244 if line.startswith("+++ /dev/null"):
245 # removed file, only `^-` following after that until the next hunk
246 continue
247 elif line.startswith("+++ b/"):
248 plus_name = os.path.normpath(line[6:].strip())
249 plus_line = 1
250 self.map[plus_name] = {}
251 elif line.startswith("@@ "):
252 plus_line = int(line.split(" ")[2].split(",")[0])
253 elif line.startswith(" "):
254 plus_line += 1
255 elif line.startswith("+"):
256 self.map[plus_name][plus_line] = diff_line
257 self.source_map[diff_line] = (plus_name, plus_line, line[1:])
258 plus_line += 1
259
260 def find_line(self, file, line):
261 if file in self.map and line in self.map[file]:
262 return self.map[file][line]
263 return None
264
265 def find_source(self, diff_line):
266 return self.source_map.get(diff_line)
267
268
269 def print_diff_coverage(path, file_hits, out):
270 if not os.path.exists(path):
271 return
272 dm = DiffMap(path)
273 src = f"{BASE_DIR}/{path}"
274 lines_found = 0
275 lines_hit = 0
276 out.write(f"SF:{src}\n")
277 for f in file_hits:
278 line_hits = file_hits[f]
279 for i in range(len(line_hits)):
280 if line_hits[i] is not None:
281 diff_line = dm.find_line(f, i + 1)
282 if diff_line:
283 lines_found += 1
284 out.write(f"DA:{diff_line},{line_hits[i]}\n")
285 if line_hits[i] > 0:
286 lines_hit += 1
287 out.write(f"LH:{lines_hit}\n")
288 out.write(f"LF:{lines_found}\n")
289 out.write("end_of_record\n")
290
291
292 def write_lcov(covdata: Sequence[Mapping[str, str]], outlabel: str) -> None:
293
294 with open(f"{BASE_DIR}/package.json") as f:
295 package = json.load(f)
296 dist_map = get_dist_map(package)
297 file_hits: Any = {}
298
299 def covranges(functions):
300 for f in functions:
301 for r in f['ranges']:
302 yield r
303
304 # Coverage data is reported as a "count" value for a range of
305 # text. These ranges overlap when functions are nested. For
306 # example, take this source code:
307 #
308 # 1 . function foo(x) {
309 # 2 . function bar() {
310 # 3 . }
311 # 4 . if (x)
312 # 5 . bar();
313 # 6 . }
314 # 7 .
315 # 8 . foo(0)
316 #
317 # There will be a range with count 1 for the whole source code
318 # (lines 1 to 8) since all code is executed when loading a file.
319 # Then there will be a range with count 1 for "foo" (lines 1 to 6)
320 # since it is called from the top-level, and there will be a range
321 # with count 0 for "bar" (lines 2 and 3), since it is never
322 # actually called. If block-level precision has been enabled
323 # while collecting the coverage data, there will also be a range
324 # with count 0 for line 5, since that branch if the "if" is not
325 # executed.
326 #
327 # We process ranges like this in order, from longest to shortest,
328 # and record their counts for each line they cover. The count of a
329 # range that is processed later will overwrite any count that has
330 # been recorded earlier. This makes the count correct for nested
331 # functions since they are processed last.
332 #
333 # In the example, first lines 1 to 8 are set to count 1, then
334 # lines 1 to 6 are set to count 1 again, then lines 2 and 3 are
335 # set to count 0, and finally line 5 is also set to count 0:
336 #
337 # 1 1 function foo(x) {
338 # 2 0 function bar() {
339 # 3 0 }
340 # 4 1 if (x)
341 # 5 0 bar();
342 # 6 1 }
343 # 7 1
344 # 8 1 foo(0)
345 #
346 # Thus, when processing ranges for a single file, we must
347 # prioritize the counts of smaller ranges over larger ones, and
348 # can't just add them all up. This doesn't work, however, when
349 # something like webpack is involved, and a source file is copied
350 # into multiple files in "dist/".
351 #
352 # The coverage data contains ranges for all files that are loaded
353 # into the browser during the whole session, such as when
354 # transitioning from the login page to the shell, and when loading
355 # multiple iframes for the individual pages.
356 #
357 # For example, if both shell.js (loaded at the top-level) and
358 # overview.js (loaded into an iframe) include lib/button.js, then
359 # the coverage data might report that shell.js does execute line 5
360 # of lib/button.js and also that overview.js does not execute it.
361 # We need to add the counts up for line 5 so that the combined
362 # report says that is has been executed.
363 #
364 # The same applies to reloading and navigating in the browser. If
365 # a page is reloaded, there will be separate coverage reports for
366 # its files. For example, if a reload happens, shell.js will be
367 # mentioned twice in the report, and we need to add up the counts
368 # from each mention.
369
370 for script in covdata:
371 distfile = get_distfile(script['url'], dist_map)
372 if distfile:
373 ranges = sorted(covranges(script['functions']),
374 key=lambda r: r['endOffset'] - r['startOffset'], reverse=True)
375 hits: Any = {}
376 for r in ranges:
377 record_range(hits, r, distfile)
378 merge_hits(file_hits, hits)
379
380 if len(file_hits) > 0:
381 os.makedirs(f"{BASE_DIR}/lcov", exist_ok=True)
382 filename = f"{BASE_DIR}/lcov/{outlabel}.info.gz"
383 with gzip.open(filename, "wt") as out:
384 for f in file_hits:
385 print_file_coverage(f, file_hits[f], out)
386 print_diff_coverage("lcov/github-pr.diff", file_hits, out)
387 print("Wrote coverage data to " + filename)
388
389
390 def get_review_comments(diff_info_file):
391 comments = []
392 cur_src = None
393 start_line = None
394 cur_line = None
395
396 def is_interesting_line(text):
397 # Don't complain when being told to shut up
398 if "// not-covered: " in text:
399 return False
400 # Don't complain about lines that contain only punctuation, or
401 # nothing but "else". We don't seem to get reliable
402 # information for them.
403 if not re.search(r'[a-zA-Z0-9]', text.replace("else", "")):
404 return False
405 return True
406
407 def flush_cur_comment():
408 nonlocal comments
409 if cur_src:
410 comment = {"path": cur_src,
411 "line": cur_line}
412 if start_line != cur_line:
413 comment["start_line"] = start_line
414 body = f"These {cur_line - start_line + 1} added lines are not executed by any test."
415 else:
416 body = "This added line is not executed by any test."
417 log_url = os.environ.get("COCKPIT_CI_LOG_URL", None)
418 if log_url is not None:
419 body += f" [Details]({os.path.dirname(log_url)}/Coverage/lcov/github-pr.diff.gcov.html)"
420 comment["body"] = body
421 comments.append(comment)
422
423 dm = DiffMap("lcov/github-pr.diff")
424
425 with open(diff_info_file) as f:
426 for line in f.readlines():
427 if line.startswith("DA:"):
428 parts = line[3:].split(",")
429 if int(parts[1]) == 0:
430 info = dm.find_source(int(parts[0]))
431 if not info:
432 continue
433 (src, line, text) = info
434 if not is_interesting_line(text):
435 continue
436 if src == cur_src and line == cur_line + 1:
437 cur_line = line
438 else:
439 flush_cur_comment()
440 cur_src = src
441 start_line = line
442 cur_line = line
443 flush_cur_comment()
444
445 return comments
446
447
448 def prepare_for_code_coverage() -> None:
449 # This gives us a convenient link at the top of the logs, see link-patterns.json
450 print("Code coverage report in Coverage/index.html")
451 if os.path.exists("lcov"):
452 shutil.rmtree("lcov")
453 os.makedirs("lcov")
454 # Detect the default branch to compare with, Anaconda still uses master as main.
455 branch = "main"
456 try:
457 subprocess.check_call(["git", "rev-parse", "--quiet", "--verify", branch], stdout=subprocess.DEVNULL)
458 except subprocess.SubprocessError:
459 branch = "master"
460 with open("lcov/github-pr.diff", "w") as f:
461 subprocess.check_call(["git", "-c", "diff.noprefix=false", "diff", "--patience", branch], stdout=f)
462
463
464 def limit_comments(comments: list[dict[str, str]]) -> tuple[list[dict[str, str]], str]:
465 """Limit the number of code coverage comments to 10, if there are more add a link to the full report"""
466
467 if len(comments) <= 10:
468 return comments, ""
469
470 log_url = os.environ.get("COCKPIT_CI_LOG_URL", None)
471 if log_url is not None:
472 base_url = os.path.dirname(log_url)
473 coverage_report = f"{base_url}/Coverage/lcov/github-pr.diff.gcov.html"
474 report_link_comment = f"There are more than 10 code coverage comments, see [the full report here]({coverage_report})."
475 else:
476 report_link_comment = ""
477
478 return comments[:10], report_link_comment
479
480
481 def create_coverage_report() -> None:
482 output = os.environ.get("TEST_ATTACHMENTS", BASE_DIR)
483 lcov_files = glob.glob(f"{BASE_DIR}/lcov/*.info.gz")
484 try:
485 title = os.path.basename(subprocess.check_output(["git", "remote", "get-url", "origin"])).decode().strip()
486 except subprocess.CalledProcessError:
487 title = "?"
488 if len(lcov_files) > 0:
489 all_file = f"{BASE_DIR}/lcov/all.info"
490 diff_file = f"{BASE_DIR}/lcov/diff.info"
491 excludes = []
492 # Exclude pkg/lib in Cockpit projects such as podman/machines.
493 if title != "cockpit.git" and title != "cockpit":
494 excludes = ["--exclude", "pkg/lib"]
495 subprocess.check_call(["lcov", "--quiet", "--output", all_file, *excludes,
496 *itertools.chain(*[["--add", f] for f in lcov_files])])
497 subprocess.check_call(["lcov", "--quiet", "--ignore-errors", "empty,empty,unused,unused", "--output", diff_file,
498 "--extract", all_file, "*/github-pr.diff"])
499 summary = subprocess.check_output(["genhtml", "--no-function-coverage",
500 "--prefix", os.getcwd(),
501 "--title", title,
502 "--output-dir", f"{output}/Coverage", all_file]).decode()
503
504 coverage = summary.split("\n")[-2]
505 match = re.search(r".*lines\.*:\s*([\d\.]*%).*", coverage)
506 if match:
507 print("Overall line coverage:", match.group(1))
508
509 comments, review_body = limit_comments(get_review_comments(diff_file))
510 rev = os.environ.get("TEST_REVISION", None)
511 pull = os.environ.get("TEST_PULL", None)
512 if rev and pull:
513 from lib import github
514
515 api = github.GitHub()
516 old_comments = api.get(f"pulls/{pull}/comments?sort=created&direction=desc&per_page=100") or []
517 for oc in old_comments:
518 if ("body" in oc and "path" in oc and "line" in oc and
519 "not executed by any test." in oc["body"]):
520 api.delete(f"pulls/comments/{oc['id']}")
521 if len(comments) > 0:
522 api.post(f"pulls/{pull}/reviews",
523 {"commit_id": rev, "event": "COMMENT",
524 "comments": comments, "body": review_body})
525 else:
526 sys.stderr.write("Error: no code coverage files generated\n")