env_utility.py 16 KB

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