eclipse.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. #
  2. # Copyright (c) 2006-2022, 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. from . import rt_studio
  15. import sys
  16. import os
  17. # Add parent directory to path to import building and utils
  18. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  19. from building import *
  20. from utils import *
  21. from utils import _make_path_relative
  22. from utils import xml_indent
  23. MODULE_VER_NUM = 6
  24. source_pattern = ['*.c', '*.cpp', '*.cxx', '*.cc', '*.s', '*.S', '*.asm','*.cmd']
  25. def OSPath(path):
  26. import platform
  27. if type(path) == type('str'):
  28. if platform.system() == 'Windows':
  29. return path.replace('/', '\\')
  30. else:
  31. return path.replace('\\', '/')
  32. else:
  33. if platform.system() == 'Windows':
  34. return [item.replace('/', '\\') for item in path]
  35. else:
  36. return [item.replace('\\', '/') for item in path]
  37. # collect the build source code path and parent path
  38. def CollectPaths(paths):
  39. all_paths = []
  40. def ParentPaths(path):
  41. ret = os.path.dirname(path)
  42. if ret == path or ret == '':
  43. return []
  44. return [ret] + ParentPaths(ret)
  45. for path in paths:
  46. # path = os.path.abspath(path)
  47. path = path.replace('\\', '/')
  48. all_paths = all_paths + [path] + ParentPaths(path)
  49. all_paths = list(set(all_paths))
  50. return sorted(all_paths)
  51. '''
  52. Collect all of files under paths
  53. '''
  54. def CollectFiles(paths, pattern):
  55. files = []
  56. for path in paths:
  57. if type(pattern) == type(''):
  58. files = files + glob.glob(path + '/' + pattern)
  59. else:
  60. for item in pattern:
  61. # print('--> %s' % (path + '/' + item))
  62. files = files + glob.glob(path + '/' + item)
  63. return sorted(files)
  64. def CollectAllFilesinPath(path, pattern):
  65. files = []
  66. for item in pattern:
  67. files += glob.glob(path + '/' + item)
  68. list = os.listdir(path)
  69. if len(list):
  70. for item in list:
  71. if item.startswith('.'):
  72. continue
  73. if item == 'bsp':
  74. continue
  75. if os.path.isdir(os.path.join(path, item)):
  76. files = files + CollectAllFilesinPath(os.path.join(path, item), pattern)
  77. return files
  78. '''
  79. Exclude files from infiles
  80. '''
  81. def ExcludeFiles(infiles, files):
  82. in_files = set([OSPath(file) for file in infiles])
  83. exl_files = set([OSPath(file) for file in files])
  84. exl_files = in_files - exl_files
  85. return exl_files
  86. # caluclate the exclude path for project
  87. def ExcludePaths(rootpath, paths):
  88. ret = []
  89. files = os.listdir(OSPath(rootpath))
  90. for file in files:
  91. if file.startswith('.'):
  92. continue
  93. fullname = os.path.join(OSPath(rootpath), file)
  94. if os.path.isdir(fullname):
  95. # print(fullname)
  96. if not fullname in paths:
  97. ret = ret + [fullname]
  98. else:
  99. ret = ret + ExcludePaths(fullname, paths)
  100. return ret
  101. rtt_path_prefix = '"${workspace_loc://${ProjName}//'
  102. def ConverToRttEclipsePathFormat(path):
  103. return rtt_path_prefix + path + '}"'
  104. def IsRttEclipsePathFormat(path):
  105. if path.startswith(rtt_path_prefix):
  106. return True
  107. else:
  108. return False
  109. # all libs added by scons should be ends with five whitespace as a flag
  110. rtt_lib_flag = 5 * " "
  111. def ConverToRttEclipseLibFormat(lib):
  112. return str(lib) + str(rtt_lib_flag)
  113. def IsRttEclipseLibFormat(path):
  114. if path.endswith(rtt_lib_flag):
  115. return True
  116. else:
  117. return False
  118. def IsCppProject():
  119. return GetDepend('RT_USING_CPLUSPLUS')
  120. def HandleToolOption(tools, env, project, reset):
  121. is_cpp_prj = IsCppProject()
  122. BSP_ROOT = os.path.abspath(env['BSP_ROOT'])
  123. CPPDEFINES = project['CPPDEFINES']
  124. paths = [ConverToRttEclipsePathFormat(RelativeProjectPath(env, os.path.normpath(i)).replace('\\', '/')) for i in project['CPPPATH']]
  125. compile_include_paths_options = []
  126. compile_include_files_options = []
  127. compile_defs_options = []
  128. linker_scriptfile_option = None
  129. linker_script_option = None
  130. linker_nostart_option = None
  131. linker_libs_option = None
  132. linker_paths_option = None
  133. linker_newlib_nano_option = None
  134. for tool in tools:
  135. if tool.get('id').find('compile') != 1:
  136. options = tool.findall('option')
  137. # find all compile options
  138. for option in options:
  139. option_id = option.get('id')
  140. if ('compiler.include.paths' in option_id) or ('compiler.option.includepaths' in option_id) or ('compiler.tasking.include' in option_id):
  141. compile_include_paths_options += [option]
  142. elif option.get('id').find('compiler.include.files') != -1 or option.get('id').find('compiler.option.includefiles') != -1 :
  143. compile_include_files_options += [option]
  144. elif option.get('id').find('compiler.defs') != -1 or option.get('id').find('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 'LIBPATH' in env:
  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('value') == 'true' and '_REENT_SMALL' not in CPPDEFINES:
  181. CPPDEFINES += ['_REENT_SMALL']
  182. file_header = '''
  183. #ifndef RTCONFIG_PREINC_H__
  184. #define RTCONFIG_PREINC_H__
  185. /* Automatically generated file; DO NOT EDIT. */
  186. /* RT-Thread pre-include file */
  187. '''
  188. file_tail = '\n#endif /*RTCONFIG_PREINC_H__*/\n'
  189. rtt_pre_inc_item = '"${workspace_loc:/${ProjName}/rtconfig_preinc.h}"'
  190. # save the CPPDEFINES in to rtconfig_preinc.h
  191. with open('rtconfig_preinc.h', mode = 'w+') as f:
  192. f.write(file_header)
  193. for cppdef in CPPDEFINES:
  194. f.write("#define " + cppdef.replace('=', ' ') + '\n')
  195. f.write(file_tail)
  196. # change the c.compiler.include.files
  197. files = option.findall('listOptionValue')
  198. find_ok = False
  199. for item in files:
  200. if item.get('value') == rtt_pre_inc_item:
  201. find_ok = True
  202. break
  203. if find_ok is False:
  204. SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': rtt_pre_inc_item})
  205. if len(compile_include_files_options) == 0:
  206. for option in compile_defs_options:
  207. defs = option.findall('listOptionValue')
  208. project_defs = []
  209. for item in defs:
  210. if reset is True:
  211. # clean all old configuration
  212. option.remove(item)
  213. else:
  214. project_defs += [item.get('value')]
  215. if len(project_defs) > 0:
  216. cproject_defs = set(CPPDEFINES) - set(project_defs)
  217. else:
  218. cproject_defs = CPPDEFINES
  219. # print('c.compiler.defs')
  220. cproject_defs = sorted(cproject_defs)
  221. for item in cproject_defs:
  222. SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': item})
  223. # update linker script config
  224. if linker_scriptfile_option is not None :
  225. option = linker_scriptfile_option
  226. linker_script = 'link.lds'
  227. items = env['LINKFLAGS'].split(' ')
  228. if '-T' in items:
  229. linker_script = items[items.index('-T') + 1]
  230. linker_script = ConverToRttEclipsePathFormat(linker_script)
  231. listOptionValue = option.find('listOptionValue')
  232. if listOptionValue != None:
  233. if reset is True or IsRttEclipsePathFormat(listOptionValue.get('value')):
  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 'LIBS' in env:
  260. for lib in env['LIBS']:
  261. lib_name = os.path.basename(str(lib))
  262. if lib_name.endswith('.a'):
  263. if lib_name.startswith('lib'):
  264. lib = lib_name[3:].split('.')[0]
  265. else:
  266. lib = ':' + lib_name
  267. formatedLib = ConverToRttEclipseLibFormat(lib)
  268. SubElement(option, 'listOptionValue', {
  269. 'builtIn': 'false', 'value': formatedLib})
  270. # update lib paths
  271. if linker_paths_option is not None:
  272. option = linker_paths_option
  273. # remove old lib paths
  274. for item in option.findall('listOptionValue'):
  275. if IsRttEclipsePathFormat(item.get('value')):
  276. # clean old configuration
  277. option.remove(item)
  278. # add new old lib paths
  279. for path in env['LIBPATH']:
  280. SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': ConverToRttEclipsePathFormat(RelativeProjectPath(env, path).replace('\\', '/'))})
  281. return
  282. def UpdateProjectStructure(env, prj_name):
  283. bsp_root = env['BSP_ROOT']
  284. rtt_root = env['RTT_ROOT']
  285. project = etree.parse('.project')
  286. root = project.getroot()
  287. if rtt_root.startswith(bsp_root):
  288. linkedResources = root.find('linkedResources')
  289. if linkedResources == None:
  290. linkedResources = SubElement(root, 'linkedResources')
  291. links = linkedResources.findall('link')
  292. # delete all RT-Thread folder links
  293. for link in links:
  294. if link.find('name').text.startswith('rt-thread'):
  295. linkedResources.remove(link)
  296. if prj_name:
  297. name = root.find('name')
  298. if name == None:
  299. name = SubElement(root, 'name')
  300. name.text = prj_name
  301. out = open('.project', 'w')
  302. out.write('<?xml version="1.0" encoding="UTF-8"?>\n')
  303. xml_indent(root)
  304. out.write(etree.tostring(root, encoding='utf-8').decode('utf-8'))
  305. out.close()
  306. return
  307. def GenExcluding(env, project):
  308. rtt_root = os.path.abspath(env['RTT_ROOT'])
  309. bsp_root = os.path.abspath(env['BSP_ROOT'])
  310. coll_dirs = CollectPaths(project['DIRS'])
  311. all_paths_temp = [OSPath(path) for path in coll_dirs]
  312. all_paths = []
  313. # add used path
  314. for path in all_paths_temp:
  315. if path.startswith(rtt_root) or path.startswith(bsp_root):
  316. all_paths.append(path)
  317. if bsp_root.startswith(rtt_root):
  318. # bsp folder is in the RT-Thread root folder, such as the RT-Thread source code on GitHub
  319. exclude_paths = ExcludePaths(rtt_root, all_paths)
  320. elif rtt_root.startswith(bsp_root):
  321. # RT-Thread root folder is in the bsp folder, such as project folder which generate by 'scons --dist' cmd
  322. check_path = []
  323. exclude_paths = []
  324. # analyze the primary folder which relative to BSP_ROOT and in all_paths
  325. for path in all_paths:
  326. if path.startswith(bsp_root):
  327. folders = RelativeProjectPath(env, path).split('\\')
  328. if folders[0] != '.' and '\\' + folders[0] not in check_path:
  329. check_path += ['\\' + folders[0]]
  330. # exclue the folder which has managed by scons
  331. for path in check_path:
  332. exclude_paths += ExcludePaths(bsp_root + path, all_paths)
  333. else:
  334. exclude_paths = ExcludePaths(rtt_root, all_paths)
  335. exclude_paths += ExcludePaths(bsp_root, all_paths)
  336. paths = exclude_paths
  337. exclude_paths = []
  338. # remove the folder which not has source code by source_pattern
  339. for path in paths:
  340. # add bsp and libcpu folder and not collect source files (too more files)
  341. if path.endswith('rt-thread\\bsp') or path.endswith('rt-thread\\libcpu'):
  342. exclude_paths += [path]
  343. continue
  344. set = CollectAllFilesinPath(path, source_pattern)
  345. if len(set):
  346. exclude_paths += [path]
  347. exclude_paths = [RelativeProjectPath(env, path).replace('\\', '/') for path in exclude_paths]
  348. all_files = CollectFiles(all_paths, source_pattern)
  349. src_files = project['FILES']
  350. exclude_files = ExcludeFiles(all_files, src_files)
  351. exclude_files = [RelativeProjectPath(env, file).replace('\\', '/') for file in exclude_files]
  352. env['ExPaths'] = exclude_paths
  353. env['ExFiles'] = exclude_files
  354. return exclude_paths + exclude_files
  355. def RelativeProjectPath(env, path):
  356. project_root = os.path.abspath(env['BSP_ROOT'])
  357. rtt_root = os.path.abspath(env['RTT_ROOT'])
  358. if path.startswith(project_root):
  359. return _make_path_relative(project_root, path)
  360. if path.startswith(rtt_root):
  361. return 'rt-thread/' + _make_path_relative(rtt_root, path)
  362. # TODO add others folder
  363. print('ERROR: the ' + path + ' not support')
  364. return path
  365. def HandleExcludingOption(entry, sourceEntries, excluding):
  366. old_excluding = []
  367. if entry != None:
  368. exclud = entry.get('excluding')
  369. if exclud != None:
  370. old_excluding = entry.get('excluding').split('|')
  371. sourceEntries.remove(entry)
  372. value = ''
  373. for item in old_excluding:
  374. if item.startswith('//'):
  375. old_excluding.remove(item)
  376. else:
  377. if value == '':
  378. value = item
  379. else:
  380. value += '|' + item
  381. for item in excluding:
  382. # add special excluding path prefix for RT-Thread
  383. item = '//' + item
  384. if value == '':
  385. value = item
  386. else:
  387. value += '|' + item
  388. SubElement(sourceEntries, 'entry', {'excluding': value, 'flags': 'VALUE_WORKSPACE_PATH|RESOLVED', 'kind':'sourcePath', 'name':""})
  389. def UpdateCproject(env, project, excluding, reset, prj_name):
  390. excluding = sorted(excluding)
  391. cproject = etree.parse('.cproject')
  392. root = cproject.getroot()
  393. cconfigurations = root.findall('storageModule/cconfiguration')
  394. for cconfiguration in cconfigurations:
  395. tools = cconfiguration.findall('storageModule/configuration/folderInfo/toolChain/tool')
  396. HandleToolOption(tools, env, project, reset)
  397. sourceEntries = cconfiguration.find('storageModule/configuration/sourceEntries')
  398. if sourceEntries != None:
  399. entry = sourceEntries.find('entry')
  400. HandleExcludingOption(entry, sourceEntries, excluding)
  401. # update refreshScope
  402. if prj_name:
  403. prj_name = '/' + prj_name
  404. configurations = root.findall('storageModule/configuration')
  405. for configuration in configurations:
  406. resource = configuration.find('resource')
  407. configuration.remove(resource)
  408. SubElement(configuration, 'resource', {'resourceType': "PROJECT", 'workspacePath': prj_name})
  409. # write back to .cproject
  410. out = open('.cproject', 'w')
  411. out.write('<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n')
  412. out.write('<?fileVersion 4.0.0?>')
  413. xml_indent(root)
  414. out.write(etree.tostring(root, encoding='utf-8').decode('utf-8'))
  415. out.close()
  416. def TargetEclipse(env, reset=False, prj_name=None):
  417. global source_pattern
  418. print('Update eclipse setting...')
  419. # generate cproject file
  420. if not os.path.exists('.cproject'):
  421. if rt_studio.gen_cproject_file(os.path.abspath(".cproject")) is False:
  422. print('Fail!')
  423. return
  424. # generate project file
  425. if not os.path.exists('.project'):
  426. if rt_studio.gen_project_file(os.path.abspath(".project")) is False:
  427. print('Fail!')
  428. return
  429. # generate projcfg.ini file
  430. if not os.path.exists('.settings/projcfg.ini'):
  431. # if search files with uvprojx or uvproj suffix
  432. file = ""
  433. items = os.listdir(".")
  434. if len(items) > 0:
  435. for item in items:
  436. if item.endswith(".uvprojx") or item.endswith(".uvproj"):
  437. file = os.path.abspath(item)
  438. break
  439. chip_name = rt_studio.get_mcu_info(file)
  440. if rt_studio.gen_projcfg_ini_file(chip_name, prj_name, os.path.abspath(".settings/projcfg.ini")) is False:
  441. print('Fail!')
  442. return
  443. # enable lowwer .s file compiled in eclipse cdt
  444. if not os.path.exists('.settings/org.eclipse.core.runtime.prefs'):
  445. if rt_studio.gen_org_eclipse_core_runtime_prefs(
  446. os.path.abspath(".settings/org.eclipse.core.runtime.prefs")) is False:
  447. print('Fail!')
  448. return
  449. # add clean2 target to fix issues when files too many
  450. if not os.path.exists('makefile.targets'):
  451. if rt_studio.gen_makefile_targets(os.path.abspath("makefile.targets")) is False:
  452. print('Fail!')
  453. return
  454. project = ProjectInfo(env)
  455. # update the project file structure info on '.project' file
  456. UpdateProjectStructure(env, prj_name)
  457. # generate the exclude paths and files
  458. excluding = GenExcluding(env, project)
  459. # update the project configuration on '.cproject' file
  460. UpdateCproject(env, project, excluding, reset, prj_name)
  461. print('done!')
  462. return