problem.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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 Problem(object):
  88. """
  89. A generic problem in our source code. See the subclasses below for the
  90. specific problems we are trying to tackle.
  91. """
  92. def __init__(self, problem_type, problem_location, metric_value):
  93. self.problem_location = problem_location
  94. self.metric_value = int(metric_value)
  95. self.warning_threshold = self.metric_value
  96. self.problem_type = problem_type
  97. def is_worse_than(self, other_problem):
  98. """Return True if this is a worse problem than other_problem"""
  99. if self.metric_value > other_problem.metric_value:
  100. return True
  101. elif self.metric_value > other_problem.warning_threshold:
  102. self.warn()
  103. return False
  104. def warn(self):
  105. """Warn about this problem on stderr only."""
  106. print("(warning) {}".format(self), file=sys.stderr)
  107. def key(self):
  108. """Generate a unique key that describes this problem that can be used as a dictionary key"""
  109. # Problem location is a filesystem path, so we need to normalize this
  110. # across platforms otherwise same paths are not gonna match.
  111. canonical_location = os.path.normcase(self.problem_location)
  112. return "%s:%s" % (canonical_location, self.problem_type)
  113. def __str__(self):
  114. return "problem %s %s %s" % (self.problem_type, self.problem_location, self.metric_value)
  115. class FileSizeProblem(Problem):
  116. """
  117. Denotes a problem with the size of a .c file.
  118. The 'problem_location' is the filesystem path of the .c file, and the
  119. 'metric_value' is the number of lines in the .c file.
  120. """
  121. def __init__(self, problem_location, metric_value):
  122. super(FileSizeProblem, self).__init__("file-size", problem_location, metric_value)
  123. class IncludeCountProblem(Problem):
  124. """
  125. Denotes a problem with the number of #includes in a .c file.
  126. The 'problem_location' is the filesystem path of the .c file, and the
  127. 'metric_value' is the number of #includes in the .c file.
  128. """
  129. def __init__(self, problem_location, metric_value):
  130. super(IncludeCountProblem, self).__init__("include-count", problem_location, metric_value)
  131. class FunctionSizeProblem(Problem):
  132. """
  133. Denotes a problem with a size of a function in a .c file.
  134. The 'problem_location' is "<path>:<function>()" where <path> is the
  135. filesystem path of the .c file and <function> is the name of the offending
  136. function.
  137. The 'metric_value' is the size of the offending function in lines.
  138. """
  139. def __init__(self, problem_location, metric_value):
  140. super(FunctionSizeProblem, self).__init__("function-size", problem_location, metric_value)
  141. comment_re = re.compile(r'#.*$')
  142. def get_old_problem_from_exception_str(exception_str):
  143. orig_str = exception_str
  144. exception_str = comment_re.sub("", exception_str)
  145. fields = exception_str.split()
  146. if len(fields) == 0:
  147. # empty line or comment
  148. return None
  149. elif len(fields) == 4:
  150. # valid line
  151. _, problem_type, problem_location, metric_value = fields
  152. else:
  153. raise ValueError("Misformatted line {!r}".format(orig_str))
  154. if problem_type == "file-size":
  155. return FileSizeProblem(problem_location, metric_value)
  156. elif problem_type == "include-count":
  157. return IncludeCountProblem(problem_location, metric_value)
  158. elif problem_type == "function-size":
  159. return FunctionSizeProblem(problem_location, metric_value)
  160. else:
  161. raise ValueError("Unknown exception type {!r}".format(orig_str))