complexity.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #
  2. # Metrix++, Copyright 2009-2013, Metrix++ Project
  3. # Link: http://metrixplusplus.sourceforge.net
  4. #
  5. # This file is a part of Metrix++ Tool.
  6. #
  7. # Metrix++ is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, version 3 of the License.
  10. #
  11. # Metrix++ is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Metrix++. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. import core.api
  20. import re
  21. class Plugin(core.api.Plugin, core.api.Child, core.api.IConfigurable):
  22. def declare_configuration(self, parser):
  23. parser.add_option("--std.code.complexity.on", action="store_true", default=False,
  24. help="Enables collection of complexity metrics: cyclomatic by McCabe [default: %default]")
  25. def configure(self, options):
  26. self.is_active = options.__dict__['std.code.complexity.on']
  27. def initialize(self):
  28. if self.is_active == True:
  29. namespace = self.get_plugin_loader().get_database_loader().create_namespace(self.get_name(), support_regions = True)
  30. namespace.add_field('cyclomatic', int)
  31. core.api.subscribe_by_parents_name('std.code.cpp', self, 'callback_cpp')
  32. # trigger version property set
  33. core.api.Plugin.initialize(self)
  34. # cyclomatic complexity pattern
  35. pattern = re.compile(r'''([^0-9A-Za-z_]((if)|(case)|(for)|(while))[^0-9A-Za-z_])|[&][&]|[|][|]|[?]''')
  36. def callback_cpp(self, parent, data, is_updated):
  37. is_updated = is_updated or self.is_updated
  38. if is_updated == True:
  39. text = data.get_content(exclude = data.get_marker_types().ALL_EXCEPT_CODE)
  40. for region in data.iterate_regions(filter_group=data.get_region_types().FUNCTION):
  41. # cyclomatic complexity
  42. count = 0
  43. start_pos = region.get_offset_begin()
  44. for sub_id in region.iterate_subregion_ids():
  45. # exclude sub regions, like enclosed classes
  46. count += len(self.pattern.findall(text, start_pos, data.get_region(sub_id).get_offset_begin()))
  47. start_pos = data.get_region(sub_id).get_offset_end()
  48. count += len(self.pattern.findall(text, start_pos, region.get_offset_end()))
  49. region.set_data(self.get_name(), 'cyclomatic', count)