magic.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 mpp.api
  8. import re
  9. class Plugin(mpp.api.Plugin,
  10. mpp.api.IConfigurable,
  11. mpp.api.Child,
  12. mpp.api.MetricPluginMixin):
  13. def declare_configuration(self, parser):
  14. parser.add_option("--myext.magic.numbers", "--mmn",
  15. action="store_true", default=False,
  16. help="Enables collection of magic numbers metric [default: %default]")
  17. # Add new option
  18. parser.add_option("--myext.magic.numbers.simplier", "--mmns",
  19. action="store_true", default=False,
  20. help="Is set, 0, -1 and 1 numbers are not counted [default: %default]")
  21. def configure(self, options):
  22. self.is_active_numbers = options.__dict__['myext.magic.numbers']
  23. # remember the option here
  24. self.is_active_numbers_simplier = options.__dict__['myext.magic.numbers.simplier']
  25. def initialize(self):
  26. pattern_to_search_java = re.compile(
  27. r'''((const(\s+[_$a-zA-Z][_$a-zA-Z0-9]*)+\s*[=]\s*)[-+]?[0-9]+\b)|(\b[0-9]+\b)''')
  28. pattern_to_search_cpp_cs = re.compile(
  29. r'''((const(\s+[_a-zA-Z][_a-zA-Z0-9]*)+\s*[=]\s*)[-+]?[0-9]+\b)|(\b[0-9]+\b)''')
  30. pattern_to_search = re.compile(
  31. r'''\b[0-9]+\b''')
  32. self.declare_metric(self.is_active_numbers,
  33. self.Field('numbers', int,
  34. non_zero=True),
  35. {
  36. 'std.code.java': (pattern_to_search_java, self.NumbersCounter),
  37. 'std.code.cpp': (pattern_to_search_cpp_cs, self.NumbersCounter),
  38. 'std.code.cs': (pattern_to_search_cpp_cs, self.NumbersCounter),
  39. '*': pattern_to_search
  40. },
  41. marker_type_mask=mpp.api.Marker.T.CODE,
  42. region_type_mask=mpp.api.Region.T.ANY)
  43. super(Plugin, self).initialize(fields=self.get_fields(),
  44. # remember option settings in data file properties
  45. # in order to detect changes in settings on iterative re-run
  46. properties=[self.Property('number.simplier', self.is_active_numbers_simplier)])
  47. if self.is_active() == True:
  48. self.subscribe_by_parents_interface(mpp.api.ICode)
  49. class NumbersCounter(mpp.api.MetricPluginMixin.IterIncrementCounter):
  50. def increment(self, match):
  51. if (match.group(0).startswith('const') or
  52. (self.plugin.is_active_numbers_simplier == True and
  53. match.group(0) in ['0', '1', '-1', '+1'])):
  54. return 0
  55. return 1