problem.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. """
  2. In this file we define a ProblemVault class where we store all the
  3. exceptions and all the problems we find with the code.
  4. The ProblemVault is capable of registering problems and also figuring out if a
  5. problem is worse than a registered exception so that it only warns when things
  6. get worse.
  7. """
  8. from __future__ import print_function
  9. import os.path
  10. import re
  11. import sys
  12. STATUS_ERR = 2
  13. STATUS_WARN = 1
  14. STATUS_OK = 0
  15. class ProblemVault(object):
  16. """
  17. Singleton where we store the various new problems we
  18. found in the code, and also the old problems we read from the exception
  19. file.
  20. """
  21. def __init__(self, exception_fname=None):
  22. # Exception dictionary: { problem.key() : Problem object }
  23. self.exceptions = {}
  24. # Exception dictionary: maps key to the problem it was used to
  25. # suppress.
  26. self.used_exception_for = {}
  27. if exception_fname == None:
  28. return
  29. try:
  30. with open(exception_fname, 'r') as exception_f:
  31. self.register_exceptions(exception_f)
  32. except IOError:
  33. print("No exception file provided", file=sys.stderr)
  34. def register_exceptions(self, exception_file):
  35. # Register exceptions
  36. for lineno, line in enumerate(exception_file, 1):
  37. try:
  38. problem = get_old_problem_from_exception_str(line)
  39. except ValueError as v:
  40. print("Exception file line {} not recognized: {}"
  41. .format(lineno,v),
  42. file=sys.stderr)
  43. continue
  44. if problem is None:
  45. continue
  46. # Fail if we see dup exceptions. There is really no reason to have dup exceptions.
  47. if problem.key() in self.exceptions:
  48. print("Duplicate exceptions lines found in exception file:\n\t{}\n\t{}\nAborting...".format(problem, self.exceptions[problem.key()]),
  49. file=sys.stderr)
  50. sys.exit(1)
  51. self.exceptions[problem.key()] = problem
  52. #print "Registering exception: %s" % problem
  53. def register_problem(self, problem):
  54. """
  55. Register this problem to the problem value. Return true if it was a new
  56. problem or it worsens an already existing problem. A true
  57. value may be STATUS_ERR to indicate a hard violation, or STATUS_WARN
  58. to indicate a warning.
  59. """
  60. # This is a new problem, print it
  61. if problem.key() not in self.exceptions:
  62. return STATUS_ERR
  63. # If it's an old problem, we don't warn if the situation got better
  64. # (e.g. we went from 4k LoC to 3k LoC), but we do warn if the
  65. # situation worsened (e.g. we went from 60 includes to 80).
  66. status = problem.is_worse_than(self.exceptions[problem.key()])
  67. # Remember that we used this exception, so that we can later
  68. # determine whether the exception was overbroad.
  69. self.used_exception_for[problem.key()] = problem
  70. return status
  71. def list_overbroad_exceptions(self):
  72. """Return an iterator of tuples containing (ex,prob) where ex is an
  73. exceptions in this vault that are stricter than it needs to be, and
  74. prob is the worst problem (if any) that it covered.
  75. """
  76. for k in self.exceptions:
  77. e = self.exceptions[k]
  78. p = self.used_exception_for.get(k)
  79. if p is None or e.is_worse_than(p):
  80. yield (e, p)
  81. def set_tolerances(self, fns):
  82. """Adjust the tolerances for the exceptions in this vault. Takes
  83. a map of problem type to a function that adjusts the permitted
  84. function to its new maximum value."""
  85. for k in self.exceptions:
  86. ex = self.exceptions[k]
  87. fn = fns.get(ex.problem_type)
  88. if fn is not None:
  89. ex.metric_value = fn(ex.metric_value)
  90. class ProblemFilter(object):
  91. def __init__(self):
  92. self.thresholds = dict()
  93. def addThreshold(self, item):
  94. self.thresholds[(item.get_type(),item.get_file_type())] = item
  95. def matches(self, item):
  96. key = (item.get_type(), item.get_file_type())
  97. filt = self.thresholds.get(key, None)
  98. if filt is None:
  99. return False
  100. return item.is_worse_than(filt)
  101. def filter(self, sequence):
  102. for item in iter(sequence):
  103. if self.matches(item):
  104. yield item
  105. class Item(object):
  106. """
  107. A generic measurement about some aspect of our source code. See
  108. the subclasses below for the specific problems we are trying to tackle.
  109. """
  110. def __init__(self, problem_type, problem_location, metric_value):
  111. self.problem_location = problem_location
  112. self.metric_value = int(metric_value)
  113. self.warning_threshold = self.metric_value
  114. self.problem_type = problem_type
  115. def is_worse_than(self, other_problem):
  116. """Return STATUS_ERR if this is a worse problem than other_problem.
  117. Return STATUS_WARN if it is a little worse, but falls within the
  118. warning threshold. Return STATUS_OK if this problem is not
  119. at all worse than other_problem.
  120. """
  121. if self.metric_value > other_problem.metric_value:
  122. return STATUS_ERR
  123. elif self.metric_value > other_problem.warning_threshold:
  124. return STATUS_WARN
  125. else:
  126. return STATUS_OK
  127. def key(self):
  128. """Generate a unique key that describes this problem that can be used as a dictionary key"""
  129. # Item location is a filesystem path, so we need to normalize this
  130. # across platforms otherwise same paths are not gonna match.
  131. canonical_location = os.path.normcase(self.problem_location)
  132. return "%s:%s" % (canonical_location, self.problem_type)
  133. def __str__(self):
  134. return "problem %s %s %s" % (self.problem_type, self.problem_location, self.metric_value)
  135. def get_type(self):
  136. return self.problem_type
  137. def get_file_type(self):
  138. if self.problem_location.endswith(".h"):
  139. return "*.h"
  140. else:
  141. return "*.c"
  142. class FileSizeItem(Item):
  143. """
  144. Denotes a problem with the size of a .c file.
  145. The 'problem_location' is the filesystem path of the .c file, and the
  146. 'metric_value' is the number of lines in the .c file.
  147. """
  148. def __init__(self, problem_location, metric_value):
  149. super(FileSizeItem, self).__init__("file-size", problem_location, metric_value)
  150. class IncludeCountItem(Item):
  151. """
  152. Denotes a problem with the number of #includes in a .c file.
  153. The 'problem_location' is the filesystem path of the .c file, and the
  154. 'metric_value' is the number of #includes in the .c file.
  155. """
  156. def __init__(self, problem_location, metric_value):
  157. super(IncludeCountItem, self).__init__("include-count", problem_location, metric_value)
  158. class FunctionSizeItem(Item):
  159. """
  160. Denotes a problem with a size of a function in a .c file.
  161. The 'problem_location' is "<path>:<function>()" where <path> is the
  162. filesystem path of the .c file and <function> is the name of the offending
  163. function.
  164. The 'metric_value' is the size of the offending function in lines.
  165. """
  166. def __init__(self, problem_location, metric_value):
  167. super(FunctionSizeItem, self).__init__("function-size", problem_location, metric_value)
  168. class DependencyViolationItem(Item):
  169. """
  170. Denotes a dependency violation in a .c or .h file. A dependency violation
  171. occurs when a file includes a file from some module that is not listed
  172. in its .may_include file.
  173. The 'problem_location' is the file that contains the problem.
  174. The 'metric_value' is the number of forbidden includes.
  175. """
  176. def __init__(self, problem_location, metric_value):
  177. super(DependencyViolationItem, self).__init__("dependency-violation",
  178. problem_location,
  179. metric_value)
  180. comment_re = re.compile(r'#.*$')
  181. def get_old_problem_from_exception_str(exception_str):
  182. orig_str = exception_str
  183. exception_str = comment_re.sub("", exception_str)
  184. fields = exception_str.split()
  185. if len(fields) == 0:
  186. # empty line or comment
  187. return None
  188. elif len(fields) == 4:
  189. # valid line
  190. _, problem_type, problem_location, metric_value = fields
  191. else:
  192. raise ValueError("Misformatted line {!r}".format(orig_str))
  193. if problem_type == "file-size":
  194. return FileSizeItem(problem_location, metric_value)
  195. elif problem_type == "include-count":
  196. return IncludeCountItem(problem_location, metric_value)
  197. elif problem_type == "function-size":
  198. return FunctionSizeItem(problem_location, metric_value)
  199. elif problem_type == "dependency-violation":
  200. return DependencyViolationItem(problem_location, metric_value)
  201. else:
  202. raise ValueError("Unknown exception type {!r}".format(orig_str))