pretty_vcproj.py 10 KB

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