pretty_vcproj.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. #!/usr/bin/env python
  2. # Copyright (c) 2012 Google Inc. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Make the format of a vcproj really pretty.
  6. This script normalize and sort an xml. It also fetches all the properties
  7. inside linked vsprops and include them explicitly in the vcproj.
  8. It outputs the resulting xml to stdout.
  9. """
  10. __author__ = 'nsylvain (Nicolas Sylvain)'
  11. import os
  12. import sys
  13. from xml.dom.minidom import parse
  14. from xml.dom.minidom import Node
  15. REPLACEMENTS = dict()
  16. ARGUMENTS = None
  17. class CmpTuple(object):
  18. """Compare function between 2 tuple."""
  19. def __call__(self, x, y):
  20. return cmp(x[0], y[0])
  21. class CmpNode(object):
  22. """Compare function between 2 xml nodes."""
  23. def __call__(self, x, y):
  24. def get_string(node):
  25. node_string = "node"
  26. node_string += node.nodeName
  27. if node.nodeValue:
  28. node_string += node.nodeValue
  29. if node.attributes:
  30. # We first sort by name, if present.
  31. node_string += node.getAttribute("Name")
  32. all_nodes = []
  33. for (name, value) in node.attributes.items():
  34. all_nodes.append((name, value))
  35. all_nodes.sort(CmpTuple())
  36. for (name, value) in all_nodes:
  37. node_string += name
  38. node_string += value
  39. return node_string
  40. return cmp(get_string(x), get_string(y))
  41. def PrettyPrintNode(node, indent=0):
  42. if node.nodeType == Node.TEXT_NODE:
  43. if node.data.strip():
  44. print '%s%s' % (' '*indent, node.data.strip())
  45. return
  46. if node.childNodes:
  47. node.normalize()
  48. # Get the number of attributes
  49. attr_count = 0
  50. if node.attributes:
  51. attr_count = node.attributes.length
  52. # Print the main tag
  53. if attr_count == 0:
  54. print '%s<%s>' % (' '*indent, node.nodeName)
  55. else:
  56. print '%s<%s' % (' '*indent, node.nodeName)
  57. all_attributes = []
  58. for (name, value) in node.attributes.items():
  59. all_attributes.append((name, value))
  60. all_attributes.sort(CmpTuple())
  61. for (name, value) in all_attributes:
  62. print '%s %s="%s"' % (' '*indent, name, value)
  63. print '%s>' % (' '*indent)
  64. if node.nodeValue:
  65. print '%s %s' % (' '*indent, node.nodeValue)
  66. for sub_node in node.childNodes:
  67. PrettyPrintNode(sub_node, indent=indent+2)
  68. print '%s</%s>' % (' '*indent, node.nodeName)
  69. def FlattenFilter(node):
  70. """Returns a list of all the node and sub nodes."""
  71. node_list = []
  72. if (node.attributes and
  73. node.getAttribute('Name') == '_excluded_files'):
  74. # We don't add the "_excluded_files" filter.
  75. return []
  76. for current in node.childNodes:
  77. if current.nodeName == 'Filter':
  78. node_list.extend(FlattenFilter(current))
  79. else:
  80. node_list.append(current)
  81. return node_list
  82. def FixFilenames(filenames, current_directory):
  83. new_list = []
  84. for filename in filenames:
  85. if filename:
  86. for key in REPLACEMENTS:
  87. filename = filename.replace(key, REPLACEMENTS[key])
  88. os.chdir(current_directory)
  89. filename = filename.strip('"\' ')
  90. if filename.startswith('$'):
  91. new_list.append(filename)
  92. else:
  93. new_list.append(os.path.abspath(filename))
  94. return new_list
  95. def AbsoluteNode(node):
  96. """Makes all the properties we know about in this node absolute."""
  97. if node.attributes:
  98. for (name, value) in node.attributes.items():
  99. if name in ['InheritedPropertySheets', 'RelativePath',
  100. 'AdditionalIncludeDirectories',
  101. 'IntermediateDirectory', 'OutputDirectory',
  102. 'AdditionalLibraryDirectories']:
  103. # We want to fix up these paths
  104. path_list = value.split(';')
  105. new_list = FixFilenames(path_list, os.path.dirname(ARGUMENTS[1]))
  106. node.setAttribute(name, ';'.join(new_list))
  107. if not value:
  108. node.removeAttribute(name)
  109. def CleanupVcproj(node):
  110. """For each sub node, we call recursively this function."""
  111. for sub_node in node.childNodes:
  112. AbsoluteNode(sub_node)
  113. CleanupVcproj(sub_node)
  114. # Normalize the node, and remove all extranous whitespaces.
  115. for sub_node in node.childNodes:
  116. if sub_node.nodeType == Node.TEXT_NODE:
  117. sub_node.data = sub_node.data.replace("\r", "")
  118. sub_node.data = sub_node.data.replace("\n", "")
  119. sub_node.data = sub_node.data.rstrip()
  120. # Fix all the semicolon separated attributes to be sorted, and we also
  121. # remove the dups.
  122. if node.attributes:
  123. for (name, value) in node.attributes.items():
  124. sorted_list = sorted(value.split(';'))
  125. unique_list = []
  126. for i in sorted_list:
  127. if not unique_list.count(i):
  128. unique_list.append(i)
  129. node.setAttribute(name, ';'.join(unique_list))
  130. if not value:
  131. node.removeAttribute(name)
  132. if node.childNodes:
  133. node.normalize()
  134. # For each node, take a copy, and remove it from the list.
  135. node_array = []
  136. while node.childNodes and node.childNodes[0]:
  137. # Take a copy of the node and remove it from the list.
  138. current = node.childNodes[0]
  139. node.removeChild(current)
  140. # If the child is a filter, we want to append all its children
  141. # to this same list.
  142. if current.nodeName == 'Filter':
  143. node_array.extend(FlattenFilter(current))
  144. else:
  145. node_array.append(current)
  146. # Sort the list.
  147. node_array.sort(CmpNode())
  148. # Insert the nodes in the correct order.
  149. for new_node in node_array:
  150. # But don't append empty tool node.
  151. if new_node.nodeName == 'Tool':
  152. if new_node.attributes and new_node.attributes.length == 1:
  153. # This one was empty.
  154. continue
  155. if new_node.nodeName == 'UserMacro':
  156. continue
  157. node.appendChild(new_node)
  158. def GetConfiguationNodes(vcproj):
  159. #TODO(nsylvain): Find a better way to navigate the xml.
  160. nodes = []
  161. for node in vcproj.childNodes:
  162. if node.nodeName == "Configurations":
  163. for sub_node in node.childNodes:
  164. if sub_node.nodeName == "Configuration":
  165. nodes.append(sub_node)
  166. return nodes
  167. def GetChildrenVsprops(filename):
  168. dom = parse(filename)
  169. if dom.documentElement.attributes:
  170. vsprops = dom.documentElement.getAttribute('InheritedPropertySheets')
  171. return FixFilenames(vsprops.split(';'), os.path.dirname(filename))
  172. return []
  173. def SeekToNode(node1, child2):
  174. # A text node does not have properties.
  175. if child2.nodeType == Node.TEXT_NODE:
  176. return None
  177. # Get the name of the current node.
  178. current_name = child2.getAttribute("Name")
  179. if not current_name:
  180. # There is no name. We don't know how to merge.
  181. return None
  182. # Look through all the nodes to find a match.
  183. for sub_node in node1.childNodes:
  184. if sub_node.nodeName == child2.nodeName:
  185. name = sub_node.getAttribute("Name")
  186. if name == current_name:
  187. return sub_node
  188. # No match. We give up.
  189. return None
  190. def MergeAttributes(node1, node2):
  191. # No attributes to merge?
  192. if not node2.attributes:
  193. return
  194. for (name, value2) in node2.attributes.items():
  195. # Don't merge the 'Name' attribute.
  196. if name == 'Name':
  197. continue
  198. value1 = node1.getAttribute(name)
  199. if value1:
  200. # The attribute exist in the main node. If it's equal, we leave it
  201. # untouched, otherwise we concatenate it.
  202. if value1 != value2:
  203. node1.setAttribute(name, ';'.join([value1, value2]))
  204. else:
  205. # The attribute does nto exist in the main node. We append this one.
  206. node1.setAttribute(name, value2)
  207. # If the attribute was a property sheet attributes, we remove it, since
  208. # they are useless.
  209. if name == 'InheritedPropertySheets':
  210. node1.removeAttribute(name)
  211. def MergeProperties(node1, node2):
  212. MergeAttributes(node1, node2)
  213. for child2 in node2.childNodes:
  214. child1 = SeekToNode(node1, child2)
  215. if child1:
  216. MergeProperties(child1, child2)
  217. else:
  218. node1.appendChild(child2.cloneNode(True))
  219. def main(argv):
  220. """Main function of this vcproj prettifier."""
  221. global ARGUMENTS
  222. ARGUMENTS = argv
  223. # check if we have exactly 1 parameter.
  224. if len(argv) < 2:
  225. print ('Usage: %s "c:\\path\\to\\vcproj.vcproj" [key1=value1] '
  226. '[key2=value2]' % argv[0])
  227. return 1
  228. # Parse the keys
  229. for i in range(2, len(argv)):
  230. (key, value) = argv[i].split('=')
  231. REPLACEMENTS[key] = value
  232. # Open the vcproj and parse the xml.
  233. dom = parse(argv[1])
  234. # First thing we need to do is find the Configuration Node and merge them
  235. # with the vsprops they include.
  236. for configuration_node in GetConfiguationNodes(dom.documentElement):
  237. # Get the property sheets associated with this configuration.
  238. vsprops = configuration_node.getAttribute('InheritedPropertySheets')
  239. # Fix the filenames to be absolute.
  240. vsprops_list = FixFilenames(vsprops.strip().split(';'),
  241. os.path.dirname(argv[1]))
  242. # Extend the list of vsprops with all vsprops contained in the current
  243. # vsprops.
  244. for current_vsprops in vsprops_list:
  245. vsprops_list.extend(GetChildrenVsprops(current_vsprops))
  246. # Now that we have all the vsprops, we need to merge them.
  247. for current_vsprops in vsprops_list:
  248. MergeProperties(configuration_node,
  249. parse(current_vsprops).documentElement)
  250. # Now that everything is merged, we need to cleanup the xml.
  251. CleanupVcproj(dom.documentElement)
  252. # Finally, we use the prett xml function to print the vcproj back to the
  253. # user.
  254. #print dom.toprettyxml(newl="\n")
  255. PrettyPrintNode(dom.documentElement)
  256. return 0
  257. if __name__ == '__main__':
  258. sys.exit(main(sys.argv))