idf_tools.py 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675
  1. #!/usr/bin/env python
  2. # coding=utf-8
  3. #
  4. # This script helps installing tools required to use the ESP-IDF, and updating PATH
  5. # to use the installed tools. It can also create a Python virtual environment,
  6. # and install Python requirements into it.
  7. # It does not install OS dependencies. It does install tools such as the Xtensa
  8. # GCC toolchain and ESP32 ULP coprocessor toolchain.
  9. #
  10. # By default, downloaded tools will be installed under $HOME/.espressif directory
  11. # (%USERPROFILE%/.espressif on Windows). This path can be modified by setting
  12. # IDF_TOOLS_PATH variable prior to running this tool.
  13. #
  14. # Users do not need to interact with this script directly. In IDF root directory,
  15. # install.sh (.bat) and export.sh (.bat) scripts are provided to invoke this script.
  16. #
  17. # Usage:
  18. #
  19. # * To install the tools, run `idf_tools.py install`.
  20. #
  21. # * To install the Python environment, run `idf_tools.py install-python-env`.
  22. #
  23. # * To start using the tools, run `eval "$(idf_tools.py export)"` — this will update
  24. # the PATH to point to the installed tools and set up other environment variables
  25. # needed by the tools.
  26. #
  27. ###
  28. #
  29. # Copyright 2019 Espressif Systems (Shanghai) PTE LTD
  30. #
  31. # Licensed under the Apache License, Version 2.0 (the "License");
  32. # you may not use this file except in compliance with the License.
  33. # You may obtain a copy of the License at
  34. #
  35. # http://www.apache.org/licenses/LICENSE-2.0
  36. #
  37. # Unless required by applicable law or agreed to in writing, software
  38. # distributed under the License is distributed on an "AS IS" BASIS,
  39. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40. # See the License for the specific language governing permissions and
  41. # limitations under the License.
  42. import argparse
  43. import contextlib
  44. import copy
  45. import errno
  46. import functools
  47. import hashlib
  48. import json
  49. import os
  50. import platform
  51. import re
  52. import shutil
  53. import ssl
  54. import subprocess
  55. import sys
  56. import tarfile
  57. import zipfile
  58. from collections import OrderedDict, namedtuple
  59. try:
  60. import typing # noqa: F401
  61. except ImportError:
  62. pass
  63. try:
  64. from urllib.error import ContentTooShortError
  65. from urllib.request import urlopen
  66. except ImportError:
  67. from urllib import ContentTooShortError, urlopen
  68. try:
  69. from exceptions import WindowsError
  70. except ImportError:
  71. class WindowsError(OSError):
  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. TOOLS_FILE_VERSION = 1
  77. IDF_TOOLS_PATH_DEFAULT = os.path.join('~', '.espressif')
  78. UNKNOWN_VERSION = 'unknown'
  79. SUBST_TOOL_PATH_REGEX = re.compile(r'\${TOOL_PATH}')
  80. VERSION_REGEX_REPLACE_DEFAULT = r'\1'
  81. IDF_MAINTAINER = os.environ.get('IDF_MAINTAINER') or False
  82. TODO_MESSAGE = 'TODO'
  83. DOWNLOAD_RETRY_COUNT = 3
  84. URL_PREFIX_MAP_SEPARATOR = ','
  85. IDF_TOOLS_INSTALL_CMD = os.environ.get('IDF_TOOLS_INSTALL_CMD')
  86. IDF_TOOLS_EXPORT_CMD = os.environ.get('IDF_TOOLS_INSTALL_CMD')
  87. PYTHON_PLATFORM = platform.system() + '-' + platform.machine()
  88. # Identifiers used in tools.json for different platforms.
  89. PLATFORM_WIN32 = 'win32'
  90. PLATFORM_WIN64 = 'win64'
  91. PLATFORM_MACOS = 'macos'
  92. PLATFORM_LINUX32 = 'linux-i686'
  93. PLATFORM_LINUX64 = 'linux-amd64'
  94. PLATFORM_LINUX_ARM32 = 'linux-armel'
  95. PLATFORM_LINUX_ARM64 = 'linux-arm64'
  96. # Mappings from various other names these platforms are known as, to the identifiers above.
  97. # This includes strings produced from "platform.system() + '-' + platform.machine()", see PYTHON_PLATFORM
  98. # definition above.
  99. # This list also includes various strings used in release archives of xtensa-esp32-elf-gcc, OpenOCD, etc.
  100. PLATFORM_FROM_NAME = {
  101. # Windows
  102. PLATFORM_WIN32: PLATFORM_WIN32,
  103. 'Windows-i686': PLATFORM_WIN32,
  104. 'Windows-x86': PLATFORM_WIN32,
  105. PLATFORM_WIN64: PLATFORM_WIN64,
  106. 'Windows-x86_64': PLATFORM_WIN64,
  107. 'Windows-AMD64': PLATFORM_WIN64,
  108. # macOS
  109. PLATFORM_MACOS: PLATFORM_MACOS,
  110. 'osx': PLATFORM_MACOS,
  111. 'darwin': PLATFORM_MACOS,
  112. 'Darwin-x86_64': PLATFORM_MACOS,
  113. # pretend it is x86_64 until Darwin-arm64 tool builds are available:
  114. 'Darwin-arm64': PLATFORM_MACOS,
  115. # Linux
  116. PLATFORM_LINUX64: PLATFORM_LINUX64,
  117. 'linux64': PLATFORM_LINUX64,
  118. 'Linux-x86_64': PLATFORM_LINUX64,
  119. PLATFORM_LINUX32: PLATFORM_LINUX32,
  120. 'linux32': PLATFORM_LINUX32,
  121. 'Linux-i686': PLATFORM_LINUX32,
  122. PLATFORM_LINUX_ARM32: PLATFORM_LINUX_ARM32,
  123. 'Linux-arm': PLATFORM_LINUX_ARM32,
  124. 'Linux-armv7l': PLATFORM_LINUX_ARM32,
  125. PLATFORM_LINUX_ARM64: PLATFORM_LINUX_ARM64,
  126. 'Linux-arm64': PLATFORM_LINUX_ARM64,
  127. 'Linux-aarch64': PLATFORM_LINUX_ARM64,
  128. 'Linux-armv8l': PLATFORM_LINUX_ARM64,
  129. }
  130. UNKNOWN_PLATFORM = 'unknown'
  131. CURRENT_PLATFORM = PLATFORM_FROM_NAME.get(PYTHON_PLATFORM, UNKNOWN_PLATFORM)
  132. EXPORT_SHELL = 'shell'
  133. EXPORT_KEY_VALUE = 'key-value'
  134. ISRG_X1_ROOT_CERT = u"""
  135. -----BEGIN CERTIFICATE-----
  136. MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
  137. TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
  138. cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
  139. WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
  140. ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
  141. MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
  142. h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
  143. 0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
  144. A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
  145. T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
  146. B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
  147. B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
  148. KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
  149. OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn
  150. jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw
  151. qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
  152. rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
  153. HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
  154. hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
  155. ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
  156. 3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
  157. NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
  158. ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
  159. TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
  160. jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
  161. oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
  162. 4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
  163. mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
  164. emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
  165. -----END CERTIFICATE-----
  166. """
  167. global_quiet = False
  168. global_non_interactive = False
  169. global_idf_path = None # type: typing.Optional[str]
  170. global_idf_tools_path = None # type: typing.Optional[str]
  171. global_tools_json = None # type: typing.Optional[str]
  172. def fatal(text, *args):
  173. if not global_quiet:
  174. sys.stderr.write('ERROR: ' + text + '\n', *args)
  175. def warn(text, *args):
  176. if not global_quiet:
  177. sys.stderr.write('WARNING: ' + text + '\n', *args)
  178. def info(text, f=None, *args):
  179. if not global_quiet:
  180. if f is None:
  181. f = sys.stdout
  182. f.write(text + '\n', *args)
  183. def run_cmd_check_output(cmd, input_text=None, extra_paths=None):
  184. # If extra_paths is given, locate the executable in one of these directories.
  185. # Note: it would seem logical to add extra_paths to env[PATH], instead, and let OS do the job of finding the
  186. # executable for us. However this does not work on Windows: https://bugs.python.org/issue8557.
  187. if extra_paths:
  188. found = False
  189. extensions = ['']
  190. if sys.platform == 'win32':
  191. extensions.append('.exe')
  192. for path in extra_paths:
  193. for ext in extensions:
  194. fullpath = os.path.join(path, cmd[0] + ext)
  195. if os.path.exists(fullpath):
  196. cmd[0] = fullpath
  197. found = True
  198. break
  199. if found:
  200. break
  201. try:
  202. if input_text:
  203. input_text = input_text.encode()
  204. result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, input=input_text)
  205. return result.stdout + result.stderr
  206. except (AttributeError, TypeError):
  207. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
  208. stdout, stderr = p.communicate(input_text)
  209. if p.returncode != 0:
  210. try:
  211. raise subprocess.CalledProcessError(p.returncode, cmd, stdout, stderr)
  212. except TypeError:
  213. raise subprocess.CalledProcessError(p.returncode, cmd, stdout)
  214. return stdout + stderr
  215. def to_shell_specific_paths(paths_list):
  216. if sys.platform == 'win32':
  217. paths_list = [p.replace('/', os.path.sep) if os.path.sep in p else p for p in paths_list]
  218. if 'MSYSTEM' in os.environ:
  219. paths_msys = run_cmd_check_output(['cygpath', '-u', '-f', '-'],
  220. input_text='\n'.join(paths_list))
  221. paths_list = paths_msys.decode().strip().split('\n')
  222. return paths_list
  223. def get_env_for_extra_paths(extra_paths):
  224. """
  225. Return a copy of environment variables dict, prepending paths listed in extra_paths
  226. to the PATH environment variable.
  227. """
  228. env_arg = os.environ.copy()
  229. new_path = os.pathsep.join(extra_paths) + os.pathsep + env_arg['PATH']
  230. if sys.version_info.major == 2:
  231. env_arg['PATH'] = new_path.encode('utf8')
  232. else:
  233. env_arg['PATH'] = new_path
  234. return env_arg
  235. def get_file_size_sha256(filename, block_size=65536):
  236. sha256 = hashlib.sha256()
  237. size = 0
  238. with open(filename, 'rb') as f:
  239. for block in iter(lambda: f.read(block_size), b''):
  240. sha256.update(block)
  241. size += len(block)
  242. return size, sha256.hexdigest()
  243. def report_progress(count, block_size, total_size):
  244. percent = int(count * block_size * 100 / total_size)
  245. percent = min(100, percent)
  246. sys.stdout.write('\r%d%%' % percent)
  247. sys.stdout.flush()
  248. def mkdir_p(path):
  249. try:
  250. os.makedirs(path)
  251. except OSError as exc:
  252. if exc.errno != errno.EEXIST or not os.path.isdir(path):
  253. raise
  254. def unpack(filename, destination):
  255. info('Extracting {0} to {1}'.format(filename, destination))
  256. if filename.endswith(('.tar.gz', '.tgz')):
  257. archive_obj = tarfile.open(filename, 'r:gz')
  258. elif filename.endswith('zip'):
  259. archive_obj = zipfile.ZipFile(filename)
  260. else:
  261. raise NotImplementedError('Unsupported archive type')
  262. if sys.version_info.major == 2:
  263. # This is a workaround for the issue that unicode destination is not handled:
  264. # https://bugs.python.org/issue17153
  265. destination = str(destination)
  266. archive_obj.extractall(destination)
  267. def splittype(url):
  268. match = re.match('([^/:]+):(.*)', url, re.DOTALL)
  269. if match:
  270. scheme, data = match.groups()
  271. return scheme.lower(), data
  272. return None, url
  273. # An alternative version of urlretrieve which takes SSL context as an argument
  274. def urlretrieve_ctx(url, filename, reporthook=None, data=None, context=None):
  275. url_type, path = splittype(url)
  276. # urlopen doesn't have context argument in Python <=2.7.9
  277. extra_urlopen_args = {}
  278. if context:
  279. extra_urlopen_args['context'] = context
  280. with contextlib.closing(urlopen(url, data, **extra_urlopen_args)) as fp:
  281. headers = fp.info()
  282. # Just return the local path and the "headers" for file://
  283. # URLs. No sense in performing a copy unless requested.
  284. if url_type == 'file' and not filename:
  285. return os.path.normpath(path), headers
  286. # Handle temporary file setup.
  287. tfp = open(filename, 'wb')
  288. with tfp:
  289. result = filename, headers
  290. bs = 1024 * 8
  291. size = int(headers.get('content-length', -1))
  292. read = 0
  293. blocknum = 0
  294. if reporthook:
  295. reporthook(blocknum, bs, size)
  296. while True:
  297. block = fp.read(bs)
  298. if not block:
  299. break
  300. read += len(block)
  301. tfp.write(block)
  302. blocknum += 1
  303. if reporthook:
  304. reporthook(blocknum, bs, size)
  305. if size >= 0 and read < size:
  306. raise ContentTooShortError(
  307. 'retrieval incomplete: got only %i out of %i bytes'
  308. % (read, size), result)
  309. return result
  310. # Sometimes renaming a directory on Windows (randomly?) causes a PermissionError.
  311. # This is confirmed to be a workaround:
  312. # https://github.com/espressif/esp-idf/issues/3819#issuecomment-515167118
  313. # https://github.com/espressif/esp-idf/issues/4063#issuecomment-531490140
  314. # https://stackoverflow.com/a/43046729
  315. def rename_with_retry(path_from, path_to):
  316. if sys.platform.startswith('win'):
  317. retry_count = 100
  318. else:
  319. retry_count = 1
  320. for retry in range(retry_count):
  321. try:
  322. os.rename(path_from, path_to)
  323. return
  324. except (OSError, WindowsError): # WindowsError until Python 3.3, then OSError
  325. if retry == retry_count - 1:
  326. raise
  327. warn('Rename {} to {} failed, retrying...'.format(path_from, path_to))
  328. def strip_container_dirs(path, levels):
  329. assert levels > 0
  330. # move the original directory out of the way (add a .tmp suffix)
  331. tmp_path = path + '.tmp'
  332. if os.path.exists(tmp_path):
  333. shutil.rmtree(tmp_path)
  334. rename_with_retry(path, tmp_path)
  335. os.mkdir(path)
  336. base_path = tmp_path
  337. # walk given number of levels down
  338. for level in range(levels):
  339. contents = os.listdir(base_path)
  340. if len(contents) > 1:
  341. raise RuntimeError('at level {}, expected 1 entry, got {}'.format(level, contents))
  342. base_path = os.path.join(base_path, contents[0])
  343. if not os.path.isdir(base_path):
  344. raise RuntimeError('at level {}, {} is not a directory'.format(level, contents[0]))
  345. # get the list of directories/files to move
  346. contents = os.listdir(base_path)
  347. for name in contents:
  348. move_from = os.path.join(base_path, name)
  349. move_to = os.path.join(path, name)
  350. rename_with_retry(move_from, move_to)
  351. shutil.rmtree(tmp_path)
  352. class ToolNotFound(RuntimeError):
  353. pass
  354. class ToolExecError(RuntimeError):
  355. pass
  356. class DownloadError(RuntimeError):
  357. pass
  358. class IDFToolDownload(object):
  359. def __init__(self, platform_name, url, size, sha256):
  360. self.platform_name = platform_name
  361. self.url = url
  362. self.size = size
  363. self.sha256 = sha256
  364. self.platform_name = platform_name
  365. @functools.total_ordering
  366. class IDFToolVersion(object):
  367. STATUS_RECOMMENDED = 'recommended'
  368. STATUS_SUPPORTED = 'supported'
  369. STATUS_DEPRECATED = 'deprecated'
  370. STATUS_VALUES = [STATUS_RECOMMENDED, STATUS_SUPPORTED, STATUS_DEPRECATED]
  371. def __init__(self, version, status):
  372. self.version = version
  373. self.status = status
  374. self.downloads = OrderedDict()
  375. self.latest = False
  376. def __lt__(self, other):
  377. if self.status != other.status:
  378. return self.status > other.status
  379. else:
  380. assert not (self.status == IDFToolVersion.STATUS_RECOMMENDED
  381. and other.status == IDFToolVersion.STATUS_RECOMMENDED)
  382. return self.version < other.version
  383. def __eq__(self, other):
  384. return self.status == other.status and self.version == other.version
  385. def add_download(self, platform_name, url, size, sha256):
  386. self.downloads[platform_name] = IDFToolDownload(platform_name, url, size, sha256)
  387. def get_download_for_platform(self, platform_name): # type: (str) -> IDFToolDownload
  388. if platform_name in PLATFORM_FROM_NAME.keys():
  389. platform_name = PLATFORM_FROM_NAME[platform_name]
  390. if platform_name in self.downloads.keys():
  391. return self.downloads[platform_name]
  392. if 'any' in self.downloads.keys():
  393. return self.downloads['any']
  394. return None
  395. def compatible_with_platform(self, platform_name=PYTHON_PLATFORM):
  396. return self.get_download_for_platform(platform_name) is not None
  397. def get_supported_platforms(self): # type: () -> typing.Set[str]
  398. return set(self.downloads.keys())
  399. OPTIONS_LIST = ['version_cmd',
  400. 'version_regex',
  401. 'version_regex_replace',
  402. 'export_paths',
  403. 'export_vars',
  404. 'install',
  405. 'info_url',
  406. 'license',
  407. 'strip_container_dirs']
  408. IDFToolOptions = namedtuple('IDFToolOptions', OPTIONS_LIST)
  409. class IDFTool(object):
  410. # possible values of 'install' field
  411. INSTALL_ALWAYS = 'always'
  412. INSTALL_ON_REQUEST = 'on_request'
  413. INSTALL_NEVER = 'never'
  414. def __init__(self, name, description, install, info_url, license, version_cmd, version_regex, version_regex_replace=None,
  415. strip_container_dirs=0):
  416. self.name = name
  417. self.description = description
  418. self.versions = OrderedDict() # type: typing.Dict[str, IDFToolVersion]
  419. self.version_in_path = None
  420. self.versions_installed = []
  421. if version_regex_replace is None:
  422. version_regex_replace = VERSION_REGEX_REPLACE_DEFAULT
  423. self.options = IDFToolOptions(version_cmd, version_regex, version_regex_replace,
  424. [], OrderedDict(), install, info_url, license, strip_container_dirs)
  425. self.platform_overrides = []
  426. self._platform = CURRENT_PLATFORM
  427. self._update_current_options()
  428. def copy_for_platform(self, platform): # type: (str) -> IDFTool
  429. result = copy.deepcopy(self)
  430. result._platform = platform
  431. result._update_current_options()
  432. return result
  433. def _update_current_options(self):
  434. self._current_options = IDFToolOptions(*self.options)
  435. for override in self.platform_overrides:
  436. if self._platform not in override['platforms']:
  437. continue
  438. override_dict = override.copy()
  439. del override_dict['platforms']
  440. self._current_options = self._current_options._replace(**override_dict)
  441. def add_version(self, version):
  442. assert(type(version) is IDFToolVersion)
  443. self.versions[version.version] = version
  444. def get_path(self): # type: () -> str
  445. return os.path.join(global_idf_tools_path, 'tools', self.name)
  446. def get_path_for_version(self, version): # type: (str) -> str
  447. assert(version in self.versions)
  448. return os.path.join(self.get_path(), version)
  449. def get_export_paths(self, version): # type: (str) -> typing.List[str]
  450. tool_path = self.get_path_for_version(version)
  451. return [os.path.join(tool_path, *p) for p in self._current_options.export_paths]
  452. def get_export_vars(self, version): # type: (str) -> typing.Dict[str]
  453. """
  454. Get the dictionary of environment variables to be exported, for the given version.
  455. Expands:
  456. - ${TOOL_PATH} => the actual path where the version is installed
  457. """
  458. result = {}
  459. for k, v in self._current_options.export_vars.items():
  460. replace_path = self.get_path_for_version(version).replace('\\', '\\\\')
  461. v_repl = re.sub(SUBST_TOOL_PATH_REGEX, replace_path, v)
  462. if v_repl != v:
  463. v_repl = to_shell_specific_paths([v_repl])[0]
  464. result[k] = v_repl
  465. return result
  466. def check_version(self, extra_paths=None): # type: (typing.Optional[typing.List[str]]) -> str
  467. """
  468. Execute the tool, optionally prepending extra_paths to PATH,
  469. extract the version string and return it as a result.
  470. Raises ToolNotFound if the tool is not found (not present in the paths).
  471. Raises ToolExecError if the tool returns with a non-zero exit code.
  472. Returns 'unknown' if tool returns something from which version string
  473. can not be extracted.
  474. """
  475. # this function can not be called for a different platform
  476. assert self._platform == CURRENT_PLATFORM
  477. cmd = self._current_options.version_cmd
  478. try:
  479. version_cmd_result = run_cmd_check_output(cmd, None, extra_paths)
  480. except OSError:
  481. # tool is not on the path
  482. raise ToolNotFound('Tool {} not found'.format(self.name))
  483. except subprocess.CalledProcessError as e:
  484. raise ToolExecError('returned non-zero exit code ({}) with error message:\n{}'.format(
  485. e.returncode, e.stderr.decode('utf-8',errors='ignore'))) # type: ignore
  486. in_str = version_cmd_result.decode('utf-8')
  487. match = re.search(self._current_options.version_regex, in_str)
  488. if not match:
  489. return UNKNOWN_VERSION
  490. return re.sub(self._current_options.version_regex, self._current_options.version_regex_replace, match.group(0))
  491. def get_install_type(self):
  492. return self._current_options.install
  493. def compatible_with_platform(self):
  494. return any([v.compatible_with_platform() for v in self.versions.values()])
  495. def get_supported_platforms(self): # type: () -> typing.Set[str]
  496. result = set()
  497. for v in self.versions.values():
  498. result.update(v.get_supported_platforms())
  499. return result
  500. def get_recommended_version(self):
  501. recommended_versions = [k for k, v in self.versions.items()
  502. if v.status == IDFToolVersion.STATUS_RECOMMENDED
  503. and v.compatible_with_platform(self._platform)]
  504. assert len(recommended_versions) <= 1
  505. if recommended_versions:
  506. return recommended_versions[0]
  507. return None
  508. def get_preferred_installed_version(self):
  509. recommended_versions = [k for k in self.versions_installed
  510. if self.versions[k].status == IDFToolVersion.STATUS_RECOMMENDED
  511. and self.versions[k].compatible_with_platform(self._platform)]
  512. assert len(recommended_versions) <= 1
  513. if recommended_versions:
  514. return recommended_versions[0]
  515. return None
  516. def find_installed_versions(self):
  517. """
  518. Checks whether the tool can be found in PATH and in global_idf_tools_path.
  519. Writes results to self.version_in_path and self.versions_installed.
  520. """
  521. # this function can not be called for a different platform
  522. assert self._platform == CURRENT_PLATFORM
  523. # First check if the tool is in system PATH
  524. try:
  525. ver_str = self.check_version()
  526. except ToolNotFound:
  527. # not in PATH
  528. pass
  529. except ToolExecError as e:
  530. warn('tool {} found in path, but {}'.format(
  531. self.name, e))
  532. else:
  533. self.version_in_path = ver_str
  534. # Now check all the versions installed in global_idf_tools_path
  535. self.versions_installed = []
  536. for version, version_obj in self.versions.items():
  537. if not version_obj.compatible_with_platform():
  538. continue
  539. tool_path = self.get_path_for_version(version)
  540. if not os.path.exists(tool_path):
  541. # version not installed
  542. continue
  543. try:
  544. ver_str = self.check_version(self.get_export_paths(version))
  545. except ToolNotFound:
  546. warn('directory for tool {} version {} is present, but tool was not found'.format(
  547. self.name, version))
  548. except ToolExecError as e:
  549. warn('tool {} version {} is installed, but {}'.format(
  550. self.name, version, e))
  551. else:
  552. if ver_str != version:
  553. warn('tool {} version {} is installed, but has reported version {}'.format(
  554. self.name, version, ver_str))
  555. else:
  556. self.versions_installed.append(version)
  557. def download(self, version):
  558. assert(version in self.versions)
  559. download_obj = self.versions[version].get_download_for_platform(self._platform)
  560. if not download_obj:
  561. fatal('No packages for tool {} platform {}!'.format(self.name, self._platform))
  562. raise DownloadError()
  563. url = download_obj.url
  564. archive_name = os.path.basename(url)
  565. local_path = os.path.join(global_idf_tools_path, 'dist', archive_name)
  566. mkdir_p(os.path.dirname(local_path))
  567. if os.path.isfile(local_path):
  568. if not self.check_download_file(download_obj, local_path):
  569. warn('removing downloaded file {0} and downloading again'.format(archive_name))
  570. os.unlink(local_path)
  571. else:
  572. info('file {0} is already downloaded'.format(archive_name))
  573. return
  574. downloaded = False
  575. for retry in range(DOWNLOAD_RETRY_COUNT):
  576. local_temp_path = local_path + '.tmp'
  577. info('Downloading {} to {}'.format(archive_name, local_temp_path))
  578. try:
  579. ctx = None
  580. # For dl.espressif.com, add the ISRG x1 root certificate.
  581. # This works around the issue with outdated certificate stores in some installations.
  582. if 'dl.espressif.com' in url:
  583. try:
  584. ctx = ssl.create_default_context()
  585. ctx.load_verify_locations(cadata=ISRG_X1_ROOT_CERT)
  586. except AttributeError:
  587. # no ssl.create_default_context or load_verify_locations cadata argument
  588. # in Python <=2.7.8
  589. pass
  590. urlretrieve_ctx(url, local_temp_path, report_progress if not global_non_interactive else None, context=ctx)
  591. sys.stdout.write('\rDone\n')
  592. except Exception as e:
  593. # urlretrieve could throw different exceptions, e.g. IOError when the server is down
  594. # Errors are ignored because the downloaded file is checked a couple of lines later.
  595. warn('Download failure {}'.format(e))
  596. sys.stdout.flush()
  597. if not os.path.isfile(local_temp_path) or not self.check_download_file(download_obj, local_temp_path):
  598. warn('Failed to download {} to {}'.format(url, local_temp_path))
  599. continue
  600. rename_with_retry(local_temp_path, local_path)
  601. downloaded = True
  602. break
  603. if not downloaded:
  604. fatal('Failed to download, and retry count has expired')
  605. raise DownloadError()
  606. def install(self, version):
  607. # Currently this is called after calling 'download' method, so here are a few asserts
  608. # for the conditions which should be true once that method is done.
  609. assert (version in self.versions)
  610. download_obj = self.versions[version].get_download_for_platform(self._platform)
  611. assert (download_obj is not None)
  612. archive_name = os.path.basename(download_obj.url)
  613. archive_path = os.path.join(global_idf_tools_path, 'dist', archive_name)
  614. assert (os.path.isfile(archive_path))
  615. dest_dir = self.get_path_for_version(version)
  616. if os.path.exists(dest_dir):
  617. warn('destination path already exists, removing')
  618. shutil.rmtree(dest_dir)
  619. mkdir_p(dest_dir)
  620. unpack(archive_path, dest_dir)
  621. if self._current_options.strip_container_dirs:
  622. strip_container_dirs(dest_dir, self._current_options.strip_container_dirs)
  623. @staticmethod
  624. def check_download_file(download_obj, local_path):
  625. expected_sha256 = download_obj.sha256
  626. expected_size = download_obj.size
  627. file_size, file_sha256 = get_file_size_sha256(local_path)
  628. if file_size != expected_size:
  629. warn('file size mismatch for {}, expected {}, got {}'.format(local_path, expected_size, file_size))
  630. return False
  631. if file_sha256 != expected_sha256:
  632. warn('hash mismatch for {}, expected {}, got {}'.format(local_path, expected_sha256, file_sha256))
  633. return False
  634. return True
  635. @classmethod
  636. def from_json(cls, tool_dict):
  637. # json.load will return 'str' types in Python 3 and 'unicode' in Python 2
  638. expected_str_type = type(u'')
  639. # Validate json fields
  640. tool_name = tool_dict.get('name')
  641. if type(tool_name) is not expected_str_type:
  642. raise RuntimeError('tool_name is not a string')
  643. description = tool_dict.get('description')
  644. if type(description) is not expected_str_type:
  645. raise RuntimeError('description is not a string')
  646. version_cmd = tool_dict.get('version_cmd')
  647. if type(version_cmd) is not list:
  648. raise RuntimeError('version_cmd for tool %s is not a list of strings' % tool_name)
  649. version_regex = tool_dict.get('version_regex')
  650. if type(version_regex) is not expected_str_type or not version_regex:
  651. raise RuntimeError('version_regex for tool %s is not a non-empty string' % tool_name)
  652. version_regex_replace = tool_dict.get('version_regex_replace')
  653. if version_regex_replace and type(version_regex_replace) is not expected_str_type:
  654. raise RuntimeError('version_regex_replace for tool %s is not a string' % tool_name)
  655. export_paths = tool_dict.get('export_paths')
  656. if type(export_paths) is not list:
  657. raise RuntimeError('export_paths for tool %s is not a list' % tool_name)
  658. export_vars = tool_dict.get('export_vars', {})
  659. if type(export_vars) is not dict:
  660. raise RuntimeError('export_vars for tool %s is not a mapping' % tool_name)
  661. versions = tool_dict.get('versions')
  662. if type(versions) is not list:
  663. raise RuntimeError('versions for tool %s is not an array' % tool_name)
  664. install = tool_dict.get('install', False)
  665. if type(install) is not expected_str_type:
  666. raise RuntimeError('install for tool %s is not a string' % tool_name)
  667. info_url = tool_dict.get('info_url', False)
  668. if type(info_url) is not expected_str_type:
  669. raise RuntimeError('info_url for tool %s is not a string' % tool_name)
  670. license = tool_dict.get('license', False)
  671. if type(license) is not expected_str_type:
  672. raise RuntimeError('license for tool %s is not a string' % tool_name)
  673. strip_container_dirs = tool_dict.get('strip_container_dirs', 0)
  674. if strip_container_dirs and type(strip_container_dirs) is not int:
  675. raise RuntimeError('strip_container_dirs for tool %s is not an int' % tool_name)
  676. overrides_list = tool_dict.get('platform_overrides', [])
  677. if type(overrides_list) is not list:
  678. raise RuntimeError('platform_overrides for tool %s is not a list' % tool_name)
  679. # Create the object
  680. tool_obj = cls(tool_name, description, install, info_url, license,
  681. version_cmd, version_regex, version_regex_replace,
  682. strip_container_dirs)
  683. for path in export_paths:
  684. tool_obj.options.export_paths.append(path)
  685. for name, value in export_vars.items():
  686. tool_obj.options.export_vars[name] = value
  687. for index, override in enumerate(overrides_list):
  688. platforms_list = override.get('platforms')
  689. if type(platforms_list) is not list:
  690. raise RuntimeError('platforms for override %d of tool %s is not a list' % (index, tool_name))
  691. install = override.get('install')
  692. if install is not None and type(install) is not expected_str_type:
  693. raise RuntimeError('install for override %d of tool %s is not a string' % (index, tool_name))
  694. version_cmd = override.get('version_cmd')
  695. if version_cmd is not None and type(version_cmd) is not list:
  696. raise RuntimeError('version_cmd for override %d of tool %s is not a list of strings' %
  697. (index, tool_name))
  698. version_regex = override.get('version_regex')
  699. if version_regex is not None and (type(version_regex) is not expected_str_type or not version_regex):
  700. raise RuntimeError('version_regex for override %d of tool %s is not a non-empty string' %
  701. (index, tool_name))
  702. version_regex_replace = override.get('version_regex_replace')
  703. if version_regex_replace is not None and type(version_regex_replace) is not expected_str_type:
  704. raise RuntimeError('version_regex_replace for override %d of tool %s is not a string' %
  705. (index, tool_name))
  706. export_paths = override.get('export_paths')
  707. if export_paths is not None and type(export_paths) is not list:
  708. raise RuntimeError('export_paths for override %d of tool %s is not a list' % (index, tool_name))
  709. export_vars = override.get('export_vars')
  710. if export_vars is not None and type(export_vars) is not dict:
  711. raise RuntimeError('export_vars for override %d of tool %s is not a mapping' % (index, tool_name))
  712. tool_obj.platform_overrides.append(override)
  713. recommended_versions = {}
  714. for version_dict in versions:
  715. version = version_dict.get('name')
  716. if type(version) is not expected_str_type:
  717. raise RuntimeError('version name for tool {} is not a string'.format(tool_name))
  718. version_status = version_dict.get('status')
  719. if type(version_status) is not expected_str_type and version_status not in IDFToolVersion.STATUS_VALUES:
  720. raise RuntimeError('tool {} version {} status is not one of {}', tool_name, version,
  721. IDFToolVersion.STATUS_VALUES)
  722. version_obj = IDFToolVersion(version, version_status)
  723. for platform_id, platform_dict in version_dict.items():
  724. if platform_id in ['name', 'status']:
  725. continue
  726. if platform_id not in PLATFORM_FROM_NAME.keys():
  727. raise RuntimeError('invalid platform %s for tool %s version %s' %
  728. (platform_id, tool_name, version))
  729. version_obj.add_download(platform_id,
  730. platform_dict['url'], platform_dict['size'], platform_dict['sha256'])
  731. if version_status == IDFToolVersion.STATUS_RECOMMENDED:
  732. if platform_id not in recommended_versions:
  733. recommended_versions[platform_id] = []
  734. recommended_versions[platform_id].append(version)
  735. tool_obj.add_version(version_obj)
  736. for platform_id, version_list in recommended_versions.items():
  737. if len(version_list) > 1:
  738. raise RuntimeError('tool {} for platform {} has {} recommended versions'.format(
  739. tool_name, platform_id, len(recommended_versions)))
  740. if install != IDFTool.INSTALL_NEVER and len(recommended_versions) == 0:
  741. raise RuntimeError('required/optional tool {} for platform {} has no recommended versions'.format(
  742. tool_name, platform_id))
  743. tool_obj._update_current_options()
  744. return tool_obj
  745. def to_json(self):
  746. versions_array = []
  747. for version, version_obj in self.versions.items():
  748. version_json = {
  749. 'name': version,
  750. 'status': version_obj.status
  751. }
  752. for platform_id, download in version_obj.downloads.items():
  753. version_json[platform_id] = {
  754. 'url': download.url,
  755. 'size': download.size,
  756. 'sha256': download.sha256
  757. }
  758. versions_array.append(version_json)
  759. overrides_array = self.platform_overrides
  760. tool_json = {
  761. 'name': self.name,
  762. 'description': self.description,
  763. 'export_paths': self.options.export_paths,
  764. 'export_vars': self.options.export_vars,
  765. 'install': self.options.install,
  766. 'info_url': self.options.info_url,
  767. 'license': self.options.license,
  768. 'version_cmd': self.options.version_cmd,
  769. 'version_regex': self.options.version_regex,
  770. 'versions': versions_array,
  771. }
  772. if self.options.version_regex_replace != VERSION_REGEX_REPLACE_DEFAULT:
  773. tool_json['version_regex_replace'] = self.options.version_regex_replace
  774. if overrides_array:
  775. tool_json['platform_overrides'] = overrides_array
  776. if self.options.strip_container_dirs:
  777. tool_json['strip_container_dirs'] = self.options.strip_container_dirs
  778. return tool_json
  779. def load_tools_info(): # type: () -> typing.Dict[str, IDFTool]
  780. """
  781. Load tools metadata from tools.json, return a dictionary: tool name - tool info
  782. """
  783. tool_versions_file_name = global_tools_json
  784. with open(tool_versions_file_name, 'r') as f:
  785. tools_info = json.load(f)
  786. return parse_tools_info_json(tools_info)
  787. def parse_tools_info_json(tools_info):
  788. """
  789. Parse and validate the dictionary obtained by loading the tools.json file.
  790. Returns a dictionary of tools (key: tool name, value: IDFTool object).
  791. """
  792. if tools_info['version'] != TOOLS_FILE_VERSION:
  793. raise RuntimeError('Invalid version')
  794. tools_dict = OrderedDict()
  795. tools_array = tools_info.get('tools')
  796. if type(tools_array) is not list:
  797. raise RuntimeError('tools property is missing or not an array')
  798. for tool_dict in tools_array:
  799. tool = IDFTool.from_json(tool_dict)
  800. tools_dict[tool.name] = tool
  801. return tools_dict
  802. def dump_tools_json(tools_info):
  803. tools_array = []
  804. for tool_name, tool_obj in tools_info.items():
  805. tool_json = tool_obj.to_json()
  806. tools_array.append(tool_json)
  807. file_json = {'version': TOOLS_FILE_VERSION, 'tools': tools_array}
  808. return json.dumps(file_json, indent=2, separators=(',', ': '), sort_keys=True)
  809. def get_python_env_path():
  810. python_ver_major_minor = '{}.{}'.format(sys.version_info.major, sys.version_info.minor)
  811. version_file_path = os.path.join(global_idf_path, 'version.txt')
  812. if os.path.exists(version_file_path):
  813. with open(version_file_path, 'r') as version_file:
  814. idf_version_str = version_file.read()
  815. else:
  816. idf_version_str = ''
  817. try:
  818. idf_version_str = subprocess.check_output(['git', 'describe'],
  819. cwd=global_idf_path, env=os.environ).decode()
  820. except OSError:
  821. # OSError should cover FileNotFoundError and WindowsError
  822. warn('Git was not found')
  823. except subprocess.CalledProcessError as e:
  824. warn('Git describe was unsuccessul: {}'.format(e.output))
  825. match = re.match(r'^v([0-9]+\.[0-9]+).*', idf_version_str)
  826. if match:
  827. idf_version = match.group(1)
  828. else:
  829. idf_version = None
  830. # fallback when IDF is a shallow clone
  831. try:
  832. with open(os.path.join(global_idf_path, 'components', 'esp_common', 'include', 'esp_idf_version.h')) as f:
  833. m = re.search(r'^#define\s+ESP_IDF_VERSION_MAJOR\s+(\d+).+?^#define\s+ESP_IDF_VERSION_MINOR\s+(\d+)',
  834. f.read(), re.DOTALL | re.MULTILINE)
  835. if m:
  836. idf_version = '.'.join((m.group(1), m.group(2)))
  837. else:
  838. warn('Reading IDF version from C header file failed!')
  839. except Exception as e:
  840. warn('Is it not possible to determine the IDF version: {}'.format(e))
  841. if idf_version is None:
  842. fatal('IDF version cannot be determined')
  843. raise SystemExit(1)
  844. idf_python_env_path = os.path.join(global_idf_tools_path, 'python_env',
  845. 'idf{}_py{}_env'.format(idf_version, python_ver_major_minor))
  846. if sys.platform == 'win32':
  847. subdir = 'Scripts'
  848. python_exe = 'python.exe'
  849. else:
  850. subdir = 'bin'
  851. python_exe = 'python'
  852. idf_python_export_path = os.path.join(idf_python_env_path, subdir)
  853. virtualenv_python = os.path.join(idf_python_export_path, python_exe)
  854. return idf_python_env_path, idf_python_export_path, virtualenv_python
  855. def action_list(args):
  856. tools_info = load_tools_info()
  857. for name, tool in tools_info.items():
  858. if tool.get_install_type() == IDFTool.INSTALL_NEVER:
  859. continue
  860. optional_str = ' (optional)' if tool.get_install_type() == IDFTool.INSTALL_ON_REQUEST else ''
  861. info('* {}: {}{}'.format(name, tool.description, optional_str))
  862. tool.find_installed_versions()
  863. versions_for_platform = {k: v for k, v in tool.versions.items() if v.compatible_with_platform()}
  864. if not versions_for_platform:
  865. info(' (no versions compatible with platform {})'.format(PYTHON_PLATFORM))
  866. continue
  867. versions_sorted = sorted(versions_for_platform.keys(), key=tool.versions.get, reverse=True)
  868. for version in versions_sorted:
  869. version_obj = tool.versions[version]
  870. info(' - {} ({}{})'.format(version, version_obj.status,
  871. ', installed' if version in tool.versions_installed else ''))
  872. def action_check(args):
  873. tools_info = load_tools_info()
  874. not_found_list = []
  875. info('Checking for installed tools...')
  876. for name, tool in tools_info.items():
  877. if tool.get_install_type() == IDFTool.INSTALL_NEVER:
  878. continue
  879. tool_found_somewhere = False
  880. info('Checking tool %s' % name)
  881. tool.find_installed_versions()
  882. if tool.version_in_path:
  883. info(' version found in PATH: %s' % tool.version_in_path)
  884. tool_found_somewhere = True
  885. else:
  886. info(' no version found in PATH')
  887. for version in tool.versions_installed:
  888. info(' version installed in tools directory: %s' % version)
  889. tool_found_somewhere = True
  890. if not tool_found_somewhere and tool.get_install_type() == IDFTool.INSTALL_ALWAYS:
  891. not_found_list.append(name)
  892. if not_found_list:
  893. fatal('The following required tools were not found: ' + ' '.join(not_found_list))
  894. raise SystemExit(1)
  895. def action_export(args):
  896. tools_info = load_tools_info()
  897. all_tools_found = True
  898. export_vars = {}
  899. paths_to_export = []
  900. for name, tool in tools_info.items():
  901. if tool.get_install_type() == IDFTool.INSTALL_NEVER:
  902. continue
  903. tool.find_installed_versions()
  904. if tool.version_in_path:
  905. if tool.version_in_path not in tool.versions:
  906. # unsupported version
  907. if args.prefer_system:
  908. warn('using an unsupported version of tool {} found in PATH: {}'.format(
  909. tool.name, tool.version_in_path))
  910. continue
  911. else:
  912. # unsupported version in path
  913. pass
  914. else:
  915. # supported/deprecated version in PATH, use it
  916. version_obj = tool.versions[tool.version_in_path]
  917. if version_obj.status == IDFToolVersion.STATUS_SUPPORTED:
  918. info('Using a supported version of tool {} found in PATH: {}.'.format(name, tool.version_in_path),
  919. f=sys.stderr)
  920. info('However the recommended version is {}.'.format(tool.get_recommended_version()),
  921. f=sys.stderr)
  922. elif version_obj.status == IDFToolVersion.STATUS_DEPRECATED:
  923. warn('using a deprecated version of tool {} found in PATH: {}'.format(name, tool.version_in_path))
  924. continue
  925. self_restart_cmd = '{} {}{}'.format(sys.executable, __file__,
  926. (' --tools-json ' + args.tools_json) if args.tools_json else '')
  927. self_restart_cmd = to_shell_specific_paths([self_restart_cmd])[0]
  928. if IDF_TOOLS_EXPORT_CMD:
  929. prefer_system_hint = ''
  930. else:
  931. prefer_system_hint = ' To use it, run \'{} export --prefer-system\''.format(self_restart_cmd)
  932. if IDF_TOOLS_INSTALL_CMD:
  933. install_cmd = to_shell_specific_paths([IDF_TOOLS_INSTALL_CMD])[0]
  934. else:
  935. install_cmd = self_restart_cmd + ' install'
  936. if not tool.versions_installed:
  937. if tool.get_install_type() == IDFTool.INSTALL_ALWAYS:
  938. all_tools_found = False
  939. fatal('tool {} has no installed versions. Please run \'{}\' to install it.'.format(
  940. tool.name, install_cmd))
  941. if tool.version_in_path and tool.version_in_path not in tool.versions:
  942. info('An unsupported version of tool {} was found in PATH: {}. '.format(name, tool.version_in_path) +
  943. prefer_system_hint, f=sys.stderr)
  944. continue
  945. else:
  946. # tool is optional, and does not have versions installed
  947. # use whatever is available in PATH
  948. continue
  949. if tool.version_in_path and tool.version_in_path not in tool.versions:
  950. info('Not using an unsupported version of tool {} found in PATH: {}.'.format(
  951. tool.name, tool.version_in_path) + prefer_system_hint, f=sys.stderr)
  952. version_to_use = tool.get_preferred_installed_version()
  953. export_paths = tool.get_export_paths(version_to_use)
  954. if export_paths:
  955. paths_to_export += export_paths
  956. tool_export_vars = tool.get_export_vars(version_to_use)
  957. for k, v in tool_export_vars.items():
  958. old_v = os.environ.get(k)
  959. if old_v is None or old_v != v:
  960. export_vars[k] = v
  961. current_path = os.getenv('PATH')
  962. idf_python_env_path, idf_python_export_path, virtualenv_python = get_python_env_path()
  963. if os.path.exists(virtualenv_python):
  964. idf_python_env_path = to_shell_specific_paths([idf_python_env_path])[0]
  965. if os.getenv('IDF_PYTHON_ENV_PATH') != idf_python_env_path:
  966. export_vars['IDF_PYTHON_ENV_PATH'] = to_shell_specific_paths([idf_python_env_path])[0]
  967. if idf_python_export_path not in current_path:
  968. paths_to_export.append(idf_python_export_path)
  969. idf_tools_dir = os.path.join(global_idf_path, 'tools')
  970. idf_tools_dir = to_shell_specific_paths([idf_tools_dir])[0]
  971. if idf_tools_dir not in current_path:
  972. paths_to_export.append(idf_tools_dir)
  973. if sys.platform == 'win32' and 'MSYSTEM' not in os.environ:
  974. old_path = '%PATH%'
  975. path_sep = ';'
  976. else:
  977. old_path = '$PATH'
  978. # can't trust os.pathsep here, since for Windows Python started from MSYS shell,
  979. # os.pathsep will be ';'
  980. path_sep = ':'
  981. if args.format == EXPORT_SHELL:
  982. if sys.platform == 'win32' and 'MSYSTEM' not in os.environ:
  983. export_format = 'SET "{}={}"'
  984. export_sep = '\n'
  985. else:
  986. export_format = 'export {}="{}"'
  987. export_sep = ';'
  988. elif args.format == EXPORT_KEY_VALUE:
  989. export_format = '{}={}'
  990. export_sep = '\n'
  991. else:
  992. raise NotImplementedError('unsupported export format {}'.format(args.format))
  993. if paths_to_export:
  994. export_vars['PATH'] = path_sep.join(to_shell_specific_paths(paths_to_export) + [old_path])
  995. export_statements = export_sep.join([export_format.format(k, v) for k, v in export_vars.items()])
  996. if export_statements:
  997. print(export_statements)
  998. if not all_tools_found:
  999. raise SystemExit(1)
  1000. def apply_url_mirrors(args, tool_download_obj):
  1001. apply_mirror_prefix_map(args, tool_download_obj)
  1002. apply_github_assets_option(tool_download_obj)
  1003. def apply_mirror_prefix_map(args, tool_download_obj):
  1004. """Rewrite URL for given tool_obj, given tool_version, and current platform,
  1005. if --mirror-prefix-map flag or IDF_MIRROR_PREFIX_MAP environment variable is given.
  1006. """
  1007. mirror_prefix_map = None
  1008. mirror_prefix_map_env = os.getenv('IDF_MIRROR_PREFIX_MAP')
  1009. if mirror_prefix_map_env:
  1010. mirror_prefix_map = mirror_prefix_map_env.split(';')
  1011. if IDF_MAINTAINER and args.mirror_prefix_map:
  1012. if mirror_prefix_map:
  1013. warn('Both IDF_MIRROR_PREFIX_MAP environment variable and --mirror-prefix-map flag are specified, ' +
  1014. 'will use the value from the command line.')
  1015. mirror_prefix_map = args.mirror_prefix_map
  1016. if mirror_prefix_map and tool_download_obj:
  1017. for item in mirror_prefix_map:
  1018. if URL_PREFIX_MAP_SEPARATOR not in item:
  1019. warn('invalid mirror-prefix-map item (missing \'{}\') {}'.format(URL_PREFIX_MAP_SEPARATOR, item))
  1020. continue
  1021. search, replace = item.split(URL_PREFIX_MAP_SEPARATOR, 1)
  1022. old_url = tool_download_obj.url
  1023. new_url = re.sub(search, replace, old_url)
  1024. if new_url != old_url:
  1025. info('Changed download URL: {} => {}'.format(old_url, new_url))
  1026. tool_download_obj.url = new_url
  1027. break
  1028. def apply_github_assets_option(tool_download_obj):
  1029. """ Rewrite URL for given tool_obj if the download URL is an https://github.com/ URL and the variable
  1030. IDF_GITHUB_ASSETS is set. The github.com part of the URL will be replaced.
  1031. """
  1032. try:
  1033. github_assets = os.environ['IDF_GITHUB_ASSETS'].strip()
  1034. except KeyError:
  1035. return # no IDF_GITHUB_ASSETS
  1036. if not github_assets: # variable exists but is empty
  1037. return
  1038. # check no URL qualifier in the mirror URL
  1039. if '://' in github_assets:
  1040. fatal("IDF_GITHUB_ASSETS shouldn't include any URL qualifier, https:// is assumed")
  1041. raise SystemExit(1)
  1042. # Strip any trailing / from the mirror URL
  1043. github_assets = github_assets.rstrip('/')
  1044. old_url = tool_download_obj.url
  1045. new_url = re.sub(r'^https://github.com/', 'https://{}/'.format(github_assets), old_url)
  1046. if new_url != old_url:
  1047. info('Using GitHub assets mirror for URL: {} => {}'.format(old_url, new_url))
  1048. tool_download_obj.url = new_url
  1049. def action_download(args):
  1050. tools_info = load_tools_info()
  1051. tools_spec = args.tools
  1052. if args.platform not in PLATFORM_FROM_NAME:
  1053. fatal('unknown platform: {}' % args.platform)
  1054. raise SystemExit(1)
  1055. platform = PLATFORM_FROM_NAME[args.platform]
  1056. tools_info_for_platform = OrderedDict()
  1057. for name, tool_obj in tools_info.items():
  1058. tool_for_platform = tool_obj.copy_for_platform(platform)
  1059. tools_info_for_platform[name] = tool_for_platform
  1060. if not tools_spec or 'required' in tools_spec:
  1061. tools_spec = [k for k, v in tools_info_for_platform.items() if v.get_install_type() == IDFTool.INSTALL_ALWAYS]
  1062. info('Downloading tools for {}: {}'.format(platform, ', '.join(tools_spec)))
  1063. elif 'all' in tools_spec:
  1064. tools_spec = [k for k, v in tools_info_for_platform.items() if v.get_install_type() != IDFTool.INSTALL_NEVER]
  1065. info('Downloading tools for {}: {}'.format(platform, ', '.join(tools_spec)))
  1066. for tool_spec in tools_spec:
  1067. if '@' not in tool_spec:
  1068. tool_name = tool_spec
  1069. tool_version = None
  1070. else:
  1071. tool_name, tool_version = tool_spec.split('@', 1)
  1072. if tool_name not in tools_info_for_platform:
  1073. fatal('unknown tool name: {}'.format(tool_name))
  1074. raise SystemExit(1)
  1075. tool_obj = tools_info_for_platform[tool_name]
  1076. if tool_version is not None and tool_version not in tool_obj.versions:
  1077. fatal('unknown version for tool {}: {}'.format(tool_name, tool_version))
  1078. raise SystemExit(1)
  1079. if tool_version is None:
  1080. tool_version = tool_obj.get_recommended_version()
  1081. if tool_version is None:
  1082. fatal('tool {} not found for {} platform'.format(tool_name, platform))
  1083. raise SystemExit(1)
  1084. tool_spec = '{}@{}'.format(tool_name, tool_version)
  1085. info('Downloading {}'.format(tool_spec))
  1086. apply_url_mirrors(args, tool_obj.versions[tool_version].get_download_for_platform(platform))
  1087. tool_obj.download(tool_version)
  1088. def action_install(args):
  1089. tools_info = load_tools_info()
  1090. tools_spec = args.tools
  1091. if not tools_spec or 'required' in tools_spec:
  1092. tools_spec = [k for k, v in tools_info.items() if v.get_install_type() == IDFTool.INSTALL_ALWAYS]
  1093. info('Installing tools: {}'.format(', '.join(tools_spec)))
  1094. elif 'all' in tools_spec:
  1095. tools_spec = [k for k, v in tools_info.items() if v.get_install_type() != IDFTool.INSTALL_NEVER]
  1096. info('Installing tools: {}'.format(', '.join(tools_spec)))
  1097. for tool_spec in tools_spec:
  1098. if '@' not in tool_spec:
  1099. tool_name = tool_spec
  1100. tool_version = None
  1101. else:
  1102. tool_name, tool_version = tool_spec.split('@', 1)
  1103. if tool_name not in tools_info:
  1104. fatal('unknown tool name: {}'.format(tool_name))
  1105. raise SystemExit(1)
  1106. tool_obj = tools_info[tool_name]
  1107. if not tool_obj.compatible_with_platform():
  1108. fatal('tool {} does not have versions compatible with platform {}'.format(tool_name, CURRENT_PLATFORM))
  1109. raise SystemExit(1)
  1110. if tool_version is not None and tool_version not in tool_obj.versions:
  1111. fatal('unknown version for tool {}: {}'.format(tool_name, tool_version))
  1112. raise SystemExit(1)
  1113. if tool_version is None:
  1114. tool_version = tool_obj.get_recommended_version()
  1115. assert tool_version is not None
  1116. tool_obj.find_installed_versions()
  1117. tool_spec = '{}@{}'.format(tool_name, tool_version)
  1118. if tool_version in tool_obj.versions_installed:
  1119. info('Skipping {} (already installed)'.format(tool_spec))
  1120. continue
  1121. info('Installing {}'.format(tool_spec))
  1122. apply_url_mirrors(args, tool_obj.versions[tool_version].get_download_for_platform(PYTHON_PLATFORM))
  1123. tool_obj.download(tool_version)
  1124. tool_obj.install(tool_version)
  1125. def get_wheels_dir():
  1126. tools_info = load_tools_info()
  1127. wheels_package_name = 'idf-python-wheels'
  1128. if wheels_package_name not in tools_info:
  1129. return None
  1130. wheels_package = tools_info[wheels_package_name]
  1131. recommended_version = wheels_package.get_recommended_version()
  1132. if recommended_version is None:
  1133. return None
  1134. wheels_dir = wheels_package.get_path_for_version(recommended_version)
  1135. if not os.path.exists(wheels_dir):
  1136. return None
  1137. return wheels_dir
  1138. def action_install_python_env(args): # type: ignore
  1139. reinstall = args.reinstall
  1140. idf_python_env_path, _, virtualenv_python = get_python_env_path()
  1141. is_virtualenv = hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix)
  1142. if is_virtualenv and (not os.path.exists(idf_python_env_path) or reinstall):
  1143. fatal('This script was called from a virtual environment, can not create a virtual environment again')
  1144. raise SystemExit(1)
  1145. if os.path.exists(virtualenv_python):
  1146. try:
  1147. subprocess.check_call([virtualenv_python, '--version'], stdout=sys.stdout, stderr=sys.stderr)
  1148. except (OSError, subprocess.CalledProcessError):
  1149. # At this point we can reinstall the virtual environment if it is non-functional. This can happen at least
  1150. # when the Python interpreter was removed which was used to create the virtual environment.
  1151. reinstall = True
  1152. try:
  1153. subprocess.check_call([virtualenv_python, '-m', 'pip', '--version'], stdout=sys.stdout, stderr=sys.stderr)
  1154. except subprocess.CalledProcessError:
  1155. warn('PIP is not available in the virtual environment.')
  1156. # Reinstallation of the virtual environment could help if PIP was installed for the main Python
  1157. reinstall = True
  1158. if reinstall and os.path.exists(idf_python_env_path):
  1159. warn('Removing the existing Python environment in {}'.format(idf_python_env_path))
  1160. shutil.rmtree(idf_python_env_path)
  1161. if not os.path.exists(virtualenv_python):
  1162. info('Creating a new Python environment in {}'.format(idf_python_env_path))
  1163. try:
  1164. import virtualenv # noqa: F401
  1165. except ImportError:
  1166. info('Installing virtualenv')
  1167. subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--user', 'virtualenv'],
  1168. stdout=sys.stdout, stderr=sys.stderr)
  1169. subprocess.check_call([sys.executable, '-m', 'virtualenv', idf_python_env_path],
  1170. stdout=sys.stdout, stderr=sys.stderr)
  1171. run_args = [virtualenv_python, '-m', 'pip', 'install', '--no-warn-script-location']
  1172. requirements_txt = os.path.join(global_idf_path, 'requirements.txt')
  1173. run_args += ['-r', requirements_txt]
  1174. if args.extra_wheels_dir:
  1175. run_args += ['--find-links', args.extra_wheels_dir]
  1176. if args.no_index:
  1177. run_args += ['--no-index']
  1178. if args.extra_wheels_url:
  1179. run_args += ['--extra-index-url', args.extra_wheels_url]
  1180. wheels_dir = get_wheels_dir()
  1181. if wheels_dir is not None:
  1182. run_args += ['--find-links', wheels_dir]
  1183. info('Installing Python packages from {}'.format(requirements_txt))
  1184. subprocess.check_call(run_args, stdout=sys.stdout, stderr=sys.stderr)
  1185. def action_add_version(args):
  1186. tools_info = load_tools_info()
  1187. tool_name = args.tool
  1188. tool_obj = tools_info.get(tool_name)
  1189. if not tool_obj:
  1190. info('Creating new tool entry for {}'.format(tool_name))
  1191. tool_obj = IDFTool(tool_name, TODO_MESSAGE, IDFTool.INSTALL_ALWAYS,
  1192. TODO_MESSAGE, TODO_MESSAGE, [TODO_MESSAGE], TODO_MESSAGE)
  1193. tools_info[tool_name] = tool_obj
  1194. version = args.version
  1195. version_obj = tool_obj.versions.get(version)
  1196. if version not in tool_obj.versions:
  1197. info('Creating new version {}'.format(version))
  1198. version_obj = IDFToolVersion(version, IDFToolVersion.STATUS_SUPPORTED)
  1199. tool_obj.versions[version] = version_obj
  1200. url_prefix = args.url_prefix or 'https://%s/' % TODO_MESSAGE
  1201. for file_path in args.files:
  1202. file_name = os.path.basename(file_path)
  1203. # Guess which platform this file is for
  1204. found_platform = None
  1205. for platform_alias, platform_id in PLATFORM_FROM_NAME.items():
  1206. if platform_alias in file_name:
  1207. found_platform = platform_id
  1208. break
  1209. if found_platform is None:
  1210. info('Could not guess platform for file {}'.format(file_name))
  1211. found_platform = TODO_MESSAGE
  1212. # Get file size and calculate the SHA256
  1213. file_size, file_sha256 = get_file_size_sha256(file_path)
  1214. url = url_prefix + file_name
  1215. info('Adding download for platform {}'.format(found_platform))
  1216. info(' size: {}'.format(file_size))
  1217. info(' SHA256: {}'.format(file_sha256))
  1218. info(' URL: {}'.format(url))
  1219. version_obj.add_download(found_platform, url, file_size, file_sha256)
  1220. json_str = dump_tools_json(tools_info)
  1221. if not args.output:
  1222. args.output = os.path.join(global_idf_path, TOOLS_FILE_NEW)
  1223. with open(args.output, 'w') as f:
  1224. f.write(json_str)
  1225. f.write('\n')
  1226. info('Wrote output to {}'.format(args.output))
  1227. def action_rewrite(args):
  1228. tools_info = load_tools_info()
  1229. json_str = dump_tools_json(tools_info)
  1230. if not args.output:
  1231. args.output = os.path.join(global_idf_path, TOOLS_FILE_NEW)
  1232. with open(args.output, 'w') as f:
  1233. f.write(json_str)
  1234. f.write('\n')
  1235. info('Wrote output to {}'.format(args.output))
  1236. def action_validate(args):
  1237. try:
  1238. import jsonschema
  1239. except ImportError:
  1240. fatal('You need to install jsonschema package to use validate command')
  1241. raise SystemExit(1)
  1242. with open(os.path.join(global_idf_path, TOOLS_FILE), 'r') as tools_file:
  1243. tools_json = json.load(tools_file)
  1244. with open(os.path.join(global_idf_path, TOOLS_SCHEMA_FILE), 'r') as schema_file:
  1245. schema_json = json.load(schema_file)
  1246. jsonschema.validate(tools_json, schema_json)
  1247. # on failure, this will raise an exception with a fairly verbose diagnostic message
  1248. def action_gen_doc(args):
  1249. f = args.output
  1250. tools_info = load_tools_info()
  1251. def print_out(text):
  1252. f.write(text + '\n')
  1253. print_out('.. |zwsp| unicode:: U+200B')
  1254. print_out(' :trim:')
  1255. print_out('')
  1256. idf_gh_url = 'https://github.com/espressif/esp-idf'
  1257. for tool_name, tool_obj in tools_info.items():
  1258. info_url = tool_obj.options.info_url
  1259. if idf_gh_url + '/tree' in info_url:
  1260. info_url = re.sub(idf_gh_url + r'/tree/\w+/(.*)', r':idf:`\1`', info_url)
  1261. license_url = 'https://spdx.org/licenses/' + tool_obj.options.license
  1262. print_out("""
  1263. .. _tool-{name}:
  1264. {name}
  1265. {underline}
  1266. {description}
  1267. .. include:: idf-tools-notes.inc
  1268. :start-after: tool-{name}-notes
  1269. :end-before: ---
  1270. License: `{license} <{license_url}>`_
  1271. More info: {info_url}
  1272. .. list-table::
  1273. :widths: 10 10 80
  1274. :header-rows: 1
  1275. * - Platform
  1276. - Required
  1277. - Download
  1278. """.rstrip().format(name=tool_name,
  1279. underline=args.heading_underline_char * len(tool_name),
  1280. description=tool_obj.description,
  1281. license=tool_obj.options.license,
  1282. license_url=license_url,
  1283. info_url=info_url))
  1284. for platform_name in sorted(tool_obj.get_supported_platforms()):
  1285. platform_tool = tool_obj.copy_for_platform(platform_name)
  1286. install_type = platform_tool.get_install_type()
  1287. if install_type == IDFTool.INSTALL_NEVER:
  1288. continue
  1289. elif install_type == IDFTool.INSTALL_ALWAYS:
  1290. install_type_str = 'required'
  1291. elif install_type == IDFTool.INSTALL_ON_REQUEST:
  1292. install_type_str = 'optional'
  1293. else:
  1294. raise NotImplementedError()
  1295. version = platform_tool.get_recommended_version()
  1296. version_obj = platform_tool.versions[version]
  1297. download_obj = version_obj.get_download_for_platform(platform_name)
  1298. # Note: keep the list entries indented to the same number of columns
  1299. # as the list header above.
  1300. print_out("""
  1301. * - {}
  1302. - {}
  1303. - {}
  1304. .. rst-class:: tool-sha256
  1305. SHA256: {}
  1306. """.strip('\n').format(platform_name, install_type_str, download_obj.url, download_obj.sha256))
  1307. print_out('')
  1308. print_out('')
  1309. def main(argv):
  1310. parser = argparse.ArgumentParser()
  1311. parser.add_argument('--quiet', help='Don\'t output diagnostic messages to stdout/stderr', action='store_true')
  1312. parser.add_argument('--non-interactive', help='Don\'t output interactive messages and questions', action='store_true')
  1313. parser.add_argument('--tools-json', help='Path to the tools.json file to use')
  1314. parser.add_argument('--idf-path', help='ESP-IDF path to use')
  1315. subparsers = parser.add_subparsers(dest='action')
  1316. subparsers.add_parser('list', help='List tools and versions available')
  1317. subparsers.add_parser('check', help='Print summary of tools installed or found in PATH')
  1318. export = subparsers.add_parser('export', help='Output command for setting tool paths, suitable for shell')
  1319. export.add_argument('--format', choices=[EXPORT_SHELL, EXPORT_KEY_VALUE], default=EXPORT_SHELL,
  1320. help='Format of the output: shell (suitable for printing into shell), ' +
  1321. 'or key-value (suitable for parsing by other tools')
  1322. export.add_argument('--prefer-system', help='Normally, if the tool is already present in PATH, ' +
  1323. 'but has an unsupported version, a version from the tools directory ' +
  1324. 'will be used instead. If this flag is given, the version in PATH ' +
  1325. 'will be used.', action='store_true')
  1326. install = subparsers.add_parser('install', help='Download and install tools into the tools directory')
  1327. install.add_argument('tools', metavar='TOOL', nargs='*', default=['required'],
  1328. help='Tools to install. ' +
  1329. 'To install a specific version use <tool_name>@<version> syntax. ' +
  1330. 'Use empty or \'required\' to install required tools, not optional ones. ' +
  1331. 'Use \'all\' to install all tools, including the optional ones.')
  1332. download = subparsers.add_parser('download', help='Download the tools into the dist directory')
  1333. download.add_argument('--platform', help='Platform to download the tools for')
  1334. download.add_argument('tools', metavar='TOOL', nargs='*', default=['required'],
  1335. help='Tools to download. ' +
  1336. 'To download a specific version use <tool_name>@<version> syntax. ' +
  1337. 'Use empty or \'required\' to download required tools, not optional ones. ' +
  1338. 'Use \'all\' to download all tools, including the optional ones.')
  1339. if IDF_MAINTAINER:
  1340. for subparser in [download, install]:
  1341. subparser.add_argument('--mirror-prefix-map', nargs='*',
  1342. help='Pattern to rewrite download URLs, with source and replacement separated by comma.' +
  1343. ' E.g. http://foo.com,http://test.foo.com')
  1344. install_python_env = subparsers.add_parser('install-python-env',
  1345. help='Create Python virtual environment and install the ' +
  1346. 'required Python packages')
  1347. install_python_env.add_argument('--reinstall', help='Discard the previously installed environment',
  1348. action='store_true')
  1349. install_python_env.add_argument('--extra-wheels-dir', help='Additional directories with wheels ' +
  1350. 'to use during installation')
  1351. install_python_env.add_argument('--extra-wheels-url', help='Additional URL with wheels', default='https://dl.espressif.com/pypi')
  1352. install_python_env.add_argument('--no-index', help='Work offline without retrieving wheels index')
  1353. if IDF_MAINTAINER:
  1354. add_version = subparsers.add_parser('add-version', help='Add or update download info for a version')
  1355. add_version.add_argument('--output', help='Save new tools.json into this file')
  1356. add_version.add_argument('--tool', help='Tool name to set add a version for', required=True)
  1357. add_version.add_argument('--version', help='Version identifier', required=True)
  1358. add_version.add_argument('--url-prefix', help='String to prepend to file names to obtain download URLs')
  1359. add_version.add_argument('files', help='File names of the download artifacts', nargs='*')
  1360. rewrite = subparsers.add_parser('rewrite', help='Load tools.json, validate, and save the result back into JSON')
  1361. rewrite.add_argument('--output', help='Save new tools.json into this file')
  1362. subparsers.add_parser('validate', help='Validate tools.json against schema file')
  1363. gen_doc = subparsers.add_parser('gen-doc', help='Write the list of tools as a documentation page')
  1364. gen_doc.add_argument('--output', type=argparse.FileType('w'), default=sys.stdout,
  1365. help='Output file name')
  1366. gen_doc.add_argument('--heading-underline-char', help='Character to use when generating RST sections', default='~')
  1367. args = parser.parse_args(argv)
  1368. if args.action is None:
  1369. parser.print_help()
  1370. parser.exit(1)
  1371. if args.quiet:
  1372. global global_quiet
  1373. global_quiet = True
  1374. if args.non_interactive:
  1375. global global_non_interactive
  1376. global_non_interactive = True
  1377. global global_idf_path
  1378. global_idf_path = os.environ.get('IDF_PATH')
  1379. if args.idf_path:
  1380. global_idf_path = args.idf_path
  1381. if not global_idf_path:
  1382. global_idf_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..'))
  1383. os.environ['IDF_PATH'] = global_idf_path
  1384. global global_idf_tools_path
  1385. global_idf_tools_path = os.environ.get('IDF_TOOLS_PATH') or os.path.expanduser(IDF_TOOLS_PATH_DEFAULT)
  1386. # On macOS, unset __PYVENV_LAUNCHER__ variable if it is set.
  1387. # Otherwise sys.executable keeps pointing to the system Python, even when a python binary from a virtualenv is invoked.
  1388. # See https://bugs.python.org/issue22490#msg283859.
  1389. os.environ.pop('__PYVENV_LAUNCHER__', None)
  1390. if sys.version_info.major == 2:
  1391. try:
  1392. global_idf_tools_path.decode('ascii')
  1393. except UnicodeDecodeError:
  1394. fatal('IDF_TOOLS_PATH contains non-ASCII characters: {}'.format(global_idf_tools_path) +
  1395. '\nThis is not supported yet with Python 2. ' +
  1396. 'Please set IDF_TOOLS_PATH to a directory with an ASCII name, or switch to Python 3.')
  1397. raise SystemExit(1)
  1398. if CURRENT_PLATFORM == UNKNOWN_PLATFORM:
  1399. fatal('Platform {} appears to be unsupported'.format(PYTHON_PLATFORM))
  1400. raise SystemExit(1)
  1401. global global_tools_json
  1402. if args.tools_json:
  1403. global_tools_json = args.tools_json
  1404. else:
  1405. global_tools_json = os.path.join(global_idf_path, TOOLS_FILE)
  1406. action_func_name = 'action_' + args.action.replace('-', '_')
  1407. action_func = globals()[action_func_name]
  1408. action_func(args)
  1409. if __name__ == '__main__':
  1410. main(sys.argv[1:])