magic.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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("--std.code.magic.numbers", "--scmn",
  15. action="store_true", default=False,
  16. help="Enables collection of magic numbers metric [default: %default]")
  17. parser.add_option("--std.code.magic.numbers.simplier", "--scmns",
  18. action="store_true", default=False,
  19. help="Is set, 0, -1 and 1 numbers are not counted "
  20. "in 'std.code.magic.numbers' metric [default: %default]")
  21. def configure(self, options):
  22. self.is_active_numbers = options.__dict__['std.code.magic.numbers']
  23. self.is_active_numbers_simplier = options.__dict__['std.code.magic.numbers.simplier']
  24. def initialize(self):
  25. pattern_to_search_java = re.compile(
  26. r'''((const(\s+[_$a-zA-Z][_$a-zA-Z0-9]*)+\s*[=]\s*)[-+]?[0-9]+\b)|(\b[0-9]+\b)''')
  27. pattern_to_search_cpp_cs = re.compile(
  28. r'''((const(\s+[_a-zA-Z][_a-zA-Z0-9]*)+\s*[=]\s*)[-+]?[0-9]+\b)|(\b[0-9]+\b)''')
  29. self.declare_metric(self.is_active_numbers,
  30. self.Field('numbers', int,
  31. non_zero=True),
  32. {
  33. 'std.code.java': (pattern_to_search_java, self.NumbersCounter),
  34. 'std.code.cpp': (pattern_to_search_cpp_cs, self.NumbersCounter),
  35. 'std.code.cs': (pattern_to_search_cpp_cs, self.NumbersCounter),
  36. },
  37. marker_type_mask=mpp.api.Marker.T.CODE,
  38. region_type_mask=mpp.api.Region.T.ANY)
  39. super(Plugin, self).initialize(fields=self.get_fields(),
  40. properties=[self.Property('number.simplier', self.is_active_numbers_simplier)])
  41. if self.is_active() == True:
  42. self.subscribe_by_parents_interface(mpp.api.ICode)
  43. class NumbersCounter(mpp.api.MetricPluginMixin.IterIncrementCounter):
  44. def increment(self, match):
  45. if (match.group(0).startswith('const') or
  46. (self.plugin.is_active_numbers_simplier == True and
  47. match.group(0) in ['0', '1', '-1', '+1'])):
  48. return 0
  49. return 1