idf_tools.py 67 KB

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