idf_tools.py 103 KB

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