eclipse.py 17 KB

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