jack2 codebase
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1026 lines
30KB

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