cov.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  1. #!/usr/bin/env python3
  2. #
  3. # Script to find coverage info after running tests.
  4. #
  5. # Example:
  6. # ./scripts/cov.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 itertools as it
  17. import json
  18. import math as m
  19. import os
  20. import re
  21. import shlex
  22. import subprocess as sp
  23. # TODO use explode_asserts to avoid counting assert branches?
  24. # TODO use dwarf=info to find functions for inline functions?
  25. GCOV_PATH = ['gcov']
  26. # integer fields
  27. class Int(co.namedtuple('Int', 'x')):
  28. __slots__ = ()
  29. def __new__(cls, x=0):
  30. if isinstance(x, Int):
  31. return x
  32. if isinstance(x, str):
  33. try:
  34. x = int(x, 0)
  35. except ValueError:
  36. # also accept +-∞ and +-inf
  37. if re.match('^\s*\+?\s*(?:∞|inf)\s*$', x):
  38. x = m.inf
  39. elif re.match('^\s*-\s*(?:∞|inf)\s*$', x):
  40. x = -m.inf
  41. else:
  42. raise
  43. assert isinstance(x, int) or m.isinf(x), x
  44. return super().__new__(cls, x)
  45. def __str__(self):
  46. if self.x == m.inf:
  47. return '∞'
  48. elif self.x == -m.inf:
  49. return '-∞'
  50. else:
  51. return str(self.x)
  52. def __int__(self):
  53. assert not m.isinf(self.x)
  54. return self.x
  55. def __float__(self):
  56. return float(self.x)
  57. none = '%7s' % '-'
  58. def table(self):
  59. return '%7s' % (self,)
  60. diff_none = '%7s' % '-'
  61. diff_table = table
  62. def diff_diff(self, other):
  63. new = self.x if self else 0
  64. old = other.x if other else 0
  65. diff = new - old
  66. if diff == +m.inf:
  67. return '%7s' % '+∞'
  68. elif diff == -m.inf:
  69. return '%7s' % '-∞'
  70. else:
  71. return '%+7d' % diff
  72. def ratio(self, other):
  73. new = self.x if self else 0
  74. old = other.x if other else 0
  75. if m.isinf(new) and m.isinf(old):
  76. return 0.0
  77. elif m.isinf(new):
  78. return +m.inf
  79. elif m.isinf(old):
  80. return -m.inf
  81. elif not old and not new:
  82. return 0.0
  83. elif not old:
  84. return 1.0
  85. else:
  86. return (new-old) / old
  87. def __add__(self, other):
  88. return self.__class__(self.x + other.x)
  89. def __sub__(self, other):
  90. return self.__class__(self.x - other.x)
  91. def __mul__(self, other):
  92. return self.__class__(self.x * other.x)
  93. # fractional fields, a/b
  94. class Frac(co.namedtuple('Frac', 'a,b')):
  95. __slots__ = ()
  96. def __new__(cls, a=0, b=None):
  97. if isinstance(a, Frac) and b is None:
  98. return a
  99. if isinstance(a, str) and b is None:
  100. a, b = a.split('/', 1)
  101. if b is None:
  102. b = a
  103. return super().__new__(cls, Int(a), Int(b))
  104. def __str__(self):
  105. return '%s/%s' % (self.a, self.b)
  106. def __float__(self):
  107. return float(self.a)
  108. none = '%11s %7s' % ('-', '-')
  109. def table(self):
  110. t = self.a.x/self.b.x if self.b.x else 1.0
  111. return '%11s %7s' % (
  112. self,
  113. '∞%' if t == +m.inf
  114. else '-∞%' if t == -m.inf
  115. else '%.1f%%' % (100*t))
  116. diff_none = '%11s' % '-'
  117. def diff_table(self):
  118. return '%11s' % (self,)
  119. def diff_diff(self, other):
  120. new_a, new_b = self if self else (Int(0), Int(0))
  121. old_a, old_b = other if other else (Int(0), Int(0))
  122. return '%11s' % ('%s/%s' % (
  123. new_a.diff_diff(old_a).strip(),
  124. new_b.diff_diff(old_b).strip()))
  125. def ratio(self, other):
  126. new_a, new_b = self if self else (Int(0), Int(0))
  127. old_a, old_b = other if other else (Int(0), Int(0))
  128. new = new_a.x/new_b.x if new_b.x else 1.0
  129. old = old_a.x/old_b.x if old_b.x else 1.0
  130. return new - old
  131. def __add__(self, other):
  132. return self.__class__(self.a + other.a, self.b + other.b)
  133. def __sub__(self, other):
  134. return self.__class__(self.a - other.a, self.b - other.b)
  135. def __mul__(self, other):
  136. return self.__class__(self.a * other.a, self.b + other.b)
  137. def __lt__(self, other):
  138. self_t = self.a.x/self.b.x if self.b.x else 1.0
  139. other_t = other.a.x/other.b.x if other.b.x else 1.0
  140. return (self_t, self.a.x) < (other_t, other.a.x)
  141. def __gt__(self, other):
  142. return self.__class__.__lt__(other, self)
  143. def __le__(self, other):
  144. return not self.__gt__(other)
  145. def __ge__(self, other):
  146. return not self.__lt__(other)
  147. # coverage results
  148. class CovResult(co.namedtuple('CovResult', [
  149. 'file', 'function', 'line',
  150. 'calls', 'hits', 'funcs', 'lines', 'branches'])):
  151. _by = ['file', 'function', 'line']
  152. _fields = ['calls', 'hits', 'funcs', 'lines', 'branches']
  153. _sort = ['funcs', 'lines', 'branches', 'hits', 'calls']
  154. _types = {
  155. 'calls': Int, 'hits': Int,
  156. 'funcs': Frac, 'lines': Frac, 'branches': Frac}
  157. __slots__ = ()
  158. def __new__(cls, file='', function='', line=0,
  159. calls=0, hits=0, funcs=0, lines=0, branches=0):
  160. return super().__new__(cls, file, function, int(Int(line)),
  161. Int(calls), Int(hits), Frac(funcs), Frac(lines), Frac(branches))
  162. def __add__(self, other):
  163. return CovResult(self.file, self.function, self.line,
  164. max(self.calls, other.calls),
  165. max(self.hits, other.hits),
  166. self.funcs + other.funcs,
  167. self.lines + other.lines,
  168. self.branches + other.branches)
  169. def openio(path, mode='r', buffering=-1):
  170. # allow '-' for stdin/stdout
  171. if path == '-':
  172. if mode == 'r':
  173. return os.fdopen(os.dup(sys.stdin.fileno()), mode, buffering)
  174. else:
  175. return os.fdopen(os.dup(sys.stdout.fileno()), mode, buffering)
  176. else:
  177. return open(path, mode, buffering)
  178. def collect(gcda_paths, *,
  179. gcov_path=GCOV_PATH,
  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-path may contain extra args
  187. cmd = GCOV_PATH + ['-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(CovResult(
  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(CovResult(
  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(
  323. key=lambda n: tuple(
  324. (getattr(table[n], k),)
  325. if getattr(table.get(n), k, None) is not None else ()
  326. for k in ([k] if k else [
  327. k for k in Result._sort if k in fields])),
  328. reverse=reverse ^ (not k or k in Result._fields))
  329. # build up our lines
  330. lines = []
  331. # header
  332. header = []
  333. header.append('%s%s' % (
  334. ','.join(by),
  335. ' (%d added, %d removed)' % (
  336. sum(1 for n in table if n not in diff_table),
  337. sum(1 for n in diff_table if n not in table))
  338. if diff_results is not None and not percent else '')
  339. if not summary else '')
  340. if diff_results is None:
  341. for k in fields:
  342. header.append(k)
  343. elif percent:
  344. for k in fields:
  345. header.append(k)
  346. else:
  347. for k in fields:
  348. header.append('o'+k)
  349. for k in fields:
  350. header.append('n'+k)
  351. for k in fields:
  352. header.append('d'+k)
  353. header.append('')
  354. lines.append(header)
  355. def table_entry(name, r, diff_r=None, ratios=[]):
  356. entry = []
  357. entry.append(name)
  358. if diff_results is None:
  359. for k in fields:
  360. entry.append(getattr(r, k).table()
  361. if getattr(r, k, None) is not None
  362. else types[k].none)
  363. elif percent:
  364. for k in fields:
  365. entry.append(getattr(r, k).diff_table()
  366. if getattr(r, k, None) is not None
  367. else types[k].diff_none)
  368. else:
  369. for k in fields:
  370. entry.append(getattr(diff_r, k).diff_table()
  371. if getattr(diff_r, k, None) is not None
  372. else types[k].diff_none)
  373. for k in fields:
  374. entry.append(getattr(r, k).diff_table()
  375. if getattr(r, k, None) is not None
  376. else types[k].diff_none)
  377. for k in fields:
  378. entry.append(types[k].diff_diff(
  379. getattr(r, k, None),
  380. getattr(diff_r, k, None)))
  381. if diff_results is None:
  382. entry.append('')
  383. elif percent:
  384. entry.append(' (%s)' % ', '.join(
  385. '+∞%' if t == +m.inf
  386. else '-∞%' if t == -m.inf
  387. else '%+.1f%%' % (100*t)
  388. for t in ratios))
  389. else:
  390. entry.append(' (%s)' % ', '.join(
  391. '+∞%' if t == +m.inf
  392. else '-∞%' if t == -m.inf
  393. else '%+.1f%%' % (100*t)
  394. for t in ratios
  395. if t)
  396. if any(ratios) else '')
  397. return entry
  398. # entries
  399. if not summary:
  400. for name in names:
  401. r = table.get(name)
  402. if diff_results is None:
  403. diff_r = None
  404. ratios = None
  405. else:
  406. diff_r = diff_table.get(name)
  407. ratios = [
  408. types[k].ratio(
  409. getattr(r, k, None),
  410. getattr(diff_r, k, None))
  411. for k in fields]
  412. if not all_ and not any(ratios):
  413. continue
  414. lines.append(table_entry(name, r, diff_r, ratios))
  415. # total
  416. r = next(iter(fold(Result, results, by=[])), None)
  417. if diff_results is None:
  418. diff_r = None
  419. ratios = None
  420. else:
  421. diff_r = next(iter(fold(Result, diff_results, by=[])), None)
  422. ratios = [
  423. types[k].ratio(
  424. getattr(r, k, None),
  425. getattr(diff_r, k, None))
  426. for k in fields]
  427. lines.append(table_entry('TOTAL', r, diff_r, ratios))
  428. # find the best widths, note that column 0 contains the names and column -1
  429. # the ratios, so those are handled a bit differently
  430. widths = [
  431. ((max(it.chain([w], (len(l[i]) for l in lines)))+1+4-1)//4)*4-1
  432. for w, i in zip(
  433. it.chain([23], it.repeat(7)),
  434. range(len(lines[0])-1))]
  435. # print our table
  436. for line in lines:
  437. print('%-*s %s%s' % (
  438. widths[0], line[0],
  439. ' '.join('%*s' % (w, x)
  440. for w, x in zip(widths[1:], line[1:-1])),
  441. line[-1]))
  442. def annotate(Result, results, *,
  443. annotate=False,
  444. lines=False,
  445. branches=False,
  446. **args):
  447. # if neither branches/lines specified, color both
  448. if annotate and not lines and not branches:
  449. lines, branches = True, True
  450. for path in co.OrderedDict.fromkeys(r.file for r in results).keys():
  451. # flatten to line info
  452. results = fold(Result, results, by=['file', 'line'])
  453. table = {r.line: r for r in results if r.file == path}
  454. # calculate spans to show
  455. if not annotate:
  456. spans = []
  457. last = None
  458. func = None
  459. for line, r in sorted(table.items()):
  460. if ((lines and int(r.hits) == 0)
  461. or (branches and r.branches.a < r.branches.b)):
  462. if last is not None and line - last.stop <= args['context']:
  463. last = range(
  464. last.start,
  465. line+1+args['context'])
  466. else:
  467. if last is not None:
  468. spans.append((last, func))
  469. last = range(
  470. line-args['context'],
  471. line+1+args['context'])
  472. func = r.function
  473. if last is not None:
  474. spans.append((last, func))
  475. with open(path) as f:
  476. skipped = False
  477. for i, line in enumerate(f):
  478. # skip lines not in spans?
  479. if not annotate and not any(i+1 in s for s, _ in spans):
  480. skipped = True
  481. continue
  482. if skipped:
  483. skipped = False
  484. print('%s@@ %s:%d: %s @@%s' % (
  485. '\x1b[36m' if args['color'] else '',
  486. path,
  487. i+1,
  488. next(iter(f for _, f in spans)),
  489. '\x1b[m' if args['color'] else ''))
  490. # build line
  491. if line.endswith('\n'):
  492. line = line[:-1]
  493. if i+1 in table:
  494. r = table[i+1]
  495. line = '%-*s // %s hits%s' % (
  496. args['width'],
  497. line,
  498. r.hits,
  499. ', %s branches' % (r.branches,)
  500. if int(r.branches.b) else '')
  501. if args['color']:
  502. if lines and int(r.hits) == 0:
  503. line = '\x1b[1;31m%s\x1b[m' % line
  504. elif branches and r.branches.a < r.branches.b:
  505. line = '\x1b[35m%s\x1b[m' % line
  506. print(line)
  507. def main(gcda_paths, *,
  508. by=None,
  509. fields=None,
  510. defines=None,
  511. sort=None,
  512. hits=False,
  513. **args):
  514. # figure out what color should be
  515. if args.get('color') == 'auto':
  516. args['color'] = sys.stdout.isatty()
  517. elif args.get('color') == 'always':
  518. args['color'] = True
  519. else:
  520. args['color'] = False
  521. # find sizes
  522. if not args.get('use', None):
  523. results = collect(gcda_paths, **args)
  524. else:
  525. results = []
  526. with openio(args['use']) as f:
  527. reader = csv.DictReader(f, restval='')
  528. for r in reader:
  529. if not any('cov_'+k in r and r['cov_'+k].strip()
  530. for k in CovResult._fields):
  531. continue
  532. try:
  533. results.append(CovResult(
  534. **{k: r[k] for k in CovResult._by
  535. if k in r and r[k].strip()},
  536. **{k: r['cov_'+k]
  537. for k in CovResult._fields
  538. if 'cov_'+k in r
  539. and r['cov_'+k].strip()}))
  540. except TypeError:
  541. pass
  542. # fold
  543. results = fold(CovResult, results, by=by, defines=defines)
  544. # sort, note that python's sort is stable
  545. results.sort()
  546. if sort:
  547. for k, reverse in reversed(sort):
  548. results.sort(
  549. key=lambda r: tuple(
  550. (getattr(r, k),) if getattr(r, k) is not None else ()
  551. for k in ([k] if k else CovResult._sort)),
  552. reverse=reverse ^ (not k or k in CovResult._fields))
  553. # write results to CSV
  554. if args.get('output'):
  555. with openio(args['output'], 'w') as f:
  556. writer = csv.DictWriter(f,
  557. (by if by is not None else CovResult._by)
  558. + ['cov_'+k for k in (
  559. fields if fields is not None else CovResult._fields)])
  560. writer.writeheader()
  561. for r in results:
  562. writer.writerow(
  563. {k: getattr(r, k) for k in (
  564. by if by is not None else CovResult._by)}
  565. | {'cov_'+k: getattr(r, k) for k in (
  566. fields if fields is not None else CovResult._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. if not any('cov_'+k in r and r['cov_'+k].strip()
  575. for k in CovResult._fields):
  576. continue
  577. try:
  578. diff_results.append(CovResult(
  579. **{k: r[k] for k in CovResult._by
  580. if k in r and r[k].strip()},
  581. **{k: r['cov_'+k]
  582. for k in CovResult._fields
  583. if 'cov_'+k in r
  584. and r['cov_'+k].strip()}))
  585. except TypeError:
  586. pass
  587. except FileNotFoundError:
  588. pass
  589. # fold
  590. diff_results = fold(CovResult, diff_results,
  591. by=by, defines=defines)
  592. # print table
  593. if not args.get('quiet'):
  594. if (args.get('annotate')
  595. or args.get('lines')
  596. or args.get('branches')):
  597. # annotate sources
  598. annotate(CovResult, results, **args)
  599. else:
  600. # print table
  601. table(CovResult, results,
  602. diff_results if args.get('diff') else None,
  603. by=by if by is not None else ['function'],
  604. fields=fields if fields is not None
  605. else ['lines', 'branches'] if not hits
  606. else ['calls', 'hits'],
  607. sort=sort,
  608. **args)
  609. # catch lack of coverage
  610. if args.get('error_on_lines') and any(
  611. r.lines.a < r.lines.b for r in results):
  612. sys.exit(2)
  613. elif args.get('error_on_branches') and any(
  614. r.branches.a < r.branches.b for r in results):
  615. sys.exit(3)
  616. if __name__ == "__main__":
  617. import argparse
  618. import sys
  619. parser = argparse.ArgumentParser(
  620. description="Find coverage info after running tests.",
  621. allow_abbrev=False)
  622. parser.add_argument(
  623. 'gcda_paths',
  624. nargs='*',
  625. help="Input *.gcda files.")
  626. parser.add_argument(
  627. '-v', '--verbose',
  628. action='store_true',
  629. help="Output commands that run behind the scenes.")
  630. parser.add_argument(
  631. '-q', '--quiet',
  632. action='store_true',
  633. help="Don't show anything, useful with -o.")
  634. parser.add_argument(
  635. '-o', '--output',
  636. help="Specify CSV file to store results.")
  637. parser.add_argument(
  638. '-u', '--use',
  639. help="Don't parse anything, use this CSV file.")
  640. parser.add_argument(
  641. '-d', '--diff',
  642. help="Specify CSV file to diff against.")
  643. parser.add_argument(
  644. '-a', '--all',
  645. action='store_true',
  646. help="Show all, not just the ones that changed.")
  647. parser.add_argument(
  648. '-p', '--percent',
  649. action='store_true',
  650. help="Only show percentage change, not a full diff.")
  651. parser.add_argument(
  652. '-b', '--by',
  653. action='append',
  654. choices=CovResult._by,
  655. help="Group by this field.")
  656. parser.add_argument(
  657. '-f', '--field',
  658. dest='fields',
  659. action='append',
  660. choices=CovResult._fields,
  661. help="Show this field.")
  662. parser.add_argument(
  663. '-D', '--define',
  664. dest='defines',
  665. action='append',
  666. type=lambda x: (lambda k,v: (k, set(v.split(','))))(*x.split('=', 1)),
  667. help="Only include results where this field is this value.")
  668. class AppendSort(argparse.Action):
  669. def __call__(self, parser, namespace, value, option):
  670. if namespace.sort is None:
  671. namespace.sort = []
  672. namespace.sort.append((value, True if option == '-S' else False))
  673. parser.add_argument(
  674. '-s', '--sort',
  675. nargs='?',
  676. action=AppendSort,
  677. help="Sort by this field.")
  678. parser.add_argument(
  679. '-S', '--reverse-sort',
  680. nargs='?',
  681. action=AppendSort,
  682. help="Sort by this field, but backwards.")
  683. parser.add_argument(
  684. '-Y', '--summary',
  685. action='store_true',
  686. help="Only show the total.")
  687. parser.add_argument(
  688. '-F', '--source',
  689. dest='sources',
  690. action='append',
  691. help="Only consider definitions in this file. Defaults to anything "
  692. "in the current directory.")
  693. parser.add_argument(
  694. '--everything',
  695. action='store_true',
  696. help="Include builtin and libc specific symbols.")
  697. parser.add_argument(
  698. '--hits',
  699. action='store_true',
  700. help="Show total hits instead of coverage.")
  701. parser.add_argument(
  702. '-A', '--annotate',
  703. action='store_true',
  704. help="Show source files annotated with coverage info.")
  705. parser.add_argument(
  706. '-L', '--lines',
  707. action='store_true',
  708. help="Show uncovered lines.")
  709. parser.add_argument(
  710. '-B', '--branches',
  711. action='store_true',
  712. help="Show uncovered branches.")
  713. parser.add_argument(
  714. '-c', '--context',
  715. type=lambda x: int(x, 0),
  716. default=3,
  717. help="Show n additional lines of context. Defaults to 3.")
  718. parser.add_argument(
  719. '-W', '--width',
  720. type=lambda x: int(x, 0),
  721. default=80,
  722. help="Assume source is styled with this many columns. Defaults to 80.")
  723. parser.add_argument(
  724. '--color',
  725. choices=['never', 'always', 'auto'],
  726. default='auto',
  727. help="When to use terminal colors. Defaults to 'auto'.")
  728. parser.add_argument(
  729. '-e', '--error-on-lines',
  730. action='store_true',
  731. help="Error if any lines are not covered.")
  732. parser.add_argument(
  733. '-E', '--error-on-branches',
  734. action='store_true',
  735. help="Error if any branches are not covered.")
  736. parser.add_argument(
  737. '--gcov-path',
  738. default=GCOV_PATH,
  739. type=lambda x: x.split(),
  740. help="Path to the gcov executable, may include paths. "
  741. "Defaults to %r." % GCOV_PATH)
  742. sys.exit(main(**{k: v
  743. for k, v in vars(parser.parse_intermixed_args()).items()
  744. if v is not None}))