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.

882 lines
33KB

  1. #! /usr/bin/env python
  2. # encoding: utf-8
  3. # CodeLite Project
  4. # Christian Klein (chrikle@berlios.de)
  5. # Created: Jan 2012
  6. # As templete for this file I used the msvs.py
  7. # I hope this template will work proper
  8. """
  9. Redistribution and use in source and binary forms, with or without
  10. modification, are permitted provided that the following conditions
  11. are met:
  12. 1. Redistributions of source code must retain the above copyright
  13. notice, this list of conditions and the following disclaimer.
  14. 2. Redistributions in binary form must reproduce the above copyright
  15. notice, this list of conditions and the following disclaimer in the
  16. documentation and/or other materials provided with the distribution.
  17. 3. The name of the author may not be used to endorse or promote products
  18. derived from this software without specific prior written permission.
  19. THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
  20. IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  21. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  22. DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
  23. INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  24. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  25. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  26. HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  27. STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
  28. IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  29. POSSIBILITY OF SUCH DAMAGE.
  30. """
  31. """
  32. To add this tool to your project:
  33. def options(conf):
  34. opt.load('codelite')
  35. It can be a good idea to add the sync_exec tool too.
  36. To generate solution files:
  37. $ waf configure codelite
  38. To customize the outputs, provide subclasses in your wscript files:
  39. from waflib.extras import codelite
  40. class vsnode_target(codelite.vsnode_target):
  41. def get_build_command(self, props):
  42. # likely to be required
  43. return "waf.bat build"
  44. def collect_source(self):
  45. # likely to be required
  46. ...
  47. class codelite_bar(codelite.codelite_generator):
  48. def init(self):
  49. codelite.codelite_generator.init(self)
  50. self.vsnode_target = vsnode_target
  51. The codelite class re-uses the same build() function for reading the targets (task generators),
  52. you may therefore specify codelite settings on the context object:
  53. def build(bld):
  54. bld.codelite_solution_name = 'foo.workspace'
  55. bld.waf_command = 'waf.bat'
  56. bld.projects_dir = bld.srcnode.make_node('')
  57. bld.projects_dir.mkdir()
  58. ASSUMPTIONS:
  59. * a project can be either a directory or a target, project 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. <CodeLite_Project Name="${project.name}" InternalType="Library">
  69. <Plugins>
  70. <Plugin Name="qmake">
  71. <![CDATA[00010001N0005Release000000000000]]>
  72. </Plugin>
  73. </Plugins>
  74. <Description/>
  75. <Dependencies/>
  76. <VirtualDirectory Name="src">
  77. ${for x in project.source}
  78. ${if (project.get_key(x)=="sourcefile")}
  79. <File Name="${x.abspath()}"/>
  80. ${endif}
  81. ${endfor}
  82. </VirtualDirectory>
  83. <VirtualDirectory Name="include">
  84. ${for x in project.source}
  85. ${if (project.get_key(x)=="headerfile")}
  86. <File Name="${x.abspath()}"/>
  87. ${endif}
  88. ${endfor}
  89. </VirtualDirectory>
  90. <Settings Type="Dynamic Library">
  91. <GlobalSettings>
  92. <Compiler Options="" C_Options="">
  93. <IncludePath Value="."/>
  94. </Compiler>
  95. <Linker Options="">
  96. <LibraryPath Value="."/>
  97. </Linker>
  98. <ResourceCompiler Options=""/>
  99. </GlobalSettings>
  100. <Configuration Name="Release" CompilerType="gnu gcc" ReleasegerType="GNU gdb Releaseger" Type="Dynamic Library" BuildCmpWithGlobalSettings="append" BuildLnkWithGlobalSettings="append" BuildResWithGlobalSettings="append">
  101. <Compiler Options="" C_Options="" Required="yes" PreCompiledHeader="" PCHInCommandLine="no" UseDifferentPCHFlags="no" PCHFlags="">
  102. <IncludePath Value="."/>
  103. <IncludePath Value="."/>
  104. </Compiler>
  105. <Linker Options="" Required="yes">
  106. <LibraryPath Value=""/>
  107. </Linker>
  108. <ResourceCompiler Options="" Required="no"/>
  109. <General OutputFile="${xml:project.build_properties[0].output_file}" IntermediateDirectory="" Command="" CommandArguments="" PauseExecWhenProcTerminates="yes"/>
  110. <Environment EnvVarSetName="&lt;Use Defaults&gt;" DbgSetName="&lt;Use Defaults&gt;">
  111. <![CDATA[]]>
  112. </Environment>
  113. <Releaseger IsRemote="no" RemoteHostName="" RemoteHostPort="" ReleasegerPath="">
  114. <PostConnectCommands/>
  115. <StartupCommands/>
  116. </Releaseger>
  117. <PreBuild/>
  118. <PostBuild/>
  119. <CustomBuild Enabled="yes">
  120. $b = project.build_properties[0]}
  121. <RebuildCommand>${xml:project.get_rebuild_command(project.build_properties[0])}</RebuildCommand>
  122. <CleanCommand>${xml:project.get_clean_command(project.build_properties[0])}</CleanCommand>
  123. <BuildCommand>${xml:project.get_build_command(project.build_properties[0])}</BuildCommand>
  124. <Target Name="Install">${xml:project.get_install_command(project.build_properties[0])}</Target>
  125. <Target Name="Build and Install">${xml:project.get_build_and_install_command(project.build_properties[0])}</Target>
  126. <Target Name="Build All">${xml:project.get_build_all_command(project.build_properties[0])}</Target>
  127. <Target Name="Rebuild All">${xml:project.get_rebuild_all_command(project.build_properties[0])}</Target>
  128. <Target Name="Clean All">${xml:project.get_clean_all_command(project.build_properties[0])}</Target>
  129. <Target Name="Build and Install All">${xml:project.get_build_and_install_all_command(project.build_properties[0])}</Target>
  130. <PreprocessFileCommand/>
  131. <SingleFileCommand/>
  132. <MakefileGenerationCommand/>
  133. <ThirdPartyToolName>None</ThirdPartyToolName>
  134. <WorkingDirectory/>
  135. </CustomBuild>
  136. <AdditionalRules>
  137. <CustomPostBuild/>
  138. <CustomPreBuild/>
  139. </AdditionalRules>
  140. <Completion>
  141. <ClangCmpFlags/>
  142. <ClangPP/>
  143. <SearchPaths/>
  144. </Completion>
  145. </Configuration>
  146. <Configuration Name="Release" CompilerType="gnu gcc" ReleasegerType="GNU gdb Releaseger" Type="" BuildCmpWithGlobalSettings="append" BuildLnkWithGlobalSettings="append" BuildResWithGlobalSettings="append">
  147. <Compiler Options="" C_Options="" Required="yes" PreCompiledHeader="" PCHInCommandLine="no" UseDifferentPCHFlags="no" PCHFlags="">
  148. <IncludePath Value="."/>
  149. </Compiler>
  150. <Linker Options="" Required="yes"/>
  151. <ResourceCompiler Options="" Required="no"/>
  152. <General OutputFile="" IntermediateDirectory="./Release" Command="" CommandArguments="" UseSeparateReleaseArgs="no" ReleaseArguments="" WorkingDirectory="$(IntermediateDirectory)" PauseExecWhenProcTerminates="yes"/>
  153. <Environment EnvVarSetName="&lt;Use Defaults&gt;" DbgSetName="&lt;Use Defaults&gt;">
  154. <![CDATA[
  155. ]]>
  156. </Environment>
  157. <Releaseger IsRemote="no" RemoteHostName="" RemoteHostPort="" ReleasegerPath="">
  158. <PostConnectCommands/>
  159. <StartupCommands/>
  160. </Releaseger>
  161. <PreBuild/>
  162. <PostBuild/>
  163. <CustomBuild Enabled="no">
  164. <RebuildCommand/>
  165. <CleanCommand/>
  166. <BuildCommand/>
  167. <PreprocessFileCommand/>
  168. <SingleFileCommand/>
  169. <MakefileGenerationCommand/>
  170. <ThirdPartyToolName/>
  171. <WorkingDirectory/>
  172. </CustomBuild>
  173. <AdditionalRules>
  174. <CustomPostBuild/>
  175. <CustomPreBuild/>
  176. </AdditionalRules>
  177. <Completion>
  178. <ClangCmpFlags/>
  179. <ClangPP/>
  180. <SearchPaths/>
  181. </Completion>
  182. </Configuration>
  183. </Settings>
  184. </CodeLite_Project>'''
  185. SOLUTION_TEMPLATE = '''<?xml version="1.0" encoding="utf-8"?>
  186. <CodeLite_Workspace Name="${getattr(project, 'codelite_solution_name', None)[:-10]}" Database="./${getattr(project, 'codelite_solution_name', None)[:-10]}.tags">
  187. ${for p in project.all_projects}
  188. <Project Name = "${p.name}" Path = "${p.title}" Active="No"/>
  189. ${endfor}
  190. <BuildMatrix>
  191. <WorkspaceConfiguration Name="Release" Selected="yes">
  192. ${for p in project.all_projects}
  193. <Project Name="${p.name}" ConfigName="Release"/>
  194. ${endfor}
  195. </WorkspaceConfiguration>
  196. </BuildMatrix>
  197. </CodeLite_Workspace>'''
  198. COMPILE_TEMPLATE = '''def f(project):
  199. lst = []
  200. def xml_escape(value):
  201. return value.replace("&", "&amp;").replace('"', "&quot;").replace("'", "&apos;").replace("<", "&lt;").replace(">", "&gt;")
  202. %s
  203. #f = open('cmd.txt', 'w')
  204. #f.write(str(lst))
  205. #f.close()
  206. return ''.join(lst)
  207. '''
  208. reg_act = re.compile(r"(?P<backslash>\\)|(?P<dollar>\$\$)|(?P<subst>\$\{(?P<code>[^}]*?)\})", re.M)
  209. def compile_template(line):
  210. """
  211. Compile a template expression into a python function (like jsps, but way shorter)
  212. """
  213. extr = []
  214. def repl(match):
  215. g = match.group
  216. if g('dollar'): return "$"
  217. elif g('backslash'):
  218. return "\\"
  219. elif g('subst'):
  220. extr.append(g('code'))
  221. return "<<|@|>>"
  222. return None
  223. line2 = reg_act.sub(repl, line)
  224. params = line2.split('<<|@|>>')
  225. assert(extr)
  226. indent = 0
  227. buf = []
  228. app = buf.append
  229. def app(txt):
  230. buf.append(indent * '\t' + txt)
  231. for x in range(len(extr)):
  232. if params[x]:
  233. app("lst.append(%r)" % params[x])
  234. f = extr[x]
  235. if f.startswith('if') or f.startswith('for'):
  236. app(f + ':')
  237. indent += 1
  238. elif f.startswith('py:'):
  239. app(f[3:])
  240. elif f.startswith('endif') or f.startswith('endfor'):
  241. indent -= 1
  242. elif f.startswith('else') or f.startswith('elif'):
  243. indent -= 1
  244. app(f + ':')
  245. indent += 1
  246. elif f.startswith('xml:'):
  247. app('lst.append(xml_escape(%s))' % f[4:])
  248. else:
  249. #app('lst.append((%s) or "cannot find %s")' % (f, f))
  250. app('lst.append(%s)' % f)
  251. if extr:
  252. if params[-1]:
  253. app("lst.append(%r)" % params[-1])
  254. fun = COMPILE_TEMPLATE % "\n\t".join(buf)
  255. #print(fun)
  256. return Task.funex(fun)
  257. re_blank = re.compile('(\n|\r|\\s)*\n', re.M)
  258. def rm_blank_lines(txt):
  259. txt = re_blank.sub('\r\n', txt)
  260. return txt
  261. BOM = '\xef\xbb\xbf'
  262. try:
  263. BOM = bytes(BOM, 'iso8859-1') # python 3
  264. except NameError:
  265. pass
  266. def stealth_write(self, data, flags='wb'):
  267. try:
  268. x = unicode
  269. except NameError:
  270. data = data.encode('utf-8') # python 3
  271. else:
  272. data = data.decode(sys.getfilesystemencoding(), 'replace')
  273. data = data.encode('utf-8')
  274. if self.name.endswith('.project') or self.name.endswith('.project'):
  275. data = BOM + data
  276. try:
  277. txt = self.read(flags='rb')
  278. if txt != data:
  279. raise ValueError('must write')
  280. except (IOError, ValueError):
  281. self.write(data, flags=flags)
  282. else:
  283. Logs.debug('codelite: skipping %s' % self.abspath())
  284. Node.Node.stealth_write = stealth_write
  285. re_quote = re.compile("[^a-zA-Z0-9-]")
  286. def quote(s):
  287. return re_quote.sub("_", s)
  288. def xml_escape(value):
  289. return value.replace("&", "&amp;").replace('"', "&quot;").replace("'", "&apos;").replace("<", "&lt;").replace(">", "&gt;")
  290. def make_uuid(v, prefix = None):
  291. """
  292. simple utility function
  293. """
  294. if isinstance(v, dict):
  295. keys = list(v.keys())
  296. keys.sort()
  297. tmp = str([(k, v[k]) for k in keys])
  298. else:
  299. tmp = str(v)
  300. d = Utils.md5(tmp.encode()).hexdigest().upper()
  301. if prefix:
  302. d = '%s%s' % (prefix, d[8:])
  303. gid = uuid.UUID(d, version = 4)
  304. return str(gid).upper()
  305. def diff(node, fromnode):
  306. # difference between two nodes, but with "(..)" instead of ".."
  307. c1 = node
  308. c2 = fromnode
  309. c1h = c1.height()
  310. c2h = c2.height()
  311. lst = []
  312. up = 0
  313. while c1h > c2h:
  314. lst.append(c1.name)
  315. c1 = c1.parent
  316. c1h -= 1
  317. while c2h > c1h:
  318. up += 1
  319. c2 = c2.parent
  320. c2h -= 1
  321. while id(c1) != id(c2):
  322. lst.append(c1.name)
  323. up += 1
  324. c1 = c1.parent
  325. c2 = c2.parent
  326. for i in range(up):
  327. lst.append('(..)')
  328. lst.reverse()
  329. return tuple(lst)
  330. class build_property(object):
  331. pass
  332. class vsnode(object):
  333. """
  334. Abstract class representing visual studio elements
  335. We assume that all visual studio nodes have a uuid and a parent
  336. """
  337. def __init__(self, ctx):
  338. self.ctx = ctx # codelite context
  339. self.name = '' # string, mandatory
  340. self.vspath = '' # path in visual studio (name for dirs, absolute path for projects)
  341. self.uuid = '' # string, mandatory
  342. self.parent = None # parent node for visual studio nesting
  343. def get_waf(self):
  344. """
  345. Override in subclasses...
  346. """
  347. return '%s/%s' % (self.ctx.srcnode.abspath(), getattr(self.ctx, 'waf_command', 'waf'))
  348. def ptype(self):
  349. """
  350. Return a special uuid for projects written in the solution file
  351. """
  352. pass
  353. def write(self):
  354. """
  355. Write the project file, by default, do nothing
  356. """
  357. pass
  358. def make_uuid(self, val):
  359. """
  360. Alias for creating uuid values easily (the templates cannot access global variables)
  361. """
  362. return make_uuid(val)
  363. class vsnode_vsdir(vsnode):
  364. """
  365. Nodes representing visual studio folders (which do not match the filesystem tree!)
  366. """
  367. VS_GUID_SOLUTIONFOLDER = "2150E333-8FDC-42A3-9474-1A3956D46DE8"
  368. def __init__(self, ctx, uuid, name, vspath=''):
  369. vsnode.__init__(self, ctx)
  370. self.title = self.name = name
  371. self.uuid = uuid
  372. self.vspath = vspath or name
  373. def ptype(self):
  374. return self.VS_GUID_SOLUTIONFOLDER
  375. class vsnode_project(vsnode):
  376. """
  377. Abstract class representing visual studio project elements
  378. A project is assumed to be writable, and has a node representing the file to write to
  379. """
  380. VS_GUID_VCPROJ = "8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942"
  381. def ptype(self):
  382. return self.VS_GUID_VCPROJ
  383. def __init__(self, ctx, node):
  384. vsnode.__init__(self, ctx)
  385. self.path = node
  386. self.uuid = make_uuid(node.abspath())
  387. self.name = node.name
  388. self.title = self.path.abspath()
  389. self.source = [] # list of node objects
  390. self.build_properties = [] # list of properties (nmake commands, output dir, etc)
  391. def dirs(self):
  392. """
  393. Get the list of parent folders of the source files (header files included)
  394. for writing the filters
  395. """
  396. lst = []
  397. def add(x):
  398. if x.height() > self.tg.path.height() and x not in lst:
  399. lst.append(x)
  400. add(x.parent)
  401. for x in self.source:
  402. add(x.parent)
  403. return lst
  404. def write(self):
  405. Logs.debug('codelite: creating %r' % self.path)
  406. #print "self.name:",self.name
  407. # first write the project file
  408. template1 = compile_template(PROJECT_TEMPLATE)
  409. proj_str = template1(self)
  410. proj_str = rm_blank_lines(proj_str)
  411. self.path.stealth_write(proj_str)
  412. # then write the filter
  413. #template2 = compile_template(FILTER_TEMPLATE)
  414. #filter_str = template2(self)
  415. #filter_str = rm_blank_lines(filter_str)
  416. #tmp = self.path.parent.make_node(self.path.name + '.filters')
  417. #tmp.stealth_write(filter_str)
  418. def get_key(self, node):
  419. """
  420. required for writing the source files
  421. """
  422. name = node.name
  423. if name.endswith('.cpp') or name.endswith('.c'):
  424. return 'sourcefile'
  425. return 'headerfile'
  426. def collect_properties(self):
  427. """
  428. Returns a list of triplet (configuration, platform, output_directory)
  429. """
  430. ret = []
  431. for c in self.ctx.configurations:
  432. for p in self.ctx.platforms:
  433. x = build_property()
  434. x.outdir = ''
  435. x.configuration = c
  436. x.platform = p
  437. x.preprocessor_definitions = ''
  438. x.includes_search_path = ''
  439. # can specify "deploy_dir" too
  440. ret.append(x)
  441. self.build_properties = ret
  442. def get_build_params(self, props):
  443. opt = ''
  444. return (self.get_waf(), opt)
  445. def get_build_command(self, props):
  446. return "%s build %s" % self.get_build_params(props)
  447. def get_clean_command(self, props):
  448. return "%s clean %s" % self.get_build_params(props)
  449. def get_rebuild_command(self, props):
  450. return "%s clean build %s" % self.get_build_params(props)
  451. def get_install_command(self, props):
  452. return "%s install %s" % self.get_build_params(props)
  453. def get_build_and_install_command(self, props):
  454. return "%s build install %s" % self.get_build_params(props)
  455. def get_build_and_install_all_command(self, props):
  456. return "%s build install" % self.get_build_params(props)[0]
  457. def get_clean_all_command(self, props):
  458. return "%s clean" % self.get_build_params(props)[0]
  459. def get_build_all_command(self, props):
  460. return "%s build" % self.get_build_params(props)[0]
  461. def get_rebuild_all_command(self, props):
  462. return "%s clean build" % self.get_build_params(props)[0]
  463. def get_filter_name(self, node):
  464. lst = diff(node, self.tg.path)
  465. return '\\'.join(lst) or '.'
  466. class vsnode_alias(vsnode_project):
  467. def __init__(self, ctx, node, name):
  468. vsnode_project.__init__(self, ctx, node)
  469. self.name = name
  470. self.output_file = ''
  471. class vsnode_build_all(vsnode_alias):
  472. """
  473. Fake target used to emulate the behaviour of "make all" (starting one process by target is slow)
  474. This is the only alias enabled by default
  475. """
  476. def __init__(self, ctx, node, name='build_all_projects'):
  477. vsnode_alias.__init__(self, ctx, node, name)
  478. self.is_active = True
  479. class vsnode_install_all(vsnode_alias):
  480. """
  481. Fake target used to emulate the behaviour of "make install"
  482. """
  483. def __init__(self, ctx, node, name='install_all_projects'):
  484. vsnode_alias.__init__(self, ctx, node, name)
  485. def get_build_command(self, props):
  486. return "%s build install %s" % self.get_build_params(props)
  487. def get_clean_command(self, props):
  488. return "%s clean %s" % self.get_build_params(props)
  489. def get_rebuild_command(self, props):
  490. return "%s clean build install %s" % self.get_build_params(props)
  491. class vsnode_project_view(vsnode_alias):
  492. """
  493. Fake target used to emulate a file system view
  494. """
  495. def __init__(self, ctx, node, name='project_view'):
  496. vsnode_alias.__init__(self, ctx, node, name)
  497. self.tg = self.ctx() # fake one, cannot remove
  498. self.exclude_files = Node.exclude_regs + '''
  499. waf-1.8.*
  500. waf3-1.8.*/**
  501. .waf-1.8.*
  502. .waf3-1.8.*/**
  503. **/*.sdf
  504. **/*.suo
  505. **/*.ncb
  506. **/%s
  507. ''' % Options.lockfile
  508. def collect_source(self):
  509. # this is likely to be slow
  510. self.source = self.ctx.srcnode.ant_glob('**', excl=self.exclude_files)
  511. def get_build_command(self, props):
  512. params = self.get_build_params(props) + (self.ctx.cmd,)
  513. return "%s %s %s" % params
  514. def get_clean_command(self, props):
  515. return ""
  516. def get_rebuild_command(self, props):
  517. return self.get_build_command(props)
  518. class vsnode_target(vsnode_project):
  519. """
  520. CodeLite project representing a targets (programs, libraries, etc) and bound
  521. to a task generator
  522. """
  523. def __init__(self, ctx, tg):
  524. """
  525. A project is more or less equivalent to a file/folder
  526. """
  527. base = getattr(ctx, 'projects_dir', None) or tg.path
  528. node = base.make_node(quote(tg.name) + ctx.project_extension) # the project file as a Node
  529. vsnode_project.__init__(self, ctx, node)
  530. self.name = quote(tg.name)
  531. self.tg = tg # task generator
  532. def get_build_params(self, props):
  533. """
  534. Override the default to add the target name
  535. """
  536. opt = ''
  537. if getattr(self, 'tg', None):
  538. opt += " --targets=%s" % self.tg.name
  539. return (self.get_waf(), opt)
  540. def collect_source(self):
  541. tg = self.tg
  542. source_files = tg.to_nodes(getattr(tg, 'source', []))
  543. include_dirs = Utils.to_list(getattr(tg, 'codelite_includes', []))
  544. include_files = []
  545. for x in include_dirs:
  546. if isinstance(x, str):
  547. x = tg.path.find_node(x)
  548. if x:
  549. lst = [y for y in x.ant_glob(HEADERS_GLOB, flat=False)]
  550. include_files.extend(lst)
  551. # remove duplicates
  552. self.source.extend(list(set(source_files + include_files)))
  553. self.source.sort(key=lambda x: x.abspath())
  554. def collect_properties(self):
  555. """
  556. CodeLite projects are associated with platforms and configurations (for building especially)
  557. """
  558. super(vsnode_target, self).collect_properties()
  559. for x in self.build_properties:
  560. x.outdir = self.path.parent.abspath()
  561. x.preprocessor_definitions = ''
  562. x.includes_search_path = ''
  563. try:
  564. tsk = self.tg.link_task
  565. except AttributeError:
  566. pass
  567. else:
  568. x.output_file = tsk.outputs[0].abspath()
  569. x.preprocessor_definitions = ';'.join(tsk.env.DEFINES)
  570. x.includes_search_path = ';'.join(self.tg.env.INCPATHS)
  571. class codelite_generator(BuildContext):
  572. '''generates a CodeLite workspace'''
  573. cmd = 'codelite'
  574. fun = 'build'
  575. def init(self):
  576. """
  577. Some data that needs to be present
  578. """
  579. if not getattr(self, 'configurations', None):
  580. self.configurations = ['Release'] # LocalRelease, RemoteDebug, etc
  581. if not getattr(self, 'platforms', None):
  582. self.platforms = ['Win32']
  583. if not getattr(self, 'all_projects', None):
  584. self.all_projects = []
  585. if not getattr(self, 'project_extension', None):
  586. self.project_extension = '.project'
  587. if not getattr(self, 'projects_dir', None):
  588. self.projects_dir = self.srcnode.make_node('')
  589. self.projects_dir.mkdir()
  590. # bind the classes to the object, so that subclass can provide custom generators
  591. if not getattr(self, 'vsnode_vsdir', None):
  592. self.vsnode_vsdir = vsnode_vsdir
  593. if not getattr(self, 'vsnode_target', None):
  594. self.vsnode_target = vsnode_target
  595. if not getattr(self, 'vsnode_build_all', None):
  596. self.vsnode_build_all = vsnode_build_all
  597. if not getattr(self, 'vsnode_install_all', None):
  598. self.vsnode_install_all = vsnode_install_all
  599. if not getattr(self, 'vsnode_project_view', None):
  600. self.vsnode_project_view = vsnode_project_view
  601. self.numver = '11.00'
  602. self.vsver = '2010'
  603. def execute(self):
  604. """
  605. Entry point
  606. """
  607. self.restore()
  608. if not self.all_envs:
  609. self.load_envs()
  610. self.recurse([self.run_dir])
  611. # user initialization
  612. self.init()
  613. # two phases for creating the solution
  614. self.collect_projects() # add project objects into "self.all_projects"
  615. self.write_files() # write the corresponding project and solution files
  616. def collect_projects(self):
  617. """
  618. Fill the list self.all_projects with project objects
  619. Fill the list of build targets
  620. """
  621. self.collect_targets()
  622. #self.add_aliases()
  623. #self.collect_dirs()
  624. default_project = getattr(self, 'default_project', None)
  625. def sortfun(x):
  626. if x.name == default_project:
  627. return ''
  628. return getattr(x, 'path', None) and x.path.abspath() or x.name
  629. self.all_projects.sort(key=sortfun)
  630. def write_files(self):
  631. """
  632. Write the project and solution files from the data collected
  633. so far. It is unlikely that you will want to change this
  634. """
  635. for p in self.all_projects:
  636. p.write()
  637. # and finally write the solution file
  638. node = self.get_solution_node()
  639. node.parent.mkdir()
  640. Logs.warn('Creating %r' % node)
  641. #a = dir(self.root)
  642. #for b in a:
  643. # print b
  644. #print self.group_names
  645. #print "Hallo2: ",self.root.listdir()
  646. #print getattr(self, 'codelite_solution_name', None)
  647. template1 = compile_template(SOLUTION_TEMPLATE)
  648. sln_str = template1(self)
  649. sln_str = rm_blank_lines(sln_str)
  650. node.stealth_write(sln_str)
  651. def get_solution_node(self):
  652. """
  653. The solution filename is required when writing the .vcproj files
  654. return self.solution_node and if it does not exist, make one
  655. """
  656. try:
  657. return self.solution_node
  658. except:
  659. pass
  660. codelite_solution_name = getattr(self, 'codelite_solution_name', None)
  661. if not codelite_solution_name:
  662. codelite_solution_name = getattr(Context.g_module, Context.APPNAME, 'project') + '.workspace'
  663. setattr(self, 'codelite_solution_name', codelite_solution_name)
  664. if os.path.isabs(codelite_solution_name):
  665. self.solution_node = self.root.make_node(codelite_solution_name)
  666. else:
  667. self.solution_node = self.srcnode.make_node(codelite_solution_name)
  668. return self.solution_node
  669. def project_configurations(self):
  670. """
  671. Helper that returns all the pairs (config,platform)
  672. """
  673. ret = []
  674. for c in self.configurations:
  675. for p in self.platforms:
  676. ret.append((c, p))
  677. return ret
  678. def collect_targets(self):
  679. """
  680. Process the list of task generators
  681. """
  682. for g in self.groups:
  683. for tg in g:
  684. if not isinstance(tg, TaskGen.task_gen):
  685. continue
  686. if not hasattr(tg, 'codelite_includes'):
  687. tg.codelite_includes = tg.to_list(getattr(tg, 'includes', [])) + tg.to_list(getattr(tg, 'export_includes', []))
  688. tg.post()
  689. if not getattr(tg, 'link_task', None):
  690. continue
  691. p = self.vsnode_target(self, tg)
  692. p.collect_source() # delegate this processing
  693. p.collect_properties()
  694. self.all_projects.append(p)
  695. def add_aliases(self):
  696. """
  697. Add a specific target that emulates the "make all" necessary for Visual studio when pressing F7
  698. We also add an alias for "make install" (disabled by default)
  699. """
  700. base = getattr(self, 'projects_dir', None) or self.tg.path
  701. node_project = base.make_node('build_all_projects' + self.project_extension) # Node
  702. p_build = self.vsnode_build_all(self, node_project)
  703. p_build.collect_properties()
  704. self.all_projects.append(p_build)
  705. node_project = base.make_node('install_all_projects' + self.project_extension) # Node
  706. p_install = self.vsnode_install_all(self, node_project)
  707. p_install.collect_properties()
  708. self.all_projects.append(p_install)
  709. node_project = base.make_node('project_view' + self.project_extension) # Node
  710. p_view = self.vsnode_project_view(self, node_project)
  711. p_view.collect_source()
  712. p_view.collect_properties()
  713. self.all_projects.append(p_view)
  714. n = self.vsnode_vsdir(self, make_uuid(self.srcnode.abspath() + 'build_aliases'), "build_aliases")
  715. p_build.parent = p_install.parent = p_view.parent = n
  716. self.all_projects.append(n)
  717. def collect_dirs(self):
  718. """
  719. Create the folder structure in the CodeLite project view
  720. """
  721. seen = {}
  722. def make_parents(proj):
  723. # look at a project, try to make a parent
  724. if getattr(proj, 'parent', None):
  725. # aliases already have parents
  726. return
  727. x = proj.iter_path
  728. if x in seen:
  729. proj.parent = seen[x]
  730. return
  731. # There is not vsnode_vsdir for x.
  732. # So create a project representing the folder "x"
  733. n = proj.parent = seen[x] = self.vsnode_vsdir(self, make_uuid(x.abspath()), x.name)
  734. n.iter_path = x.parent
  735. self.all_projects.append(n)
  736. # recurse up to the project directory
  737. if x.height() > self.srcnode.height() + 1:
  738. make_parents(n)
  739. for p in self.all_projects[:]: # iterate over a copy of all projects
  740. if not getattr(p, 'tg', None):
  741. # but only projects that have a task generator
  742. continue
  743. # make a folder for each task generator
  744. p.iter_path = p.tg.path
  745. make_parents(p)
  746. def options(ctx):
  747. pass