coverage.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  1. #!/usr/bin/env python3
  2. #
  3. # Script to find coverage info after running tests.
  4. #
  5. # Example:
  6. # ./scripts/coverage.py \
  7. # lfs.t.a.gcda lfs_util.t.a.gcda \
  8. # -Flfs.c -Flfs_util.c -slines
  9. #
  10. # Copyright (c) 2022, The littlefs authors.
  11. # Copyright (c) 2020, Arm Limited. All rights reserved.
  12. # SPDX-License-Identifier: BSD-3-Clause
  13. #
  14. import collections as co
  15. import csv
  16. import glob
  17. import itertools as it
  18. import json
  19. import math as m
  20. import os
  21. import re
  22. import shlex
  23. import subprocess as sp
  24. # TODO use explode_asserts to avoid counting assert branches?
  25. # TODO use dwarf=info to find functions for inline functions?
  26. GCDA_PATHS = ['*.gcda']
  27. GCOV_TOOL = ['gcov']
  28. # integer fields
  29. class Int(co.namedtuple('Int', 'x')):
  30. __slots__ = ()
  31. def __new__(cls, x=0):
  32. if isinstance(x, Int):
  33. return x
  34. if isinstance(x, str):
  35. try:
  36. x = int(x, 0)
  37. except ValueError:
  38. # also accept +-∞ and +-inf
  39. if re.match('^\s*\+?\s*(?:∞|inf)\s*$', x):
  40. x = m.inf
  41. elif re.match('^\s*-\s*(?:∞|inf)\s*$', x):
  42. x = -m.inf
  43. else:
  44. raise
  45. assert isinstance(x, int) or m.isinf(x), x
  46. return super().__new__(cls, x)
  47. def __str__(self):
  48. if self.x == m.inf:
  49. return '∞'
  50. elif self.x == -m.inf:
  51. return '-∞'
  52. else:
  53. return str(self.x)
  54. def __int__(self):
  55. assert not m.isinf(self.x)
  56. return self.x
  57. def __float__(self):
  58. return float(self.x)
  59. none = '%7s' % '-'
  60. def table(self):
  61. return '%7s' % (self,)
  62. diff_none = '%7s' % '-'
  63. diff_table = table
  64. def diff_diff(self, other):
  65. new = self.x if self else 0
  66. old = other.x if other else 0
  67. diff = new - old
  68. if diff == +m.inf:
  69. return '%7s' % '+∞'
  70. elif diff == -m.inf:
  71. return '%7s' % '-∞'
  72. else:
  73. return '%+7d' % diff
  74. def ratio(self, other):
  75. new = self.x if self else 0
  76. old = other.x if other else 0
  77. if m.isinf(new) and m.isinf(old):
  78. return 0.0
  79. elif m.isinf(new):
  80. return +m.inf
  81. elif m.isinf(old):
  82. return -m.inf
  83. elif not old and not new:
  84. return 0.0
  85. elif not old:
  86. return 1.0
  87. else:
  88. return (new-old) / old
  89. def __add__(self, other):
  90. return self.__class__(self.x + other.x)
  91. def __sub__(self, other):
  92. return self.__class__(self.x - other.x)
  93. def __mul__(self, other):
  94. return self.__class__(self.x * other.x)
  95. # fractional fields, a/b
  96. class Frac(co.namedtuple('Frac', 'a,b')):
  97. __slots__ = ()
  98. def __new__(cls, a=0, b=None):
  99. if isinstance(a, Frac) and b is None:
  100. return a
  101. if isinstance(a, str) and b is None:
  102. a, b = a.split('/', 1)
  103. if b is None:
  104. b = a
  105. return super().__new__(cls, Int(a), Int(b))
  106. def __str__(self):
  107. return '%s/%s' % (self.a, self.b)
  108. def __float__(self):
  109. return float(self.a)
  110. none = '%11s %7s' % ('-', '-')
  111. def table(self):
  112. t = self.a.x/self.b.x if self.b.x else 1.0
  113. return '%11s %7s' % (
  114. self,
  115. '∞%' if t == +m.inf
  116. else '-∞%' if t == -m.inf
  117. else '%.1f%%' % (100*t))
  118. diff_none = '%11s' % '-'
  119. def diff_table(self):
  120. return '%11s' % (self,)
  121. def diff_diff(self, other):
  122. new_a, new_b = self if self else (Int(0), Int(0))
  123. old_a, old_b = other if other else (Int(0), Int(0))
  124. return '%11s' % ('%s/%s' % (
  125. new_a.diff_diff(old_a).strip(),
  126. new_b.diff_diff(old_b).strip()))
  127. def ratio(self, other):
  128. new_a, new_b = self if self else (Int(0), Int(0))
  129. old_a, old_b = other if other else (Int(0), Int(0))
  130. new = new_a.x/new_b.x if new_b.x else 1.0
  131. old = old_a.x/old_b.x if old_b.x else 1.0
  132. return new - old
  133. def __add__(self, other):
  134. return self.__class__(self.a + other.a, self.b + other.b)
  135. def __sub__(self, other):
  136. return self.__class__(self.a - other.a, self.b - other.b)
  137. def __mul__(self, other):
  138. return self.__class__(self.a * other.a, self.b + other.b)
  139. def __lt__(self, other):
  140. self_t = self.a.x/self.b.x if self.b.x else 1.0
  141. other_t = other.a.x/other.b.x if other.b.x else 1.0
  142. return (self_t, self.a.x) < (other_t, other.a.x)
  143. def __gt__(self, other):
  144. return self.__class__.__lt__(other, self)
  145. def __le__(self, other):
  146. return not self.__gt__(other)
  147. def __ge__(self, other):
  148. return not self.__lt__(other)
  149. # coverage results
  150. class CoverageResult(co.namedtuple('CoverageResult', [
  151. 'file', 'function', 'line',
  152. 'calls', 'hits', 'funcs', 'lines', 'branches'])):
  153. _by = ['file', 'function', 'line']
  154. _fields = ['calls', 'hits', 'funcs', 'lines', 'branches']
  155. _types = {
  156. 'calls': Int, 'hits': Int,
  157. 'funcs': Frac, 'lines': Frac, 'branches': Frac}
  158. __slots__ = ()
  159. def __new__(cls, file='', function='', line=0,
  160. calls=0, hits=0, funcs=0, lines=0, branches=0):
  161. return super().__new__(cls, file, function, int(Int(line)),
  162. Int(calls), Int(hits), Frac(funcs), Frac(lines), Frac(branches))
  163. def __add__(self, other):
  164. return CoverageResult(self.file, self.function, self.line,
  165. max(self.calls, other.calls),
  166. max(self.hits, other.hits),
  167. self.funcs + other.funcs,
  168. self.lines + other.lines,
  169. self.branches + other.branches)
  170. def openio(path, mode='r'):
  171. if path == '-':
  172. if mode == 'r':
  173. return os.fdopen(os.dup(sys.stdin.fileno()), 'r')
  174. else:
  175. return os.fdopen(os.dup(sys.stdout.fileno()), 'w')
  176. else:
  177. return open(path, mode)
  178. def collect(gcda_paths, *,
  179. gcov_tool=GCOV_TOOL,
  180. sources=None,
  181. everything=False,
  182. **args):
  183. results = []
  184. for path in gcda_paths:
  185. # get coverage info through gcov's json output
  186. # note, gcov-tool may contain extra args
  187. cmd = GCOV_TOOL + ['-b', '-t', '--json-format', path]
  188. if args.get('verbose'):
  189. print(' '.join(shlex.quote(c) for c in cmd))
  190. proc = sp.Popen(cmd,
  191. stdout=sp.PIPE,
  192. stderr=sp.PIPE if not args.get('verbose') else None,
  193. universal_newlines=True,
  194. errors='replace',
  195. close_fds=False)
  196. data = json.load(proc.stdout)
  197. proc.wait()
  198. if proc.returncode != 0:
  199. if not args.get('verbose'):
  200. for line in proc.stderr:
  201. sys.stdout.write(line)
  202. sys.exit(-1)
  203. # collect line/branch coverage
  204. for file in data['files']:
  205. # ignore filtered sources
  206. if sources is not None:
  207. if not any(
  208. os.path.abspath(file['file']) == os.path.abspath(s)
  209. for s in sources):
  210. continue
  211. else:
  212. # default to only cwd
  213. if not everything and not os.path.commonpath([
  214. os.getcwd(),
  215. os.path.abspath(file['file'])]) == os.getcwd():
  216. continue
  217. # simplify path
  218. if os.path.commonpath([
  219. os.getcwd(),
  220. os.path.abspath(file['file'])]) == os.getcwd():
  221. file_name = os.path.relpath(file['file'])
  222. else:
  223. file_name = os.path.abspath(file['file'])
  224. for func in file['functions']:
  225. func_name = func.get('name', '(inlined)')
  226. # discard internal functions (this includes injected test cases)
  227. if not everything:
  228. if func_name.startswith('__'):
  229. continue
  230. # go ahead and add functions, later folding will merge this if
  231. # there are other hits on this line
  232. results.append(CoverageResult(
  233. file_name, func_name, func['start_line'],
  234. func['execution_count'], 0,
  235. Frac(1 if func['execution_count'] > 0 else 0, 1),
  236. 0,
  237. 0))
  238. for line in file['lines']:
  239. func_name = line.get('function_name', '(inlined)')
  240. # discard internal function (this includes injected test cases)
  241. if not everything:
  242. if func_name.startswith('__'):
  243. continue
  244. # go ahead and add lines, later folding will merge this if
  245. # there are other hits on this line
  246. results.append(CoverageResult(
  247. file_name, func_name, line['line_number'],
  248. 0, line['count'],
  249. 0,
  250. Frac(1 if line['count'] > 0 else 0, 1),
  251. Frac(
  252. sum(1 if branch['count'] > 0 else 0
  253. for branch in line['branches']),
  254. len(line['branches']))))
  255. return results
  256. def fold(Result, results, *,
  257. by=None,
  258. defines=None,
  259. **_):
  260. if by is None:
  261. by = Result._by
  262. for k in it.chain(by or [], (k for k, _ in defines or [])):
  263. if k not in Result._by and k not in Result._fields:
  264. print("error: could not find field %r?" % k)
  265. sys.exit(-1)
  266. # filter by matching defines
  267. if defines is not None:
  268. results_ = []
  269. for r in results:
  270. if all(getattr(r, k) in vs for k, vs in defines):
  271. results_.append(r)
  272. results = results_
  273. # organize results into conflicts
  274. folding = co.OrderedDict()
  275. for r in results:
  276. name = tuple(getattr(r, k) for k in by)
  277. if name not in folding:
  278. folding[name] = []
  279. folding[name].append(r)
  280. # merge conflicts
  281. folded = []
  282. for name, rs in folding.items():
  283. folded.append(sum(rs[1:], start=rs[0]))
  284. return folded
  285. def table(Result, results, diff_results=None, *,
  286. by=None,
  287. fields=None,
  288. sort=None,
  289. summary=False,
  290. all=False,
  291. percent=False,
  292. **_):
  293. all_, all = all, __builtins__.all
  294. if by is None:
  295. by = Result._by
  296. if fields is None:
  297. fields = Result._fields
  298. types = Result._types
  299. # fold again
  300. results = fold(Result, results, by=by)
  301. if diff_results is not None:
  302. diff_results = fold(Result, diff_results, by=by)
  303. # organize by name
  304. table = {
  305. ','.join(str(getattr(r, k) or '') for k in by): r
  306. for r in results}
  307. diff_table = {
  308. ','.join(str(getattr(r, k) or '') for k in by): r
  309. for r in diff_results or []}
  310. names = list(table.keys() | diff_table.keys())
  311. # sort again, now with diff info, note that python's sort is stable
  312. names.sort()
  313. if diff_results is not None:
  314. names.sort(key=lambda n: tuple(
  315. types[k].ratio(
  316. getattr(table.get(n), k, None),
  317. getattr(diff_table.get(n), k, None))
  318. for k in fields),
  319. reverse=True)
  320. if sort:
  321. for k, reverse in reversed(sort):
  322. names.sort(key=lambda n: (getattr(table[n], k),)
  323. if getattr(table.get(n), k, None) is not None else (),
  324. reverse=reverse ^ (not k or k in Result._fields))
  325. # build up our lines
  326. lines = []
  327. # header
  328. line = []
  329. line.append('%s%s' % (
  330. ','.join(by),
  331. ' (%d added, %d removed)' % (
  332. sum(1 for n in table if n not in diff_table),
  333. sum(1 for n in diff_table if n not in table))
  334. if diff_results is not None and not percent else '')
  335. if not summary else '')
  336. if diff_results is None:
  337. for k in fields:
  338. line.append(k)
  339. elif percent:
  340. for k in fields:
  341. line.append(k)
  342. else:
  343. for k in fields:
  344. line.append('o'+k)
  345. for k in fields:
  346. line.append('n'+k)
  347. for k in fields:
  348. line.append('d'+k)
  349. line.append('')
  350. lines.append(line)
  351. # entries
  352. if not summary:
  353. for name in names:
  354. r = table.get(name)
  355. if diff_results is not None:
  356. diff_r = diff_table.get(name)
  357. ratios = [
  358. types[k].ratio(
  359. getattr(r, k, None),
  360. getattr(diff_r, k, None))
  361. for k in fields]
  362. if not any(ratios) and not all_:
  363. continue
  364. line = []
  365. line.append(name)
  366. if diff_results is None:
  367. for k in fields:
  368. line.append(getattr(r, k).table()
  369. if getattr(r, k, None) is not None
  370. else types[k].none)
  371. elif percent:
  372. for k in fields:
  373. line.append(getattr(r, k).diff_table()
  374. if getattr(r, k, None) is not None
  375. else types[k].diff_none)
  376. else:
  377. for k in fields:
  378. line.append(getattr(diff_r, k).diff_table()
  379. if getattr(diff_r, k, None) is not None
  380. else types[k].diff_none)
  381. for k in fields:
  382. line.append(getattr(r, k).diff_table()
  383. if getattr(r, k, None) is not None
  384. else types[k].diff_none)
  385. for k in fields:
  386. line.append(types[k].diff_diff(
  387. getattr(r, k, None),
  388. getattr(diff_r, k, None)))
  389. if diff_results is None:
  390. line.append('')
  391. elif percent:
  392. line.append(' (%s)' % ', '.join(
  393. '+∞%' if t == +m.inf
  394. else '-∞%' if t == -m.inf
  395. else '%+.1f%%' % (100*t)
  396. for t in ratios))
  397. else:
  398. line.append(' (%s)' % ', '.join(
  399. '+∞%' if t == +m.inf
  400. else '-∞%' if t == -m.inf
  401. else '%+.1f%%' % (100*t)
  402. for t in ratios
  403. if t)
  404. if any(ratios) else '')
  405. lines.append(line)
  406. # total
  407. r = next(iter(fold(Result, results, by=[])), None)
  408. if diff_results is not None:
  409. diff_r = next(iter(fold(Result, diff_results, by=[])), None)
  410. ratios = [
  411. types[k].ratio(
  412. getattr(r, k, None),
  413. getattr(diff_r, k, None))
  414. for k in fields]
  415. line = []
  416. line.append('TOTAL')
  417. if diff_results is None:
  418. for k in fields:
  419. line.append(getattr(r, k).table()
  420. if getattr(r, k, None) is not None
  421. else types[k].none)
  422. elif percent:
  423. for k in fields:
  424. line.append(getattr(r, k).diff_table()
  425. if getattr(r, k, None) is not None
  426. else types[k].diff_none)
  427. else:
  428. for k in fields:
  429. line.append(getattr(diff_r, k).diff_table()
  430. if getattr(diff_r, k, None) is not None
  431. else types[k].diff_none)
  432. for k in fields:
  433. line.append(getattr(r, k).diff_table()
  434. if getattr(r, k, None) is not None
  435. else types[k].diff_none)
  436. for k in fields:
  437. line.append(types[k].diff_diff(
  438. getattr(r, k, None),
  439. getattr(diff_r, k, None)))
  440. if diff_results is None:
  441. line.append('')
  442. elif percent:
  443. line.append(' (%s)' % ', '.join(
  444. '+∞%' if t == +m.inf
  445. else '-∞%' if t == -m.inf
  446. else '%+.1f%%' % (100*t)
  447. for t in ratios))
  448. else:
  449. line.append(' (%s)' % ', '.join(
  450. '+∞%' if t == +m.inf
  451. else '-∞%' if t == -m.inf
  452. else '%+.1f%%' % (100*t)
  453. for t in ratios
  454. if t)
  455. if any(ratios) else '')
  456. lines.append(line)
  457. # find the best widths, note that column 0 contains the names and column -1
  458. # the ratios, so those are handled a bit differently
  459. widths = [
  460. ((max(it.chain([w], (len(l[i]) for l in lines)))+1+4-1)//4)*4-1
  461. for w, i in zip(
  462. it.chain([23], it.repeat(7)),
  463. range(len(lines[0])-1))]
  464. # print our table
  465. for line in lines:
  466. print('%-*s %s%s' % (
  467. widths[0], line[0],
  468. ' '.join('%*s' % (w, x)
  469. for w, x in zip(widths[1:], line[1:-1])),
  470. line[-1]))
  471. def annotate(Result, results, *,
  472. annotate=False,
  473. lines=False,
  474. branches=False,
  475. **args):
  476. # if neither branches/lines specified, color both
  477. if annotate and not lines and not branches:
  478. lines, branches = True, True
  479. for path in co.OrderedDict.fromkeys(r.file for r in results).keys():
  480. # flatten to line info
  481. results = fold(Result, results, by=['file', 'line'])
  482. table = {r.line: r for r in results if r.file == path}
  483. # calculate spans to show
  484. if not annotate:
  485. spans = []
  486. last = None
  487. func = None
  488. for line, r in sorted(table.items()):
  489. if ((lines and int(r.hits) == 0)
  490. or (branches and r.branches.a < r.branches.b)):
  491. if last is not None and line - last.stop <= args['context']:
  492. last = range(
  493. last.start,
  494. line+1+args['context'])
  495. else:
  496. if last is not None:
  497. spans.append((last, func))
  498. last = range(
  499. line-args['context'],
  500. line+1+args['context'])
  501. func = r.function
  502. if last is not None:
  503. spans.append((last, func))
  504. with open(path) as f:
  505. skipped = False
  506. for i, line in enumerate(f):
  507. # skip lines not in spans?
  508. if not annotate and not any(i+1 in s for s, _ in spans):
  509. skipped = True
  510. continue
  511. if skipped:
  512. skipped = False
  513. print('%s@@ %s:%d: %s @@%s' % (
  514. '\x1b[36m' if args['color'] else '',
  515. path,
  516. i+1,
  517. next(iter(f for _, f in spans)),
  518. '\x1b[m' if args['color'] else ''))
  519. # build line
  520. if line.endswith('\n'):
  521. line = line[:-1]
  522. if i+1 in table:
  523. r = table[i+1]
  524. line = '%-*s // %s hits%s' % (
  525. args['width'],
  526. line,
  527. r.hits,
  528. ', %s branches' % (r.branches,)
  529. if int(r.branches.b) else '')
  530. if args['color']:
  531. if lines and int(r.hits) == 0:
  532. line = '\x1b[1;31m%s\x1b[m' % line
  533. elif branches and r.branches.a < r.branches.b:
  534. line = '\x1b[35m%s\x1b[m' % line
  535. print(line)
  536. def main(gcda_paths, *,
  537. by=None,
  538. fields=None,
  539. defines=None,
  540. sort=None,
  541. hits=False,
  542. **args):
  543. # figure out what color should be
  544. if args.get('color') == 'auto':
  545. args['color'] = sys.stdout.isatty()
  546. elif args.get('color') == 'always':
  547. args['color'] = True
  548. else:
  549. args['color'] = False
  550. # find sizes
  551. if not args.get('use', None):
  552. # find .gcda files
  553. paths = []
  554. for path in gcda_paths:
  555. if os.path.isdir(path):
  556. path = path + '/*.gcda'
  557. for path in glob.glob(path):
  558. paths.append(path)
  559. if not paths:
  560. print("error: no .gcda files found in %r?" % gcda_paths)
  561. sys.exit(-1)
  562. results = collect(paths, **args)
  563. else:
  564. results = []
  565. with openio(args['use']) as f:
  566. reader = csv.DictReader(f, restval='')
  567. for r in reader:
  568. try:
  569. results.append(CoverageResult(
  570. **{k: r[k] for k in CoverageResult._by
  571. if k in r and r[k].strip()},
  572. **{k: r['coverage_'+k]
  573. for k in CoverageResult._fields
  574. if 'coverage_'+k in r
  575. and r['coverage_'+k].strip()}))
  576. except TypeError:
  577. pass
  578. # fold
  579. results = fold(CoverageResult, results, by=by, defines=defines)
  580. # sort, note that python's sort is stable
  581. results.sort()
  582. if sort:
  583. for k, reverse in reversed(sort):
  584. results.sort(key=lambda r: (getattr(r, k),)
  585. if getattr(r, k) is not None else (),
  586. reverse=reverse ^ (not k or k in CoverageResult._fields))
  587. # write results to CSV
  588. if args.get('output'):
  589. with openio(args['output'], 'w') as f:
  590. writer = csv.DictWriter(f,
  591. (by if by is not None else CoverageResult._by)
  592. + ['coverage_'+k for k in CoverageResult._fields])
  593. writer.writeheader()
  594. for r in results:
  595. writer.writerow(
  596. {k: getattr(r, k)
  597. for k in (by if by is not None else CoverageResult._by)}
  598. | {'coverage_'+k: getattr(r, k)
  599. for k in CoverageResult._fields})
  600. # find previous results?
  601. if args.get('diff'):
  602. diff_results = []
  603. try:
  604. with openio(args['diff']) as f:
  605. reader = csv.DictReader(f, restval='')
  606. for r in reader:
  607. try:
  608. diff_results.append(CoverageResult(
  609. **{k: r[k] for k in CoverageResult._by
  610. if k in r and r[k].strip()},
  611. **{k: r['coverage_'+k]
  612. for k in CoverageResult._fields
  613. if 'coverage_'+k in r
  614. and r['coverage_'+k].strip()}))
  615. except TypeError:
  616. pass
  617. except FileNotFoundError:
  618. pass
  619. # fold
  620. diff_results = fold(CoverageResult, diff_results,
  621. by=by, defines=defines)
  622. # print table
  623. if not args.get('quiet'):
  624. if (args.get('annotate')
  625. or args.get('lines')
  626. or args.get('branches')):
  627. # annotate sources
  628. annotate(CoverageResult, results, **args)
  629. else:
  630. # print table
  631. table(CoverageResult, results,
  632. diff_results if args.get('diff') else None,
  633. by=by if by is not None else ['function'],
  634. fields=fields if fields is not None
  635. else ['lines', 'branches'] if not hits
  636. else ['calls', 'hits'],
  637. sort=sort,
  638. **args)
  639. # catch lack of coverage
  640. if args.get('error_on_lines') and any(
  641. r.coverage_lines.a < r.coverage_lines.b for r in results):
  642. sys.exit(2)
  643. elif args.get('error_on_branches') and any(
  644. r.coverage_branches.a < r.coverage_branches.b for r in results):
  645. sys.exit(3)
  646. if __name__ == "__main__":
  647. import argparse
  648. import sys
  649. parser = argparse.ArgumentParser(
  650. description="Find coverage info after running tests.",
  651. allow_abbrev=False)
  652. parser.add_argument(
  653. 'gcda_paths',
  654. nargs='*',
  655. default=GCDA_PATHS,
  656. help="Description of where to find *.gcda files. May be a directory "
  657. "or a list of paths. Defaults to %r." % GCDA_PATHS)
  658. parser.add_argument(
  659. '-v', '--verbose',
  660. action='store_true',
  661. help="Output commands that run behind the scenes.")
  662. parser.add_argument(
  663. '-q', '--quiet',
  664. action='store_true',
  665. help="Don't show anything, useful with -o.")
  666. parser.add_argument(
  667. '-o', '--output',
  668. help="Specify CSV file to store results.")
  669. parser.add_argument(
  670. '-u', '--use',
  671. help="Don't parse anything, use this CSV file.")
  672. parser.add_argument(
  673. '-d', '--diff',
  674. help="Specify CSV file to diff against.")
  675. parser.add_argument(
  676. '-a', '--all',
  677. action='store_true',
  678. help="Show all, not just the ones that changed.")
  679. parser.add_argument(
  680. '-p', '--percent',
  681. action='store_true',
  682. help="Only show percentage change, not a full diff.")
  683. parser.add_argument(
  684. '-b', '--by',
  685. action='append',
  686. choices=CoverageResult._by,
  687. help="Group by this field.")
  688. parser.add_argument(
  689. '-f', '--field',
  690. dest='fields',
  691. action='append',
  692. choices=CoverageResult._fields,
  693. help="Show this field.")
  694. parser.add_argument(
  695. '-D', '--define',
  696. dest='defines',
  697. action='append',
  698. type=lambda x: (lambda k,v: (k, set(v.split(','))))(*x.split('=', 1)),
  699. help="Only include results where this field is this value.")
  700. class AppendSort(argparse.Action):
  701. def __call__(self, parser, namespace, value, option):
  702. if namespace.sort is None:
  703. namespace.sort = []
  704. namespace.sort.append((value, True if option == '-S' else False))
  705. parser.add_argument(
  706. '-s', '--sort',
  707. action=AppendSort,
  708. help="Sort by this field.")
  709. parser.add_argument(
  710. '-S', '--reverse-sort',
  711. action=AppendSort,
  712. help="Sort by this field, but backwards.")
  713. parser.add_argument(
  714. '-Y', '--summary',
  715. action='store_true',
  716. help="Only show the total.")
  717. parser.add_argument(
  718. '-F', '--source',
  719. dest='sources',
  720. action='append',
  721. help="Only consider definitions in this file. Defaults to anything "
  722. "in the current directory.")
  723. parser.add_argument(
  724. '--everything',
  725. action='store_true',
  726. help="Include builtin and libc specific symbols.")
  727. parser.add_argument(
  728. '--hits',
  729. action='store_true',
  730. help="Show total hits instead of coverage.")
  731. parser.add_argument(
  732. '-A', '--annotate',
  733. action='store_true',
  734. help="Show source files annotated with coverage info.")
  735. parser.add_argument(
  736. '-L', '--lines',
  737. action='store_true',
  738. help="Show uncovered lines.")
  739. parser.add_argument(
  740. '-B', '--branches',
  741. action='store_true',
  742. help="Show uncovered branches.")
  743. parser.add_argument(
  744. '-c', '--context',
  745. type=lambda x: int(x, 0),
  746. default=3,
  747. help="Show n additional lines of context. Defaults to 3.")
  748. parser.add_argument(
  749. '-W', '--width',
  750. type=lambda x: int(x, 0),
  751. default=80,
  752. help="Assume source is styled with this many columns. Defaults to 80.")
  753. parser.add_argument(
  754. '--color',
  755. choices=['never', 'always', 'auto'],
  756. default='auto',
  757. help="When to use terminal colors. Defaults to 'auto'.")
  758. parser.add_argument(
  759. '-e', '--error-on-lines',
  760. action='store_true',
  761. help="Error if any lines are not covered.")
  762. parser.add_argument(
  763. '-E', '--error-on-branches',
  764. action='store_true',
  765. help="Error if any branches are not covered.")
  766. parser.add_argument(
  767. '--gcov-tool',
  768. default=GCOV_TOOL,
  769. type=lambda x: x.split(),
  770. help="Path to the gcov tool to use. Defaults to %r." % GCOV_TOOL)
  771. sys.exit(main(**{k: v
  772. for k, v in vars(parser.parse_intermixed_args()).items()
  773. if v is not None}))