ecf3fa7399188ab536166425992116d3b5f3c70be1e80442dd189447cf4c4106455d11f4f9e52b9777a9b8057190998b47208baaa7e7d9733d067ebb7fd656 13 KB

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