idf_tools.py 110 KB

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