limit.py 16 KB

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