MSVSNew.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. # Copyright (c) 2012 Google Inc. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """New implementation of Visual Studio project generation."""
  5. import os
  6. import random
  7. import gyp.common
  8. # hashlib is supplied as of Python 2.5 as the replacement interface for md5
  9. # and other secure hashes. In 2.6, md5 is deprecated. Import hashlib if
  10. # available, avoiding a deprecation warning under 2.6. Import md5 otherwise,
  11. # preserving 2.4 compatibility.
  12. try:
  13. import hashlib
  14. _new_md5 = hashlib.md5
  15. except ImportError:
  16. import md5
  17. _new_md5 = md5.new
  18. # Initialize random number generator
  19. random.seed()
  20. # GUIDs for project types
  21. ENTRY_TYPE_GUIDS = {
  22. 'project': '{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}',
  23. 'folder': '{2150E333-8FDC-42A3-9474-1A3956D46DE8}',
  24. }
  25. #------------------------------------------------------------------------------
  26. # Helper functions
  27. def MakeGuid(name, seed='msvs_new'):
  28. """Returns a GUID for the specified target name.
  29. Args:
  30. name: Target name.
  31. seed: Seed for MD5 hash.
  32. Returns:
  33. A GUID-line string calculated from the name and seed.
  34. This generates something which looks like a GUID, but depends only on the
  35. name and seed. This means the same name/seed will always generate the same
  36. GUID, so that projects and solutions which refer to each other can explicitly
  37. determine the GUID to refer to explicitly. It also means that the GUID will
  38. not change when the project for a target is rebuilt.
  39. """
  40. # Calculate a MD5 signature for the seed and name.
  41. d = _new_md5(str(seed) + str(name)).hexdigest().upper()
  42. # Convert most of the signature to GUID form (discard the rest)
  43. guid = ('{' + d[:8] + '-' + d[8:12] + '-' + d[12:16] + '-' + d[16:20]
  44. + '-' + d[20:32] + '}')
  45. return guid
  46. #------------------------------------------------------------------------------
  47. class MSVSSolutionEntry(object):
  48. def __cmp__(self, other):
  49. # Sort by name then guid (so things are in order on vs2008).
  50. return cmp((self.name, self.get_guid()), (other.name, other.get_guid()))
  51. class MSVSFolder(MSVSSolutionEntry):
  52. """Folder in a Visual Studio project or solution."""
  53. def __init__(self, path, name = None, entries = None,
  54. guid = None, items = None):
  55. """Initializes the folder.
  56. Args:
  57. path: Full path to the folder.
  58. name: Name of the folder.
  59. entries: List of folder entries to nest inside this folder. May contain
  60. Folder or Project objects. May be None, if the folder is empty.
  61. guid: GUID to use for folder, if not None.
  62. items: List of solution items to include in the folder project. May be
  63. None, if the folder does not directly contain items.
  64. """
  65. if name:
  66. self.name = name
  67. else:
  68. # Use last layer.
  69. self.name = os.path.basename(path)
  70. self.path = path
  71. self.guid = guid
  72. # Copy passed lists (or set to empty lists)
  73. self.entries = sorted(list(entries or []))
  74. self.items = list(items or [])
  75. self.entry_type_guid = ENTRY_TYPE_GUIDS['folder']
  76. def get_guid(self):
  77. if self.guid is None:
  78. # Use consistent guids for folders (so things don't regenerate).
  79. self.guid = MakeGuid(self.path, seed='msvs_folder')
  80. return self.guid
  81. #------------------------------------------------------------------------------
  82. class MSVSProject(MSVSSolutionEntry):
  83. """Visual Studio project."""
  84. def __init__(self, path, name = None, dependencies = None, guid = None,
  85. spec = None, build_file = None, config_platform_overrides = None,
  86. fixpath_prefix = None):
  87. """Initializes the project.
  88. Args:
  89. path: Absolute path to the project file.
  90. name: Name of project. If None, the name will be the same as the base
  91. name of the project file.
  92. dependencies: List of other Project objects this project is dependent
  93. upon, if not None.
  94. guid: GUID to use for project, if not None.
  95. spec: Dictionary specifying how to build this project.
  96. build_file: Filename of the .gyp file that the vcproj file comes from.
  97. config_platform_overrides: optional dict of configuration platforms to
  98. used in place of the default for this target.
  99. fixpath_prefix: the path used to adjust the behavior of _fixpath
  100. """
  101. self.path = path
  102. self.guid = guid
  103. self.spec = spec
  104. self.build_file = build_file
  105. # Use project filename if name not specified
  106. self.name = name or os.path.splitext(os.path.basename(path))[0]
  107. # Copy passed lists (or set to empty lists)
  108. self.dependencies = list(dependencies or [])
  109. self.entry_type_guid = ENTRY_TYPE_GUIDS['project']
  110. if config_platform_overrides:
  111. self.config_platform_overrides = config_platform_overrides
  112. else:
  113. self.config_platform_overrides = {}
  114. self.fixpath_prefix = fixpath_prefix
  115. self.msbuild_toolset = None
  116. def set_dependencies(self, dependencies):
  117. self.dependencies = list(dependencies or [])
  118. def get_guid(self):
  119. if self.guid is None:
  120. # Set GUID from path
  121. # TODO(rspangler): This is fragile.
  122. # 1. We can't just use the project filename sans path, since there could
  123. # be multiple projects with the same base name (for example,
  124. # foo/unittest.vcproj and bar/unittest.vcproj).
  125. # 2. The path needs to be relative to $SOURCE_ROOT, so that the project
  126. # GUID is the same whether it's included from base/base.sln or
  127. # foo/bar/baz/baz.sln.
  128. # 3. The GUID needs to be the same each time this builder is invoked, so
  129. # that we don't need to rebuild the solution when the project changes.
  130. # 4. We should be able to handle pre-built project files by reading the
  131. # GUID from the files.
  132. self.guid = MakeGuid(self.name)
  133. return self.guid
  134. def set_msbuild_toolset(self, msbuild_toolset):
  135. self.msbuild_toolset = msbuild_toolset
  136. #------------------------------------------------------------------------------
  137. class MSVSSolution(object):
  138. """Visual Studio solution."""
  139. def __init__(self, path, version, entries=None, variants=None,
  140. websiteProperties=True):
  141. """Initializes the solution.
  142. Args:
  143. path: Path to solution file.
  144. version: Format version to emit.
  145. entries: List of entries in solution. May contain Folder or Project
  146. objects. May be None, if the folder is empty.
  147. variants: List of build variant strings. If none, a default list will
  148. be used.
  149. websiteProperties: Flag to decide if the website properties section
  150. is generated.
  151. """
  152. self.path = path
  153. self.websiteProperties = websiteProperties
  154. self.version = version
  155. # Copy passed lists (or set to empty lists)
  156. self.entries = list(entries or [])
  157. if variants:
  158. # Copy passed list
  159. self.variants = variants[:]
  160. else:
  161. # Use default
  162. self.variants = ['Debug|Win32', 'Release|Win32']
  163. # TODO(rspangler): Need to be able to handle a mapping of solution config
  164. # to project config. Should we be able to handle variants being a dict,
  165. # or add a separate variant_map variable? If it's a dict, we can't
  166. # guarantee the order of variants since dict keys aren't ordered.
  167. # TODO(rspangler): Automatically write to disk for now; should delay until
  168. # node-evaluation time.
  169. self.Write()
  170. def Write(self, writer=gyp.common.WriteOnDiff):
  171. """Writes the solution file to disk.
  172. Raises:
  173. IndexError: An entry appears multiple times.
  174. """
  175. # Walk the entry tree and collect all the folders and projects.
  176. all_entries = set()
  177. entries_to_check = self.entries[:]
  178. while entries_to_check:
  179. e = entries_to_check.pop(0)
  180. # If this entry has been visited, nothing to do.
  181. if e in all_entries:
  182. continue
  183. all_entries.add(e)
  184. # If this is a folder, check its entries too.
  185. if isinstance(e, MSVSFolder):
  186. entries_to_check += e.entries
  187. all_entries = sorted(all_entries)
  188. # Open file and print header
  189. f = writer(self.path)
  190. f.write('Microsoft Visual Studio Solution File, '
  191. 'Format Version %s\r\n' % self.version.SolutionVersion())
  192. f.write('# %s\r\n' % self.version.Description())
  193. # Project entries
  194. sln_root = os.path.split(self.path)[0]
  195. for e in all_entries:
  196. relative_path = gyp.common.RelativePath(e.path, sln_root)
  197. # msbuild does not accept an empty folder_name.
  198. # use '.' in case relative_path is empty.
  199. folder_name = relative_path.replace('/', '\\') or '.'
  200. f.write('Project("%s") = "%s", "%s", "%s"\r\n' % (
  201. e.entry_type_guid, # Entry type GUID
  202. e.name, # Folder name
  203. folder_name, # Folder name (again)
  204. e.get_guid(), # Entry GUID
  205. ))
  206. # TODO(rspangler): Need a way to configure this stuff
  207. if self.websiteProperties:
  208. f.write('\tProjectSection(WebsiteProperties) = preProject\r\n'
  209. '\t\tDebug.AspNetCompiler.Debug = "True"\r\n'
  210. '\t\tRelease.AspNetCompiler.Debug = "False"\r\n'
  211. '\tEndProjectSection\r\n')
  212. if isinstance(e, MSVSFolder):
  213. if e.items:
  214. f.write('\tProjectSection(SolutionItems) = preProject\r\n')
  215. for i in e.items:
  216. f.write('\t\t%s = %s\r\n' % (i, i))
  217. f.write('\tEndProjectSection\r\n')
  218. if isinstance(e, MSVSProject):
  219. if e.dependencies:
  220. f.write('\tProjectSection(ProjectDependencies) = postProject\r\n')
  221. for d in e.dependencies:
  222. f.write('\t\t%s = %s\r\n' % (d.get_guid(), d.get_guid()))
  223. f.write('\tEndProjectSection\r\n')
  224. f.write('EndProject\r\n')
  225. # Global section
  226. f.write('Global\r\n')
  227. # Configurations (variants)
  228. f.write('\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\r\n')
  229. for v in self.variants:
  230. f.write('\t\t%s = %s\r\n' % (v, v))
  231. f.write('\tEndGlobalSection\r\n')
  232. # Sort config guids for easier diffing of solution changes.
  233. config_guids = []
  234. config_guids_overrides = {}
  235. for e in all_entries:
  236. if isinstance(e, MSVSProject):
  237. config_guids.append(e.get_guid())
  238. config_guids_overrides[e.get_guid()] = e.config_platform_overrides
  239. config_guids.sort()
  240. f.write('\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\r\n')
  241. for g in config_guids:
  242. for v in self.variants:
  243. nv = config_guids_overrides[g].get(v, v)
  244. # Pick which project configuration to build for this solution
  245. # configuration.
  246. f.write('\t\t%s.%s.ActiveCfg = %s\r\n' % (
  247. g, # Project GUID
  248. v, # Solution build configuration
  249. nv, # Project build config for that solution config
  250. ))
  251. # Enable project in this solution configuration.
  252. f.write('\t\t%s.%s.Build.0 = %s\r\n' % (
  253. g, # Project GUID
  254. v, # Solution build configuration
  255. nv, # Project build config for that solution config
  256. ))
  257. f.write('\tEndGlobalSection\r\n')
  258. # TODO(rspangler): Should be able to configure this stuff too (though I've
  259. # never seen this be any different)
  260. f.write('\tGlobalSection(SolutionProperties) = preSolution\r\n')
  261. f.write('\t\tHideSolutionNode = FALSE\r\n')
  262. f.write('\tEndGlobalSection\r\n')
  263. # Folder mappings
  264. # Omit this section if there are no folders
  265. if any([e.entries for e in all_entries if isinstance(e, MSVSFolder)]):
  266. f.write('\tGlobalSection(NestedProjects) = preSolution\r\n')
  267. for e in all_entries:
  268. if not isinstance(e, MSVSFolder):
  269. continue # Does not apply to projects, only folders
  270. for subentry in e.entries:
  271. f.write('\t\t%s = %s\r\n' % (subentry.get_guid(), e.get_guid()))
  272. f.write('\tEndGlobalSection\r\n')
  273. f.write('EndGlobal\r\n')
  274. f.close()