eclipse.py 16 KB

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