1+ #!/usr/bin/env python
2+
3+ # Usage: ./lcov-to-cobertura-xml.py lcov-file.dat output/cobertura.xml
4+
5+ import re , sys , os , time
6+ from xml .dom import minidom
7+ from optparse import OptionParser
8+
9+ # Given a FILE lcov-file return appropriate data structure
10+ def parse_lcov_file (lcov_path , options ):
11+ '''Given a path to a file in lcov format, return a data structure
12+ representing it that can be serialized in any logical format.'''
13+
14+ if (os .path .isfile (lcov_path )):
15+ coverage_data = {'packages' : {}, 'summary' : {'lines-total' : 0 , 'lines-covered' : 0 }}
16+ current_package = None
17+ current_package_lines_total = 0
18+ current_package_lines_covered = 0
19+ current_file = None
20+ current_file_lines_total = 0
21+ current_file_lines_covered = 0
22+ current_file_lines = {}
23+ lcov_file = open (lcov_path , 'r' )
24+
25+ for line in lcov_file :
26+ if line .strip () == 'end_of_record' :
27+ if current_file is not None :
28+ current_package_dict = coverage_data ['packages' ][current_package ]
29+ current_package_dict ['lines-total' ] += current_package_lines_total
30+ current_package_dict ['lines-covered' ] += current_package_lines_covered
31+ current_file_dict = current_package_dict ['classes' ][current_file ]
32+ current_file_dict ['lines-total' ] = current_file_lines_total
33+ current_file_dict ['lines-covered' ] = current_file_lines_covered
34+ current_file_dict ['lines' ] = current_file_lines
35+ coverage_data ['summary' ]['lines-total' ] += current_file_lines_total
36+ coverage_data ['summary' ]['lines-covered' ] += current_file_lines_covered
37+ pass
38+
39+ line_parts = line .split (':' )
40+ input_type = line_parts [0 ]
41+
42+ if input_type == 'SF' :
43+ # Get file name
44+ file_name = line_parts [- 1 ].strip ()
45+ relative_file_name = os .path .relpath (file_name , options .base_dir )
46+ package = '.' .join (relative_file_name .split (os .path .sep )[0 :- 1 ])
47+ class_name = file_name .split (os .path .sep )[- 1 ]
48+ # TODO: exclude test files here
49+ if package not in coverage_data ['packages' ]:
50+ coverage_data ['packages' ][package ] = {'classes' : {}, 'lines-total' : 0 , 'lines-covered' : 0 }
51+ coverage_data ['packages' ][package ]['classes' ][relative_file_name ] = {'name' : class_name , 'lines' : {}, 'lines-total' : 0 , 'lines-covered' : 0 }
52+ current_package = package
53+ current_file = relative_file_name
54+ current_file_lines .clear ()
55+ current_file_lines_total = 0
56+ current_file_lines_covered = 0
57+ current_package_lines_total = 0
58+ current_package_lines_covered = 0
59+
60+ elif input_type == 'DA' :
61+ line_coverage = line_parts [- 1 ].strip ().split (',' )
62+ current_file_lines [line_coverage [0 ]] = line_coverage [1 ]
63+
64+ # Increment lines total/covered for class and package
65+ if int (line_coverage [1 ]) > 0 :
66+ current_package_lines_covered += 1
67+ current_file_lines_covered += 1
68+ current_package_lines_total += 1
69+ current_file_lines_total += 1
70+
71+ for package_name , package_data in coverage_data ['packages' ].items ():
72+ package_data ['line-rate' ] = compute_line_rate (package_data ['lines-total' ], package_data ['lines-covered' ])
73+
74+ lcov_file .close ()
75+
76+ return coverage_data
77+ else :
78+ raise '%s cannot be read' % lcov_path
79+
80+ def compute_line_rate (lines_total , lines_covered ):
81+ if lines_total == 0 :
82+ return '0.0'
83+ return str (float (float (lines_covered ) / float (lines_total )))
84+
85+ # Generate cobertura XML
86+ def generate_cobertura_xml (coverage_data , options ):
87+ '''Given a list of lines of lcov input, return a String cobertura XML
88+ representation'''
89+
90+ dom_impl = minidom .getDOMImplementation ()
91+ doctype = dom_impl .createDocumentType ("coverage" , None , "http://cobertura.sourceforge.net/xml/coverage-03.dtd" )
92+ document = dom_impl .createDocument (None , "coverage" , doctype )
93+ root = document .documentElement
94+
95+ summary = coverage_data ['summary' ]
96+
97+ root .setAttribute ('branch-rate' , '0' )
98+ root .setAttribute ('branches-covered' , '0' )
99+ root .setAttribute ('branches-valid' , '0' )
100+ root .setAttribute ('complexity' , '0' )
101+ root .setAttribute ('line-rate' , compute_line_rate (summary ['lines-total' ], summary ['lines-covered' ]))
102+ root .setAttribute ('lines-valid' , str (summary ['lines-total' ]))
103+ root .setAttribute ('timestamp' , str (int (time .time ())))
104+ root .setAttribute ('version' , '1.9' )
105+
106+ sources = document .createElement ('sources' )
107+ root .appendChild (sources )
108+
109+ packages_element = document .createElement ('packages' )
110+
111+ packages = coverage_data ['packages' ]
112+ for package_name , package_data in packages .items ():
113+ # TODO: make more robust
114+ if package_name in options .excludes :
115+ continue
116+ package_element = document .createElement ('package' )
117+ package_element .setAttribute ('line-rate' , package_data ['line-rate' ])
118+ package_element .setAttribute ('name' , package_name )
119+ classes_element = document .createElement ('classes' )
120+ for class_name , class_data in package_data ['classes' ].items ():
121+ class_element = document .createElement ('class' )
122+ class_element .setAttribute ('branch-rate' , '0' )
123+ class_element .setAttribute ('complexity' , '0' )
124+ class_element .setAttribute ('filename' , class_name )
125+ class_element .setAttribute ('line-rate' , compute_line_rate (class_data ['lines-total' ], class_data ['lines-covered' ]))
126+ class_element .setAttribute ('name' , class_data ['name' ])
127+ lines_element = document .createElement ('lines' )
128+
129+ lines = class_data ['lines' ].keys ()
130+ lines .sort ()
131+ for line_number in lines :
132+ line_element = document .createElement ('line' )
133+ line_element .setAttribute ('branch' , '0' )
134+ line_element .setAttribute ('hits' , str (class_data ['lines' ][line_number ]))
135+ line_element .setAttribute ('number' , str (line_number ))
136+ lines_element .appendChild (line_element )
137+
138+ class_element .appendChild (lines_element )
139+ classes_element .appendChild (class_element )
140+
141+ package_element .appendChild (classes_element )
142+ packages_element .appendChild (package_element )
143+ root .appendChild (packages_element )
144+
145+ return document .toprettyxml ()
146+
147+ def write_output (xml_output , output_path ):
148+ output_file = open (output_path , 'w' )
149+ print >> output_file , xml_output
150+ output_file .close ()
151+
152+ if __name__ == '__main__' :
153+ parser = OptionParser ()
154+ parser .usage = 'lcov-to-cobertura-xml.py lcov-file.dat'
155+ parser .description = 'Converts JsTestDriver lcov output to cobertura-compatible XML'
156+ parser .add_option ('-b' , '--base-dir' , help = 'Directory where source files are located' , action = 'store' , dest = 'base_dir' , default = '.' )
157+ parser .add_option ('-e' , '--excludes' , help = 'Comma-separated list of regexes of packages to exclude' , action = 'append' , dest = 'excludes' , default = [])
158+ parser .add_option ('-o' , '--output' , help = 'Path to store cobertura xml file' , action = 'store' , dest = 'output' , default = 'coverage.xml' )
159+ (options , args ) = parser .parse_args (args = sys .argv )
160+ if len (args ) != 2 :
161+ print parser .usage
162+ sys .exit (1 )
163+ coverage_data = parse_lcov_file (args [1 ], options )
164+ xml_output = generate_cobertura_xml (coverage_data , options )
165+ write_output (xml_output , options .output )
0 commit comments