idf_tools.py 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820
  1. #!/usr/bin/env python
  2. # coding=utf-8
  3. #
  4. # SPDX-FileCopyrightText: 2019-2021 Espressif Systems (Shanghai) CO LTD
  5. #
  6. # SPDX-License-Identifier: Apache-2.0
  7. #
  8. # This script helps installing tools required to use the ESP-IDF, and updating PATH
  9. # to use the installed tools. It can also create a Python virtual environment,
  10. # and install Python requirements into it.
  11. # It does not install OS dependencies. It does install tools such as the Xtensa
  12. # GCC toolchain and ESP32 ULP coprocessor toolchain.
  13. #
  14. # By default, downloaded tools will be installed under $HOME/.espressif directory
  15. # (%USERPROFILE%/.espressif on Windows). This path can be modified by setting
  16. # IDF_TOOLS_PATH variable prior to running this tool.
  17. #
  18. # Users do not need to interact with this script directly. In IDF root directory,
  19. # install.sh (.bat) and export.sh (.bat) scripts are provided to invoke this script.
  20. #
  21. # Usage:
  22. #
  23. # * To install the tools, run `idf_tools.py install`.
  24. #
  25. # * To install the Python environment, run `idf_tools.py install-python-env`.
  26. #
  27. # * To start using the tools, run `eval "$(idf_tools.py export)"` — this will update
  28. # the PATH to point to the installed tools and set up other environment variables
  29. # needed by the tools.
  30. import argparse
  31. import contextlib
  32. import copy
  33. import errno
  34. import functools
  35. import hashlib
  36. import json
  37. import os
  38. import platform
  39. import re
  40. import shutil
  41. import ssl
  42. import subprocess
  43. import sys
  44. import tarfile
  45. from collections import OrderedDict, namedtuple
  46. from ssl import SSLContext # noqa: F401
  47. from tarfile import TarFile # noqa: F401
  48. from zipfile import ZipFile
  49. # Important notice: Please keep the lines above compatible with old Pythons so it won't fail with ImportError but with
  50. # a nice message printed by python_version_checker.check()
  51. try:
  52. import python_version_checker
  53. # check the Python version before it will fail with an exception on syntax or package incompatibility.
  54. python_version_checker.check()
  55. except RuntimeError as e:
  56. print(e)
  57. raise SystemExit(1)
  58. from typing import IO, Any, Callable, Dict, List, Optional, Set, Tuple, Union # noqa: F401
  59. from urllib.error import ContentTooShortError
  60. from urllib.request import urlopen
  61. # the following is only for typing annotation
  62. from urllib.response import addinfourl # noqa: F401
  63. try:
  64. from exceptions import WindowsError
  65. except ImportError:
  66. # Unix
  67. class WindowsError(OSError): # type: ignore
  68. pass
  69. TOOLS_FILE = 'tools/tools.json'
  70. TOOLS_SCHEMA_FILE = 'tools/tools_schema.json'
  71. TOOLS_FILE_NEW = 'tools/tools.new.json'
  72. IDF_ENV_FILE = 'idf-env.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_ARMHF = 'linux-armhf'
  93. PLATFORM_LINUX_ARM64 = 'linux-arm64'
  94. # Mappings from various other names these platforms are known as, to the identifiers above.
  95. # This includes strings produced from "platform.system() + '-' + platform.machine()", see PYTHON_PLATFORM
  96. # definition above.
  97. # This list also includes various strings used in release archives of xtensa-esp32-elf-gcc, OpenOCD, etc.
  98. PLATFORM_FROM_NAME = {
  99. # Windows
  100. PLATFORM_WIN32: PLATFORM_WIN32,
  101. 'Windows-i686': PLATFORM_WIN32,
  102. 'Windows-x86': PLATFORM_WIN32,
  103. PLATFORM_WIN64: PLATFORM_WIN64,
  104. 'Windows-x86_64': PLATFORM_WIN64,
  105. 'Windows-AMD64': PLATFORM_WIN64,
  106. # macOS
  107. PLATFORM_MACOS: PLATFORM_MACOS,
  108. 'osx': PLATFORM_MACOS,
  109. 'darwin': PLATFORM_MACOS,
  110. 'Darwin-x86_64': PLATFORM_MACOS,
  111. # pretend it is x86_64 until Darwin-arm64 tool builds are available:
  112. 'Darwin-arm64': PLATFORM_MACOS,
  113. # Linux
  114. PLATFORM_LINUX64: PLATFORM_LINUX64,
  115. 'linux64': PLATFORM_LINUX64,
  116. 'Linux-x86_64': PLATFORM_LINUX64,
  117. 'FreeBSD-amd64': PLATFORM_LINUX64,
  118. PLATFORM_LINUX32: PLATFORM_LINUX32,
  119. 'linux32': PLATFORM_LINUX32,
  120. 'Linux-i686': PLATFORM_LINUX32,
  121. 'FreeBSD-i386': PLATFORM_LINUX32,
  122. PLATFORM_LINUX_ARM32: PLATFORM_LINUX_ARM32,
  123. 'Linux-arm': PLATFORM_LINUX_ARM32,
  124. 'Linux-armv7l': PLATFORM_LINUX_ARM32,
  125. PLATFORM_LINUX_ARMHF: PLATFORM_LINUX_ARMHF,
  126. PLATFORM_LINUX_ARM64: PLATFORM_LINUX_ARM64,
  127. 'Linux-arm64': PLATFORM_LINUX_ARM64,
  128. 'Linux-aarch64': PLATFORM_LINUX_ARM64,
  129. 'Linux-armv8l': PLATFORM_LINUX_ARM64,
  130. }
  131. UNKNOWN_PLATFORM = 'unknown'
  132. CURRENT_PLATFORM = PLATFORM_FROM_NAME.get(PYTHON_PLATFORM, UNKNOWN_PLATFORM)
  133. EXPORT_SHELL = 'shell'
  134. EXPORT_KEY_VALUE = 'key-value'
  135. ISRG_X1_ROOT_CERT = u"""
  136. -----BEGIN CERTIFICATE-----
  137. MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
  138. TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
  139. cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
  140. WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
  141. ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
  142. MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
  143. h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
  144. 0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
  145. A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
  146. T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
  147. B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
  148. B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
  149. KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
  150. OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn
  151. jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw
  152. qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
  153. rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
  154. HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
  155. hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
  156. ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
  157. 3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
  158. NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
  159. ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
  160. TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
  161. jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
  162. oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
  163. 4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
  164. mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
  165. emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
  166. -----END CERTIFICATE-----
  167. """
  168. global_quiet = False
  169. global_non_interactive = False
  170. global_idf_path = None # type: Optional[str]
  171. global_idf_tools_path = None # type: Optional[str]
  172. global_tools_json = None # type: Optional[str]
  173. def fatal(text, *args): # type: (str, str) -> None
  174. if not global_quiet:
  175. sys.stderr.write('ERROR: ' + text + '\n', *args)
  176. def warn(text, *args): # type: (str, str) -> None
  177. if not global_quiet:
  178. sys.stderr.write('WARNING: ' + text + '\n', *args)
  179. def info(text, f=None, *args): # type: (str, Optional[IO[str]], str) -> None
  180. if not global_quiet:
  181. if f is None:
  182. f = sys.stdout
  183. f.write(text + '\n', *args)
  184. def run_cmd_check_output(cmd, input_text=None, extra_paths=None):
  185. # type: (List[str], Optional[str], Optional[List[str]]) -> bytes
  186. # If extra_paths is given, locate the executable in one of these directories.
  187. # Note: it would seem logical to add extra_paths to env[PATH], instead, and let OS do the job of finding the
  188. # executable for us. However this does not work on Windows: https://bugs.python.org/issue8557.
  189. if extra_paths:
  190. found = False
  191. extensions = ['']
  192. if sys.platform == 'win32':
  193. extensions.append('.exe')
  194. for path in extra_paths:
  195. for ext in extensions:
  196. fullpath = os.path.join(path, cmd[0] + ext)
  197. if os.path.exists(fullpath):
  198. cmd[0] = fullpath
  199. found = True
  200. break
  201. if found:
  202. break
  203. try:
  204. input_bytes = None
  205. if input_text:
  206. input_bytes = input_text.encode()
  207. result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, input=input_bytes)
  208. return result.stdout + result.stderr
  209. except (AttributeError, TypeError):
  210. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
  211. stdout, stderr = p.communicate(input_bytes)
  212. if p.returncode != 0:
  213. try:
  214. raise subprocess.CalledProcessError(p.returncode, cmd, stdout, stderr)
  215. except TypeError:
  216. raise subprocess.CalledProcessError(p.returncode, cmd, stdout)
  217. return stdout + stderr
  218. def to_shell_specific_paths(paths_list): # type: (List[str]) -> List[str]
  219. if sys.platform == 'win32':
  220. paths_list = [p.replace('/', os.path.sep) if os.path.sep in p else p for p in paths_list]
  221. return paths_list
  222. def get_env_for_extra_paths(extra_paths): # type: (List[str]) -> Dict[str, str]
  223. """
  224. Return a copy of environment variables dict, prepending paths listed in extra_paths
  225. to the PATH environment variable.
  226. """
  227. env_arg = os.environ.copy()
  228. new_path = os.pathsep.join(extra_paths) + os.pathsep + env_arg['PATH']
  229. if sys.version_info.major == 2:
  230. env_arg['PATH'] = new_path.encode('utf8') # type: ignore
  231. else:
  232. env_arg['PATH'] = new_path
  233. return env_arg
  234. def get_file_size_sha256(filename, block_size=65536): # type: (str, int) -> Tuple[int, str]
  235. sha256 = hashlib.sha256()
  236. size = 0
  237. with open(filename, 'rb') as f:
  238. for block in iter(lambda: f.read(block_size), b''):
  239. sha256.update(block)
  240. size += len(block)
  241. return size, sha256.hexdigest()
  242. def report_progress(count, block_size, total_size): # type: (int, int, int) -> None
  243. percent = int(count * block_size * 100 / total_size)
  244. percent = min(100, percent)
  245. sys.stdout.write('\r%d%%' % percent)
  246. sys.stdout.flush()
  247. def mkdir_p(path): # type: (str) -> None
  248. try:
  249. os.makedirs(path)
  250. except OSError as exc:
  251. if exc.errno != errno.EEXIST or not os.path.isdir(path):
  252. raise
  253. def unpack(filename, destination): # type: (str, str) -> None
  254. info('Extracting {0} to {1}'.format(filename, destination))
  255. if filename.endswith(('.tar.gz', '.tgz')):
  256. archive_obj = tarfile.open(filename, 'r:gz') # type: Union[TarFile, ZipFile]
  257. elif filename.endswith(('.tar.xz')):
  258. archive_obj = tarfile.open(filename, 'r:xz')
  259. elif filename.endswith('zip'):
  260. archive_obj = ZipFile(filename)
  261. else:
  262. raise NotImplementedError('Unsupported archive type')
  263. if sys.version_info.major == 2:
  264. # This is a workaround for the issue that unicode destination is not handled:
  265. # https://bugs.python.org/issue17153
  266. destination = str(destination)
  267. archive_obj.extractall(destination)
  268. def splittype(url): # type: (str) -> Tuple[Optional[str], str]
  269. match = re.match('([^/:]+):(.*)', url, re.DOTALL)
  270. if match:
  271. scheme, data = match.groups()
  272. return scheme.lower(), data
  273. return None, url
  274. # An alternative version of urlretrieve which takes SSL context as an argument
  275. def urlretrieve_ctx(url, filename, reporthook=None, data=None, context=None):
  276. # type: (str, str, Optional[Callable[[int, int, int], None]], Optional[bytes], Optional[SSLContext]) -> Tuple[str, addinfourl]
  277. url_type, path = splittype(url)
  278. # urlopen doesn't have context argument in Python <=2.7.9
  279. extra_urlopen_args = {}
  280. if context:
  281. extra_urlopen_args['context'] = context
  282. with contextlib.closing(urlopen(url, data, **extra_urlopen_args)) as fp: # type: ignore
  283. headers = fp.info()
  284. # Just return the local path and the "headers" for file://
  285. # URLs. No sense in performing a copy unless requested.
  286. if url_type == 'file' and not filename:
  287. return os.path.normpath(path), headers
  288. # Handle temporary file setup.
  289. tfp = open(filename, 'wb')
  290. with tfp:
  291. result = filename, headers
  292. bs = 1024 * 8
  293. size = int(headers.get('content-length', -1))
  294. read = 0
  295. blocknum = 0
  296. if reporthook:
  297. reporthook(blocknum, bs, size)
  298. while True:
  299. block = fp.read(bs)
  300. if not block:
  301. break
  302. read += len(block)
  303. tfp.write(block)
  304. blocknum += 1
  305. if reporthook:
  306. reporthook(blocknum, bs, size)
  307. if size >= 0 and read < size:
  308. raise ContentTooShortError(
  309. 'retrieval incomplete: got only %i out of %i bytes'
  310. % (read, size), result)
  311. return result
  312. # Sometimes renaming a directory on Windows (randomly?) causes a PermissionError.
  313. # This is confirmed to be a workaround:
  314. # https://github.com/espressif/esp-idf/issues/3819#issuecomment-515167118
  315. # https://github.com/espressif/esp-idf/issues/4063#issuecomment-531490140
  316. # https://stackoverflow.com/a/43046729
  317. def rename_with_retry(path_from, path_to): # type: (str, str) -> None
  318. if sys.platform.startswith('win'):
  319. retry_count = 100
  320. else:
  321. retry_count = 1
  322. for retry in range(retry_count):
  323. try:
  324. os.rename(path_from, path_to)
  325. return
  326. except (OSError, WindowsError): # WindowsError until Python 3.3, then OSError
  327. if retry == retry_count - 1:
  328. raise
  329. warn('Rename {} to {} failed, retrying...'.format(path_from, path_to))
  330. def strip_container_dirs(path, levels): # type: (str, int) -> None
  331. assert levels > 0
  332. # move the original directory out of the way (add a .tmp suffix)
  333. tmp_path = path + '.tmp'
  334. if os.path.exists(tmp_path):
  335. shutil.rmtree(tmp_path)
  336. rename_with_retry(path, tmp_path)
  337. os.mkdir(path)
  338. base_path = tmp_path
  339. # walk given number of levels down
  340. for level in range(levels):
  341. contents = os.listdir(base_path)
  342. if len(contents) > 1:
  343. raise RuntimeError('at level {}, expected 1 entry, got {}'.format(level, contents))
  344. base_path = os.path.join(base_path, contents[0])
  345. if not os.path.isdir(base_path):
  346. raise RuntimeError('at level {}, {} is not a directory'.format(level, contents[0]))
  347. # get the list of directories/files to move
  348. contents = os.listdir(base_path)
  349. for name in contents:
  350. move_from = os.path.join(base_path, name)
  351. move_to = os.path.join(path, name)
  352. rename_with_retry(move_from, move_to)
  353. shutil.rmtree(tmp_path)
  354. class ToolNotFound(RuntimeError):
  355. pass
  356. class ToolExecError(RuntimeError):
  357. pass
  358. class DownloadError(RuntimeError):
  359. pass
  360. class IDFToolDownload(object):
  361. def __init__(self, platform_name, url, size, sha256): # type: (str, str, int, str) -> None
  362. self.platform_name = platform_name
  363. self.url = url
  364. self.size = size
  365. self.sha256 = sha256
  366. self.platform_name = platform_name
  367. @functools.total_ordering
  368. class IDFToolVersion(object):
  369. STATUS_RECOMMENDED = 'recommended'
  370. STATUS_SUPPORTED = 'supported'
  371. STATUS_DEPRECATED = 'deprecated'
  372. STATUS_VALUES = [STATUS_RECOMMENDED, STATUS_SUPPORTED, STATUS_DEPRECATED]
  373. def __init__(self, version, status): # type: (str, str) -> None
  374. self.version = version
  375. self.status = status
  376. self.downloads = OrderedDict() # type: OrderedDict[str, IDFToolDownload]
  377. self.latest = False
  378. def __lt__(self, other): # type: (IDFToolVersion) -> bool
  379. if self.status != other.status:
  380. return self.status > other.status
  381. else:
  382. assert not (self.status == IDFToolVersion.STATUS_RECOMMENDED
  383. and other.status == IDFToolVersion.STATUS_RECOMMENDED)
  384. return self.version < other.version
  385. def __eq__(self, other): # type: (object) -> bool
  386. if not isinstance(other, IDFToolVersion):
  387. return NotImplemented
  388. return self.status == other.status and self.version == other.version
  389. def add_download(self, platform_name, url, size, sha256): # type: (str, str, int, str) -> None
  390. self.downloads[platform_name] = IDFToolDownload(platform_name, url, size, sha256)
  391. def get_download_for_platform(self, platform_name): # type: (str) -> Optional[IDFToolDownload]
  392. if platform_name in PLATFORM_FROM_NAME.keys():
  393. platform_name = PLATFORM_FROM_NAME[platform_name]
  394. if platform_name in self.downloads.keys():
  395. return self.downloads[platform_name]
  396. if 'any' in self.downloads.keys():
  397. return self.downloads['any']
  398. return None
  399. def compatible_with_platform(self, platform_name=PYTHON_PLATFORM):
  400. # type: (str) -> bool
  401. return self.get_download_for_platform(platform_name) is not None
  402. def get_supported_platforms(self): # type: () -> set[str]
  403. return set(self.downloads.keys())
  404. IDFToolOptions = namedtuple('IDFToolOptions', [
  405. 'version_cmd',
  406. 'version_regex',
  407. 'version_regex_replace',
  408. 'export_paths',
  409. 'export_vars',
  410. 'install',
  411. 'info_url',
  412. 'license',
  413. 'strip_container_dirs',
  414. 'supported_targets'])
  415. class IDFTool(object):
  416. # possible values of 'install' field
  417. INSTALL_ALWAYS = 'always'
  418. INSTALL_ON_REQUEST = 'on_request'
  419. INSTALL_NEVER = 'never'
  420. def __init__(self, name, description, install, info_url, license, version_cmd, version_regex, supported_targets, version_regex_replace=None,
  421. strip_container_dirs=0):
  422. # type: (str, str, str, str, str, List[str], str, List[str], Optional[str], int) -> None
  423. self.name = name
  424. self.description = description
  425. self.versions = OrderedDict() # type: Dict[str, IDFToolVersion]
  426. self.version_in_path = None # type: Optional[str]
  427. self.versions_installed = [] # type: List[str]
  428. if version_regex_replace is None:
  429. version_regex_replace = VERSION_REGEX_REPLACE_DEFAULT
  430. self.options = IDFToolOptions(version_cmd, version_regex, version_regex_replace,
  431. [], OrderedDict(), install, info_url, license, strip_container_dirs, supported_targets) # type: ignore
  432. self.platform_overrides = [] # type: List[Dict[str, str]]
  433. self._platform = CURRENT_PLATFORM
  434. self._update_current_options()
  435. def copy_for_platform(self, platform): # type: (str) -> IDFTool
  436. result = copy.deepcopy(self)
  437. result._platform = platform
  438. result._update_current_options()
  439. return result
  440. def _update_current_options(self): # type: () -> None
  441. self._current_options = IDFToolOptions(*self.options)
  442. for override in self.platform_overrides:
  443. if self._platform not in override['platforms']:
  444. continue
  445. override_dict = override.copy()
  446. del override_dict['platforms']
  447. self._current_options = self._current_options._replace(**override_dict) # type: ignore
  448. def add_version(self, version): # type: (IDFToolVersion) -> None
  449. assert(type(version) is IDFToolVersion)
  450. self.versions[version.version] = version
  451. def get_path(self): # type: () -> str
  452. return os.path.join(global_idf_tools_path, 'tools', self.name) # type: ignore
  453. def get_path_for_version(self, version): # type: (str) -> str
  454. assert(version in self.versions)
  455. return os.path.join(self.get_path(), version)
  456. def get_export_paths(self, version): # type: (str) -> List[str]
  457. tool_path = self.get_path_for_version(version)
  458. return [os.path.join(tool_path, *p) for p in self._current_options.export_paths] # type: ignore
  459. def get_export_vars(self, version): # type: (str) -> Dict[str, str]
  460. """
  461. Get the dictionary of environment variables to be exported, for the given version.
  462. Expands:
  463. - ${TOOL_PATH} => the actual path where the version is installed
  464. """
  465. result = {}
  466. for k, v in self._current_options.export_vars.items(): # type: ignore
  467. replace_path = self.get_path_for_version(version).replace('\\', '\\\\')
  468. v_repl = re.sub(SUBST_TOOL_PATH_REGEX, replace_path, v)
  469. if v_repl != v:
  470. v_repl = to_shell_specific_paths([v_repl])[0]
  471. result[k] = v_repl
  472. return result
  473. def check_version(self, extra_paths=None): # type: (Optional[List[str]]) -> str
  474. """
  475. Execute the tool, optionally prepending extra_paths to PATH,
  476. extract the version string and return it as a result.
  477. Raises ToolNotFound if the tool is not found (not present in the paths).
  478. Raises ToolExecError if the tool returns with a non-zero exit code.
  479. Returns 'unknown' if tool returns something from which version string
  480. can not be extracted.
  481. """
  482. # this function can not be called for a different platform
  483. assert self._platform == CURRENT_PLATFORM
  484. cmd = self._current_options.version_cmd # type: ignore
  485. try:
  486. version_cmd_result = run_cmd_check_output(cmd, None, extra_paths)
  487. except OSError:
  488. # tool is not on the path
  489. raise ToolNotFound('Tool {} not found'.format(self.name))
  490. except subprocess.CalledProcessError as e:
  491. raise ToolExecError('returned non-zero exit code ({}) with error message:\n{}'.format(
  492. e.returncode, e.stderr.decode('utf-8',errors='ignore'))) # type: ignore
  493. in_str = version_cmd_result.decode('utf-8')
  494. match = re.search(self._current_options.version_regex, in_str) # type: ignore
  495. if not match:
  496. return UNKNOWN_VERSION
  497. return re.sub(self._current_options.version_regex, self._current_options.version_regex_replace, match.group(0)) # type: ignore
  498. def get_install_type(self): # type: () -> Callable[[str], None]
  499. return self._current_options.install # type: ignore
  500. def get_supported_targets(self): # type: () -> list[str]
  501. return self._current_options.supported_targets # type: ignore
  502. def compatible_with_platform(self): # type: () -> bool
  503. return any([v.compatible_with_platform() for v in self.versions.values()])
  504. def get_supported_platforms(self): # type: () -> Set[str]
  505. result = set()
  506. for v in self.versions.values():
  507. result.update(v.get_supported_platforms())
  508. return result
  509. def get_recommended_version(self): # type: () -> Optional[str]
  510. recommended_versions = [k for k, v in self.versions.items()
  511. if v.status == IDFToolVersion.STATUS_RECOMMENDED
  512. and v.compatible_with_platform(self._platform)]
  513. assert len(recommended_versions) <= 1
  514. if recommended_versions:
  515. return recommended_versions[0]
  516. return None
  517. def get_preferred_installed_version(self): # type: () -> Optional[str]
  518. recommended_versions = [k for k in self.versions_installed
  519. if self.versions[k].status == IDFToolVersion.STATUS_RECOMMENDED
  520. and self.versions[k].compatible_with_platform(self._platform)]
  521. assert len(recommended_versions) <= 1
  522. if recommended_versions:
  523. return recommended_versions[0]
  524. return None
  525. def find_installed_versions(self): # type: () -> None
  526. """
  527. Checks whether the tool can be found in PATH and in global_idf_tools_path.
  528. Writes results to self.version_in_path and self.versions_installed.
  529. """
  530. # this function can not be called for a different platform
  531. assert self._platform == CURRENT_PLATFORM
  532. # First check if the tool is in system PATH
  533. try:
  534. ver_str = self.check_version()
  535. except ToolNotFound:
  536. # not in PATH
  537. pass
  538. except ToolExecError as e:
  539. warn('tool {} found in path, but {}'.format(
  540. self.name, e))
  541. else:
  542. self.version_in_path = ver_str
  543. # Now check all the versions installed in global_idf_tools_path
  544. self.versions_installed = []
  545. for version, version_obj in self.versions.items():
  546. if not version_obj.compatible_with_platform():
  547. continue
  548. tool_path = self.get_path_for_version(version)
  549. if not os.path.exists(tool_path):
  550. # version not installed
  551. continue
  552. try:
  553. ver_str = self.check_version(self.get_export_paths(version))
  554. except ToolNotFound:
  555. warn('directory for tool {} version {} is present, but tool was not found'.format(
  556. self.name, version))
  557. except ToolExecError as e:
  558. warn('tool {} version {} is installed, but {}'.format(
  559. self.name, version, e))
  560. else:
  561. if ver_str != version:
  562. warn('tool {} version {} is installed, but has reported version {}'.format(
  563. self.name, version, ver_str))
  564. else:
  565. self.versions_installed.append(version)
  566. def download(self, version): # type: (str) -> None
  567. assert(version in self.versions)
  568. download_obj = self.versions[version].get_download_for_platform(self._platform)
  569. if not download_obj:
  570. fatal('No packages for tool {} platform {}!'.format(self.name, self._platform))
  571. raise DownloadError()
  572. url = download_obj.url
  573. archive_name = os.path.basename(url)
  574. local_path = os.path.join(global_idf_tools_path, 'dist', archive_name) # type: ignore
  575. mkdir_p(os.path.dirname(local_path))
  576. if os.path.isfile(local_path):
  577. if not self.check_download_file(download_obj, local_path):
  578. warn('removing downloaded file {0} and downloading again'.format(archive_name))
  579. os.unlink(local_path)
  580. else:
  581. info('file {0} is already downloaded'.format(archive_name))
  582. return
  583. downloaded = False
  584. for retry in range(DOWNLOAD_RETRY_COUNT):
  585. local_temp_path = local_path + '.tmp'
  586. info('Downloading {} to {}'.format(archive_name, local_temp_path))
  587. try:
  588. ctx = None
  589. # For dl.espressif.com, add the ISRG x1 root certificate.
  590. # This works around the issue with outdated certificate stores in some installations.
  591. if 'dl.espressif.com' in url:
  592. try:
  593. ctx = ssl.create_default_context()
  594. ctx.load_verify_locations(cadata=ISRG_X1_ROOT_CERT)
  595. except AttributeError:
  596. # no ssl.create_default_context or load_verify_locations cadata argument
  597. # in Python <=2.7.8
  598. pass
  599. urlretrieve_ctx(url, local_temp_path, report_progress if not global_non_interactive else None, context=ctx)
  600. sys.stdout.write('\rDone\n')
  601. except Exception as e:
  602. # urlretrieve could throw different exceptions, e.g. IOError when the server is down
  603. # Errors are ignored because the downloaded file is checked a couple of lines later.
  604. warn('Download failure {}'.format(e))
  605. sys.stdout.flush()
  606. if not os.path.isfile(local_temp_path) or not self.check_download_file(download_obj, local_temp_path):
  607. warn('Failed to download {} to {}'.format(url, local_temp_path))
  608. continue
  609. rename_with_retry(local_temp_path, local_path)
  610. downloaded = True
  611. break
  612. if not downloaded:
  613. fatal('Failed to download, and retry count has expired')
  614. raise DownloadError()
  615. def install(self, version): # type: (str) -> None
  616. # Currently this is called after calling 'download' method, so here are a few asserts
  617. # for the conditions which should be true once that method is done.
  618. assert (version in self.versions)
  619. download_obj = self.versions[version].get_download_for_platform(self._platform)
  620. assert (download_obj is not None)
  621. archive_name = os.path.basename(download_obj.url)
  622. archive_path = os.path.join(global_idf_tools_path, 'dist', archive_name) # type: ignore
  623. assert (os.path.isfile(archive_path))
  624. dest_dir = self.get_path_for_version(version)
  625. if os.path.exists(dest_dir):
  626. warn('destination path already exists, removing')
  627. shutil.rmtree(dest_dir)
  628. mkdir_p(dest_dir)
  629. unpack(archive_path, dest_dir)
  630. if self._current_options.strip_container_dirs: # type: ignore
  631. strip_container_dirs(dest_dir, self._current_options.strip_container_dirs) # type: ignore
  632. @staticmethod
  633. def check_download_file(download_obj, local_path): # type: (IDFToolDownload, str) -> bool
  634. expected_sha256 = download_obj.sha256
  635. expected_size = download_obj.size
  636. file_size, file_sha256 = get_file_size_sha256(local_path)
  637. if file_size != expected_size:
  638. warn('file size mismatch for {}, expected {}, got {}'.format(local_path, expected_size, file_size))
  639. return False
  640. if file_sha256 != expected_sha256:
  641. warn('hash mismatch for {}, expected {}, got {}'.format(local_path, expected_sha256, file_sha256))
  642. return False
  643. return True
  644. @classmethod
  645. def from_json(cls, tool_dict): # type: (Dict[str, Union[str, List[str], Dict[str, str]]]) -> IDFTool
  646. # json.load will return 'str' types in Python 3 and 'unicode' in Python 2
  647. expected_str_type = type(u'')
  648. # Validate json fields
  649. tool_name = tool_dict.get('name') # type: ignore
  650. if type(tool_name) is not expected_str_type:
  651. raise RuntimeError('tool_name is not a string')
  652. description = tool_dict.get('description') # type: ignore
  653. if type(description) is not expected_str_type:
  654. raise RuntimeError('description is not a string')
  655. version_cmd = tool_dict.get('version_cmd')
  656. if type(version_cmd) is not list:
  657. raise RuntimeError('version_cmd for tool %s is not a list of strings' % tool_name)
  658. version_regex = tool_dict.get('version_regex')
  659. if type(version_regex) is not expected_str_type or not version_regex:
  660. raise RuntimeError('version_regex for tool %s is not a non-empty string' % tool_name)
  661. version_regex_replace = tool_dict.get('version_regex_replace')
  662. if version_regex_replace and type(version_regex_replace) is not expected_str_type:
  663. raise RuntimeError('version_regex_replace for tool %s is not a string' % tool_name)
  664. export_paths = tool_dict.get('export_paths')
  665. if type(export_paths) is not list:
  666. raise RuntimeError('export_paths for tool %s is not a list' % tool_name)
  667. export_vars = tool_dict.get('export_vars', {}) # type: ignore
  668. if type(export_vars) is not dict:
  669. raise RuntimeError('export_vars for tool %s is not a mapping' % tool_name)
  670. versions = tool_dict.get('versions')
  671. if type(versions) is not list:
  672. raise RuntimeError('versions for tool %s is not an array' % tool_name)
  673. install = tool_dict.get('install', False) # type: ignore
  674. if type(install) is not expected_str_type:
  675. raise RuntimeError('install for tool %s is not a string' % tool_name)
  676. info_url = tool_dict.get('info_url', False) # type: ignore
  677. if type(info_url) is not expected_str_type:
  678. raise RuntimeError('info_url for tool %s is not a string' % tool_name)
  679. license = tool_dict.get('license', False) # type: ignore
  680. if type(license) is not expected_str_type:
  681. raise RuntimeError('license for tool %s is not a string' % tool_name)
  682. strip_container_dirs = tool_dict.get('strip_container_dirs', 0)
  683. if strip_container_dirs and type(strip_container_dirs) is not int:
  684. raise RuntimeError('strip_container_dirs for tool %s is not an int' % tool_name)
  685. overrides_list = tool_dict.get('platform_overrides', []) # type: ignore
  686. if type(overrides_list) is not list:
  687. raise RuntimeError('platform_overrides for tool %s is not a list' % tool_name)
  688. supported_targets = tool_dict.get('supported_targets')
  689. if not isinstance(supported_targets, list):
  690. raise RuntimeError('supported_targets for tool %s is not a list of strings' % tool_name)
  691. # Create the object
  692. tool_obj = cls(tool_name, description, install, info_url, license, # type: ignore
  693. version_cmd, version_regex, supported_targets, version_regex_replace, # type: ignore
  694. strip_container_dirs) # type: ignore
  695. for path in export_paths: # type: ignore
  696. tool_obj.options.export_paths.append(path) # type: ignore
  697. for name, value in export_vars.items(): # type: ignore
  698. tool_obj.options.export_vars[name] = value # type: ignore
  699. for index, override in enumerate(overrides_list):
  700. platforms_list = override.get('platforms') # type: ignore
  701. if type(platforms_list) is not list:
  702. raise RuntimeError('platforms for override %d of tool %s is not a list' % (index, tool_name))
  703. install = override.get('install') # type: ignore
  704. if install is not None and type(install) is not expected_str_type:
  705. raise RuntimeError('install for override %d of tool %s is not a string' % (index, tool_name))
  706. version_cmd = override.get('version_cmd') # type: ignore
  707. if version_cmd is not None and type(version_cmd) is not list:
  708. raise RuntimeError('version_cmd for override %d of tool %s is not a list of strings' %
  709. (index, tool_name))
  710. version_regex = override.get('version_regex') # type: ignore
  711. if version_regex is not None and (type(version_regex) is not expected_str_type or not version_regex):
  712. raise RuntimeError('version_regex for override %d of tool %s is not a non-empty string' %
  713. (index, tool_name))
  714. version_regex_replace = override.get('version_regex_replace') # type: ignore
  715. if version_regex_replace is not None and type(version_regex_replace) is not expected_str_type:
  716. raise RuntimeError('version_regex_replace for override %d of tool %s is not a string' %
  717. (index, tool_name))
  718. export_paths = override.get('export_paths') # type: ignore
  719. if export_paths is not None and type(export_paths) is not list:
  720. raise RuntimeError('export_paths for override %d of tool %s is not a list' % (index, tool_name))
  721. export_vars = override.get('export_vars') # type: ignore
  722. if export_vars is not None and type(export_vars) is not dict:
  723. raise RuntimeError('export_vars for override %d of tool %s is not a mapping' % (index, tool_name))
  724. tool_obj.platform_overrides.append(override) # type: ignore
  725. recommended_versions = {} # type: dict[str, list[str]]
  726. for version_dict in versions: # type: ignore
  727. version = version_dict.get('name') # type: ignore
  728. if type(version) is not expected_str_type:
  729. raise RuntimeError('version name for tool {} is not a string'.format(tool_name))
  730. version_status = version_dict.get('status') # type: ignore
  731. if type(version_status) is not expected_str_type and version_status not in IDFToolVersion.STATUS_VALUES:
  732. raise RuntimeError('tool {} version {} status is not one of {}', tool_name, version,
  733. IDFToolVersion.STATUS_VALUES)
  734. version_obj = IDFToolVersion(version, version_status)
  735. for platform_id, platform_dict in version_dict.items(): # type: ignore
  736. if platform_id in ['name', 'status']:
  737. continue
  738. if platform_id not in PLATFORM_FROM_NAME.keys():
  739. raise RuntimeError('invalid platform %s for tool %s version %s' %
  740. (platform_id, tool_name, version))
  741. version_obj.add_download(platform_id,
  742. platform_dict['url'], platform_dict['size'], platform_dict['sha256'])
  743. if version_status == IDFToolVersion.STATUS_RECOMMENDED:
  744. if platform_id not in recommended_versions:
  745. recommended_versions[platform_id] = []
  746. recommended_versions[platform_id].append(version)
  747. tool_obj.add_version(version_obj)
  748. for platform_id, version_list in recommended_versions.items():
  749. if len(version_list) > 1:
  750. raise RuntimeError('tool {} for platform {} has {} recommended versions'.format(
  751. tool_name, platform_id, len(recommended_versions)))
  752. if install != IDFTool.INSTALL_NEVER and len(recommended_versions) == 0:
  753. raise RuntimeError('required/optional tool {} for platform {} has no recommended versions'.format(
  754. tool_name, platform_id))
  755. tool_obj._update_current_options()
  756. return tool_obj
  757. def to_json(self): # type: ignore
  758. versions_array = []
  759. for version, version_obj in self.versions.items():
  760. version_json = {
  761. 'name': version,
  762. 'status': version_obj.status
  763. }
  764. for platform_id, download in version_obj.downloads.items():
  765. version_json[platform_id] = {
  766. 'url': download.url,
  767. 'size': download.size,
  768. 'sha256': download.sha256
  769. }
  770. versions_array.append(version_json)
  771. overrides_array = self.platform_overrides
  772. tool_json = {
  773. 'name': self.name,
  774. 'description': self.description,
  775. 'export_paths': self.options.export_paths,
  776. 'export_vars': self.options.export_vars,
  777. 'install': self.options.install,
  778. 'info_url': self.options.info_url,
  779. 'license': self.options.license,
  780. 'version_cmd': self.options.version_cmd,
  781. 'version_regex': self.options.version_regex,
  782. 'supported_targets': self.options.supported_targets,
  783. 'versions': versions_array,
  784. }
  785. if self.options.version_regex_replace != VERSION_REGEX_REPLACE_DEFAULT:
  786. tool_json['version_regex_replace'] = self.options.version_regex_replace
  787. if overrides_array:
  788. tool_json['platform_overrides'] = overrides_array
  789. if self.options.strip_container_dirs:
  790. tool_json['strip_container_dirs'] = self.options.strip_container_dirs
  791. return tool_json
  792. def load_tools_info(): # type: () -> dict[str, IDFTool]
  793. """
  794. Load tools metadata from tools.json, return a dictionary: tool name - tool info
  795. """
  796. tool_versions_file_name = global_tools_json
  797. with open(tool_versions_file_name, 'r') as f: # type: ignore
  798. tools_info = json.load(f)
  799. return parse_tools_info_json(tools_info) # type: ignore
  800. def parse_tools_info_json(tools_info): # type: ignore
  801. """
  802. Parse and validate the dictionary obtained by loading the tools.json file.
  803. Returns a dictionary of tools (key: tool name, value: IDFTool object).
  804. """
  805. if tools_info['version'] != TOOLS_FILE_VERSION:
  806. raise RuntimeError('Invalid version')
  807. tools_dict = OrderedDict()
  808. tools_array = tools_info.get('tools')
  809. if type(tools_array) is not list:
  810. raise RuntimeError('tools property is missing or not an array')
  811. for tool_dict in tools_array:
  812. tool = IDFTool.from_json(tool_dict)
  813. tools_dict[tool.name] = tool
  814. return tools_dict
  815. def dump_tools_json(tools_info): # type: ignore
  816. tools_array = []
  817. for tool_name, tool_obj in tools_info.items():
  818. tool_json = tool_obj.to_json()
  819. tools_array.append(tool_json)
  820. file_json = {'version': TOOLS_FILE_VERSION, 'tools': tools_array}
  821. return json.dumps(file_json, indent=2, separators=(',', ': '), sort_keys=True)
  822. def get_python_env_path(): # type: () -> Tuple[str, str, str]
  823. python_ver_major_minor = '{}.{}'.format(sys.version_info.major, sys.version_info.minor)
  824. version_file_path = os.path.join(global_idf_path, 'version.txt') # type: ignore
  825. if os.path.exists(version_file_path):
  826. with open(version_file_path, 'r') as version_file:
  827. idf_version_str = version_file.read()
  828. else:
  829. idf_version_str = ''
  830. try:
  831. idf_version_str = subprocess.check_output(['git', 'describe'],
  832. cwd=global_idf_path, env=os.environ).decode()
  833. except OSError:
  834. # OSError should cover FileNotFoundError and WindowsError
  835. warn('Git was not found')
  836. except subprocess.CalledProcessError as e:
  837. warn('Git describe was unsuccessful: {}'.format(e.output))
  838. match = re.match(r'^v([0-9]+\.[0-9]+).*', idf_version_str)
  839. if match:
  840. idf_version = match.group(1) # type: Optional[str]
  841. else:
  842. idf_version = None
  843. # fallback when IDF is a shallow clone
  844. try:
  845. with open(os.path.join(global_idf_path, 'components', 'esp_common', 'include', 'esp_idf_version.h')) as f: # type: ignore
  846. m = re.search(r'^#define\s+ESP_IDF_VERSION_MAJOR\s+(\d+).+?^#define\s+ESP_IDF_VERSION_MINOR\s+(\d+)',
  847. f.read(), re.DOTALL | re.MULTILINE)
  848. if m:
  849. idf_version = '.'.join((m.group(1), m.group(2)))
  850. else:
  851. warn('Reading IDF version from C header file failed!')
  852. except Exception as e:
  853. warn('Is it not possible to determine the IDF version: {}'.format(e))
  854. if idf_version is None:
  855. fatal('IDF version cannot be determined')
  856. raise SystemExit(1)
  857. idf_python_env_path = os.path.join(global_idf_tools_path, 'python_env', # type: ignore
  858. 'idf{}_py{}_env'.format(idf_version, python_ver_major_minor))
  859. if sys.platform == 'win32':
  860. subdir = 'Scripts'
  861. python_exe = 'python.exe'
  862. else:
  863. subdir = 'bin'
  864. python_exe = 'python'
  865. idf_python_export_path = os.path.join(idf_python_env_path, subdir)
  866. virtualenv_python = os.path.join(idf_python_export_path, python_exe)
  867. return idf_python_env_path, idf_python_export_path, virtualenv_python
  868. def get_idf_env(): # type: () -> Any
  869. try:
  870. idf_env_file_path = os.path.join(global_idf_tools_path, IDF_ENV_FILE) # type: ignore
  871. with open(idf_env_file_path, 'r') as idf_env_file:
  872. return json.load(idf_env_file)
  873. except (IOError, OSError):
  874. if not os.path.exists(idf_env_file_path):
  875. warn('File {} was not found. '.format(idf_env_file_path))
  876. else:
  877. filename, ending = os.path.splitext(os.path.basename(idf_env_file_path))
  878. warn('File {} can not be opened, renaming to {}'.format(idf_env_file_path,filename + '_failed' + ending))
  879. os.rename(idf_env_file_path, os.path.join(os.path.dirname(idf_env_file_path), (filename + '_failed' + ending)))
  880. info('Creating {}' .format(idf_env_file_path))
  881. return {'idfSelectedId': 'sha', 'idfInstalled': {'sha': {'targets': {}}}}
  882. def export_targets_to_idf_env_json(targets): # type: (list[str]) -> None
  883. idf_env_json = get_idf_env()
  884. targets = list(set(targets + get_user_defined_targets()))
  885. for env in idf_env_json['idfInstalled']:
  886. if env == idf_env_json['idfSelectedId']:
  887. idf_env_json['idfInstalled'][env]['targets'] = targets
  888. break
  889. try:
  890. if global_idf_tools_path: # mypy fix for Optional[str] in the next call
  891. # the directory doesn't exist if this is run on a clean system the first time
  892. mkdir_p(global_idf_tools_path)
  893. with open(os.path.join(global_idf_tools_path, IDF_ENV_FILE), 'w') as w: # type: ignore
  894. json.dump(idf_env_json, w, indent=4)
  895. except (IOError, OSError):
  896. warn('File {} can not be created. '.format(os.path.join(global_idf_tools_path, IDF_ENV_FILE))) # type: ignore
  897. def clean_targets(targets_str): # type: (str) -> list[str]
  898. targets_from_tools_json = get_all_targets_from_tools_json()
  899. invalid_targets = []
  900. targets_str = targets_str.lower()
  901. targets = targets_str.replace('-', '').split(',')
  902. if targets != ['all']:
  903. invalid_targets = [t for t in targets if t not in targets_from_tools_json]
  904. if invalid_targets:
  905. warn('Targets: "{}" are not supported. Only allowed options are: {}.'.format(', '.join(invalid_targets), ', '.join(targets_from_tools_json)))
  906. raise SystemExit(1)
  907. # removing duplicates
  908. targets = list(set(targets))
  909. export_targets_to_idf_env_json(targets)
  910. else:
  911. export_targets_to_idf_env_json(targets_from_tools_json)
  912. return targets
  913. def get_user_defined_targets(): # type: () -> list[str]
  914. try:
  915. with open(os.path.join(global_idf_tools_path, IDF_ENV_FILE), 'r') as idf_env_file: # type: ignore
  916. idf_env_json = json.load(idf_env_file)
  917. except OSError:
  918. # warn('File {} was not found. Installing tools for all esp targets.'.format(os.path.join(global_idf_tools_path, IDF_ENV_FILE))) # type: ignore
  919. return []
  920. targets = []
  921. for env in idf_env_json['idfInstalled']:
  922. if env == idf_env_json['idfSelectedId']:
  923. targets = idf_env_json['idfInstalled'][env]['targets']
  924. break
  925. return targets
  926. def get_all_targets_from_tools_json(): # type: () -> list[str]
  927. tools_info = load_tools_info()
  928. targets_from_tools_json = [] # type: list[str]
  929. for _, v in tools_info.items():
  930. targets_from_tools_json.extend(v.get_supported_targets())
  931. # remove duplicates
  932. targets_from_tools_json = list(set(targets_from_tools_json))
  933. if 'all' in targets_from_tools_json:
  934. targets_from_tools_json.remove('all')
  935. return sorted(targets_from_tools_json)
  936. def filter_tools_info(tools_info): # type: (OrderedDict[str, IDFTool]) -> OrderedDict[str,IDFTool]
  937. targets = get_user_defined_targets()
  938. if not targets:
  939. return tools_info
  940. else:
  941. filtered_tools_spec = {k:v for k, v in tools_info.items() if
  942. (v.get_install_type() == IDFTool.INSTALL_ALWAYS or v.get_install_type() == IDFTool.INSTALL_ON_REQUEST) and
  943. (any(item in targets for item in v.get_supported_targets()) or v.get_supported_targets() == ['all'])}
  944. return OrderedDict(filtered_tools_spec)
  945. def action_list(args): # type: ignore
  946. tools_info = load_tools_info()
  947. for name, tool in tools_info.items():
  948. if tool.get_install_type() == IDFTool.INSTALL_NEVER:
  949. continue
  950. optional_str = ' (optional)' if tool.get_install_type() == IDFTool.INSTALL_ON_REQUEST else ''
  951. info('* {}: {}{}'.format(name, tool.description, optional_str))
  952. tool.find_installed_versions()
  953. versions_for_platform = {k: v for k, v in tool.versions.items() if v.compatible_with_platform()}
  954. if not versions_for_platform:
  955. info(' (no versions compatible with platform {})'.format(PYTHON_PLATFORM))
  956. continue
  957. versions_sorted = sorted(versions_for_platform.keys(), key=tool.versions.get, reverse=True) # type: ignore
  958. for version in versions_sorted:
  959. version_obj = tool.versions[version]
  960. info(' - {} ({}{})'.format(version, version_obj.status,
  961. ', installed' if version in tool.versions_installed else ''))
  962. def action_check(args): # type: ignore
  963. tools_info = load_tools_info()
  964. tools_info = filter_tools_info(tools_info)
  965. not_found_list = []
  966. info('Checking for installed tools...')
  967. for name, tool in tools_info.items():
  968. if tool.get_install_type() == IDFTool.INSTALL_NEVER:
  969. continue
  970. tool_found_somewhere = False
  971. info('Checking tool %s' % name)
  972. tool.find_installed_versions()
  973. if tool.version_in_path:
  974. info(' version found in PATH: %s' % tool.version_in_path)
  975. tool_found_somewhere = True
  976. else:
  977. info(' no version found in PATH')
  978. for version in tool.versions_installed:
  979. info(' version installed in tools directory: %s' % version)
  980. tool_found_somewhere = True
  981. if not tool_found_somewhere and tool.get_install_type() == IDFTool.INSTALL_ALWAYS:
  982. not_found_list.append(name)
  983. if not_found_list:
  984. fatal('The following required tools were not found: ' + ' '.join(not_found_list))
  985. raise SystemExit(1)
  986. def action_export(args): # type: ignore
  987. tools_info = load_tools_info()
  988. tools_info = filter_tools_info(tools_info)
  989. all_tools_found = True
  990. export_vars = {}
  991. paths_to_export = []
  992. for name, tool in tools_info.items():
  993. if tool.get_install_type() == IDFTool.INSTALL_NEVER:
  994. continue
  995. tool.find_installed_versions()
  996. if tool.version_in_path:
  997. if tool.version_in_path not in tool.versions:
  998. # unsupported version
  999. if args.prefer_system: # type: ignore
  1000. warn('using an unsupported version of tool {} found in PATH: {}'.format(
  1001. tool.name, tool.version_in_path))
  1002. continue
  1003. else:
  1004. # unsupported version in path
  1005. pass
  1006. else:
  1007. # supported/deprecated version in PATH, use it
  1008. version_obj = tool.versions[tool.version_in_path]
  1009. if version_obj.status == IDFToolVersion.STATUS_SUPPORTED:
  1010. info('Using a supported version of tool {} found in PATH: {}.'.format(name, tool.version_in_path),
  1011. f=sys.stderr)
  1012. info('However the recommended version is {}.'.format(tool.get_recommended_version()),
  1013. f=sys.stderr)
  1014. elif version_obj.status == IDFToolVersion.STATUS_DEPRECATED:
  1015. warn('using a deprecated version of tool {} found in PATH: {}'.format(name, tool.version_in_path))
  1016. continue
  1017. self_restart_cmd = '{} {}{}'.format(sys.executable, __file__,
  1018. (' --tools-json ' + args.tools_json) if args.tools_json else '')
  1019. self_restart_cmd = to_shell_specific_paths([self_restart_cmd])[0]
  1020. if IDF_TOOLS_EXPORT_CMD:
  1021. prefer_system_hint = ''
  1022. else:
  1023. prefer_system_hint = ' To use it, run \'{} export --prefer-system\''.format(self_restart_cmd)
  1024. if IDF_TOOLS_INSTALL_CMD:
  1025. install_cmd = to_shell_specific_paths([IDF_TOOLS_INSTALL_CMD])[0]
  1026. else:
  1027. install_cmd = self_restart_cmd + ' install'
  1028. if not tool.versions_installed:
  1029. if tool.get_install_type() == IDFTool.INSTALL_ALWAYS:
  1030. all_tools_found = False
  1031. fatal('tool {} has no installed versions. Please run \'{}\' to install it.'.format(
  1032. tool.name, install_cmd))
  1033. if tool.version_in_path and tool.version_in_path not in tool.versions:
  1034. info('An unsupported version of tool {} was found in PATH: {}. '.format(name, tool.version_in_path) +
  1035. prefer_system_hint, f=sys.stderr)
  1036. continue
  1037. else:
  1038. # tool is optional, and does not have versions installed
  1039. # use whatever is available in PATH
  1040. continue
  1041. if tool.version_in_path and tool.version_in_path not in tool.versions:
  1042. info('Not using an unsupported version of tool {} found in PATH: {}.'.format(
  1043. tool.name, tool.version_in_path) + prefer_system_hint, f=sys.stderr)
  1044. version_to_use = tool.get_preferred_installed_version()
  1045. export_paths = tool.get_export_paths(version_to_use)
  1046. if export_paths:
  1047. paths_to_export += export_paths
  1048. tool_export_vars = tool.get_export_vars(version_to_use)
  1049. for k, v in tool_export_vars.items():
  1050. old_v = os.environ.get(k)
  1051. if old_v is None or old_v != v:
  1052. export_vars[k] = v
  1053. current_path = os.getenv('PATH')
  1054. idf_python_env_path, idf_python_export_path, virtualenv_python = get_python_env_path()
  1055. if os.path.exists(virtualenv_python):
  1056. idf_python_env_path = to_shell_specific_paths([idf_python_env_path])[0]
  1057. if os.getenv('IDF_PYTHON_ENV_PATH') != idf_python_env_path:
  1058. export_vars['IDF_PYTHON_ENV_PATH'] = to_shell_specific_paths([idf_python_env_path])[0]
  1059. if idf_python_export_path not in current_path:
  1060. paths_to_export.append(idf_python_export_path)
  1061. idf_tools_dir = os.path.join(global_idf_path, 'tools')
  1062. idf_tools_dir = to_shell_specific_paths([idf_tools_dir])[0]
  1063. if idf_tools_dir not in current_path:
  1064. paths_to_export.append(idf_tools_dir)
  1065. if sys.platform == 'win32':
  1066. old_path = '%PATH%'
  1067. path_sep = ';'
  1068. else:
  1069. old_path = '$PATH'
  1070. path_sep = ':'
  1071. if args.format == EXPORT_SHELL:
  1072. if sys.platform == 'win32':
  1073. export_format = 'SET "{}={}"'
  1074. export_sep = '\n'
  1075. else:
  1076. export_format = 'export {}="{}"'
  1077. export_sep = ';'
  1078. elif args.format == EXPORT_KEY_VALUE:
  1079. export_format = '{}={}'
  1080. export_sep = '\n'
  1081. else:
  1082. raise NotImplementedError('unsupported export format {}'.format(args.format))
  1083. if paths_to_export:
  1084. export_vars['PATH'] = path_sep.join(to_shell_specific_paths(paths_to_export) + [old_path])
  1085. export_statements = export_sep.join([export_format.format(k, v) for k, v in export_vars.items()])
  1086. if export_statements:
  1087. print(export_statements)
  1088. if not all_tools_found:
  1089. raise SystemExit(1)
  1090. def apply_url_mirrors(args, tool_download_obj): # type: ignore
  1091. apply_mirror_prefix_map(args, tool_download_obj)
  1092. apply_github_assets_option(tool_download_obj)
  1093. def apply_mirror_prefix_map(args, tool_download_obj): # type: ignore
  1094. """Rewrite URL for given tool_obj, given tool_version, and current platform,
  1095. if --mirror-prefix-map flag or IDF_MIRROR_PREFIX_MAP environment variable is given.
  1096. """
  1097. mirror_prefix_map = None
  1098. mirror_prefix_map_env = os.getenv('IDF_MIRROR_PREFIX_MAP')
  1099. if mirror_prefix_map_env:
  1100. mirror_prefix_map = mirror_prefix_map_env.split(';')
  1101. if IDF_MAINTAINER and args.mirror_prefix_map:
  1102. if mirror_prefix_map:
  1103. warn('Both IDF_MIRROR_PREFIX_MAP environment variable and --mirror-prefix-map flag are specified, ' +
  1104. 'will use the value from the command line.')
  1105. mirror_prefix_map = args.mirror_prefix_map
  1106. if mirror_prefix_map and tool_download_obj:
  1107. for item in mirror_prefix_map:
  1108. if URL_PREFIX_MAP_SEPARATOR not in item:
  1109. warn('invalid mirror-prefix-map item (missing \'{}\') {}'.format(URL_PREFIX_MAP_SEPARATOR, item))
  1110. continue
  1111. search, replace = item.split(URL_PREFIX_MAP_SEPARATOR, 1)
  1112. old_url = tool_download_obj.url
  1113. new_url = re.sub(search, replace, old_url)
  1114. if new_url != old_url:
  1115. info('Changed download URL: {} => {}'.format(old_url, new_url))
  1116. tool_download_obj.url = new_url
  1117. break
  1118. def apply_github_assets_option(tool_download_obj): # type: ignore
  1119. """ Rewrite URL for given tool_obj if the download URL is an https://github.com/ URL and the variable
  1120. IDF_GITHUB_ASSETS is set. The github.com part of the URL will be replaced.
  1121. """
  1122. try:
  1123. github_assets = os.environ['IDF_GITHUB_ASSETS'].strip()
  1124. except KeyError:
  1125. return # no IDF_GITHUB_ASSETS
  1126. if not github_assets: # variable exists but is empty
  1127. return
  1128. # check no URL qualifier in the mirror URL
  1129. if '://' in github_assets:
  1130. fatal("IDF_GITHUB_ASSETS shouldn't include any URL qualifier, https:// is assumed")
  1131. raise SystemExit(1)
  1132. # Strip any trailing / from the mirror URL
  1133. github_assets = github_assets.rstrip('/')
  1134. old_url = tool_download_obj.url
  1135. new_url = re.sub(r'^https://github.com/', 'https://{}/'.format(github_assets), old_url)
  1136. if new_url != old_url:
  1137. info('Using GitHub assets mirror for URL: {} => {}'.format(old_url, new_url))
  1138. tool_download_obj.url = new_url
  1139. def action_download(args): # type: ignore
  1140. tools_info = load_tools_info()
  1141. tools_spec = args.tools
  1142. targets = [] # type: list[str]
  1143. # Installing only single tools, no targets are specified.
  1144. if 'required' in tools_spec:
  1145. targets = clean_targets(args.targets)
  1146. if args.platform not in PLATFORM_FROM_NAME:
  1147. fatal('unknown platform: {}' % args.platform)
  1148. raise SystemExit(1)
  1149. platform = PLATFORM_FROM_NAME[args.platform]
  1150. tools_info_for_platform = OrderedDict()
  1151. for name, tool_obj in tools_info.items():
  1152. tool_for_platform = tool_obj.copy_for_platform(platform)
  1153. tools_info_for_platform[name] = tool_for_platform
  1154. if not tools_spec or 'required' in tools_spec:
  1155. # Downloading tools for all ESP_targets required by the operating system.
  1156. tools_spec = [k for k, v in tools_info_for_platform.items() if v.get_install_type() == IDFTool.INSTALL_ALWAYS]
  1157. # Filtering tools user defined list of ESP_targets
  1158. if 'all' not in targets:
  1159. def is_tool_selected(tool): # type: (IDFTool) -> bool
  1160. supported_targets = tool.get_supported_targets()
  1161. return (any(item in targets for item in supported_targets) or supported_targets == ['all'])
  1162. tools_spec = [k for k in tools_spec if is_tool_selected(tools_info[k])]
  1163. info('Downloading tools for {}: {}'.format(platform, ', '.join(tools_spec)))
  1164. # Downloading tools for all ESP_targets (MacOS, Windows, Linux)
  1165. elif 'all' in tools_spec:
  1166. tools_spec = [k for k, v in tools_info_for_platform.items() if v.get_install_type() != IDFTool.INSTALL_NEVER]
  1167. info('Downloading tools for {}: {}'.format(platform, ', '.join(tools_spec)))
  1168. for tool_spec in tools_spec:
  1169. if '@' not in tool_spec:
  1170. tool_name = tool_spec
  1171. tool_version = None
  1172. else:
  1173. tool_name, tool_version = tool_spec.split('@', 1)
  1174. if tool_name not in tools_info_for_platform:
  1175. fatal('unknown tool name: {}'.format(tool_name))
  1176. raise SystemExit(1)
  1177. tool_obj = tools_info_for_platform[tool_name]
  1178. if tool_version is not None and tool_version not in tool_obj.versions:
  1179. fatal('unknown version for tool {}: {}'.format(tool_name, tool_version))
  1180. raise SystemExit(1)
  1181. if tool_version is None:
  1182. tool_version = tool_obj.get_recommended_version()
  1183. if tool_version is None:
  1184. fatal('tool {} not found for {} platform'.format(tool_name, platform))
  1185. raise SystemExit(1)
  1186. tool_spec = '{}@{}'.format(tool_name, tool_version)
  1187. info('Downloading {}'.format(tool_spec))
  1188. apply_url_mirrors(args, tool_obj.versions[tool_version].get_download_for_platform(platform))
  1189. tool_obj.download(tool_version)
  1190. def action_install(args): # type: ignore
  1191. tools_info = load_tools_info()
  1192. tools_spec = args.tools # type: ignore
  1193. targets = [] # type: list[str]
  1194. # Installing only single tools, no targets are specified.
  1195. if 'required' in tools_spec:
  1196. targets = clean_targets(args.targets)
  1197. info('Selected targets are: {}' .format(', '.join(get_user_defined_targets())))
  1198. if not tools_spec or 'required' in tools_spec:
  1199. # Installing tools for all ESP_targets required by the operating system.
  1200. tools_spec = [k for k, v in tools_info.items() if v.get_install_type() == IDFTool.INSTALL_ALWAYS]
  1201. # Filtering tools user defined list of ESP_targets
  1202. if 'all' not in targets:
  1203. def is_tool_selected(tool): # type: (IDFTool) -> bool
  1204. supported_targets = tool.get_supported_targets()
  1205. return (any(item in targets for item in supported_targets) or supported_targets == ['all'])
  1206. tools_spec = [k for k in tools_spec if is_tool_selected(tools_info[k])]
  1207. info('Installing tools: {}'.format(', '.join(tools_spec)))
  1208. # Installing tools for all ESP_targets (MacOS, Windows, Linux)
  1209. elif 'all' in tools_spec:
  1210. tools_spec = [k for k, v in tools_info.items() if v.get_install_type() != IDFTool.INSTALL_NEVER]
  1211. info('Installing tools: {}'.format(', '.join(tools_spec)))
  1212. for tool_spec in tools_spec:
  1213. if '@' not in tool_spec:
  1214. tool_name = tool_spec
  1215. tool_version = None
  1216. else:
  1217. tool_name, tool_version = tool_spec.split('@', 1)
  1218. if tool_name not in tools_info:
  1219. fatal('unknown tool name: {}'.format(tool_name))
  1220. raise SystemExit(1)
  1221. tool_obj = tools_info[tool_name]
  1222. if not tool_obj.compatible_with_platform():
  1223. fatal('tool {} does not have versions compatible with platform {}'.format(tool_name, CURRENT_PLATFORM))
  1224. raise SystemExit(1)
  1225. if tool_version is not None and tool_version not in tool_obj.versions:
  1226. fatal('unknown version for tool {}: {}'.format(tool_name, tool_version))
  1227. raise SystemExit(1)
  1228. if tool_version is None:
  1229. tool_version = tool_obj.get_recommended_version()
  1230. assert tool_version is not None
  1231. tool_obj.find_installed_versions()
  1232. tool_spec = '{}@{}'.format(tool_name, tool_version)
  1233. if tool_version in tool_obj.versions_installed:
  1234. info('Skipping {} (already installed)'.format(tool_spec))
  1235. continue
  1236. info('Installing {}'.format(tool_spec))
  1237. apply_url_mirrors(args, tool_obj.versions[tool_version].get_download_for_platform(PYTHON_PLATFORM))
  1238. tool_obj.download(tool_version)
  1239. tool_obj.install(tool_version)
  1240. def get_wheels_dir(): # type: () -> Optional[str]
  1241. tools_info = load_tools_info()
  1242. wheels_package_name = 'idf-python-wheels'
  1243. if wheels_package_name not in tools_info:
  1244. return None
  1245. wheels_package = tools_info[wheels_package_name]
  1246. recommended_version = wheels_package.get_recommended_version()
  1247. if recommended_version is None:
  1248. return None
  1249. wheels_dir = wheels_package.get_path_for_version(recommended_version)
  1250. if not os.path.exists(wheels_dir):
  1251. return None
  1252. return wheels_dir
  1253. def action_install_python_env(args): # type: ignore
  1254. reinstall = args.reinstall
  1255. idf_python_env_path, _, virtualenv_python = get_python_env_path()
  1256. is_virtualenv = hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix)
  1257. if is_virtualenv and (not os.path.exists(idf_python_env_path) or reinstall):
  1258. fatal('This script was called from a virtual environment, can not create a virtual environment again')
  1259. raise SystemExit(1)
  1260. if os.path.exists(virtualenv_python):
  1261. try:
  1262. subprocess.check_call([virtualenv_python, '--version'], stdout=sys.stdout, stderr=sys.stderr)
  1263. except (OSError, subprocess.CalledProcessError):
  1264. # At this point we can reinstall the virtual environment if it is non-functional. This can happen at least
  1265. # when the Python interpreter was removed which was used to create the virtual environment.
  1266. reinstall = True
  1267. try:
  1268. subprocess.check_call([virtualenv_python, '-m', 'pip', '--version'], stdout=sys.stdout, stderr=sys.stderr)
  1269. except subprocess.CalledProcessError:
  1270. warn('PIP is not available in the virtual environment.')
  1271. # Reinstallation of the virtual environment could help if PIP was installed for the main Python
  1272. reinstall = True
  1273. if reinstall and os.path.exists(idf_python_env_path):
  1274. warn('Removing the existing Python environment in {}'.format(idf_python_env_path))
  1275. shutil.rmtree(idf_python_env_path)
  1276. if not os.path.exists(virtualenv_python):
  1277. info('Creating a new Python environment in {}'.format(idf_python_env_path))
  1278. try:
  1279. import virtualenv # noqa: F401
  1280. except ImportError:
  1281. info('Installing virtualenv')
  1282. subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--user', 'virtualenv'],
  1283. stdout=sys.stdout, stderr=sys.stderr)
  1284. subprocess.check_call([sys.executable, '-m', 'virtualenv', '--seeder', 'pip', idf_python_env_path],
  1285. stdout=sys.stdout, stderr=sys.stderr)
  1286. run_args = [virtualenv_python, '-m', 'pip', 'install', '--no-warn-script-location']
  1287. requirements_txt = os.path.join(global_idf_path, 'requirements.txt')
  1288. run_args += ['-r', requirements_txt]
  1289. if args.extra_wheels_dir:
  1290. run_args += ['--find-links', args.extra_wheels_dir]
  1291. if args.no_index:
  1292. run_args += ['--no-index']
  1293. if args.extra_wheels_url:
  1294. run_args += ['--extra-index-url', args.extra_wheels_url]
  1295. wheels_dir = get_wheels_dir()
  1296. if wheels_dir is not None:
  1297. run_args += ['--find-links', wheels_dir]
  1298. info('Installing Python packages from {}'.format(requirements_txt))
  1299. subprocess.check_call(run_args, stdout=sys.stdout, stderr=sys.stderr)
  1300. def action_add_version(args): # type: ignore
  1301. tools_info = load_tools_info()
  1302. tool_name = args.tool
  1303. tool_obj = tools_info.get(tool_name)
  1304. if not tool_obj:
  1305. info('Creating new tool entry for {}'.format(tool_name))
  1306. tool_obj = IDFTool(tool_name, TODO_MESSAGE, IDFTool.INSTALL_ALWAYS,
  1307. TODO_MESSAGE, TODO_MESSAGE, [TODO_MESSAGE], TODO_MESSAGE)
  1308. tools_info[tool_name] = tool_obj
  1309. version = args.version
  1310. version_obj = tool_obj.versions.get(version)
  1311. if version not in tool_obj.versions:
  1312. info('Creating new version {}'.format(version))
  1313. version_obj = IDFToolVersion(version, IDFToolVersion.STATUS_SUPPORTED)
  1314. tool_obj.versions[version] = version_obj
  1315. url_prefix = args.url_prefix or 'https://%s/' % TODO_MESSAGE
  1316. for file_path in args.files:
  1317. file_name = os.path.basename(file_path)
  1318. # Guess which platform this file is for
  1319. found_platform = None
  1320. for platform_alias, platform_id in PLATFORM_FROM_NAME.items():
  1321. if platform_alias in file_name:
  1322. found_platform = platform_id
  1323. break
  1324. if found_platform is None:
  1325. info('Could not guess platform for file {}'.format(file_name))
  1326. found_platform = TODO_MESSAGE
  1327. # Get file size and calculate the SHA256
  1328. file_size, file_sha256 = get_file_size_sha256(file_path)
  1329. url = url_prefix + file_name
  1330. info('Adding download for platform {}'.format(found_platform))
  1331. info(' size: {}'.format(file_size))
  1332. info(' SHA256: {}'.format(file_sha256))
  1333. info(' URL: {}'.format(url))
  1334. version_obj.add_download(found_platform, url, file_size, file_sha256)
  1335. json_str = dump_tools_json(tools_info)
  1336. if not args.output:
  1337. args.output = os.path.join(global_idf_path, TOOLS_FILE_NEW)
  1338. with open(args.output, 'w') as f:
  1339. f.write(json_str)
  1340. f.write('\n')
  1341. info('Wrote output to {}'.format(args.output))
  1342. def action_rewrite(args): # type: ignore
  1343. tools_info = load_tools_info()
  1344. json_str = dump_tools_json(tools_info)
  1345. if not args.output:
  1346. args.output = os.path.join(global_idf_path, TOOLS_FILE_NEW)
  1347. with open(args.output, 'w') as f:
  1348. f.write(json_str)
  1349. f.write('\n')
  1350. info('Wrote output to {}'.format(args.output))
  1351. def action_validate(args): # type: ignore
  1352. try:
  1353. import jsonschema
  1354. except ImportError:
  1355. fatal('You need to install jsonschema package to use validate command')
  1356. raise SystemExit(1)
  1357. with open(os.path.join(global_idf_path, TOOLS_FILE), 'r') as tools_file:
  1358. tools_json = json.load(tools_file)
  1359. with open(os.path.join(global_idf_path, TOOLS_SCHEMA_FILE), 'r') as schema_file:
  1360. schema_json = json.load(schema_file)
  1361. jsonschema.validate(tools_json, schema_json)
  1362. # on failure, this will raise an exception with a fairly verbose diagnostic message
  1363. def action_gen_doc(args): # type: ignore
  1364. f = args.output
  1365. tools_info = load_tools_info()
  1366. def print_out(text): # type: (str) -> None
  1367. f.write(text + '\n')
  1368. print_out('.. |zwsp| unicode:: U+200B')
  1369. print_out(' :trim:')
  1370. print_out('')
  1371. idf_gh_url = 'https://github.com/espressif/esp-idf'
  1372. for tool_name, tool_obj in tools_info.items():
  1373. info_url = tool_obj.options.info_url
  1374. if idf_gh_url + '/tree' in info_url:
  1375. info_url = re.sub(idf_gh_url + r'/tree/\w+/(.*)', r':idf:`\1`', info_url)
  1376. license_url = 'https://spdx.org/licenses/' + tool_obj.options.license
  1377. print_out("""
  1378. .. _tool-{name}:
  1379. {name}
  1380. {underline}
  1381. {description}
  1382. .. include:: idf-tools-notes.inc
  1383. :start-after: tool-{name}-notes
  1384. :end-before: ---
  1385. License: `{license} <{license_url}>`_
  1386. More info: {info_url}
  1387. .. list-table::
  1388. :widths: 10 10 80
  1389. :header-rows: 1
  1390. * - Platform
  1391. - Required
  1392. - Download
  1393. """.rstrip().format(name=tool_name,
  1394. underline=args.heading_underline_char * len(tool_name),
  1395. description=tool_obj.description,
  1396. license=tool_obj.options.license,
  1397. license_url=license_url,
  1398. info_url=info_url))
  1399. for platform_name in sorted(tool_obj.get_supported_platforms()):
  1400. platform_tool = tool_obj.copy_for_platform(platform_name)
  1401. install_type = platform_tool.get_install_type()
  1402. if install_type == IDFTool.INSTALL_NEVER:
  1403. continue
  1404. elif install_type == IDFTool.INSTALL_ALWAYS:
  1405. install_type_str = 'required'
  1406. elif install_type == IDFTool.INSTALL_ON_REQUEST:
  1407. install_type_str = 'optional'
  1408. else:
  1409. raise NotImplementedError()
  1410. version = platform_tool.get_recommended_version()
  1411. version_obj = platform_tool.versions[version]
  1412. download_obj = version_obj.get_download_for_platform(platform_name)
  1413. # Note: keep the list entries indented to the same number of columns
  1414. # as the list header above.
  1415. print_out("""
  1416. * - {}
  1417. - {}
  1418. - {}
  1419. .. rst-class:: tool-sha256
  1420. SHA256: {}
  1421. """.strip('\n').format(platform_name, install_type_str, download_obj.url, download_obj.sha256))
  1422. print_out('')
  1423. print_out('')
  1424. def main(argv): # type: (list[str]) -> None
  1425. parser = argparse.ArgumentParser()
  1426. parser.add_argument('--quiet', help='Don\'t output diagnostic messages to stdout/stderr', action='store_true')
  1427. parser.add_argument('--non-interactive', help='Don\'t output interactive messages and questions', action='store_true')
  1428. parser.add_argument('--tools-json', help='Path to the tools.json file to use')
  1429. parser.add_argument('--idf-path', help='ESP-IDF path to use')
  1430. subparsers = parser.add_subparsers(dest='action')
  1431. subparsers.add_parser('list', help='List tools and versions available')
  1432. subparsers.add_parser('check', help='Print summary of tools installed or found in PATH')
  1433. export = subparsers.add_parser('export', help='Output command for setting tool paths, suitable for shell')
  1434. export.add_argument('--format', choices=[EXPORT_SHELL, EXPORT_KEY_VALUE], default=EXPORT_SHELL,
  1435. help='Format of the output: shell (suitable for printing into shell), ' +
  1436. 'or key-value (suitable for parsing by other tools')
  1437. export.add_argument('--prefer-system', help='Normally, if the tool is already present in PATH, ' +
  1438. 'but has an unsupported version, a version from the tools directory ' +
  1439. 'will be used instead. If this flag is given, the version in PATH ' +
  1440. 'will be used.', action='store_true')
  1441. install = subparsers.add_parser('install', help='Download and install tools into the tools directory')
  1442. install.add_argument('tools', metavar='TOOL', nargs='*', default=['required'],
  1443. help='Tools to install. ' +
  1444. 'To install a specific version use <tool_name>@<version> syntax. ' +
  1445. 'Use empty or \'required\' to install required tools, not optional ones. ' +
  1446. 'Use \'all\' to install all tools, including the optional ones.')
  1447. install.add_argument('--targets', default='all', help='A comma separated list of desired chip targets for installing.' +
  1448. ' It defaults to installing all supported targets.')
  1449. download = subparsers.add_parser('download', help='Download the tools into the dist directory')
  1450. download.add_argument('--platform', default=CURRENT_PLATFORM, help='Platform to download the tools for')
  1451. download.add_argument('tools', metavar='TOOL', nargs='*', default=['required'],
  1452. help='Tools to download. ' +
  1453. 'To download a specific version use <tool_name>@<version> syntax. ' +
  1454. 'Use empty or \'required\' to download required tools, not optional ones. ' +
  1455. 'Use \'all\' to download all tools, including the optional ones.')
  1456. download.add_argument('--targets', default='all', help='A comma separated list of desired chip targets for installing.' +
  1457. ' It defaults to installing all supported targets.')
  1458. if IDF_MAINTAINER:
  1459. for subparser in [download, install]:
  1460. subparser.add_argument('--mirror-prefix-map', nargs='*',
  1461. help='Pattern to rewrite download URLs, with source and replacement separated by comma.' +
  1462. ' E.g. http://foo.com,http://test.foo.com')
  1463. install_python_env = subparsers.add_parser('install-python-env',
  1464. help='Create Python virtual environment and install the ' +
  1465. 'required Python packages')
  1466. install_python_env.add_argument('--reinstall', help='Discard the previously installed environment',
  1467. action='store_true')
  1468. install_python_env.add_argument('--extra-wheels-dir', help='Additional directories with wheels ' +
  1469. 'to use during installation')
  1470. install_python_env.add_argument('--extra-wheels-url', help='Additional URL with wheels', default='https://dl.espressif.com/pypi')
  1471. install_python_env.add_argument('--no-index', help='Work offline without retrieving wheels index')
  1472. if IDF_MAINTAINER:
  1473. add_version = subparsers.add_parser('add-version', help='Add or update download info for a version')
  1474. add_version.add_argument('--output', help='Save new tools.json into this file')
  1475. add_version.add_argument('--tool', help='Tool name to set add a version for', required=True)
  1476. add_version.add_argument('--version', help='Version identifier', required=True)
  1477. add_version.add_argument('--url-prefix', help='String to prepend to file names to obtain download URLs')
  1478. add_version.add_argument('files', help='File names of the download artifacts', nargs='*')
  1479. rewrite = subparsers.add_parser('rewrite', help='Load tools.json, validate, and save the result back into JSON')
  1480. rewrite.add_argument('--output', help='Save new tools.json into this file')
  1481. subparsers.add_parser('validate', help='Validate tools.json against schema file')
  1482. gen_doc = subparsers.add_parser('gen-doc', help='Write the list of tools as a documentation page')
  1483. gen_doc.add_argument('--output', type=argparse.FileType('w'), default=sys.stdout,
  1484. help='Output file name')
  1485. gen_doc.add_argument('--heading-underline-char', help='Character to use when generating RST sections', default='~')
  1486. args = parser.parse_args(argv)
  1487. if args.action is None:
  1488. parser.print_help()
  1489. parser.exit(1)
  1490. if args.quiet:
  1491. global global_quiet
  1492. global_quiet = True
  1493. if args.non_interactive:
  1494. global global_non_interactive
  1495. global_non_interactive = True
  1496. global global_idf_path
  1497. global_idf_path = os.environ.get('IDF_PATH')
  1498. if args.idf_path:
  1499. global_idf_path = args.idf_path
  1500. if not global_idf_path:
  1501. global_idf_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..'))
  1502. os.environ['IDF_PATH'] = global_idf_path
  1503. global global_idf_tools_path
  1504. global_idf_tools_path = os.environ.get('IDF_TOOLS_PATH') or os.path.expanduser(IDF_TOOLS_PATH_DEFAULT)
  1505. # On macOS, unset __PYVENV_LAUNCHER__ variable if it is set.
  1506. # Otherwise sys.executable keeps pointing to the system Python, even when a python binary from a virtualenv is invoked.
  1507. # See https://bugs.python.org/issue22490#msg283859.
  1508. os.environ.pop('__PYVENV_LAUNCHER__', None)
  1509. if sys.version_info.major == 2:
  1510. try:
  1511. global_idf_tools_path.decode('ascii') # type: ignore
  1512. except UnicodeDecodeError:
  1513. fatal('IDF_TOOLS_PATH contains non-ASCII characters: {}'.format(global_idf_tools_path) +
  1514. '\nThis is not supported yet with Python 2. ' +
  1515. 'Please set IDF_TOOLS_PATH to a directory with an ASCII name, or switch to Python 3.')
  1516. raise SystemExit(1)
  1517. if CURRENT_PLATFORM == UNKNOWN_PLATFORM:
  1518. fatal('Platform {} appears to be unsupported'.format(PYTHON_PLATFORM))
  1519. raise SystemExit(1)
  1520. global global_tools_json
  1521. if args.tools_json:
  1522. global_tools_json = args.tools_json
  1523. else:
  1524. global_tools_json = os.path.join(global_idf_path, TOOLS_FILE)
  1525. action_func_name = 'action_' + args.action.replace('-', '_')
  1526. action_func = globals()[action_func_name]
  1527. action_func(args)
  1528. if __name__ == '__main__':
  1529. if 'MSYSTEM' in os.environ:
  1530. fatal('MSys/Mingw is not supported. Please follow the getting started guide of the documentation to set up '
  1531. 'a supported environment')
  1532. raise SystemExit(1)
  1533. main(sys.argv[1:])