eclipse.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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 glob
  12. import xml.etree.ElementTree as etree
  13. from xml.etree.ElementTree import SubElement
  14. import rt_studio
  15. from building import *
  16. from utils import *
  17. from utils import _make_path_relative
  18. from utils import xml_indent
  19. MODULE_VER_NUM = 6
  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(OSPath(rootpath))
  86. for file in files:
  87. if file.startswith('.'):
  88. continue
  89. fullname = os.path.join(OSPath(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. # all libs added by scons should be ends with five whitespace as a flag
  106. rtt_lib_flag = 5 * " "
  107. def ConverToRttEclipseLibFormat(lib):
  108. return str(lib) + str(rtt_lib_flag)
  109. def IsRttEclipseLibFormat(path):
  110. if path.endswith(rtt_lib_flag):
  111. return True
  112. else:
  113. return False
  114. def IsCppProject():
  115. return GetDepend('RT_USING_CPLUSPLUS')
  116. def HandleToolOption(tools, env, project, reset):
  117. is_cpp_prj = IsCppProject()
  118. BSP_ROOT = os.path.abspath(env['BSP_ROOT'])
  119. CPPDEFINES = project['CPPDEFINES']
  120. paths = [ConverToRttEclipsePathFormat(RelativeProjectPath(env, os.path.normpath(i)).replace('\\', '/')) for i in project['CPPPATH']]
  121. compile_include_paths_options = []
  122. compile_include_files_options = []
  123. compile_defs_options = []
  124. linker_scriptfile_option = None
  125. linker_script_option = None
  126. linker_nostart_option = None
  127. linker_libs_option = None
  128. linker_paths_option = None
  129. linker_newlib_nano_option = None
  130. for tool in tools:
  131. if tool.get('id').find('compile') != 1:
  132. options = tool.findall('option')
  133. # find all compile options
  134. for option in options:
  135. if option.get('id').find('compiler.include.paths') != -1 or option.get('id').find('compiler.option.includepaths') != -1:
  136. compile_include_paths_options += [option]
  137. elif option.get('id').find('compiler.include.files') != -1 or option.get('id').find('compiler.option.includefiles') != -1 :
  138. compile_include_files_options += [option]
  139. elif option.get('id').find('compiler.defs') != -1 or option.get('id').find('compiler.option.definedsymbols') != -1:
  140. compile_defs_options += [option]
  141. if tool.get('id').find('linker') != -1:
  142. options = tool.findall('option')
  143. # find all linker options
  144. for option in options:
  145. # the project type and option type must equal
  146. if is_cpp_prj != (option.get('id').find('cpp.linker') != -1):
  147. continue
  148. if option.get('id').find('linker.scriptfile') != -1:
  149. linker_scriptfile_option = option
  150. elif option.get('id').find('linker.option.script') != -1:
  151. linker_script_option = option
  152. elif option.get('id').find('linker.nostart') != -1:
  153. linker_nostart_option = option
  154. elif option.get('id').find('linker.libs') != -1:
  155. linker_libs_option = option
  156. elif option.get('id').find('linker.paths') != -1 and env.has_key('LIBPATH'):
  157. linker_paths_option = option
  158. elif option.get('id').find('linker.usenewlibnano') != -1:
  159. linker_newlib_nano_option = option
  160. # change the inclue path
  161. for option in compile_include_paths_options:
  162. # find all of paths in this project
  163. include_paths = option.findall('listOptionValue')
  164. for item in include_paths:
  165. if reset is True or IsRttEclipsePathFormat(item.get('value')) :
  166. # clean old configuration
  167. option.remove(item)
  168. # print('c.compiler.include.paths')
  169. paths = sorted(paths)
  170. for item in paths:
  171. SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': item})
  172. # change the inclue files (default) or definitions
  173. for option in compile_include_files_options:
  174. # add '_REENT_SMALL' to CPPDEFINES when --specs=nano.specs has select
  175. if linker_newlib_nano_option is not None and linker_newlib_nano_option.get('value') == 'true' and '_REENT_SMALL' not in CPPDEFINES:
  176. CPPDEFINES += ['_REENT_SMALL']
  177. file_header = '''
  178. #ifndef RTCONFIG_PREINC_H__
  179. #define RTCONFIG_PREINC_H__
  180. /* Automatically generated file; DO NOT EDIT. */
  181. /* RT-Thread pre-include file */
  182. '''
  183. file_tail = '\n#endif /*RTCONFIG_PREINC_H__*/\n'
  184. rtt_pre_inc_item = '"${workspace_loc:/${ProjName}/rtconfig_preinc.h}"'
  185. # save the CPPDEFINES in to rtconfig_preinc.h
  186. with open('rtconfig_preinc.h', mode = 'w+') as f:
  187. f.write(file_header)
  188. for cppdef in CPPDEFINES:
  189. f.write("#define " + cppdef.replace('=', ' ') + '\n')
  190. f.write(file_tail)
  191. # change the c.compiler.include.files
  192. files = option.findall('listOptionValue')
  193. find_ok = False
  194. for item in files:
  195. if item.get('value') == rtt_pre_inc_item:
  196. find_ok = True
  197. break
  198. if find_ok is False:
  199. SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': rtt_pre_inc_item})
  200. if len(compile_include_files_options) == 0:
  201. for option in compile_defs_options:
  202. defs = option.findall('listOptionValue')
  203. project_defs = []
  204. for item in defs:
  205. if reset is True:
  206. # clean all old configuration
  207. option.remove(item)
  208. else:
  209. project_defs += [item.get('value')]
  210. if len(project_defs) > 0:
  211. cproject_defs = set(CPPDEFINES) - set(project_defs)
  212. else:
  213. cproject_defs = CPPDEFINES
  214. # print('c.compiler.defs')
  215. cproject_defs = sorted(cproject_defs)
  216. for item in cproject_defs:
  217. SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': item})
  218. # update linker script config
  219. if linker_scriptfile_option is not None :
  220. option = linker_scriptfile_option
  221. linker_script = 'link.lds'
  222. items = env['LINKFLAGS'].split(' ')
  223. if '-T' in items:
  224. linker_script = items[items.index('-T') + 1]
  225. linker_script = ConverToRttEclipsePathFormat(linker_script)
  226. listOptionValue = option.find('listOptionValue')
  227. if listOptionValue != None:
  228. listOptionValue.set('value', linker_script)
  229. else:
  230. SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': linker_script})
  231. # scriptfile in stm32cubeIDE
  232. if linker_script_option is not None :
  233. option = linker_script_option
  234. items = env['LINKFLAGS'].split(' ')
  235. if '-T' in items:
  236. linker_script = ConverToRttEclipsePathFormat(items[items.index('-T') + 1]).strip('"')
  237. option.set('value', linker_script)
  238. # update nostartfiles config
  239. if linker_nostart_option is not None :
  240. option = linker_nostart_option
  241. if env['LINKFLAGS'].find('-nostartfiles') != -1:
  242. option.set('value', 'true')
  243. else:
  244. option.set('value', 'false')
  245. # update libs
  246. if linker_libs_option is not None:
  247. option = linker_libs_option
  248. # remove old libs
  249. for item in option.findall('listOptionValue'):
  250. if IsRttEclipseLibFormat(item.get("value")):
  251. option.remove(item)
  252. # add new libs
  253. if env.has_key('LIBS'):
  254. for lib in env['LIBS']:
  255. formatedLib = ConverToRttEclipseLibFormat(lib)
  256. SubElement(option, 'listOptionValue', {
  257. 'builtIn': 'false', 'value': formatedLib})
  258. # update lib paths
  259. if linker_paths_option is not None:
  260. option = linker_paths_option
  261. # remove old lib paths
  262. for item in option.findall('listOptionValue'):
  263. if IsRttEclipsePathFormat(item.get('value')):
  264. # clean old configuration
  265. option.remove(item)
  266. # add new old lib paths
  267. for path in env['LIBPATH']:
  268. SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': ConverToRttEclipsePathFormat(RelativeProjectPath(env, path).replace('\\', '/'))})
  269. return
  270. def UpdateProjectStructure(env, prj_name):
  271. bsp_root = env['BSP_ROOT']
  272. rtt_root = env['RTT_ROOT']
  273. project = etree.parse('.project')
  274. root = project.getroot()
  275. if rtt_root.startswith(bsp_root):
  276. linkedResources = root.find('linkedResources')
  277. if linkedResources == None:
  278. linkedResources = SubElement(root, 'linkedResources')
  279. links = linkedResources.findall('link')
  280. # delete all RT-Thread folder links
  281. for link in links:
  282. if link.find('name').text.startswith('rt-thread'):
  283. linkedResources.remove(link)
  284. if prj_name:
  285. name = root.find('name')
  286. if name == None:
  287. name = SubElement(root, 'name')
  288. name.text = prj_name
  289. out = open('.project', 'w')
  290. out.write('<?xml version="1.0" encoding="UTF-8"?>\n')
  291. xml_indent(root)
  292. out.write(etree.tostring(root, encoding='utf-8'))
  293. out.close()
  294. return
  295. def GenExcluding(env, project):
  296. rtt_root = os.path.abspath(env['RTT_ROOT'])
  297. bsp_root = os.path.abspath(env['BSP_ROOT'])
  298. coll_dirs = CollectPaths(project['DIRS'])
  299. all_paths_temp = [OSPath(path) for path in coll_dirs]
  300. all_paths = []
  301. # add used path
  302. for path in all_paths_temp:
  303. if path.startswith(rtt_root) or path.startswith(bsp_root):
  304. all_paths.append(path)
  305. if bsp_root.startswith(rtt_root):
  306. # bsp folder is in the RT-Thread root folder, such as the RT-Thread source code on GitHub
  307. exclude_paths = ExcludePaths(rtt_root, all_paths)
  308. elif rtt_root.startswith(bsp_root):
  309. # RT-Thread root folder is in the bsp folder, such as project folder which generate by 'scons --dist' cmd
  310. check_path = []
  311. exclude_paths = []
  312. # analyze the primary folder which relative to BSP_ROOT and in all_paths
  313. for path in all_paths:
  314. if path.startswith(bsp_root):
  315. folders = RelativeProjectPath(env, path).split('\\')
  316. if folders[0] != '.' and '\\' + folders[0] not in check_path:
  317. check_path += ['\\' + folders[0]]
  318. # exclue the folder which has managed by scons
  319. for path in check_path:
  320. exclude_paths += ExcludePaths(bsp_root + path, all_paths)
  321. else:
  322. exclude_paths = ExcludePaths(rtt_root, all_paths)
  323. exclude_paths += ExcludePaths(bsp_root, all_paths)
  324. paths = exclude_paths
  325. exclude_paths = []
  326. # remove the folder which not has source code by source_pattern
  327. for path in paths:
  328. # add bsp and libcpu folder and not collect source files (too more files)
  329. if path.endswith('rt-thread\\bsp') or path.endswith('rt-thread\\libcpu'):
  330. exclude_paths += [path]
  331. continue
  332. set = CollectAllFilesinPath(path, source_pattern)
  333. if len(set):
  334. exclude_paths += [path]
  335. exclude_paths = [RelativeProjectPath(env, path).replace('\\', '/') for path in exclude_paths]
  336. all_files = CollectFiles(all_paths, source_pattern)
  337. src_files = project['FILES']
  338. exclude_files = ExcludeFiles(all_files, src_files)
  339. exclude_files = [RelativeProjectPath(env, file).replace('\\', '/') for file in exclude_files]
  340. env['ExPaths'] = exclude_paths
  341. env['ExFiles'] = exclude_files
  342. return exclude_paths + exclude_files
  343. def RelativeProjectPath(env, path):
  344. project_root = os.path.abspath(env['BSP_ROOT'])
  345. rtt_root = os.path.abspath(env['RTT_ROOT'])
  346. if path.startswith(project_root):
  347. return _make_path_relative(project_root, path)
  348. if path.startswith(rtt_root):
  349. return 'rt-thread/' + _make_path_relative(rtt_root, path)
  350. # TODO add others folder
  351. print('ERROR: the ' + path + ' not support')
  352. return path
  353. def HandleExcludingOption(entry, sourceEntries, excluding):
  354. old_excluding = []
  355. if entry != None:
  356. old_excluding = entry.get('excluding').split('|')
  357. sourceEntries.remove(entry)
  358. value = ''
  359. for item in old_excluding:
  360. if item.startswith('//'):
  361. old_excluding.remove(item)
  362. else:
  363. if value == '':
  364. value = item
  365. else:
  366. value += '|' + item
  367. for item in excluding:
  368. # add special excluding path prefix for RT-Thread
  369. item = '//' + item
  370. if value == '':
  371. value = item
  372. else:
  373. value += '|' + item
  374. SubElement(sourceEntries, 'entry', {'excluding': value, 'flags': 'VALUE_WORKSPACE_PATH|RESOLVED', 'kind':'sourcePath', 'name':""})
  375. def UpdateCproject(env, project, excluding, reset, prj_name):
  376. excluding = sorted(excluding)
  377. cproject = etree.parse('.cproject')
  378. root = cproject.getroot()
  379. cconfigurations = root.findall('storageModule/cconfiguration')
  380. for cconfiguration in cconfigurations:
  381. tools = cconfiguration.findall('storageModule/configuration/folderInfo/toolChain/tool')
  382. HandleToolOption(tools, env, project, reset)
  383. sourceEntries = cconfiguration.find('storageModule/configuration/sourceEntries')
  384. entry = sourceEntries.find('entry')
  385. HandleExcludingOption(entry, sourceEntries, excluding)
  386. # update refreshScope
  387. if prj_name:
  388. prj_name = '/' + prj_name
  389. configurations = root.findall('storageModule/configuration')
  390. for configuration in configurations:
  391. resource = configuration.find('resource')
  392. configuration.remove(resource)
  393. SubElement(configuration, 'resource', {'resourceType': "PROJECT", 'workspacePath': prj_name})
  394. # write back to .cproject
  395. out = open('.cproject', 'w')
  396. out.write('<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n')
  397. out.write('<?fileVersion 4.0.0?>')
  398. xml_indent(root)
  399. out.write(etree.tostring(root, encoding='utf-8'))
  400. out.close()
  401. def TargetEclipse(env, reset=False, prj_name=None):
  402. global source_pattern
  403. print('Update eclipse setting...')
  404. # generate cproject file
  405. if not os.path.exists('.cproject'):
  406. if rt_studio.gen_cproject_file(os.path.abspath(".cproject")) is False:
  407. print('Fail!')
  408. return
  409. # generate project file
  410. if not os.path.exists('.project'):
  411. if rt_studio.gen_project_file(os.path.abspath(".project")) is False:
  412. print('Fail!')
  413. return
  414. # generate projcfg.ini file
  415. if not os.path.exists('.settings/projcfg.ini'):
  416. # if search files with uvprojx or uvproj suffix
  417. items = os.listdir(".")
  418. if len(items) > 0:
  419. for item in items:
  420. if item.endswith(".uvprojx") or item.endswith(".uvproj"):
  421. file = os.path.abspath(item)
  422. break
  423. else:
  424. file = ""
  425. chip_name = rt_studio.get_mcu_info(file)
  426. if rt_studio.gen_projcfg_ini_file(chip_name, prj_name, os.path.abspath(".settings/projcfg.ini")) is False:
  427. print('Fail!')
  428. return
  429. # enable lowwer .s file compiled in eclipse cdt
  430. if not os.path.exists('.settings/org.eclipse.core.runtime.prefs'):
  431. if rt_studio.gen_org_eclipse_core_runtime_prefs(
  432. os.path.abspath(".settings/org.eclipse.core.runtime.prefs")) is False:
  433. print('Fail!')
  434. return
  435. # add clean2 target to fix issues when files too many
  436. if not os.path.exists('makefile.targets'):
  437. if rt_studio.gen_makefile_targets(os.path.abspath("makefile.targets")) is False:
  438. print('Fail!')
  439. return
  440. project = ProjectInfo(env)
  441. # update the project file structure info on '.project' file
  442. UpdateProjectStructure(env, prj_name)
  443. # generate the exclude paths and files
  444. excluding = GenExcluding(env, project)
  445. # update the project configuration on '.cproject' file
  446. UpdateCproject(env, project, excluding, reset, prj_name)
  447. print('done!')
  448. return