msvs.py 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  1. #! /usr/bin/env python
  2. # encoding: utf-8
  3. # Avalanche Studios 2009-2011
  4. # Thomas Nagy 2011
  5. """
  6. Redistribution and use in source and binary forms, with or without
  7. modification, are permitted provided that the following conditions
  8. are met:
  9. 1. Redistributions of source code must retain the above copyright
  10. notice, this list of conditions and the following disclaimer.
  11. 2. Redistributions in binary form must reproduce the above copyright
  12. notice, this list of conditions and the following disclaimer in the
  13. documentation and/or other materials provided with the distribution.
  14. 3. The name of the author may not be used to endorse or promote products
  15. derived from this software without specific prior written permission.
  16. THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
  17. IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
  20. INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  22. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  23. HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  24. STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
  25. IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  26. POSSIBILITY OF SUCH DAMAGE.
  27. """
  28. """
  29. To add this tool to your project:
  30. def options(conf):
  31. opt.load('msvs')
  32. It can be a good idea to add the sync_exec tool too.
  33. To generate solution files:
  34. $ waf configure msvs
  35. To customize the outputs, provide subclasses in your wscript files::
  36. from waflib.extras import msvs
  37. class vsnode_target(msvs.vsnode_target):
  38. def get_build_command(self, props):
  39. # likely to be required
  40. return "waf.bat build"
  41. def collect_source(self):
  42. # likely to be required
  43. ...
  44. class msvs_bar(msvs.msvs_generator):
  45. def init(self):
  46. msvs.msvs_generator.init(self)
  47. self.vsnode_target = vsnode_target
  48. The msvs class re-uses the same build() function for reading the targets (task generators),
  49. you may therefore specify msvs settings on the context object::
  50. def build(bld):
  51. bld.solution_name = 'foo.sln'
  52. bld.waf_command = 'waf.bat'
  53. bld.projects_dir = bld.srcnode.make_node('.depproj')
  54. bld.projects_dir.mkdir()
  55. For visual studio 2008, the command is called 'msvs2008', and the classes
  56. such as vsnode_target are wrapped by a decorator class 'wrap_2008' to
  57. provide special functionality.
  58. To customize platform toolsets, pass additional parameters, for example::
  59. class msvs_2013(msvs.msvs_generator):
  60. cmd = 'msvs2013'
  61. numver = '13.00'
  62. vsver = '2013'
  63. platform_toolset_ver = 'v120'
  64. ASSUMPTIONS:
  65. * a project can be either a directory or a target, vcxproj files are written only for targets that have source files
  66. * each project is a vcxproj file, therefore the project uuid needs only to be a hash of the absolute path
  67. """
  68. import os, re, sys
  69. import uuid # requires python 2.5
  70. from waflib.Build import BuildContext
  71. from waflib import Utils, TaskGen, Logs, Task, Context, Node, Options
  72. HEADERS_GLOB = '**/(*.h|*.hpp|*.H|*.inl)'
  73. PROJECT_TEMPLATE = r'''<?xml version="1.0" encoding="UTF-8"?>
  74. <Project DefaultTargets="Build" ToolsVersion="4.0"
  75. xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  76. <ItemGroup Label="ProjectConfigurations">
  77. ${for b in project.build_properties}
  78. <ProjectConfiguration Include="${b.configuration}|${b.platform}">
  79. <Configuration>${b.configuration}</Configuration>
  80. <Platform>${b.platform}</Platform>
  81. </ProjectConfiguration>
  82. ${endfor}
  83. </ItemGroup>
  84. <PropertyGroup Label="Globals">
  85. <ProjectGuid>{${project.uuid}}</ProjectGuid>
  86. <Keyword>MakeFileProj</Keyword>
  87. <ProjectName>${project.name}</ProjectName>
  88. </PropertyGroup>
  89. <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
  90. ${for b in project.build_properties}
  91. <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='${b.configuration}|${b.platform}'" Label="Configuration">
  92. <ConfigurationType>Makefile</ConfigurationType>
  93. <OutDir>${b.outdir}</OutDir>
  94. <PlatformToolset>${project.platform_toolset_ver}</PlatformToolset>
  95. </PropertyGroup>
  96. ${endfor}
  97. <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
  98. <ImportGroup Label="ExtensionSettings">
  99. </ImportGroup>
  100. ${for b in project.build_properties}
  101. <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='${b.configuration}|${b.platform}'">
  102. <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  103. </ImportGroup>
  104. ${endfor}
  105. ${for b in project.build_properties}
  106. <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='${b.configuration}|${b.platform}'">
  107. <NMakeBuildCommandLine>${xml:project.get_build_command(b)}</NMakeBuildCommandLine>
  108. <NMakeReBuildCommandLine>${xml:project.get_rebuild_command(b)}</NMakeReBuildCommandLine>
  109. <NMakeCleanCommandLine>${xml:project.get_clean_command(b)}</NMakeCleanCommandLine>
  110. <NMakeIncludeSearchPath>${xml:b.includes_search_path}</NMakeIncludeSearchPath>
  111. <NMakePreprocessorDefinitions>${xml:b.preprocessor_definitions};$(NMakePreprocessorDefinitions)</NMakePreprocessorDefinitions>
  112. <IncludePath>${xml:b.includes_search_path}</IncludePath>
  113. <ExecutablePath>$(ExecutablePath)</ExecutablePath>
  114. ${if getattr(b, 'output_file', None)}
  115. <NMakeOutput>${xml:b.output_file}</NMakeOutput>
  116. ${endif}
  117. ${if getattr(b, 'deploy_dir', None)}
  118. <RemoteRoot>${xml:b.deploy_dir}</RemoteRoot>
  119. ${endif}
  120. </PropertyGroup>
  121. ${endfor}
  122. ${for b in project.build_properties}
  123. ${if getattr(b, 'deploy_dir', None)}
  124. <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='${b.configuration}|${b.platform}'">
  125. <Deploy>
  126. <DeploymentType>CopyToHardDrive</DeploymentType>
  127. </Deploy>
  128. </ItemDefinitionGroup>
  129. ${endif}
  130. ${endfor}
  131. <ItemGroup>
  132. ${for x in project.source}
  133. <${project.get_key(x)} Include='${x.win32path()}' />
  134. ${endfor}
  135. </ItemGroup>
  136. <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
  137. <ImportGroup Label="ExtensionTargets">
  138. </ImportGroup>
  139. </Project>
  140. '''
  141. FILTER_TEMPLATE = '''<?xml version="1.0" encoding="UTF-8"?>
  142. <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  143. <ItemGroup>
  144. ${for x in project.source}
  145. <${project.get_key(x)} Include="${x.win32path()}">
  146. <Filter>${project.get_filter_name(x.parent)}</Filter>
  147. </${project.get_key(x)}>
  148. ${endfor}
  149. </ItemGroup>
  150. <ItemGroup>
  151. ${for x in project.dirs()}
  152. <Filter Include="${project.get_filter_name(x)}">
  153. <UniqueIdentifier>{${project.make_uuid(x.win32path())}}</UniqueIdentifier>
  154. </Filter>
  155. ${endfor}
  156. </ItemGroup>
  157. </Project>
  158. '''
  159. PROJECT_2008_TEMPLATE = r'''<?xml version="1.0" encoding="UTF-8"?>
  160. <VisualStudioProject ProjectType="Visual C++" Version="9,00"
  161. Name="${xml: project.name}" ProjectGUID="{${project.uuid}}"
  162. Keyword="MakeFileProj"
  163. TargetFrameworkVersion="196613">
  164. <Platforms>
  165. ${if project.build_properties}
  166. ${for b in project.build_properties}
  167. <Platform Name="${xml: b.platform}" />
  168. ${endfor}
  169. ${else}
  170. <Platform Name="Win32" />
  171. ${endif}
  172. </Platforms>
  173. <ToolFiles>
  174. </ToolFiles>
  175. <Configurations>
  176. ${if project.build_properties}
  177. ${for b in project.build_properties}
  178. <Configuration
  179. Name="${xml: b.configuration}|${xml: b.platform}"
  180. IntermediateDirectory="$ConfigurationName"
  181. OutputDirectory="${xml: b.outdir}"
  182. ConfigurationType="0">
  183. <Tool
  184. Name="VCNMakeTool"
  185. BuildCommandLine="${xml: project.get_build_command(b)}"
  186. ReBuildCommandLine="${xml: project.get_rebuild_command(b)}"
  187. CleanCommandLine="${xml: project.get_clean_command(b)}"
  188. ${if getattr(b, 'output_file', None)}
  189. Output="${xml: b.output_file}"
  190. ${endif}
  191. PreprocessorDefinitions="${xml: b.preprocessor_definitions}"
  192. IncludeSearchPath="${xml: b.includes_search_path}"
  193. ForcedIncludes=""
  194. ForcedUsingAssemblies=""
  195. AssemblySearchPath=""
  196. CompileAsManaged=""
  197. />
  198. </Configuration>
  199. ${endfor}
  200. ${else}
  201. <Configuration Name="Release|Win32" >
  202. </Configuration>
  203. ${endif}
  204. </Configurations>
  205. <References>
  206. </References>
  207. <Files>
  208. ${project.display_filter()}
  209. </Files>
  210. </VisualStudioProject>
  211. '''
  212. SOLUTION_TEMPLATE = '''Microsoft Visual Studio Solution File, Format Version ${project.numver}
  213. # Visual Studio ${project.vsver}
  214. ${for p in project.all_projects}
  215. Project("{${p.ptype()}}") = "${p.name}", "${p.title}", "{${p.uuid}}"
  216. EndProject${endfor}
  217. Global
  218. GlobalSection(SolutionConfigurationPlatforms) = preSolution
  219. ${if project.all_projects}
  220. ${for (configuration, platform) in project.all_projects[0].ctx.project_configurations()}
  221. ${configuration}|${platform} = ${configuration}|${platform}
  222. ${endfor}
  223. ${endif}
  224. EndGlobalSection
  225. GlobalSection(ProjectConfigurationPlatforms) = postSolution
  226. ${for p in project.all_projects}
  227. ${if hasattr(p, 'source')}
  228. ${for b in p.build_properties}
  229. {${p.uuid}}.${b.configuration}|${b.platform}.ActiveCfg = ${b.configuration}|${b.platform}
  230. ${if getattr(p, 'is_active', None)}
  231. {${p.uuid}}.${b.configuration}|${b.platform}.Build.0 = ${b.configuration}|${b.platform}
  232. ${endif}
  233. ${if getattr(p, 'is_deploy', None)}
  234. {${p.uuid}}.${b.configuration}|${b.platform}.Deploy.0 = ${b.configuration}|${b.platform}
  235. ${endif}
  236. ${endfor}
  237. ${endif}
  238. ${endfor}
  239. EndGlobalSection
  240. GlobalSection(SolutionProperties) = preSolution
  241. HideSolutionNode = FALSE
  242. EndGlobalSection
  243. GlobalSection(NestedProjects) = preSolution
  244. ${for p in project.all_projects}
  245. ${if p.parent}
  246. {${p.uuid}} = {${p.parent.uuid}}
  247. ${endif}
  248. ${endfor}
  249. EndGlobalSection
  250. EndGlobal
  251. '''
  252. COMPILE_TEMPLATE = '''def f(project):
  253. lst = []
  254. def xml_escape(value):
  255. return value.replace("&", "&amp;").replace('"', "&quot;").replace("'", "&apos;").replace("<", "&lt;").replace(">", "&gt;")
  256. %s
  257. #f = open('cmd.txt', 'w')
  258. #f.write(str(lst))
  259. #f.close()
  260. return ''.join(lst)
  261. '''
  262. reg_act = re.compile(r"(?P<backslash>\\)|(?P<dollar>\$\$)|(?P<subst>\$\{(?P<code>[^}]*?)\})", re.M)
  263. def compile_template(line):
  264. """
  265. Compile a template expression into a python function (like jsps, but way shorter)
  266. """
  267. extr = []
  268. def repl(match):
  269. g = match.group
  270. if g('dollar'):
  271. return "$"
  272. elif g('backslash'):
  273. return "\\"
  274. elif g('subst'):
  275. extr.append(g('code'))
  276. return "<<|@|>>"
  277. return None
  278. line2 = reg_act.sub(repl, line)
  279. params = line2.split('<<|@|>>')
  280. assert(extr)
  281. indent = 0
  282. buf = []
  283. app = buf.append
  284. def app(txt):
  285. buf.append(indent * '\t' + txt)
  286. for x in range(len(extr)):
  287. if params[x]:
  288. app("lst.append(%r)" % params[x])
  289. f = extr[x]
  290. if f.startswith(('if', 'for')):
  291. app(f + ':')
  292. indent += 1
  293. elif f.startswith('py:'):
  294. app(f[3:])
  295. elif f.startswith(('endif', 'endfor')):
  296. indent -= 1
  297. elif f.startswith(('else', 'elif')):
  298. indent -= 1
  299. app(f + ':')
  300. indent += 1
  301. elif f.startswith('xml:'):
  302. app('lst.append(xml_escape(%s))' % f[4:])
  303. else:
  304. #app('lst.append((%s) or "cannot find %s")' % (f, f))
  305. app('lst.append(%s)' % f)
  306. if extr:
  307. if params[-1]:
  308. app("lst.append(%r)" % params[-1])
  309. fun = COMPILE_TEMPLATE % "\n\t".join(buf)
  310. #print(fun)
  311. return Task.funex(fun)
  312. re_blank = re.compile('(\n|\r|\\s)*\n', re.M)
  313. def rm_blank_lines(txt):
  314. txt = re_blank.sub('\r\n', txt)
  315. return txt
  316. BOM = '\xef\xbb\xbf'
  317. try:
  318. BOM = bytes(BOM, 'latin-1') # python 3
  319. except TypeError:
  320. pass
  321. def stealth_write(self, data, flags='wb'):
  322. try:
  323. unicode
  324. except NameError:
  325. data = data.encode('utf-8') # python 3
  326. else:
  327. data = data.decode(sys.getfilesystemencoding(), 'replace')
  328. data = data.encode('utf-8')
  329. if self.name.endswith(('.vcproj', '.vcxproj')):
  330. data = BOM + data
  331. try:
  332. txt = self.read(flags='rb')
  333. if txt != data:
  334. raise ValueError('must write')
  335. except (IOError, ValueError):
  336. self.write(data, flags=flags)
  337. else:
  338. Logs.debug('msvs: skipping %s', self.win32path())
  339. Node.Node.stealth_write = stealth_write
  340. re_win32 = re.compile(r'^([/\\]cygdrive)?[/\\]([a-z])([^a-z0-9_-].*)', re.I)
  341. def win32path(self):
  342. p = self.abspath()
  343. m = re_win32.match(p)
  344. if m:
  345. return "%s:%s" % (m.group(2).upper(), m.group(3))
  346. return p
  347. Node.Node.win32path = win32path
  348. re_quote = re.compile("[^a-zA-Z0-9-]")
  349. def quote(s):
  350. return re_quote.sub("_", s)
  351. def xml_escape(value):
  352. return value.replace("&", "&amp;").replace('"', "&quot;").replace("'", "&apos;").replace("<", "&lt;").replace(">", "&gt;")
  353. def make_uuid(v, prefix = None):
  354. """
  355. simple utility function
  356. """
  357. if isinstance(v, dict):
  358. keys = list(v.keys())
  359. keys.sort()
  360. tmp = str([(k, v[k]) for k in keys])
  361. else:
  362. tmp = str(v)
  363. d = Utils.md5(tmp.encode()).hexdigest().upper()
  364. if prefix:
  365. d = '%s%s' % (prefix, d[8:])
  366. gid = uuid.UUID(d, version = 4)
  367. return str(gid).upper()
  368. def diff(node, fromnode):
  369. # difference between two nodes, but with "(..)" instead of ".."
  370. c1 = node
  371. c2 = fromnode
  372. c1h = c1.height()
  373. c2h = c2.height()
  374. lst = []
  375. up = 0
  376. while c1h > c2h:
  377. lst.append(c1.name)
  378. c1 = c1.parent
  379. c1h -= 1
  380. while c2h > c1h:
  381. up += 1
  382. c2 = c2.parent
  383. c2h -= 1
  384. while id(c1) != id(c2):
  385. lst.append(c1.name)
  386. up += 1
  387. c1 = c1.parent
  388. c2 = c2.parent
  389. for i in range(up):
  390. lst.append('(..)')
  391. lst.reverse()
  392. return tuple(lst)
  393. class build_property(object):
  394. pass
  395. class vsnode(object):
  396. """
  397. Abstract class representing visual studio elements
  398. We assume that all visual studio nodes have a uuid and a parent
  399. """
  400. def __init__(self, ctx):
  401. self.ctx = ctx # msvs context
  402. self.name = '' # string, mandatory
  403. self.vspath = '' # path in visual studio (name for dirs, absolute path for projects)
  404. self.uuid = '' # string, mandatory
  405. self.parent = None # parent node for visual studio nesting
  406. def get_waf(self):
  407. """
  408. Override in subclasses...
  409. """
  410. return 'cd /d "%s" & %s' % (self.ctx.srcnode.win32path(), getattr(self.ctx, 'waf_command', 'waf.bat'))
  411. def ptype(self):
  412. """
  413. Return a special uuid for projects written in the solution file
  414. """
  415. pass
  416. def write(self):
  417. """
  418. Write the project file, by default, do nothing
  419. """
  420. pass
  421. def make_uuid(self, val):
  422. """
  423. Alias for creating uuid values easily (the templates cannot access global variables)
  424. """
  425. return make_uuid(val)
  426. class vsnode_vsdir(vsnode):
  427. """
  428. Nodes representing visual studio folders (which do not match the filesystem tree!)
  429. """
  430. VS_GUID_SOLUTIONFOLDER = "2150E333-8FDC-42A3-9474-1A3956D46DE8"
  431. def __init__(self, ctx, uuid, name, vspath=''):
  432. vsnode.__init__(self, ctx)
  433. self.title = self.name = name
  434. self.uuid = uuid
  435. self.vspath = vspath or name
  436. def ptype(self):
  437. return self.VS_GUID_SOLUTIONFOLDER
  438. class vsnode_project(vsnode):
  439. """
  440. Abstract class representing visual studio project elements
  441. A project is assumed to be writable, and has a node representing the file to write to
  442. """
  443. VS_GUID_VCPROJ = "8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942"
  444. def ptype(self):
  445. return self.VS_GUID_VCPROJ
  446. def __init__(self, ctx, node):
  447. vsnode.__init__(self, ctx)
  448. self.path = node
  449. self.uuid = make_uuid(node.win32path())
  450. self.name = node.name
  451. self.platform_toolset_ver = getattr(ctx, 'platform_toolset_ver', None)
  452. self.title = self.path.win32path()
  453. self.source = [] # list of node objects
  454. self.build_properties = [] # list of properties (nmake commands, output dir, etc)
  455. def dirs(self):
  456. """
  457. Get the list of parent folders of the source files (header files included)
  458. for writing the filters
  459. """
  460. lst = []
  461. def add(x):
  462. if x.height() > self.tg.path.height() and x not in lst:
  463. lst.append(x)
  464. add(x.parent)
  465. for x in self.source:
  466. add(x.parent)
  467. return lst
  468. def write(self):
  469. Logs.debug('msvs: creating %r', self.path)
  470. # first write the project file
  471. template1 = compile_template(PROJECT_TEMPLATE)
  472. proj_str = template1(self)
  473. proj_str = rm_blank_lines(proj_str)
  474. self.path.stealth_write(proj_str)
  475. # then write the filter
  476. template2 = compile_template(FILTER_TEMPLATE)
  477. filter_str = template2(self)
  478. filter_str = rm_blank_lines(filter_str)
  479. tmp = self.path.parent.make_node(self.path.name + '.filters')
  480. tmp.stealth_write(filter_str)
  481. def get_key(self, node):
  482. """
  483. required for writing the source files
  484. """
  485. name = node.name
  486. if name.endswith(('.cpp', '.c')):
  487. return 'ClCompile'
  488. return 'ClInclude'
  489. def collect_properties(self):
  490. """
  491. Returns a list of triplet (configuration, platform, output_directory)
  492. """
  493. ret = []
  494. for c in self.ctx.configurations:
  495. for p in self.ctx.platforms:
  496. x = build_property()
  497. x.outdir = ''
  498. x.configuration = c
  499. x.platform = p
  500. x.preprocessor_definitions = ''
  501. x.includes_search_path = ''
  502. # can specify "deploy_dir" too
  503. ret.append(x)
  504. self.build_properties = ret
  505. def get_build_params(self, props):
  506. opt = '--execsolution=%s' % self.ctx.get_solution_node().win32path()
  507. return (self.get_waf(), opt)
  508. def get_build_command(self, props):
  509. return "%s build %s" % self.get_build_params(props)
  510. def get_clean_command(self, props):
  511. return "%s clean %s" % self.get_build_params(props)
  512. def get_rebuild_command(self, props):
  513. return "%s clean build %s" % self.get_build_params(props)
  514. def get_filter_name(self, node):
  515. lst = diff(node, self.tg.path)
  516. return '\\'.join(lst) or '.'
  517. class vsnode_alias(vsnode_project):
  518. def __init__(self, ctx, node, name):
  519. vsnode_project.__init__(self, ctx, node)
  520. self.name = name
  521. self.output_file = ''
  522. class vsnode_build_all(vsnode_alias):
  523. """
  524. Fake target used to emulate the behaviour of "make all" (starting one process by target is slow)
  525. This is the only alias enabled by default
  526. """
  527. def __init__(self, ctx, node, name='build_all_projects'):
  528. vsnode_alias.__init__(self, ctx, node, name)
  529. self.is_active = True
  530. class vsnode_install_all(vsnode_alias):
  531. """
  532. Fake target used to emulate the behaviour of "make install"
  533. """
  534. def __init__(self, ctx, node, name='install_all_projects'):
  535. vsnode_alias.__init__(self, ctx, node, name)
  536. def get_build_command(self, props):
  537. return "%s build install %s" % self.get_build_params(props)
  538. def get_clean_command(self, props):
  539. return "%s clean %s" % self.get_build_params(props)
  540. def get_rebuild_command(self, props):
  541. return "%s clean build install %s" % self.get_build_params(props)
  542. class vsnode_project_view(vsnode_alias):
  543. """
  544. Fake target used to emulate a file system view
  545. """
  546. def __init__(self, ctx, node, name='project_view'):
  547. vsnode_alias.__init__(self, ctx, node, name)
  548. self.tg = self.ctx() # fake one, cannot remove
  549. self.exclude_files = Node.exclude_regs + '''
  550. waf-2*
  551. waf3-2*/**
  552. .waf-2*
  553. .waf3-2*/**
  554. **/*.sdf
  555. **/*.suo
  556. **/*.ncb
  557. **/%s
  558. ''' % Options.lockfile
  559. def collect_source(self):
  560. # this is likely to be slow
  561. self.source = self.ctx.srcnode.ant_glob('**', excl=self.exclude_files)
  562. def get_build_command(self, props):
  563. params = self.get_build_params(props) + (self.ctx.cmd,)
  564. return "%s %s %s" % params
  565. def get_clean_command(self, props):
  566. return ""
  567. def get_rebuild_command(self, props):
  568. return self.get_build_command(props)
  569. class vsnode_target(vsnode_project):
  570. """
  571. Visual studio project representing a targets (programs, libraries, etc) and bound
  572. to a task generator
  573. """
  574. def __init__(self, ctx, tg):
  575. """
  576. A project is more or less equivalent to a file/folder
  577. """
  578. base = getattr(ctx, 'projects_dir', None) or tg.path
  579. node = base.make_node(quote(tg.name) + ctx.project_extension) # the project file as a Node
  580. vsnode_project.__init__(self, ctx, node)
  581. self.name = quote(tg.name)
  582. self.tg = tg # task generator
  583. def get_build_params(self, props):
  584. """
  585. Override the default to add the target name
  586. """
  587. opt = '--execsolution=%s' % self.ctx.get_solution_node().win32path()
  588. if getattr(self, 'tg', None):
  589. opt += " --targets=%s" % self.tg.name
  590. return (self.get_waf(), opt)
  591. def collect_source(self):
  592. tg = self.tg
  593. source_files = tg.to_nodes(getattr(tg, 'source', []))
  594. include_dirs = Utils.to_list(getattr(tg, 'msvs_includes', []))
  595. include_files = []
  596. for x in include_dirs:
  597. if isinstance(x, str):
  598. x = tg.path.find_node(x)
  599. if x:
  600. lst = [y for y in x.ant_glob(HEADERS_GLOB, flat=False)]
  601. include_files.extend(lst)
  602. # remove duplicates
  603. self.source.extend(list(set(source_files + include_files)))
  604. self.source.sort(key=lambda x: x.win32path())
  605. def collect_properties(self):
  606. """
  607. Visual studio projects are associated with platforms and configurations (for building especially)
  608. """
  609. super(vsnode_target, self).collect_properties()
  610. for x in self.build_properties:
  611. x.outdir = self.path.parent.win32path()
  612. x.preprocessor_definitions = ''
  613. x.includes_search_path = ''
  614. try:
  615. tsk = self.tg.link_task
  616. except AttributeError:
  617. pass
  618. else:
  619. x.output_file = tsk.outputs[0].win32path()
  620. x.preprocessor_definitions = ';'.join(tsk.env.DEFINES)
  621. x.includes_search_path = ';'.join(self.tg.env.INCPATHS)
  622. class msvs_generator(BuildContext):
  623. '''generates a visual studio 2010 solution'''
  624. cmd = 'msvs'
  625. fun = 'build'
  626. numver = '11.00' # Visual Studio Version Number
  627. vsver = '2010' # Visual Studio Version Year
  628. platform_toolset_ver = 'v110' # Platform Toolset Version Number
  629. def init(self):
  630. """
  631. Some data that needs to be present
  632. """
  633. if not getattr(self, 'configurations', None):
  634. self.configurations = ['Release'] # LocalRelease, RemoteDebug, etc
  635. if not getattr(self, 'platforms', None):
  636. self.platforms = ['Win32']
  637. if not getattr(self, 'all_projects', None):
  638. self.all_projects = []
  639. if not getattr(self, 'project_extension', None):
  640. self.project_extension = '.vcxproj'
  641. if not getattr(self, 'projects_dir', None):
  642. self.projects_dir = self.srcnode.make_node('.depproj')
  643. self.projects_dir.mkdir()
  644. # bind the classes to the object, so that subclass can provide custom generators
  645. if not getattr(self, 'vsnode_vsdir', None):
  646. self.vsnode_vsdir = vsnode_vsdir
  647. if not getattr(self, 'vsnode_target', None):
  648. self.vsnode_target = vsnode_target
  649. if not getattr(self, 'vsnode_build_all', None):
  650. self.vsnode_build_all = vsnode_build_all
  651. if not getattr(self, 'vsnode_install_all', None):
  652. self.vsnode_install_all = vsnode_install_all
  653. if not getattr(self, 'vsnode_project_view', None):
  654. self.vsnode_project_view = vsnode_project_view
  655. self.numver = self.__class__.numver
  656. self.vsver = self.__class__.vsver
  657. self.platform_toolset_ver = self.__class__.platform_toolset_ver
  658. def execute(self):
  659. """
  660. Entry point
  661. """
  662. self.restore()
  663. if not self.all_envs:
  664. self.load_envs()
  665. self.recurse([self.run_dir])
  666. # user initialization
  667. self.init()
  668. # two phases for creating the solution
  669. self.collect_projects() # add project objects into "self.all_projects"
  670. self.write_files() # write the corresponding project and solution files
  671. def collect_projects(self):
  672. """
  673. Fill the list self.all_projects with project objects
  674. Fill the list of build targets
  675. """
  676. self.collect_targets()
  677. self.add_aliases()
  678. self.collect_dirs()
  679. default_project = getattr(self, 'default_project', None)
  680. def sortfun(x):
  681. if x.name == default_project:
  682. return ''
  683. return getattr(x, 'path', None) and x.path.win32path() or x.name
  684. self.all_projects.sort(key=sortfun)
  685. def write_files(self):
  686. """
  687. Write the project and solution files from the data collected
  688. so far. It is unlikely that you will want to change this
  689. """
  690. for p in self.all_projects:
  691. p.write()
  692. # and finally write the solution file
  693. node = self.get_solution_node()
  694. node.parent.mkdir()
  695. Logs.warn('Creating %r', node)
  696. template1 = compile_template(SOLUTION_TEMPLATE)
  697. sln_str = template1(self)
  698. sln_str = rm_blank_lines(sln_str)
  699. node.stealth_write(sln_str)
  700. def get_solution_node(self):
  701. """
  702. The solution filename is required when writing the .vcproj files
  703. return self.solution_node and if it does not exist, make one
  704. """
  705. try:
  706. return self.solution_node
  707. except AttributeError:
  708. pass
  709. solution_name = getattr(self, 'solution_name', None)
  710. if not solution_name:
  711. solution_name = getattr(Context.g_module, Context.APPNAME, 'project') + '.sln'
  712. if os.path.isabs(solution_name):
  713. self.solution_node = self.root.make_node(solution_name)
  714. else:
  715. self.solution_node = self.srcnode.make_node(solution_name)
  716. return self.solution_node
  717. def project_configurations(self):
  718. """
  719. Helper that returns all the pairs (config,platform)
  720. """
  721. ret = []
  722. for c in self.configurations:
  723. for p in self.platforms:
  724. ret.append((c, p))
  725. return ret
  726. def collect_targets(self):
  727. """
  728. Process the list of task generators
  729. """
  730. for g in self.groups:
  731. for tg in g:
  732. if not isinstance(tg, TaskGen.task_gen):
  733. continue
  734. if not hasattr(tg, 'msvs_includes'):
  735. tg.msvs_includes = tg.to_list(getattr(tg, 'includes', [])) + tg.to_list(getattr(tg, 'export_includes', []))
  736. tg.post()
  737. if not getattr(tg, 'link_task', None):
  738. continue
  739. p = self.vsnode_target(self, tg)
  740. p.collect_source() # delegate this processing
  741. p.collect_properties()
  742. self.all_projects.append(p)
  743. def add_aliases(self):
  744. """
  745. Add a specific target that emulates the "make all" necessary for Visual studio when pressing F7
  746. We also add an alias for "make install" (disabled by default)
  747. """
  748. base = getattr(self, 'projects_dir', None) or self.tg.path
  749. node_project = base.make_node('build_all_projects' + self.project_extension) # Node
  750. p_build = self.vsnode_build_all(self, node_project)
  751. p_build.collect_properties()
  752. self.all_projects.append(p_build)
  753. node_project = base.make_node('install_all_projects' + self.project_extension) # Node
  754. p_install = self.vsnode_install_all(self, node_project)
  755. p_install.collect_properties()
  756. self.all_projects.append(p_install)
  757. node_project = base.make_node('project_view' + self.project_extension) # Node
  758. p_view = self.vsnode_project_view(self, node_project)
  759. p_view.collect_source()
  760. p_view.collect_properties()
  761. self.all_projects.append(p_view)
  762. n = self.vsnode_vsdir(self, make_uuid(self.srcnode.win32path() + 'build_aliases'), "build_aliases")
  763. p_build.parent = p_install.parent = p_view.parent = n
  764. self.all_projects.append(n)
  765. def collect_dirs(self):
  766. """
  767. Create the folder structure in the Visual studio project view
  768. """
  769. seen = {}
  770. def make_parents(proj):
  771. # look at a project, try to make a parent
  772. if getattr(proj, 'parent', None):
  773. # aliases already have parents
  774. return
  775. x = proj.iter_path
  776. if x in seen:
  777. proj.parent = seen[x]
  778. return
  779. # There is not vsnode_vsdir for x.
  780. # So create a project representing the folder "x"
  781. n = proj.parent = seen[x] = self.vsnode_vsdir(self, make_uuid(x.win32path()), x.name)
  782. n.iter_path = x.parent
  783. self.all_projects.append(n)
  784. # recurse up to the project directory
  785. if x.height() > self.srcnode.height() + 1:
  786. make_parents(n)
  787. for p in self.all_projects[:]: # iterate over a copy of all projects
  788. if not getattr(p, 'tg', None):
  789. # but only projects that have a task generator
  790. continue
  791. # make a folder for each task generator
  792. p.iter_path = p.tg.path
  793. make_parents(p)
  794. def wrap_2008(cls):
  795. class dec(cls):
  796. def __init__(self, *k, **kw):
  797. cls.__init__(self, *k, **kw)
  798. self.project_template = PROJECT_2008_TEMPLATE
  799. def display_filter(self):
  800. root = build_property()
  801. root.subfilters = []
  802. root.sourcefiles = []
  803. root.source = []
  804. root.name = ''
  805. @Utils.run_once
  806. def add_path(lst):
  807. if not lst:
  808. return root
  809. child = build_property()
  810. child.subfilters = []
  811. child.sourcefiles = []
  812. child.source = []
  813. child.name = lst[-1]
  814. par = add_path(lst[:-1])
  815. par.subfilters.append(child)
  816. return child
  817. for x in self.source:
  818. # this crap is for enabling subclasses to override get_filter_name
  819. tmp = self.get_filter_name(x.parent)
  820. tmp = tmp != '.' and tuple(tmp.split('\\')) or ()
  821. par = add_path(tmp)
  822. par.source.append(x)
  823. def display(n):
  824. buf = []
  825. for x in n.source:
  826. buf.append('<File RelativePath="%s" FileType="%s"/>\n' % (xml_escape(x.win32path()), self.get_key(x)))
  827. for x in n.subfilters:
  828. buf.append('<Filter Name="%s">' % xml_escape(x.name))
  829. buf.append(display(x))
  830. buf.append('</Filter>')
  831. return '\n'.join(buf)
  832. return display(root)
  833. def get_key(self, node):
  834. """
  835. If you do not want to let visual studio use the default file extensions,
  836. override this method to return a value:
  837. 0: C/C++ Code, 1: C++ Class, 2: C++ Header File, 3: C++ Form,
  838. 4: C++ Control, 5: Text File, 6: DEF File, 7: IDL File,
  839. 8: Makefile, 9: RGS File, 10: RC File, 11: RES File, 12: XSD File,
  840. 13: XML File, 14: HTML File, 15: CSS File, 16: Bitmap, 17: Icon,
  841. 18: Resx File, 19: BSC File, 20: XSX File, 21: C++ Web Service,
  842. 22: ASAX File, 23: Asp Page, 24: Document, 25: Discovery File,
  843. 26: C# File, 27: eFileTypeClassDiagram, 28: MHTML Document,
  844. 29: Property Sheet, 30: Cursor, 31: Manifest, 32: eFileTypeRDLC
  845. """
  846. return ''
  847. def write(self):
  848. Logs.debug('msvs: creating %r', self.path)
  849. template1 = compile_template(self.project_template)
  850. proj_str = template1(self)
  851. proj_str = rm_blank_lines(proj_str)
  852. self.path.stealth_write(proj_str)
  853. return dec
  854. class msvs_2008_generator(msvs_generator):
  855. '''generates a visual studio 2008 solution'''
  856. cmd = 'msvs2008'
  857. fun = msvs_generator.fun
  858. numver = '10.00'
  859. vsver = '2008'
  860. def init(self):
  861. if not getattr(self, 'project_extension', None):
  862. self.project_extension = '_2008.vcproj'
  863. if not getattr(self, 'solution_name', None):
  864. self.solution_name = getattr(Context.g_module, Context.APPNAME, 'project') + '_2008.sln'
  865. if not getattr(self, 'vsnode_target', None):
  866. self.vsnode_target = wrap_2008(vsnode_target)
  867. if not getattr(self, 'vsnode_build_all', None):
  868. self.vsnode_build_all = wrap_2008(vsnode_build_all)
  869. if not getattr(self, 'vsnode_install_all', None):
  870. self.vsnode_install_all = wrap_2008(vsnode_install_all)
  871. if not getattr(self, 'vsnode_project_view', None):
  872. self.vsnode_project_view = wrap_2008(vsnode_project_view)
  873. msvs_generator.init(self)
  874. def options(ctx):
  875. """
  876. If the msvs option is used, try to detect if the build is made from visual studio
  877. """
  878. ctx.add_option('--execsolution', action='store', help='when building with visual studio, use a build state file')
  879. old = BuildContext.execute
  880. def override_build_state(ctx):
  881. def lock(rm, add):
  882. uns = ctx.options.execsolution.replace('.sln', rm)
  883. uns = ctx.root.make_node(uns)
  884. try:
  885. uns.delete()
  886. except OSError:
  887. pass
  888. uns = ctx.options.execsolution.replace('.sln', add)
  889. uns = ctx.root.make_node(uns)
  890. try:
  891. uns.write('')
  892. except EnvironmentError:
  893. pass
  894. if ctx.options.execsolution:
  895. ctx.launch_dir = Context.top_dir # force a build for the whole project (invalid cwd when called by visual studio)
  896. lock('.lastbuildstate', '.unsuccessfulbuild')
  897. old(ctx)
  898. lock('.unsuccessfulbuild', '.lastbuildstate')
  899. else:
  900. old(ctx)
  901. BuildContext.execute = override_build_state