magic.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. # specialized pattern for java
  21. pattern_to_search_java = re.compile(
  22. r'''((const(\s+[_$a-zA-Z][_$a-zA-Z0-9]*)+\s*[=]\s*)[-+]?[0-9]+\b)|(\b[0-9]+\b)''')
  23. # pattern for C++ and C# languages
  24. pattern_to_search_cpp_cs = re.compile(
  25. r'''((const(\s+[_a-zA-Z][_a-zA-Z0-9]*)+\s*[=]\s*)[-+]?[0-9]+\b)|(\b[0-9]+\b)''')
  26. # pattern for all other languages
  27. pattern_to_search = re.compile(
  28. r'''\b[0-9]+\b''')
  29. self.declare_metric(self.is_active_numbers,
  30. self.Field('numbers', int),
  31. # dictionary of pairs instead of a single pair
  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. '*': pattern_to_search
  37. },
  38. marker_type_mask=mpp.api.Marker.T.CODE,
  39. region_type_mask=mpp.api.Region.T.ANY)
  40. super(Plugin, self).initialize(fields=self.get_fields())
  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'):
  46. return 0
  47. return 1