idf_tools.py 86 KB

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