export.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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 logging
  20. import time
  21. import re
  22. import core.log
  23. import core.db.loader
  24. import core.db.post
  25. import core.db.utils
  26. import core.cmdparser
  27. import core.export.convert
  28. def main():
  29. log_plugin = core.log.Plugin()
  30. db_plugin = core.db.post.Plugin()
  31. parser = core.cmdparser.MultiOptionParser(usage="Usage: %prog [options] -- [path 1] ... [path N]")
  32. log_plugin.declare_configuration(parser)
  33. db_plugin.declare_configuration(parser)
  34. parser.add_option("--general.format", default='xml', choices=['txt', 'xml', 'python'], help="Format of the output data. "
  35. "Possible values are 'xml', 'txt' or 'python' [default: %default]")
  36. parser.add_option("--general.namespaces", default=None, help="Allows to enumerate namespaces of interest."
  37. " If not defined all namespaces available in database file will be processed."
  38. " Separate several namespaces by comma, for example 'general,std.code.complexity'"
  39. " [default: %default]")
  40. parser.add_option("--general.nest-regions", action="store_true", default=False,
  41. help="If the option is set (True), data for regions is exported in the form of a tree. "
  42. "Otherwise, all regions are exported in plain list. [default: %default]")
  43. (options, args) = parser.parse_args()
  44. log_plugin.configure(options)
  45. db_plugin.configure(options)
  46. out_format = options.__dict__['general.format']
  47. nest_regions = options.__dict__['general.nest_regions']
  48. namespaces = None
  49. if options.__dict__['general.namespaces'] != None:
  50. namespaces = re.split(',', options.__dict__['general.namespaces'])
  51. loader_prev = core.db.loader.Loader()
  52. if db_plugin.dbfile_prev != None:
  53. loader_prev.open_database(db_plugin.dbfile_prev)
  54. loader = core.db.loader.Loader()
  55. loader.open_database(db_plugin.dbfile)
  56. paths = None
  57. if len(args) == 0:
  58. paths = [""]
  59. else:
  60. paths = args
  61. (result, exit_code) = export_to_str(out_format, paths, loader, loader_prev, namespaces, nest_regions)
  62. print result
  63. return exit_code
  64. def export_to_str(out_format, paths, loader, loader_prev, namespaces, nest_regions):
  65. exit_code = 0
  66. result = ""
  67. if out_format == 'txt':
  68. result += "=" * 80 + "\n" + "Export" + "\n" + "_" * 80 + "\n\n"
  69. elif out_format == 'xml':
  70. result += "<export>\n"
  71. elif out_format == 'python':
  72. result += "{'export': ["
  73. for (ind, path) in enumerate(paths):
  74. logging.info("Processing: " + re.sub(r'''[\\]''', "/", path))
  75. aggregated_data = loader.load_aggregated_data(path, namespaces=namespaces)
  76. aggregated_data_tree = {}
  77. subdirs = []
  78. subfiles = []
  79. if aggregated_data != None:
  80. aggregated_data_tree = aggregated_data.get_data_tree(namespaces=namespaces)
  81. subdirs = aggregated_data.get_subdirs()
  82. subfiles = aggregated_data.get_subfiles()
  83. else:
  84. logging.error("Specified path '" + path + "' is invalid (not found in the database records)")
  85. exit_code += 1
  86. aggregated_data_prev = loader_prev.load_aggregated_data(path, namespaces=namespaces)
  87. if aggregated_data_prev != None:
  88. aggregated_data_tree = append_diff(aggregated_data_tree,
  89. aggregated_data_prev.get_data_tree(namespaces=namespaces))
  90. file_data = loader.load_file_data(path)
  91. file_data_tree = {}
  92. if file_data != None:
  93. file_data_tree = file_data.get_data_tree(namespaces=namespaces)
  94. file_data_prev = loader_prev.load_file_data(path)
  95. append_regions(file_data_tree, file_data, file_data_prev, namespaces, nest_regions)
  96. data = {"info": {"path": path, "id": ind + 1},
  97. "aggregated-data": aggregated_data_tree,
  98. "file-data": file_data_tree,
  99. "subdirs": subdirs,
  100. "subfiles": subfiles}
  101. if out_format == 'txt':
  102. result += core.export.convert.to_txt(data, root_name = "data") + "\n"
  103. elif out_format == 'xml':
  104. result += core.export.convert.to_xml(data, root_name = "data") + "\n"
  105. elif out_format == 'python':
  106. postfix = ""
  107. if ind < len(paths) - 1:
  108. postfix = ", "
  109. result += core.export.convert.to_python(data, root_name = "data") + postfix
  110. if out_format == 'txt':
  111. result += "\n"
  112. elif out_format == 'xml':
  113. result += "</export>"
  114. elif out_format == 'python':
  115. result += "]}"
  116. return (result, exit_code)
  117. def append_regions(file_data_tree, file_data, file_data_prev, namespaces, nest_regions):
  118. regions_matcher = None
  119. if file_data_prev != None:
  120. file_data_tree = append_diff(file_data_tree,
  121. file_data_prev.get_data_tree(namespaces=namespaces))
  122. regions_matcher = core.db.utils.FileRegionsMatcher(file_data, file_data_prev)
  123. if nest_regions == False:
  124. regions = []
  125. for region in file_data.iterate_regions():
  126. region_data_tree = region.get_data_tree(namespaces=namespaces)
  127. if regions_matcher != None and regions_matcher.is_matched(region.get_id()):
  128. region_data_prev = file_data_prev.get_region(regions_matcher.get_prev_id(region.get_id()))
  129. region_data_tree = append_diff(region_data_tree,
  130. region_data_prev.get_data_tree(namespaces=namespaces))
  131. regions.append({"info": {"name" : region.name,
  132. 'type' : file_data.get_region_types()().to_str(region.get_type()),
  133. "cursor" : region.cursor,
  134. 'line_begin': region.line_begin,
  135. 'line_end': region.line_end,
  136. 'offset_begin': region.begin,
  137. 'offset_end': region.end},
  138. "data": region_data_tree})
  139. file_data_tree['regions'] = regions
  140. else:
  141. def append_rec(region_id, file_data_tree, file_data, file_data_prev, namespaces):
  142. region = file_data.get_region(region_id)
  143. region_data_tree = region.get_data_tree(namespaces=namespaces)
  144. if regions_matcher != None and regions_matcher.is_matched(region.get_id()):
  145. region_data_prev = file_data_prev.get_region(regions_matcher.get_prev_id(region.get_id()))
  146. region_data_tree = append_diff(region_data_tree,
  147. region_data_prev.get_data_tree(namespaces=namespaces))
  148. result = {"info": {"name" : region.name,
  149. 'type' : file_data.get_region_types()().to_str(region.get_type()),
  150. "cursor" : region.cursor,
  151. 'line_begin': region.line_begin,
  152. 'line_end': region.line_end,
  153. 'offset_begin': region.begin,
  154. 'offset_end': region.end},
  155. "data": region_data_tree,
  156. "subregions": []}
  157. for sub_id in file_data.get_region(region_id).iterate_subregion_ids():
  158. result['subregions'].append(append_rec(sub_id, file_data_tree, file_data, file_data_prev, namespaces))
  159. return result
  160. file_data_tree['regions'] = []
  161. file_data_tree['regions'].append(append_rec(1, file_data_tree, file_data, file_data_prev, namespaces))
  162. def append_diff(main_tree, prev_tree):
  163. assert(main_tree != None)
  164. assert(prev_tree != None)
  165. for name in main_tree.keys():
  166. if name not in prev_tree.keys():
  167. continue
  168. for field in main_tree[name].keys():
  169. if field not in prev_tree[name].keys():
  170. continue
  171. if isinstance(main_tree[name][field], dict) and isinstance(prev_tree[name][field], dict):
  172. diff = {}
  173. for key in main_tree[name][field].keys():
  174. if key not in prev_tree[name][field].keys():
  175. continue
  176. main_val = main_tree[name][field][key]
  177. prev_val = prev_tree[name][field][key]
  178. if main_val == None:
  179. main_val = 0
  180. if prev_val == None:
  181. prev_val = 0
  182. diff[key] = main_val - prev_val
  183. main_tree[name][field]['__diff__'] = diff
  184. elif (not isinstance(main_tree[name][field], dict)) and (not isinstance(prev_tree[name][field], dict)):
  185. if '__diff__' not in main_tree[name]:
  186. main_tree[name]['__diff__'] = {}
  187. main_tree[name]['__diff__'][field] = main_tree[name][field] - prev_tree[name][field]
  188. return main_tree
  189. if __name__ == '__main__':
  190. ts = time.time()
  191. core.log.set_default_format()
  192. exit_code = main()
  193. logging.warning("Exit code: " + str(exit_code) + ". Time spent: " + str(round((time.time() - ts), 2)) + " seconds. Done")
  194. exit(exit_code)