idf_tools.py 111 KB

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