collect.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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 mpp.api
  20. import re
  21. import os
  22. import logging
  23. import time
  24. import binascii
  25. import fnmatch
  26. class Plugin(mpp.api.Plugin, mpp.api.Parent, mpp.api.IConfigurable, mpp.api.IRunable):
  27. def __init__(self):
  28. self.reader = DirectoryReader()
  29. self.include_rules = []
  30. self.exclude_rules = []
  31. self.exclude_files = []
  32. self.parsers = []
  33. super(Plugin, self).__init__()
  34. def declare_configuration(self, parser):
  35. parser.add_option("--std.general.proctime", "--sgpt", action="store_true", default=False,
  36. help="If the option is set (True), the tool measures processing time per file [default: %default]")
  37. parser.add_option("--std.general.procerrors", "--sgpe", action="store_true", default=False,
  38. help="If the option is set (True), the tool counts number of processing/parsing errors per file [default: %default]")
  39. parser.add_option("--std.general.size", "--sgs", action="store_true", default=False,
  40. help="If the option is set (True), the tool collects file size metric (in bytes) [default: %default]")
  41. parser.add_option("--include-files", "--if", default=r'.*',
  42. help="Defines the regular expression pattern to include files in processing [default: %default]")
  43. parser.add_option("--exclude-files", "--ef", default=r'^[.]',
  44. help="Defines the regular expression pattern to exclude files from processing [default: %default]")
  45. parser.add_option("--non-recursively", "--nr", action="store_true", default=False,
  46. help="If the option is set (True), sub-directories are not processed [default: %default]")
  47. self.optparser = parser
  48. def configure(self, options):
  49. self.is_proctime_enabled = options.__dict__['std.general.proctime']
  50. self.is_procerrors_enabled = options.__dict__['std.general.procerrors']
  51. self.is_size_enabled = options.__dict__['std.general.size']
  52. try:
  53. self.add_include_rule(re.compile(options.__dict__['include_files']))
  54. except Exception as e:
  55. self.optparser.error("option --include-files: " + str(e))
  56. try:
  57. self.add_exclude_rule(re.compile(options.__dict__['exclude_files']))
  58. except Exception as e:
  59. self.optparser.error("option --exclude-files: " + str(e))
  60. self.non_recursively = options.__dict__['non_recursively']
  61. def initialize(self):
  62. fields = []
  63. if self.is_proctime_enabled == True:
  64. fields.append(self.Field('proctime', float))
  65. if self.is_procerrors_enabled == True:
  66. fields.append(self.Field('procerrors', int))
  67. if self.is_size_enabled == True:
  68. fields.append(self.Field('size', int))
  69. super(Plugin, self).initialize(namespace='std.general', support_regions=False, fields=fields)
  70. self.add_exclude_file(self.get_plugin('mpp.dbf').get_dbfile_path())
  71. self.add_exclude_file(self.get_plugin('mpp.dbf').get_dbfile_prev_path())
  72. def run(self, args):
  73. if len(args) == 0:
  74. return self.reader.run(self, "./")
  75. for directory in args:
  76. return self.reader.run(self, directory)
  77. def register_parser(self, fnmatch_exp_list, parser):
  78. self.parsers.append((fnmatch_exp_list, parser))
  79. def get_parser(self, file_path):
  80. for parser in self.parsers:
  81. for fnmatch_exp in parser[0]:
  82. if fnmatch.fnmatch(file_path, fnmatch_exp):
  83. return parser[1]
  84. return None
  85. def add_include_rule(self, re_compiled_pattern):
  86. self.include_rules.append(re_compiled_pattern)
  87. def add_exclude_rule(self, re_compiled_pattern):
  88. self.exclude_rules.append(re_compiled_pattern)
  89. def add_exclude_file(self, file_path):
  90. if file_path == None:
  91. return
  92. self.exclude_files.append(file_path)
  93. def is_file_excluded(self, file_name):
  94. for each in self.include_rules:
  95. if re.match(each, os.path.basename(file_name)) == None:
  96. return True
  97. for each in self.exclude_rules:
  98. if re.match(each, os.path.basename(file_name)) != None:
  99. return True
  100. for each in self.exclude_files:
  101. if os.path.basename(each) == os.path.basename(file_name):
  102. if os.stat(each) == os.stat(file_name):
  103. return True
  104. return False
  105. class DirectoryReader():
  106. def run(self, plugin, directory):
  107. IS_TEST_MODE = False
  108. if 'METRIXPLUSPLUS_TEST_MODE' in os.environ.keys():
  109. IS_TEST_MODE = True
  110. def run_per_file(plugin, fname, full_path):
  111. exit_code = 0
  112. norm_path = re.sub(r'''[\\]''', "/", full_path)
  113. if os.path.isabs(norm_path) == False and norm_path.startswith('./') == False:
  114. norm_path = './' + norm_path
  115. if plugin.is_file_excluded(norm_path) == False:
  116. if os.path.isdir(full_path):
  117. if plugin.non_recursively == False:
  118. exit_code += run_recursively(plugin, full_path)
  119. else:
  120. parser = plugin.get_parser(full_path)
  121. if parser == None:
  122. logging.info("Skipping: " + norm_path)
  123. else:
  124. logging.info("Processing: " + norm_path)
  125. ts = time.time()
  126. f = open(full_path, 'rU');
  127. text = f.read();
  128. f.close()
  129. checksum = binascii.crc32(text) & 0xffffffff # to match python 3
  130. db_loader = plugin.get_plugin('mpp.dbf').get_loader()
  131. (data, is_updated) = db_loader.create_file_data(norm_path, checksum, text)
  132. procerrors = parser.process(plugin, data, is_updated)
  133. if plugin.is_proctime_enabled == True:
  134. data.set_data('std.general', 'proctime',
  135. (time.time() - ts) if IS_TEST_MODE == False else 0.01)
  136. if plugin.is_procerrors_enabled == True and procerrors != None and procerrors != 0:
  137. data.set_data('std.general', 'procerrors', procerrors)
  138. if plugin.is_size_enabled == True:
  139. data.set_data('std.general', 'size', len(text))
  140. db_loader.save_file_data(data)
  141. logging.debug("-" * 60)
  142. exit_code += procerrors
  143. else:
  144. logging.info("Excluding: " + norm_path)
  145. return exit_code
  146. def run_recursively(plugin, directory):
  147. exit_code = 0
  148. for fname in sorted(os.listdir(directory)):
  149. full_path = os.path.join(directory, fname)
  150. exit_code += run_per_file(plugin, fname, full_path)
  151. return exit_code
  152. if os.path.exists(directory) == False:
  153. logging.error("Skipping (does not exist): " + directory)
  154. return 1
  155. if os.path.isdir(directory):
  156. total_errors = run_recursively(plugin, directory)
  157. else:
  158. total_errors = run_per_file(plugin, os.path.basename(directory), directory)
  159. total_errors = total_errors # used, warnings are per file if not zero
  160. return 0 # ignore errors, collection is successful anyway