limit.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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, original):
  71. self.type = limit_type
  72. self.limit = limit
  73. self.namespace = namespace
  74. self.field = field
  75. self.filter = db_filter
  76. self.original = original
  77. def __repr__(self):
  78. return "'{0}:{1}' {2} {3}".format(self.namespace, self.field, self.filter[1], self.limit)
  79. self.limits = []
  80. pattern = re.compile(r'''([^:]+)[:]([^:]+)[:]([-+]?[0-9]+(?:[.][0-9]+)?)''')
  81. if options.__dict__['max_limit'] != None:
  82. for each in options.__dict__['max_limit']:
  83. match = re.match(pattern, each)
  84. if match == None:
  85. self.parser.error("option --max-limit: Invalid format: " + each)
  86. limit = Limit("max", float(match.group(3)), match.group(1), match.group(2), (match.group(2), '>', float(match.group(3))), each)
  87. self.limits.append(limit)
  88. if options.__dict__['min_limit'] != None:
  89. for each in options.__dict__['min_limit']:
  90. match = re.match(pattern, each)
  91. if match == None:
  92. self.parser.error("option --min-limit: Invalid format: " + each)
  93. limit = Limit("min", float(match.group(3)), match.group(1), match.group(2), (match.group(2), '<', float(match.group(3))), each)
  94. self.limits.append(limit)
  95. def initialize(self):
  96. super(Plugin, self).initialize()
  97. db_loader = self.get_plugin('mpp.dbf').get_loader()
  98. self._verify_namespaces(db_loader.iterate_namespace_names())
  99. for each in db_loader.iterate_namespace_names():
  100. self._verify_fields(each, db_loader.get_namespace(each).iterate_field_names())
  101. def _verify_namespaces(self, valid_namespaces):
  102. valid = []
  103. for each in valid_namespaces:
  104. valid.append(each)
  105. for each in self.limits:
  106. if each.namespace not in valid:
  107. self.parser.error("option --{0}-limit: metric '{1}:{2}' is not available in the database file.".
  108. format(each.type, each.namespace, each.field))
  109. def _verify_fields(self, namespace, valid_fields):
  110. valid = []
  111. for each in valid_fields:
  112. valid.append(each)
  113. for each in self.limits:
  114. if each.namespace == namespace:
  115. if each.field not in valid:
  116. self.parser.error("option --{0}-limit: metric '{1}:{2}' is not available in the database file.".
  117. format(each.type, each.namespace, each.field))
  118. def iterate_limits(self):
  119. for each in self.limits:
  120. yield each
  121. def is_mode_matched(self, limit, value, diff, is_modified):
  122. if is_modified == None:
  123. # means new region, True in all modes
  124. return True
  125. if self.mode == self.MODE_ALL:
  126. return True
  127. if self.mode == self.MODE_TOUCHED and is_modified == True:
  128. return True
  129. if self.mode == self.MODE_TREND and is_modified == True:
  130. if limit < value and diff > 0:
  131. return True
  132. if limit > value and diff < 0:
  133. return True
  134. return False
  135. def run(self, args):
  136. return main(self, args)
  137. def main(plugin, args):
  138. exit_code = 0
  139. loader_prev = plugin.get_plugin('mpp.dbf').get_loader_prev()
  140. loader = plugin.get_plugin('mpp.dbf').get_loader()
  141. paths = None
  142. if len(args) == 0:
  143. paths = [""]
  144. else:
  145. paths = args
  146. # Try to optimise iterative change scans
  147. modified_file_ids = None
  148. if plugin.mode != plugin.MODE_ALL:
  149. modified_file_ids = get_list_of_modified_files(loader, loader_prev)
  150. for path in paths:
  151. path = mpp.utils.preprocess_path(path)
  152. for limit in plugin.iterate_limits():
  153. warns_count = 0
  154. logging.info("Applying limit: " + str(limit))
  155. filters = [limit.filter]
  156. if modified_file_ids != None:
  157. filters.append(('file_id', 'IN', modified_file_ids))
  158. sort_by = None
  159. limit_by = None
  160. limit_warnings = None
  161. if plugin.hotspots != None:
  162. sort_by = limit.field
  163. if limit.type == "max":
  164. sort_by = "-" + sort_by
  165. if plugin.mode == plugin.MODE_ALL:
  166. # if it is not ALL mode, the tool counts number of printed warnings below
  167. limit_by = plugin.hotspots
  168. limit_warnings = plugin.hotspots
  169. selected_data = loader.load_selected_data(limit.namespace,
  170. fields = [limit.field],
  171. path=path,
  172. filters = filters,
  173. sort_by=sort_by,
  174. limit_by=limit_by)
  175. if selected_data == None:
  176. mpp.utils.report_bad_path(path)
  177. exit_code += 1
  178. continue
  179. for select_data in selected_data:
  180. if limit_warnings != None and limit_warnings <= 0:
  181. break
  182. is_modified = None
  183. diff = None
  184. file_data = loader.load_file_data(select_data.get_path())
  185. file_data_prev = loader_prev.load_file_data(select_data.get_path())
  186. if file_data_prev != None:
  187. if file_data.get_checksum() == file_data_prev.get_checksum():
  188. diff = 0
  189. is_modified = False
  190. else:
  191. matcher = mpp.utils.FileRegionsMatcher(file_data, file_data_prev)
  192. prev_id = matcher.get_prev_id(select_data.get_region().get_id())
  193. if matcher.is_matched(select_data.get_region().get_id()):
  194. if matcher.is_modified(select_data.get_region().get_id()):
  195. is_modified = True
  196. else:
  197. is_modified = False
  198. diff = mpp.api.DiffData(select_data,
  199. file_data_prev.get_region(prev_id)).get_data(limit.namespace, limit.field)
  200. if (plugin.is_mode_matched(limit.limit,
  201. select_data.get_data(limit.namespace, limit.field),
  202. diff,
  203. is_modified) == False):
  204. continue
  205. is_sup = is_metric_suppressed(limit.namespace, limit.field, loader, select_data)
  206. if is_sup == True and plugin.no_suppress == False:
  207. continue
  208. warns_count += 1
  209. exit_code += 1
  210. region_cursor = 0
  211. region_name = None
  212. if select_data.get_region() != None:
  213. region_cursor = select_data.get_region().cursor
  214. region_name = select_data.get_region().name
  215. report_limit_exceeded(select_data.get_path(),
  216. region_cursor,
  217. limit.namespace,
  218. limit.field,
  219. region_name,
  220. select_data.get_data(limit.namespace, limit.field),
  221. diff,
  222. limit.limit,
  223. is_modified,
  224. is_sup)
  225. if limit_warnings != None:
  226. limit_warnings -= 1
  227. mpp.cout.notify(path, None, mpp.cout.SEVERITY_INFO, "{0} regions exceeded the limit {1}".format(warns_count, str(limit)))
  228. return exit_code
  229. def get_list_of_modified_files(loader, loader_prev):
  230. logging.info("Identifying changed files...")
  231. old_files_map = {}
  232. for each in loader_prev.iterate_file_data():
  233. old_files_map[each.get_path()] = each.get_checksum()
  234. if len(old_files_map) == 0:
  235. return None
  236. modified_file_ids = []
  237. for each in loader.iterate_file_data():
  238. if len(modified_file_ids) > 1000: # If more than 1000 files changed, skip optimisation
  239. return None
  240. if (each.get_path() not in old_files_map.keys()) or old_files_map[each.get_path()] != each.get_checksum():
  241. modified_file_ids.append(str(each.get_id()))
  242. old_files_map = None
  243. if len(modified_file_ids) != 0:
  244. modified_file_ids = " , ".join(modified_file_ids)
  245. modified_file_ids = "(" + modified_file_ids + ")"
  246. return modified_file_ids
  247. return None
  248. def is_metric_suppressed(metric_namespace, metric_field, loader, select_data):
  249. data = loader.load_file_data(select_data.get_path())
  250. if select_data.get_region() != None:
  251. data = data.get_region(select_data.get_region().get_id())
  252. sup_data = data.get_data('std.suppress', 'list')
  253. else:
  254. sup_data = data.get_data('std.suppress.file', 'list')
  255. if sup_data != None and sup_data.find('[' + metric_namespace + ':' + metric_field + ']') != -1:
  256. return True
  257. return False
  258. def report_limit_exceeded(path, cursor, namespace, field, region_name,
  259. stat_level, trend_value, stat_limit,
  260. is_modified, is_suppressed):
  261. if region_name != None:
  262. message = "Metric '" + namespace + ":" + field + "' for region '" + region_name + "' exceeds the limit."
  263. else:
  264. message = "Metric '" + namespace + ":" + field + "' exceeds the limit."
  265. details = [("Metric name", namespace + ":" + field),
  266. ("Region name", region_name),
  267. ("Metric value", stat_level),
  268. ("Modified", is_modified),
  269. ("Change trend", '{0:{1}}'.format(trend_value, '+' if trend_value else '')),
  270. ("Limit", stat_limit),
  271. ("Suppressed", is_suppressed)]
  272. mpp.cout.notify(path, cursor, mpp.cout.SEVERITY_WARNING, message, details)