cov.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  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_TOOL = ['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. _types = {
  154. 'calls': Int, 'hits': Int,
  155. 'funcs': Frac, 'lines': Frac, 'branches': Frac}
  156. __slots__ = ()
  157. def __new__(cls, file='', function='', line=0,
  158. calls=0, hits=0, funcs=0, lines=0, branches=0):
  159. return super().__new__(cls, file, function, int(Int(line)),
  160. Int(calls), Int(hits), Frac(funcs), Frac(lines), Frac(branches))
  161. def __add__(self, other):
  162. return CovResult(self.file, self.function, self.line,
  163. max(self.calls, other.calls),
  164. max(self.hits, other.hits),
  165. self.funcs + other.funcs,
  166. self.lines + other.lines,
  167. self.branches + other.branches)
  168. def openio(path, mode='r', buffering=-1):
  169. # allow '-' for stdin/stdout
  170. if path == '-':
  171. if mode == 'r':
  172. return os.fdopen(os.dup(sys.stdin.fileno()), mode, buffering)
  173. else:
  174. return os.fdopen(os.dup(sys.stdout.fileno()), mode, buffering)
  175. else:
  176. return open(path, mode, buffering)
  177. def collect(gcda_paths, *,
  178. gcov_tool=GCOV_TOOL,
  179. sources=None,
  180. everything=False,
  181. **args):
  182. results = []
  183. for path in gcda_paths:
  184. # get coverage info through gcov's json output
  185. # note, gcov-tool may contain extra args
  186. cmd = GCOV_TOOL + ['-b', '-t', '--json-format', path]
  187. if args.get('verbose'):
  188. print(' '.join(shlex.quote(c) for c in cmd))
  189. proc = sp.Popen(cmd,
  190. stdout=sp.PIPE,
  191. stderr=sp.PIPE if not args.get('verbose') else None,
  192. universal_newlines=True,
  193. errors='replace',
  194. close_fds=False)
  195. data = json.load(proc.stdout)
  196. proc.wait()
  197. if proc.returncode != 0:
  198. if not args.get('verbose'):
  199. for line in proc.stderr:
  200. sys.stdout.write(line)
  201. sys.exit(-1)
  202. # collect line/branch coverage
  203. for file in data['files']:
  204. # ignore filtered sources
  205. if sources is not None:
  206. if not any(
  207. os.path.abspath(file['file']) == os.path.abspath(s)
  208. for s in sources):
  209. continue
  210. else:
  211. # default to only cwd
  212. if not everything and not os.path.commonpath([
  213. os.getcwd(),
  214. os.path.abspath(file['file'])]) == os.getcwd():
  215. continue
  216. # simplify path
  217. if os.path.commonpath([
  218. os.getcwd(),
  219. os.path.abspath(file['file'])]) == os.getcwd():
  220. file_name = os.path.relpath(file['file'])
  221. else:
  222. file_name = os.path.abspath(file['file'])
  223. for func in file['functions']:
  224. func_name = func.get('name', '(inlined)')
  225. # discard internal functions (this includes injected test cases)
  226. if not everything:
  227. if func_name.startswith('__'):
  228. continue
  229. # go ahead and add functions, later folding will merge this if
  230. # there are other hits on this line
  231. results.append(CovResult(
  232. file_name, func_name, func['start_line'],
  233. func['execution_count'], 0,
  234. Frac(1 if func['execution_count'] > 0 else 0, 1),
  235. 0,
  236. 0))
  237. for line in file['lines']:
  238. func_name = line.get('function_name', '(inlined)')
  239. # discard internal function (this includes injected test cases)
  240. if not everything:
  241. if func_name.startswith('__'):
  242. continue
  243. # go ahead and add lines, later folding will merge this if
  244. # there are other hits on this line
  245. results.append(CovResult(
  246. file_name, func_name, line['line_number'],
  247. 0, line['count'],
  248. 0,
  249. Frac(1 if line['count'] > 0 else 0, 1),
  250. Frac(
  251. sum(1 if branch['count'] > 0 else 0
  252. for branch in line['branches']),
  253. len(line['branches']))))
  254. return results
  255. def fold(Result, results, *,
  256. by=None,
  257. defines=None,
  258. **_):
  259. if by is None:
  260. by = Result._by
  261. for k in it.chain(by or [], (k for k, _ in defines or [])):
  262. if k not in Result._by and k not in Result._fields:
  263. print("error: could not find field %r?" % k)
  264. sys.exit(-1)
  265. # filter by matching defines
  266. if defines is not None:
  267. results_ = []
  268. for r in results:
  269. if all(getattr(r, k) in vs for k, vs in defines):
  270. results_.append(r)
  271. results = results_
  272. # organize results into conflicts
  273. folding = co.OrderedDict()
  274. for r in results:
  275. name = tuple(getattr(r, k) for k in by)
  276. if name not in folding:
  277. folding[name] = []
  278. folding[name].append(r)
  279. # merge conflicts
  280. folded = []
  281. for name, rs in folding.items():
  282. folded.append(sum(rs[1:], start=rs[0]))
  283. return folded
  284. def table(Result, results, diff_results=None, *,
  285. by=None,
  286. fields=None,
  287. sort=None,
  288. summary=False,
  289. all=False,
  290. percent=False,
  291. **_):
  292. all_, all = all, __builtins__.all
  293. if by is None:
  294. by = Result._by
  295. if fields is None:
  296. fields = Result._fields
  297. types = Result._types
  298. # fold again
  299. results = fold(Result, results, by=by)
  300. if diff_results is not None:
  301. diff_results = fold(Result, diff_results, by=by)
  302. # organize by name
  303. table = {
  304. ','.join(str(getattr(r, k) or '') for k in by): r
  305. for r in results}
  306. diff_table = {
  307. ','.join(str(getattr(r, k) or '') for k in by): r
  308. for r in diff_results or []}
  309. names = list(table.keys() | diff_table.keys())
  310. # sort again, now with diff info, note that python's sort is stable
  311. names.sort()
  312. if diff_results is not None:
  313. names.sort(key=lambda n: tuple(
  314. types[k].ratio(
  315. getattr(table.get(n), k, None),
  316. getattr(diff_table.get(n), k, None))
  317. for k in fields),
  318. reverse=True)
  319. if sort:
  320. for k, reverse in reversed(sort):
  321. names.sort(key=lambda n: (getattr(table[n], k),)
  322. if getattr(table.get(n), k, None) is not None else (),
  323. reverse=reverse ^ (not k or k in Result._fields))
  324. # build up our lines
  325. lines = []
  326. # header
  327. header = []
  328. header.append('%s%s' % (
  329. ','.join(by),
  330. ' (%d added, %d removed)' % (
  331. sum(1 for n in table if n not in diff_table),
  332. sum(1 for n in diff_table if n not in table))
  333. if diff_results is not None and not percent else '')
  334. if not summary else '')
  335. if diff_results is None:
  336. for k in fields:
  337. header.append(k)
  338. elif percent:
  339. for k in fields:
  340. header.append(k)
  341. else:
  342. for k in fields:
  343. header.append('o'+k)
  344. for k in fields:
  345. header.append('n'+k)
  346. for k in fields:
  347. header.append('d'+k)
  348. header.append('')
  349. lines.append(header)
  350. def table_entry(name, r, diff_r=None, ratios=[]):
  351. entry = []
  352. entry.append(name)
  353. if diff_results is None:
  354. for k in fields:
  355. entry.append(getattr(r, k).table()
  356. if getattr(r, k, None) is not None
  357. else types[k].none)
  358. elif percent:
  359. for k in fields:
  360. entry.append(getattr(r, k).diff_table()
  361. if getattr(r, k, None) is not None
  362. else types[k].diff_none)
  363. else:
  364. for k in fields:
  365. entry.append(getattr(diff_r, k).diff_table()
  366. if getattr(diff_r, k, None) is not None
  367. else types[k].diff_none)
  368. for k in fields:
  369. entry.append(getattr(r, k).diff_table()
  370. if getattr(r, k, None) is not None
  371. else types[k].diff_none)
  372. for k in fields:
  373. entry.append(types[k].diff_diff(
  374. getattr(r, k, None),
  375. getattr(diff_r, k, None)))
  376. if diff_results is None:
  377. entry.append('')
  378. elif percent:
  379. entry.append(' (%s)' % ', '.join(
  380. '+∞%' if t == +m.inf
  381. else '-∞%' if t == -m.inf
  382. else '%+.1f%%' % (100*t)
  383. for t in ratios))
  384. else:
  385. entry.append(' (%s)' % ', '.join(
  386. '+∞%' if t == +m.inf
  387. else '-∞%' if t == -m.inf
  388. else '%+.1f%%' % (100*t)
  389. for t in ratios
  390. if t)
  391. if any(ratios) else '')
  392. return entry
  393. # entries
  394. if not summary:
  395. for name in names:
  396. r = table.get(name)
  397. if diff_results is None:
  398. diff_r = None
  399. ratios = None
  400. else:
  401. diff_r = diff_table.get(name)
  402. ratios = [
  403. types[k].ratio(
  404. getattr(r, k, None),
  405. getattr(diff_r, k, None))
  406. for k in fields]
  407. if not all_ and not any(ratios):
  408. continue
  409. lines.append(table_entry(name, r, diff_r, ratios))
  410. # total
  411. r = next(iter(fold(Result, results, by=[])), None)
  412. if diff_results is None:
  413. diff_r = None
  414. ratios = None
  415. else:
  416. diff_r = next(iter(fold(Result, diff_results, by=[])), None)
  417. ratios = [
  418. types[k].ratio(
  419. getattr(r, k, None),
  420. getattr(diff_r, k, None))
  421. for k in fields]
  422. lines.append(table_entry('TOTAL', r, diff_r, ratios))
  423. # find the best widths, note that column 0 contains the names and column -1
  424. # the ratios, so those are handled a bit differently
  425. widths = [
  426. ((max(it.chain([w], (len(l[i]) for l in lines)))+1+4-1)//4)*4-1
  427. for w, i in zip(
  428. it.chain([23], it.repeat(7)),
  429. range(len(lines[0])-1))]
  430. # print our table
  431. for line in lines:
  432. print('%-*s %s%s' % (
  433. widths[0], line[0],
  434. ' '.join('%*s' % (w, x)
  435. for w, x in zip(widths[1:], line[1:-1])),
  436. line[-1]))
  437. def annotate(Result, results, *,
  438. annotate=False,
  439. lines=False,
  440. branches=False,
  441. **args):
  442. # if neither branches/lines specified, color both
  443. if annotate and not lines and not branches:
  444. lines, branches = True, True
  445. for path in co.OrderedDict.fromkeys(r.file for r in results).keys():
  446. # flatten to line info
  447. results = fold(Result, results, by=['file', 'line'])
  448. table = {r.line: r for r in results if r.file == path}
  449. # calculate spans to show
  450. if not annotate:
  451. spans = []
  452. last = None
  453. func = None
  454. for line, r in sorted(table.items()):
  455. if ((lines and int(r.hits) == 0)
  456. or (branches and r.branches.a < r.branches.b)):
  457. if last is not None and line - last.stop <= args['context']:
  458. last = range(
  459. last.start,
  460. line+1+args['context'])
  461. else:
  462. if last is not None:
  463. spans.append((last, func))
  464. last = range(
  465. line-args['context'],
  466. line+1+args['context'])
  467. func = r.function
  468. if last is not None:
  469. spans.append((last, func))
  470. with open(path) as f:
  471. skipped = False
  472. for i, line in enumerate(f):
  473. # skip lines not in spans?
  474. if not annotate and not any(i+1 in s for s, _ in spans):
  475. skipped = True
  476. continue
  477. if skipped:
  478. skipped = False
  479. print('%s@@ %s:%d: %s @@%s' % (
  480. '\x1b[36m' if args['color'] else '',
  481. path,
  482. i+1,
  483. next(iter(f for _, f in spans)),
  484. '\x1b[m' if args['color'] else ''))
  485. # build line
  486. if line.endswith('\n'):
  487. line = line[:-1]
  488. if i+1 in table:
  489. r = table[i+1]
  490. line = '%-*s // %s hits%s' % (
  491. args['width'],
  492. line,
  493. r.hits,
  494. ', %s branches' % (r.branches,)
  495. if int(r.branches.b) else '')
  496. if args['color']:
  497. if lines and int(r.hits) == 0:
  498. line = '\x1b[1;31m%s\x1b[m' % line
  499. elif branches and r.branches.a < r.branches.b:
  500. line = '\x1b[35m%s\x1b[m' % line
  501. print(line)
  502. def main(gcda_paths, *,
  503. by=None,
  504. fields=None,
  505. defines=None,
  506. sort=None,
  507. hits=False,
  508. **args):
  509. # figure out what color should be
  510. if args.get('color') == 'auto':
  511. args['color'] = sys.stdout.isatty()
  512. elif args.get('color') == 'always':
  513. args['color'] = True
  514. else:
  515. args['color'] = False
  516. # find sizes
  517. if not args.get('use', None):
  518. results = collect(gcda_paths, **args)
  519. else:
  520. results = []
  521. with openio(args['use']) as f:
  522. reader = csv.DictReader(f, restval='')
  523. for r in reader:
  524. try:
  525. results.append(CovResult(
  526. **{k: r[k] for k in CovResult._by
  527. if k in r and r[k].strip()},
  528. **{k: r['cov_'+k]
  529. for k in CovResult._fields
  530. if 'cov_'+k in r
  531. and r['cov_'+k].strip()}))
  532. except TypeError:
  533. pass
  534. # fold
  535. results = fold(CovResult, results, by=by, defines=defines)
  536. # sort, note that python's sort is stable
  537. results.sort()
  538. if sort:
  539. for k, reverse in reversed(sort):
  540. results.sort(key=lambda r: (getattr(r, k),)
  541. if getattr(r, k) is not None else (),
  542. reverse=reverse ^ (not k or k in CovResult._fields))
  543. # write results to CSV
  544. if args.get('output'):
  545. with openio(args['output'], 'w') as f:
  546. writer = csv.DictWriter(f,
  547. (by if by is not None else CovResult._by)
  548. + ['cov_'+k for k in CovResult._fields])
  549. writer.writeheader()
  550. for r in results:
  551. writer.writerow(
  552. {k: getattr(r, k)
  553. for k in (by if by is not None else CovResult._by)}
  554. | {'cov_'+k: getattr(r, k)
  555. for k in CovResult._fields})
  556. # find previous results?
  557. if args.get('diff'):
  558. diff_results = []
  559. try:
  560. with openio(args['diff']) as f:
  561. reader = csv.DictReader(f, restval='')
  562. for r in reader:
  563. try:
  564. diff_results.append(CovResult(
  565. **{k: r[k] for k in CovResult._by
  566. if k in r and r[k].strip()},
  567. **{k: r['cov_'+k]
  568. for k in CovResult._fields
  569. if 'cov_'+k in r
  570. and r['cov_'+k].strip()}))
  571. except TypeError:
  572. pass
  573. except FileNotFoundError:
  574. pass
  575. # fold
  576. diff_results = fold(CovResult, diff_results,
  577. by=by, defines=defines)
  578. # print table
  579. if not args.get('quiet'):
  580. if (args.get('annotate')
  581. or args.get('lines')
  582. or args.get('branches')):
  583. # annotate sources
  584. annotate(CovResult, results, **args)
  585. else:
  586. # print table
  587. table(CovResult, results,
  588. diff_results if args.get('diff') else None,
  589. by=by if by is not None else ['function'],
  590. fields=fields if fields is not None
  591. else ['lines', 'branches'] if not hits
  592. else ['calls', 'hits'],
  593. sort=sort,
  594. **args)
  595. # catch lack of coverage
  596. if args.get('error_on_lines') and any(
  597. r.lines.a < r.lines.b for r in results):
  598. sys.exit(2)
  599. elif args.get('error_on_branches') and any(
  600. r.branches.a < r.branches.b for r in results):
  601. sys.exit(3)
  602. if __name__ == "__main__":
  603. import argparse
  604. import sys
  605. parser = argparse.ArgumentParser(
  606. description="Find coverage info after running tests.",
  607. allow_abbrev=False)
  608. parser.add_argument(
  609. 'gcda_paths',
  610. nargs='*',
  611. help="Input *.gcda files.")
  612. parser.add_argument(
  613. '-v', '--verbose',
  614. action='store_true',
  615. help="Output commands that run behind the scenes.")
  616. parser.add_argument(
  617. '-q', '--quiet',
  618. action='store_true',
  619. help="Don't show anything, useful with -o.")
  620. parser.add_argument(
  621. '-o', '--output',
  622. help="Specify CSV file to store results.")
  623. parser.add_argument(
  624. '-u', '--use',
  625. help="Don't parse anything, use this CSV file.")
  626. parser.add_argument(
  627. '-d', '--diff',
  628. help="Specify CSV file to diff against.")
  629. parser.add_argument(
  630. '-a', '--all',
  631. action='store_true',
  632. help="Show all, not just the ones that changed.")
  633. parser.add_argument(
  634. '-p', '--percent',
  635. action='store_true',
  636. help="Only show percentage change, not a full diff.")
  637. parser.add_argument(
  638. '-b', '--by',
  639. action='append',
  640. choices=CovResult._by,
  641. help="Group by this field.")
  642. parser.add_argument(
  643. '-f', '--field',
  644. dest='fields',
  645. action='append',
  646. choices=CovResult._fields,
  647. help="Show this field.")
  648. parser.add_argument(
  649. '-D', '--define',
  650. dest='defines',
  651. action='append',
  652. type=lambda x: (lambda k,v: (k, set(v.split(','))))(*x.split('=', 1)),
  653. help="Only include results where this field is this value.")
  654. class AppendSort(argparse.Action):
  655. def __call__(self, parser, namespace, value, option):
  656. if namespace.sort is None:
  657. namespace.sort = []
  658. namespace.sort.append((value, True if option == '-S' else False))
  659. parser.add_argument(
  660. '-s', '--sort',
  661. action=AppendSort,
  662. help="Sort by this field.")
  663. parser.add_argument(
  664. '-S', '--reverse-sort',
  665. action=AppendSort,
  666. help="Sort by this field, but backwards.")
  667. parser.add_argument(
  668. '-Y', '--summary',
  669. action='store_true',
  670. help="Only show the total.")
  671. parser.add_argument(
  672. '-F', '--source',
  673. dest='sources',
  674. action='append',
  675. help="Only consider definitions in this file. Defaults to anything "
  676. "in the current directory.")
  677. parser.add_argument(
  678. '--everything',
  679. action='store_true',
  680. help="Include builtin and libc specific symbols.")
  681. parser.add_argument(
  682. '--hits',
  683. action='store_true',
  684. help="Show total hits instead of coverage.")
  685. parser.add_argument(
  686. '-A', '--annotate',
  687. action='store_true',
  688. help="Show source files annotated with coverage info.")
  689. parser.add_argument(
  690. '-L', '--lines',
  691. action='store_true',
  692. help="Show uncovered lines.")
  693. parser.add_argument(
  694. '-B', '--branches',
  695. action='store_true',
  696. help="Show uncovered branches.")
  697. parser.add_argument(
  698. '-c', '--context',
  699. type=lambda x: int(x, 0),
  700. default=3,
  701. help="Show n additional lines of context. Defaults to 3.")
  702. parser.add_argument(
  703. '-W', '--width',
  704. type=lambda x: int(x, 0),
  705. default=80,
  706. help="Assume source is styled with this many columns. Defaults to 80.")
  707. parser.add_argument(
  708. '--color',
  709. choices=['never', 'always', 'auto'],
  710. default='auto',
  711. help="When to use terminal colors. Defaults to 'auto'.")
  712. parser.add_argument(
  713. '-e', '--error-on-lines',
  714. action='store_true',
  715. help="Error if any lines are not covered.")
  716. parser.add_argument(
  717. '-E', '--error-on-branches',
  718. action='store_true',
  719. help="Error if any branches are not covered.")
  720. parser.add_argument(
  721. '--gcov-tool',
  722. default=GCOV_TOOL,
  723. type=lambda x: x.split(),
  724. help="Path to the gcov tool to use. Defaults to %r." % GCOV_TOOL)
  725. sys.exit(main(**{k: v
  726. for k, v in vars(parser.parse_intermixed_args()).items()
  727. if v is not None}))