problem.py 7.6 KB

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