magic.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. def configure(self, options):
  18. self.is_active_numbers = options.__dict__['myext.magic.numbers']
  19. def initialize(self):
  20. pattern_to_search_java = re.compile(
  21. r'''((const(\s+[_$a-zA-Z][_$a-zA-Z0-9]*)+\s*[=]\s*)[-+]?[0-9]+\b)|(\b[0-9]+\b)''')
  22. pattern_to_search_cpp_cs = re.compile(
  23. r'''((const(\s+[_a-zA-Z][_a-zA-Z0-9]*)+\s*[=]\s*)[-+]?[0-9]+\b)|(\b[0-9]+\b)''')
  24. pattern_to_search = re.compile(
  25. r'''\b[0-9]+\b''')
  26. self.declare_metric(self.is_active_numbers,
  27. self.Field('numbers', int,
  28. # optimize the size of datafile:
  29. # store only non-zero results
  30. non_zero=True),
  31. {
  32. 'std.code.java': (pattern_to_search_java, self.NumbersCounter),
  33. 'std.code.cpp': (pattern_to_search_cpp_cs, self.NumbersCounter),
  34. 'std.code.cs': (pattern_to_search_cpp_cs, self.NumbersCounter),
  35. '*': pattern_to_search
  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. if self.is_active() == True:
  41. self.subscribe_by_parents_interface(mpp.api.ICode)
  42. class NumbersCounter(mpp.api.MetricPluginMixin.IterIncrementCounter):
  43. def increment(self, match):
  44. if match.group(0).startswith('const'):
  45. return 0
  46. return 1