problem.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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. if exception_fname == None:
  22. return
  23. try:
  24. with open(exception_fname, 'r') as exception_f:
  25. self.register_exceptions(exception_f)
  26. except IOError:
  27. print("No exception file provided", file=sys.stderr)
  28. def register_exceptions(self, exception_file):
  29. # Register exceptions
  30. for lineno, line in enumerate(exception_file, 1):
  31. try:
  32. problem = get_old_problem_from_exception_str(line)
  33. except ValueError as v:
  34. print("Exception file line {} not recognized: {}"
  35. .format(lineno,v),
  36. file=sys.stderr)
  37. continue
  38. if problem is None:
  39. continue
  40. # Fail if we see dup exceptions. There is really no reason to have dup exceptions.
  41. if problem.key() in self.exceptions:
  42. print("Duplicate exceptions lines found in exception file:\n\t{}\n\t{}\nAborting...".format(problem, self.exceptions[problem.key()]),
  43. file=sys.stderr)
  44. sys.exit(1)
  45. self.exceptions[problem.key()] = problem
  46. #print "Registering exception: %s" % problem
  47. def register_problem(self, problem):
  48. """
  49. Register this problem to the problem value. Return True if it was a new
  50. problem or it worsens an already existing problem.
  51. """
  52. # This is a new problem, print it
  53. if problem.key() not in self.exceptions:
  54. print(problem)
  55. return True
  56. # If it's an old problem, we don't warn if the situation got better
  57. # (e.g. we went from 4k LoC to 3k LoC), but we do warn if the
  58. # situation worsened (e.g. we went from 60 includes to 80).
  59. if problem.is_worse_than(self.exceptions[problem.key()]):
  60. print(problem)
  61. return True
  62. return False
  63. class Problem(object):
  64. """
  65. A generic problem in our source code. See the subclasses below for the
  66. specific problems we are trying to tackle.
  67. """
  68. def __init__(self, problem_type, problem_location, metric_value):
  69. self.problem_location = problem_location
  70. self.metric_value = int(metric_value)
  71. self.problem_type = problem_type
  72. def is_worse_than(self, other_problem):
  73. """Return True if this is a worse problem than other_problem"""
  74. if self.metric_value > other_problem.metric_value:
  75. return True
  76. return False
  77. def key(self):
  78. """Generate a unique key that describes this problem that can be used as a dictionary key"""
  79. # Problem location is a filesystem path, so we need to normalize this
  80. # across platforms otherwise same paths are not gonna match.
  81. canonical_location = os.path.normcase(self.problem_location)
  82. return "%s:%s" % (canonical_location, self.problem_type)
  83. def __str__(self):
  84. return "problem %s %s %s" % (self.problem_type, self.problem_location, self.metric_value)
  85. class FileSizeProblem(Problem):
  86. """
  87. Denotes a problem with the size of a .c file.
  88. The 'problem_location' is the filesystem path of the .c file, and the
  89. 'metric_value' is the number of lines in the .c file.
  90. """
  91. def __init__(self, problem_location, metric_value):
  92. super(FileSizeProblem, self).__init__("file-size", problem_location, metric_value)
  93. class IncludeCountProblem(Problem):
  94. """
  95. Denotes a problem with the number of #includes in a .c file.
  96. The 'problem_location' is the filesystem path of the .c file, and the
  97. 'metric_value' is the number of #includes in the .c file.
  98. """
  99. def __init__(self, problem_location, metric_value):
  100. super(IncludeCountProblem, self).__init__("include-count", problem_location, metric_value)
  101. class FunctionSizeProblem(Problem):
  102. """
  103. Denotes a problem with a size of a function in a .c file.
  104. The 'problem_location' is "<path>:<function>()" where <path> is the
  105. filesystem path of the .c file and <function> is the name of the offending
  106. function.
  107. The 'metric_value' is the size of the offending function in lines.
  108. """
  109. def __init__(self, problem_location, metric_value):
  110. super(FunctionSizeProblem, self).__init__("function-size", problem_location, metric_value)
  111. comment_re = re.compile(r'#.*$')
  112. def get_old_problem_from_exception_str(exception_str):
  113. orig_str = exception_str
  114. exception_str = comment_re.sub("", exception_str)
  115. fields = exception_str.split()
  116. if len(fields) == 0:
  117. # empty line or comment
  118. return None
  119. elif len(fields) == 4:
  120. # valid line
  121. _, problem_type, problem_location, metric_value = fields
  122. else:
  123. raise ValueError("Misformatted line {!r}".format(orig_str))
  124. if problem_type == "file-size":
  125. return FileSizeProblem(problem_location, metric_value)
  126. elif problem_type == "include-count":
  127. return IncludeCountProblem(problem_location, metric_value)
  128. elif problem_type == "function-size":
  129. return FunctionSizeProblem(problem_location, metric_value)
  130. else:
  131. raise ValueError("Unknown exception type {!r}".format(orig_str))