env_utility.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. #! /usr/bin/env python
  2. # coding=utf-8
  3. #
  4. # Copyright (c) 2024, RT-Thread Development Team
  5. #
  6. # SPDX-License-Identifier: GPL-2.0
  7. #
  8. # Change Logs:
  9. # Date Author Notes
  10. # 2024-04-20 Bernard the first version
  11. import os
  12. import json
  13. import platform
  14. import re
  15. import sys
  16. import shutil
  17. import hashlib
  18. import operator
  19. def GetEnvPath():
  20. if "ENV_ROOT" in os.environ:
  21. return os.environ["ENV_ROOT"]
  22. if platform.system() == 'Windows':
  23. env_root = os.path.join(os.environ['USERPROFILE'], '.env')
  24. else:
  25. env_root = os.path.join(os.environ['HOME'], '.env')
  26. return env_root
  27. def GetPkgPath():
  28. if "PKGS_DIR" in os.environ:
  29. return os.environ["PKGS_DIR"]
  30. elif "PKGS_ROOT" in os.environ:
  31. return os.environ["PKGS_ROOT"]
  32. elif GetEnvPath():
  33. return os.path.join(GetEnvPath(), "packages")
  34. else:
  35. return None
  36. def GetSDKPackagePath():
  37. env = GetEnvPath()
  38. if env:
  39. return os.path.join(env, "tools", "scripts", "packages")
  40. return None
  41. # get SDK path based on name
  42. # for example, GetSDKPath('arm-none-eabi') = '.env/tools/scripts/packages/arm-none-eabi-gcc-v10.3'
  43. def GetSDKPath(name):
  44. sdk_pkgs = GetSDKPackagePath()
  45. if sdk_pkgs:
  46. # read packages.json under env/tools/scripts/packages
  47. with open(os.path.join(sdk_pkgs, 'pkgs.json'), 'r', encoding='utf-8') as f:
  48. # packages_json = f.read()
  49. packages = json.load(f)
  50. for item in packages:
  51. package_path = os.path.join(GetEnvPath(), 'packages', item['path'], 'package.json')
  52. # read package['path']/package.json under env/packages
  53. with open(package_path, 'r', encoding='utf-8') as f:
  54. # package_json = f.read()
  55. package = json.load(f)
  56. if package['name'] == name:
  57. return os.path.join(sdk_pkgs, package['name'] + '-' + item['ver'])
  58. # not found named package
  59. return None
  60. def help_info():
  61. print(
  62. "**********************************************************************************\n"
  63. "* Help infomation:\n"
  64. "* Git tool install step.\n"
  65. "* If your system is linux, you can use command below to install git.\n"
  66. "* $ sudo yum install git\n"
  67. "* $ sudo apt-get install git\n"
  68. "* If your system is windows, you should download git software(msysGit).\n"
  69. "* Download path: http://git-scm.com/download/win\n"
  70. "* After you install it, be sure to add the git command execution PATH \n"
  71. "* to your system PATH.\n"
  72. "* Usually, git command PATH is $YOUR_INSTALL_DIR\\Git\\bin\n"
  73. "* If your system is OSX, please download git and install it.\n"
  74. "* Download path: http://git-scm.com/download/mac\n"
  75. "**********************************************************************************\n"
  76. )
  77. def touch_env(use_gitee=False):
  78. if sys.platform != 'win32':
  79. home_dir = os.environ['HOME']
  80. else:
  81. home_dir = os.environ['USERPROFILE']
  82. if use_gitee:
  83. # "Install RT-Thread Environment from Gitee"
  84. sdk_url = 'https://gitee.com/RT-Thread-Mirror/sdk.git'
  85. pkg_url = 'https://gitee.com/RT-Thread-Mirror/packages.git'
  86. env_url = 'https://gitee.com/RT-Thread-Mirror/env.git'
  87. else:
  88. pkg_url = 'https://github.com/RT-Thread/packages.git'
  89. sdk_url = 'https://github.com/RT-Thread/sdk.git'
  90. env_url = 'https://github.com/RT-Thread/env.git'
  91. pkg_url = os.getenv('RTT_PACKAGE_URL') or pkg_url
  92. sdk_url = os.getenv('RTT_SDK_URL') or sdk_url
  93. env_url = os.getenv('RTT_ENV_URL') or env_url
  94. # make .env and other directories
  95. env_dir = os.path.join(home_dir, '.env')
  96. if not os.path.exists(env_dir):
  97. os.mkdir(env_dir)
  98. os.mkdir(os.path.join(env_dir, 'local_pkgs'))
  99. os.mkdir(os.path.join(env_dir, 'packages'))
  100. os.mkdir(os.path.join(env_dir, 'tools'))
  101. kconfig = open(os.path.join(env_dir, 'packages', 'Kconfig'), 'w')
  102. kconfig.close()
  103. # git clone packages
  104. if not os.path.exists(os.path.join(env_dir, 'packages', 'packages')):
  105. try:
  106. ret = os.system('git clone %s %s' % (pkg_url, os.path.join(env_dir, 'packages', 'packages')))
  107. if ret != 0:
  108. shutil.rmtree(os.path.join(env_dir, 'packages', 'packages'))
  109. print(
  110. "********************************************************************************\n"
  111. "* Warnning:\n"
  112. "* Run command error for \"git clone https://github.com/RT-Thread/packages.git\".\n"
  113. "* This error may have been caused by not found a git tool or network error.\n"
  114. "* If the git tool is not installed, install the git tool first.\n"
  115. "* If the git utility is installed, check whether the git command is added to \n"
  116. "* the system PATH.\n"
  117. "* This error may cause the RT-Thread packages to not work properly.\n"
  118. "********************************************************************************\n"
  119. )
  120. help_info()
  121. else:
  122. kconfig = open(os.path.join(env_dir, 'packages', 'Kconfig'), 'w')
  123. kconfig.write('source "$PKGS_DIR/packages/Kconfig"')
  124. kconfig.close()
  125. except:
  126. print(
  127. "**********************************************************************************\n"
  128. "* Warnning:\n"
  129. "* Run command error for \"git clone https://github.com/RT-Thread/packages.git\". \n"
  130. "* This error may have been caused by not found a git tool or git tool not in \n"
  131. "* the system PATH. \n"
  132. "* This error may cause the RT-Thread packages to not work properly. \n"
  133. "**********************************************************************************\n"
  134. )
  135. help_info()
  136. # git clone env scripts
  137. if not os.path.exists(os.path.join(env_dir, 'tools', 'scripts')):
  138. try:
  139. ret = os.system('git clone %s %s' % (env_url, os.path.join(env_dir, 'tools', 'scripts')))
  140. if ret != 0:
  141. shutil.rmtree(os.path.join(env_dir, 'tools', 'scripts'))
  142. print(
  143. "********************************************************************************\n"
  144. "* Warnning:\n"
  145. "* Run command error for \"git clone https://github.com/RT-Thread/env.git\".\n"
  146. "* This error may have been caused by not found a git tool or network error.\n"
  147. "* If the git tool is not installed, install the git tool first.\n"
  148. "* If the git utility is installed, check whether the git command is added \n"
  149. "* to the system PATH.\n"
  150. "* This error may cause script tools to fail to work properly.\n"
  151. "********************************************************************************\n"
  152. )
  153. help_info()
  154. except:
  155. print(
  156. "********************************************************************************\n"
  157. "* Warnning:\n"
  158. "* Run command error for \"git clone https://github.com/RT-Thread/env.git\". \n"
  159. "* This error may have been caused by not found a git tool or git tool not in \n"
  160. "* the system PATH. \n"
  161. "* This error may cause script tools to fail to work properly. \n"
  162. "********************************************************************************\n"
  163. )
  164. help_info()
  165. # git clone sdk
  166. if not os.path.exists(os.path.join(env_dir, 'packages', 'sdk')):
  167. try:
  168. ret = os.system('git clone %s %s' % (sdk_url, os.path.join(env_dir, 'packages', 'sdk')))
  169. if ret != 0:
  170. shutil.rmtree(os.path.join(env_dir, 'packages', 'sdk'))
  171. print(
  172. "********************************************************************************\n"
  173. "* Warnning:\n"
  174. "* Run command error for \"git clone https://github.com/RT-Thread/sdk.git\".\n"
  175. "* This error may have been caused by not found a git tool or network error.\n"
  176. "* If the git tool is not installed, install the git tool first.\n"
  177. "* If the git utility is installed, check whether the git command is added \n"
  178. "* to the system PATH.\n"
  179. "* This error may cause the RT-Thread SDK to not work properly.\n"
  180. "********************************************************************************\n"
  181. )
  182. help_info()
  183. except:
  184. print(
  185. "********************************************************************************\n"
  186. "* Warnning:\n"
  187. "* Run command error for \"https://github.com/RT-Thread/sdk.git\".\n"
  188. "* This error may have been caused by not found a git tool or git tool not in \n"
  189. "* the system PATH. \n"
  190. "* This error may cause the RT-Thread SDK to not work properly. \n"
  191. "********************************************************************************\n"
  192. )
  193. help_info()
  194. # try to create an empty .config file
  195. if not os.path.exists(os.path.join(env_dir, 'tools', '.config')):
  196. kconfig = open(os.path.join(env_dir, 'tools', '.config'), 'w')
  197. kconfig.close()
  198. # copy env.sh or env.ps1, Kconfig
  199. shutil.copy(os.path.join(env_dir, 'tools', 'scripts', 'Kconfig'), os.path.join(home_dir, '.env', 'tools'))
  200. if sys.platform != 'win32':
  201. shutil.copy(os.path.join(env_dir, 'tools', 'scripts', 'env.sh'), os.path.join(home_dir, '.env', 'env.sh'))
  202. else:
  203. shutil.copy(os.path.join(env_dir, 'tools', 'scripts', 'env.ps1'), os.path.join(home_dir, '.env', 'env.ps1'))
  204. # unzip kconfig-mconf.zip
  205. # zip_file = os.path.join(env_dir, 'tools', 'scripts', 'kconfig-mconf.zip')
  206. # if os.path.exists(zip_file):
  207. # zip_file_dir = os.path.join(env_dir, 'tools', 'bin')
  208. # if os.path.exists(zip_file_dir):
  209. # shutil.rmtree(zip_file_dir)
  210. # zip_file_obj = zipfile.ZipFile(zip_file, 'r')
  211. # for file in zip_file_obj.namelist():
  212. # zip_file_obj.extract(file, zip_file_dir)
  213. # zip_file_obj.close()
  214. def is_pkg_special_config(config_str):
  215. '''judge if it's CONFIG_PKG_XX_PATH or CONFIG_PKG_XX_VER'''
  216. if type(config_str) == type('a'):
  217. if config_str.startswith("PKG_") and (config_str.endswith('_PATH') or config_str.endswith('_VER')):
  218. return True
  219. return False
  220. def mk_rtconfig(filename):
  221. try:
  222. config = open(filename, 'r')
  223. except:
  224. print('open config:%s failed' % filename)
  225. return
  226. rtconfig = open('rtconfig.h', 'w')
  227. rtconfig.write('#ifndef RT_CONFIG_H__\n')
  228. rtconfig.write('#define RT_CONFIG_H__\n\n')
  229. empty_line = 1
  230. for line in config:
  231. line = line.lstrip(' ').replace('\n', '').replace('\r', '')
  232. if len(line) == 0:
  233. continue
  234. if line[0] == '#':
  235. if len(line) == 1:
  236. if empty_line:
  237. continue
  238. rtconfig.write('\n')
  239. empty_line = 1
  240. continue
  241. if line.startswith('# CONFIG_'):
  242. line = ' ' + line[9:]
  243. else:
  244. line = line[1:]
  245. rtconfig.write('/*%s */\n' % line)
  246. empty_line = 0
  247. else:
  248. empty_line = 0
  249. setting = line.split('=')
  250. if len(setting) >= 2:
  251. if setting[0].startswith('CONFIG_'):
  252. setting[0] = setting[0][7:]
  253. # remove CONFIG_PKG_XX_PATH or CONFIG_PKG_XX_VER
  254. if is_pkg_special_config(setting[0]):
  255. continue
  256. if setting[1] == 'y':
  257. rtconfig.write('#define %s\n' % setting[0])
  258. else:
  259. rtconfig.write('#define %s %s\n' % (setting[0], re.findall(r"^.*?=(.*)$", line)[0]))
  260. if os.path.isfile('rtconfig_project.h'):
  261. rtconfig.write('#include "rtconfig_project.h"\n')
  262. rtconfig.write('\n')
  263. rtconfig.write('#endif\n')
  264. rtconfig.close()
  265. def get_file_md5(file):
  266. MD5 = hashlib.new('md5')
  267. with open(file, 'r') as fp:
  268. MD5.update(fp.read().encode('utf8'))
  269. fp_md5 = MD5.hexdigest()
  270. return fp_md5
  271. # Exclude utestcases
  272. def exclude_utestcases(RTT_ROOT):
  273. if os.path.isfile(os.path.join(RTT_ROOT, 'examples/utest/testcases/Kconfig')):
  274. return
  275. if not os.path.isfile(os.path.join(RTT_ROOT, 'Kconfig')):
  276. return
  277. with open(os.path.join(RTT_ROOT, 'Kconfig'), 'r') as f:
  278. data = f.readlines()
  279. with open(os.path.join(RTT_ROOT, 'Kconfig'), 'w') as f:
  280. for line in data:
  281. if line.find('examples/utest/testcases/Kconfig') == -1:
  282. f.write(line)
  283. # fix locale for kconfiglib
  284. def kconfiglib_fix_locale():
  285. import os
  286. import locale
  287. # Get the list of supported locales
  288. supported_locales = set(locale.locale_alias.keys())
  289. # Check if LANG is set and its value is not in the supported locales
  290. if 'LANG' in os.environ and os.environ['LANG'] not in supported_locales:
  291. os.environ['LANG'] = 'C'
  292. def kconfiglib_check_installed():
  293. try:
  294. import kconfiglib
  295. except ImportError as e:
  296. print("\033[1;31m**ERROR**: Failed to import kconfiglib, " + str(e))
  297. print("")
  298. print("You may need to install it using:")
  299. print(" pip install kconfiglib\033[0m")
  300. print("")
  301. sys.exit(1)
  302. # set PKGS_DIR envrionment
  303. pkg_dir = GetPkgPath()
  304. if os.path.exists(pkg_dir):
  305. os.environ["PKGS_DIR"] = pkg_dir
  306. elif sys.platform != 'win32':
  307. touch_env()
  308. os.environ["PKGS_DIR"] = GetPkgPath()
  309. else:
  310. print("\033[1;33m**WARNING**: PKGS_DIR not found, please install ENV tools\033[0m")
  311. # menuconfig for Linux and Windows
  312. def menuconfig(RTT_ROOT):
  313. kconfiglib_check_installed()
  314. import menuconfig
  315. # Exclude utestcases
  316. exclude_utestcases(RTT_ROOT)
  317. fn = '.config'
  318. fn_old = '.config.old'
  319. sys.argv = ['menuconfig', 'Kconfig']
  320. # fix vscode console
  321. kconfiglib_fix_locale()
  322. menuconfig._main()
  323. if os.path.isfile(fn):
  324. if os.path.isfile(fn_old):
  325. diff_eq = operator.eq(get_file_md5(fn), get_file_md5(fn_old))
  326. else:
  327. diff_eq = False
  328. else:
  329. sys.exit(-1)
  330. # make rtconfig.h
  331. if diff_eq == False:
  332. shutil.copyfile(fn, fn_old)
  333. mk_rtconfig(fn)
  334. # guiconfig for windows and linux
  335. def guiconfig(RTT_ROOT):
  336. kconfiglib_check_installed()
  337. import guiconfig
  338. # Exclude utestcases
  339. exclude_utestcases(RTT_ROOT)
  340. fn = '.config'
  341. fn_old = '.config.old'
  342. sys.argv = ['guiconfig', 'Kconfig']
  343. guiconfig._main()
  344. if os.path.isfile(fn):
  345. if os.path.isfile(fn_old):
  346. diff_eq = operator.eq(get_file_md5(fn), get_file_md5(fn_old))
  347. else:
  348. diff_eq = False
  349. else:
  350. sys.exit(-1)
  351. # make rtconfig.h
  352. if diff_eq == False:
  353. shutil.copyfile(fn, fn_old)
  354. mk_rtconfig(fn)
  355. # defconfig for windows and linux
  356. def defconfig(RTT_ROOT):
  357. kconfiglib_check_installed()
  358. import defconfig
  359. # Exclude utestcases
  360. exclude_utestcases(RTT_ROOT)
  361. fn = '.config'
  362. sys.argv = ['defconfig', '--kconfig', 'Kconfig', '.config']
  363. defconfig.main()
  364. # silent mode, force to make rtconfig.h
  365. mk_rtconfig(fn)
  366. def genconfig():
  367. from SCons.Script import SCons
  368. PreProcessor = SCons.cpp.PreProcessor()
  369. try:
  370. f = open('rtconfig.h', 'r')
  371. contents = f.read()
  372. f.close()
  373. except:
  374. print("Open rtconfig.h file failed.")
  375. PreProcessor.process_contents(contents)
  376. options = PreProcessor.cpp_namespace
  377. try:
  378. f = open('.config', 'w')
  379. for opt, value in options.items():
  380. if type(value) == type(1):
  381. f.write("CONFIG_%s=%d\n" % (opt, value))
  382. if type(value) == type('') and value == '':
  383. f.write("CONFIG_%s=y\n" % opt)
  384. elif type(value) == type('str'):
  385. f.write("CONFIG_%s=%s\n" % (opt, value))
  386. print("Generate .config done!")
  387. f.close()
  388. except:
  389. print("Generate .config file failed.")