export.py 10 KB

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