coverage.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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. header = []
  329. header.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. header.append(k)
  339. elif percent:
  340. for k in fields:
  341. header.append(k)
  342. else:
  343. for k in fields:
  344. header.append('o'+k)
  345. for k in fields:
  346. header.append('n'+k)
  347. for k in fields:
  348. header.append('d'+k)
  349. header.append('')
  350. lines.append(header)
  351. def table_entry(name, r, diff_r=None, ratios=[]):
  352. entry = []
  353. entry.append(name)
  354. if diff_results is None:
  355. for k in fields:
  356. entry.append(getattr(r, k).table()
  357. if getattr(r, k, None) is not None
  358. else types[k].none)
  359. elif percent:
  360. for k in fields:
  361. entry.append(getattr(r, k).diff_table()
  362. if getattr(r, k, None) is not None
  363. else types[k].diff_none)
  364. else:
  365. for k in fields:
  366. entry.append(getattr(diff_r, k).diff_table()
  367. if getattr(diff_r, k, None) is not None
  368. else types[k].diff_none)
  369. for k in fields:
  370. entry.append(getattr(r, k).diff_table()
  371. if getattr(r, k, None) is not None
  372. else types[k].diff_none)
  373. for k in fields:
  374. entry.append(types[k].diff_diff(
  375. getattr(r, k, None),
  376. getattr(diff_r, k, None)))
  377. if diff_results is None:
  378. entry.append('')
  379. elif percent:
  380. entry.append(' (%s)' % ', '.join(
  381. '+∞%' if t == +m.inf
  382. else '-∞%' if t == -m.inf
  383. else '%+.1f%%' % (100*t)
  384. for t in ratios))
  385. else:
  386. entry.append(' (%s)' % ', '.join(
  387. '+∞%' if t == +m.inf
  388. else '-∞%' if t == -m.inf
  389. else '%+.1f%%' % (100*t)
  390. for t in ratios
  391. if t)
  392. if any(ratios) else '')
  393. return entry
  394. # entries
  395. if not summary:
  396. for name in names:
  397. r = table.get(name)
  398. if diff_results is None:
  399. diff_r = None
  400. ratios = None
  401. else:
  402. diff_r = diff_table.get(name)
  403. ratios = [
  404. types[k].ratio(
  405. getattr(r, k, None),
  406. getattr(diff_r, k, None))
  407. for k in fields]
  408. if not all_ and not any(ratios):
  409. continue
  410. lines.append(table_entry(name, r, diff_r, ratios))
  411. # total
  412. r = next(iter(fold(Result, results, by=[])), None)
  413. if diff_results is None:
  414. diff_r = None
  415. ratios = None
  416. else:
  417. diff_r = next(iter(fold(Result, diff_results, by=[])), None)
  418. ratios = [
  419. types[k].ratio(
  420. getattr(r, k, None),
  421. getattr(diff_r, k, None))
  422. for k in fields]
  423. lines.append(table_entry('TOTAL', r, diff_r, ratios))
  424. # find the best widths, note that column 0 contains the names and column -1
  425. # the ratios, so those are handled a bit differently
  426. widths = [
  427. ((max(it.chain([w], (len(l[i]) for l in lines)))+1+4-1)//4)*4-1
  428. for w, i in zip(
  429. it.chain([23], it.repeat(7)),
  430. range(len(lines[0])-1))]
  431. # print our table
  432. for line in lines:
  433. print('%-*s %s%s' % (
  434. widths[0], line[0],
  435. ' '.join('%*s' % (w, x)
  436. for w, x in zip(widths[1:], line[1:-1])),
  437. line[-1]))
  438. def annotate(Result, results, *,
  439. annotate=False,
  440. lines=False,
  441. branches=False,
  442. **args):
  443. # if neither branches/lines specified, color both
  444. if annotate and not lines and not branches:
  445. lines, branches = True, True
  446. for path in co.OrderedDict.fromkeys(r.file for r in results).keys():
  447. # flatten to line info
  448. results = fold(Result, results, by=['file', 'line'])
  449. table = {r.line: r for r in results if r.file == path}
  450. # calculate spans to show
  451. if not annotate:
  452. spans = []
  453. last = None
  454. func = None
  455. for line, r in sorted(table.items()):
  456. if ((lines and int(r.hits) == 0)
  457. or (branches and r.branches.a < r.branches.b)):
  458. if last is not None and line - last.stop <= args['context']:
  459. last = range(
  460. last.start,
  461. line+1+args['context'])
  462. else:
  463. if last is not None:
  464. spans.append((last, func))
  465. last = range(
  466. line-args['context'],
  467. line+1+args['context'])
  468. func = r.function
  469. if last is not None:
  470. spans.append((last, func))
  471. with open(path) as f:
  472. skipped = False
  473. for i, line in enumerate(f):
  474. # skip lines not in spans?
  475. if not annotate and not any(i+1 in s for s, _ in spans):
  476. skipped = True
  477. continue
  478. if skipped:
  479. skipped = False
  480. print('%s@@ %s:%d: %s @@%s' % (
  481. '\x1b[36m' if args['color'] else '',
  482. path,
  483. i+1,
  484. next(iter(f for _, f in spans)),
  485. '\x1b[m' if args['color'] else ''))
  486. # build line
  487. if line.endswith('\n'):
  488. line = line[:-1]
  489. if i+1 in table:
  490. r = table[i+1]
  491. line = '%-*s // %s hits%s' % (
  492. args['width'],
  493. line,
  494. r.hits,
  495. ', %s branches' % (r.branches,)
  496. if int(r.branches.b) else '')
  497. if args['color']:
  498. if lines and int(r.hits) == 0:
  499. line = '\x1b[1;31m%s\x1b[m' % line
  500. elif branches and r.branches.a < r.branches.b:
  501. line = '\x1b[35m%s\x1b[m' % line
  502. print(line)
  503. def main(gcda_paths, *,
  504. by=None,
  505. fields=None,
  506. defines=None,
  507. sort=None,
  508. hits=False,
  509. **args):
  510. # figure out what color should be
  511. if args.get('color') == 'auto':
  512. args['color'] = sys.stdout.isatty()
  513. elif args.get('color') == 'always':
  514. args['color'] = True
  515. else:
  516. args['color'] = False
  517. # find sizes
  518. if not args.get('use', None):
  519. # find .gcda files
  520. paths = []
  521. for path in gcda_paths:
  522. if os.path.isdir(path):
  523. path = path + '/*.gcda'
  524. for path in glob.glob(path):
  525. paths.append(path)
  526. if not paths:
  527. print("error: no .gcda files found in %r?" % gcda_paths)
  528. sys.exit(-1)
  529. results = collect(paths, **args)
  530. else:
  531. results = []
  532. with openio(args['use']) as f:
  533. reader = csv.DictReader(f, restval='')
  534. for r in reader:
  535. try:
  536. results.append(CoverageResult(
  537. **{k: r[k] for k in CoverageResult._by
  538. if k in r and r[k].strip()},
  539. **{k: r['coverage_'+k]
  540. for k in CoverageResult._fields
  541. if 'coverage_'+k in r
  542. and r['coverage_'+k].strip()}))
  543. except TypeError:
  544. pass
  545. # fold
  546. results = fold(CoverageResult, results, by=by, defines=defines)
  547. # sort, note that python's sort is stable
  548. results.sort()
  549. if sort:
  550. for k, reverse in reversed(sort):
  551. results.sort(key=lambda r: (getattr(r, k),)
  552. if getattr(r, k) is not None else (),
  553. reverse=reverse ^ (not k or k in CoverageResult._fields))
  554. # write results to CSV
  555. if args.get('output'):
  556. with openio(args['output'], 'w') as f:
  557. writer = csv.DictWriter(f,
  558. (by if by is not None else CoverageResult._by)
  559. + ['coverage_'+k for k in CoverageResult._fields])
  560. writer.writeheader()
  561. for r in results:
  562. writer.writerow(
  563. {k: getattr(r, k)
  564. for k in (by if by is not None else CoverageResult._by)}
  565. | {'coverage_'+k: getattr(r, k)
  566. for k in CoverageResult._fields})
  567. # find previous results?
  568. if args.get('diff'):
  569. diff_results = []
  570. try:
  571. with openio(args['diff']) as f:
  572. reader = csv.DictReader(f, restval='')
  573. for r in reader:
  574. try:
  575. diff_results.append(CoverageResult(
  576. **{k: r[k] for k in CoverageResult._by
  577. if k in r and r[k].strip()},
  578. **{k: r['coverage_'+k]
  579. for k in CoverageResult._fields
  580. if 'coverage_'+k in r
  581. and r['coverage_'+k].strip()}))
  582. except TypeError:
  583. pass
  584. except FileNotFoundError:
  585. pass
  586. # fold
  587. diff_results = fold(CoverageResult, diff_results,
  588. by=by, defines=defines)
  589. # print table
  590. if not args.get('quiet'):
  591. if (args.get('annotate')
  592. or args.get('lines')
  593. or args.get('branches')):
  594. # annotate sources
  595. annotate(CoverageResult, results, **args)
  596. else:
  597. # print table
  598. table(CoverageResult, results,
  599. diff_results if args.get('diff') else None,
  600. by=by if by is not None else ['function'],
  601. fields=fields if fields is not None
  602. else ['lines', 'branches'] if not hits
  603. else ['calls', 'hits'],
  604. sort=sort,
  605. **args)
  606. # catch lack of coverage
  607. if args.get('error_on_lines') and any(
  608. r.coverage_lines.a < r.coverage_lines.b for r in results):
  609. sys.exit(2)
  610. elif args.get('error_on_branches') and any(
  611. r.coverage_branches.a < r.coverage_branches.b for r in results):
  612. sys.exit(3)
  613. if __name__ == "__main__":
  614. import argparse
  615. import sys
  616. parser = argparse.ArgumentParser(
  617. description="Find coverage info after running tests.",
  618. allow_abbrev=False)
  619. parser.add_argument(
  620. 'gcda_paths',
  621. nargs='*',
  622. default=GCDA_PATHS,
  623. help="Description of where to find *.gcda files. May be a directory "
  624. "or a list of paths. Defaults to %r." % GCDA_PATHS)
  625. parser.add_argument(
  626. '-v', '--verbose',
  627. action='store_true',
  628. help="Output commands that run behind the scenes.")
  629. parser.add_argument(
  630. '-q', '--quiet',
  631. action='store_true',
  632. help="Don't show anything, useful with -o.")
  633. parser.add_argument(
  634. '-o', '--output',
  635. help="Specify CSV file to store results.")
  636. parser.add_argument(
  637. '-u', '--use',
  638. help="Don't parse anything, use this CSV file.")
  639. parser.add_argument(
  640. '-d', '--diff',
  641. help="Specify CSV file to diff against.")
  642. parser.add_argument(
  643. '-a', '--all',
  644. action='store_true',
  645. help="Show all, not just the ones that changed.")
  646. parser.add_argument(
  647. '-p', '--percent',
  648. action='store_true',
  649. help="Only show percentage change, not a full diff.")
  650. parser.add_argument(
  651. '-b', '--by',
  652. action='append',
  653. choices=CoverageResult._by,
  654. help="Group by this field.")
  655. parser.add_argument(
  656. '-f', '--field',
  657. dest='fields',
  658. action='append',
  659. choices=CoverageResult._fields,
  660. help="Show this field.")
  661. parser.add_argument(
  662. '-D', '--define',
  663. dest='defines',
  664. action='append',
  665. type=lambda x: (lambda k,v: (k, set(v.split(','))))(*x.split('=', 1)),
  666. help="Only include results where this field is this value.")
  667. class AppendSort(argparse.Action):
  668. def __call__(self, parser, namespace, value, option):
  669. if namespace.sort is None:
  670. namespace.sort = []
  671. namespace.sort.append((value, True if option == '-S' else False))
  672. parser.add_argument(
  673. '-s', '--sort',
  674. action=AppendSort,
  675. help="Sort by this field.")
  676. parser.add_argument(
  677. '-S', '--reverse-sort',
  678. action=AppendSort,
  679. help="Sort by this field, but backwards.")
  680. parser.add_argument(
  681. '-Y', '--summary',
  682. action='store_true',
  683. help="Only show the total.")
  684. parser.add_argument(
  685. '-F', '--source',
  686. dest='sources',
  687. action='append',
  688. help="Only consider definitions in this file. Defaults to anything "
  689. "in the current directory.")
  690. parser.add_argument(
  691. '--everything',
  692. action='store_true',
  693. help="Include builtin and libc specific symbols.")
  694. parser.add_argument(
  695. '--hits',
  696. action='store_true',
  697. help="Show total hits instead of coverage.")
  698. parser.add_argument(
  699. '-A', '--annotate',
  700. action='store_true',
  701. help="Show source files annotated with coverage info.")
  702. parser.add_argument(
  703. '-L', '--lines',
  704. action='store_true',
  705. help="Show uncovered lines.")
  706. parser.add_argument(
  707. '-B', '--branches',
  708. action='store_true',
  709. help="Show uncovered branches.")
  710. parser.add_argument(
  711. '-c', '--context',
  712. type=lambda x: int(x, 0),
  713. default=3,
  714. help="Show n additional lines of context. Defaults to 3.")
  715. parser.add_argument(
  716. '-W', '--width',
  717. type=lambda x: int(x, 0),
  718. default=80,
  719. help="Assume source is styled with this many columns. Defaults to 80.")
  720. parser.add_argument(
  721. '--color',
  722. choices=['never', 'always', 'auto'],
  723. default='auto',
  724. help="When to use terminal colors. Defaults to 'auto'.")
  725. parser.add_argument(
  726. '-e', '--error-on-lines',
  727. action='store_true',
  728. help="Error if any lines are not covered.")
  729. parser.add_argument(
  730. '-E', '--error-on-branches',
  731. action='store_true',
  732. help="Error if any branches are not covered.")
  733. parser.add_argument(
  734. '--gcov-tool',
  735. default=GCOV_TOOL,
  736. type=lambda x: x.split(),
  737. help="Path to the gcov tool to use. Defaults to %r." % GCOV_TOOL)
  738. sys.exit(main(**{k: v
  739. for k, v in vars(parser.parse_intermixed_args()).items()
  740. if v is not None}))