idf_tools.py 61 KB

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