idf_tools.py 76 KB

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