idf_tools.py 72 KB

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