limit.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. #
  2. # Metrix++, Copyright 2009-2013, Metrix++ Project
  3. # Link: http://metrixplusplus.sourceforge.net
  4. #
  5. # This file is a part of Metrix++ Tool.
  6. #
  7. # Metrix++ is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, version 3 of the License.
  10. #
  11. # Metrix++ is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Metrix++. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. import logging
  20. import re
  21. import mpp.api
  22. import mpp.utils
  23. import mpp.cout
  24. class Plugin(mpp.api.Plugin, mpp.api.IConfigurable, mpp.api.IRunable):
  25. MODE_NEW = 0x01
  26. MODE_TREND = 0x03
  27. MODE_TOUCHED = 0x07
  28. MODE_ALL = 0x15
  29. def declare_configuration(self, parser):
  30. self.parser = parser
  31. parser.add_option("--hotspots", "--hs", default=None, help="If not set (none), all exceeded limits are printed."
  32. " If set, exceeded limits are sorted (the worst is the first) and only first HOTSPOTS limits are printed."
  33. " [default: %default]", type=int)
  34. parser.add_option("--disable-suppressions", "--ds", action="store_true", default=False,
  35. help = "If not set (none), all suppressions are ignored"
  36. " and associated warnings are printed. [default: %default]")
  37. parser.add_option("--warn-mode", "--wm", default='all', choices=['new', 'trend', 'touched', 'all'],
  38. help="Defines the warnings mode. "
  39. "'all' - all warnings active, "
  40. "'new' - warnings for new regions/files only, "
  41. "'trend' - warnings for new regions/files and for bad trend of modified regions/files, "
  42. "'touched' - warnings for new and modified regions/files "
  43. "[default: %default]")
  44. parser.add_option("--min-limit", "--min", action="multiopt",
  45. help="A threshold per 'namespace:field' metric in order to select regions, "
  46. "which have got metric value less than the specified limit. "
  47. "This option can be specified multiple times, if it is necessary to apply several limits. "
  48. "Should be in the format: <namespace>:<field>:<limit-value>, for example: "
  49. "'std.code.lines:comments:1'.")
  50. parser.add_option("--max-limit", "--max", action="multiopt",
  51. help="A threshold per 'namespace:field' metric in order to select regions, "
  52. "which have got metric value more than the specified limit. "
  53. "This option can be specified multiple times, if it is necessary to apply several limits. "
  54. "Should be in the format: <namespace>:<field>:<limit-value>, for example: "
  55. "'std.code.complexity:cyclomatic:7'.")
  56. def configure(self, options):
  57. self.hotspots = options.__dict__['hotspots']
  58. self.no_suppress = options.__dict__['disable_suppressions']
  59. if options.__dict__['warn_mode'] == 'new':
  60. self.mode = self.MODE_NEW
  61. elif options.__dict__['warn_mode'] == 'trend':
  62. self.mode = self.MODE_TREND
  63. elif options.__dict__['warn_mode'] == 'touched':
  64. self.mode = self.MODE_TOUCHED
  65. elif options.__dict__['warn_mode'] == 'all':
  66. self.mode = self.MODE_ALL
  67. if self.mode != self.MODE_ALL and options.__dict__['db_file_prev'] == None:
  68. self.parser.error("option --warn-mode: The mode '" + options.__dict__['warn_mode'] + "' requires '--db-file-prev' option set")
  69. class Limit(object):
  70. def __init__(self, limit_type, limit, namespace, field, db_filter):
  71. self.type = limit_type
  72. self.limit = limit
  73. self.namespace = namespace
  74. self.field = field
  75. self.filter = db_filter
  76. def __repr__(self):
  77. return "namespace '" + self.namespace + "', filter '" + str(self.filter) + "'"
  78. self.limits = []
  79. pattern = re.compile(r'''([^:]+)[:]([^:]+)[:]([-+]?[0-9]+(?:[.][0-9]+)?)''')
  80. if options.__dict__['max_limit'] != None:
  81. for each in options.__dict__['max_limit']:
  82. match = re.match(pattern, each)
  83. if match == None:
  84. self.parser.error("option --max-limit: Invalid format: " + each)
  85. limit = Limit("max", float(match.group(3)), match.group(1), match.group(2), (match.group(2), '>', float(match.group(3))))
  86. self.limits.append(limit)
  87. if options.__dict__['min_limit'] != None:
  88. for each in options.__dict__['min_limit']:
  89. match = re.match(pattern, each)
  90. if match == None:
  91. self.parser.error("option --min-limit: Invalid format: " + each)
  92. limit = Limit("min", float(match.group(3)), match.group(1), match.group(2), (match.group(2), '<', float(match.group(3))))
  93. self.limits.append(limit)
  94. def initialize(self):
  95. super(Plugin, self).initialize()
  96. db_loader = self.get_plugin('mpp.dbf').get_loader()
  97. self._verify_namespaces(db_loader.iterate_namespace_names())
  98. for each in db_loader.iterate_namespace_names():
  99. self._verify_fields(each, db_loader.get_namespace(each).iterate_field_names())
  100. def _verify_namespaces(self, valid_namespaces):
  101. valid = []
  102. for each in valid_namespaces:
  103. valid.append(each)
  104. for each in self.limits:
  105. if each.namespace not in valid:
  106. self.parser.error("option --{0}-limit: metric '{1}:{2}' is not available in the database file.".
  107. format(each.type, each.namespace, each.field))
  108. def _verify_fields(self, namespace, valid_fields):
  109. valid = []
  110. for each in valid_fields:
  111. valid.append(each)
  112. for each in self.limits:
  113. if each.namespace == namespace:
  114. if each.field not in valid:
  115. self.parser.error("option --{0}-limit: metric '{1}:{2}' is not available in the database file.".
  116. format(each.type, each.namespace, each.field))
  117. def iterate_limits(self):
  118. for each in self.limits:
  119. yield each
  120. def is_mode_matched(self, limit, value, diff, is_modified):
  121. if is_modified == None:
  122. # means new region, True in all modes
  123. return True
  124. if self.mode == self.MODE_ALL:
  125. return True
  126. if self.mode == self.MODE_TOUCHED and is_modified == True:
  127. return True
  128. if self.mode == self.MODE_TREND and is_modified == True:
  129. if limit < value and diff > 0:
  130. return True
  131. if limit > value and diff < 0:
  132. return True
  133. return False
  134. def run(self, args):
  135. return main(self, args)
  136. def main(plugin, args):
  137. exit_code = 0
  138. loader_prev = plugin.get_plugin('mpp.dbf').get_loader_prev()
  139. loader = plugin.get_plugin('mpp.dbf').get_loader()
  140. paths = None
  141. if len(args) == 0:
  142. paths = [""]
  143. else:
  144. paths = args
  145. # Try to optimise iterative change scans
  146. modified_file_ids = None
  147. if plugin.mode != plugin.MODE_ALL:
  148. modified_file_ids = get_list_of_modified_files(loader, loader_prev)
  149. for path in paths:
  150. path = mpp.utils.preprocess_path(path)
  151. for limit in plugin.iterate_limits():
  152. logging.info("Applying limit: " + str(limit))
  153. filters = [limit.filter]
  154. if modified_file_ids != None:
  155. filters.append(('file_id', 'IN', modified_file_ids))
  156. sort_by = None
  157. limit_by = None
  158. limit_warnings = None
  159. if plugin.hotspots != None:
  160. sort_by = limit.field
  161. if limit.type == "max":
  162. sort_by = "-" + sort_by
  163. if plugin.mode == plugin.MODE_ALL:
  164. # if it is not ALL mode, the tool counts number of printed warnings below
  165. limit_by = plugin.hotspots
  166. limit_warnings = plugin.hotspots
  167. selected_data = loader.load_selected_data(limit.namespace,
  168. fields = [limit.field],
  169. path=path,
  170. filters = filters,
  171. sort_by=sort_by,
  172. limit_by=limit_by)
  173. if selected_data == None:
  174. mpp.utils.report_bad_path(path)
  175. exit_code += 1
  176. continue
  177. for select_data in selected_data:
  178. if limit_warnings != None and limit_warnings <= 0:
  179. break
  180. is_modified = None
  181. diff = None
  182. file_data = loader.load_file_data(select_data.get_path())
  183. file_data_prev = loader_prev.load_file_data(select_data.get_path())
  184. if file_data_prev != None:
  185. if file_data.get_checksum() == file_data_prev.get_checksum():
  186. diff = 0
  187. is_modified = False
  188. else:
  189. matcher = mpp.utils.FileRegionsMatcher(file_data, file_data_prev)
  190. prev_id = matcher.get_prev_id(select_data.get_region().get_id())
  191. if matcher.is_matched(select_data.get_region().get_id()):
  192. if matcher.is_modified(select_data.get_region().get_id()):
  193. is_modified = True
  194. else:
  195. is_modified = False
  196. diff = mpp.api.DiffData(select_data,
  197. file_data_prev.get_region(prev_id)).get_data(limit.namespace, limit.field)
  198. if (plugin.is_mode_matched(limit.limit,
  199. select_data.get_data(limit.namespace, limit.field),
  200. diff,
  201. is_modified) == False):
  202. continue
  203. is_sup = is_metric_suppressed(limit.namespace, limit.field, loader, select_data)
  204. if is_sup == True and plugin.no_suppress == False:
  205. continue
  206. exit_code += 1
  207. region_cursor = 0
  208. region_name = None
  209. if select_data.get_region() != None:
  210. region_cursor = select_data.get_region().cursor
  211. region_name = select_data.get_region().name
  212. report_limit_exceeded(select_data.get_path(),
  213. region_cursor,
  214. limit.namespace,
  215. limit.field,
  216. region_name,
  217. select_data.get_data(limit.namespace, limit.field),
  218. diff,
  219. limit.limit,
  220. is_modified,
  221. is_sup)
  222. if limit_warnings != None:
  223. limit_warnings -= 1
  224. return exit_code
  225. def get_list_of_modified_files(loader, loader_prev):
  226. logging.info("Identifying changed files...")
  227. old_files_map = {}
  228. for each in loader_prev.iterate_file_data():
  229. old_files_map[each.get_path()] = each.get_checksum()
  230. if len(old_files_map) == 0:
  231. return None
  232. modified_file_ids = []
  233. for each in loader.iterate_file_data():
  234. if len(modified_file_ids) > 1000: # If more than 1000 files changed, skip optimisation
  235. return None
  236. if (each.get_path() not in old_files_map.keys()) or old_files_map[each.get_path()] != each.get_checksum():
  237. modified_file_ids.append(str(each.get_id()))
  238. old_files_map = None
  239. if len(modified_file_ids) != 0:
  240. modified_file_ids = " , ".join(modified_file_ids)
  241. modified_file_ids = "(" + modified_file_ids + ")"
  242. return modified_file_ids
  243. return None
  244. def is_metric_suppressed(metric_namespace, metric_field, loader, select_data):
  245. data = loader.load_file_data(select_data.get_path())
  246. if select_data.get_region() != None:
  247. data = data.get_region(select_data.get_region().get_id())
  248. sup_data = data.get_data('std.suppress', 'list')
  249. else:
  250. sup_data = data.get_data('std.suppress.file', 'list')
  251. if sup_data != None and sup_data.find('[' + metric_namespace + ':' + metric_field + ']') != -1:
  252. return True
  253. return False
  254. def report_limit_exceeded(path, cursor, namespace, field, region_name,
  255. stat_level, trend_value, stat_limit,
  256. is_modified, is_suppressed):
  257. if region_name != None:
  258. message = "Metric '" + namespace + ":" + field + "' for region '" + region_name + "' exceeds the limit."
  259. else:
  260. message = "Metric '" + namespace + ":" + field + "' exceeds the limit."
  261. details = [("Metric name", namespace + ":" + field),
  262. ("Region name", region_name),
  263. ("Metric value", stat_level),
  264. ("Modified", is_modified),
  265. ("Change trend", '{0:{1}}'.format(trend_value, '+' if trend_value else '')),
  266. ("Limit", stat_limit),
  267. ("Suppressed", is_suppressed)]
  268. mpp.cout.notify(path, cursor, mpp.cout.SEVERITY_WARNING, message, details)