idf_tools.py 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683
  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. try:
  58. import typing # noqa: F401
  59. from typing import IO, Any, Callable, Optional, Tuple, Union # noqa: F401
  60. except ImportError:
  61. pass
  62. try:
  63. from urllib.request import urlretrieve
  64. except ImportError:
  65. from urllib import urlretrieve
  66. try:
  67. from exceptions import WindowsError
  68. except ImportError:
  69. class WindowsError(OSError):
  70. pass
  71. TOOLS_FILE = 'tools/tools.json'
  72. TOOLS_SCHEMA_FILE = 'tools/tools_schema.json'
  73. TOOLS_FILE_NEW = 'tools/tools.new.json'
  74. IDF_ENV_FILE = 'idf-env.json'
  75. TOOLS_FILE_VERSION = 1
  76. IDF_TOOLS_PATH_DEFAULT = os.path.join('~', '.espressif')
  77. UNKNOWN_VERSION = 'unknown'
  78. SUBST_TOOL_PATH_REGEX = re.compile(r'\${TOOL_PATH}')
  79. VERSION_REGEX_REPLACE_DEFAULT = r'\1'
  80. IDF_MAINTAINER = os.environ.get('IDF_MAINTAINER') or False
  81. TODO_MESSAGE = 'TODO'
  82. DOWNLOAD_RETRY_COUNT = 3
  83. URL_PREFIX_MAP_SEPARATOR = ','
  84. IDF_TOOLS_INSTALL_CMD = os.environ.get('IDF_TOOLS_INSTALL_CMD')
  85. IDF_TOOLS_EXPORT_CMD = os.environ.get('IDF_TOOLS_INSTALL_CMD')
  86. PYTHON_PLATFORM = platform.system() + '-' + platform.machine()
  87. # Identifiers used in tools.json for different platforms.
  88. PLATFORM_WIN32 = 'win32'
  89. PLATFORM_WIN64 = 'win64'
  90. PLATFORM_MACOS = 'macos'
  91. PLATFORM_LINUX32 = 'linux-i686'
  92. PLATFORM_LINUX64 = 'linux-amd64'
  93. PLATFORM_LINUX_ARM32 = 'linux-armel'
  94. PLATFORM_LINUX_ARM64 = 'linux-arm64'
  95. # Mappings from various other names these platforms are known as, to the identifiers above.
  96. # This includes strings produced from "platform.system() + '-' + platform.machine()", see PYTHON_PLATFORM
  97. # definition above.
  98. # This list also includes various strings used in release archives of xtensa-esp32-elf-gcc, OpenOCD, etc.
  99. PLATFORM_FROM_NAME = {
  100. # Windows
  101. PLATFORM_WIN32: PLATFORM_WIN32,
  102. 'Windows-i686': PLATFORM_WIN32,
  103. 'Windows-x86': PLATFORM_WIN32,
  104. PLATFORM_WIN64: PLATFORM_WIN64,
  105. 'Windows-x86_64': PLATFORM_WIN64,
  106. 'Windows-AMD64': PLATFORM_WIN64,
  107. # macOS
  108. PLATFORM_MACOS: PLATFORM_MACOS,
  109. 'osx': PLATFORM_MACOS,
  110. 'darwin': PLATFORM_MACOS,
  111. 'Darwin-x86_64': PLATFORM_MACOS,
  112. # pretend it is x86_64 until Darwin-arm64 tool builds are available:
  113. 'Darwin-arm64': 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. global_quiet = False
  134. global_non_interactive = False
  135. global_idf_path = None # type: typing.Optional[str]
  136. global_idf_tools_path = None # type: typing.Optional[str]
  137. global_tools_json = None # type: typing.Optional[str]
  138. def fatal(text, *args):
  139. if not global_quiet:
  140. sys.stderr.write('ERROR: ' + text + '\n', *args)
  141. def warn(text, *args):
  142. if not global_quiet:
  143. sys.stderr.write('WARNING: ' + text + '\n', *args)
  144. def info(text, f=None, *args):
  145. if not global_quiet:
  146. if f is None:
  147. f = sys.stdout
  148. f.write(text + '\n', *args)
  149. def run_cmd_check_output(cmd, input_text=None, extra_paths=None):
  150. # If extra_paths is given, locate the executable in one of these directories.
  151. # Note: it would seem logical to add extra_paths to env[PATH], instead, and let OS do the job of finding the
  152. # executable for us. However this does not work on Windows: https://bugs.python.org/issue8557.
  153. if extra_paths:
  154. found = False
  155. extensions = ['']
  156. if sys.platform == 'win32':
  157. extensions.append('.exe')
  158. for path in extra_paths:
  159. for ext in extensions:
  160. fullpath = os.path.join(path, cmd[0] + ext)
  161. if os.path.exists(fullpath):
  162. cmd[0] = fullpath
  163. found = True
  164. break
  165. if found:
  166. break
  167. try:
  168. if input_text:
  169. input_text = input_text.encode()
  170. result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, input=input_text)
  171. return result.stdout + result.stderr
  172. except (AttributeError, TypeError):
  173. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
  174. stdout, stderr = p.communicate(input_text)
  175. if p.returncode != 0:
  176. try:
  177. raise subprocess.CalledProcessError(p.returncode, cmd, stdout, stderr)
  178. except TypeError:
  179. raise subprocess.CalledProcessError(p.returncode, cmd, stdout)
  180. return stdout + stderr
  181. def to_shell_specific_paths(paths_list):
  182. if sys.platform == 'win32':
  183. paths_list = [p.replace('/', os.path.sep) if os.path.sep in p else p for p in paths_list]
  184. if 'MSYSTEM' in os.environ:
  185. paths_msys = run_cmd_check_output(['cygpath', '-u', '-f', '-'],
  186. input_text='\n'.join(paths_list))
  187. paths_list = paths_msys.decode().strip().split('\n')
  188. return paths_list
  189. def get_env_for_extra_paths(extra_paths):
  190. """
  191. Return a copy of environment variables dict, prepending paths listed in extra_paths
  192. to the PATH environment variable.
  193. """
  194. env_arg = os.environ.copy()
  195. new_path = os.pathsep.join(extra_paths) + os.pathsep + env_arg['PATH']
  196. if sys.version_info.major == 2:
  197. env_arg['PATH'] = new_path.encode('utf8')
  198. else:
  199. env_arg['PATH'] = new_path
  200. return env_arg
  201. def get_file_size_sha256(filename, block_size=65536):
  202. sha256 = hashlib.sha256()
  203. size = 0
  204. with open(filename, 'rb') as f:
  205. for block in iter(lambda: f.read(block_size), b''):
  206. sha256.update(block)
  207. size += len(block)
  208. return size, sha256.hexdigest()
  209. def report_progress(count, block_size, total_size):
  210. percent = int(count * block_size * 100 / total_size)
  211. percent = min(100, percent)
  212. sys.stdout.write("\r%d%%" % percent)
  213. sys.stdout.flush()
  214. def mkdir_p(path):
  215. try:
  216. os.makedirs(path)
  217. except OSError as exc:
  218. if exc.errno != errno.EEXIST or not os.path.isdir(path):
  219. raise
  220. def unpack(filename, destination):
  221. info('Extracting {0} to {1}'.format(filename, destination))
  222. if filename.endswith('tar.gz'):
  223. archive_obj = tarfile.open(filename, 'r:gz')
  224. elif filename.endswith('zip'):
  225. archive_obj = zipfile.ZipFile(filename)
  226. else:
  227. raise NotImplementedError('Unsupported archive type')
  228. if sys.version_info.major == 2:
  229. # This is a workaround for the issue that unicode destination is not handled:
  230. # https://bugs.python.org/issue17153
  231. destination = str(destination)
  232. archive_obj.extractall(destination)
  233. # Sometimes renaming a directory on Windows (randomly?) causes a PermissionError.
  234. # This is confirmed to be a workaround:
  235. # https://github.com/espressif/esp-idf/issues/3819#issuecomment-515167118
  236. # https://github.com/espressif/esp-idf/issues/4063#issuecomment-531490140
  237. # https://stackoverflow.com/a/43046729
  238. def rename_with_retry(path_from, path_to):
  239. if sys.platform.startswith('win'):
  240. retry_count = 100
  241. else:
  242. retry_count = 1
  243. for retry in range(retry_count):
  244. try:
  245. os.rename(path_from, path_to)
  246. return
  247. except (OSError, WindowsError): # WindowsError until Python 3.3, then OSError
  248. if retry == retry_count - 1:
  249. raise
  250. warn('Rename {} to {} failed, retrying...'.format(path_from, path_to))
  251. def strip_container_dirs(path, levels):
  252. assert levels > 0
  253. # move the original directory out of the way (add a .tmp suffix)
  254. tmp_path = path + '.tmp'
  255. if os.path.exists(tmp_path):
  256. shutil.rmtree(tmp_path)
  257. rename_with_retry(path, tmp_path)
  258. os.mkdir(path)
  259. base_path = tmp_path
  260. # walk given number of levels down
  261. for level in range(levels):
  262. contents = os.listdir(base_path)
  263. if len(contents) > 1:
  264. raise RuntimeError('at level {}, expected 1 entry, got {}'.format(level, contents))
  265. base_path = os.path.join(base_path, contents[0])
  266. if not os.path.isdir(base_path):
  267. raise RuntimeError('at level {}, {} is not a directory'.format(level, contents[0]))
  268. # get the list of directories/files to move
  269. contents = os.listdir(base_path)
  270. for name in contents:
  271. move_from = os.path.join(base_path, name)
  272. move_to = os.path.join(path, name)
  273. rename_with_retry(move_from, move_to)
  274. shutil.rmtree(tmp_path)
  275. class ToolNotFound(RuntimeError):
  276. pass
  277. class ToolExecError(RuntimeError):
  278. pass
  279. class DownloadError(RuntimeError):
  280. pass
  281. class IDFToolDownload(object):
  282. def __init__(self, platform_name, url, size, sha256):
  283. self.platform_name = platform_name
  284. self.url = url
  285. self.size = size
  286. self.sha256 = sha256
  287. self.platform_name = platform_name
  288. @functools.total_ordering
  289. class IDFToolVersion(object):
  290. STATUS_RECOMMENDED = 'recommended'
  291. STATUS_SUPPORTED = 'supported'
  292. STATUS_DEPRECATED = 'deprecated'
  293. STATUS_VALUES = [STATUS_RECOMMENDED, STATUS_SUPPORTED, STATUS_DEPRECATED]
  294. def __init__(self, version, status):
  295. self.version = version
  296. self.status = status
  297. self.downloads = OrderedDict()
  298. self.latest = False
  299. def __lt__(self, other):
  300. if self.status != other.status:
  301. return self.status > other.status
  302. else:
  303. assert not (self.status == IDFToolVersion.STATUS_RECOMMENDED
  304. and other.status == IDFToolVersion.STATUS_RECOMMENDED)
  305. return self.version < other.version
  306. def __eq__(self, other):
  307. return self.status == other.status and self.version == other.version
  308. def add_download(self, platform_name, url, size, sha256):
  309. self.downloads[platform_name] = IDFToolDownload(platform_name, url, size, sha256)
  310. def get_download_for_platform(self, platform_name): # type: (str) -> IDFToolDownload
  311. if platform_name in PLATFORM_FROM_NAME.keys():
  312. platform_name = PLATFORM_FROM_NAME[platform_name]
  313. if platform_name in self.downloads.keys():
  314. return self.downloads[platform_name]
  315. if 'any' in self.downloads.keys():
  316. return self.downloads['any']
  317. return None
  318. def compatible_with_platform(self, platform_name=PYTHON_PLATFORM):
  319. return self.get_download_for_platform(platform_name) is not None
  320. def get_supported_platforms(self): # type: () -> typing.Set[str]
  321. return set(self.downloads.keys())
  322. OPTIONS_LIST = ['version_cmd',
  323. 'version_regex',
  324. 'version_regex_replace',
  325. 'export_paths',
  326. 'export_vars',
  327. 'install',
  328. 'info_url',
  329. 'license',
  330. 'strip_container_dirs',
  331. 'supported_targets']
  332. IDFToolOptions = namedtuple('IDFToolOptions', OPTIONS_LIST)
  333. class IDFTool(object):
  334. # possible values of 'install' field
  335. INSTALL_ALWAYS = 'always'
  336. INSTALL_ON_REQUEST = 'on_request'
  337. INSTALL_NEVER = 'never'
  338. def __init__(self, name, description, install, info_url, license, version_cmd, version_regex, supported_targets, version_regex_replace=None,
  339. strip_container_dirs=0):
  340. # type: (str, str, str, str, str, list[str], str, list[str], Optional[str], int) -> None
  341. self.name = name
  342. self.description = description
  343. self.versions = OrderedDict() # type: typing.Dict[str, IDFToolVersion]
  344. self.version_in_path = None
  345. self.versions_installed = []
  346. if version_regex_replace is None:
  347. version_regex_replace = VERSION_REGEX_REPLACE_DEFAULT
  348. self.options = IDFToolOptions(version_cmd, version_regex, version_regex_replace,
  349. [], OrderedDict(), install, info_url, license, strip_container_dirs, supported_targets) # type: ignore
  350. self.platform_overrides = [] # type: list[dict[str, str]]
  351. self._platform = CURRENT_PLATFORM
  352. self._update_current_options()
  353. def copy_for_platform(self, platform): # type: (str) -> IDFTool
  354. result = copy.deepcopy(self)
  355. result._platform = platform
  356. result._update_current_options()
  357. return result
  358. def _update_current_options(self):
  359. self._current_options = IDFToolOptions(*self.options)
  360. for override in self.platform_overrides:
  361. if self._platform not in override['platforms']:
  362. continue
  363. override_dict = override.copy()
  364. del override_dict['platforms']
  365. self._current_options = self._current_options._replace(**override_dict)
  366. def add_version(self, version):
  367. assert(type(version) is IDFToolVersion)
  368. self.versions[version.version] = version
  369. def get_path(self): # type: () -> str
  370. return os.path.join(global_idf_tools_path, 'tools', self.name)
  371. def get_path_for_version(self, version): # type: (str) -> str
  372. assert(version in self.versions)
  373. return os.path.join(self.get_path(), version)
  374. def get_export_paths(self, version): # type: (str) -> typing.List[str]
  375. tool_path = self.get_path_for_version(version)
  376. return [os.path.join(tool_path, *p) for p in self._current_options.export_paths]
  377. def get_export_vars(self, version): # type: (str) -> typing.Dict[str]
  378. """
  379. Get the dictionary of environment variables to be exported, for the given version.
  380. Expands:
  381. - ${TOOL_PATH} => the actual path where the version is installed
  382. """
  383. result = {}
  384. for k, v in self._current_options.export_vars.items():
  385. replace_path = self.get_path_for_version(version).replace('\\', '\\\\')
  386. v_repl = re.sub(SUBST_TOOL_PATH_REGEX, replace_path, v)
  387. if v_repl != v:
  388. v_repl = to_shell_specific_paths([v_repl])[0]
  389. result[k] = v_repl
  390. return result
  391. def check_version(self, extra_paths=None): # type: (typing.Optional[typing.List[str]]) -> str
  392. """
  393. Execute the tool, optionally prepending extra_paths to PATH,
  394. extract the version string and return it as a result.
  395. Raises ToolNotFound if the tool is not found (not present in the paths).
  396. Raises ToolExecError if the tool returns with a non-zero exit code.
  397. Returns 'unknown' if tool returns something from which version string
  398. can not be extracted.
  399. """
  400. # this function can not be called for a different platform
  401. assert self._platform == CURRENT_PLATFORM
  402. cmd = self._current_options.version_cmd
  403. try:
  404. version_cmd_result = run_cmd_check_output(cmd, None, extra_paths)
  405. except OSError:
  406. # tool is not on the path
  407. raise ToolNotFound('Tool {} not found'.format(self.name))
  408. except subprocess.CalledProcessError as e:
  409. raise ToolExecError('returned non-zero exit code ({}) with error message:\n{}'.format(
  410. e.returncode, e.stderr.decode('utf-8',errors='ignore'))) # type: ignore
  411. in_str = version_cmd_result.decode("utf-8")
  412. match = re.search(self._current_options.version_regex, in_str)
  413. if not match:
  414. return UNKNOWN_VERSION
  415. return re.sub(self._current_options.version_regex, self._current_options.version_regex_replace, match.group(0))
  416. def get_install_type(self):
  417. return self._current_options.install
  418. def get_supported_targets(self): # type: () -> list[str]
  419. return self._current_options.supported_targets # type: ignore
  420. def compatible_with_platform(self): # type: () -> bool
  421. return any([v.compatible_with_platform() for v in self.versions.values()])
  422. def get_supported_platforms(self): # type: () -> typing.Set[str]
  423. result = set()
  424. for v in self.versions.values():
  425. result.update(v.get_supported_platforms())
  426. return result
  427. def get_recommended_version(self):
  428. recommended_versions = [k for k, v in self.versions.items()
  429. if v.status == IDFToolVersion.STATUS_RECOMMENDED
  430. and v.compatible_with_platform(self._platform)]
  431. assert len(recommended_versions) <= 1
  432. if recommended_versions:
  433. return recommended_versions[0]
  434. return None
  435. def get_preferred_installed_version(self):
  436. recommended_versions = [k for k in self.versions_installed
  437. if self.versions[k].status == IDFToolVersion.STATUS_RECOMMENDED
  438. and self.versions[k].compatible_with_platform(self._platform)]
  439. assert len(recommended_versions) <= 1
  440. if recommended_versions:
  441. return recommended_versions[0]
  442. return None
  443. def find_installed_versions(self):
  444. """
  445. Checks whether the tool can be found in PATH and in global_idf_tools_path.
  446. Writes results to self.version_in_path and self.versions_installed.
  447. """
  448. # this function can not be called for a different platform
  449. assert self._platform == CURRENT_PLATFORM
  450. # First check if the tool is in system PATH
  451. try:
  452. ver_str = self.check_version()
  453. except ToolNotFound:
  454. # not in PATH
  455. pass
  456. except ToolExecError as e:
  457. warn('tool {} found in path, but {}'.format(
  458. self.name, e))
  459. else:
  460. self.version_in_path = ver_str
  461. # Now check all the versions installed in global_idf_tools_path
  462. self.versions_installed = []
  463. for version, version_obj in self.versions.items():
  464. if not version_obj.compatible_with_platform():
  465. continue
  466. tool_path = self.get_path_for_version(version)
  467. if not os.path.exists(tool_path):
  468. # version not installed
  469. continue
  470. try:
  471. ver_str = self.check_version(self.get_export_paths(version))
  472. except ToolNotFound:
  473. warn('directory for tool {} version {} is present, but tool was not found'.format(
  474. self.name, version))
  475. except ToolExecError as e:
  476. warn('tool {} version {} is installed, but {}'.format(
  477. self.name, version, e))
  478. else:
  479. if ver_str != version:
  480. warn('tool {} version {} is installed, but has reported version {}'.format(
  481. self.name, version, ver_str))
  482. else:
  483. self.versions_installed.append(version)
  484. def download(self, version):
  485. assert(version in self.versions)
  486. download_obj = self.versions[version].get_download_for_platform(self._platform)
  487. if not download_obj:
  488. fatal('No packages for tool {} platform {}!'.format(self.name, self._platform))
  489. raise DownloadError()
  490. url = download_obj.url
  491. archive_name = os.path.basename(url)
  492. local_path = os.path.join(global_idf_tools_path, 'dist', archive_name)
  493. mkdir_p(os.path.dirname(local_path))
  494. if os.path.isfile(local_path):
  495. if not self.check_download_file(download_obj, local_path):
  496. warn('removing downloaded file {0} and downloading again'.format(archive_name))
  497. os.unlink(local_path)
  498. else:
  499. info('file {0} is already downloaded'.format(archive_name))
  500. return
  501. downloaded = False
  502. for retry in range(DOWNLOAD_RETRY_COUNT):
  503. local_temp_path = local_path + '.tmp'
  504. info('Downloading {} to {}'.format(archive_name, local_temp_path))
  505. try:
  506. urlretrieve(url, local_temp_path, report_progress if not global_non_interactive else None)
  507. sys.stdout.write("\rDone\n")
  508. except Exception as e:
  509. # urlretrieve could throw different exceptions, e.g. IOError when the server is down
  510. # Errors are ignored because the downloaded file is checked a couple of lines later.
  511. warn('Download failure {}'.format(e))
  512. sys.stdout.flush()
  513. if not os.path.isfile(local_temp_path) or not self.check_download_file(download_obj, local_temp_path):
  514. warn('Failed to download {} to {}'.format(url, local_temp_path))
  515. continue
  516. rename_with_retry(local_temp_path, local_path)
  517. downloaded = True
  518. break
  519. if not downloaded:
  520. fatal('Failed to download, and retry count has expired')
  521. raise DownloadError()
  522. def install(self, version):
  523. # Currently this is called after calling 'download' method, so here are a few asserts
  524. # for the conditions which should be true once that method is done.
  525. assert (version in self.versions)
  526. download_obj = self.versions[version].get_download_for_platform(self._platform)
  527. assert (download_obj is not None)
  528. archive_name = os.path.basename(download_obj.url)
  529. archive_path = os.path.join(global_idf_tools_path, 'dist', archive_name)
  530. assert (os.path.isfile(archive_path))
  531. dest_dir = self.get_path_for_version(version)
  532. if os.path.exists(dest_dir):
  533. warn('destination path already exists, removing')
  534. shutil.rmtree(dest_dir)
  535. mkdir_p(dest_dir)
  536. unpack(archive_path, dest_dir)
  537. if self._current_options.strip_container_dirs:
  538. strip_container_dirs(dest_dir, self._current_options.strip_container_dirs)
  539. @staticmethod
  540. def check_download_file(download_obj, local_path):
  541. expected_sha256 = download_obj.sha256
  542. expected_size = download_obj.size
  543. file_size, file_sha256 = get_file_size_sha256(local_path)
  544. if file_size != expected_size:
  545. warn('file size mismatch for {}, expected {}, got {}'.format(local_path, expected_size, file_size))
  546. return False
  547. if file_sha256 != expected_sha256:
  548. warn('hash mismatch for {}, expected {}, got {}'.format(local_path, expected_sha256, file_sha256))
  549. return False
  550. return True
  551. @classmethod
  552. def from_json(cls, tool_dict):
  553. # json.load will return 'str' types in Python 3 and 'unicode' in Python 2
  554. expected_str_type = type(u'')
  555. # Validate json fields
  556. tool_name = tool_dict.get('name')
  557. if type(tool_name) is not expected_str_type:
  558. raise RuntimeError('tool_name is not a string')
  559. description = tool_dict.get('description')
  560. if type(description) is not expected_str_type:
  561. raise RuntimeError('description is not a string')
  562. version_cmd = tool_dict.get('version_cmd')
  563. if type(version_cmd) is not list:
  564. raise RuntimeError('version_cmd for tool %s is not a list of strings' % tool_name)
  565. version_regex = tool_dict.get('version_regex')
  566. if type(version_regex) is not expected_str_type or not version_regex:
  567. raise RuntimeError('version_regex for tool %s is not a non-empty string' % tool_name)
  568. version_regex_replace = tool_dict.get('version_regex_replace')
  569. if version_regex_replace and type(version_regex_replace) is not expected_str_type:
  570. raise RuntimeError('version_regex_replace for tool %s is not a string' % tool_name)
  571. export_paths = tool_dict.get('export_paths')
  572. if type(export_paths) is not list:
  573. raise RuntimeError('export_paths for tool %s is not a list' % tool_name)
  574. export_vars = tool_dict.get('export_vars', {})
  575. if type(export_vars) is not dict:
  576. raise RuntimeError('export_vars for tool %s is not a mapping' % tool_name)
  577. versions = tool_dict.get('versions')
  578. if type(versions) is not list:
  579. raise RuntimeError('versions for tool %s is not an array' % tool_name)
  580. install = tool_dict.get('install', False)
  581. if type(install) is not expected_str_type:
  582. raise RuntimeError('install for tool %s is not a string' % tool_name)
  583. info_url = tool_dict.get('info_url', False)
  584. if type(info_url) is not expected_str_type:
  585. raise RuntimeError('info_url for tool %s is not a string' % tool_name)
  586. license = tool_dict.get('license', False)
  587. if type(license) is not expected_str_type:
  588. raise RuntimeError('license for tool %s is not a string' % tool_name)
  589. strip_container_dirs = tool_dict.get('strip_container_dirs', 0)
  590. if strip_container_dirs and type(strip_container_dirs) is not int:
  591. raise RuntimeError('strip_container_dirs for tool %s is not an int' % tool_name)
  592. overrides_list = tool_dict.get('platform_overrides', [])
  593. if type(overrides_list) is not list:
  594. raise RuntimeError('platform_overrides for tool %s is not a list' % tool_name)
  595. supported_targets = tool_dict.get('supported_targets')
  596. if not isinstance(supported_targets, list):
  597. raise RuntimeError('supported_targets for tool %s is not a list of strings' % tool_name)
  598. # Create the object
  599. tool_obj = cls(tool_name, description, install, info_url, license, # type: ignore
  600. version_cmd, version_regex, supported_targets, version_regex_replace, # type: ignore
  601. strip_container_dirs) # type: ignore
  602. for path in export_paths:
  603. tool_obj.options.export_paths.append(path)
  604. for name, value in export_vars.items():
  605. tool_obj.options.export_vars[name] = value
  606. for index, override in enumerate(overrides_list):
  607. platforms_list = override.get('platforms')
  608. if type(platforms_list) is not list:
  609. raise RuntimeError('platforms for override %d of tool %s is not a list' % (index, tool_name))
  610. install = override.get('install')
  611. if install is not None and type(install) is not expected_str_type:
  612. raise RuntimeError('install for override %d of tool %s is not a string' % (index, tool_name))
  613. version_cmd = override.get('version_cmd')
  614. if version_cmd is not None and type(version_cmd) is not list:
  615. raise RuntimeError('version_cmd for override %d of tool %s is not a list of strings' %
  616. (index, tool_name))
  617. version_regex = override.get('version_regex')
  618. if version_regex is not None and (type(version_regex) is not expected_str_type or not version_regex):
  619. raise RuntimeError('version_regex for override %d of tool %s is not a non-empty string' %
  620. (index, tool_name))
  621. version_regex_replace = override.get('version_regex_replace')
  622. if version_regex_replace is not None and type(version_regex_replace) is not expected_str_type:
  623. raise RuntimeError('version_regex_replace for override %d of tool %s is not a string' %
  624. (index, tool_name))
  625. export_paths = override.get('export_paths')
  626. if export_paths is not None and type(export_paths) is not list:
  627. raise RuntimeError('export_paths for override %d of tool %s is not a list' % (index, tool_name))
  628. export_vars = override.get('export_vars')
  629. if export_vars is not None and type(export_vars) is not dict:
  630. raise RuntimeError('export_vars for override %d of tool %s is not a mapping' % (index, tool_name))
  631. tool_obj.platform_overrides.append(override)
  632. recommended_versions = {}
  633. for version_dict in versions:
  634. version = version_dict.get('name')
  635. if type(version) is not expected_str_type:
  636. raise RuntimeError('version name for tool {} is not a string'.format(tool_name))
  637. version_status = version_dict.get('status')
  638. if type(version_status) is not expected_str_type and version_status not in IDFToolVersion.STATUS_VALUES:
  639. raise RuntimeError('tool {} version {} status is not one of {}', tool_name, version,
  640. IDFToolVersion.STATUS_VALUES)
  641. version_obj = IDFToolVersion(version, version_status)
  642. for platform_id, platform_dict in version_dict.items():
  643. if platform_id in ['name', 'status']:
  644. continue
  645. if platform_id not in PLATFORM_FROM_NAME.keys():
  646. raise RuntimeError('invalid platform %s for tool %s version %s' %
  647. (platform_id, tool_name, version))
  648. version_obj.add_download(platform_id,
  649. platform_dict['url'], platform_dict['size'], platform_dict['sha256'])
  650. if version_status == IDFToolVersion.STATUS_RECOMMENDED:
  651. if platform_id not in recommended_versions:
  652. recommended_versions[platform_id] = []
  653. recommended_versions[platform_id].append(version)
  654. tool_obj.add_version(version_obj)
  655. for platform_id, version_list in recommended_versions.items():
  656. if len(version_list) > 1:
  657. raise RuntimeError('tool {} for platform {} has {} recommended versions'.format(
  658. tool_name, platform_id, len(recommended_versions)))
  659. if install != IDFTool.INSTALL_NEVER and len(recommended_versions) == 0:
  660. raise RuntimeError('required/optional tool {} for platform {} has no recommended versions'.format(
  661. tool_name, platform_id))
  662. tool_obj._update_current_options()
  663. return tool_obj
  664. def to_json(self):
  665. versions_array = []
  666. for version, version_obj in self.versions.items():
  667. version_json = {
  668. 'name': version,
  669. 'status': version_obj.status
  670. }
  671. for platform_id, download in version_obj.downloads.items():
  672. version_json[platform_id] = {
  673. 'url': download.url,
  674. 'size': download.size,
  675. 'sha256': download.sha256
  676. }
  677. versions_array.append(version_json)
  678. overrides_array = self.platform_overrides
  679. tool_json = {
  680. 'name': self.name,
  681. 'description': self.description,
  682. 'export_paths': self.options.export_paths,
  683. 'export_vars': self.options.export_vars,
  684. 'install': self.options.install,
  685. 'info_url': self.options.info_url,
  686. 'license': self.options.license,
  687. 'version_cmd': self.options.version_cmd,
  688. 'version_regex': self.options.version_regex,
  689. 'supported_targets': self.options.supported_targets,
  690. 'versions': versions_array,
  691. }
  692. if self.options.version_regex_replace != VERSION_REGEX_REPLACE_DEFAULT:
  693. tool_json['version_regex_replace'] = self.options.version_regex_replace
  694. if overrides_array:
  695. tool_json['platform_overrides'] = overrides_array
  696. if self.options.strip_container_dirs:
  697. tool_json['strip_container_dirs'] = self.options.strip_container_dirs
  698. return tool_json
  699. def load_tools_info(): # type: () -> typing.Dict[str, IDFTool]
  700. """
  701. Load tools metadata from tools.json, return a dictionary: tool name - tool info
  702. """
  703. tool_versions_file_name = global_tools_json
  704. with open(tool_versions_file_name, 'r') as f:
  705. tools_info = json.load(f)
  706. return parse_tools_info_json(tools_info)
  707. def parse_tools_info_json(tools_info):
  708. """
  709. Parse and validate the dictionary obtained by loading the tools.json file.
  710. Returns a dictionary of tools (key: tool name, value: IDFTool object).
  711. """
  712. if tools_info['version'] != TOOLS_FILE_VERSION:
  713. raise RuntimeError('Invalid version')
  714. tools_dict = OrderedDict()
  715. tools_array = tools_info.get('tools')
  716. if type(tools_array) is not list:
  717. raise RuntimeError('tools property is missing or not an array')
  718. for tool_dict in tools_array:
  719. tool = IDFTool.from_json(tool_dict)
  720. tools_dict[tool.name] = tool
  721. return tools_dict
  722. def dump_tools_json(tools_info):
  723. tools_array = []
  724. for tool_name, tool_obj in tools_info.items():
  725. tool_json = tool_obj.to_json()
  726. tools_array.append(tool_json)
  727. file_json = {'version': TOOLS_FILE_VERSION, 'tools': tools_array}
  728. return json.dumps(file_json, indent=2, separators=(',', ': '), sort_keys=True)
  729. def get_python_env_path():
  730. python_ver_major_minor = '{}.{}'.format(sys.version_info.major, sys.version_info.minor)
  731. version_file_path = os.path.join(global_idf_path, 'version.txt')
  732. if os.path.exists(version_file_path):
  733. with open(version_file_path, "r") as version_file:
  734. idf_version_str = version_file.read()
  735. else:
  736. idf_version_str = ''
  737. try:
  738. idf_version_str = subprocess.check_output(['git', 'describe'],
  739. cwd=global_idf_path, env=os.environ).decode()
  740. except OSError:
  741. # OSError should cover FileNotFoundError and WindowsError
  742. warn('Git was not found')
  743. except subprocess.CalledProcessError as e:
  744. warn('Git describe was unsuccessul: {}'.format(e.output))
  745. match = re.match(r'^v([0-9]+\.[0-9]+).*', idf_version_str)
  746. if match:
  747. idf_version = match.group(1)
  748. else:
  749. idf_version = None
  750. # fallback when IDF is a shallow clone
  751. try:
  752. with open(os.path.join(global_idf_path, 'components', 'esp_common', 'include', 'esp_idf_version.h')) as f:
  753. m = re.search(r'^#define\s+ESP_IDF_VERSION_MAJOR\s+(\d+).+?^#define\s+ESP_IDF_VERSION_MINOR\s+(\d+)',
  754. f.read(), re.DOTALL | re.MULTILINE)
  755. if m:
  756. idf_version = '.'.join((m.group(1), m.group(2)))
  757. else:
  758. warn('Reading IDF version from C header file failed!')
  759. except Exception as e:
  760. warn('Is it not possible to determine the IDF version: {}'.format(e))
  761. if idf_version is None:
  762. fatal('IDF version cannot be determined')
  763. raise SystemExit(1)
  764. idf_python_env_path = os.path.join(global_idf_tools_path, 'python_env',
  765. 'idf{}_py{}_env'.format(idf_version, python_ver_major_minor))
  766. if sys.platform == 'win32':
  767. subdir = 'Scripts'
  768. python_exe = 'python.exe'
  769. else:
  770. subdir = 'bin'
  771. python_exe = 'python'
  772. idf_python_export_path = os.path.join(idf_python_env_path, subdir)
  773. virtualenv_python = os.path.join(idf_python_export_path, python_exe)
  774. return idf_python_env_path, idf_python_export_path, virtualenv_python
  775. def get_idf_env(): # type: () -> Any
  776. try:
  777. idf_env_file_path = os.path.join(global_idf_tools_path, IDF_ENV_FILE) # type: ignore
  778. with open(idf_env_file_path, 'r') as idf_env_file:
  779. return json.load(idf_env_file)
  780. except (IOError, OSError):
  781. if not os.path.exists(idf_env_file_path):
  782. warn('File {} was not found. '.format(idf_env_file_path))
  783. else:
  784. filename, ending = os.path.splitext(os.path.basename(idf_env_file_path))
  785. warn('File {} can not be opened, renaming to {}'.format(idf_env_file_path,filename + '_failed' + ending))
  786. os.rename(idf_env_file_path, os.path.join(os.path.dirname(idf_env_file_path), (filename + '_failed' + ending)))
  787. info('Creating {}' .format(idf_env_file_path))
  788. return {'idfSelectedId': 'sha', 'idfInstalled': {'sha': {'targets': {}}}}
  789. def export_targets_to_idf_env_json(targets): # type: (list[str]) -> None
  790. idf_env_json = get_idf_env()
  791. targets = list(set(targets + get_user_defined_targets()))
  792. for env in idf_env_json['idfInstalled']:
  793. if env == idf_env_json['idfSelectedId']:
  794. idf_env_json['idfInstalled'][env]['targets'] = targets
  795. break
  796. try:
  797. with open(os.path.join(global_idf_tools_path, IDF_ENV_FILE), 'w') as w: # type: ignore
  798. json.dump(idf_env_json, w, indent=4)
  799. except (IOError, OSError):
  800. warn('File {} can not be created. '.format(os.path.join(global_idf_tools_path, IDF_ENV_FILE))) # type: ignore
  801. def clean_targets(targets_str): # type: (str) -> list[str]
  802. targets_from_tools_json = get_all_targets_from_tools_json()
  803. invalid_targets = []
  804. targets_str = targets_str.lower()
  805. targets = targets_str.replace('-', '').split(',')
  806. if targets != ['all']:
  807. invalid_targets = [t for t in targets if t not in targets_from_tools_json]
  808. if invalid_targets:
  809. warn('Targets: "{}" are not supported. Only allowed options are: {}.'.format(', '.join(invalid_targets), ', '.join(targets_from_tools_json)))
  810. raise SystemExit(1)
  811. # removing duplicates
  812. targets = list(set(targets))
  813. export_targets_to_idf_env_json(targets)
  814. else:
  815. export_targets_to_idf_env_json(targets_from_tools_json)
  816. return targets
  817. def get_user_defined_targets(): # type: () -> list[str]
  818. try:
  819. with open(os.path.join(global_idf_tools_path, IDF_ENV_FILE), 'r') as idf_env_file: # type: ignore
  820. idf_env_json = json.load(idf_env_file)
  821. except (OSError, IOError):
  822. # warn('File {} was not found. Installing tools for all esp targets.'.format(os.path.join(global_idf_tools_path, IDF_ENV_FILE))) # type: ignore
  823. return []
  824. targets = []
  825. for env in idf_env_json['idfInstalled']:
  826. if env == idf_env_json['idfSelectedId']:
  827. targets = idf_env_json['idfInstalled'][env]['targets']
  828. break
  829. return targets
  830. def get_all_targets_from_tools_json(): # type: () -> list[str]
  831. tools_info = load_tools_info()
  832. targets_from_tools_json = [] # type: list[str]
  833. for _, v in tools_info.items():
  834. targets_from_tools_json.extend(v.get_supported_targets())
  835. # remove duplicates
  836. targets_from_tools_json = list(set(targets_from_tools_json))
  837. if 'all' in targets_from_tools_json:
  838. targets_from_tools_json.remove('all')
  839. return sorted(targets_from_tools_json)
  840. def filter_tools_info(tools_info): # type: (OrderedDict[str, IDFTool]) -> OrderedDict[str,IDFTool]
  841. targets = get_user_defined_targets()
  842. if not targets:
  843. return tools_info
  844. else:
  845. filtered_tools_spec = {k:v for k, v in tools_info.items() if
  846. (v.get_install_type() == IDFTool.INSTALL_ALWAYS or v.get_install_type() == IDFTool.INSTALL_ON_REQUEST) and
  847. (any(item in targets for item in v.get_supported_targets()) or v.get_supported_targets() == ['all'])}
  848. return OrderedDict(filtered_tools_spec)
  849. def action_list(args): # type: ignore
  850. tools_info = load_tools_info()
  851. for name, tool in tools_info.items():
  852. if tool.get_install_type() == IDFTool.INSTALL_NEVER:
  853. continue
  854. optional_str = ' (optional)' if tool.get_install_type() == IDFTool.INSTALL_ON_REQUEST else ''
  855. info('* {}: {}{}'.format(name, tool.description, optional_str))
  856. tool.find_installed_versions()
  857. versions_for_platform = {k: v for k, v in tool.versions.items() if v.compatible_with_platform()}
  858. if not versions_for_platform:
  859. info(' (no versions compatible with platform {})'.format(PYTHON_PLATFORM))
  860. continue
  861. versions_sorted = sorted(versions_for_platform.keys(), key=tool.versions.get, reverse=True)
  862. for version in versions_sorted:
  863. version_obj = tool.versions[version]
  864. info(' - {} ({}{})'.format(version, version_obj.status,
  865. ', installed' if version in tool.versions_installed else ''))
  866. def action_check(args):
  867. tools_info = load_tools_info()
  868. tools_info = filter_tools_info(tools_info)
  869. not_found_list = []
  870. info('Checking for installed tools...')
  871. for name, tool in tools_info.items():
  872. if tool.get_install_type() == IDFTool.INSTALL_NEVER:
  873. continue
  874. tool_found_somewhere = False
  875. info('Checking tool %s' % name)
  876. tool.find_installed_versions()
  877. if tool.version_in_path:
  878. info(' version found in PATH: %s' % tool.version_in_path)
  879. tool_found_somewhere = True
  880. else:
  881. info(' no version found in PATH')
  882. for version in tool.versions_installed:
  883. info(' version installed in tools directory: %s' % version)
  884. tool_found_somewhere = True
  885. if not tool_found_somewhere and tool.get_install_type() == IDFTool.INSTALL_ALWAYS:
  886. not_found_list.append(name)
  887. if not_found_list:
  888. fatal('The following required tools were not found: ' + ' '.join(not_found_list))
  889. raise SystemExit(1)
  890. def action_export(args):
  891. tools_info = load_tools_info()
  892. tools_info = filter_tools_info(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. targets = [] # type: list[str]
  1049. # Installing only single tools, no targets are specified.
  1050. if 'required' in tools_spec:
  1051. targets = clean_targets(args.targets)
  1052. if args.platform not in PLATFORM_FROM_NAME:
  1053. fatal('unknown platform: {}' % args.platform)
  1054. raise SystemExit(1)
  1055. platform = PLATFORM_FROM_NAME[args.platform]
  1056. tools_info_for_platform = OrderedDict()
  1057. for name, tool_obj in tools_info.items():
  1058. tool_for_platform = tool_obj.copy_for_platform(platform)
  1059. tools_info_for_platform[name] = tool_for_platform
  1060. if not tools_spec or 'required' in tools_spec:
  1061. # Downloading tools for all ESP_targets required by the operating system.
  1062. tools_spec = [k for k, v in tools_info_for_platform.items() if v.get_install_type() == IDFTool.INSTALL_ALWAYS]
  1063. # Filtering tools user defined list of ESP_targets
  1064. if 'all' not in targets:
  1065. def is_tool_selected(tool): # type: (IDFTool) -> bool
  1066. supported_targets = tool.get_supported_targets()
  1067. return (any(item in targets for item in supported_targets) or supported_targets == ['all'])
  1068. tools_spec = [k for k in tools_spec if is_tool_selected(tools_info[k])]
  1069. info('Downloading tools for {}: {}'.format(platform, ', '.join(tools_spec)))
  1070. # Downloading tools for all ESP_targets (MacOS, Windows, Linux)
  1071. elif 'all' in tools_spec:
  1072. tools_spec = [k for k, v in tools_info_for_platform.items() if v.get_install_type() != IDFTool.INSTALL_NEVER]
  1073. info('Downloading tools for {}: {}'.format(platform, ', '.join(tools_spec)))
  1074. for tool_spec in tools_spec:
  1075. if '@' not in tool_spec:
  1076. tool_name = tool_spec
  1077. tool_version = None
  1078. else:
  1079. tool_name, tool_version = tool_spec.split('@', 1)
  1080. if tool_name not in tools_info_for_platform:
  1081. fatal('unknown tool name: {}'.format(tool_name))
  1082. raise SystemExit(1)
  1083. tool_obj = tools_info_for_platform[tool_name]
  1084. if tool_version is not None and tool_version not in tool_obj.versions:
  1085. fatal('unknown version for tool {}: {}'.format(tool_name, tool_version))
  1086. raise SystemExit(1)
  1087. if tool_version is None:
  1088. tool_version = tool_obj.get_recommended_version()
  1089. if tool_version is None:
  1090. fatal('tool {} not found for {} platform'.format(tool_name, platform))
  1091. raise SystemExit(1)
  1092. tool_spec = '{}@{}'.format(tool_name, tool_version)
  1093. info('Downloading {}'.format(tool_spec))
  1094. apply_url_mirrors(args, tool_obj.versions[tool_version].get_download_for_platform(platform))
  1095. tool_obj.download(tool_version)
  1096. def action_install(args):
  1097. tools_info = load_tools_info()
  1098. tools_spec = args.tools # type: ignore
  1099. targets = [] # type: list[str]
  1100. # Installing only single tools, no targets are specified.
  1101. if 'required' in tools_spec:
  1102. targets = clean_targets(args.targets)
  1103. info('Selected targets are: {}' .format(', '.join(get_user_defined_targets())))
  1104. if not tools_spec or 'required' in tools_spec:
  1105. # Installing tools for all ESP_targets required by the operating system.
  1106. tools_spec = [k for k, v in tools_info.items() if v.get_install_type() == IDFTool.INSTALL_ALWAYS]
  1107. # Filtering tools user defined list of ESP_targets
  1108. if 'all' not in targets:
  1109. def is_tool_selected(tool): # type: (IDFTool) -> bool
  1110. supported_targets = tool.get_supported_targets()
  1111. return (any(item in targets for item in supported_targets) or supported_targets == ['all'])
  1112. tools_spec = [k for k in tools_spec if is_tool_selected(tools_info[k])]
  1113. info('Installing tools: {}'.format(', '.join(tools_spec)))
  1114. # Installing tools for all ESP_targets (MacOS, Windows, Linux)
  1115. elif 'all' in tools_spec:
  1116. tools_spec = [k for k, v in tools_info.items() if v.get_install_type() != IDFTool.INSTALL_NEVER]
  1117. info('Installing tools: {}'.format(', '.join(tools_spec)))
  1118. for tool_spec in tools_spec:
  1119. if '@' not in tool_spec:
  1120. tool_name = tool_spec
  1121. tool_version = None
  1122. else:
  1123. tool_name, tool_version = tool_spec.split('@', 1)
  1124. if tool_name not in tools_info:
  1125. fatal('unknown tool name: {}'.format(tool_name))
  1126. raise SystemExit(1)
  1127. tool_obj = tools_info[tool_name]
  1128. if not tool_obj.compatible_with_platform():
  1129. fatal('tool {} does not have versions compatible with platform {}'.format(tool_name, CURRENT_PLATFORM))
  1130. raise SystemExit(1)
  1131. if tool_version is not None and tool_version not in tool_obj.versions:
  1132. fatal('unknown version for tool {}: {}'.format(tool_name, tool_version))
  1133. raise SystemExit(1)
  1134. if tool_version is None:
  1135. tool_version = tool_obj.get_recommended_version()
  1136. assert tool_version is not None
  1137. tool_obj.find_installed_versions()
  1138. tool_spec = '{}@{}'.format(tool_name, tool_version)
  1139. if tool_version in tool_obj.versions_installed:
  1140. info('Skipping {} (already installed)'.format(tool_spec))
  1141. continue
  1142. info('Installing {}'.format(tool_spec))
  1143. apply_url_mirrors(args, tool_obj.versions[tool_version].get_download_for_platform(PYTHON_PLATFORM))
  1144. tool_obj.download(tool_version)
  1145. tool_obj.install(tool_version)
  1146. def action_install_python_env(args): # type: ignore
  1147. reinstall = args.reinstall
  1148. idf_python_env_path, _, virtualenv_python = get_python_env_path()
  1149. is_virtualenv = hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix)
  1150. if is_virtualenv and (not os.path.exists(idf_python_env_path) or reinstall):
  1151. fatal('This script was called from a virtual environment, can not create a virtual environment again')
  1152. raise SystemExit(1)
  1153. if os.path.exists(virtualenv_python):
  1154. try:
  1155. subprocess.check_call([virtualenv_python, '--version'], stdout=sys.stdout, stderr=sys.stderr)
  1156. except (OSError, subprocess.CalledProcessError):
  1157. # At this point we can reinstall the virtual environment if it is non-functional. This can happen at least
  1158. # when the Python interpreter was removed which was used to create the virtual environment.
  1159. reinstall = True
  1160. try:
  1161. subprocess.check_call([virtualenv_python, '-m', 'pip', '--version'], stdout=sys.stdout, stderr=sys.stderr)
  1162. except subprocess.CalledProcessError:
  1163. warn('PIP is not available in the virtual environment.')
  1164. # Reinstallation of the virtual environment could help if PIP was installed for the main Python
  1165. reinstall = True
  1166. if reinstall and os.path.exists(idf_python_env_path):
  1167. warn('Removing the existing Python environment in {}'.format(idf_python_env_path))
  1168. shutil.rmtree(idf_python_env_path)
  1169. if not os.path.exists(virtualenv_python):
  1170. info('Creating a new Python environment in {}'.format(idf_python_env_path))
  1171. try:
  1172. import virtualenv # noqa: F401
  1173. except ImportError:
  1174. info('Installing virtualenv')
  1175. subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--user', 'virtualenv'],
  1176. stdout=sys.stdout, stderr=sys.stderr)
  1177. subprocess.check_call([sys.executable, '-m', 'virtualenv', '--seeder', 'pip', idf_python_env_path],
  1178. stdout=sys.stdout, stderr=sys.stderr)
  1179. run_args = [virtualenv_python, '-m', 'pip', 'install', '--no-warn-script-location']
  1180. requirements_txt = os.path.join(global_idf_path, 'requirements.txt')
  1181. run_args += ['-r', requirements_txt]
  1182. if args.extra_wheels_dir:
  1183. run_args += ['--find-links', args.extra_wheels_dir]
  1184. info('Installing Python packages from {}'.format(requirements_txt))
  1185. subprocess.check_call(run_args, stdout=sys.stdout, stderr=sys.stderr)
  1186. def action_add_version(args):
  1187. tools_info = load_tools_info()
  1188. tool_name = args.tool
  1189. tool_obj = tools_info.get(tool_name)
  1190. if not tool_obj:
  1191. info('Creating new tool entry for {}'.format(tool_name))
  1192. tool_obj = IDFTool(tool_name, TODO_MESSAGE, IDFTool.INSTALL_ALWAYS,
  1193. TODO_MESSAGE, TODO_MESSAGE, [TODO_MESSAGE], TODO_MESSAGE)
  1194. tools_info[tool_name] = tool_obj
  1195. version = args.version
  1196. version_obj = tool_obj.versions.get(version)
  1197. if version not in tool_obj.versions:
  1198. info('Creating new version {}'.format(version))
  1199. version_obj = IDFToolVersion(version, IDFToolVersion.STATUS_SUPPORTED)
  1200. tool_obj.versions[version] = version_obj
  1201. url_prefix = args.url_prefix or 'https://%s/' % TODO_MESSAGE
  1202. for file_path in args.files:
  1203. file_name = os.path.basename(file_path)
  1204. # Guess which platform this file is for
  1205. found_platform = None
  1206. for platform_alias, platform_id in PLATFORM_FROM_NAME.items():
  1207. if platform_alias in file_name:
  1208. found_platform = platform_id
  1209. break
  1210. if found_platform is None:
  1211. info('Could not guess platform for file {}'.format(file_name))
  1212. found_platform = TODO_MESSAGE
  1213. # Get file size and calculate the SHA256
  1214. file_size, file_sha256 = get_file_size_sha256(file_path)
  1215. url = url_prefix + file_name
  1216. info('Adding download for platform {}'.format(found_platform))
  1217. info(' size: {}'.format(file_size))
  1218. info(' SHA256: {}'.format(file_sha256))
  1219. info(' URL: {}'.format(url))
  1220. version_obj.add_download(found_platform, url, file_size, file_sha256)
  1221. json_str = dump_tools_json(tools_info)
  1222. if not args.output:
  1223. args.output = os.path.join(global_idf_path, TOOLS_FILE_NEW)
  1224. with open(args.output, 'w') as f:
  1225. f.write(json_str)
  1226. f.write('\n')
  1227. info('Wrote output to {}'.format(args.output))
  1228. def action_rewrite(args):
  1229. tools_info = load_tools_info()
  1230. json_str = dump_tools_json(tools_info)
  1231. if not args.output:
  1232. args.output = os.path.join(global_idf_path, TOOLS_FILE_NEW)
  1233. with open(args.output, 'w') as f:
  1234. f.write(json_str)
  1235. f.write('\n')
  1236. info('Wrote output to {}'.format(args.output))
  1237. def action_validate(args):
  1238. try:
  1239. import jsonschema
  1240. except ImportError:
  1241. fatal('You need to install jsonschema package to use validate command')
  1242. raise SystemExit(1)
  1243. with open(os.path.join(global_idf_path, TOOLS_FILE), 'r') as tools_file:
  1244. tools_json = json.load(tools_file)
  1245. with open(os.path.join(global_idf_path, TOOLS_SCHEMA_FILE), 'r') as schema_file:
  1246. schema_json = json.load(schema_file)
  1247. jsonschema.validate(tools_json, schema_json)
  1248. # on failure, this will raise an exception with a fairly verbose diagnostic message
  1249. def action_gen_doc(args):
  1250. f = args.output
  1251. tools_info = load_tools_info()
  1252. def print_out(text):
  1253. f.write(text + '\n')
  1254. print_out(".. |zwsp| unicode:: U+200B")
  1255. print_out(" :trim:")
  1256. print_out("")
  1257. idf_gh_url = "https://github.com/espressif/esp-idf"
  1258. for tool_name, tool_obj in tools_info.items():
  1259. info_url = tool_obj.options.info_url
  1260. if idf_gh_url + "/tree" in info_url:
  1261. info_url = re.sub(idf_gh_url + r"/tree/\w+/(.*)", r":idf:`\1`", info_url)
  1262. license_url = "https://spdx.org/licenses/" + tool_obj.options.license
  1263. print_out("""
  1264. .. _tool-{name}:
  1265. {name}
  1266. {underline}
  1267. {description}
  1268. .. include:: idf-tools-notes.inc
  1269. :start-after: tool-{name}-notes
  1270. :end-before: ---
  1271. License: `{license} <{license_url}>`_
  1272. More info: {info_url}
  1273. .. list-table::
  1274. :widths: 10 10 80
  1275. :header-rows: 1
  1276. * - Platform
  1277. - Required
  1278. - Download
  1279. """.rstrip().format(name=tool_name,
  1280. underline=args.heading_underline_char * len(tool_name),
  1281. description=tool_obj.description,
  1282. license=tool_obj.options.license,
  1283. license_url=license_url,
  1284. info_url=info_url))
  1285. for platform_name in sorted(tool_obj.get_supported_platforms()):
  1286. platform_tool = tool_obj.copy_for_platform(platform_name)
  1287. install_type = platform_tool.get_install_type()
  1288. if install_type == IDFTool.INSTALL_NEVER:
  1289. continue
  1290. elif install_type == IDFTool.INSTALL_ALWAYS:
  1291. install_type_str = "required"
  1292. elif install_type == IDFTool.INSTALL_ON_REQUEST:
  1293. install_type_str = "optional"
  1294. else:
  1295. raise NotImplementedError()
  1296. version = platform_tool.get_recommended_version()
  1297. version_obj = platform_tool.versions[version]
  1298. download_obj = version_obj.get_download_for_platform(platform_name)
  1299. # Note: keep the list entries indented to the same number of columns
  1300. # as the list header above.
  1301. print_out("""
  1302. * - {}
  1303. - {}
  1304. - {}
  1305. .. rst-class:: tool-sha256
  1306. SHA256: {}
  1307. """.strip('\n').format(platform_name, install_type_str, download_obj.url, download_obj.sha256))
  1308. print_out('')
  1309. print_out('')
  1310. def main(argv):
  1311. parser = argparse.ArgumentParser()
  1312. parser.add_argument('--quiet', help='Don\'t output diagnostic messages to stdout/stderr', action='store_true')
  1313. parser.add_argument('--non-interactive', help='Don\'t output interactive messages and questions', action='store_true')
  1314. parser.add_argument('--tools-json', help='Path to the tools.json file to use')
  1315. parser.add_argument('--idf-path', help='ESP-IDF path to use')
  1316. subparsers = parser.add_subparsers(dest='action')
  1317. subparsers.add_parser('list', help='List tools and versions available')
  1318. subparsers.add_parser('check', help='Print summary of tools installed or found in PATH')
  1319. export = subparsers.add_parser('export', help='Output command for setting tool paths, suitable for shell')
  1320. export.add_argument('--format', choices=[EXPORT_SHELL, EXPORT_KEY_VALUE], default=EXPORT_SHELL,
  1321. help='Format of the output: shell (suitable for printing into shell), ' +
  1322. 'or key-value (suitable for parsing by other tools')
  1323. export.add_argument('--prefer-system', help='Normally, if the tool is already present in PATH, ' +
  1324. 'but has an unsupported version, a version from the tools directory ' +
  1325. 'will be used instead. If this flag is given, the version in PATH ' +
  1326. 'will be used.', action='store_true')
  1327. install = subparsers.add_parser('install', help='Download and install tools into the tools directory')
  1328. install.add_argument('tools', metavar='TOOL', nargs='*', default=['required'],
  1329. help='Tools to install. ' +
  1330. 'To install a specific version use <tool_name>@<version> syntax. ' +
  1331. 'Use empty or \'required\' to install required tools, not optional ones. ' +
  1332. 'Use \'all\' to install all tools, including the optional ones.')
  1333. install.add_argument('--targets', default='all', help='A comma separated list of desired chip targets for installing.' +
  1334. ' It defaults to installing all supported targets.')
  1335. download = subparsers.add_parser('download', help='Download the tools into the dist directory')
  1336. download.add_argument('--platform', help='Platform to download the tools for')
  1337. download.add_argument('tools', metavar='TOOL', nargs='*', default=['required'],
  1338. help='Tools to download. ' +
  1339. 'To download a specific version use <tool_name>@<version> syntax. ' +
  1340. 'Use empty or \'required\' to download required tools, not optional ones. ' +
  1341. 'Use \'all\' to download all tools, including the optional ones.')
  1342. download.add_argument('--targets', default='all', help='A comma separated list of desired chip targets for installing.' +
  1343. ' It defaults to installing all supported targets.')
  1344. if IDF_MAINTAINER:
  1345. for subparser in [download, install]:
  1346. subparser.add_argument('--mirror-prefix-map', nargs='*',
  1347. help='Pattern to rewrite download URLs, with source and replacement separated by comma.' +
  1348. ' E.g. http://foo.com,http://test.foo.com')
  1349. install_python_env = subparsers.add_parser('install-python-env',
  1350. help='Create Python virtual environment and install the ' +
  1351. 'required Python packages')
  1352. install_python_env.add_argument('--reinstall', help='Discard the previously installed environment',
  1353. action='store_true')
  1354. install_python_env.add_argument('--extra-wheels-dir', help='Additional directories with wheels ' +
  1355. 'to use during installation')
  1356. if IDF_MAINTAINER:
  1357. add_version = subparsers.add_parser('add-version', help='Add or update download info for a version')
  1358. add_version.add_argument('--output', help='Save new tools.json into this file')
  1359. add_version.add_argument('--tool', help='Tool name to set add a version for', required=True)
  1360. add_version.add_argument('--version', help='Version identifier', required=True)
  1361. add_version.add_argument('--url-prefix', help='String to prepend to file names to obtain download URLs')
  1362. add_version.add_argument('files', help='File names of the download artifacts', nargs='*')
  1363. rewrite = subparsers.add_parser('rewrite', help='Load tools.json, validate, and save the result back into JSON')
  1364. rewrite.add_argument('--output', help='Save new tools.json into this file')
  1365. subparsers.add_parser('validate', help='Validate tools.json against schema file')
  1366. gen_doc = subparsers.add_parser('gen-doc', help='Write the list of tools as a documentation page')
  1367. gen_doc.add_argument('--output', type=argparse.FileType('w'), default=sys.stdout,
  1368. help='Output file name')
  1369. gen_doc.add_argument('--heading-underline-char', help='Character to use when generating RST sections', default='~')
  1370. args = parser.parse_args(argv)
  1371. if args.action is None:
  1372. parser.print_help()
  1373. parser.exit(1)
  1374. if args.quiet:
  1375. global global_quiet
  1376. global_quiet = True
  1377. if args.non_interactive:
  1378. global global_non_interactive
  1379. global_non_interactive = True
  1380. global global_idf_path
  1381. global_idf_path = os.environ.get('IDF_PATH')
  1382. if args.idf_path:
  1383. global_idf_path = args.idf_path
  1384. if not global_idf_path:
  1385. global_idf_path = os.path.realpath(os.path.join(os.path.dirname(__file__), ".."))
  1386. os.environ['IDF_PATH'] = global_idf_path
  1387. global global_idf_tools_path
  1388. global_idf_tools_path = os.environ.get('IDF_TOOLS_PATH') or os.path.expanduser(IDF_TOOLS_PATH_DEFAULT)
  1389. # On macOS, unset __PYVENV_LAUNCHER__ variable if it is set.
  1390. # Otherwise sys.executable keeps pointing to the system Python, even when a python binary from a virtualenv is invoked.
  1391. # See https://bugs.python.org/issue22490#msg283859.
  1392. os.environ.pop('__PYVENV_LAUNCHER__', None)
  1393. if sys.version_info.major == 2:
  1394. try:
  1395. global_idf_tools_path.decode('ascii')
  1396. except UnicodeDecodeError:
  1397. fatal('IDF_TOOLS_PATH contains non-ASCII characters: {}'.format(global_idf_tools_path) +
  1398. '\nThis is not supported yet with Python 2. ' +
  1399. 'Please set IDF_TOOLS_PATH to a directory with an ASCII name, or switch to Python 3.')
  1400. raise SystemExit(1)
  1401. if CURRENT_PLATFORM == UNKNOWN_PLATFORM:
  1402. fatal('Platform {} appears to be unsupported'.format(PYTHON_PLATFORM))
  1403. raise SystemExit(1)
  1404. global global_tools_json
  1405. if args.tools_json:
  1406. global_tools_json = args.tools_json
  1407. else:
  1408. global_tools_json = os.path.join(global_idf_path, TOOLS_FILE)
  1409. action_func_name = 'action_' + args.action.replace('-', '_')
  1410. action_func = globals()[action_func_name]
  1411. action_func(args)
  1412. if __name__ == '__main__':
  1413. main(sys.argv[1:])