misc.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. """Miscellaneous stuff for Coverage."""
  2. import errno
  3. import inspect
  4. import os
  5. import sys
  6. from coverage.backward import md5, sorted # pylint: disable=W0622
  7. from coverage.backward import string_class, to_bytes
  8. def nice_pair(pair):
  9. """Make a nice string representation of a pair of numbers.
  10. If the numbers are equal, just return the number, otherwise return the pair
  11. with a dash between them, indicating the range.
  12. """
  13. start, end = pair
  14. if start == end:
  15. return "%d" % start
  16. else:
  17. return "%d-%d" % (start, end)
  18. def format_lines(statements, lines):
  19. """Nicely format a list of line numbers.
  20. Format a list of line numbers for printing by coalescing groups of lines as
  21. long as the lines represent consecutive statements. This will coalesce
  22. even if there are gaps between statements.
  23. For example, if `statements` is [1,2,3,4,5,10,11,12,13,14] and
  24. `lines` is [1,2,5,10,11,13,14] then the result will be "1-2, 5-11, 13-14".
  25. """
  26. pairs = []
  27. i = 0
  28. j = 0
  29. start = None
  30. statements = sorted(statements)
  31. lines = sorted(lines)
  32. while i < len(statements) and j < len(lines):
  33. if statements[i] == lines[j]:
  34. if start == None:
  35. start = lines[j]
  36. end = lines[j]
  37. j += 1
  38. elif start:
  39. pairs.append((start, end))
  40. start = None
  41. i += 1
  42. if start:
  43. pairs.append((start, end))
  44. ret = ', '.join(map(nice_pair, pairs))
  45. return ret
  46. def short_stack():
  47. """Return a string summarizing the call stack."""
  48. stack = inspect.stack()[:0:-1]
  49. return "\n".join(["%30s : %s @%d" % (t[3],t[1],t[2]) for t in stack])
  50. def expensive(fn):
  51. """A decorator to cache the result of an expensive operation.
  52. Only applies to methods with no arguments.
  53. """
  54. attr = "_cache_" + fn.__name__
  55. def _wrapped(self):
  56. """Inner fn that checks the cache."""
  57. if not hasattr(self, attr):
  58. setattr(self, attr, fn(self))
  59. return getattr(self, attr)
  60. return _wrapped
  61. def bool_or_none(b):
  62. """Return bool(b), but preserve None."""
  63. if b is None:
  64. return None
  65. else:
  66. return bool(b)
  67. def join_regex(regexes):
  68. """Combine a list of regexes into one that matches any of them."""
  69. if len(regexes) > 1:
  70. return "|".join(["(%s)" % r for r in regexes])
  71. elif regexes:
  72. return regexes[0]
  73. else:
  74. return ""
  75. def file_be_gone(path):
  76. """Remove a file, and don't get annoyed if it doesn't exist."""
  77. try:
  78. os.remove(path)
  79. except OSError:
  80. _, e, _ = sys.exc_info()
  81. if e.errno != errno.ENOENT:
  82. raise
  83. class Hasher(object):
  84. """Hashes Python data into md5."""
  85. def __init__(self):
  86. self.md5 = md5()
  87. def update(self, v):
  88. """Add `v` to the hash, recursively if needed."""
  89. self.md5.update(to_bytes(str(type(v))))
  90. if isinstance(v, string_class):
  91. self.md5.update(to_bytes(v))
  92. elif v is None:
  93. pass
  94. elif isinstance(v, (int, float)):
  95. self.md5.update(to_bytes(str(v)))
  96. elif isinstance(v, (tuple, list)):
  97. for e in v:
  98. self.update(e)
  99. elif isinstance(v, dict):
  100. keys = v.keys()
  101. for k in sorted(keys):
  102. self.update(k)
  103. self.update(v[k])
  104. else:
  105. for k in dir(v):
  106. if k.startswith('__'):
  107. continue
  108. a = getattr(v, k)
  109. if inspect.isroutine(a):
  110. continue
  111. self.update(k)
  112. self.update(a)
  113. def digest(self):
  114. """Retrieve the digest of the hash."""
  115. return self.md5.digest()
  116. class CoverageException(Exception):
  117. """An exception specific to Coverage."""
  118. pass
  119. class NoSource(CoverageException):
  120. """We couldn't find the source for a module."""
  121. pass
  122. class NoCode(NoSource):
  123. """We couldn't find any code at all."""
  124. pass
  125. class NotPython(CoverageException):
  126. """A source file turned out not to be parsable Python."""
  127. pass
  128. class ExceptionDuringRun(CoverageException):
  129. """An exception happened while running customer code.
  130. Construct it with three arguments, the values from `sys.exc_info`.
  131. """
  132. pass