cov.py 26 KB

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