collect.py 8.8 KB

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