idf_tools.py 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655
  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('Command {} has returned non-zero exit code ({})\n'.format(
  485. ' '.join(self._current_options.version_cmd), e.returncode))
  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:
  530. warn('tool {} found in path, but failed to run'.format(self.name))
  531. else:
  532. self.version_in_path = ver_str
  533. # Now check all the versions installed in global_idf_tools_path
  534. self.versions_installed = []
  535. for version, version_obj in self.versions.items():
  536. if not version_obj.compatible_with_platform():
  537. continue
  538. tool_path = self.get_path_for_version(version)
  539. if not os.path.exists(tool_path):
  540. # version not installed
  541. continue
  542. try:
  543. ver_str = self.check_version(self.get_export_paths(version))
  544. except ToolNotFound:
  545. warn('directory for tool {} version {} is present, but tool was not found'.format(
  546. self.name, version))
  547. except ToolExecError:
  548. warn('tool {} version {} is installed, but the tool failed to run'.format(
  549. self.name, version))
  550. else:
  551. if ver_str != version:
  552. warn('tool {} version {} is installed, but has reported version {}'.format(
  553. self.name, version, ver_str))
  554. else:
  555. self.versions_installed.append(version)
  556. def download(self, version):
  557. assert(version in self.versions)
  558. download_obj = self.versions[version].get_download_for_platform(self._platform)
  559. if not download_obj:
  560. fatal('No packages for tool {} platform {}!'.format(self.name, self._platform))
  561. raise DownloadError()
  562. url = download_obj.url
  563. archive_name = os.path.basename(url)
  564. local_path = os.path.join(global_idf_tools_path, 'dist', archive_name)
  565. mkdir_p(os.path.dirname(local_path))
  566. if os.path.isfile(local_path):
  567. if not self.check_download_file(download_obj, local_path):
  568. warn('removing downloaded file {0} and downloading again'.format(archive_name))
  569. os.unlink(local_path)
  570. else:
  571. info('file {0} is already downloaded'.format(archive_name))
  572. return
  573. downloaded = False
  574. for retry in range(DOWNLOAD_RETRY_COUNT):
  575. local_temp_path = local_path + '.tmp'
  576. info('Downloading {} to {}'.format(archive_name, local_temp_path))
  577. try:
  578. ctx = None
  579. # For dl.espressif.com, add the ISRG x1 root certificate.
  580. # This works around the issue with outdated certificate stores in some installations.
  581. if 'dl.espressif.com' in url:
  582. try:
  583. ctx = ssl.create_default_context()
  584. ctx.load_verify_locations(cadata=ISRG_X1_ROOT_CERT)
  585. except AttributeError:
  586. # no ssl.create_default_context or load_verify_locations cadata argument
  587. # in Python <=2.7.8
  588. pass
  589. urlretrieve_ctx(url, local_temp_path, report_progress if not global_non_interactive else None, context=ctx)
  590. sys.stdout.write('\rDone\n')
  591. except Exception as e:
  592. # urlretrieve could throw different exceptions, e.g. IOError when the server is down
  593. # Errors are ignored because the downloaded file is checked a couple of lines later.
  594. warn('Download failure {}'.format(e))
  595. sys.stdout.flush()
  596. if not os.path.isfile(local_temp_path) or not self.check_download_file(download_obj, local_temp_path):
  597. warn('Failed to download {} to {}'.format(url, local_temp_path))
  598. continue
  599. rename_with_retry(local_temp_path, local_path)
  600. downloaded = True
  601. break
  602. if not downloaded:
  603. fatal('Failed to download, and retry count has expired')
  604. raise DownloadError()
  605. def install(self, version):
  606. # Currently this is called after calling 'download' method, so here are a few asserts
  607. # for the conditions which should be true once that method is done.
  608. assert (version in self.versions)
  609. download_obj = self.versions[version].get_download_for_platform(self._platform)
  610. assert (download_obj is not None)
  611. archive_name = os.path.basename(download_obj.url)
  612. archive_path = os.path.join(global_idf_tools_path, 'dist', archive_name)
  613. assert (os.path.isfile(archive_path))
  614. dest_dir = self.get_path_for_version(version)
  615. if os.path.exists(dest_dir):
  616. warn('destination path already exists, removing')
  617. shutil.rmtree(dest_dir)
  618. mkdir_p(dest_dir)
  619. unpack(archive_path, dest_dir)
  620. if self._current_options.strip_container_dirs:
  621. strip_container_dirs(dest_dir, self._current_options.strip_container_dirs)
  622. @staticmethod
  623. def check_download_file(download_obj, local_path):
  624. expected_sha256 = download_obj.sha256
  625. expected_size = download_obj.size
  626. file_size, file_sha256 = get_file_size_sha256(local_path)
  627. if file_size != expected_size:
  628. warn('file size mismatch for {}, expected {}, got {}'.format(local_path, expected_size, file_size))
  629. return False
  630. if file_sha256 != expected_sha256:
  631. warn('hash mismatch for {}, expected {}, got {}'.format(local_path, expected_sha256, file_sha256))
  632. return False
  633. return True
  634. @classmethod
  635. def from_json(cls, tool_dict):
  636. # json.load will return 'str' types in Python 3 and 'unicode' in Python 2
  637. expected_str_type = type(u'')
  638. # Validate json fields
  639. tool_name = tool_dict.get('name')
  640. if type(tool_name) is not expected_str_type:
  641. raise RuntimeError('tool_name is not a string')
  642. description = tool_dict.get('description')
  643. if type(description) is not expected_str_type:
  644. raise RuntimeError('description is not a string')
  645. version_cmd = tool_dict.get('version_cmd')
  646. if type(version_cmd) is not list:
  647. raise RuntimeError('version_cmd for tool %s is not a list of strings' % tool_name)
  648. version_regex = tool_dict.get('version_regex')
  649. if type(version_regex) is not expected_str_type or not version_regex:
  650. raise RuntimeError('version_regex for tool %s is not a non-empty string' % tool_name)
  651. version_regex_replace = tool_dict.get('version_regex_replace')
  652. if version_regex_replace and type(version_regex_replace) is not expected_str_type:
  653. raise RuntimeError('version_regex_replace for tool %s is not a string' % tool_name)
  654. export_paths = tool_dict.get('export_paths')
  655. if type(export_paths) is not list:
  656. raise RuntimeError('export_paths for tool %s is not a list' % tool_name)
  657. export_vars = tool_dict.get('export_vars', {})
  658. if type(export_vars) is not dict:
  659. raise RuntimeError('export_vars for tool %s is not a mapping' % tool_name)
  660. versions = tool_dict.get('versions')
  661. if type(versions) is not list:
  662. raise RuntimeError('versions for tool %s is not an array' % tool_name)
  663. install = tool_dict.get('install', False)
  664. if type(install) is not expected_str_type:
  665. raise RuntimeError('install for tool %s is not a string' % tool_name)
  666. info_url = tool_dict.get('info_url', False)
  667. if type(info_url) is not expected_str_type:
  668. raise RuntimeError('info_url for tool %s is not a string' % tool_name)
  669. license = tool_dict.get('license', False)
  670. if type(license) is not expected_str_type:
  671. raise RuntimeError('license for tool %s is not a string' % tool_name)
  672. strip_container_dirs = tool_dict.get('strip_container_dirs', 0)
  673. if strip_container_dirs and type(strip_container_dirs) is not int:
  674. raise RuntimeError('strip_container_dirs for tool %s is not an int' % tool_name)
  675. overrides_list = tool_dict.get('platform_overrides', [])
  676. if type(overrides_list) is not list:
  677. raise RuntimeError('platform_overrides for tool %s is not a list' % tool_name)
  678. # Create the object
  679. tool_obj = cls(tool_name, description, install, info_url, license,
  680. version_cmd, version_regex, version_regex_replace,
  681. strip_container_dirs)
  682. for path in export_paths:
  683. tool_obj.options.export_paths.append(path)
  684. for name, value in export_vars.items():
  685. tool_obj.options.export_vars[name] = value
  686. for index, override in enumerate(overrides_list):
  687. platforms_list = override.get('platforms')
  688. if type(platforms_list) is not list:
  689. raise RuntimeError('platforms for override %d of tool %s is not a list' % (index, tool_name))
  690. install = override.get('install')
  691. if install is not None and type(install) is not expected_str_type:
  692. raise RuntimeError('install for override %d of tool %s is not a string' % (index, tool_name))
  693. version_cmd = override.get('version_cmd')
  694. if version_cmd is not None and type(version_cmd) is not list:
  695. raise RuntimeError('version_cmd for override %d of tool %s is not a list of strings' %
  696. (index, tool_name))
  697. version_regex = override.get('version_regex')
  698. if version_regex is not None and (type(version_regex) is not expected_str_type or not version_regex):
  699. raise RuntimeError('version_regex for override %d of tool %s is not a non-empty string' %
  700. (index, tool_name))
  701. version_regex_replace = override.get('version_regex_replace')
  702. if version_regex_replace is not None and type(version_regex_replace) is not expected_str_type:
  703. raise RuntimeError('version_regex_replace for override %d of tool %s is not a string' %
  704. (index, tool_name))
  705. export_paths = override.get('export_paths')
  706. if export_paths is not None and type(export_paths) is not list:
  707. raise RuntimeError('export_paths for override %d of tool %s is not a list' % (index, tool_name))
  708. export_vars = override.get('export_vars')
  709. if export_vars is not None and type(export_vars) is not dict:
  710. raise RuntimeError('export_vars for override %d of tool %s is not a mapping' % (index, tool_name))
  711. tool_obj.platform_overrides.append(override)
  712. recommended_versions = {}
  713. for version_dict in versions:
  714. version = version_dict.get('name')
  715. if type(version) is not expected_str_type:
  716. raise RuntimeError('version name for tool {} is not a string'.format(tool_name))
  717. version_status = version_dict.get('status')
  718. if type(version_status) is not expected_str_type and version_status not in IDFToolVersion.STATUS_VALUES:
  719. raise RuntimeError('tool {} version {} status is not one of {}', tool_name, version,
  720. IDFToolVersion.STATUS_VALUES)
  721. version_obj = IDFToolVersion(version, version_status)
  722. for platform_id, platform_dict in version_dict.items():
  723. if platform_id in ['name', 'status']:
  724. continue
  725. if platform_id not in PLATFORM_FROM_NAME.keys():
  726. raise RuntimeError('invalid platform %s for tool %s version %s' %
  727. (platform_id, tool_name, version))
  728. version_obj.add_download(platform_id,
  729. platform_dict['url'], platform_dict['size'], platform_dict['sha256'])
  730. if version_status == IDFToolVersion.STATUS_RECOMMENDED:
  731. if platform_id not in recommended_versions:
  732. recommended_versions[platform_id] = []
  733. recommended_versions[platform_id].append(version)
  734. tool_obj.add_version(version_obj)
  735. for platform_id, version_list in recommended_versions.items():
  736. if len(version_list) > 1:
  737. raise RuntimeError('tool {} for platform {} has {} recommended versions'.format(
  738. tool_name, platform_id, len(recommended_versions)))
  739. if install != IDFTool.INSTALL_NEVER and len(recommended_versions) == 0:
  740. raise RuntimeError('required/optional tool {} for platform {} has no recommended versions'.format(
  741. tool_name, platform_id))
  742. tool_obj._update_current_options()
  743. return tool_obj
  744. def to_json(self):
  745. versions_array = []
  746. for version, version_obj in self.versions.items():
  747. version_json = {
  748. 'name': version,
  749. 'status': version_obj.status
  750. }
  751. for platform_id, download in version_obj.downloads.items():
  752. version_json[platform_id] = {
  753. 'url': download.url,
  754. 'size': download.size,
  755. 'sha256': download.sha256
  756. }
  757. versions_array.append(version_json)
  758. overrides_array = self.platform_overrides
  759. tool_json = {
  760. 'name': self.name,
  761. 'description': self.description,
  762. 'export_paths': self.options.export_paths,
  763. 'export_vars': self.options.export_vars,
  764. 'install': self.options.install,
  765. 'info_url': self.options.info_url,
  766. 'license': self.options.license,
  767. 'version_cmd': self.options.version_cmd,
  768. 'version_regex': self.options.version_regex,
  769. 'versions': versions_array,
  770. }
  771. if self.options.version_regex_replace != VERSION_REGEX_REPLACE_DEFAULT:
  772. tool_json['version_regex_replace'] = self.options.version_regex_replace
  773. if overrides_array:
  774. tool_json['platform_overrides'] = overrides_array
  775. if self.options.strip_container_dirs:
  776. tool_json['strip_container_dirs'] = self.options.strip_container_dirs
  777. return tool_json
  778. def load_tools_info(): # type: () -> typing.Dict[str, IDFTool]
  779. """
  780. Load tools metadata from tools.json, return a dictionary: tool name - tool info
  781. """
  782. tool_versions_file_name = global_tools_json
  783. with open(tool_versions_file_name, 'r') as f:
  784. tools_info = json.load(f)
  785. return parse_tools_info_json(tools_info)
  786. def parse_tools_info_json(tools_info):
  787. """
  788. Parse and validate the dictionary obtained by loading the tools.json file.
  789. Returns a dictionary of tools (key: tool name, value: IDFTool object).
  790. """
  791. if tools_info['version'] != TOOLS_FILE_VERSION:
  792. raise RuntimeError('Invalid version')
  793. tools_dict = OrderedDict()
  794. tools_array = tools_info.get('tools')
  795. if type(tools_array) is not list:
  796. raise RuntimeError('tools property is missing or not an array')
  797. for tool_dict in tools_array:
  798. tool = IDFTool.from_json(tool_dict)
  799. tools_dict[tool.name] = tool
  800. return tools_dict
  801. def dump_tools_json(tools_info):
  802. tools_array = []
  803. for tool_name, tool_obj in tools_info.items():
  804. tool_json = tool_obj.to_json()
  805. tools_array.append(tool_json)
  806. file_json = {'version': TOOLS_FILE_VERSION, 'tools': tools_array}
  807. return json.dumps(file_json, indent=2, separators=(',', ': '), sort_keys=True)
  808. def get_python_env_path():
  809. python_ver_major_minor = '{}.{}'.format(sys.version_info.major, sys.version_info.minor)
  810. version_file_path = os.path.join(global_idf_path, 'version.txt')
  811. if os.path.exists(version_file_path):
  812. with open(version_file_path, 'r') as version_file:
  813. idf_version_str = version_file.read()
  814. else:
  815. try:
  816. idf_version_str = subprocess.check_output(['git', 'describe'],
  817. cwd=global_idf_path, env=os.environ).decode()
  818. except subprocess.CalledProcessError as e:
  819. warn('Git describe was unsuccessul: {}'.format(e))
  820. idf_version_str = ''
  821. match = re.match(r'^v([0-9]+\.[0-9]+).*', idf_version_str)
  822. if match:
  823. idf_version = match.group(1)
  824. else:
  825. idf_version = None
  826. # fallback when IDF is a shallow clone
  827. try:
  828. with open(os.path.join(global_idf_path, 'components', 'esp_common', 'include', 'esp_idf_version.h')) as f:
  829. m = re.search(r'^#define\s+ESP_IDF_VERSION_MAJOR\s+(\d+).+?^#define\s+ESP_IDF_VERSION_MINOR\s+(\d+)',
  830. f.read(), re.DOTALL | re.MULTILINE)
  831. if m:
  832. idf_version = '.'.join((m.group(1), m.group(2)))
  833. else:
  834. warn('Reading IDF version from C header file failed!')
  835. except Exception as e:
  836. warn('Is it not possible to determine the IDF version: {}'.format(e))
  837. if idf_version is None:
  838. fatal('IDF version cannot be determined')
  839. raise SystemExit(1)
  840. idf_python_env_path = os.path.join(global_idf_tools_path, 'python_env',
  841. 'idf{}_py{}_env'.format(idf_version, python_ver_major_minor))
  842. if sys.platform == 'win32':
  843. subdir = 'Scripts'
  844. python_exe = 'python.exe'
  845. else:
  846. subdir = 'bin'
  847. python_exe = 'python'
  848. idf_python_export_path = os.path.join(idf_python_env_path, subdir)
  849. virtualenv_python = os.path.join(idf_python_export_path, python_exe)
  850. return idf_python_env_path, idf_python_export_path, virtualenv_python
  851. def action_list(args):
  852. tools_info = load_tools_info()
  853. for name, tool in tools_info.items():
  854. if tool.get_install_type() == IDFTool.INSTALL_NEVER:
  855. continue
  856. optional_str = ' (optional)' if tool.get_install_type() == IDFTool.INSTALL_ON_REQUEST else ''
  857. info('* {}: {}{}'.format(name, tool.description, optional_str))
  858. tool.find_installed_versions()
  859. versions_for_platform = {k: v for k, v in tool.versions.items() if v.compatible_with_platform()}
  860. if not versions_for_platform:
  861. info(' (no versions compatible with platform {})'.format(PYTHON_PLATFORM))
  862. continue
  863. versions_sorted = sorted(versions_for_platform.keys(), key=tool.versions.get, reverse=True)
  864. for version in versions_sorted:
  865. version_obj = tool.versions[version]
  866. info(' - {} ({}{})'.format(version, version_obj.status,
  867. ', installed' if version in tool.versions_installed else ''))
  868. def action_check(args):
  869. tools_info = load_tools_info()
  870. not_found_list = []
  871. info('Checking for installed tools...')
  872. for name, tool in tools_info.items():
  873. if tool.get_install_type() == IDFTool.INSTALL_NEVER:
  874. continue
  875. tool_found_somewhere = False
  876. info('Checking tool %s' % name)
  877. tool.find_installed_versions()
  878. if tool.version_in_path:
  879. info(' version found in PATH: %s' % tool.version_in_path)
  880. tool_found_somewhere = True
  881. else:
  882. info(' no version found in PATH')
  883. for version in tool.versions_installed:
  884. info(' version installed in tools directory: %s' % version)
  885. tool_found_somewhere = True
  886. if not tool_found_somewhere and tool.get_install_type() == IDFTool.INSTALL_ALWAYS:
  887. not_found_list.append(name)
  888. if not_found_list:
  889. fatal('The following required tools were not found: ' + ' '.join(not_found_list))
  890. raise SystemExit(1)
  891. def action_export(args):
  892. tools_info = load_tools_info()
  893. all_tools_found = True
  894. export_vars = {}
  895. paths_to_export = []
  896. for name, tool in tools_info.items():
  897. if tool.get_install_type() == IDFTool.INSTALL_NEVER:
  898. continue
  899. tool.find_installed_versions()
  900. if tool.version_in_path:
  901. if tool.version_in_path not in tool.versions:
  902. # unsupported version
  903. if args.prefer_system:
  904. warn('using an unsupported version of tool {} found in PATH: {}'.format(
  905. tool.name, tool.version_in_path))
  906. continue
  907. else:
  908. # unsupported version in path
  909. pass
  910. else:
  911. # supported/deprecated version in PATH, use it
  912. version_obj = tool.versions[tool.version_in_path]
  913. if version_obj.status == IDFToolVersion.STATUS_SUPPORTED:
  914. info('Using a supported version of tool {} found in PATH: {}.'.format(name, tool.version_in_path),
  915. f=sys.stderr)
  916. info('However the recommended version is {}.'.format(tool.get_recommended_version()),
  917. f=sys.stderr)
  918. elif version_obj.status == IDFToolVersion.STATUS_DEPRECATED:
  919. warn('using a deprecated version of tool {} found in PATH: {}'.format(name, tool.version_in_path))
  920. continue
  921. self_restart_cmd = '{} {}{}'.format(sys.executable, __file__,
  922. (' --tools-json ' + args.tools_json) if args.tools_json else '')
  923. self_restart_cmd = to_shell_specific_paths([self_restart_cmd])[0]
  924. if IDF_TOOLS_EXPORT_CMD:
  925. prefer_system_hint = ''
  926. else:
  927. prefer_system_hint = ' To use it, run \'{} export --prefer-system\''.format(self_restart_cmd)
  928. if IDF_TOOLS_INSTALL_CMD:
  929. install_cmd = to_shell_specific_paths([IDF_TOOLS_INSTALL_CMD])[0]
  930. else:
  931. install_cmd = self_restart_cmd + ' install'
  932. if not tool.versions_installed:
  933. if tool.get_install_type() == IDFTool.INSTALL_ALWAYS:
  934. all_tools_found = False
  935. fatal('tool {} has no installed versions. Please run \'{}\' to install it.'.format(
  936. tool.name, install_cmd))
  937. if tool.version_in_path and tool.version_in_path not in tool.versions:
  938. info('An unsupported version of tool {} was found in PATH: {}. '.format(name, tool.version_in_path) +
  939. prefer_system_hint, f=sys.stderr)
  940. continue
  941. else:
  942. # tool is optional, and does not have versions installed
  943. # use whatever is available in PATH
  944. continue
  945. if tool.version_in_path and tool.version_in_path not in tool.versions:
  946. info('Not using an unsupported version of tool {} found in PATH: {}.'.format(
  947. tool.name, tool.version_in_path) + prefer_system_hint, f=sys.stderr)
  948. version_to_use = tool.get_preferred_installed_version()
  949. export_paths = tool.get_export_paths(version_to_use)
  950. if export_paths:
  951. paths_to_export += export_paths
  952. tool_export_vars = tool.get_export_vars(version_to_use)
  953. for k, v in tool_export_vars.items():
  954. old_v = os.environ.get(k)
  955. if old_v is None or old_v != v:
  956. export_vars[k] = v
  957. current_path = os.getenv('PATH')
  958. idf_python_env_path, idf_python_export_path, virtualenv_python = get_python_env_path()
  959. if os.path.exists(virtualenv_python):
  960. idf_python_env_path = to_shell_specific_paths([idf_python_env_path])[0]
  961. if os.getenv('IDF_PYTHON_ENV_PATH') != idf_python_env_path:
  962. export_vars['IDF_PYTHON_ENV_PATH'] = to_shell_specific_paths([idf_python_env_path])[0]
  963. if idf_python_export_path not in current_path:
  964. paths_to_export.append(idf_python_export_path)
  965. idf_tools_dir = os.path.join(global_idf_path, 'tools')
  966. idf_tools_dir = to_shell_specific_paths([idf_tools_dir])[0]
  967. if idf_tools_dir not in current_path:
  968. paths_to_export.append(idf_tools_dir)
  969. if sys.platform == 'win32' and 'MSYSTEM' not in os.environ:
  970. old_path = '%PATH%'
  971. path_sep = ';'
  972. else:
  973. old_path = '$PATH'
  974. # can't trust os.pathsep here, since for Windows Python started from MSYS shell,
  975. # os.pathsep will be ';'
  976. path_sep = ':'
  977. if args.format == EXPORT_SHELL:
  978. if sys.platform == 'win32' and 'MSYSTEM' not in os.environ:
  979. export_format = 'SET "{}={}"'
  980. export_sep = '\n'
  981. else:
  982. export_format = 'export {}="{}"'
  983. export_sep = ';'
  984. elif args.format == EXPORT_KEY_VALUE:
  985. export_format = '{}={}'
  986. export_sep = '\n'
  987. else:
  988. raise NotImplementedError('unsupported export format {}'.format(args.format))
  989. if paths_to_export:
  990. export_vars['PATH'] = path_sep.join(to_shell_specific_paths(paths_to_export) + [old_path])
  991. export_statements = export_sep.join([export_format.format(k, v) for k, v in export_vars.items()])
  992. if export_statements:
  993. print(export_statements)
  994. if not all_tools_found:
  995. raise SystemExit(1)
  996. def apply_url_mirrors(args, tool_download_obj):
  997. apply_mirror_prefix_map(args, tool_download_obj)
  998. apply_github_assets_option(tool_download_obj)
  999. def apply_mirror_prefix_map(args, tool_download_obj):
  1000. """Rewrite URL for given tool_obj, given tool_version, and current platform,
  1001. if --mirror-prefix-map flag or IDF_MIRROR_PREFIX_MAP environment variable is given.
  1002. """
  1003. mirror_prefix_map = None
  1004. mirror_prefix_map_env = os.getenv('IDF_MIRROR_PREFIX_MAP')
  1005. if mirror_prefix_map_env:
  1006. mirror_prefix_map = mirror_prefix_map_env.split(';')
  1007. if IDF_MAINTAINER and args.mirror_prefix_map:
  1008. if mirror_prefix_map:
  1009. warn('Both IDF_MIRROR_PREFIX_MAP environment variable and --mirror-prefix-map flag are specified, ' +
  1010. 'will use the value from the command line.')
  1011. mirror_prefix_map = args.mirror_prefix_map
  1012. if mirror_prefix_map and tool_download_obj:
  1013. for item in mirror_prefix_map:
  1014. if URL_PREFIX_MAP_SEPARATOR not in item:
  1015. warn('invalid mirror-prefix-map item (missing \'{}\') {}'.format(URL_PREFIX_MAP_SEPARATOR, item))
  1016. continue
  1017. search, replace = item.split(URL_PREFIX_MAP_SEPARATOR, 1)
  1018. old_url = tool_download_obj.url
  1019. new_url = re.sub(search, replace, old_url)
  1020. if new_url != old_url:
  1021. info('Changed download URL: {} => {}'.format(old_url, new_url))
  1022. tool_download_obj.url = new_url
  1023. break
  1024. def apply_github_assets_option(tool_download_obj):
  1025. """ Rewrite URL for given tool_obj if the download URL is an https://github.com/ URL and the variable
  1026. IDF_GITHUB_ASSETS is set. The github.com part of the URL will be replaced.
  1027. """
  1028. try:
  1029. github_assets = os.environ['IDF_GITHUB_ASSETS'].strip()
  1030. except KeyError:
  1031. return # no IDF_GITHUB_ASSETS
  1032. if not github_assets: # variable exists but is empty
  1033. return
  1034. # check no URL qualifier in the mirror URL
  1035. if '://' in github_assets:
  1036. fatal("IDF_GITHUB_ASSETS shouldn't include any URL qualifier, https:// is assumed")
  1037. raise SystemExit(1)
  1038. # Strip any trailing / from the mirror URL
  1039. github_assets = github_assets.rstrip('/')
  1040. old_url = tool_download_obj.url
  1041. new_url = re.sub(r'^https://github.com/', 'https://{}/'.format(github_assets), old_url)
  1042. if new_url != old_url:
  1043. info('Using GitHub assets mirror for URL: {} => {}'.format(old_url, new_url))
  1044. tool_download_obj.url = new_url
  1045. def action_download(args):
  1046. tools_info = load_tools_info()
  1047. tools_spec = args.tools
  1048. if args.platform not in PLATFORM_FROM_NAME:
  1049. fatal('unknown platform: {}' % args.platform)
  1050. raise SystemExit(1)
  1051. platform = PLATFORM_FROM_NAME[args.platform]
  1052. tools_info_for_platform = OrderedDict()
  1053. for name, tool_obj in tools_info.items():
  1054. tool_for_platform = tool_obj.copy_for_platform(platform)
  1055. tools_info_for_platform[name] = tool_for_platform
  1056. if not tools_spec or 'required' in tools_spec:
  1057. tools_spec = [k for k, v in tools_info_for_platform.items() if v.get_install_type() == IDFTool.INSTALL_ALWAYS]
  1058. info('Downloading tools for {}: {}'.format(platform, ', '.join(tools_spec)))
  1059. elif 'all' in tools_spec:
  1060. tools_spec = [k for k, v in tools_info_for_platform.items() if v.get_install_type() != IDFTool.INSTALL_NEVER]
  1061. info('Downloading tools for {}: {}'.format(platform, ', '.join(tools_spec)))
  1062. for tool_spec in tools_spec:
  1063. if '@' not in tool_spec:
  1064. tool_name = tool_spec
  1065. tool_version = None
  1066. else:
  1067. tool_name, tool_version = tool_spec.split('@', 1)
  1068. if tool_name not in tools_info_for_platform:
  1069. fatal('unknown tool name: {}'.format(tool_name))
  1070. raise SystemExit(1)
  1071. tool_obj = tools_info_for_platform[tool_name]
  1072. if tool_version is not None and tool_version not in tool_obj.versions:
  1073. fatal('unknown version for tool {}: {}'.format(tool_name, tool_version))
  1074. raise SystemExit(1)
  1075. if tool_version is None:
  1076. tool_version = tool_obj.get_recommended_version()
  1077. if tool_version is None:
  1078. fatal('tool {} not found for {} platform'.format(tool_name, platform))
  1079. raise SystemExit(1)
  1080. tool_spec = '{}@{}'.format(tool_name, tool_version)
  1081. info('Downloading {}'.format(tool_spec))
  1082. apply_url_mirrors(args, tool_obj.versions[tool_version].get_download_for_platform(platform))
  1083. tool_obj.download(tool_version)
  1084. def action_install(args):
  1085. tools_info = load_tools_info()
  1086. tools_spec = args.tools
  1087. if not tools_spec or 'required' in tools_spec:
  1088. tools_spec = [k for k, v in tools_info.items() if v.get_install_type() == IDFTool.INSTALL_ALWAYS]
  1089. info('Installing tools: {}'.format(', '.join(tools_spec)))
  1090. elif 'all' in tools_spec:
  1091. tools_spec = [k for k, v in tools_info.items() if v.get_install_type() != IDFTool.INSTALL_NEVER]
  1092. info('Installing tools: {}'.format(', '.join(tools_spec)))
  1093. for tool_spec in tools_spec:
  1094. if '@' not in tool_spec:
  1095. tool_name = tool_spec
  1096. tool_version = None
  1097. else:
  1098. tool_name, tool_version = tool_spec.split('@', 1)
  1099. if tool_name not in tools_info:
  1100. fatal('unknown tool name: {}'.format(tool_name))
  1101. raise SystemExit(1)
  1102. tool_obj = tools_info[tool_name]
  1103. if not tool_obj.compatible_with_platform():
  1104. fatal('tool {} does not have versions compatible with platform {}'.format(tool_name, CURRENT_PLATFORM))
  1105. raise SystemExit(1)
  1106. if tool_version is not None and tool_version not in tool_obj.versions:
  1107. fatal('unknown version for tool {}: {}'.format(tool_name, tool_version))
  1108. raise SystemExit(1)
  1109. if tool_version is None:
  1110. tool_version = tool_obj.get_recommended_version()
  1111. assert tool_version is not None
  1112. tool_obj.find_installed_versions()
  1113. tool_spec = '{}@{}'.format(tool_name, tool_version)
  1114. if tool_version in tool_obj.versions_installed:
  1115. info('Skipping {} (already installed)'.format(tool_spec))
  1116. continue
  1117. info('Installing {}'.format(tool_spec))
  1118. apply_url_mirrors(args, tool_obj.versions[tool_version].get_download_for_platform(PYTHON_PLATFORM))
  1119. tool_obj.download(tool_version)
  1120. tool_obj.install(tool_version)
  1121. def get_wheels_dir():
  1122. tools_info = load_tools_info()
  1123. wheels_package_name = 'idf-python-wheels'
  1124. if wheels_package_name not in tools_info:
  1125. return None
  1126. wheels_package = tools_info[wheels_package_name]
  1127. recommended_version = wheels_package.get_recommended_version()
  1128. if recommended_version is None:
  1129. return None
  1130. wheels_dir = wheels_package.get_path_for_version(recommended_version)
  1131. if not os.path.exists(wheels_dir):
  1132. return None
  1133. return wheels_dir
  1134. def action_install_python_env(args):
  1135. idf_python_env_path, _, virtualenv_python = get_python_env_path()
  1136. is_virtualenv = hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix)
  1137. if is_virtualenv and (not os.path.exists(idf_python_env_path) or args.reinstall):
  1138. fatal('This script was called from a virtual environment, can not create a virtual environment again')
  1139. raise SystemExit(1)
  1140. if args.reinstall and os.path.exists(idf_python_env_path):
  1141. warn('Removing the existing Python environment in {}'.format(idf_python_env_path))
  1142. shutil.rmtree(idf_python_env_path)
  1143. if not os.path.exists(virtualenv_python):
  1144. info('Creating a new Python environment in {}'.format(idf_python_env_path))
  1145. try:
  1146. import virtualenv # noqa: F401
  1147. except ImportError:
  1148. info('Installing virtualenv')
  1149. subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--user', 'virtualenv'],
  1150. stdout=sys.stdout, stderr=sys.stderr)
  1151. subprocess.check_call([sys.executable, '-m', 'virtualenv', idf_python_env_path],
  1152. stdout=sys.stdout, stderr=sys.stderr)
  1153. run_args = [virtualenv_python, '-m', 'pip', 'install', '--no-warn-script-location']
  1154. requirements_txt = os.path.join(global_idf_path, 'requirements.txt')
  1155. run_args += ['-r', requirements_txt]
  1156. if args.extra_wheels_dir:
  1157. run_args += ['--find-links', args.extra_wheels_dir]
  1158. if args.no_index:
  1159. run_args += ['--no-index']
  1160. if args.extra_wheels_url:
  1161. run_args += ['--extra-index-url', args.extra_wheels_url]
  1162. wheels_dir = get_wheels_dir()
  1163. if wheels_dir is not None:
  1164. run_args += ['--find-links', wheels_dir]
  1165. info('Installing Python packages from {}'.format(requirements_txt))
  1166. subprocess.check_call(run_args, stdout=sys.stdout, stderr=sys.stderr)
  1167. def action_add_version(args):
  1168. tools_info = load_tools_info()
  1169. tool_name = args.tool
  1170. tool_obj = tools_info.get(tool_name)
  1171. if not tool_obj:
  1172. info('Creating new tool entry for {}'.format(tool_name))
  1173. tool_obj = IDFTool(tool_name, TODO_MESSAGE, IDFTool.INSTALL_ALWAYS,
  1174. TODO_MESSAGE, TODO_MESSAGE, [TODO_MESSAGE], TODO_MESSAGE)
  1175. tools_info[tool_name] = tool_obj
  1176. version = args.version
  1177. version_obj = tool_obj.versions.get(version)
  1178. if version not in tool_obj.versions:
  1179. info('Creating new version {}'.format(version))
  1180. version_obj = IDFToolVersion(version, IDFToolVersion.STATUS_SUPPORTED)
  1181. tool_obj.versions[version] = version_obj
  1182. url_prefix = args.url_prefix or 'https://%s/' % TODO_MESSAGE
  1183. for file_path in args.files:
  1184. file_name = os.path.basename(file_path)
  1185. # Guess which platform this file is for
  1186. found_platform = None
  1187. for platform_alias, platform_id in PLATFORM_FROM_NAME.items():
  1188. if platform_alias in file_name:
  1189. found_platform = platform_id
  1190. break
  1191. if found_platform is None:
  1192. info('Could not guess platform for file {}'.format(file_name))
  1193. found_platform = TODO_MESSAGE
  1194. # Get file size and calculate the SHA256
  1195. file_size, file_sha256 = get_file_size_sha256(file_path)
  1196. url = url_prefix + file_name
  1197. info('Adding download for platform {}'.format(found_platform))
  1198. info(' size: {}'.format(file_size))
  1199. info(' SHA256: {}'.format(file_sha256))
  1200. info(' URL: {}'.format(url))
  1201. version_obj.add_download(found_platform, url, file_size, file_sha256)
  1202. json_str = dump_tools_json(tools_info)
  1203. if not args.output:
  1204. args.output = os.path.join(global_idf_path, TOOLS_FILE_NEW)
  1205. with open(args.output, 'w') as f:
  1206. f.write(json_str)
  1207. f.write('\n')
  1208. info('Wrote output to {}'.format(args.output))
  1209. def action_rewrite(args):
  1210. tools_info = load_tools_info()
  1211. json_str = dump_tools_json(tools_info)
  1212. if not args.output:
  1213. args.output = os.path.join(global_idf_path, TOOLS_FILE_NEW)
  1214. with open(args.output, 'w') as f:
  1215. f.write(json_str)
  1216. f.write('\n')
  1217. info('Wrote output to {}'.format(args.output))
  1218. def action_validate(args):
  1219. try:
  1220. import jsonschema
  1221. except ImportError:
  1222. fatal('You need to install jsonschema package to use validate command')
  1223. raise SystemExit(1)
  1224. with open(os.path.join(global_idf_path, TOOLS_FILE), 'r') as tools_file:
  1225. tools_json = json.load(tools_file)
  1226. with open(os.path.join(global_idf_path, TOOLS_SCHEMA_FILE), 'r') as schema_file:
  1227. schema_json = json.load(schema_file)
  1228. jsonschema.validate(tools_json, schema_json)
  1229. # on failure, this will raise an exception with a fairly verbose diagnostic message
  1230. def action_gen_doc(args):
  1231. f = args.output
  1232. tools_info = load_tools_info()
  1233. def print_out(text):
  1234. f.write(text + '\n')
  1235. print_out('.. |zwsp| unicode:: U+200B')
  1236. print_out(' :trim:')
  1237. print_out('')
  1238. idf_gh_url = 'https://github.com/espressif/esp-idf'
  1239. for tool_name, tool_obj in tools_info.items():
  1240. info_url = tool_obj.options.info_url
  1241. if idf_gh_url + '/tree' in info_url:
  1242. info_url = re.sub(idf_gh_url + r'/tree/\w+/(.*)', r':idf:`\1`', info_url)
  1243. license_url = 'https://spdx.org/licenses/' + tool_obj.options.license
  1244. print_out("""
  1245. .. _tool-{name}:
  1246. {name}
  1247. {underline}
  1248. {description}
  1249. .. include:: idf-tools-notes.inc
  1250. :start-after: tool-{name}-notes
  1251. :end-before: ---
  1252. License: `{license} <{license_url}>`_
  1253. More info: {info_url}
  1254. .. list-table::
  1255. :widths: 10 10 80
  1256. :header-rows: 1
  1257. * - Platform
  1258. - Required
  1259. - Download
  1260. """.rstrip().format(name=tool_name,
  1261. underline=args.heading_underline_char * len(tool_name),
  1262. description=tool_obj.description,
  1263. license=tool_obj.options.license,
  1264. license_url=license_url,
  1265. info_url=info_url))
  1266. for platform_name in sorted(tool_obj.get_supported_platforms()):
  1267. platform_tool = tool_obj.copy_for_platform(platform_name)
  1268. install_type = platform_tool.get_install_type()
  1269. if install_type == IDFTool.INSTALL_NEVER:
  1270. continue
  1271. elif install_type == IDFTool.INSTALL_ALWAYS:
  1272. install_type_str = 'required'
  1273. elif install_type == IDFTool.INSTALL_ON_REQUEST:
  1274. install_type_str = 'optional'
  1275. else:
  1276. raise NotImplementedError()
  1277. version = platform_tool.get_recommended_version()
  1278. version_obj = platform_tool.versions[version]
  1279. download_obj = version_obj.get_download_for_platform(platform_name)
  1280. # Note: keep the list entries indented to the same number of columns
  1281. # as the list header above.
  1282. print_out("""
  1283. * - {}
  1284. - {}
  1285. - {}
  1286. .. rst-class:: tool-sha256
  1287. SHA256: {}
  1288. """.strip('\n').format(platform_name, install_type_str, download_obj.url, download_obj.sha256))
  1289. print_out('')
  1290. print_out('')
  1291. def main(argv):
  1292. parser = argparse.ArgumentParser()
  1293. parser.add_argument('--quiet', help='Don\'t output diagnostic messages to stdout/stderr', action='store_true')
  1294. parser.add_argument('--non-interactive', help='Don\'t output interactive messages and questions', action='store_true')
  1295. parser.add_argument('--tools-json', help='Path to the tools.json file to use')
  1296. parser.add_argument('--idf-path', help='ESP-IDF path to use')
  1297. subparsers = parser.add_subparsers(dest='action')
  1298. subparsers.add_parser('list', help='List tools and versions available')
  1299. subparsers.add_parser('check', help='Print summary of tools installed or found in PATH')
  1300. export = subparsers.add_parser('export', help='Output command for setting tool paths, suitable for shell')
  1301. export.add_argument('--format', choices=[EXPORT_SHELL, EXPORT_KEY_VALUE], default=EXPORT_SHELL,
  1302. help='Format of the output: shell (suitable for printing into shell), ' +
  1303. 'or key-value (suitable for parsing by other tools')
  1304. export.add_argument('--prefer-system', help='Normally, if the tool is already present in PATH, ' +
  1305. 'but has an unsupported version, a version from the tools directory ' +
  1306. 'will be used instead. If this flag is given, the version in PATH ' +
  1307. 'will be used.', action='store_true')
  1308. install = subparsers.add_parser('install', help='Download and install tools into the tools directory')
  1309. install.add_argument('tools', metavar='TOOL', nargs='*', default=['required'],
  1310. help='Tools to install. ' +
  1311. 'To install a specific version use <tool_name>@<version> syntax. ' +
  1312. 'Use empty or \'required\' to install required tools, not optional ones. ' +
  1313. 'Use \'all\' to install all tools, including the optional ones.')
  1314. download = subparsers.add_parser('download', help='Download the tools into the dist directory')
  1315. download.add_argument('--platform', help='Platform to download the tools for')
  1316. download.add_argument('tools', metavar='TOOL', nargs='*', default=['required'],
  1317. help='Tools to download. ' +
  1318. 'To download a specific version use <tool_name>@<version> syntax. ' +
  1319. 'Use empty or \'required\' to download required tools, not optional ones. ' +
  1320. 'Use \'all\' to download all tools, including the optional ones.')
  1321. if IDF_MAINTAINER:
  1322. for subparser in [download, install]:
  1323. subparser.add_argument('--mirror-prefix-map', nargs='*',
  1324. help='Pattern to rewrite download URLs, with source and replacement separated by comma.' +
  1325. ' E.g. http://foo.com,http://test.foo.com')
  1326. install_python_env = subparsers.add_parser('install-python-env',
  1327. help='Create Python virtual environment and install the ' +
  1328. 'required Python packages')
  1329. install_python_env.add_argument('--reinstall', help='Discard the previously installed environment',
  1330. action='store_true')
  1331. install_python_env.add_argument('--extra-wheels-dir', help='Additional directories with wheels ' +
  1332. 'to use during installation')
  1333. install_python_env.add_argument('--extra-wheels-url', help='Additional URL with wheels', default='https://dl.espressif.com/pypi')
  1334. install_python_env.add_argument('--no-index', help='Work offline without retrieving wheels index')
  1335. if IDF_MAINTAINER:
  1336. add_version = subparsers.add_parser('add-version', help='Add or update download info for a version')
  1337. add_version.add_argument('--output', help='Save new tools.json into this file')
  1338. add_version.add_argument('--tool', help='Tool name to set add a version for', required=True)
  1339. add_version.add_argument('--version', help='Version identifier', required=True)
  1340. add_version.add_argument('--url-prefix', help='String to prepend to file names to obtain download URLs')
  1341. add_version.add_argument('files', help='File names of the download artifacts', nargs='*')
  1342. rewrite = subparsers.add_parser('rewrite', help='Load tools.json, validate, and save the result back into JSON')
  1343. rewrite.add_argument('--output', help='Save new tools.json into this file')
  1344. subparsers.add_parser('validate', help='Validate tools.json against schema file')
  1345. gen_doc = subparsers.add_parser('gen-doc', help='Write the list of tools as a documentation page')
  1346. gen_doc.add_argument('--output', type=argparse.FileType('w'), default=sys.stdout,
  1347. help='Output file name')
  1348. gen_doc.add_argument('--heading-underline-char', help='Character to use when generating RST sections', default='~')
  1349. args = parser.parse_args(argv)
  1350. if args.action is None:
  1351. parser.print_help()
  1352. parser.exit(1)
  1353. if args.quiet:
  1354. global global_quiet
  1355. global_quiet = True
  1356. if args.non_interactive:
  1357. global global_non_interactive
  1358. global_non_interactive = True
  1359. global global_idf_path
  1360. global_idf_path = os.environ.get('IDF_PATH')
  1361. if args.idf_path:
  1362. global_idf_path = args.idf_path
  1363. if not global_idf_path:
  1364. global_idf_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..'))
  1365. os.environ['IDF_PATH'] = global_idf_path
  1366. global global_idf_tools_path
  1367. global_idf_tools_path = os.environ.get('IDF_TOOLS_PATH') or os.path.expanduser(IDF_TOOLS_PATH_DEFAULT)
  1368. # On macOS, unset __PYVENV_LAUNCHER__ variable if it is set.
  1369. # Otherwise sys.executable keeps pointing to the system Python, even when a python binary from a virtualenv is invoked.
  1370. # See https://bugs.python.org/issue22490#msg283859.
  1371. os.environ.pop('__PYVENV_LAUNCHER__', None)
  1372. if sys.version_info.major == 2:
  1373. try:
  1374. global_idf_tools_path.decode('ascii')
  1375. except UnicodeDecodeError:
  1376. fatal('IDF_TOOLS_PATH contains non-ASCII characters: {}'.format(global_idf_tools_path) +
  1377. '\nThis is not supported yet with Python 2. ' +
  1378. 'Please set IDF_TOOLS_PATH to a directory with an ASCII name, or switch to Python 3.')
  1379. raise SystemExit(1)
  1380. if CURRENT_PLATFORM == UNKNOWN_PLATFORM:
  1381. fatal('Platform {} appears to be unsupported'.format(PYTHON_PLATFORM))
  1382. raise SystemExit(1)
  1383. global global_tools_json
  1384. if args.tools_json:
  1385. global_tools_json = args.tools_json
  1386. else:
  1387. global_tools_json = os.path.join(global_idf_path, TOOLS_FILE)
  1388. action_func_name = 'action_' + args.action.replace('-', '_')
  1389. action_func = globals()[action_func_name]
  1390. action_func(args)
  1391. if __name__ == '__main__':
  1392. main(sys.argv[1:])