eclipse.py 19 KB

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