idf_tools.py 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452
  1. #!/usr/bin/env python
  2. # coding=utf-8
  3. #
  4. # This script helps installing tools required to use the ESP-IDF, and updating PATH
  5. # to use the installed tools. It can also create a Python virtual environment,
  6. # and install Python requirements into it.
  7. # It does not install OS dependencies. It does install tools such as the Xtensa
  8. # GCC toolchain and ESP32 ULP coprocessor toolchain.
  9. #
  10. # By default, downloaded tools will be installed under $HOME/.espressif directory
  11. # (%USERPROFILE%/.espressif on Windows). This path can be modified by setting
  12. # IDF_TOOLS_PATH variable prior to running this tool.
  13. #
  14. # Users do not need to interact with this script directly. In IDF root directory,
  15. # install.sh (.bat) and export.sh (.bat) scripts are provided to invoke this script.
  16. #
  17. # Usage:
  18. #
  19. # * To install the tools, run `idf_tools.py install`.
  20. #
  21. # * To install the Python environment, run `idf_tools.py install-python-env`.
  22. #
  23. # * To start using the tools, run `eval "$(idf_tools.py export)"` — this will update
  24. # the PATH to point to the installed tools and set up other environment variables
  25. # needed by the tools.
  26. #
  27. ###
  28. #
  29. # Copyright 2019 Espressif Systems (Shanghai) PTE LTD
  30. #
  31. # Licensed under the Apache License, Version 2.0 (the "License");
  32. # you may not use this file except in compliance with the License.
  33. # You may obtain a copy of the License at
  34. #
  35. # http://www.apache.org/licenses/LICENSE-2.0
  36. #
  37. # Unless required by applicable law or agreed to in writing, software
  38. # distributed under the License is distributed on an "AS IS" BASIS,
  39. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40. # See the License for the specific language governing permissions and
  41. # limitations under the License.
  42. import json
  43. import os
  44. import subprocess
  45. import sys
  46. import argparse
  47. import re
  48. import platform
  49. import hashlib
  50. import tarfile
  51. import time
  52. import zipfile
  53. import errno
  54. import shutil
  55. import functools
  56. import copy
  57. from collections import OrderedDict, namedtuple
  58. try:
  59. from urllib.request import urlretrieve
  60. except ImportError:
  61. from urllib import urlretrieve
  62. try:
  63. from exceptions import WindowsError
  64. except ImportError:
  65. class WindowsError(OSError):
  66. pass
  67. TOOLS_FILE = 'tools/tools.json'
  68. TOOLS_SCHEMA_FILE = 'tools/tools_schema.json'
  69. TOOLS_FILE_NEW = 'tools/tools.new.json'
  70. TOOLS_FILE_VERSION = 1
  71. IDF_TOOLS_PATH_DEFAULT = os.path.join('~', '.espressif')
  72. UNKNOWN_VERSION = 'unknown'
  73. SUBST_TOOL_PATH_REGEX = re.compile(r'\${TOOL_PATH}')
  74. VERSION_REGEX_REPLACE_DEFAULT = r'\1'
  75. IDF_MAINTAINER = os.environ.get('IDF_MAINTAINER') or False
  76. TODO_MESSAGE = 'TODO'
  77. DOWNLOAD_RETRY_COUNT = 3
  78. URL_PREFIX_MAP_SEPARATOR = ','
  79. IDF_TOOLS_INSTALL_CMD = os.environ.get('IDF_TOOLS_INSTALL_CMD')
  80. IDF_TOOLS_EXPORT_CMD = os.environ.get('IDF_TOOLS_INSTALL_CMD')
  81. PYTHON_PLATFORM = platform.system() + '-' + platform.machine()
  82. # Identifiers used in tools.json for different platforms.
  83. PLATFORM_WIN32 = 'win32'
  84. PLATFORM_WIN64 = 'win64'
  85. PLATFORM_MACOS = 'macos'
  86. PLATFORM_LINUX32 = 'linux-i686'
  87. PLATFORM_LINUX64 = 'linux-amd64'
  88. PLATFORM_LINUX_ARM32 = 'linux-armel'
  89. PLATFORM_LINUX_ARMHF = 'linux-armhf'
  90. PLATFORM_LINUX_ARM64 = 'linux-arm64'
  91. # Mappings from various other names these platforms are known as, to the identifiers above.
  92. # This includes strings produced from "platform.system() + '-' + platform.machine()", see PYTHON_PLATFORM
  93. # definition above.
  94. # This list also includes various strings used in release archives of xtensa-esp32-elf-gcc, OpenOCD, etc.
  95. PLATFORM_FROM_NAME = {
  96. # Windows
  97. PLATFORM_WIN32: PLATFORM_WIN32,
  98. 'Windows-i686': PLATFORM_WIN32,
  99. 'Windows-x86': PLATFORM_WIN32,
  100. PLATFORM_WIN64: PLATFORM_WIN64,
  101. 'Windows-x86_64': PLATFORM_WIN64,
  102. 'Windows-AMD64': PLATFORM_WIN64,
  103. # macOS
  104. PLATFORM_MACOS: PLATFORM_MACOS,
  105. 'osx': PLATFORM_MACOS,
  106. 'darwin': PLATFORM_MACOS,
  107. 'Darwin-x86_64': PLATFORM_MACOS,
  108. # pretend it is x86_64 until Darwin-arm64 tool builds are available:
  109. 'Darwin-arm64': PLATFORM_MACOS,
  110. # Linux
  111. PLATFORM_LINUX64: PLATFORM_LINUX64,
  112. 'linux64': PLATFORM_LINUX64,
  113. 'Linux-x86_64': PLATFORM_LINUX64,
  114. PLATFORM_LINUX32: PLATFORM_LINUX32,
  115. 'linux32': PLATFORM_LINUX32,
  116. 'Linux-i686': PLATFORM_LINUX32,
  117. PLATFORM_LINUX_ARM32: PLATFORM_LINUX_ARM32,
  118. 'Linux-arm': PLATFORM_LINUX_ARM32,
  119. 'Linux-armv7l': PLATFORM_LINUX_ARM32,
  120. PLATFORM_LINUX_ARMHF: PLATFORM_LINUX_ARMHF,
  121. PLATFORM_LINUX_ARM64: PLATFORM_LINUX_ARM64,
  122. 'Linux-arm64': PLATFORM_LINUX_ARM64,
  123. 'Linux-aarch64': PLATFORM_LINUX_ARM64,
  124. 'Linux-armv8l': PLATFORM_LINUX_ARM64,
  125. }
  126. UNKNOWN_PLATFORM = 'unknown'
  127. CURRENT_PLATFORM = PLATFORM_FROM_NAME.get(PYTHON_PLATFORM, UNKNOWN_PLATFORM)
  128. EXPORT_SHELL = 'shell'
  129. EXPORT_KEY_VALUE = 'key-value'
  130. global_quiet = False
  131. global_non_interactive = False
  132. global_idf_path = None
  133. global_idf_tools_path = None
  134. global_tools_json = None
  135. def fatal(text, *args):
  136. if not global_quiet:
  137. sys.stderr.write('ERROR: ' + text + '\n', *args)
  138. def warn(text, *args):
  139. if not global_quiet:
  140. sys.stderr.write('WARNING: ' + text + '\n', *args)
  141. def info(text, f=None, *args):
  142. if not global_quiet:
  143. if f is None:
  144. f = sys.stdout
  145. f.write(text + '\n', *args)
  146. def run_cmd_check_output(cmd, input_text=None, extra_paths=None):
  147. # If extra_paths is given, locate the executable in one of these directories.
  148. # Note: it would seem logical to add extra_paths to env[PATH], instead, and let OS do the job of finding the
  149. # executable for us. However this does not work on Windows: https://bugs.python.org/issue8557.
  150. if extra_paths:
  151. found = False
  152. extensions = ['']
  153. if sys.platform == 'win32':
  154. extensions.append('.exe')
  155. for path in extra_paths:
  156. for ext in extensions:
  157. fullpath = os.path.join(path, cmd[0] + ext)
  158. if os.path.exists(fullpath):
  159. cmd[0] = fullpath
  160. found = True
  161. break
  162. if found:
  163. break
  164. try:
  165. if input_text:
  166. input_text = input_text.encode()
  167. result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, input=input_text)
  168. return result.stdout + result.stderr
  169. except (AttributeError, TypeError):
  170. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
  171. stdout, stderr = p.communicate(input_text)
  172. if p.returncode != 0:
  173. try:
  174. raise subprocess.CalledProcessError(p.returncode, cmd, stdout, stderr)
  175. except TypeError:
  176. raise subprocess.CalledProcessError(p.returncode, cmd, stdout)
  177. return stdout + stderr
  178. def to_shell_specific_paths(paths_list):
  179. if sys.platform == 'win32':
  180. paths_list = [p.replace('/', os.path.sep) if os.path.sep in p else p for p in paths_list]
  181. if 'MSYSTEM' in os.environ:
  182. paths_msys = run_cmd_check_output(['cygpath', '-u', '-f', '-'],
  183. input_text='\n'.join(paths_list))
  184. paths_list = paths_msys.decode().strip().split('\n')
  185. return paths_list
  186. def get_env_for_extra_paths(extra_paths):
  187. """
  188. Return a copy of environment variables dict, prepending paths listed in extra_paths
  189. to the PATH environment variable.
  190. """
  191. env_arg = os.environ.copy()
  192. new_path = os.pathsep.join(extra_paths) + os.pathsep + env_arg['PATH']
  193. if sys.version_info.major == 2:
  194. env_arg['PATH'] = new_path.encode('utf8')
  195. else:
  196. env_arg['PATH'] = new_path
  197. return env_arg
  198. def get_file_size_sha256(filename, block_size=65536):
  199. sha256 = hashlib.sha256()
  200. size = 0
  201. with open(filename, 'rb') as f:
  202. for block in iter(lambda: f.read(block_size), b''):
  203. sha256.update(block)
  204. size += len(block)
  205. return size, sha256.hexdigest()
  206. def report_progress(count, block_size, total_size):
  207. percent = int(count * block_size * 100 / total_size)
  208. percent = min(100, percent)
  209. sys.stdout.write("\r%d%%" % percent)
  210. sys.stdout.flush()
  211. def mkdir_p(path):
  212. try:
  213. os.makedirs(path)
  214. except OSError as exc:
  215. if exc.errno != errno.EEXIST or not os.path.isdir(path):
  216. raise
  217. def unpack(filename, destination):
  218. info('Extracting {0} to {1}'.format(filename, destination))
  219. if filename.endswith('tar.gz'):
  220. archive_obj = tarfile.open(filename, 'r:gz')
  221. elif filename.endswith('zip'):
  222. archive_obj = zipfile.ZipFile(filename)
  223. else:
  224. raise NotImplementedError('Unsupported archive type')
  225. if sys.version_info.major == 2:
  226. # This is a workaround for the issue that unicode destination is not handled:
  227. # https://bugs.python.org/issue17153
  228. destination = str(destination)
  229. archive_obj.extractall(destination)
  230. # Sometimes renaming a directory on Windows (randomly?) causes a PermissionError.
  231. # This is confirmed to be a workaround:
  232. # https://github.com/espressif/esp-idf/issues/3819#issuecomment-515167118
  233. # https://github.com/espressif/esp-idf/issues/4063#issuecomment-531490140
  234. # https://stackoverflow.com/a/43046729
  235. def rename_with_retry(path_from, path_to): # type: (str, str) -> None
  236. retry_count = 20 if sys.platform.startswith('win') else 1
  237. for retry in range(retry_count):
  238. try:
  239. os.rename(path_from, path_to)
  240. return
  241. except OSError:
  242. msg = 'Rename {} to {} failed'.format(path_from, path_to)
  243. if retry == retry_count - 1:
  244. fatal(msg + '. Antivirus software might be causing this. Disabling it temporarily could solve the issue.')
  245. raise
  246. warn(msg + ', retrying...')
  247. # Sleep before the next try in order to pass the antivirus check on Windows
  248. time.sleep(0.5)
  249. def strip_container_dirs(path, levels):
  250. assert levels > 0
  251. # move the original directory out of the way (add a .tmp suffix)
  252. tmp_path = path + '.tmp'
  253. if os.path.exists(tmp_path):
  254. shutil.rmtree(tmp_path)
  255. rename_with_retry(path, tmp_path)
  256. os.mkdir(path)
  257. base_path = tmp_path
  258. # walk given number of levels down
  259. for level in range(levels):
  260. contents = os.listdir(base_path)
  261. if len(contents) > 1:
  262. raise RuntimeError('at level {}, expected 1 entry, got {}'.format(level, contents))
  263. base_path = os.path.join(base_path, contents[0])
  264. if not os.path.isdir(base_path):
  265. raise RuntimeError('at level {}, {} is not a directory'.format(level, contents[0]))
  266. # get the list of directories/files to move
  267. contents = os.listdir(base_path)
  268. for name in contents:
  269. move_from = os.path.join(base_path, name)
  270. move_to = os.path.join(path, name)
  271. rename_with_retry(move_from, move_to)
  272. shutil.rmtree(tmp_path)
  273. class ToolNotFound(RuntimeError):
  274. pass
  275. class ToolExecError(RuntimeError):
  276. pass
  277. class DownloadError(RuntimeError):
  278. pass
  279. class IDFToolDownload(object):
  280. def __init__(self, platform_name, url, size, sha256):
  281. self.platform_name = platform_name
  282. self.url = url
  283. self.size = size
  284. self.sha256 = sha256
  285. self.platform_name = platform_name
  286. @functools.total_ordering
  287. class IDFToolVersion(object):
  288. STATUS_RECOMMENDED = 'recommended'
  289. STATUS_SUPPORTED = 'supported'
  290. STATUS_DEPRECATED = 'deprecated'
  291. STATUS_VALUES = [STATUS_RECOMMENDED, STATUS_SUPPORTED, STATUS_DEPRECATED]
  292. def __init__(self, version, status):
  293. self.version = version
  294. self.status = status
  295. self.downloads = OrderedDict()
  296. self.latest = False
  297. def __lt__(self, other):
  298. if self.status != other.status:
  299. return self.status > other.status
  300. else:
  301. assert not (self.status == IDFToolVersion.STATUS_RECOMMENDED
  302. and other.status == IDFToolVersion.STATUS_RECOMMENDED)
  303. return self.version < other.version
  304. def __eq__(self, other):
  305. return self.status == other.status and self.version == other.version
  306. def add_download(self, platform_name, url, size, sha256):
  307. self.downloads[platform_name] = IDFToolDownload(platform_name, url, size, sha256)
  308. def get_download_for_platform(self, platform_name):
  309. if platform_name in PLATFORM_FROM_NAME.keys():
  310. platform_name = PLATFORM_FROM_NAME[platform_name]
  311. if platform_name in self.downloads.keys():
  312. return self.downloads[platform_name]
  313. if 'any' in self.downloads.keys():
  314. return self.downloads['any']
  315. return None
  316. def compatible_with_platform(self, platform_name=PYTHON_PLATFORM):
  317. return self.get_download_for_platform(platform_name) is not None
  318. OPTIONS_LIST = ['version_cmd',
  319. 'version_regex',
  320. 'version_regex_replace',
  321. 'export_paths',
  322. 'export_vars',
  323. 'install',
  324. 'info_url',
  325. 'license',
  326. 'strip_container_dirs']
  327. IDFToolOptions = namedtuple('IDFToolOptions', OPTIONS_LIST)
  328. class IDFTool(object):
  329. # possible values of 'install' field
  330. INSTALL_ALWAYS = 'always'
  331. INSTALL_ON_REQUEST = 'on_request'
  332. INSTALL_NEVER = 'never'
  333. def __init__(self, name, description, install, info_url, license, version_cmd, version_regex, version_regex_replace=None,
  334. strip_container_dirs=0):
  335. self.name = name
  336. self.description = description
  337. self.versions = OrderedDict()
  338. self.version_in_path = None
  339. self.versions_installed = []
  340. if version_regex_replace is None:
  341. version_regex_replace = VERSION_REGEX_REPLACE_DEFAULT
  342. self.options = IDFToolOptions(version_cmd, version_regex, version_regex_replace,
  343. [], OrderedDict(), install, info_url, license, strip_container_dirs)
  344. self.platform_overrides = []
  345. self._platform = CURRENT_PLATFORM
  346. self._update_current_options()
  347. def copy_for_platform(self, platform):
  348. result = copy.deepcopy(self)
  349. result._platform = platform
  350. result._update_current_options()
  351. return result
  352. def _update_current_options(self):
  353. self._current_options = IDFToolOptions(*self.options)
  354. for override in self.platform_overrides:
  355. if self._platform not in override['platforms']:
  356. continue
  357. override_dict = override.copy()
  358. del override_dict['platforms']
  359. self._current_options = self._current_options._replace(**override_dict)
  360. def add_version(self, version):
  361. assert(type(version) is IDFToolVersion)
  362. self.versions[version.version] = version
  363. def get_path(self):
  364. return os.path.join(global_idf_tools_path, 'tools', self.name)
  365. def get_path_for_version(self, version):
  366. assert(version in self.versions)
  367. return os.path.join(self.get_path(), version)
  368. def get_export_paths(self, version):
  369. tool_path = self.get_path_for_version(version)
  370. return [os.path.join(tool_path, *p) for p in self._current_options.export_paths]
  371. def get_export_vars(self, version):
  372. """
  373. Get the dictionary of environment variables to be exported, for the given version.
  374. Expands:
  375. - ${TOOL_PATH} => the actual path where the version is installed
  376. """
  377. result = {}
  378. for k, v in self._current_options.export_vars.items():
  379. replace_path = self.get_path_for_version(version).replace('\\', '\\\\')
  380. v_repl = re.sub(SUBST_TOOL_PATH_REGEX, replace_path, v)
  381. if v_repl != v:
  382. v_repl = to_shell_specific_paths([v_repl])[0]
  383. result[k] = v_repl
  384. return result
  385. def check_version(self, extra_paths=None):
  386. """
  387. Execute the tool, optionally prepending extra_paths to PATH,
  388. extract the version string and return it as a result.
  389. Raises ToolNotFound if the tool is not found (not present in the paths).
  390. Raises ToolExecError if the tool returns with a non-zero exit code.
  391. Returns 'unknown' if tool returns something from which version string
  392. can not be extracted.
  393. """
  394. # this function can not be called for a different platform
  395. assert self._platform == CURRENT_PLATFORM
  396. cmd = self._current_options.version_cmd
  397. try:
  398. version_cmd_result = run_cmd_check_output(cmd, None, extra_paths)
  399. except OSError:
  400. # tool is not on the path
  401. raise ToolNotFound('Tool {} not found'.format(self.name))
  402. except subprocess.CalledProcessError as e:
  403. raise ToolExecError('returned non-zero exit code ({}) with error message:\n{}'.format(
  404. e.returncode, e.stderr.decode('utf-8',errors='ignore'))) # type: ignore
  405. in_str = version_cmd_result.decode("utf-8")
  406. match = re.search(self._current_options.version_regex, in_str)
  407. if not match:
  408. return UNKNOWN_VERSION
  409. return re.sub(self._current_options.version_regex, self._current_options.version_regex_replace, match.group(0))
  410. def get_install_type(self):
  411. return self._current_options.install
  412. def compatible_with_platform(self):
  413. return any([v.compatible_with_platform() for v in self.versions.values()])
  414. def get_recommended_version(self):
  415. recommended_versions = [k for k, v in self.versions.items()
  416. if v.status == IDFToolVersion.STATUS_RECOMMENDED
  417. and v.compatible_with_platform(self._platform)]
  418. assert len(recommended_versions) <= 1
  419. if recommended_versions:
  420. return recommended_versions[0]
  421. return None
  422. def get_preferred_installed_version(self):
  423. recommended_versions = [k for k in self.versions_installed
  424. if self.versions[k].status == IDFToolVersion.STATUS_RECOMMENDED
  425. and self.versions[k].compatible_with_platform(self._platform)]
  426. assert len(recommended_versions) <= 1
  427. if recommended_versions:
  428. return recommended_versions[0]
  429. return None
  430. def find_installed_versions(self):
  431. """
  432. Checks whether the tool can be found in PATH and in global_idf_tools_path.
  433. Writes results to self.version_in_path and self.versions_installed.
  434. """
  435. # this function can not be called for a different platform
  436. assert self._platform == CURRENT_PLATFORM
  437. # First check if the tool is in system PATH
  438. try:
  439. ver_str = self.check_version()
  440. except ToolNotFound:
  441. # not in PATH
  442. pass
  443. except ToolExecError as e:
  444. warn('tool {} found in path, but {}'.format(
  445. self.name, e))
  446. else:
  447. self.version_in_path = ver_str
  448. # Now check all the versions installed in global_idf_tools_path
  449. self.versions_installed = []
  450. for version, version_obj in self.versions.items():
  451. if not version_obj.compatible_with_platform():
  452. continue
  453. tool_path = self.get_path_for_version(version)
  454. if not os.path.exists(tool_path):
  455. # version not installed
  456. continue
  457. try:
  458. ver_str = self.check_version(self.get_export_paths(version))
  459. except ToolNotFound:
  460. warn('directory for tool {} version {} is present, but tool was not found'.format(
  461. self.name, version))
  462. except ToolExecError as e:
  463. warn('tool {} version {} is installed, but {}'.format(
  464. self.name, version, e))
  465. else:
  466. if ver_str != version:
  467. warn('tool {} version {} is installed, but has reported version {}'.format(
  468. self.name, version, ver_str))
  469. else:
  470. self.versions_installed.append(version)
  471. def download(self, version):
  472. assert(version in self.versions)
  473. download_obj = self.versions[version].get_download_for_platform(self._platform)
  474. if not download_obj:
  475. fatal('No packages for tool {} platform {}!'.format(self.name, self._platform))
  476. raise DownloadError()
  477. url = download_obj.url
  478. archive_name = os.path.basename(url)
  479. local_path = os.path.join(global_idf_tools_path, 'dist', archive_name)
  480. mkdir_p(os.path.dirname(local_path))
  481. if os.path.isfile(local_path):
  482. if not self.check_download_file(download_obj, local_path):
  483. warn('removing downloaded file {0} and downloading again'.format(archive_name))
  484. os.unlink(local_path)
  485. else:
  486. info('file {0} is already downloaded'.format(archive_name))
  487. return
  488. downloaded = False
  489. for retry in range(DOWNLOAD_RETRY_COUNT):
  490. local_temp_path = local_path + '.tmp'
  491. info('Downloading {} to {}'.format(archive_name, local_temp_path))
  492. try:
  493. urlretrieve(url, local_temp_path, report_progress if not global_non_interactive else None)
  494. sys.stdout.write("\rDone\n")
  495. except Exception as e:
  496. # urlretrieve could throw different exceptions, e.g. IOError when the server is down
  497. # Errors are ignored because the downloaded file is checked a couple of lines later.
  498. warn('Download failure {}'.format(e))
  499. sys.stdout.flush()
  500. if not os.path.isfile(local_temp_path) or not self.check_download_file(download_obj, local_temp_path):
  501. warn('Failed to download {} to {}'.format(url, local_temp_path))
  502. continue
  503. rename_with_retry(local_temp_path, local_path)
  504. downloaded = True
  505. break
  506. if not downloaded:
  507. fatal('Failed to download, and retry count has expired')
  508. raise DownloadError()
  509. def install(self, version):
  510. # Currently this is called after calling 'download' method, so here are a few asserts
  511. # for the conditions which should be true once that method is done.
  512. assert (version in self.versions)
  513. download_obj = self.versions[version].get_download_for_platform(self._platform)
  514. assert (download_obj is not None)
  515. archive_name = os.path.basename(download_obj.url)
  516. archive_path = os.path.join(global_idf_tools_path, 'dist', archive_name)
  517. assert (os.path.isfile(archive_path))
  518. dest_dir = self.get_path_for_version(version)
  519. if os.path.exists(dest_dir):
  520. warn('destination path already exists, removing')
  521. shutil.rmtree(dest_dir)
  522. mkdir_p(dest_dir)
  523. unpack(archive_path, dest_dir)
  524. if self._current_options.strip_container_dirs:
  525. strip_container_dirs(dest_dir, self._current_options.strip_container_dirs)
  526. @staticmethod
  527. def check_download_file(download_obj, local_path):
  528. expected_sha256 = download_obj.sha256
  529. expected_size = download_obj.size
  530. file_size, file_sha256 = get_file_size_sha256(local_path)
  531. if file_size != expected_size:
  532. warn('file size mismatch for {}, expected {}, got {}'.format(local_path, expected_size, file_size))
  533. return False
  534. if file_sha256 != expected_sha256:
  535. warn('hash mismatch for {}, expected {}, got {}'.format(local_path, expected_sha256, file_sha256))
  536. return False
  537. return True
  538. @classmethod
  539. def from_json(cls, tool_dict):
  540. # json.load will return 'str' types in Python 3 and 'unicode' in Python 2
  541. expected_str_type = type(u'')
  542. # Validate json fields
  543. tool_name = tool_dict.get('name')
  544. if type(tool_name) is not expected_str_type:
  545. raise RuntimeError('tool_name is not a string')
  546. description = tool_dict.get('description')
  547. if type(description) is not expected_str_type:
  548. raise RuntimeError('description is not a string')
  549. version_cmd = tool_dict.get('version_cmd')
  550. if type(version_cmd) is not list:
  551. raise RuntimeError('version_cmd for tool %s is not a list of strings' % tool_name)
  552. version_regex = tool_dict.get('version_regex')
  553. if type(version_regex) is not expected_str_type or not version_regex:
  554. raise RuntimeError('version_regex for tool %s is not a non-empty string' % tool_name)
  555. version_regex_replace = tool_dict.get('version_regex_replace')
  556. if version_regex_replace and type(version_regex_replace) is not expected_str_type:
  557. raise RuntimeError('version_regex_replace for tool %s is not a string' % tool_name)
  558. export_paths = tool_dict.get('export_paths')
  559. if type(export_paths) is not list:
  560. raise RuntimeError('export_paths for tool %s is not a list' % tool_name)
  561. export_vars = tool_dict.get('export_vars', {})
  562. if type(export_vars) is not dict:
  563. raise RuntimeError('export_vars for tool %s is not a mapping' % tool_name)
  564. versions = tool_dict.get('versions')
  565. if type(versions) is not list:
  566. raise RuntimeError('versions for tool %s is not an array' % tool_name)
  567. install = tool_dict.get('install', False)
  568. if type(install) is not expected_str_type:
  569. raise RuntimeError('install for tool %s is not a string' % tool_name)
  570. info_url = tool_dict.get('info_url', False)
  571. if type(info_url) is not expected_str_type:
  572. raise RuntimeError('info_url for tool %s is not a string' % tool_name)
  573. license = tool_dict.get('license', False)
  574. if type(license) is not expected_str_type:
  575. raise RuntimeError('license for tool %s is not a string' % tool_name)
  576. strip_container_dirs = tool_dict.get('strip_container_dirs', 0)
  577. if strip_container_dirs and type(strip_container_dirs) is not int:
  578. raise RuntimeError('strip_container_dirs for tool %s is not an int' % tool_name)
  579. overrides_list = tool_dict.get('platform_overrides', [])
  580. if type(overrides_list) is not list:
  581. raise RuntimeError('platform_overrides for tool %s is not a list' % tool_name)
  582. # Create the object
  583. tool_obj = cls(tool_name, description, install, info_url, license,
  584. version_cmd, version_regex, version_regex_replace,
  585. strip_container_dirs)
  586. for path in export_paths:
  587. tool_obj.options.export_paths.append(path)
  588. for name, value in export_vars.items():
  589. tool_obj.options.export_vars[name] = value
  590. for index, override in enumerate(overrides_list):
  591. platforms_list = override.get('platforms')
  592. if type(platforms_list) is not list:
  593. raise RuntimeError('platforms for override %d of tool %s is not a list' % (index, tool_name))
  594. install = override.get('install')
  595. if install is not None and type(install) is not expected_str_type:
  596. raise RuntimeError('install for override %d of tool %s is not a string' % (index, tool_name))
  597. version_cmd = override.get('version_cmd')
  598. if version_cmd is not None and type(version_cmd) is not list:
  599. raise RuntimeError('version_cmd for override %d of tool %s is not a list of strings' %
  600. (index, tool_name))
  601. version_regex = override.get('version_regex')
  602. if version_regex is not None and (type(version_regex) is not expected_str_type or not version_regex):
  603. raise RuntimeError('version_regex for override %d of tool %s is not a non-empty string' %
  604. (index, tool_name))
  605. version_regex_replace = override.get('version_regex_replace')
  606. if version_regex_replace is not None and type(version_regex_replace) is not expected_str_type:
  607. raise RuntimeError('version_regex_replace for override %d of tool %s is not a string' %
  608. (index, tool_name))
  609. export_paths = override.get('export_paths')
  610. if export_paths is not None and type(export_paths) is not list:
  611. raise RuntimeError('export_paths for override %d of tool %s is not a list' % (index, tool_name))
  612. export_vars = override.get('export_vars')
  613. if export_vars is not None and type(export_vars) is not dict:
  614. raise RuntimeError('export_vars for override %d of tool %s is not a mapping' % (index, tool_name))
  615. tool_obj.platform_overrides.append(override)
  616. recommended_versions = {}
  617. for version_dict in versions:
  618. version = version_dict.get('name')
  619. if type(version) is not expected_str_type:
  620. raise RuntimeError('version name for tool {} is not a string'.format(tool_name))
  621. version_status = version_dict.get('status')
  622. if type(version_status) is not expected_str_type and version_status not in IDFToolVersion.STATUS_VALUES:
  623. raise RuntimeError('tool {} version {} status is not one of {}', tool_name, version,
  624. IDFToolVersion.STATUS_VALUES)
  625. version_obj = IDFToolVersion(version, version_status)
  626. for platform_id, platform_dict in version_dict.items():
  627. if platform_id in ['name', 'status']:
  628. continue
  629. if platform_id not in PLATFORM_FROM_NAME.keys():
  630. raise RuntimeError('invalid platform %s for tool %s version %s' %
  631. (platform_id, tool_name, version))
  632. version_obj.add_download(platform_id,
  633. platform_dict['url'], platform_dict['size'], platform_dict['sha256'])
  634. if version_status == IDFToolVersion.STATUS_RECOMMENDED:
  635. if platform_id not in recommended_versions:
  636. recommended_versions[platform_id] = []
  637. recommended_versions[platform_id].append(version)
  638. tool_obj.add_version(version_obj)
  639. for platform_id, version_list in recommended_versions.items():
  640. if len(version_list) > 1:
  641. raise RuntimeError('tool {} for platform {} has {} recommended versions'.format(
  642. tool_name, platform_id, len(recommended_versions)))
  643. if install != IDFTool.INSTALL_NEVER and len(recommended_versions) == 0:
  644. raise RuntimeError('required/optional tool {} for platform {} has no recommended versions'.format(
  645. tool_name, platform_id))
  646. tool_obj._update_current_options()
  647. return tool_obj
  648. def to_json(self):
  649. versions_array = []
  650. for version, version_obj in self.versions.items():
  651. version_json = {
  652. 'name': version,
  653. 'status': version_obj.status
  654. }
  655. for platform_id, download in version_obj.downloads.items():
  656. version_json[platform_id] = {
  657. 'url': download.url,
  658. 'size': download.size,
  659. 'sha256': download.sha256
  660. }
  661. versions_array.append(version_json)
  662. overrides_array = self.platform_overrides
  663. tool_json = {
  664. 'name': self.name,
  665. 'description': self.description,
  666. 'export_paths': self.options.export_paths,
  667. 'export_vars': self.options.export_vars,
  668. 'install': self.options.install,
  669. 'info_url': self.options.info_url,
  670. 'license': self.options.license,
  671. 'version_cmd': self.options.version_cmd,
  672. 'version_regex': self.options.version_regex,
  673. 'versions': versions_array,
  674. }
  675. if self.options.version_regex_replace != VERSION_REGEX_REPLACE_DEFAULT:
  676. tool_json['version_regex_replace'] = self.options.version_regex_replace
  677. if overrides_array:
  678. tool_json['platform_overrides'] = overrides_array
  679. if self.options.strip_container_dirs:
  680. tool_json['strip_container_dirs'] = self.options.strip_container_dirs
  681. return tool_json
  682. def load_tools_info():
  683. """
  684. Load tools metadata from tools.json, return a dictionary: tool name - tool info
  685. """
  686. tool_versions_file_name = global_tools_json
  687. with open(tool_versions_file_name, 'r') as f:
  688. tools_info = json.load(f)
  689. return parse_tools_info_json(tools_info)
  690. def parse_tools_info_json(tools_info):
  691. """
  692. Parse and validate the dictionary obtained by loading the tools.json file.
  693. Returns a dictionary of tools (key: tool name, value: IDFTool object).
  694. """
  695. if tools_info['version'] != TOOLS_FILE_VERSION:
  696. raise RuntimeError('Invalid version')
  697. tools_dict = OrderedDict()
  698. tools_array = tools_info.get('tools')
  699. if type(tools_array) is not list:
  700. raise RuntimeError('tools property is missing or not an array')
  701. for tool_dict in tools_array:
  702. tool = IDFTool.from_json(tool_dict)
  703. tools_dict[tool.name] = tool
  704. return tools_dict
  705. def dump_tools_json(tools_info):
  706. tools_array = []
  707. for tool_name, tool_obj in tools_info.items():
  708. tool_json = tool_obj.to_json()
  709. tools_array.append(tool_json)
  710. file_json = {'version': TOOLS_FILE_VERSION, 'tools': tools_array}
  711. return json.dumps(file_json, indent=2, separators=(',', ': '), sort_keys=True)
  712. def get_python_env_path():
  713. python_ver_major_minor = '{}.{}'.format(sys.version_info.major, sys.version_info.minor)
  714. version_file_path = os.path.join(global_idf_path, 'version.txt')
  715. if os.path.exists(version_file_path):
  716. with open(version_file_path, "r") as version_file:
  717. idf_version_str = version_file.read()
  718. else:
  719. idf_version_str = ''
  720. try:
  721. idf_version_str = subprocess.check_output(['git', 'describe'],
  722. cwd=global_idf_path, env=os.environ).decode()
  723. except OSError:
  724. # OSError should cover FileNotFoundError and WindowsError
  725. warn('Git was not found')
  726. except subprocess.CalledProcessError as e:
  727. warn('Git describe was unsuccessul: {}'.format(e.output))
  728. match = re.match(r'^v([0-9]+\.[0-9]+).*', idf_version_str)
  729. if match:
  730. idf_version = match.group(1)
  731. else:
  732. idf_version = None
  733. # fallback when IDF is a shallow clone
  734. try:
  735. with open(os.path.join(global_idf_path, 'components', 'esp_common', 'include', 'esp_idf_version.h')) as f:
  736. m = re.search(r'^#define\s+ESP_IDF_VERSION_MAJOR\s+(\d+).+?^#define\s+ESP_IDF_VERSION_MINOR\s+(\d+)',
  737. f.read(), re.DOTALL | re.MULTILINE)
  738. if m:
  739. idf_version = '.'.join((m.group(1), m.group(2)))
  740. else:
  741. warn('Reading IDF version from C header file failed!')
  742. except Exception as e:
  743. warn('Is it not possible to determine the IDF version: {}'.format(e))
  744. if idf_version is None:
  745. fatal('IDF version cannot be determined')
  746. raise SystemExit(1)
  747. idf_python_env_path = os.path.join(global_idf_tools_path, 'python_env',
  748. 'idf{}_py{}_env'.format(idf_version, python_ver_major_minor))
  749. if sys.platform == 'win32':
  750. subdir = 'Scripts'
  751. python_exe = 'python.exe'
  752. else:
  753. subdir = 'bin'
  754. python_exe = 'python'
  755. idf_python_export_path = os.path.join(idf_python_env_path, subdir)
  756. virtualenv_python = os.path.join(idf_python_export_path, python_exe)
  757. return idf_python_env_path, idf_python_export_path, virtualenv_python
  758. def action_list(args):
  759. tools_info = load_tools_info()
  760. for name, tool in tools_info.items():
  761. if tool.get_install_type() == IDFTool.INSTALL_NEVER:
  762. continue
  763. optional_str = ' (optional)' if tool.get_install_type() == IDFTool.INSTALL_ON_REQUEST else ''
  764. info('* {}: {}{}'.format(name, tool.description, optional_str))
  765. tool.find_installed_versions()
  766. versions_for_platform = {k: v for k, v in tool.versions.items() if v.compatible_with_platform()}
  767. if not versions_for_platform:
  768. info(' (no versions compatible with platform {})'.format(PYTHON_PLATFORM))
  769. continue
  770. versions_sorted = sorted(versions_for_platform.keys(), key=tool.versions.get, reverse=True)
  771. for version in versions_sorted:
  772. version_obj = tool.versions[version]
  773. info(' - {} ({}{})'.format(version, version_obj.status,
  774. ', installed' if version in tool.versions_installed else ''))
  775. def action_check(args):
  776. tools_info = load_tools_info()
  777. not_found_list = []
  778. info('Checking for installed tools...')
  779. for name, tool in tools_info.items():
  780. if tool.get_install_type() == IDFTool.INSTALL_NEVER:
  781. continue
  782. tool_found_somewhere = False
  783. info('Checking tool %s' % name)
  784. tool.find_installed_versions()
  785. if tool.version_in_path:
  786. info(' version found in PATH: %s' % tool.version_in_path)
  787. tool_found_somewhere = True
  788. else:
  789. info(' no version found in PATH')
  790. for version in tool.versions_installed:
  791. info(' version installed in tools directory: %s' % version)
  792. tool_found_somewhere = True
  793. if not tool_found_somewhere and tool.get_install_type() == IDFTool.INSTALL_ALWAYS:
  794. not_found_list.append(name)
  795. if not_found_list:
  796. fatal('The following required tools were not found: ' + ' '.join(not_found_list))
  797. raise SystemExit(1)
  798. def action_export(args):
  799. tools_info = load_tools_info()
  800. all_tools_found = True
  801. export_vars = {}
  802. paths_to_export = []
  803. for name, tool in tools_info.items():
  804. if tool.get_install_type() == IDFTool.INSTALL_NEVER:
  805. continue
  806. tool.find_installed_versions()
  807. if tool.version_in_path:
  808. if tool.version_in_path not in tool.versions:
  809. # unsupported version
  810. if args.prefer_system:
  811. warn('using an unsupported version of tool {} found in PATH: {}'.format(
  812. tool.name, tool.version_in_path))
  813. continue
  814. else:
  815. # unsupported version in path
  816. pass
  817. else:
  818. # supported/deprecated version in PATH, use it
  819. version_obj = tool.versions[tool.version_in_path]
  820. if version_obj.status == IDFToolVersion.STATUS_SUPPORTED:
  821. info('Using a supported version of tool {} found in PATH: {}.'.format(name, tool.version_in_path),
  822. f=sys.stderr)
  823. info('However the recommended version is {}.'.format(tool.get_recommended_version()),
  824. f=sys.stderr)
  825. elif version_obj.status == IDFToolVersion.STATUS_DEPRECATED:
  826. warn('using a deprecated version of tool {} found in PATH: {}'.format(name, tool.version_in_path))
  827. continue
  828. self_restart_cmd = '{} {}{}'.format(sys.executable, __file__,
  829. (' --tools-json ' + args.tools_json) if args.tools_json else '')
  830. self_restart_cmd = to_shell_specific_paths([self_restart_cmd])[0]
  831. if IDF_TOOLS_EXPORT_CMD:
  832. prefer_system_hint = ''
  833. else:
  834. prefer_system_hint = ' To use it, run \'{} export --prefer-system\''.format(self_restart_cmd)
  835. if IDF_TOOLS_INSTALL_CMD:
  836. install_cmd = to_shell_specific_paths([IDF_TOOLS_INSTALL_CMD])[0]
  837. else:
  838. install_cmd = self_restart_cmd + ' install'
  839. if not tool.versions_installed:
  840. if tool.get_install_type() == IDFTool.INSTALL_ALWAYS:
  841. all_tools_found = False
  842. fatal('tool {} has no installed versions. Please run \'{}\' to install it.'.format(
  843. tool.name, install_cmd))
  844. if tool.version_in_path and tool.version_in_path not in tool.versions:
  845. info('An unsupported version of tool {} was found in PATH: {}. '.format(name, tool.version_in_path) +
  846. prefer_system_hint, f=sys.stderr)
  847. continue
  848. else:
  849. # tool is optional, and does not have versions installed
  850. # use whatever is available in PATH
  851. continue
  852. if tool.version_in_path and tool.version_in_path not in tool.versions:
  853. info('Not using an unsupported version of tool {} found in PATH: {}.'.format(
  854. tool.name, tool.version_in_path) + prefer_system_hint, f=sys.stderr)
  855. version_to_use = tool.get_preferred_installed_version()
  856. export_paths = tool.get_export_paths(version_to_use)
  857. if export_paths:
  858. paths_to_export += export_paths
  859. tool_export_vars = tool.get_export_vars(version_to_use)
  860. for k, v in tool_export_vars.items():
  861. old_v = os.environ.get(k)
  862. if old_v is None or old_v != v:
  863. export_vars[k] = v
  864. current_path = os.getenv('PATH')
  865. idf_python_env_path, idf_python_export_path, virtualenv_python = get_python_env_path()
  866. if os.path.exists(virtualenv_python):
  867. idf_python_env_path = to_shell_specific_paths([idf_python_env_path])[0]
  868. if os.getenv('IDF_PYTHON_ENV_PATH') != idf_python_env_path:
  869. export_vars['IDF_PYTHON_ENV_PATH'] = to_shell_specific_paths([idf_python_env_path])[0]
  870. if idf_python_export_path not in current_path:
  871. paths_to_export.append(idf_python_export_path)
  872. idf_tools_dir = os.path.join(global_idf_path, 'tools')
  873. idf_tools_dir = to_shell_specific_paths([idf_tools_dir])[0]
  874. if idf_tools_dir not in current_path:
  875. paths_to_export.append(idf_tools_dir)
  876. if sys.platform == 'win32' and 'MSYSTEM' not in os.environ:
  877. old_path = '%PATH%'
  878. path_sep = ';'
  879. else:
  880. old_path = '$PATH'
  881. # can't trust os.pathsep here, since for Windows Python started from MSYS shell,
  882. # os.pathsep will be ';'
  883. path_sep = ':'
  884. if args.format == EXPORT_SHELL:
  885. if sys.platform == 'win32' and 'MSYSTEM' not in os.environ:
  886. export_format = 'SET "{}={}"'
  887. export_sep = '\n'
  888. else:
  889. export_format = 'export {}="{}"'
  890. export_sep = ';'
  891. elif args.format == EXPORT_KEY_VALUE:
  892. export_format = '{}={}'
  893. export_sep = '\n'
  894. else:
  895. raise NotImplementedError('unsupported export format {}'.format(args.format))
  896. if paths_to_export:
  897. export_vars['PATH'] = path_sep.join(to_shell_specific_paths(paths_to_export) + [old_path])
  898. export_statements = export_sep.join([export_format.format(k, v) for k, v in export_vars.items()])
  899. if export_statements:
  900. print(export_statements)
  901. if not all_tools_found:
  902. raise SystemExit(1)
  903. def apply_url_mirrors(args, tool_download_obj):
  904. apply_mirror_prefix_map(args, tool_download_obj)
  905. apply_github_assets_option(tool_download_obj)
  906. def apply_mirror_prefix_map(args, tool_download_obj):
  907. """Rewrite URL for given tool_obj, given tool_version, and current platform,
  908. if --mirror-prefix-map flag or IDF_MIRROR_PREFIX_MAP environment variable is given.
  909. """
  910. mirror_prefix_map = None
  911. mirror_prefix_map_env = os.getenv('IDF_MIRROR_PREFIX_MAP')
  912. if mirror_prefix_map_env:
  913. mirror_prefix_map = mirror_prefix_map_env.split(';')
  914. if IDF_MAINTAINER and args.mirror_prefix_map:
  915. if mirror_prefix_map:
  916. warn('Both IDF_MIRROR_PREFIX_MAP environment variable and --mirror-prefix-map flag are specified, ' +
  917. 'will use the value from the command line.')
  918. mirror_prefix_map = args.mirror_prefix_map
  919. if mirror_prefix_map and tool_download_obj:
  920. for item in mirror_prefix_map:
  921. if URL_PREFIX_MAP_SEPARATOR not in item:
  922. warn('invalid mirror-prefix-map item (missing \'{}\') {}'.format(URL_PREFIX_MAP_SEPARATOR, item))
  923. continue
  924. search, replace = item.split(URL_PREFIX_MAP_SEPARATOR, 1)
  925. old_url = tool_download_obj.url
  926. new_url = re.sub(search, replace, old_url)
  927. if new_url != old_url:
  928. info('Changed download URL: {} => {}'.format(old_url, new_url))
  929. tool_download_obj.url = new_url
  930. break
  931. def apply_github_assets_option(tool_download_obj):
  932. """ Rewrite URL for given tool_obj if the download URL is an https://github.com/ URL and the variable
  933. IDF_GITHUB_ASSETS is set. The github.com part of the URL will be replaced.
  934. """
  935. try:
  936. github_assets = os.environ["IDF_GITHUB_ASSETS"].strip()
  937. except KeyError:
  938. return # no IDF_GITHUB_ASSETS
  939. if not github_assets: # variable exists but is empty
  940. return
  941. # check no URL qualifier in the mirror URL
  942. if '://' in github_assets:
  943. fatal("IDF_GITHUB_ASSETS shouldn't include any URL qualifier, https:// is assumed")
  944. raise SystemExit(1)
  945. # Strip any trailing / from the mirror URL
  946. github_assets = github_assets.rstrip('/')
  947. old_url = tool_download_obj.url
  948. new_url = re.sub(r'^https://github.com/', 'https://{}/'.format(github_assets), old_url)
  949. if new_url != old_url:
  950. info('Using GitHub assets mirror for URL: {} => {}'.format(old_url, new_url))
  951. tool_download_obj.url = new_url
  952. def action_download(args):
  953. tools_info = load_tools_info()
  954. tools_spec = args.tools
  955. if args.platform not in PLATFORM_FROM_NAME:
  956. fatal('unknown platform: {}' % args.platform)
  957. raise SystemExit(1)
  958. platform = PLATFORM_FROM_NAME[args.platform]
  959. tools_info_for_platform = OrderedDict()
  960. for name, tool_obj in tools_info.items():
  961. tool_for_platform = tool_obj.copy_for_platform(platform)
  962. tools_info_for_platform[name] = tool_for_platform
  963. if not tools_spec or 'required' in tools_spec:
  964. tools_spec = [k for k, v in tools_info_for_platform.items() if v.get_install_type() == IDFTool.INSTALL_ALWAYS]
  965. info('Downloading tools for {}: {}'.format(platform, ', '.join(tools_spec)))
  966. elif 'all' in tools_spec:
  967. tools_spec = [k for k, v in tools_info_for_platform.items() if v.get_install_type() != IDFTool.INSTALL_NEVER]
  968. info('Downloading tools for {}: {}'.format(platform, ', '.join(tools_spec)))
  969. for tool_spec in tools_spec:
  970. if '@' not in tool_spec:
  971. tool_name = tool_spec
  972. tool_version = None
  973. else:
  974. tool_name, tool_version = tool_spec.split('@', 1)
  975. if tool_name not in tools_info_for_platform:
  976. fatal('unknown tool name: {}'.format(tool_name))
  977. raise SystemExit(1)
  978. tool_obj = tools_info_for_platform[tool_name]
  979. if tool_version is not None and tool_version not in tool_obj.versions:
  980. fatal('unknown version for tool {}: {}'.format(tool_name, tool_version))
  981. raise SystemExit(1)
  982. if tool_version is None:
  983. tool_version = tool_obj.get_recommended_version()
  984. if tool_version is None:
  985. fatal('tool {} not found for {} platform'.format(tool_name, platform))
  986. raise SystemExit(1)
  987. tool_spec = '{}@{}'.format(tool_name, tool_version)
  988. info('Downloading {}'.format(tool_spec))
  989. apply_url_mirrors(args, tool_obj.versions[tool_version].get_download_for_platform(platform))
  990. tool_obj.download(tool_version)
  991. def action_install(args):
  992. tools_info = load_tools_info()
  993. tools_spec = args.tools
  994. if not tools_spec or 'required' in tools_spec:
  995. tools_spec = [k for k, v in tools_info.items() if v.get_install_type() == IDFTool.INSTALL_ALWAYS]
  996. info('Installing tools: {}'.format(', '.join(tools_spec)))
  997. elif 'all' in tools_spec:
  998. tools_spec = [k for k, v in tools_info.items() if v.get_install_type() != IDFTool.INSTALL_NEVER]
  999. info('Installing tools: {}'.format(', '.join(tools_spec)))
  1000. for tool_spec in tools_spec:
  1001. if '@' not in tool_spec:
  1002. tool_name = tool_spec
  1003. tool_version = None
  1004. else:
  1005. tool_name, tool_version = tool_spec.split('@', 1)
  1006. if tool_name not in tools_info:
  1007. fatal('unknown tool name: {}'.format(tool_name))
  1008. raise SystemExit(1)
  1009. tool_obj = tools_info[tool_name]
  1010. if not tool_obj.compatible_with_platform():
  1011. fatal('tool {} does not have versions compatible with platform {}'.format(tool_name, CURRENT_PLATFORM))
  1012. raise SystemExit(1)
  1013. if tool_version is not None and tool_version not in tool_obj.versions:
  1014. fatal('unknown version for tool {}: {}'.format(tool_name, tool_version))
  1015. raise SystemExit(1)
  1016. if tool_version is None:
  1017. tool_version = tool_obj.get_recommended_version()
  1018. assert tool_version is not None
  1019. tool_obj.find_installed_versions()
  1020. tool_spec = '{}@{}'.format(tool_name, tool_version)
  1021. if tool_version in tool_obj.versions_installed:
  1022. info('Skipping {} (already installed)'.format(tool_spec))
  1023. continue
  1024. info('Installing {}'.format(tool_spec))
  1025. apply_url_mirrors(args, tool_obj.versions[tool_version].get_download_for_platform(PYTHON_PLATFORM))
  1026. tool_obj.download(tool_version)
  1027. tool_obj.install(tool_version)
  1028. def action_install_python_env(args): # type: ignore
  1029. reinstall = args.reinstall
  1030. idf_python_env_path, _, virtualenv_python = get_python_env_path()
  1031. is_virtualenv = hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix)
  1032. if is_virtualenv and (not os.path.exists(idf_python_env_path) or reinstall):
  1033. fatal('This script was called from a virtual environment, can not create a virtual environment again')
  1034. raise SystemExit(1)
  1035. if os.path.exists(virtualenv_python):
  1036. try:
  1037. subprocess.check_call([virtualenv_python, '--version'], stdout=sys.stdout, stderr=sys.stderr)
  1038. except (OSError, subprocess.CalledProcessError):
  1039. # At this point we can reinstall the virtual environment if it is non-functional. This can happen at least
  1040. # when the Python interpreter was removed which was used to create the virtual environment.
  1041. reinstall = True
  1042. try:
  1043. subprocess.check_call([virtualenv_python, '-m', 'pip', '--version'], stdout=sys.stdout, stderr=sys.stderr)
  1044. except subprocess.CalledProcessError:
  1045. warn('PIP is not available in the virtual environment.')
  1046. # Reinstallation of the virtual environment could help if PIP was installed for the main Python
  1047. reinstall = True
  1048. if reinstall and os.path.exists(idf_python_env_path):
  1049. warn('Removing the existing Python environment in {}'.format(idf_python_env_path))
  1050. shutil.rmtree(idf_python_env_path)
  1051. if not os.path.exists(virtualenv_python):
  1052. info('Creating a new Python environment in {}'.format(idf_python_env_path))
  1053. try:
  1054. import virtualenv # noqa: F401
  1055. except ImportError:
  1056. info('Installing virtualenv')
  1057. subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--user', 'virtualenv'],
  1058. stdout=sys.stdout, stderr=sys.stderr)
  1059. subprocess.check_call([sys.executable, '-m', 'virtualenv', '--seeder', 'pip', idf_python_env_path],
  1060. stdout=sys.stdout, stderr=sys.stderr)
  1061. env_copy = os.environ.copy()
  1062. if env_copy.get('PIP_USER') == 'yes':
  1063. warn('Found PIP_USER="yes" in the environment. Disabling PIP_USER in this shell to install packages into a virtual environment.')
  1064. env_copy['PIP_USER'] = 'no'
  1065. run_args = [virtualenv_python, '-m', 'pip', 'install', '--no-warn-script-location']
  1066. requirements_txt = os.path.join(global_idf_path, 'requirements.txt')
  1067. run_args += ['-r', requirements_txt]
  1068. if args.extra_wheels_dir:
  1069. run_args += ['--find-links', args.extra_wheels_dir]
  1070. info('Installing Python packages from {}'.format(requirements_txt))
  1071. subprocess.check_call(run_args, stdout=sys.stdout, stderr=sys.stderr, env=env_copy)
  1072. def action_add_version(args):
  1073. tools_info = load_tools_info()
  1074. tool_name = args.tool
  1075. tool_obj = tools_info.get(tool_name)
  1076. if not tool_obj:
  1077. info('Creating new tool entry for {}'.format(tool_name))
  1078. tool_obj = IDFTool(tool_name, TODO_MESSAGE, IDFTool.INSTALL_ALWAYS,
  1079. TODO_MESSAGE, TODO_MESSAGE, [TODO_MESSAGE], TODO_MESSAGE)
  1080. tools_info[tool_name] = tool_obj
  1081. version = args.version
  1082. version_obj = tool_obj.versions.get(version)
  1083. if version not in tool_obj.versions:
  1084. info('Creating new version {}'.format(version))
  1085. version_obj = IDFToolVersion(version, IDFToolVersion.STATUS_SUPPORTED)
  1086. tool_obj.versions[version] = version_obj
  1087. url_prefix = args.url_prefix or 'https://%s/' % TODO_MESSAGE
  1088. for file_path in args.files:
  1089. file_name = os.path.basename(file_path)
  1090. # Guess which platform this file is for
  1091. found_platform = None
  1092. for platform_alias, platform_id in PLATFORM_FROM_NAME.items():
  1093. if platform_alias in file_name:
  1094. found_platform = platform_id
  1095. break
  1096. if found_platform is None:
  1097. info('Could not guess platform for file {}'.format(file_name))
  1098. found_platform = TODO_MESSAGE
  1099. # Get file size and calculate the SHA256
  1100. file_size, file_sha256 = get_file_size_sha256(file_path)
  1101. url = url_prefix + file_name
  1102. info('Adding download for platform {}'.format(found_platform))
  1103. info(' size: {}'.format(file_size))
  1104. info(' SHA256: {}'.format(file_sha256))
  1105. info(' URL: {}'.format(url))
  1106. version_obj.add_download(found_platform, url, file_size, file_sha256)
  1107. json_str = dump_tools_json(tools_info)
  1108. if not args.output:
  1109. args.output = os.path.join(global_idf_path, TOOLS_FILE_NEW)
  1110. with open(args.output, 'w') as f:
  1111. f.write(json_str)
  1112. f.write('\n')
  1113. info('Wrote output to {}'.format(args.output))
  1114. def action_rewrite(args):
  1115. tools_info = load_tools_info()
  1116. json_str = dump_tools_json(tools_info)
  1117. if not args.output:
  1118. args.output = os.path.join(global_idf_path, TOOLS_FILE_NEW)
  1119. with open(args.output, 'w') as f:
  1120. f.write(json_str)
  1121. f.write('\n')
  1122. info('Wrote output to {}'.format(args.output))
  1123. def action_validate(args):
  1124. try:
  1125. import jsonschema
  1126. except ImportError:
  1127. fatal('You need to install jsonschema package to use validate command')
  1128. raise SystemExit(1)
  1129. with open(os.path.join(global_idf_path, TOOLS_FILE), 'r') as tools_file:
  1130. tools_json = json.load(tools_file)
  1131. with open(os.path.join(global_idf_path, TOOLS_SCHEMA_FILE), 'r') as schema_file:
  1132. schema_json = json.load(schema_file)
  1133. jsonschema.validate(tools_json, schema_json)
  1134. # on failure, this will raise an exception with a fairly verbose diagnostic message
  1135. def main(argv):
  1136. parser = argparse.ArgumentParser()
  1137. parser.add_argument('--quiet', help='Don\'t output diagnostic messages to stdout/stderr', action='store_true')
  1138. parser.add_argument('--non-interactive', help='Don\'t output interactive messages and questions', action='store_true')
  1139. parser.add_argument('--tools-json', help='Path to the tools.json file to use')
  1140. parser.add_argument('--idf-path', help='ESP-IDF path to use')
  1141. subparsers = parser.add_subparsers(dest='action')
  1142. subparsers.add_parser('list', help='List tools and versions available')
  1143. subparsers.add_parser('check', help='Print summary of tools installed or found in PATH')
  1144. export = subparsers.add_parser('export', help='Output command for setting tool paths, suitable for shell')
  1145. export.add_argument('--format', choices=[EXPORT_SHELL, EXPORT_KEY_VALUE], default=EXPORT_SHELL,
  1146. help='Format of the output: shell (suitable for printing into shell), ' +
  1147. 'or key-value (suitable for parsing by other tools')
  1148. export.add_argument('--prefer-system', help='Normally, if the tool is already present in PATH, ' +
  1149. 'but has an unsupported version, a version from the tools directory ' +
  1150. 'will be used instead. If this flag is given, the version in PATH ' +
  1151. 'will be used.', action='store_true')
  1152. install = subparsers.add_parser('install', help='Download and install tools into the tools directory')
  1153. install.add_argument('tools', metavar='TOOL', nargs='*', default=['required'],
  1154. help='Tools to install. ' +
  1155. 'To install a specific version use <tool_name>@<version> syntax. ' +
  1156. 'Use empty or \'required\' to install required tools, not optional ones. ' +
  1157. 'Use \'all\' to install all tools, including the optional ones.')
  1158. download = subparsers.add_parser('download', help='Download the tools into the dist directory')
  1159. download.add_argument('--platform', help='Platform to download the tools for')
  1160. download.add_argument('tools', metavar='TOOL', nargs='*', default=['required'],
  1161. help='Tools to download. ' +
  1162. 'To download a specific version use <tool_name>@<version> syntax. ' +
  1163. 'Use empty or \'required\' to download required tools, not optional ones. ' +
  1164. 'Use \'all\' to download all tools, including the optional ones.')
  1165. if IDF_MAINTAINER:
  1166. for subparser in [download, install]:
  1167. subparser.add_argument('--mirror-prefix-map', nargs='*',
  1168. help='Pattern to rewrite download URLs, with source and replacement separated by comma.' +
  1169. ' E.g. http://foo.com,http://test.foo.com')
  1170. install_python_env = subparsers.add_parser('install-python-env',
  1171. help='Create Python virtual environment and install the ' +
  1172. 'required Python packages')
  1173. install_python_env.add_argument('--reinstall', help='Discard the previously installed environment',
  1174. action='store_true')
  1175. install_python_env.add_argument('--extra-wheels-dir', help='Additional directories with wheels ' +
  1176. 'to use during installation')
  1177. if IDF_MAINTAINER:
  1178. add_version = subparsers.add_parser('add-version', help='Add or update download info for a version')
  1179. add_version.add_argument('--output', help='Save new tools.json into this file')
  1180. add_version.add_argument('--tool', help='Tool name to set add a version for', required=True)
  1181. add_version.add_argument('--version', help='Version identifier', required=True)
  1182. add_version.add_argument('--url-prefix', help='String to prepend to file names to obtain download URLs')
  1183. add_version.add_argument('files', help='File names of the download artifacts', nargs='*')
  1184. rewrite = subparsers.add_parser('rewrite', help='Load tools.json, validate, and save the result back into JSON')
  1185. rewrite.add_argument('--output', help='Save new tools.json into this file')
  1186. subparsers.add_parser('validate', help='Validate tools.json against schema file')
  1187. args = parser.parse_args(argv)
  1188. if args.action is None:
  1189. parser.print_help()
  1190. parser.exit(1)
  1191. if args.quiet:
  1192. global global_quiet
  1193. global_quiet = True
  1194. if args.non_interactive:
  1195. global global_non_interactive
  1196. global_non_interactive = True
  1197. global global_idf_path
  1198. global_idf_path = os.environ.get('IDF_PATH')
  1199. if args.idf_path:
  1200. global_idf_path = args.idf_path
  1201. if not global_idf_path:
  1202. global_idf_path = os.path.realpath(os.path.join(os.path.dirname(__file__), ".."))
  1203. os.environ['IDF_PATH'] = global_idf_path
  1204. global global_idf_tools_path
  1205. global_idf_tools_path = os.environ.get('IDF_TOOLS_PATH') or os.path.expanduser(IDF_TOOLS_PATH_DEFAULT)
  1206. # On macOS, unset __PYVENV_LAUNCHER__ variable if it is set.
  1207. # Otherwise sys.executable keeps pointing to the system Python, even when a python binary from a virtualenv is invoked.
  1208. # See https://bugs.python.org/issue22490#msg283859.
  1209. os.environ.pop('__PYVENV_LAUNCHER__', None)
  1210. if sys.version_info.major == 2:
  1211. try:
  1212. global_idf_tools_path.decode('ascii')
  1213. except UnicodeDecodeError:
  1214. fatal('IDF_TOOLS_PATH contains non-ASCII characters: {}'.format(global_idf_tools_path) +
  1215. '\nThis is not supported yet with Python 2. ' +
  1216. 'Please set IDF_TOOLS_PATH to a directory with an ASCII name, or switch to Python 3.')
  1217. raise SystemExit(1)
  1218. if CURRENT_PLATFORM == UNKNOWN_PLATFORM:
  1219. fatal('Platform {} appears to be unsupported'.format(PYTHON_PLATFORM))
  1220. raise SystemExit(1)
  1221. global global_tools_json
  1222. if args.tools_json:
  1223. global_tools_json = args.tools_json
  1224. else:
  1225. global_tools_json = os.path.join(global_idf_path, TOOLS_FILE)
  1226. action_func_name = 'action_' + args.action.replace('-', '_')
  1227. action_func = globals()[action_func_name]
  1228. action_func(args)
  1229. if __name__ == '__main__':
  1230. main(sys.argv[1:])