1 | # -*- coding: utf-8 -*- |
---|
2 | # |
---|
3 | # Copyright (C) 2005-2007 Christopher Lenz <cmlenz@gmx.de> |
---|
4 | # Copyright (C) 2006 Matthew Good <matt@matt-good.net> |
---|
5 | # Copyright (C) 2007-2010 Edgewall Software |
---|
6 | # All rights reserved. |
---|
7 | # |
---|
8 | # This software is licensed as described in the file COPYING, which |
---|
9 | # you should have received as part of this distribution. The terms |
---|
10 | # are also available at http://bitten.edgewall.org/wiki/License. |
---|
11 | |
---|
12 | """Recipe commands for tools commonly used in Java projects.""" |
---|
13 | |
---|
14 | from glob import glob |
---|
15 | import logging |
---|
16 | import os |
---|
17 | import posixpath |
---|
18 | import shlex |
---|
19 | import tempfile |
---|
20 | |
---|
21 | from bitten.build import CommandLine |
---|
22 | from bitten.util import xmlio |
---|
23 | |
---|
24 | log = logging.getLogger('bitten.build.javatools') |
---|
25 | |
---|
26 | __docformat__ = 'restructuredtext en' |
---|
27 | |
---|
28 | def ant(ctxt, file_=None, target=None, keep_going=False, args=None): |
---|
29 | """Run an Ant build. |
---|
30 | |
---|
31 | :param ctxt: the build context |
---|
32 | :type ctxt: `Context` |
---|
33 | :param file\_: name of the Ant build file |
---|
34 | :param target: name of the target that should be executed (optional) |
---|
35 | :param keep_going: whether Ant should keep going when errors are encountered |
---|
36 | :param args: additional arguments to pass to Ant |
---|
37 | """ |
---|
38 | executable = 'ant' |
---|
39 | ant_home = ctxt.config.get_dirpath('ant.home') |
---|
40 | if ant_home: |
---|
41 | executable = os.path.join(ant_home, 'bin', 'ant') |
---|
42 | |
---|
43 | java_home = ctxt.config.get_dirpath('java.home') |
---|
44 | if java_home: |
---|
45 | os.environ['JAVA_HOME'] = java_home |
---|
46 | |
---|
47 | logfile = tempfile.NamedTemporaryFile(prefix='ant_log', suffix='.xml') |
---|
48 | logfile.close() |
---|
49 | if args: |
---|
50 | args = shlex.split(args) |
---|
51 | else: |
---|
52 | args = [] |
---|
53 | args += ['-noinput', '-listener', 'org.apache.tools.ant.XmlLogger', |
---|
54 | '-Dant.XmlLogger.stylesheet.uri', '""', |
---|
55 | '-DXmlLogger.file', logfile.name] |
---|
56 | if file_: |
---|
57 | args += ['-buildfile', ctxt.resolve(file_)] |
---|
58 | if keep_going: |
---|
59 | args.append('-keep-going') |
---|
60 | if target: |
---|
61 | args.append(target) |
---|
62 | |
---|
63 | shell = False |
---|
64 | if os.name == 'nt': |
---|
65 | # Need to execute ant.bat through a shell on Windows |
---|
66 | shell = True |
---|
67 | |
---|
68 | cmdline = CommandLine(executable, args, cwd=ctxt.basedir, shell=shell) |
---|
69 | for out, err in cmdline.execute(): |
---|
70 | if out is not None: |
---|
71 | log.info(out) |
---|
72 | if err is not None: |
---|
73 | log.error(err) |
---|
74 | |
---|
75 | error_logged = False |
---|
76 | log_elem = xmlio.Fragment() |
---|
77 | try: |
---|
78 | xml_log = xmlio.parse(file(logfile.name, 'r')) |
---|
79 | def collect_log_messages(node): |
---|
80 | for child in node.children(): |
---|
81 | if child.name == 'message': |
---|
82 | if child.attr['priority'] == 'debug': |
---|
83 | continue |
---|
84 | log_elem.append(xmlio.Element('message', |
---|
85 | level=child.attr['priority'])[ |
---|
86 | child.gettext().replace(ctxt.basedir + os.sep, '') |
---|
87 | .replace(ctxt.basedir, '') |
---|
88 | ]) |
---|
89 | else: |
---|
90 | collect_log_messages(child) |
---|
91 | collect_log_messages(xml_log) |
---|
92 | |
---|
93 | if 'error' in xml_log.attr: |
---|
94 | ctxt.error(xml_log.attr['error']) |
---|
95 | error_logged = True |
---|
96 | |
---|
97 | except xmlio.ParseError, e: |
---|
98 | log.warning('Error parsing Ant XML log file (%s)', e) |
---|
99 | ctxt.log(log_elem) |
---|
100 | |
---|
101 | if not error_logged and cmdline.returncode != 0: |
---|
102 | ctxt.error('Ant failed (%s)' % cmdline.returncode) |
---|
103 | |
---|
104 | |
---|
105 | def _fix_traceback(result): |
---|
106 | """ |
---|
107 | Sometimes the traceback isn't prefixed with the exception type and |
---|
108 | message, so add it in if needed. |
---|
109 | """ |
---|
110 | attr = result[0].attr |
---|
111 | tracebackprefix = "" |
---|
112 | # py.test does not include the type tag in some cases so don't do this |
---|
113 | # fix when it is missing |
---|
114 | if "type" in attr: |
---|
115 | tracebackprefix = "%s: %s" % (attr['type'], attr.get('message', '')) |
---|
116 | if result[0].gettext().startswith(tracebackprefix): |
---|
117 | return result[0].gettext() |
---|
118 | else: |
---|
119 | return "\n".join((tracebackprefix, result[0].gettext())) |
---|
120 | |
---|
121 | |
---|
122 | def junit(ctxt, file_=None, srcdir=None): |
---|
123 | """Extract test results from a JUnit XML report. |
---|
124 | |
---|
125 | :param ctxt: the build context |
---|
126 | :type ctxt: `Context` |
---|
127 | :param file\_: path to the JUnit XML test results; may contain globbing |
---|
128 | wildcards for matching multiple results files |
---|
129 | :param srcdir: name of the directory containing the test sources, used to |
---|
130 | link test results to the corresponding source files |
---|
131 | """ |
---|
132 | assert file_, 'Missing required attribute "file"' |
---|
133 | try: |
---|
134 | total, failed = 0, 0 |
---|
135 | results = xmlio.Fragment() |
---|
136 | for path in glob(ctxt.resolve(file_)): |
---|
137 | fileobj = file(path, 'r') |
---|
138 | try: |
---|
139 | output = xmlio.parse(fileobj) |
---|
140 | finally: |
---|
141 | fileobj.close() |
---|
142 | if output.name == 'testsuites': |
---|
143 | # top level wrapper for testsuites |
---|
144 | testcases = [] |
---|
145 | for t_suite in output.children('testsuite'): |
---|
146 | testcases.extend([ |
---|
147 | t_case for t_case in t_suite.children('testcase')]) |
---|
148 | else: |
---|
149 | testcases = [t_case for t_case in output.children('testcase')] |
---|
150 | for testcase in testcases: |
---|
151 | test = xmlio.Element('test') |
---|
152 | test.attr['fixture'] = testcase.attr['classname'] |
---|
153 | test.attr['name'] = testcase.attr['name'] |
---|
154 | if 'time' in testcase.attr: |
---|
155 | test.attr['duration'] = testcase.attr['time'] |
---|
156 | if srcdir is not None: |
---|
157 | cls = testcase.attr['classname'].split('.') |
---|
158 | test.attr['file'] = posixpath.join(srcdir, *cls) + \ |
---|
159 | '.java' |
---|
160 | |
---|
161 | result = list(testcase.children()) |
---|
162 | if result: |
---|
163 | junit_status = result[0].name |
---|
164 | test.append(xmlio.Element('traceback')[ |
---|
165 | _fix_traceback(result)]) |
---|
166 | if junit_status == 'skipped': |
---|
167 | test.attr['status'] = 'ignore' |
---|
168 | elif junit_status == 'error': |
---|
169 | test.attr['status'] = 'error' |
---|
170 | failed += 1 |
---|
171 | else: |
---|
172 | test.attr['status'] = 'failure' |
---|
173 | failed += 1 |
---|
174 | else: |
---|
175 | test.attr['status'] = 'success' |
---|
176 | |
---|
177 | results.append(test) |
---|
178 | total += 1 |
---|
179 | if failed: |
---|
180 | ctxt.error('%d of %d test%s failed' % (failed, total, |
---|
181 | total != 1 and 's' or '')) |
---|
182 | ctxt.report('test', results) |
---|
183 | except IOError, e: |
---|
184 | log.warning('Error opening JUnit results file (%s)', e) |
---|
185 | except xmlio.ParseError, e: |
---|
186 | log.warning('Error parsing JUnit results file (%s)', e) |
---|
187 | |
---|
188 | |
---|
189 | class _LineCounter(object): |
---|
190 | def __init__(self): |
---|
191 | self.lines = [] |
---|
192 | self.covered = 0 |
---|
193 | self.num_lines = 0 |
---|
194 | |
---|
195 | def __getitem__(self, idx): |
---|
196 | if idx >= len(self.lines): |
---|
197 | return 0 |
---|
198 | return self.lines[idx] |
---|
199 | |
---|
200 | def __setitem__(self, idx, val): |
---|
201 | idx = int(idx) - 1 # 1-indexed to 0-indexed |
---|
202 | from itertools import repeat |
---|
203 | if idx >= len(self.lines): |
---|
204 | self.lines.extend(repeat('-', idx - len(self.lines) + 1)) |
---|
205 | self.lines[idx] = val |
---|
206 | self.num_lines += 1 |
---|
207 | if val != '0': |
---|
208 | self.covered += 1 |
---|
209 | |
---|
210 | def line_hits(self): |
---|
211 | return ' '.join(self.lines) |
---|
212 | line_hits = property(line_hits) |
---|
213 | |
---|
214 | def percentage(self): |
---|
215 | if self.num_lines == 0: |
---|
216 | return 0 |
---|
217 | return int(round(self.covered * 100. / self.num_lines)) |
---|
218 | percentage = property(percentage) |
---|
219 | |
---|
220 | |
---|
221 | def cobertura(ctxt, file_=None): |
---|
222 | """Extract test coverage information from a Cobertura XML report. |
---|
223 | |
---|
224 | :param ctxt: the build context |
---|
225 | :type ctxt: `Context` |
---|
226 | :param file\_: path to the Cobertura XML output |
---|
227 | """ |
---|
228 | assert file_, 'Missing required attribute "file"' |
---|
229 | |
---|
230 | coverage = xmlio.Fragment() |
---|
231 | doc = xmlio.parse(open(ctxt.resolve(file_))) |
---|
232 | srcdir = [s.gettext().strip() for ss in doc.children('sources') |
---|
233 | for s in ss.children('source')][0] |
---|
234 | |
---|
235 | classes = [cls for pkgs in doc.children('packages') |
---|
236 | for pkg in pkgs.children('package') |
---|
237 | for clss in pkg.children('classes') |
---|
238 | for cls in clss.children('class')] |
---|
239 | |
---|
240 | counters = {} |
---|
241 | class_names = {} |
---|
242 | |
---|
243 | for cls in classes: |
---|
244 | filename = cls.attr['filename'].replace(os.sep, '/') |
---|
245 | name = cls.attr['name'] |
---|
246 | if not '$' in name: # ignore internal classes |
---|
247 | class_names[filename] = name |
---|
248 | counter = counters.get(filename) |
---|
249 | if counter is None: |
---|
250 | counter = counters[filename] = _LineCounter() |
---|
251 | lines = [l for ls in cls.children('lines') |
---|
252 | for l in ls.children('line')] |
---|
253 | for line in lines: |
---|
254 | counter[line.attr['number']] = line.attr['hits'] |
---|
255 | |
---|
256 | for filename, name in class_names.iteritems(): |
---|
257 | counter = counters[filename] |
---|
258 | module = xmlio.Element('coverage', name=name, |
---|
259 | file=posixpath.join(srcdir, filename), |
---|
260 | lines=counter.num_lines, |
---|
261 | percentage=counter.percentage) |
---|
262 | module.append(xmlio.Element('line_hits')[counter.line_hits]) |
---|
263 | coverage.append(module) |
---|
264 | ctxt.report('coverage', coverage) |
---|