idf_tools.py 95 KB

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