idf_tools.py 111 KB

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