idf_tools.py 81 KB

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