eclipse.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. def ConverToEclipsePathFormat(path):
  97. if path.startswith('.'):
  98. path = path[1:]
  99. return '"${workspace_loc:/${ProjName}/' + path + '}"'
  100. def HandleToolOption(tools, env, project, reset):
  101. BSP_ROOT = os.path.abspath(env['BSP_ROOT'])
  102. CPPDEFINES = project['CPPDEFINES']
  103. paths = [ConverToEclipsePathFormat(RelativeProjectPath(env, os.path.normpath(i)).replace('\\', '/')) for i in project['CPPPATH']]
  104. for tool in tools:
  105. if tool.get('id').find('c.compile') != 1:
  106. options = tool.findall('option')
  107. include_paths_option = None
  108. include_files_option = None
  109. defs_option = None
  110. # find all compile options
  111. for option in options:
  112. if option.get('id').find('c.compiler.include.paths') != -1 or option.get('id').find('c.compiler.option.includepaths') != -1:
  113. include_paths_option = option
  114. elif option.get('id').find('c.compiler.include.files') != -1 or option.get('id').find('c.compiler.option.includefiles') != -1 :
  115. include_files_option = option
  116. elif option.get('id').find('c.compiler.defs') != -1 or option.get('id').find('c.compiler.option.definedsymbols') != -1:
  117. defs_option = option
  118. # change the inclue path
  119. if include_paths_option is not None :
  120. option = include_paths_option
  121. # find all of paths in this project
  122. include_paths = option.findall('listOptionValue')
  123. project_paths = []
  124. for item in include_paths:
  125. if reset is True:
  126. # clean all old configuration
  127. option.remove(item)
  128. else:
  129. project_paths += [item.get('value')]
  130. if len(project_paths) > 0:
  131. cproject_paths = set(paths) - set(project_paths)
  132. else:
  133. cproject_paths = paths
  134. # print('c.compiler.include.paths')
  135. cproject_paths = sorted(cproject_paths)
  136. for item in cproject_paths:
  137. SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': item})
  138. # change the inclue files (default) or definitions
  139. if include_files_option is not None:
  140. option = include_files_option
  141. file_header = '''
  142. #ifndef RTCONFIG_PREINC_H__
  143. #define RTCONFIG_PREINC_H__
  144. /* Automatically generated file; DO NOT EDIT. */
  145. /* RT-Thread Configuration */
  146. '''
  147. file_tail = '\n#endif /*RTCONFIG_PREINC_H__*/\n'
  148. rtt_pre_inc_item = '"${workspace_loc:/${ProjName}/rtconfig_preinc.h}"'
  149. # save the CPPDEFINES in to rtconfig_preinc.h
  150. with open('rtconfig_preinc.h', mode = 'w+') as f:
  151. f.write(file_header)
  152. for cppdef in CPPDEFINES:
  153. f.write("#define " + cppdef + '\n')
  154. f.write(file_tail)
  155. # change the c.compiler.include.files
  156. files = option.findall('listOptionValue')
  157. find_ok = False
  158. for item in files:
  159. if item.get('value') == rtt_pre_inc_item:
  160. find_ok = True
  161. break
  162. if find_ok is False:
  163. SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': rtt_pre_inc_item})
  164. elif defs_option is not None :
  165. option = defs_option
  166. defs = option.findall('listOptionValue')
  167. project_defs = []
  168. for item in defs:
  169. if reset is True:
  170. # clean all old configuration
  171. option.remove(item)
  172. else:
  173. project_defs += [item.get('value')]
  174. if len(project_defs) > 0:
  175. cproject_defs = set(CPPDEFINES) - set(project_defs)
  176. else:
  177. cproject_defs = CPPDEFINES
  178. # print('c.compiler.defs')
  179. cproject_defs = sorted(cproject_defs)
  180. for item in cproject_defs:
  181. SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': item})
  182. if tool.get('id').find('c.linker') != -1:
  183. options = tool.findall('option')
  184. for option in options:
  185. # update linker script config
  186. if option.get('id').find('c.linker.scriptfile') != -1:
  187. linker_script = 'link.lds'
  188. items = env['LINKFLAGS'].split(' ')
  189. if '-T' in items:
  190. linker_script = items[items.index('-T') + 1]
  191. linker_script = ConverToEclipsePathFormat(linker_script)
  192. listOptionValue = option.find('listOptionValue')
  193. if listOptionValue != None:
  194. listOptionValue.set('value', linker_script)
  195. else:
  196. SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': linker_script})
  197. # scriptfile in stm32cubeIDE
  198. if option.get('id').find('c.linker.option.script') != -1:
  199. items = env['LINKFLAGS'].split(' ')
  200. if '-T' in items:
  201. linker_script = ConverToEclipsePathFormat(items[items.index('-T') + 1]).strip('"')
  202. option.set('value',linker_script)
  203. # update nostartfiles config
  204. if option.get('id').find('c.linker.nostart') != -1:
  205. if env['LINKFLAGS'].find('-nostartfiles') != -1:
  206. option.set('value', 'true')
  207. else:
  208. option.set('value', 'false')
  209. # update libs
  210. if option.get('id').find('c.linker.libs') != -1 and env.has_key('LIBS'):
  211. # remove old libs
  212. for item in option.findall('listOptionValue'):
  213. option.remove(item)
  214. # add new libs
  215. for lib in env['LIBS']:
  216. SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': lib})
  217. # update lib paths
  218. if option.get('id').find('c.linker.paths') != -1 and env.has_key('LIBPATH'):
  219. # remove old lib paths
  220. for item in option.findall('listOptionValue'):
  221. option.remove(item)
  222. # add new old lib paths
  223. for path in env['LIBPATH']:
  224. SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': path})
  225. return
  226. def UpdateProjectStructure(env, prj_name):
  227. bsp_root = env['BSP_ROOT']
  228. rtt_root = env['RTT_ROOT']
  229. project = etree.parse('.project')
  230. root = project.getroot()
  231. if rtt_root.startswith(bsp_root):
  232. linkedResources = root.find('linkedResources')
  233. if linkedResources == None:
  234. linkedResources = SubElement(root, 'linkedResources')
  235. links = linkedResources.findall('link')
  236. # delete all RT-Thread folder links
  237. for link in links:
  238. if link.find('name').text.startswith('rt-thread'):
  239. linkedResources.remove(link)
  240. if prj_name:
  241. name = root.find('name')
  242. if name == None:
  243. name = SubElement(root, 'name')
  244. name.text = prj_name
  245. out = open('.project', 'w')
  246. out.write('<?xml version="1.0" encoding="UTF-8"?>\n')
  247. xml_indent(root)
  248. out.write(etree.tostring(root, encoding = 'utf-8'))
  249. out.close()
  250. return
  251. def GenExcluding(env, project):
  252. rtt_root = os.path.abspath(env['RTT_ROOT'])
  253. bsp_root = os.path.abspath(env['BSP_ROOT'])
  254. coll_dirs = CollectPaths(project['DIRS'])
  255. all_paths = [OSPath(path) for path in coll_dirs]
  256. if bsp_root.startswith(rtt_root):
  257. # bsp folder is in the RT-Thread root folder, such as the RT-Thread source code on GitHub
  258. exclude_paths = ExcludePaths(rtt_root, all_paths)
  259. elif rtt_root.startswith(bsp_root):
  260. # RT-Thread root folder is in the bsp folder, such as project folder which generate by 'scons --dist' cmd
  261. check_path = []
  262. exclude_paths = []
  263. # analyze the primary folder which relative to BSP_ROOT and in all_paths
  264. for path in all_paths :
  265. if path.startswith(bsp_root) :
  266. folders = RelativeProjectPath(env, path).split('\\')
  267. if folders[0] != '.' and '\\' + folders[0] not in check_path:
  268. check_path += ['\\' + folders[0]]
  269. # exclue the folder which has managed by scons
  270. for path in check_path:
  271. exclude_paths += ExcludePaths(bsp_root + path, all_paths)
  272. else:
  273. exclude_paths = ExcludePaths(rtt_root, all_paths)
  274. exclude_paths += ExcludePaths(bsp_root, all_paths)
  275. paths = exclude_paths
  276. exclude_paths = []
  277. # remove the folder which not has source code by source_pattern
  278. for path in paths:
  279. # add bsp and libcpu folder and not collect source files (too more files)
  280. if path.endswith('rt-thread\\bsp') or path.endswith('rt-thread\\libcpu'):
  281. exclude_paths += [path]
  282. continue
  283. set = CollectAllFilesinPath(path, source_pattern)
  284. if len(set):
  285. exclude_paths += [path]
  286. exclude_paths = [RelativeProjectPath(env, path).replace('\\', '/') for path in exclude_paths]
  287. all_files = CollectFiles(all_paths, source_pattern)
  288. src_files = project['FILES']
  289. exclude_files = ExcludeFiles(all_files, src_files)
  290. exclude_files = [RelativeProjectPath(env, file).replace('\\', '/') for file in exclude_files]
  291. env['ExPaths'] = exclude_paths
  292. env['ExFiles'] = exclude_files
  293. return exclude_paths + exclude_files
  294. def RelativeProjectPath(env, path):
  295. project_root = os.path.abspath(env['BSP_ROOT'])
  296. rtt_root = os.path.abspath(env['RTT_ROOT'])
  297. if path.startswith(project_root):
  298. return _make_path_relative(project_root, path)
  299. if path.startswith(rtt_root):
  300. return 'rt-thread/' + _make_path_relative(rtt_root, path)
  301. # TODO add others folder
  302. print('ERROR: the ' + path + ' not support')
  303. return path
  304. def UpdateCproject(env, project, excluding, reset):
  305. excluding = sorted(excluding)
  306. cproject = etree.parse('.cproject')
  307. root = cproject.getroot()
  308. cconfigurations = root.findall('storageModule/cconfiguration')
  309. for cconfiguration in cconfigurations:
  310. tools = cconfiguration.findall('storageModule/configuration/folderInfo/toolChain/tool')
  311. HandleToolOption(tools, env, project, reset)
  312. sourceEntries = cconfiguration.find('storageModule/configuration/sourceEntries')
  313. entry = sourceEntries.find('entry')
  314. if entry != None:
  315. sourceEntries.remove(entry)
  316. value = ''
  317. for item in excluding:
  318. if value == '':
  319. value = item
  320. else:
  321. value += '|' + item
  322. SubElement(sourceEntries, 'entry', {'excluding': value, 'flags': 'VALUE_WORKSPACE_PATH|RESOLVED', 'kind':'sourcePath', 'name':""})
  323. # write back to .cproject
  324. out = open('.cproject', 'w')
  325. out.write('<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n')
  326. out.write('<?fileVersion 4.0.0?>')
  327. xml_indent(root)
  328. out.write(etree.tostring(root, encoding='utf-8'))
  329. out.close()
  330. def TargetEclipse(env, reset = False, prj_name = None):
  331. global source_pattern
  332. print('Update eclipse setting...')
  333. if not os.path.exists('.cproject'):
  334. print('no eclipse CDT project found!')
  335. return
  336. project = ProjectInfo(env)
  337. # update the project file structure info on '.project' file
  338. UpdateProjectStructure(env, prj_name)
  339. # generate the exclude paths and files
  340. excluding = GenExcluding(env, project)
  341. # update the project configuration on '.cproject' file
  342. UpdateCproject(env, project, excluding, reset)
  343. print('done!')
  344. return