Debian Codegraph @

merge-coverage

raw
1 #! /usr/bin/python3
2
3 from optparse import OptionParser
4 import re
5 import sys
6 from xml.etree import ElementTree as ET
7
8
9 class CoverageTreeBuilder(ET.TreeBuilder):
10 def doctype(self, name, pubid, system):
11 self._doctype = (name, pubid, system)
12
13
14 class Coverage:
15 def __init__(self):
16 self._tree = None
17 self._builder = None
18
19 def _merge_children(self, left, right):
20 assert left.tag == right.tag
21 if left.tag == "coverage":
22 for right_child in right:
23 left_child = left.find(right_child.tag)
24 if left_child is not None:
25 self._merge_children(left_child, right_child)
26 else:
27 left.append(right_child)
28 # Re-compute rates from scratch.
29 lnum, lhits = 0, 0
30 bnum, bhits = 0, 0
31 condition_re = re.compile(r"\(([0-9]+)/([0-9]+)\)")
32 for package in left.find("packages").findall("package"):
33 for cclass in package.find("classes").findall("class"):
34 for line in cclass.find("lines").findall("line"):
35 lnum += 1
36 if line.get("hits", "0") != "0":
37 lhits += 1
38 if line.get("branch", "false") == "true":
39 match = condition_re.search(
40 line.get("condition-coverage"))
41 if match is not None:
42 bhits += int(match.group(1))
43 bnum += int(match.group(2))
44 left.set("branch-rate", "%.4g" % (float(bhits) / (bnum or 1.0)))
45 left.set("line-rate", "%.4g" % (float(lhits) / (lnum or 1.0)))
46 elif left.tag == "sources":
47 pass # just ignore this for now
48 elif left.tag == "packages":
49 left_names = []
50 for left_child in left:
51 assert left_child.tag == "package"
52 left_names.append(left_child.get("name"))
53 for right_child in right:
54 assert right_child.tag == "package"
55 assert right_child.get("name") not in left_names
56 left.append(right_child)
57
58 def merge(self, arg):
59 builder = CoverageTreeBuilder()
60 tree = ET.parse(arg, parser=ET.XMLParser(target=builder))
61 if self._tree is None:
62 self._tree = tree
63 self._builder = builder
64 else:
65 self._merge_children(self._tree.getroot(), tree.getroot())
66
67 def write(self, outfilename):
68 if outfilename is None:
69 outfile = sys.stdout
70 else:
71 outfile = open(outfilename, "w")
72 outfile.write('<?xml version="1.0" ?>\n')
73 doctype = self._builder._doctype
74 outfile.write("<!DOCTYPE %s%s%s>\n" % (
75 doctype[0],
76 "" if doctype[1] is None else "\n PUBLIC '%s'" % doctype[1],
77 "" if doctype[2] is None else "\n SYSTEM '%s'" % doctype[2]))
78 try:
79 self._tree.write(outfile, encoding="unicode")
80 finally:
81 outfile.close()
82
83
84 def main():
85 parser = OptionParser(usage="%prog FILE [...]")
86 parser.add_option(
87 "-o", "--output", help="output file name (default: stdout)")
88 options, args = parser.parse_args()
89 if not args:
90 parser.error("need at least one input file")
91 coverage = Coverage()
92 for arg in args:
93 coverage.merge(arg)
94 coverage.write(options.output)
95
96
97 if __name__ == "__main__":
98 main()