idf_tools.py 119 KB

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