pretty_vcproj.py 10 KB

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