eclipse.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. #
  2. # Copyright (c) 2006-2019, RT-Thread Development Team
  3. #
  4. # SPDX-License-Identifier: Apache-2.0
  5. #
  6. # Change Logs:
  7. # Date Author Notes
  8. # 2019-03-21 Bernard the first version
  9. # 2019-04-15 armink fix project update error
  10. #
  11. import os
  12. import sys
  13. import glob
  14. from utils import *
  15. from utils import _make_path_relative
  16. from utils import xml_indent
  17. import xml.etree.ElementTree as etree
  18. from xml.etree.ElementTree import SubElement
  19. from building import *
  20. MODULE_VER_NUM = 5
  21. source_pattern = ['*.c', '*.cpp', '*.cxx', '*.s', '*.S', '*.asm']
  22. def OSPath(path):
  23. import platform
  24. if type(path) == type('str'):
  25. if platform.system() == 'Windows':
  26. return path.replace('/', '\\')
  27. else:
  28. return path.replace('\\', '/')
  29. else:
  30. if platform.system() == 'Windows':
  31. return [item.replace('/', '\\') for item in path]
  32. else:
  33. return [item.replace('\\', '/') for item in path]
  34. # collect the build source code path and parent path
  35. def CollectPaths(paths):
  36. all_paths = []
  37. def ParentPaths(path):
  38. ret = os.path.dirname(path)
  39. if ret == path or ret == '':
  40. return []
  41. return [ret] + ParentPaths(ret)
  42. for path in paths:
  43. # path = os.path.abspath(path)
  44. path = path.replace('\\', '/')
  45. all_paths = all_paths + [path] + ParentPaths(path)
  46. all_paths = list(set(all_paths))
  47. return sorted(all_paths)
  48. '''
  49. Collect all of files under paths
  50. '''
  51. def CollectFiles(paths, pattern):
  52. files = []
  53. for path in paths:
  54. if type(pattern) == type(''):
  55. files = files + glob.glob(path + '/' + pattern)
  56. else:
  57. for item in pattern:
  58. # print('--> %s' % (path + '/' + item))
  59. files = files + glob.glob(path + '/' + item)
  60. return sorted(files)
  61. def CollectAllFilesinPath(path, pattern):
  62. files = []
  63. for item in pattern:
  64. files += glob.glob(path + '/' + item)
  65. list = os.listdir(path)
  66. if len(list):
  67. for item in list:
  68. if item.startswith('.'):
  69. continue
  70. if item == 'bsp':
  71. continue
  72. if os.path.isdir(os.path.join(path, item)):
  73. files = files + CollectAllFilesinPath(os.path.join(path, item), pattern)
  74. return files
  75. '''
  76. Exclude files from infiles
  77. '''
  78. def ExcludeFiles(infiles, files):
  79. in_files = set([OSPath(file) for file in infiles])
  80. exl_files = set([OSPath(file) for file in files])
  81. exl_files = in_files - exl_files
  82. return exl_files
  83. # caluclate the exclude path for project
  84. def ExcludePaths(rootpath, paths):
  85. ret = []
  86. files = os.listdir(OSPath(rootpath))
  87. for file in files:
  88. if file.startswith('.'):
  89. continue
  90. fullname = os.path.join(OSPath(rootpath), file)
  91. if os.path.isdir(fullname):
  92. # print(fullname)
  93. if not fullname in paths:
  94. ret = ret + [fullname]
  95. else:
  96. ret = ret + ExcludePaths(fullname, paths)
  97. return ret
  98. rtt_path_prefix = '"${workspace_loc://${ProjName}//'
  99. def ConverToRttEclipsePathFormat(path):
  100. return rtt_path_prefix + path + '}"'
  101. def IsRttEclipsePathFormat(path):
  102. if path.startswith(rtt_path_prefix):
  103. return True
  104. else:
  105. return False
  106. # all libs added by scons should be ends with five whitespace as a flag
  107. rtt_lib_flag = 5 * " "
  108. def ConverToRttEclipseLibFormat(lib):
  109. return str(lib) + str(rtt_lib_flag)
  110. def IsRttEclipseLibFormat(path):
  111. if path.endswith(rtt_lib_flag):
  112. return True
  113. else:
  114. return False
  115. def IsCppProject():
  116. return GetDepend('RT_USING_CPLUSPLUS')
  117. def HandleToolOption(tools, env, project, reset):
  118. is_cpp_prj = IsCppProject()
  119. BSP_ROOT = os.path.abspath(env['BSP_ROOT'])
  120. CPPDEFINES = project['CPPDEFINES']
  121. paths = [ConverToRttEclipsePathFormat(RelativeProjectPath(env, os.path.normpath(i)).replace('\\', '/')) for i in
  122. project['CPPPATH']]
  123. compile_include_paths_options = []
  124. compile_include_files_options = []
  125. compile_defs_options = []
  126. linker_scriptfile_option = None
  127. linker_script_option = None
  128. linker_nostart_option = None
  129. linker_libs_option = None
  130. linker_paths_option = None
  131. linker_newlib_nano_option = None
  132. for tool in tools:
  133. if tool.get('id').find('compile') != 1:
  134. options = tool.findall('option')
  135. # find all compile options
  136. for option in options:
  137. if option.get('id').find('compiler.include.paths') != -1 or option.get('id').find(
  138. 'compiler.option.includepaths') != -1:
  139. compile_include_paths_options += [option]
  140. elif option.get('id').find('compiler.include.files') != -1 or option.get('id').find(
  141. 'compiler.option.includefiles') != -1:
  142. compile_include_files_options += [option]
  143. elif option.get('id').find('compiler.defs') != -1 or option.get('id').find(
  144. 'compiler.option.definedsymbols') != -1:
  145. compile_defs_options += [option]
  146. if tool.get('id').find('linker') != -1:
  147. options = tool.findall('option')
  148. # find all linker options
  149. for option in options:
  150. # the project type and option type must equal
  151. if is_cpp_prj != (option.get('id').find('cpp.linker') != -1):
  152. continue
  153. if option.get('id').find('linker.scriptfile') != -1:
  154. linker_scriptfile_option = option
  155. elif option.get('id').find('linker.option.script') != -1:
  156. linker_script_option = option
  157. elif option.get('id').find('linker.nostart') != -1:
  158. linker_nostart_option = option
  159. elif option.get('id').find('linker.libs') != -1:
  160. linker_libs_option = option
  161. elif option.get('id').find('linker.paths') != -1 and env.has_key('LIBPATH'):
  162. linker_paths_option = option
  163. elif option.get('id').find('linker.usenewlibnano') != -1:
  164. linker_newlib_nano_option = option
  165. # change the inclue path
  166. for option in compile_include_paths_options:
  167. # find all of paths in this project
  168. include_paths = option.findall('listOptionValue')
  169. for item in include_paths:
  170. if reset is True or IsRttEclipsePathFormat(item.get('value')):
  171. # clean old configuration
  172. option.remove(item)
  173. # print('c.compiler.include.paths')
  174. paths = sorted(paths)
  175. for item in paths:
  176. SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': item})
  177. # change the inclue files (default) or definitions
  178. for option in compile_include_files_options:
  179. # add '_REENT_SMALL' to CPPDEFINES when --specs=nano.specs has select
  180. if linker_newlib_nano_option is not None and linker_newlib_nano_option.get(
  181. 'value') == 'true' and '_REENT_SMALL' not in CPPDEFINES:
  182. CPPDEFINES += ['_REENT_SMALL']
  183. file_header = '''
  184. #ifndef RTCONFIG_PREINC_H__
  185. #define RTCONFIG_PREINC_H__
  186. /* Automatically generated file; DO NOT EDIT. */
  187. /* RT-Thread pre-include file */
  188. '''
  189. file_tail = '\n#endif /*RTCONFIG_PREINC_H__*/\n'
  190. rtt_pre_inc_item = '"${workspace_loc:/${ProjName}/rtconfig_preinc.h}"'
  191. # save the CPPDEFINES in to rtconfig_preinc.h
  192. with open('rtconfig_preinc.h', mode='w+') as f:
  193. f.write(file_header)
  194. for cppdef in CPPDEFINES:
  195. f.write("#define " + cppdef.replace('=', ' ') + '\n')
  196. f.write(file_tail)
  197. # change the c.compiler.include.files
  198. files = option.findall('listOptionValue')
  199. find_ok = False
  200. for item in files:
  201. if item.get('value') == rtt_pre_inc_item:
  202. find_ok = True
  203. break
  204. if find_ok is False:
  205. SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': rtt_pre_inc_item})
  206. if len(compile_include_files_options) == 0:
  207. for option in compile_defs_options:
  208. defs = option.findall('listOptionValue')
  209. project_defs = []
  210. for item in defs:
  211. if reset is True:
  212. # clean all old configuration
  213. option.remove(item)
  214. else:
  215. project_defs += [item.get('value')]
  216. if len(project_defs) > 0:
  217. cproject_defs = set(CPPDEFINES) - set(project_defs)
  218. else:
  219. cproject_defs = CPPDEFINES
  220. # print('c.compiler.defs')
  221. cproject_defs = sorted(cproject_defs)
  222. for item in cproject_defs:
  223. SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': item})
  224. # update linker script config
  225. if linker_scriptfile_option is not None:
  226. option = linker_scriptfile_option
  227. linker_script = 'link.lds'
  228. items = env['LINKFLAGS'].split(' ')
  229. if '-T' in items:
  230. linker_script = items[items.index('-T') + 1]
  231. linker_script = ConverToRttEclipsePathFormat(linker_script)
  232. listOptionValue = option.find('listOptionValue')
  233. if listOptionValue != None:
  234. listOptionValue.set('value', linker_script)
  235. else:
  236. SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': linker_script})
  237. # scriptfile in stm32cubeIDE
  238. if linker_script_option is not None:
  239. option = linker_script_option
  240. items = env['LINKFLAGS'].split(' ')
  241. if '-T' in items:
  242. linker_script = ConverToRttEclipsePathFormat(items[items.index('-T') + 1]).strip('"')
  243. option.set('value', linker_script)
  244. # update nostartfiles config
  245. if linker_nostart_option is not None:
  246. option = linker_nostart_option
  247. if env['LINKFLAGS'].find('-nostartfiles') != -1:
  248. option.set('value', 'true')
  249. else:
  250. option.set('value', 'false')
  251. # update libs
  252. if linker_libs_option is not None:
  253. option = linker_libs_option
  254. # remove old libs
  255. for item in option.findall('listOptionValue'):
  256. if IsRttEclipseLibFormat(item.get("value")):
  257. option.remove(item)
  258. # add new libs
  259. if env.has_key('LIBS'):
  260. for lib in env['LIBS']:
  261. formatedLib = ConverToRttEclipseLibFormat(lib)
  262. SubElement(option, 'listOptionValue', {
  263. 'builtIn': 'false', 'value': formatedLib})
  264. # update lib paths
  265. if linker_paths_option is not None:
  266. option = linker_paths_option
  267. # remove old lib paths
  268. for item in option.findall('listOptionValue'):
  269. if IsRttEclipsePathFormat(item.get('value')):
  270. # clean old configuration
  271. option.remove(item)
  272. # add new old lib paths
  273. for path in env['LIBPATH']:
  274. SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': ConverToRttEclipsePathFormat(
  275. RelativeProjectPath(env, path).replace('\\', '/'))})
  276. return
  277. def UpdateProjectStructure(env, prj_name):
  278. bsp_root = env['BSP_ROOT']
  279. rtt_root = env['RTT_ROOT']
  280. project = etree.parse('.project')
  281. root = project.getroot()
  282. if rtt_root.startswith(bsp_root):
  283. linkedResources = root.find('linkedResources')
  284. if linkedResources == None:
  285. linkedResources = SubElement(root, 'linkedResources')
  286. links = linkedResources.findall('link')
  287. # delete all RT-Thread folder links
  288. for link in links:
  289. if link.find('name').text.startswith('rt-thread'):
  290. linkedResources.remove(link)
  291. if prj_name:
  292. name = root.find('name')
  293. if name == None:
  294. name = SubElement(root, 'name')
  295. name.text = prj_name
  296. out = open('.project', 'w')
  297. out.write('<?xml version="1.0" encoding="UTF-8"?>\n')
  298. xml_indent(root)
  299. out.write(etree.tostring(root, encoding='utf-8'))
  300. out.close()
  301. return
  302. def GenExcluding(env, project):
  303. rtt_root = os.path.abspath(env['RTT_ROOT'])
  304. bsp_root = os.path.abspath(env['BSP_ROOT'])
  305. coll_dirs = CollectPaths(project['DIRS'])
  306. all_paths_temp = [OSPath(path) for path in coll_dirs]
  307. all_paths = []
  308. # add used path
  309. for path in all_paths_temp:
  310. if path.startswith(rtt_root) or path.startswith(bsp_root):
  311. all_paths.append(path)
  312. if bsp_root.startswith(rtt_root):
  313. # bsp folder is in the RT-Thread root folder, such as the RT-Thread source code on GitHub
  314. exclude_paths = ExcludePaths(rtt_root, all_paths)
  315. elif rtt_root.startswith(bsp_root):
  316. # RT-Thread root folder is in the bsp folder, such as project folder which generate by 'scons --dist' cmd
  317. check_path = []
  318. exclude_paths = []
  319. # analyze the primary folder which relative to BSP_ROOT and in all_paths
  320. for path in all_paths:
  321. if path.startswith(bsp_root):
  322. folders = RelativeProjectPath(env, path).split('\\')
  323. if folders[0] != '.' and '\\' + folders[0] not in check_path:
  324. check_path += ['\\' + folders[0]]
  325. # exclue the folder which has managed by scons
  326. for path in check_path:
  327. exclude_paths += ExcludePaths(bsp_root + path, all_paths)
  328. else:
  329. exclude_paths = ExcludePaths(rtt_root, all_paths)
  330. exclude_paths += ExcludePaths(bsp_root, all_paths)
  331. paths = exclude_paths
  332. exclude_paths = []
  333. # remove the folder which not has source code by source_pattern
  334. for path in paths:
  335. # add bsp and libcpu folder and not collect source files (too more files)
  336. if path.endswith('rt-thread\\bsp') or path.endswith('rt-thread\\libcpu'):
  337. exclude_paths += [path]
  338. continue
  339. set = CollectAllFilesinPath(path, source_pattern)
  340. if len(set):
  341. exclude_paths += [path]
  342. exclude_paths = [RelativeProjectPath(env, path).replace('\\', '/') for path in exclude_paths]
  343. all_files = CollectFiles(all_paths, source_pattern)
  344. src_files = project['FILES']
  345. exclude_files = ExcludeFiles(all_files, src_files)
  346. exclude_files = [RelativeProjectPath(env, file).replace('\\', '/') for file in exclude_files]
  347. env['ExPaths'] = exclude_paths
  348. env['ExFiles'] = exclude_files
  349. return exclude_paths + exclude_files
  350. def RelativeProjectPath(env, path):
  351. project_root = os.path.abspath(env['BSP_ROOT'])
  352. rtt_root = os.path.abspath(env['RTT_ROOT'])
  353. if path.startswith(project_root):
  354. return _make_path_relative(project_root, path)
  355. if path.startswith(rtt_root):
  356. return 'rt-thread/' + _make_path_relative(rtt_root, path)
  357. # TODO add others folder
  358. print('ERROR: the ' + path + ' not support')
  359. return path
  360. def HandleExcludingOption(entry, sourceEntries, excluding):
  361. old_excluding = []
  362. if entry != None:
  363. old_excluding = entry.get('excluding').split('|')
  364. sourceEntries.remove(entry)
  365. value = ''
  366. for item in old_excluding:
  367. if item.startswith('//'):
  368. old_excluding.remove(item)
  369. else:
  370. if value == '':
  371. value = item
  372. else:
  373. value += '|' + item
  374. for item in excluding:
  375. # add special excluding path prefix for RT-Thread
  376. item = '//' + item
  377. if value == '':
  378. value = item
  379. else:
  380. value += '|' + item
  381. SubElement(sourceEntries, 'entry',
  382. {'excluding': value, 'flags': 'VALUE_WORKSPACE_PATH|RESOLVED', 'kind': 'sourcePath', 'name': ""})
  383. def UpdateCproject(env, project, excluding, reset, prj_name):
  384. excluding = sorted(excluding)
  385. cproject = etree.parse('.cproject')
  386. root = cproject.getroot()
  387. cconfigurations = root.findall('storageModule/cconfiguration')
  388. for cconfiguration in cconfigurations:
  389. tools = cconfiguration.findall('storageModule/configuration/folderInfo/toolChain/tool')
  390. HandleToolOption(tools, env, project, reset)
  391. sourceEntries = cconfiguration.find('storageModule/configuration/sourceEntries')
  392. entry = sourceEntries.find('entry')
  393. HandleExcludingOption(entry, sourceEntries, excluding)
  394. # update refreshScope
  395. if prj_name:
  396. prj_name = '/' + prj_name
  397. configurations = root.findall('storageModule/configuration')
  398. for configuration in configurations:
  399. resource = configuration.find('resource')
  400. configuration.remove(resource)
  401. SubElement(configuration, 'resource', {'resourceType': "PROJECT", 'workspacePath': prj_name})
  402. # write back to .cproject
  403. out = open('.cproject', 'w')
  404. out.write('<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n')
  405. out.write('<?fileVersion 4.0.0?>')
  406. xml_indent(root)
  407. out.write(etree.tostring(root, encoding='utf-8'))
  408. out.close()
  409. def TargetEclipse(env, reset=False, prj_name=None):
  410. global source_pattern
  411. print('Update eclipse setting...')
  412. if not os.path.exists('.cproject'):
  413. print('no eclipse CDT project found!')
  414. return
  415. project = ProjectInfo(env)
  416. # update the project file structure info on '.project' file
  417. UpdateProjectStructure(env, prj_name)
  418. # generate the exclude paths and files
  419. excluding = GenExcluding(env, project)
  420. # update the project configuration on '.cproject' file
  421. UpdateCproject(env, project, excluding, reset, prj_name)
  422. print('done!')
  423. return