report.py 16 KB

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