1 | # -*- coding: utf-8 -*- |
---|
2 | # |
---|
3 | # Copyright (C) 2005-2007 Christopher Lenz <cmlenz@gmx.de> |
---|
4 | # Copyright (C) 2007-2010 Edgewall Software |
---|
5 | # All rights reserved. |
---|
6 | # |
---|
7 | # This software is licensed as described in the file COPYING, which |
---|
8 | # you should have received as part of this distribution. The terms |
---|
9 | # are also available at http://bitten.edgewall.org/wiki/License. |
---|
10 | |
---|
11 | """Recipe commands for build tasks commonly used for C/C++ projects.""" |
---|
12 | |
---|
13 | import logging |
---|
14 | import re |
---|
15 | import os |
---|
16 | import posixpath |
---|
17 | import shlex |
---|
18 | |
---|
19 | from bitten.build import CommandLine, FileSet |
---|
20 | from bitten.util import xmlio |
---|
21 | |
---|
22 | log = logging.getLogger('bitten.build.ctools') |
---|
23 | |
---|
24 | __docformat__ = 'restructuredtext en' |
---|
25 | |
---|
26 | def configure(ctxt, file_='configure', enable=None, disable=None, with_=None, |
---|
27 | without=None, cflags=None, cxxflags=None, prefix=None, **kw): |
---|
28 | """Run a ``configure`` script. |
---|
29 | |
---|
30 | :param ctxt: the build context |
---|
31 | :type ctxt: `Context` |
---|
32 | :param file\_: name of the configure script |
---|
33 | :param enable: names of the features to enable, seperated by spaces |
---|
34 | :param disable: names of the features to disable, separated by spaces |
---|
35 | :param with\_: names of external packages to include |
---|
36 | :param without: names of external packages to exclude |
---|
37 | :param cflags: ``CFLAGS`` to pass to the configure script |
---|
38 | :param cxxflags: ``CXXFLAGS`` to pass to the configure script |
---|
39 | :param prefix: install prefix to pass to the configure script, will be postfixed by the machine name from the build |
---|
40 | """ |
---|
41 | args = [] |
---|
42 | if enable: |
---|
43 | args += ['--enable-%s' % feature for feature in enable.split()] |
---|
44 | if disable: |
---|
45 | args += ['--disable-%s' % feature for feature in disable.split()] |
---|
46 | # since 'with' is a reserved word in python, we need to handle the argument carefully |
---|
47 | with_ = kw.pop('with', with_) |
---|
48 | for key in kw: |
---|
49 | raise TypeError("configure() got an unexpected keyword argument '%s'" % key) |
---|
50 | if with_: |
---|
51 | for pkg in with_.split(): |
---|
52 | pkg_path = pkg + '.path' |
---|
53 | if pkg_path in ctxt.config: |
---|
54 | args.append('--with-%s=%s' % (pkg, ctxt.config[pkg_path])) |
---|
55 | else: |
---|
56 | args.append('--with-%s' % pkg) |
---|
57 | if without: |
---|
58 | args += ['--without-%s' % pkg for pkg in without.split()] |
---|
59 | if cflags: |
---|
60 | args.append('CFLAGS=%s' % cflags) |
---|
61 | if cxxflags: |
---|
62 | args.append('CXXFLAGS=%s' % cxxflags) |
---|
63 | if prefix: |
---|
64 | args.append('--prefix=%s' % prefix) |
---|
65 | |
---|
66 | from bitten.build import shtools |
---|
67 | returncode = shtools.execute(ctxt, file_=file_, args=args) |
---|
68 | if returncode != 0: |
---|
69 | ctxt.error('configure failed (%s)' % returncode) |
---|
70 | |
---|
71 | def autoreconf(ctxt, file_='configure', force=None, install=None, symlink=None, |
---|
72 | warnings=None, prepend_include=None, include =None): |
---|
73 | """Run the autotoll ``autoreconf``. |
---|
74 | |
---|
75 | :param ctxt: the build context |
---|
76 | :type ctxt: `Context` |
---|
77 | :param force: consider all files obsolete |
---|
78 | :param install: copy missing auxiliary files |
---|
79 | :param symlink: install symbolic links instead of copies |
---|
80 | :param warnings: report the warnings falling in CATEGORY |
---|
81 | :param prepend_include: prepend directories to search path |
---|
82 | :param include: append directories to search path |
---|
83 | |
---|
84 | """ |
---|
85 | args = [] |
---|
86 | if install: |
---|
87 | args.append('--install') |
---|
88 | if symlink: |
---|
89 | args.append('--symlink') |
---|
90 | if force: |
---|
91 | args.append('--force') |
---|
92 | if warnings: |
---|
93 | args.append('--warnings=%s' % warnings) |
---|
94 | |
---|
95 | if include: |
---|
96 | args += ['--include=%s' % inc for inc in include.split()] |
---|
97 | if prepend_include: |
---|
98 | args += ['--prepend-include=%s' % pinc for pinc in prepend_include.split()] |
---|
99 | |
---|
100 | from bitten.build import shtools |
---|
101 | returncode = shtools.execute(ctxt, 'autoreconf', args=args) |
---|
102 | if returncode != 0: |
---|
103 | ctxt.error('autoreconf failed (%s)' % returncode) |
---|
104 | |
---|
105 | def make(ctxt, target=None, file_=None, keep_going=False, directory=None, jobs=None, args=None): |
---|
106 | """Execute a Makefile target. |
---|
107 | |
---|
108 | :param ctxt: the build context |
---|
109 | :type ctxt: `Context` |
---|
110 | :param file\_: name of the Makefile |
---|
111 | :param keep_going: whether make should keep going when errors are |
---|
112 | encountered |
---|
113 | :param directory: directory in which to build; defaults to project source directory |
---|
114 | :param jobs: number of concurrent jobs to run |
---|
115 | :param args: command-line arguments to pass to the script |
---|
116 | """ |
---|
117 | executable = ctxt.config.get_filepath('make.path') or 'make' |
---|
118 | |
---|
119 | if directory is None: |
---|
120 | directory = ctxt.basedir |
---|
121 | |
---|
122 | margs = ['--directory', directory] |
---|
123 | |
---|
124 | if file_: |
---|
125 | margs += ['--file', ctxt.resolve(file_)] |
---|
126 | if keep_going: |
---|
127 | margs.append('--keep-going') |
---|
128 | if target: |
---|
129 | margs.append(target) |
---|
130 | if jobs: |
---|
131 | margs += ['--jobs', jobs] |
---|
132 | |
---|
133 | if args: |
---|
134 | if isinstance(args, basestring): |
---|
135 | margs += shlex.split(args) |
---|
136 | |
---|
137 | from bitten.build import shtools |
---|
138 | returncode = shtools.execute(ctxt, executable=executable, args=margs) |
---|
139 | if returncode != 0: |
---|
140 | ctxt.error('make failed (%s)' % returncode) |
---|
141 | |
---|
142 | def cppunit(ctxt, file_=None, srcdir=None): |
---|
143 | """Collect CppUnit XML data. |
---|
144 | |
---|
145 | :param ctxt: the build context |
---|
146 | :type ctxt: `Context` |
---|
147 | :param file\_: path of the file containing the CppUnit results; may contain |
---|
148 | globbing wildcards to match multiple files |
---|
149 | :param srcdir: name of the directory containing the source files, used to |
---|
150 | link the test results to the corresponding files |
---|
151 | """ |
---|
152 | assert file_, 'Missing required attribute "file"' |
---|
153 | |
---|
154 | try: |
---|
155 | fileobj = file(ctxt.resolve(file_), 'r') |
---|
156 | try: |
---|
157 | total, failed = 0, 0 |
---|
158 | results = xmlio.Fragment() |
---|
159 | for group in xmlio.parse(fileobj): |
---|
160 | if group.name not in ('FailedTests', 'SuccessfulTests'): |
---|
161 | continue |
---|
162 | for child in group.children(): |
---|
163 | test = xmlio.Element('test') |
---|
164 | name = child.children('Name').next().gettext() |
---|
165 | if '::' in name: |
---|
166 | parts = name.split('::') |
---|
167 | test.attr['fixture'] = '::'.join(parts[:-1]) |
---|
168 | name = parts[-1] |
---|
169 | test.attr['name'] = name |
---|
170 | |
---|
171 | for location in child.children('Location'): |
---|
172 | for file_elem in location.children('File'): |
---|
173 | filepath = file_elem.gettext() |
---|
174 | if srcdir is not None: |
---|
175 | filepath = posixpath.join(srcdir, filepath) |
---|
176 | test.attr['file'] = filepath |
---|
177 | break |
---|
178 | for line_elem in location.children('Line'): |
---|
179 | test.attr['line'] = line_elem.gettext() |
---|
180 | break |
---|
181 | break |
---|
182 | |
---|
183 | if child.name == 'FailedTest': |
---|
184 | for message in child.children('Message'): |
---|
185 | test.append(xmlio.Element('traceback')[ |
---|
186 | message.gettext() |
---|
187 | ]) |
---|
188 | test.attr['status'] = 'failure' |
---|
189 | failed += 1 |
---|
190 | else: |
---|
191 | test.attr['status'] = 'success' |
---|
192 | |
---|
193 | results.append(test) |
---|
194 | total += 1 |
---|
195 | |
---|
196 | if failed: |
---|
197 | ctxt.error('%d of %d test%s failed' % (failed, total, |
---|
198 | total != 1 and 's' or '')) |
---|
199 | |
---|
200 | ctxt.report('test', results) |
---|
201 | |
---|
202 | finally: |
---|
203 | fileobj.close() |
---|
204 | |
---|
205 | except IOError, e: |
---|
206 | log.warning('Error opening CppUnit results file (%s)', e) |
---|
207 | except xmlio.ParseError, e: |
---|
208 | print e |
---|
209 | log.warning('Error parsing CppUnit results file (%s)', e) |
---|
210 | |
---|
211 | def cunit (ctxt, file_=None, srcdir=None): |
---|
212 | """Collect CUnit XML data. |
---|
213 | |
---|
214 | :param ctxt: the build context |
---|
215 | :type ctxt: `Context` |
---|
216 | :param file\_: path of the file containing the CUnit results; may contain |
---|
217 | globbing wildcards to match multiple files |
---|
218 | :param srcdir: name of the directory containing the source files, used to |
---|
219 | link the test results to the corresponding files |
---|
220 | """ |
---|
221 | assert file_, 'Missing required attribute "file"' |
---|
222 | |
---|
223 | try: |
---|
224 | fileobj = file(ctxt.resolve(file_), 'r') |
---|
225 | try: |
---|
226 | total, failed = 0, 0 |
---|
227 | results = xmlio.Fragment() |
---|
228 | log_elem = xmlio.Fragment() |
---|
229 | def info (msg): |
---|
230 | log.info (msg) |
---|
231 | log_elem.append (xmlio.Element ('message', level='info')[msg]) |
---|
232 | def warning (msg): |
---|
233 | log.warning (msg) |
---|
234 | log_elem.append (xmlio.Element ('message', level='warning')[msg]) |
---|
235 | def error (msg): |
---|
236 | log.error (msg) |
---|
237 | log_elem.append (xmlio.Element ('message', level='error')[msg]) |
---|
238 | for node in xmlio.parse(fileobj): |
---|
239 | if node.name != 'CUNIT_RESULT_LISTING': |
---|
240 | continue |
---|
241 | for suiteRun in node.children ('CUNIT_RUN_SUITE'): |
---|
242 | for suite in suiteRun.children(): |
---|
243 | if suite.name not in ('CUNIT_RUN_SUITE_SUCCESS', 'CUNIT_RUN_SUITE_FAILURE'): |
---|
244 | warning ("Unknown node: %s" % suite.name) |
---|
245 | continue |
---|
246 | suiteName = suite.children ('SUITE_NAME').next().gettext() |
---|
247 | info ("%s [%s]" % ("*" * (57 - len (suiteName)), suiteName)) |
---|
248 | for record in suite.children ('CUNIT_RUN_TEST_RECORD'): |
---|
249 | for result in record.children(): |
---|
250 | if result.name not in ('CUNIT_RUN_TEST_SUCCESS', 'CUNIT_RUN_TEST_FAILURE'): |
---|
251 | continue |
---|
252 | testName = result.children ('TEST_NAME').next().gettext() |
---|
253 | info ("Running %s..." % testName); |
---|
254 | test = xmlio.Element('test') |
---|
255 | test.attr['fixture'] = suiteName |
---|
256 | test.attr['name'] = testName |
---|
257 | if result.name == 'CUNIT_RUN_TEST_FAILURE': |
---|
258 | error ("%s(%d): %s" |
---|
259 | % (result.children ('FILE_NAME').next().gettext(), |
---|
260 | int (result.children ('LINE_NUMBER').next().gettext()), |
---|
261 | result.children ('CONDITION').next().gettext())) |
---|
262 | test.attr['status'] = 'failure' |
---|
263 | failed += 1 |
---|
264 | else: |
---|
265 | test.attr['status'] = 'success' |
---|
266 | |
---|
267 | results.append(test) |
---|
268 | total += 1 |
---|
269 | |
---|
270 | if failed: |
---|
271 | ctxt.error('%d of %d test%s failed' % (failed, total, |
---|
272 | total != 1 and 's' or '')) |
---|
273 | |
---|
274 | ctxt.report('test', results) |
---|
275 | ctxt.log (log_elem) |
---|
276 | |
---|
277 | finally: |
---|
278 | fileobj.close() |
---|
279 | |
---|
280 | except IOError, e: |
---|
281 | log.warning('Error opening CUnit results file (%s)', e) |
---|
282 | except xmlio.ParseError, e: |
---|
283 | print e |
---|
284 | log.warning('Error parsing CUnit results file (%s)', e) |
---|
285 | |
---|
286 | def gcov(ctxt, include=None, exclude=None, prefix=None, root=""): |
---|
287 | """Run ``gcov`` to extract coverage data where available. |
---|
288 | |
---|
289 | :param ctxt: the build context |
---|
290 | :type ctxt: `Context` |
---|
291 | :param include: patterns of files and directories to include |
---|
292 | :param exclude: patterns of files and directories that should be excluded |
---|
293 | :param prefix: optional prefix name that is added to object files by the |
---|
294 | build system |
---|
295 | :param root: optional root path in which the build system puts the object |
---|
296 | files |
---|
297 | """ |
---|
298 | file_re = re.compile(r'^File (?:\'|\`)(?P<file>[^\']+)\'\s*$') |
---|
299 | lines_re = re.compile(r'^Lines executed:(?P<cov>\d+\.\d+)\% of (?P<num>\d+)\s*$') |
---|
300 | |
---|
301 | files = [] |
---|
302 | for filename in FileSet(ctxt.basedir, include, exclude): |
---|
303 | if os.path.splitext(filename)[1] in ('.c', '.cpp', '.cc', '.cxx'): |
---|
304 | files.append(filename) |
---|
305 | |
---|
306 | coverage = xmlio.Fragment() |
---|
307 | log_elem = xmlio.Fragment() |
---|
308 | def info (msg): |
---|
309 | log.info (msg) |
---|
310 | log_elem.append (xmlio.Element ('message', level='info')[msg]) |
---|
311 | def warning (msg): |
---|
312 | log.warning (msg) |
---|
313 | log_elem.append (xmlio.Element ('message', level='warning')[msg]) |
---|
314 | def error (msg): |
---|
315 | log.error (msg) |
---|
316 | log_elem.append (xmlio.Element ('message', level='error')[msg]) |
---|
317 | |
---|
318 | for srcfile in files: |
---|
319 | # Determine the coverage for each source file by looking for a .gcno |
---|
320 | # and .gcda pair |
---|
321 | info ("Getting coverage info for %s" % srcfile) |
---|
322 | filepath, filename = os.path.split(srcfile) |
---|
323 | stem = os.path.splitext(filename)[0] |
---|
324 | if prefix is not None: |
---|
325 | stem = prefix + '-' + stem |
---|
326 | |
---|
327 | objfile = os.path.join (root, filepath, stem + '.o') |
---|
328 | if not os.path.isfile(ctxt.resolve(objfile)): |
---|
329 | warning ('No object file found for %s at %s' % (srcfile, objfile)) |
---|
330 | continue |
---|
331 | if not os.path.isfile (ctxt.resolve (os.path.join (root, filepath, stem + '.gcno'))): |
---|
332 | warning ('No .gcno file found for %s at %s' % (srcfile, os.path.join (root, filepath, stem + '.gcno'))) |
---|
333 | continue |
---|
334 | if not os.path.isfile (ctxt.resolve (os.path.join (root, filepath, stem + '.gcda'))): |
---|
335 | warning ('No .gcda file found for %s at %s' % (srcfile, os.path.join (root, filepath, stem + '.gcda'))) |
---|
336 | continue |
---|
337 | |
---|
338 | num_lines, num_covered = 0, 0 |
---|
339 | skip_block = False |
---|
340 | cmd = CommandLine('gcov', ['-o', objfile, srcfile], |
---|
341 | cwd=ctxt.basedir) |
---|
342 | for out, err in cmd.execute(): |
---|
343 | if out == '': # catch blank lines, reset the block state... |
---|
344 | skip_block = False |
---|
345 | elif out and not skip_block: |
---|
346 | # Check for a file name |
---|
347 | match = file_re.match(out) |
---|
348 | if match: |
---|
349 | if os.path.isabs(match.group('file')): |
---|
350 | skip_block = True |
---|
351 | continue |
---|
352 | else: |
---|
353 | # check for a "Lines executed" message |
---|
354 | match = lines_re.match(out) |
---|
355 | if match: |
---|
356 | lines = float(match.group('num')) |
---|
357 | cov = float(match.group('cov')) |
---|
358 | num_covered += int(lines * cov / 100) |
---|
359 | num_lines += int(lines) |
---|
360 | if cmd.returncode != 0: |
---|
361 | continue |
---|
362 | |
---|
363 | gcov_file = ctxt.resolve( os.path.join( root, filename + '.gcov' ) ) |
---|
364 | if os.path.isfile( gcov_file ): |
---|
365 | line_hits = line_hits_from_gcov(gcov_file, info, warning) |
---|
366 | else: |
---|
367 | line_hits = [] |
---|
368 | warning ('No .gcov file found for %s at %s' % (srcfile, gcov_file)) |
---|
369 | |
---|
370 | module = xmlio.Element('coverage', name=os.path.basename(srcfile), |
---|
371 | file=srcfile.replace(os.sep, '/'), |
---|
372 | lines=num_lines, percentage=0, |
---|
373 | line_hits=' '.join(line_hits)) |
---|
374 | if num_lines: |
---|
375 | percent = int(round(num_covered * 100 / num_lines)) |
---|
376 | module.attr['percentage'] = percent |
---|
377 | coverage.append(module) |
---|
378 | |
---|
379 | ctxt.report('coverage', coverage) |
---|
380 | ctxt.log (log_elem) |
---|
381 | |
---|
382 | def line_hits_from_gcov(gcov_file, info, warning): |
---|
383 | """Read per line statistics from a .gcov file and transform to line_hits |
---|
384 | |
---|
385 | :param gcov_file: path to the file to read from |
---|
386 | :param info: function for info output |
---|
387 | :param warning: function for warning output |
---|
388 | """ |
---|
389 | info ("Getting per line coverage of %s" % gcov_file) |
---|
390 | with open(gcov_file, 'r') as coverageFile: |
---|
391 | pattern = re.compile('([\d#=-]+)[:\ ]+(\d+)') |
---|
392 | line_hits = [] |
---|
393 | for gcov_file_line_number, line in enumerate(coverageFile): |
---|
394 | match = pattern.search(line) |
---|
395 | # ignore malformed lines |
---|
396 | if not match: |
---|
397 | warning ('Could not parse line %i in %s: %s' % (gcov_file_line_number, gcov_file, line)) |
---|
398 | # mark this line as unknown |
---|
399 | line_hits.append('???') |
---|
400 | continue |
---|
401 | match = match.groups() |
---|
402 | |
---|
403 | source_line_execution_count = match[0] |
---|
404 | source_file_line_number = match[1] |
---|
405 | |
---|
406 | if(int(source_file_line_number) > 0): |
---|
407 | if source_line_execution_count == '-': |
---|
408 | line_hits.append('-') |
---|
409 | elif source_line_execution_count == '#####' or source_line_execution_count == '=====': |
---|
410 | line_hits.append('0') |
---|
411 | else: |
---|
412 | line_hits.append(source_line_execution_count) |
---|
413 | return line_hits |
---|
414 | warning('Could not gather per line information of %s' % (gcov_file)) |
---|
415 | return [] |
---|