idf_tools.py 78 KB

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