1
0

building.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. #
  2. # File : building.py
  3. # This file is part of RT-Thread RTOS
  4. # COPYRIGHT (C) 2006 - 2015, RT-Thread Development Team
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 2 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License along
  17. # with this program; if not, write to the Free Software Foundation, Inc.,
  18. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. #
  20. # Change Logs:
  21. # Date Author Notes
  22. # 2015-01-20 Bernard Add copyright information
  23. # 2015-07-25 Bernard Add LOCAL_CCFLAGS/LOCAL_CPPPATH/LOCAL_CPPDEFINES for
  24. # group definition.
  25. #
  26. import os
  27. import sys
  28. import string
  29. from SCons.Script import *
  30. from utils import _make_path_relative
  31. BuildOptions = {}
  32. Projects = []
  33. Rtt_Root = ''
  34. Env = None
  35. class Win32Spawn:
  36. def spawn(self, sh, escape, cmd, args, env):
  37. # deal with the cmd build-in commands which cannot be used in
  38. # subprocess.Popen
  39. if cmd == 'del':
  40. for f in args[1:]:
  41. try:
  42. os.remove(f)
  43. except Exception as e:
  44. print 'Error removing file: %s' % e
  45. return -1
  46. return 0
  47. import subprocess
  48. newargs = string.join(args[1:], ' ')
  49. cmdline = cmd + " " + newargs
  50. # Make sure the env is constructed by strings
  51. _e = dict([(k, str(v)) for k, v in env.items()])
  52. # Windows(tm) CreateProcess does not use the env passed to it to find
  53. # the executables. So we have to modify our own PATH to make Popen
  54. # work.
  55. old_path = os.environ['PATH']
  56. os.environ['PATH'] = _e['PATH']
  57. try:
  58. proc = subprocess.Popen(cmdline, env=_e, shell=False)
  59. except Exception as e:
  60. print 'Error in calling:\n%s' % cmdline
  61. print 'Exception: %s: %s' % (e, os.strerror(e.errno))
  62. return e.errno
  63. finally:
  64. os.environ['PATH'] = old_path
  65. return proc.wait()
  66. def PrepareBuilding(env, root_directory, has_libcpu=False, remove_components = []):
  67. import SCons.cpp
  68. import rtconfig
  69. global BuildOptions
  70. global Projects
  71. global Env
  72. global Rtt_Root
  73. Env = env
  74. Rtt_Root = root_directory
  75. # add compability with Keil MDK 4.6 which changes the directory of armcc.exe
  76. if rtconfig.PLATFORM == 'armcc':
  77. if not os.path.isfile(os.path.join(rtconfig.EXEC_PATH, 'armcc.exe')):
  78. if rtconfig.EXEC_PATH.find('bin40') > 0:
  79. rtconfig.EXEC_PATH = rtconfig.EXEC_PATH.replace('bin40', 'armcc/bin')
  80. Env['LINKFLAGS']=Env['LINKFLAGS'].replace('RV31', 'armcc')
  81. # reset AR command flags
  82. env['ARCOM'] = '$AR --create $TARGET $SOURCES'
  83. env['LIBPREFIX'] = ''
  84. env['LIBSUFFIX'] = '.lib'
  85. env['LIBLINKPREFIX'] = ''
  86. env['LIBLINKSUFFIX'] = '.lib'
  87. env['LIBDIRPREFIX'] = '--userlibpath '
  88. # patch for win32 spawn
  89. if env['PLATFORM'] == 'win32':
  90. win32_spawn = Win32Spawn()
  91. win32_spawn.env = env
  92. env['SPAWN'] = win32_spawn.spawn
  93. if env['PLATFORM'] == 'win32':
  94. os.environ['PATH'] = rtconfig.EXEC_PATH + ";" + os.environ['PATH']
  95. else:
  96. os.environ['PATH'] = rtconfig.EXEC_PATH + ":" + os.environ['PATH']
  97. # add program path
  98. env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
  99. # add rtconfig.h path
  100. env.Append(CPPPATH = [str(Dir('#').abspath)])
  101. # add library build action
  102. act = SCons.Action.Action(BuildLibInstallAction, 'Install compiled library... $TARGET')
  103. bld = Builder(action = act)
  104. Env.Append(BUILDERS = {'BuildLib': bld})
  105. # parse rtconfig.h to get used component
  106. PreProcessor = SCons.cpp.PreProcessor()
  107. f = file('rtconfig.h', 'r')
  108. contents = f.read()
  109. f.close()
  110. PreProcessor.process_contents(contents)
  111. BuildOptions = PreProcessor.cpp_namespace
  112. # add copy option
  113. AddOption('--copy',
  114. dest='copy',
  115. action='store_true',
  116. default=False,
  117. help='copy rt-thread directory to local.')
  118. AddOption('--copy-header',
  119. dest='copy-header',
  120. action='store_true',
  121. default=False,
  122. help='copy header of rt-thread directory to local.')
  123. AddOption('--cscope',
  124. dest='cscope',
  125. action='store_true',
  126. default=False,
  127. help='Build Cscope cross reference database. Requires cscope installed.')
  128. AddOption('--clang-analyzer',
  129. dest='clang-analyzer',
  130. action='store_true',
  131. default=False,
  132. help='Perform static analyze with Clang-analyzer. '+\
  133. 'Requires Clang installed.\n'+\
  134. 'It is recommended to use with scan-build like this:\n'+\
  135. '`scan-build scons --clang-analyzer`\n'+\
  136. 'If things goes well, scan-build will instruct you to invoke scan-view.')
  137. if GetOption('clang-analyzer'):
  138. # perform what scan-build does
  139. env.Replace(
  140. CC = 'ccc-analyzer',
  141. CXX = 'c++-analyzer',
  142. # skip as and link
  143. LINK = 'true',
  144. AS = 'true',)
  145. env["ENV"].update(x for x in os.environ.items() if x[0].startswith("CCC_"))
  146. # only check, don't compile. ccc-analyzer use CCC_CC as the CC.
  147. # fsyntax-only will give us some additional warning messages
  148. env['ENV']['CCC_CC'] = 'clang'
  149. env.Append(CFLAGS=['-fsyntax-only', '-Wall', '-Wno-invalid-source-encoding'])
  150. env['ENV']['CCC_CXX'] = 'clang++'
  151. env.Append(CXXFLAGS=['-fsyntax-only', '-Wall', '-Wno-invalid-source-encoding'])
  152. # remove the POST_ACTION as it will cause meaningless errors(file not
  153. # found or something like that).
  154. rtconfig.POST_ACTION = ''
  155. # add build library option
  156. AddOption('--buildlib',
  157. dest='buildlib',
  158. type='string',
  159. help='building library of a component')
  160. AddOption('--cleanlib',
  161. dest='cleanlib',
  162. action='store_true',
  163. default=False,
  164. help='clean up the library by --buildlib')
  165. # add target option
  166. AddOption('--target',
  167. dest='target',
  168. type='string',
  169. help='set target project: mdk/mdk4/iar/vs/ua')
  170. #{target_name:(CROSS_TOOL, PLATFORM)}
  171. tgt_dict = {'mdk':('keil', 'armcc'),
  172. 'mdk4':('keil', 'armcc'),
  173. 'mdk5':('keil', 'armcc'),
  174. 'iar':('iar', 'iar'),
  175. 'vs':('msvc', 'cl'),
  176. 'vs2012':('msvc', 'cl'),
  177. 'cb':('keil', 'armcc'),
  178. 'ua':('gcc', 'gcc')}
  179. tgt_name = GetOption('target')
  180. if tgt_name:
  181. # --target will change the toolchain settings which clang-analyzer is
  182. # depend on
  183. if GetOption('clang-analyzer'):
  184. print '--clang-analyzer cannot be used with --target'
  185. sys.exit(1)
  186. SetOption('no_exec', 1)
  187. try:
  188. rtconfig.CROSS_TOOL, rtconfig.PLATFORM = tgt_dict[tgt_name]
  189. except KeyError:
  190. print 'Unknow target: %s. Avaible targets: %s' % \
  191. (tgt_name, ', '.join(tgt_dict.keys()))
  192. sys.exit(1)
  193. elif (GetDepend('RT_USING_NEWLIB') == False and GetDepend('RT_USING_NOLIBC') == False) \
  194. and rtconfig.PLATFORM == 'gcc':
  195. AddDepend('RT_USING_MINILIBC')
  196. # add comstr option
  197. AddOption('--verbose',
  198. dest='verbose',
  199. action='store_true',
  200. default=False,
  201. help='print verbose information during build')
  202. if not GetOption('verbose'):
  203. # override the default verbose command string
  204. env.Replace(
  205. ARCOMSTR = 'AR $TARGET',
  206. ASCOMSTR = 'AS $TARGET',
  207. ASPPCOMSTR = 'AS $TARGET',
  208. CCCOMSTR = 'CC $TARGET',
  209. CXXCOMSTR = 'CXX $TARGET',
  210. LINKCOMSTR = 'LINK $TARGET'
  211. )
  212. # we need to seperate the variant_dir for BSPs and the kernels. BSPs could
  213. # have their own components etc. If they point to the same folder, SCons
  214. # would find the wrong source code to compile.
  215. bsp_vdir = 'build/bsp'
  216. kernel_vdir = 'build/kernel'
  217. # board build script
  218. objs = SConscript('SConscript', variant_dir=bsp_vdir, duplicate=0)
  219. # include kernel
  220. objs.extend(SConscript(Rtt_Root + '/src/SConscript', variant_dir=kernel_vdir + '/src', duplicate=0))
  221. # include libcpu
  222. if not has_libcpu:
  223. objs.extend(SConscript(Rtt_Root + '/libcpu/SConscript',
  224. variant_dir=kernel_vdir + '/libcpu', duplicate=0))
  225. # include components
  226. objs.extend(SConscript(Rtt_Root + '/components/SConscript',
  227. variant_dir=kernel_vdir + '/components',
  228. duplicate=0,
  229. exports='remove_components'))
  230. return objs
  231. def PrepareModuleBuilding(env, root_directory, bsp_directory):
  232. import rtconfig
  233. global BuildOptions
  234. global Env
  235. global Rtt_Root
  236. Env = env
  237. Rtt_Root = root_directory
  238. # parse bsp rtconfig.h to get used component
  239. PreProcessor = SCons.cpp.PreProcessor()
  240. f = file(bsp_directory + '/rtconfig.h', 'r')
  241. contents = f.read()
  242. f.close()
  243. PreProcessor.process_contents(contents)
  244. BuildOptions = PreProcessor.cpp_namespace
  245. # add build/clean library option for library checking
  246. AddOption('--buildlib',
  247. dest='buildlib',
  248. type='string',
  249. help='building library of a component')
  250. AddOption('--cleanlib',
  251. dest='cleanlib',
  252. action='store_true',
  253. default=False,
  254. help='clean up the library by --buildlib')
  255. # add program path
  256. env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
  257. def GetConfigValue(name):
  258. assert type(name) == str, 'GetConfigValue: only string parameter is valid'
  259. try:
  260. return BuildOptions[name]
  261. except:
  262. return ''
  263. def GetDepend(depend):
  264. building = True
  265. if type(depend) == type('str'):
  266. if not BuildOptions.has_key(depend) or BuildOptions[depend] == 0:
  267. building = False
  268. elif BuildOptions[depend] != '':
  269. return BuildOptions[depend]
  270. return building
  271. # for list type depend
  272. for item in depend:
  273. if item != '':
  274. if not BuildOptions.has_key(item) or BuildOptions[item] == 0:
  275. building = False
  276. return building
  277. def AddDepend(option):
  278. BuildOptions[option] = 1
  279. def MergeGroup(src_group, group):
  280. src_group['src'] = src_group['src'] + group['src']
  281. if group.has_key('CCFLAGS'):
  282. if src_group.has_key('CCFLAGS'):
  283. src_group['CCFLAGS'] = src_group['CCFLAGS'] + group['CCFLAGS']
  284. else:
  285. src_group['CCFLAGS'] = group['CCFLAGS']
  286. if group.has_key('CPPPATH'):
  287. if src_group.has_key('CPPPATH'):
  288. src_group['CPPPATH'] = src_group['CPPPATH'] + group['CPPPATH']
  289. else:
  290. src_group['CPPPATH'] = group['CPPPATH']
  291. if group.has_key('CPPDEFINES'):
  292. if src_group.has_key('CPPDEFINES'):
  293. src_group['CPPDEFINES'] = src_group['CPPDEFINES'] + group['CPPDEFINES']
  294. else:
  295. src_group['CPPDEFINES'] = group['CPPDEFINES']
  296. # for local CCFLAGS/CPPPATH/CPPDEFINES
  297. if group.has_key('LOCAL_CCFLAGS'):
  298. if src_group.has_key('LOCAL_CCFLAGS'):
  299. src_group['LOCAL_CCFLAGS'] = src_group['LOCAL_CCFLAGS'] + group['LOCAL_CCFLAGS']
  300. else:
  301. src_group['LOCAL_CCFLAGS'] = group['LOCAL_CCFLAGS']
  302. if group.has_key('LOCAL_CPPPATH'):
  303. if src_group.has_key('LOCAL_CPPPATH'):
  304. src_group['LOCAL_CPPPATH'] = src_group['LOCAL_CPPPATH'] + group['LOCAL_CPPPATH']
  305. else:
  306. src_group['LOCAL_CPPPATH'] = group['LOCAL_CPPPATH']
  307. if group.has_key('LOCAL_CPPDEFINES'):
  308. if src_group.has_key('LOCAL_CPPDEFINES'):
  309. src_group['LOCAL_CPPDEFINES'] = src_group['LOCAL_CPPDEFINES'] + group['LOCAL_CPPDEFINES']
  310. else:
  311. src_group['LOCAL_CPPDEFINES'] = group['LOCAL_CPPDEFINES']
  312. if group.has_key('LINKFLAGS'):
  313. if src_group.has_key('LINKFLAGS'):
  314. src_group['LINKFLAGS'] = src_group['LINKFLAGS'] + group['LINKFLAGS']
  315. else:
  316. src_group['LINKFLAGS'] = group['LINKFLAGS']
  317. if group.has_key('LIBS'):
  318. if src_group.has_key('LIBS'):
  319. src_group['LIBS'] = src_group['LIBS'] + group['LIBS']
  320. else:
  321. src_group['LIBS'] = group['LIBS']
  322. if group.has_key('LIBPATH'):
  323. if src_group.has_key('LIBPATH'):
  324. src_group['LIBPATH'] = src_group['LIBPATH'] + group['LIBPATH']
  325. else:
  326. src_group['LIBPATH'] = group['LIBPATH']
  327. def DefineGroup(name, src, depend, **parameters):
  328. global Env
  329. if not GetDepend(depend):
  330. return []
  331. # find exist group and get path of group
  332. group_path = ''
  333. for g in Projects:
  334. if g['name'] == name:
  335. group_path = g['path']
  336. if group_path == '':
  337. group_path = GetCurrentDir()
  338. group = parameters
  339. group['name'] = name
  340. group['path'] = group_path
  341. if type(src) == type(['src1']):
  342. group['src'] = File(src)
  343. else:
  344. group['src'] = src
  345. if group.has_key('CCFLAGS'):
  346. Env.AppendUnique(CCFLAGS = group['CCFLAGS'])
  347. if group.has_key('CPPPATH'):
  348. Env.AppendUnique(CPPPATH = group['CPPPATH'])
  349. if group.has_key('CPPDEFINES'):
  350. Env.AppendUnique(CPPDEFINES = group['CPPDEFINES'])
  351. if group.has_key('LINKFLAGS'):
  352. Env.AppendUnique(LINKFLAGS = group['LINKFLAGS'])
  353. # check whether to clean up library
  354. if GetOption('cleanlib') and os.path.exists(os.path.join(group['path'], GroupLibFullName(name, Env))):
  355. if group['src'] != []:
  356. print 'Remove library:', GroupLibFullName(name, Env)
  357. do_rm_file(os.path.join(group['path'], GroupLibFullName(name, Env)))
  358. # check whether exist group library
  359. if not GetOption('buildlib') and os.path.exists(os.path.join(group['path'], GroupLibFullName(name, Env))):
  360. group['src'] = []
  361. if group.has_key('LIBS'): group['LIBS'] = group['LIBS'] + [GroupLibName(name, Env)]
  362. else : group['LIBS'] = [GroupLibName(name, Env)]
  363. if group.has_key('LIBPATH'): group['LIBPATH'] = group['LIBPATH'] + [GetCurrentDir()]
  364. else : group['LIBPATH'] = [GetCurrentDir()]
  365. if group.has_key('LIBS'):
  366. Env.AppendUnique(LIBS = group['LIBS'])
  367. if group.has_key('LIBPATH'):
  368. Env.AppendUnique(LIBPATH = group['LIBPATH'])
  369. # check whether to build group library
  370. if group.has_key('LIBRARY'):
  371. objs = Env.Library(name, group['src'])
  372. else:
  373. # only add source
  374. objs = group['src']
  375. # merge group
  376. for g in Projects:
  377. if g['name'] == name:
  378. # merge to this group
  379. MergeGroup(g, group)
  380. return objs
  381. # add a new group
  382. Projects.append(group)
  383. return objs
  384. def GetCurrentDir():
  385. conscript = File('SConscript')
  386. fn = conscript.rfile()
  387. name = fn.name
  388. path = os.path.dirname(fn.abspath)
  389. return path
  390. PREBUILDING = []
  391. def RegisterPreBuildingAction(act):
  392. global PREBUILDING
  393. assert callable(act), 'Could only register callable objects. %s received' % repr(act)
  394. PREBUILDING.append(act)
  395. def PreBuilding():
  396. global PREBUILDING
  397. for a in PREBUILDING:
  398. a()
  399. def GroupLibName(name, env):
  400. import rtconfig
  401. if rtconfig.PLATFORM == 'armcc':
  402. return name + '_rvds'
  403. elif rtconfig.PLATFORM == 'gcc':
  404. return name + '_gcc'
  405. return name
  406. def GroupLibFullName(name, env):
  407. return env['LIBPREFIX'] + GroupLibName(name, env) + env['LIBSUFFIX']
  408. def BuildLibInstallAction(target, source, env):
  409. lib_name = GetOption('buildlib')
  410. for Group in Projects:
  411. if Group['name'] == lib_name:
  412. lib_name = GroupLibFullName(Group['name'], env)
  413. dst_name = os.path.join(Group['path'], lib_name)
  414. print 'Copy %s => %s' % (lib_name, dst_name)
  415. do_copy_file(lib_name, dst_name)
  416. break
  417. def DoBuilding(target, objects):
  418. # remove source files with local flags setting
  419. for group in Projects:
  420. if group.has_key('LOCAL_CCFLAGS') or group.has_key('LOCAL_CPPPATH') or group.has_key('LOCAL_CPPDEFINES'):
  421. for source in group['src']:
  422. for obj in objects:
  423. if source.abspath == obj.abspath or (len(obj.sources) > 0 and source.abspath == obj.sources[0].abspath):
  424. objects.remove(obj)
  425. # re-add the source files to the objects
  426. for group in Projects:
  427. if group.has_key('LOCAL_CCFLAGS') or group.has_key('LOCAL_CPPPATH') or group.has_key('LOCAL_CPPDEFINES'):
  428. CCFLAGS = Env.get('CCFLAGS', '') + group.get('LOCAL_CCFLAGS', '')
  429. CPPPATH = Env.get('CPPPATH', ['']) + group.get('LOCAL_CPPPATH', [''])
  430. CPPDEFINES = Env.get('CPPDEFINES', ['']) + group.get('LOCAL_CPPDEFINES', [''])
  431. for source in group['src']:
  432. objects += Env.Object(source, CCFLAGS = CCFLAGS,
  433. CPPPATH = CPPPATH,
  434. CPPDEFINES = CPPDEFINES)
  435. program = None
  436. # check whether special buildlib option
  437. lib_name = GetOption('buildlib')
  438. if lib_name:
  439. # build library with special component
  440. for Group in Projects:
  441. if Group['name'] == lib_name:
  442. lib_name = GroupLibName(Group['name'], Env)
  443. objects = Env.Object(Group['src'])
  444. program = Env.Library(lib_name, objects)
  445. # add library copy action
  446. Env.BuildLib(lib_name, program)
  447. break
  448. else:
  449. program = Env.Program(target, objects)
  450. EndBuilding(target, program)
  451. def EndBuilding(target, program = None):
  452. import rtconfig
  453. Env.AddPostAction(target, rtconfig.POST_ACTION)
  454. if GetOption('target') == 'mdk':
  455. from keil import MDKProject
  456. from keil import MDK4Project
  457. from keil import MDK5Project
  458. template = os.path.isfile('template.Uv2')
  459. if template:
  460. MDKProject('project.Uv2', Projects)
  461. else:
  462. template = os.path.isfile('template.uvproj')
  463. if template:
  464. MDK4Project('project.uvproj', Projects)
  465. else:
  466. template = os.path.isfile('template.uvprojx')
  467. if template:
  468. MDK5Project('project.uvprojx', Projects)
  469. else:
  470. print 'No template project file found.'
  471. if GetOption('target') == 'mdk4':
  472. from keil import MDK4Project
  473. MDK4Project('project.uvproj', Projects)
  474. if GetOption('target') == 'mdk5':
  475. from keil import MDK5Project
  476. MDK5Project('project.uvprojx', Projects)
  477. if GetOption('target') == 'iar':
  478. from iar import IARProject
  479. IARProject('project.ewp', Projects)
  480. if GetOption('target') == 'vs':
  481. from vs import VSProject
  482. VSProject('project.vcproj', Projects, program)
  483. if GetOption('target') == 'vs2012':
  484. from vs2012 import VS2012Project
  485. VS2012Project('project.vcxproj', Projects, program)
  486. if GetOption('target') == 'cb':
  487. from codeblocks import CBProject
  488. CBProject('project.cbp', Projects, program)
  489. if GetOption('target') == 'ua':
  490. from ua import PrepareUA
  491. PrepareUA(Projects, Rtt_Root, str(Dir('#')))
  492. if GetOption('copy') and program != None:
  493. MakeCopy(program)
  494. if GetOption('copy-header') and program != None:
  495. MakeCopyHeader(program)
  496. if GetOption('cscope'):
  497. from cscope import CscopeDatabase
  498. CscopeDatabase(Projects)
  499. def SrcRemove(src, remove):
  500. if not src:
  501. return
  502. if type(src[0]) == type('str'):
  503. for item in src:
  504. if os.path.basename(item) in remove:
  505. src.remove(item)
  506. return
  507. for item in src:
  508. if os.path.basename(item.rstr()) in remove:
  509. src.remove(item)
  510. def GetVersion():
  511. import SCons.cpp
  512. import string
  513. rtdef = os.path.join(Rtt_Root, 'include', 'rtdef.h')
  514. # parse rtdef.h to get RT-Thread version
  515. prepcessor = SCons.cpp.PreProcessor()
  516. f = file(rtdef, 'r')
  517. contents = f.read()
  518. f.close()
  519. prepcessor.process_contents(contents)
  520. def_ns = prepcessor.cpp_namespace
  521. version = int(filter(lambda ch: ch in '0123456789.', def_ns['RT_VERSION']))
  522. subversion = int(filter(lambda ch: ch in '0123456789.', def_ns['RT_SUBVERSION']))
  523. if def_ns.has_key('RT_REVISION'):
  524. revision = int(filter(lambda ch: ch in '0123456789.', def_ns['RT_REVISION']))
  525. return '%d.%d.%d' % (version, subversion, revision)
  526. return '0.%d.%d' % (version, subversion)
  527. def GlobSubDir(sub_dir, ext_name):
  528. import os
  529. import glob
  530. def glob_source(sub_dir, ext_name):
  531. list = os.listdir(sub_dir)
  532. src = glob.glob(os.path.join(sub_dir, ext_name))
  533. for item in list:
  534. full_subdir = os.path.join(sub_dir, item)
  535. if os.path.isdir(full_subdir):
  536. src += glob_source(full_subdir, ext_name)
  537. return src
  538. dst = []
  539. src = glob_source(sub_dir, ext_name)
  540. for item in src:
  541. dst.append(os.path.relpath(item, sub_dir))
  542. return dst
  543. def PackageSConscript(package):
  544. from package import BuildPackage
  545. return BuildPackage(package)
  546. def file_path_exist(path, *args):
  547. return os.path.exists(os.path.join(path, *args))
  548. def do_rm_file(src):
  549. if os.path.exists(src):
  550. os.unlink(src)
  551. def do_copy_file(src, dst):
  552. import shutil
  553. # check source file
  554. if not os.path.exists(src):
  555. return
  556. path = os.path.dirname(dst)
  557. # mkdir if path not exist
  558. if not os.path.exists(path):
  559. os.makedirs(path)
  560. shutil.copy2(src, dst)
  561. def do_copy_folder(src_dir, dst_dir):
  562. import shutil
  563. # check source directory
  564. if not os.path.exists(src_dir):
  565. return
  566. if os.path.exists(dst_dir):
  567. shutil.rmtree(dst_dir)
  568. shutil.copytree(src_dir, dst_dir)
  569. source_ext = ["c", "h", "s", "S", "cpp", "xpm"]
  570. source_list = []
  571. def walk_children(child):
  572. global source_list
  573. global source_ext
  574. # print child
  575. full_path = child.rfile().abspath
  576. file_type = full_path.rsplit('.',1)[1]
  577. #print file_type
  578. if file_type in source_ext:
  579. if full_path not in source_list:
  580. source_list.append(full_path)
  581. children = child.all_children()
  582. if children != []:
  583. for item in children:
  584. walk_children(item)
  585. def MakeCopy(program):
  586. global source_list
  587. global Rtt_Root
  588. global Env
  589. target_path = os.path.join(Dir('#').abspath, 'rt-thread')
  590. if Env['PLATFORM'] == 'win32':
  591. RTT_ROOT = Rtt_Root.lower()
  592. else:
  593. RTT_ROOT = Rtt_Root
  594. if target_path.startswith(RTT_ROOT):
  595. return
  596. for item in program:
  597. walk_children(item)
  598. source_list.sort()
  599. # filte source file in RT-Thread
  600. target_list = []
  601. for src in source_list:
  602. if Env['PLATFORM'] == 'win32':
  603. src = src.lower()
  604. if src.startswith(RTT_ROOT):
  605. target_list.append(src)
  606. source_list = target_list
  607. # get source path
  608. src_dir = []
  609. for src in source_list:
  610. src = src.replace(RTT_ROOT, '')
  611. if src[0] == os.sep or src[0] == '/':
  612. src = src[1:]
  613. path = os.path.dirname(src)
  614. sub_path = path.split(os.sep)
  615. full_path = RTT_ROOT
  616. for item in sub_path:
  617. full_path = os.path.join(full_path, item)
  618. if full_path not in src_dir:
  619. src_dir.append(full_path)
  620. for item in src_dir:
  621. source_list.append(os.path.join(item, 'SConscript'))
  622. for src in source_list:
  623. dst = src.replace(RTT_ROOT, '')
  624. if dst[0] == os.sep or dst[0] == '/':
  625. dst = dst[1:]
  626. print '=> ', dst
  627. dst = os.path.join(target_path, dst)
  628. do_copy_file(src, dst)
  629. # copy tools directory
  630. print "=> tools"
  631. do_copy_folder(os.path.join(RTT_ROOT, "tools"), os.path.join(target_path, "tools"))
  632. do_copy_file(os.path.join(RTT_ROOT, 'AUTHORS'), os.path.join(target_path, 'AUTHORS'))
  633. do_copy_file(os.path.join(RTT_ROOT, 'COPYING'), os.path.join(target_path, 'COPYING'))
  634. def MakeCopyHeader(program):
  635. global source_ext
  636. source_ext = []
  637. source_ext = ["h", "xpm"]
  638. global source_list
  639. global Rtt_Root
  640. global Env
  641. target_path = os.path.join(Dir('#').abspath, 'rt-thread')
  642. if Env['PLATFORM'] == 'win32':
  643. RTT_ROOT = Rtt_Root.lower()
  644. else:
  645. RTT_ROOT = Rtt_Root
  646. if target_path.startswith(RTT_ROOT):
  647. return
  648. for item in program:
  649. walk_children(item)
  650. source_list.sort()
  651. # filte source file in RT-Thread
  652. target_list = []
  653. for src in source_list:
  654. if Env['PLATFORM'] == 'win32':
  655. src = src.lower()
  656. if src.startswith(RTT_ROOT):
  657. target_list.append(src)
  658. source_list = target_list
  659. for src in source_list:
  660. dst = src.replace(RTT_ROOT, '')
  661. if dst[0] == os.sep or dst[0] == '/':
  662. dst = dst[1:]
  663. print '=> ', dst
  664. dst = os.path.join(target_path, dst)
  665. do_copy_file(src, dst)
  666. # copy tools directory
  667. print "=> tools"
  668. do_copy_folder(os.path.join(RTT_ROOT, "tools"), os.path.join(target_path, "tools"))
  669. do_copy_file(os.path.join(RTT_ROOT, 'AUTHORS'), os.path.join(target_path, 'AUTHORS'))
  670. do_copy_file(os.path.join(RTT_ROOT, 'COPYING'), os.path.join(target_path, 'COPYING'))