codelite.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  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'):
  217. return "$"
  218. elif g('backslash'):
  219. return "\\"
  220. elif g('subst'):
  221. extr.append(g('code'))
  222. return "<<|@|>>"
  223. return None
  224. line2 = reg_act.sub(repl, line)
  225. params = line2.split('<<|@|>>')
  226. assert(extr)
  227. indent = 0
  228. buf = []
  229. app = buf.append
  230. def app(txt):
  231. buf.append(indent * '\t' + txt)
  232. for x in range(len(extr)):
  233. if params[x]:
  234. app("lst.append(%r)" % params[x])
  235. f = extr[x]
  236. if f.startswith(('if', 'for')):
  237. app(f + ':')
  238. indent += 1
  239. elif f.startswith('py:'):
  240. app(f[3:])
  241. elif f.startswith(('endif', 'endfor')):
  242. indent -= 1
  243. elif f.startswith(('else', 'elif')):
  244. indent -= 1
  245. app(f + ':')
  246. indent += 1
  247. elif f.startswith('xml:'):
  248. app('lst.append(xml_escape(%s))' % f[4:])
  249. else:
  250. #app('lst.append((%s) or "cannot find %s")' % (f, f))
  251. app('lst.append(%s)' % f)
  252. if extr:
  253. if params[-1]:
  254. app("lst.append(%r)" % params[-1])
  255. fun = COMPILE_TEMPLATE % "\n\t".join(buf)
  256. #print(fun)
  257. return Task.funex(fun)
  258. re_blank = re.compile('(\n|\r|\\s)*\n', re.M)
  259. def rm_blank_lines(txt):
  260. txt = re_blank.sub('\r\n', txt)
  261. return txt
  262. BOM = '\xef\xbb\xbf'
  263. try:
  264. BOM = bytes(BOM, 'latin-1') # python 3
  265. except (TypeError, NameError):
  266. pass
  267. def stealth_write(self, data, flags='wb'):
  268. try:
  269. unicode
  270. except NameError:
  271. data = data.encode('utf-8') # python 3
  272. else:
  273. data = data.decode(sys.getfilesystemencoding(), 'replace')
  274. data = data.encode('utf-8')
  275. if self.name.endswith('.project'):
  276. data = BOM + data
  277. try:
  278. txt = self.read(flags='rb')
  279. if txt != data:
  280. raise ValueError('must write')
  281. except (IOError, ValueError):
  282. self.write(data, flags=flags)
  283. else:
  284. Logs.debug('codelite: skipping %r', self)
  285. Node.Node.stealth_write = stealth_write
  286. re_quote = re.compile("[^a-zA-Z0-9-]")
  287. def quote(s):
  288. return re_quote.sub("_", s)
  289. def xml_escape(value):
  290. return value.replace("&", "&amp;").replace('"', "&quot;").replace("'", "&apos;").replace("<", "&lt;").replace(">", "&gt;")
  291. def make_uuid(v, prefix = None):
  292. """
  293. simple utility function
  294. """
  295. if isinstance(v, dict):
  296. keys = list(v.keys())
  297. keys.sort()
  298. tmp = str([(k, v[k]) for k in keys])
  299. else:
  300. tmp = str(v)
  301. d = Utils.md5(tmp.encode()).hexdigest().upper()
  302. if prefix:
  303. d = '%s%s' % (prefix, d[8:])
  304. gid = uuid.UUID(d, version = 4)
  305. return str(gid).upper()
  306. def diff(node, fromnode):
  307. # difference between two nodes, but with "(..)" instead of ".."
  308. c1 = node
  309. c2 = fromnode
  310. c1h = c1.height()
  311. c2h = c2.height()
  312. lst = []
  313. up = 0
  314. while c1h > c2h:
  315. lst.append(c1.name)
  316. c1 = c1.parent
  317. c1h -= 1
  318. while c2h > c1h:
  319. up += 1
  320. c2 = c2.parent
  321. c2h -= 1
  322. while id(c1) != id(c2):
  323. lst.append(c1.name)
  324. up += 1
  325. c1 = c1.parent
  326. c2 = c2.parent
  327. for i in range(up):
  328. lst.append('(..)')
  329. lst.reverse()
  330. return tuple(lst)
  331. class build_property(object):
  332. pass
  333. class vsnode(object):
  334. """
  335. Abstract class representing visual studio elements
  336. We assume that all visual studio nodes have a uuid and a parent
  337. """
  338. def __init__(self, ctx):
  339. self.ctx = ctx # codelite context
  340. self.name = '' # string, mandatory
  341. self.vspath = '' # path in visual studio (name for dirs, absolute path for projects)
  342. self.uuid = '' # string, mandatory
  343. self.parent = None # parent node for visual studio nesting
  344. def get_waf(self):
  345. """
  346. Override in subclasses...
  347. """
  348. return '%s/%s' % (self.ctx.srcnode.abspath(), getattr(self.ctx, 'waf_command', 'waf'))
  349. def ptype(self):
  350. """
  351. Return a special uuid for projects written in the solution file
  352. """
  353. pass
  354. def write(self):
  355. """
  356. Write the project file, by default, do nothing
  357. """
  358. pass
  359. def make_uuid(self, val):
  360. """
  361. Alias for creating uuid values easily (the templates cannot access global variables)
  362. """
  363. return make_uuid(val)
  364. class vsnode_vsdir(vsnode):
  365. """
  366. Nodes representing visual studio folders (which do not match the filesystem tree!)
  367. """
  368. VS_GUID_SOLUTIONFOLDER = "2150E333-8FDC-42A3-9474-1A3956D46DE8"
  369. def __init__(self, ctx, uuid, name, vspath=''):
  370. vsnode.__init__(self, ctx)
  371. self.title = self.name = name
  372. self.uuid = uuid
  373. self.vspath = vspath or name
  374. def ptype(self):
  375. return self.VS_GUID_SOLUTIONFOLDER
  376. class vsnode_project(vsnode):
  377. """
  378. Abstract class representing visual studio project elements
  379. A project is assumed to be writable, and has a node representing the file to write to
  380. """
  381. VS_GUID_VCPROJ = "8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942"
  382. def ptype(self):
  383. return self.VS_GUID_VCPROJ
  384. def __init__(self, ctx, node):
  385. vsnode.__init__(self, ctx)
  386. self.path = node
  387. self.uuid = make_uuid(node.abspath())
  388. self.name = node.name
  389. self.title = self.path.abspath()
  390. self.source = [] # list of node objects
  391. self.build_properties = [] # list of properties (nmake commands, output dir, etc)
  392. def dirs(self):
  393. """
  394. Get the list of parent folders of the source files (header files included)
  395. for writing the filters
  396. """
  397. lst = []
  398. def add(x):
  399. if x.height() > self.tg.path.height() and x not in lst:
  400. lst.append(x)
  401. add(x.parent)
  402. for x in self.source:
  403. add(x.parent)
  404. return lst
  405. def write(self):
  406. Logs.debug('codelite: creating %r', self.path)
  407. #print "self.name:",self.name
  408. # first write the project file
  409. template1 = compile_template(PROJECT_TEMPLATE)
  410. proj_str = template1(self)
  411. proj_str = rm_blank_lines(proj_str)
  412. self.path.stealth_write(proj_str)
  413. # then write the filter
  414. #template2 = compile_template(FILTER_TEMPLATE)
  415. #filter_str = template2(self)
  416. #filter_str = rm_blank_lines(filter_str)
  417. #tmp = self.path.parent.make_node(self.path.name + '.filters')
  418. #tmp.stealth_write(filter_str)
  419. def get_key(self, node):
  420. """
  421. required for writing the source files
  422. """
  423. name = node.name
  424. if name.endswith(('.cpp', '.c')):
  425. return 'sourcefile'
  426. return 'headerfile'
  427. def collect_properties(self):
  428. """
  429. Returns a list of triplet (configuration, platform, output_directory)
  430. """
  431. ret = []
  432. for c in self.ctx.configurations:
  433. for p in self.ctx.platforms:
  434. x = build_property()
  435. x.outdir = ''
  436. x.configuration = c
  437. x.platform = p
  438. x.preprocessor_definitions = ''
  439. x.includes_search_path = ''
  440. # can specify "deploy_dir" too
  441. ret.append(x)
  442. self.build_properties = ret
  443. def get_build_params(self, props):
  444. opt = ''
  445. return (self.get_waf(), opt)
  446. def get_build_command(self, props):
  447. return "%s build %s" % self.get_build_params(props)
  448. def get_clean_command(self, props):
  449. return "%s clean %s" % self.get_build_params(props)
  450. def get_rebuild_command(self, props):
  451. return "%s clean build %s" % self.get_build_params(props)
  452. def get_install_command(self, props):
  453. return "%s install %s" % self.get_build_params(props)
  454. def get_build_and_install_command(self, props):
  455. return "%s build install %s" % self.get_build_params(props)
  456. def get_build_and_install_all_command(self, props):
  457. return "%s build install" % self.get_build_params(props)[0]
  458. def get_clean_all_command(self, props):
  459. return "%s clean" % self.get_build_params(props)[0]
  460. def get_build_all_command(self, props):
  461. return "%s build" % self.get_build_params(props)[0]
  462. def get_rebuild_all_command(self, props):
  463. return "%s clean build" % self.get_build_params(props)[0]
  464. def get_filter_name(self, node):
  465. lst = diff(node, self.tg.path)
  466. return '\\'.join(lst) or '.'
  467. class vsnode_alias(vsnode_project):
  468. def __init__(self, ctx, node, name):
  469. vsnode_project.__init__(self, ctx, node)
  470. self.name = name
  471. self.output_file = ''
  472. class vsnode_build_all(vsnode_alias):
  473. """
  474. Fake target used to emulate the behaviour of "make all" (starting one process by target is slow)
  475. This is the only alias enabled by default
  476. """
  477. def __init__(self, ctx, node, name='build_all_projects'):
  478. vsnode_alias.__init__(self, ctx, node, name)
  479. self.is_active = True
  480. class vsnode_install_all(vsnode_alias):
  481. """
  482. Fake target used to emulate the behaviour of "make install"
  483. """
  484. def __init__(self, ctx, node, name='install_all_projects'):
  485. vsnode_alias.__init__(self, ctx, node, name)
  486. def get_build_command(self, props):
  487. return "%s build install %s" % self.get_build_params(props)
  488. def get_clean_command(self, props):
  489. return "%s clean %s" % self.get_build_params(props)
  490. def get_rebuild_command(self, props):
  491. return "%s clean build install %s" % self.get_build_params(props)
  492. class vsnode_project_view(vsnode_alias):
  493. """
  494. Fake target used to emulate a file system view
  495. """
  496. def __init__(self, ctx, node, name='project_view'):
  497. vsnode_alias.__init__(self, ctx, node, name)
  498. self.tg = self.ctx() # fake one, cannot remove
  499. self.exclude_files = Node.exclude_regs + '''
  500. waf-2*
  501. waf3-2*/**
  502. .waf-2*
  503. .waf3-2*/**
  504. **/*.sdf
  505. **/*.suo
  506. **/*.ncb
  507. **/%s
  508. ''' % Options.lockfile
  509. def collect_source(self):
  510. # this is likely to be slow
  511. self.source = self.ctx.srcnode.ant_glob('**', excl=self.exclude_files)
  512. def get_build_command(self, props):
  513. params = self.get_build_params(props) + (self.ctx.cmd,)
  514. return "%s %s %s" % params
  515. def get_clean_command(self, props):
  516. return ""
  517. def get_rebuild_command(self, props):
  518. return self.get_build_command(props)
  519. class vsnode_target(vsnode_project):
  520. """
  521. CodeLite project representing a targets (programs, libraries, etc) and bound
  522. to a task generator
  523. """
  524. def __init__(self, ctx, tg):
  525. """
  526. A project is more or less equivalent to a file/folder
  527. """
  528. base = getattr(ctx, 'projects_dir', None) or tg.path
  529. node = base.make_node(quote(tg.name) + ctx.project_extension) # the project file as a Node
  530. vsnode_project.__init__(self, ctx, node)
  531. self.name = quote(tg.name)
  532. self.tg = tg # task generator
  533. def get_build_params(self, props):
  534. """
  535. Override the default to add the target name
  536. """
  537. opt = ''
  538. if getattr(self, 'tg', None):
  539. opt += " --targets=%s" % self.tg.name
  540. return (self.get_waf(), opt)
  541. def collect_source(self):
  542. tg = self.tg
  543. source_files = tg.to_nodes(getattr(tg, 'source', []))
  544. include_dirs = Utils.to_list(getattr(tg, 'codelite_includes', []))
  545. include_files = []
  546. for x in include_dirs:
  547. if isinstance(x, str):
  548. x = tg.path.find_node(x)
  549. if x:
  550. lst = [y for y in x.ant_glob(HEADERS_GLOB, flat=False)]
  551. include_files.extend(lst)
  552. # remove duplicates
  553. self.source.extend(list(set(source_files + include_files)))
  554. self.source.sort(key=lambda x: x.abspath())
  555. def collect_properties(self):
  556. """
  557. CodeLite projects are associated with platforms and configurations (for building especially)
  558. """
  559. super(vsnode_target, self).collect_properties()
  560. for x in self.build_properties:
  561. x.outdir = self.path.parent.abspath()
  562. x.preprocessor_definitions = ''
  563. x.includes_search_path = ''
  564. try:
  565. tsk = self.tg.link_task
  566. except AttributeError:
  567. pass
  568. else:
  569. x.output_file = tsk.outputs[0].abspath()
  570. x.preprocessor_definitions = ';'.join(tsk.env.DEFINES)
  571. x.includes_search_path = ';'.join(self.tg.env.INCPATHS)
  572. class codelite_generator(BuildContext):
  573. '''generates a CodeLite workspace'''
  574. cmd = 'codelite'
  575. fun = 'build'
  576. def init(self):
  577. """
  578. Some data that needs to be present
  579. """
  580. if not getattr(self, 'configurations', None):
  581. self.configurations = ['Release'] # LocalRelease, RemoteDebug, etc
  582. if not getattr(self, 'platforms', None):
  583. self.platforms = ['Win32']
  584. if not getattr(self, 'all_projects', None):
  585. self.all_projects = []
  586. if not getattr(self, 'project_extension', None):
  587. self.project_extension = '.project'
  588. if not getattr(self, 'projects_dir', None):
  589. self.projects_dir = self.srcnode.make_node('')
  590. self.projects_dir.mkdir()
  591. # bind the classes to the object, so that subclass can provide custom generators
  592. if not getattr(self, 'vsnode_vsdir', None):
  593. self.vsnode_vsdir = vsnode_vsdir
  594. if not getattr(self, 'vsnode_target', None):
  595. self.vsnode_target = vsnode_target
  596. if not getattr(self, 'vsnode_build_all', None):
  597. self.vsnode_build_all = vsnode_build_all
  598. if not getattr(self, 'vsnode_install_all', None):
  599. self.vsnode_install_all = vsnode_install_all
  600. if not getattr(self, 'vsnode_project_view', None):
  601. self.vsnode_project_view = vsnode_project_view
  602. self.numver = '11.00'
  603. self.vsver = '2010'
  604. def execute(self):
  605. """
  606. Entry point
  607. """
  608. self.restore()
  609. if not self.all_envs:
  610. self.load_envs()
  611. self.recurse([self.run_dir])
  612. # user initialization
  613. self.init()
  614. # two phases for creating the solution
  615. self.collect_projects() # add project objects into "self.all_projects"
  616. self.write_files() # write the corresponding project and solution files
  617. def collect_projects(self):
  618. """
  619. Fill the list self.all_projects with project objects
  620. Fill the list of build targets
  621. """
  622. self.collect_targets()
  623. #self.add_aliases()
  624. #self.collect_dirs()
  625. default_project = getattr(self, 'default_project', None)
  626. def sortfun(x):
  627. if x.name == default_project:
  628. return ''
  629. return getattr(x, 'path', None) and x.path.abspath() or x.name
  630. self.all_projects.sort(key=sortfun)
  631. def write_files(self):
  632. """
  633. Write the project and solution files from the data collected
  634. so far. It is unlikely that you will want to change this
  635. """
  636. for p in self.all_projects:
  637. p.write()
  638. # and finally write the solution file
  639. node = self.get_solution_node()
  640. node.parent.mkdir()
  641. Logs.warn('Creating %r', node)
  642. #a = dir(self.root)
  643. #for b in a:
  644. # print b
  645. #print self.group_names
  646. #print "Hallo2: ",self.root.listdir()
  647. #print getattr(self, 'codelite_solution_name', None)
  648. template1 = compile_template(SOLUTION_TEMPLATE)
  649. sln_str = template1(self)
  650. sln_str = rm_blank_lines(sln_str)
  651. node.stealth_write(sln_str)
  652. def get_solution_node(self):
  653. """
  654. The solution filename is required when writing the .vcproj files
  655. return self.solution_node and if it does not exist, make one
  656. """
  657. try:
  658. return self.solution_node
  659. except:
  660. pass
  661. codelite_solution_name = getattr(self, 'codelite_solution_name', None)
  662. if not codelite_solution_name:
  663. codelite_solution_name = getattr(Context.g_module, Context.APPNAME, 'project') + '.workspace'
  664. setattr(self, 'codelite_solution_name', codelite_solution_name)
  665. if os.path.isabs(codelite_solution_name):
  666. self.solution_node = self.root.make_node(codelite_solution_name)
  667. else:
  668. self.solution_node = self.srcnode.make_node(codelite_solution_name)
  669. return self.solution_node
  670. def project_configurations(self):
  671. """
  672. Helper that returns all the pairs (config,platform)
  673. """
  674. ret = []
  675. for c in self.configurations:
  676. for p in self.platforms:
  677. ret.append((c, p))
  678. return ret
  679. def collect_targets(self):
  680. """
  681. Process the list of task generators
  682. """
  683. for g in self.groups:
  684. for tg in g:
  685. if not isinstance(tg, TaskGen.task_gen):
  686. continue
  687. if not hasattr(tg, 'codelite_includes'):
  688. tg.codelite_includes = tg.to_list(getattr(tg, 'includes', [])) + tg.to_list(getattr(tg, 'export_includes', []))
  689. tg.post()
  690. if not getattr(tg, 'link_task', None):
  691. continue
  692. p = self.vsnode_target(self, tg)
  693. p.collect_source() # delegate this processing
  694. p.collect_properties()
  695. self.all_projects.append(p)
  696. def add_aliases(self):
  697. """
  698. Add a specific target that emulates the "make all" necessary for Visual studio when pressing F7
  699. We also add an alias for "make install" (disabled by default)
  700. """
  701. base = getattr(self, 'projects_dir', None) or self.tg.path
  702. node_project = base.make_node('build_all_projects' + self.project_extension) # Node
  703. p_build = self.vsnode_build_all(self, node_project)
  704. p_build.collect_properties()
  705. self.all_projects.append(p_build)
  706. node_project = base.make_node('install_all_projects' + self.project_extension) # Node
  707. p_install = self.vsnode_install_all(self, node_project)
  708. p_install.collect_properties()
  709. self.all_projects.append(p_install)
  710. node_project = base.make_node('project_view' + self.project_extension) # Node
  711. p_view = self.vsnode_project_view(self, node_project)
  712. p_view.collect_source()
  713. p_view.collect_properties()
  714. self.all_projects.append(p_view)
  715. n = self.vsnode_vsdir(self, make_uuid(self.srcnode.abspath() + 'build_aliases'), "build_aliases")
  716. p_build.parent = p_install.parent = p_view.parent = n
  717. self.all_projects.append(n)
  718. def collect_dirs(self):
  719. """
  720. Create the folder structure in the CodeLite project view
  721. """
  722. seen = {}
  723. def make_parents(proj):
  724. # look at a project, try to make a parent
  725. if getattr(proj, 'parent', None):
  726. # aliases already have parents
  727. return
  728. x = proj.iter_path
  729. if x in seen:
  730. proj.parent = seen[x]
  731. return
  732. # There is not vsnode_vsdir for x.
  733. # So create a project representing the folder "x"
  734. n = proj.parent = seen[x] = self.vsnode_vsdir(self, make_uuid(x.abspath()), x.name)
  735. n.iter_path = x.parent
  736. self.all_projects.append(n)
  737. # recurse up to the project directory
  738. if x.height() > self.srcnode.height() + 1:
  739. make_parents(n)
  740. for p in self.all_projects[:]: # iterate over a copy of all projects
  741. if not getattr(p, 'tg', None):
  742. # but only projects that have a task generator
  743. continue
  744. # make a folder for each task generator
  745. p.iter_path = p.tg.path
  746. make_parents(p)