idf_tools.py 117 KB

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