data.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
  2. # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt
  3. """Coverage data for coverage.py."""
  4. import glob
  5. import itertools
  6. import json
  7. import optparse
  8. import os
  9. import os.path
  10. import random
  11. import re
  12. import socket
  13. from coverage import env
  14. from coverage.backward import iitems, string_class
  15. from coverage.debug import _TEST_NAME_FILE
  16. from coverage.files import PathAliases
  17. from coverage.misc import CoverageException, file_be_gone, isolate_module
  18. os = isolate_module(os)
  19. class CoverageData(object):
  20. """Manages collected coverage data, including file storage.
  21. This class is the public supported API to the data coverage.py collects
  22. during program execution. It includes information about what code was
  23. executed. It does not include information from the analysis phase, to
  24. determine what lines could have been executed, or what lines were not
  25. executed.
  26. .. note::
  27. The file format is not documented or guaranteed. It will change in
  28. the future, in possibly complicated ways. Do not read coverage.py
  29. data files directly. Use this API to avoid disruption.
  30. There are a number of kinds of data that can be collected:
  31. * **lines**: the line numbers of source lines that were executed.
  32. These are always available.
  33. * **arcs**: pairs of source and destination line numbers for transitions
  34. between source lines. These are only available if branch coverage was
  35. used.
  36. * **file tracer names**: the module names of the file tracer plugins that
  37. handled each file in the data.
  38. * **run information**: information about the program execution. This is
  39. written during "coverage run", and then accumulated during "coverage
  40. combine".
  41. Lines, arcs, and file tracer names are stored for each source file. File
  42. names in this API are case-sensitive, even on platforms with
  43. case-insensitive file systems.
  44. To read a coverage.py data file, use :meth:`read_file`, or
  45. :meth:`read_fileobj` if you have an already-opened file. You can then
  46. access the line, arc, or file tracer data with :meth:`lines`, :meth:`arcs`,
  47. or :meth:`file_tracer`. Run information is available with
  48. :meth:`run_infos`.
  49. The :meth:`has_arcs` method indicates whether arc data is available. You
  50. can get a list of the files in the data with :meth:`measured_files`.
  51. A summary of the line data is available from :meth:`line_counts`. As with
  52. most Python containers, you can determine if there is any data at all by
  53. using this object as a boolean value.
  54. Most data files will be created by coverage.py itself, but you can use
  55. methods here to create data files if you like. The :meth:`add_lines`,
  56. :meth:`add_arcs`, and :meth:`add_file_tracers` methods add data, in ways
  57. that are convenient for coverage.py. The :meth:`add_run_info` method adds
  58. key-value pairs to the run information.
  59. To add a file without any measured data, use :meth:`touch_file`.
  60. You write to a named file with :meth:`write_file`, or to an already opened
  61. file with :meth:`write_fileobj`.
  62. You can clear the data in memory with :meth:`erase`. Two data collections
  63. can be combined by using :meth:`update` on one :class:`CoverageData`,
  64. passing it the other.
  65. """
  66. # The data file format is JSON, with these keys:
  67. #
  68. # * lines: a dict mapping file names to lists of line numbers
  69. # executed::
  70. #
  71. # { "file1": [17,23,45], "file2": [1,2,3], ... }
  72. #
  73. # * arcs: a dict mapping file names to lists of line number pairs::
  74. #
  75. # { "file1": [[17,23], [17,25], [25,26]], ... }
  76. #
  77. # * file_tracers: a dict mapping file names to plugin names::
  78. #
  79. # { "file1": "django.coverage", ... }
  80. #
  81. # * runs: a list of dicts of information about the coverage.py runs
  82. # contributing to the data::
  83. #
  84. # [ { "brief_sys": "CPython 2.7.10 Darwin" }, ... ]
  85. #
  86. # Only one of `lines` or `arcs` will be present: with branch coverage, data
  87. # is stored as arcs. Without branch coverage, it is stored as lines. The
  88. # line data is easily recovered from the arcs: it is all the first elements
  89. # of the pairs that are greater than zero.
  90. def __init__(self, debug=None):
  91. """Create a CoverageData.
  92. `debug` is a `DebugControl` object for writing debug messages.
  93. """
  94. self._debug = debug
  95. # A map from canonical Python source file name to a dictionary in
  96. # which there's an entry for each line number that has been
  97. # executed:
  98. #
  99. # { 'filename1.py': [12, 47, 1001], ... }
  100. #
  101. self._lines = None
  102. # A map from canonical Python source file name to a dictionary with an
  103. # entry for each pair of line numbers forming an arc:
  104. #
  105. # { 'filename1.py': [(12,14), (47,48), ... ], ... }
  106. #
  107. self._arcs = None
  108. # A map from canonical source file name to a plugin module name:
  109. #
  110. # { 'filename1.py': 'django.coverage', ... }
  111. #
  112. self._file_tracers = {}
  113. # A list of dicts of information about the coverage.py runs.
  114. self._runs = []
  115. def __repr__(self):
  116. return "<{klass} lines={lines} arcs={arcs} tracers={tracers} runs={runs}>".format(
  117. klass=self.__class__.__name__,
  118. lines="None" if self._lines is None else "{{{0}}}".format(len(self._lines)),
  119. arcs="None" if self._arcs is None else "{{{0}}}".format(len(self._arcs)),
  120. tracers="{{{0}}}".format(len(self._file_tracers)),
  121. runs="[{0}]".format(len(self._runs)),
  122. )
  123. ##
  124. ## Reading data
  125. ##
  126. def has_arcs(self):
  127. """Does this data have arcs?
  128. Arc data is only available if branch coverage was used during
  129. collection.
  130. Returns a boolean.
  131. """
  132. return self._has_arcs()
  133. def lines(self, filename):
  134. """Get the list of lines executed for a file.
  135. If the file was not measured, returns None. A file might be measured,
  136. and have no lines executed, in which case an empty list is returned.
  137. If the file was executed, returns a list of integers, the line numbers
  138. executed in the file. The list is in no particular order.
  139. """
  140. if self._arcs is not None:
  141. arcs = self._arcs.get(filename)
  142. if arcs is not None:
  143. all_lines = itertools.chain.from_iterable(arcs)
  144. return list(set(l for l in all_lines if l > 0))
  145. elif self._lines is not None:
  146. return self._lines.get(filename)
  147. return None
  148. def arcs(self, filename):
  149. """Get the list of arcs executed for a file.
  150. If the file was not measured, returns None. A file might be measured,
  151. and have no arcs executed, in which case an empty list is returned.
  152. If the file was executed, returns a list of 2-tuples of integers. Each
  153. pair is a starting line number and an ending line number for a
  154. transition from one line to another. The list is in no particular
  155. order.
  156. Negative numbers have special meaning. If the starting line number is
  157. -N, it represents an entry to the code object that starts at line N.
  158. If the ending ling number is -N, it's an exit from the code object that
  159. starts at line N.
  160. """
  161. if self._arcs is not None:
  162. if filename in self._arcs:
  163. return self._arcs[filename]
  164. return None
  165. def file_tracer(self, filename):
  166. """Get the plugin name of the file tracer for a file.
  167. Returns the name of the plugin that handles this file. If the file was
  168. measured, but didn't use a plugin, then "" is returned. If the file
  169. was not measured, then None is returned.
  170. """
  171. # Because the vast majority of files involve no plugin, we don't store
  172. # them explicitly in self._file_tracers. Check the measured data
  173. # instead to see if it was a known file with no plugin.
  174. if filename in (self._arcs or self._lines or {}):
  175. return self._file_tracers.get(filename, "")
  176. return None
  177. def run_infos(self):
  178. """Return the list of dicts of run information.
  179. For data collected during a single run, this will be a one-element
  180. list. If data has been combined, there will be one element for each
  181. original data file.
  182. """
  183. return self._runs
  184. def measured_files(self):
  185. """A list of all files that had been measured."""
  186. return list(self._arcs or self._lines or {})
  187. def line_counts(self, fullpath=False):
  188. """Return a dict summarizing the line coverage data.
  189. Keys are based on the file names, and values are the number of executed
  190. lines. If `fullpath` is true, then the keys are the full pathnames of
  191. the files, otherwise they are the basenames of the files.
  192. Returns a dict mapping file names to counts of lines.
  193. """
  194. summ = {}
  195. if fullpath:
  196. filename_fn = lambda f: f
  197. else:
  198. filename_fn = os.path.basename
  199. for filename in self.measured_files():
  200. summ[filename_fn(filename)] = len(self.lines(filename))
  201. return summ
  202. def __nonzero__(self):
  203. return bool(self._lines or self._arcs)
  204. __bool__ = __nonzero__
  205. def read_fileobj(self, file_obj):
  206. """Read the coverage data from the given file object.
  207. Should only be used on an empty CoverageData object.
  208. """
  209. data = self._read_raw_data(file_obj)
  210. self._lines = self._arcs = None
  211. if 'lines' in data:
  212. self._lines = data['lines']
  213. if 'arcs' in data:
  214. self._arcs = dict(
  215. (fname, [tuple(pair) for pair in arcs])
  216. for fname, arcs in iitems(data['arcs'])
  217. )
  218. self._file_tracers = data.get('file_tracers', {})
  219. self._runs = data.get('runs', [])
  220. self._validate()
  221. def read_file(self, filename):
  222. """Read the coverage data from `filename` into this object."""
  223. if self._debug and self._debug.should('dataio'):
  224. self._debug.write("Reading data from %r" % (filename,))
  225. try:
  226. with self._open_for_reading(filename) as f:
  227. self.read_fileobj(f)
  228. except Exception as exc:
  229. raise CoverageException(
  230. "Couldn't read data from '%s': %s: %s" % (
  231. filename, exc.__class__.__name__, exc,
  232. )
  233. )
  234. _GO_AWAY = "!coverage.py: This is a private format, don't read it directly!"
  235. @classmethod
  236. def _open_for_reading(cls, filename):
  237. """Open a file appropriately for reading data."""
  238. return open(filename, "r")
  239. @classmethod
  240. def _read_raw_data(cls, file_obj):
  241. """Read the raw data from a file object."""
  242. go_away = file_obj.read(len(cls._GO_AWAY))
  243. if go_away != cls._GO_AWAY:
  244. raise CoverageException("Doesn't seem to be a coverage.py data file")
  245. return json.load(file_obj)
  246. @classmethod
  247. def _read_raw_data_file(cls, filename):
  248. """Read the raw data from a file, for debugging."""
  249. with cls._open_for_reading(filename) as f:
  250. return cls._read_raw_data(f)
  251. ##
  252. ## Writing data
  253. ##
  254. def add_lines(self, line_data):
  255. """Add measured line data.
  256. `line_data` is a dictionary mapping file names to dictionaries::
  257. { filename: { lineno: None, ... }, ...}
  258. """
  259. if self._debug and self._debug.should('dataop'):
  260. self._debug.write("Adding lines: %d files, %d lines total" % (
  261. len(line_data), sum(len(lines) for lines in line_data.values())
  262. ))
  263. if self._has_arcs():
  264. raise CoverageException("Can't add lines to existing arc data")
  265. if self._lines is None:
  266. self._lines = {}
  267. for filename, linenos in iitems(line_data):
  268. if filename in self._lines:
  269. new_linenos = set(self._lines[filename])
  270. new_linenos.update(linenos)
  271. linenos = new_linenos
  272. self._lines[filename] = list(linenos)
  273. self._validate()
  274. def add_arcs(self, arc_data):
  275. """Add measured arc data.
  276. `arc_data` is a dictionary mapping file names to dictionaries::
  277. { filename: { (l1,l2): None, ... }, ...}
  278. """
  279. if self._debug and self._debug.should('dataop'):
  280. self._debug.write("Adding arcs: %d files, %d arcs total" % (
  281. len(arc_data), sum(len(arcs) for arcs in arc_data.values())
  282. ))
  283. if self._has_lines():
  284. raise CoverageException("Can't add arcs to existing line data")
  285. if self._arcs is None:
  286. self._arcs = {}
  287. for filename, arcs in iitems(arc_data):
  288. if filename in self._arcs:
  289. new_arcs = set(self._arcs[filename])
  290. new_arcs.update(arcs)
  291. arcs = new_arcs
  292. self._arcs[filename] = list(arcs)
  293. self._validate()
  294. def add_file_tracers(self, file_tracers):
  295. """Add per-file plugin information.
  296. `file_tracers` is { filename: plugin_name, ... }
  297. """
  298. if self._debug and self._debug.should('dataop'):
  299. self._debug.write("Adding file tracers: %d files" % (len(file_tracers),))
  300. existing_files = self._arcs or self._lines or {}
  301. for filename, plugin_name in iitems(file_tracers):
  302. if filename not in existing_files:
  303. raise CoverageException(
  304. "Can't add file tracer data for unmeasured file '%s'" % (filename,)
  305. )
  306. existing_plugin = self._file_tracers.get(filename)
  307. if existing_plugin is not None and plugin_name != existing_plugin:
  308. raise CoverageException(
  309. "Conflicting file tracer name for '%s': %r vs %r" % (
  310. filename, existing_plugin, plugin_name,
  311. )
  312. )
  313. self._file_tracers[filename] = plugin_name
  314. self._validate()
  315. def add_run_info(self, **kwargs):
  316. """Add information about the run.
  317. Keywords are arbitrary, and are stored in the run dictionary. Values
  318. must be JSON serializable. You may use this function more than once,
  319. but repeated keywords overwrite each other.
  320. """
  321. if self._debug and self._debug.should('dataop'):
  322. self._debug.write("Adding run info: %r" % (kwargs,))
  323. if not self._runs:
  324. self._runs = [{}]
  325. self._runs[0].update(kwargs)
  326. self._validate()
  327. def touch_file(self, filename):
  328. """Ensure that `filename` appears in the data, empty if needed."""
  329. if self._debug and self._debug.should('dataop'):
  330. self._debug.write("Touching %r" % (filename,))
  331. if not self._has_arcs() and not self._has_lines():
  332. raise CoverageException("Can't touch files in an empty CoverageData")
  333. if self._has_arcs():
  334. where = self._arcs
  335. else:
  336. where = self._lines
  337. where.setdefault(filename, [])
  338. self._validate()
  339. def write_fileobj(self, file_obj):
  340. """Write the coverage data to `file_obj`."""
  341. # Create the file data.
  342. file_data = {}
  343. if self._has_arcs():
  344. file_data['arcs'] = self._arcs
  345. if self._has_lines():
  346. file_data['lines'] = self._lines
  347. if self._file_tracers:
  348. file_data['file_tracers'] = self._file_tracers
  349. if self._runs:
  350. file_data['runs'] = self._runs
  351. # Write the data to the file.
  352. file_obj.write(self._GO_AWAY)
  353. json.dump(file_data, file_obj)
  354. def write_file(self, filename):
  355. """Write the coverage data to `filename`."""
  356. if self._debug and self._debug.should('dataio'):
  357. self._debug.write("Writing data to %r" % (filename,))
  358. with open(filename, 'w') as fdata:
  359. self.write_fileobj(fdata)
  360. def erase(self):
  361. """Erase the data in this object."""
  362. self._lines = None
  363. self._arcs = None
  364. self._file_tracers = {}
  365. self._runs = []
  366. self._validate()
  367. def update(self, other_data, aliases=None):
  368. """Update this data with data from another `CoverageData`.
  369. If `aliases` is provided, it's a `PathAliases` object that is used to
  370. re-map paths to match the local machine's.
  371. """
  372. if self._has_lines() and other_data._has_arcs():
  373. raise CoverageException("Can't combine arc data with line data")
  374. if self._has_arcs() and other_data._has_lines():
  375. raise CoverageException("Can't combine line data with arc data")
  376. aliases = aliases or PathAliases()
  377. # _file_tracers: only have a string, so they have to agree.
  378. # Have to do these first, so that our examination of self._arcs and
  379. # self._lines won't be confused by data updated from other_data.
  380. for filename in other_data.measured_files():
  381. other_plugin = other_data.file_tracer(filename)
  382. filename = aliases.map(filename)
  383. this_plugin = self.file_tracer(filename)
  384. if this_plugin is None:
  385. if other_plugin:
  386. self._file_tracers[filename] = other_plugin
  387. elif this_plugin != other_plugin:
  388. raise CoverageException(
  389. "Conflicting file tracer name for '%s': %r vs %r" % (
  390. filename, this_plugin, other_plugin,
  391. )
  392. )
  393. # _runs: add the new runs to these runs.
  394. self._runs.extend(other_data._runs)
  395. # _lines: merge dicts.
  396. if other_data._has_lines():
  397. if self._lines is None:
  398. self._lines = {}
  399. for filename, file_lines in iitems(other_data._lines):
  400. filename = aliases.map(filename)
  401. if filename in self._lines:
  402. lines = set(self._lines[filename])
  403. lines.update(file_lines)
  404. file_lines = list(lines)
  405. self._lines[filename] = file_lines
  406. # _arcs: merge dicts.
  407. if other_data._has_arcs():
  408. if self._arcs is None:
  409. self._arcs = {}
  410. for filename, file_arcs in iitems(other_data._arcs):
  411. filename = aliases.map(filename)
  412. if filename in self._arcs:
  413. arcs = set(self._arcs[filename])
  414. arcs.update(file_arcs)
  415. file_arcs = list(arcs)
  416. self._arcs[filename] = file_arcs
  417. self._validate()
  418. ##
  419. ## Miscellaneous
  420. ##
  421. def _validate(self):
  422. """If we are in paranoid mode, validate that everything is right."""
  423. if env.TESTING:
  424. self._validate_invariants()
  425. def _validate_invariants(self):
  426. """Validate internal invariants."""
  427. # Only one of _lines or _arcs should exist.
  428. assert not(self._has_lines() and self._has_arcs()), (
  429. "Shouldn't have both _lines and _arcs"
  430. )
  431. # _lines should be a dict of lists of ints.
  432. if self._has_lines():
  433. for fname, lines in iitems(self._lines):
  434. assert isinstance(fname, string_class), "Key in _lines shouldn't be %r" % (fname,)
  435. assert all(isinstance(x, int) for x in lines), (
  436. "_lines[%r] shouldn't be %r" % (fname, lines)
  437. )
  438. # _arcs should be a dict of lists of pairs of ints.
  439. if self._has_arcs():
  440. for fname, arcs in iitems(self._arcs):
  441. assert isinstance(fname, string_class), "Key in _arcs shouldn't be %r" % (fname,)
  442. assert all(isinstance(x, int) and isinstance(y, int) for x, y in arcs), (
  443. "_arcs[%r] shouldn't be %r" % (fname, arcs)
  444. )
  445. # _file_tracers should have only non-empty strings as values.
  446. for fname, plugin in iitems(self._file_tracers):
  447. assert isinstance(fname, string_class), (
  448. "Key in _file_tracers shouldn't be %r" % (fname,)
  449. )
  450. assert plugin and isinstance(plugin, string_class), (
  451. "_file_tracers[%r] shoudn't be %r" % (fname, plugin)
  452. )
  453. # _runs should be a list of dicts.
  454. for val in self._runs:
  455. assert isinstance(val, dict)
  456. for key in val:
  457. assert isinstance(key, string_class), "Key in _runs shouldn't be %r" % (key,)
  458. def add_to_hash(self, filename, hasher):
  459. """Contribute `filename`'s data to the `hasher`.
  460. `hasher` is a `coverage.misc.Hasher` instance to be updated with
  461. the file's data. It should only get the results data, not the run
  462. data.
  463. """
  464. if self._has_arcs():
  465. hasher.update(sorted(self.arcs(filename) or []))
  466. else:
  467. hasher.update(sorted(self.lines(filename) or []))
  468. hasher.update(self.file_tracer(filename))
  469. ##
  470. ## Internal
  471. ##
  472. def _has_lines(self):
  473. """Do we have data in self._lines?"""
  474. return self._lines is not None
  475. def _has_arcs(self):
  476. """Do we have data in self._arcs?"""
  477. return self._arcs is not None
  478. class CoverageDataFiles(object):
  479. """Manage the use of coverage data files."""
  480. def __init__(self, basename=None, warn=None):
  481. """Create a CoverageDataFiles to manage data files.
  482. `warn` is the warning function to use.
  483. `basename` is the name of the file to use for storing data.
  484. """
  485. self.warn = warn
  486. # Construct the file name that will be used for data storage.
  487. self.filename = os.path.abspath(basename or ".coverage")
  488. def erase(self, parallel=False):
  489. """Erase the data from the file storage.
  490. If `parallel` is true, then also deletes data files created from the
  491. basename by parallel-mode.
  492. """
  493. file_be_gone(self.filename)
  494. if parallel:
  495. data_dir, local = os.path.split(self.filename)
  496. localdot = local + '.*'
  497. pattern = os.path.join(os.path.abspath(data_dir), localdot)
  498. for filename in glob.glob(pattern):
  499. file_be_gone(filename)
  500. def read(self, data):
  501. """Read the coverage data."""
  502. if os.path.exists(self.filename):
  503. data.read_file(self.filename)
  504. def write(self, data, suffix=None):
  505. """Write the collected coverage data to a file.
  506. `suffix` is a suffix to append to the base file name. This can be used
  507. for multiple or parallel execution, so that many coverage data files
  508. can exist simultaneously. A dot will be used to join the base name and
  509. the suffix.
  510. """
  511. filename = self.filename
  512. if suffix is True:
  513. # If data_suffix was a simple true value, then make a suffix with
  514. # plenty of distinguishing information. We do this here in
  515. # `save()` at the last minute so that the pid will be correct even
  516. # if the process forks.
  517. extra = ""
  518. if _TEST_NAME_FILE: # pragma: debugging
  519. with open(_TEST_NAME_FILE) as f:
  520. test_name = f.read()
  521. extra = "." + test_name
  522. suffix = "%s%s.%s.%06d" % (
  523. socket.gethostname(), extra, os.getpid(),
  524. random.randint(0, 999999)
  525. )
  526. if suffix:
  527. filename += "." + suffix
  528. data.write_file(filename)
  529. def combine_parallel_data(self, data, aliases=None, data_paths=None):
  530. """Combine a number of data files together.
  531. Treat `self.filename` as a file prefix, and combine the data from all
  532. of the data files starting with that prefix plus a dot.
  533. If `aliases` is provided, it's a `PathAliases` object that is used to
  534. re-map paths to match the local machine's.
  535. If `data_paths` is provided, it is a list of directories or files to
  536. combine. Directories are searched for files that start with
  537. `self.filename` plus dot as a prefix, and those files are combined.
  538. If `data_paths` is not provided, then the directory portion of
  539. `self.filename` is used as the directory to search for data files.
  540. Every data file found and combined is then deleted from disk. If a file
  541. cannot be read, a warning will be issued, and the file will not be
  542. deleted.
  543. """
  544. # Because of the os.path.abspath in the constructor, data_dir will
  545. # never be an empty string.
  546. data_dir, local = os.path.split(self.filename)
  547. localdot = local + '.*'
  548. data_paths = data_paths or [data_dir]
  549. files_to_combine = []
  550. for p in data_paths:
  551. if os.path.isfile(p):
  552. files_to_combine.append(os.path.abspath(p))
  553. elif os.path.isdir(p):
  554. pattern = os.path.join(os.path.abspath(p), localdot)
  555. files_to_combine.extend(glob.glob(pattern))
  556. else:
  557. raise CoverageException("Couldn't combine from non-existent path '%s'" % (p,))
  558. for f in files_to_combine:
  559. new_data = CoverageData()
  560. try:
  561. new_data.read_file(f)
  562. except CoverageException as exc:
  563. if self.warn:
  564. # The CoverageException has the file name in it, so just
  565. # use the message as the warning.
  566. self.warn(str(exc))
  567. else:
  568. data.update(new_data, aliases=aliases)
  569. file_be_gone(f)
  570. def canonicalize_json_data(data):
  571. """Canonicalize our JSON data so it can be compared."""
  572. for fname, lines in iitems(data.get('lines', {})):
  573. data['lines'][fname] = sorted(lines)
  574. for fname, arcs in iitems(data.get('arcs', {})):
  575. data['arcs'][fname] = sorted(arcs)
  576. def pretty_data(data):
  577. """Format data as JSON, but as nicely as possible.
  578. Returns a string.
  579. """
  580. # Start with a basic JSON dump.
  581. out = json.dumps(data, indent=4, sort_keys=True)
  582. # But pairs of numbers shouldn't be split across lines...
  583. out = re.sub(r"\[\s+(-?\d+),\s+(-?\d+)\s+]", r"[\1, \2]", out)
  584. # Trailing spaces mess with tests, get rid of them.
  585. out = re.sub(r"(?m)\s+$", "", out)
  586. return out
  587. def debug_main(args):
  588. """Dump the raw data from data files.
  589. Run this as::
  590. $ python -m coverage.data [FILE]
  591. """
  592. parser = optparse.OptionParser()
  593. parser.add_option(
  594. "-c", "--canonical", action="store_true",
  595. help="Sort data into a canonical order",
  596. )
  597. options, args = parser.parse_args(args)
  598. for filename in (args or [".coverage"]):
  599. print("--- {0} ------------------------------".format(filename))
  600. data = CoverageData._read_raw_data_file(filename)
  601. if options.canonical:
  602. canonicalize_json_data(data)
  603. print(pretty_data(data))
  604. if __name__ == '__main__':
  605. import sys
  606. debug_main(sys.argv[1:])