idf_tools.py 115 KB

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