idf_tools.py 110 KB

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