-
Notifications
You must be signed in to change notification settings - Fork 7.4k
/
Copy pathidf_tools.py
executable file
·1589 lines (1339 loc) · 65.6 KB
/
idf_tools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding=utf-8
#
# This script helps installing tools required to use the ESP-IDF, and updating PATH
# to use the installed tools. It can also create a Python virtual environment,
# and install Python requirements into it.
# It does not install OS dependencies. It does install tools such as the Xtensa
# GCC toolchain and ESP32 ULP coprocessor toolchain.
#
# By default, downloaded tools will be installed under $HOME/.espressif directory
# (%USERPROFILE%/.espressif on Windows). This path can be modified by setting
# IDF_TOOLS_PATH variable prior to running this tool.
#
# Users do not need to interact with this script directly. In IDF root directory,
# install.sh (.bat) and export.sh (.bat) scripts are provided to invoke this script.
#
# Usage:
#
# * To install the tools, run `idf_tools.py install`.
#
# * To install the Python environment, run `idf_tools.py install-python-env`.
#
# * To start using the tools, run `eval "$(idf_tools.py export)"` — this will update
# the PATH to point to the installed tools and set up other environment variables
# needed by the tools.
#
###
#
# Copyright 2019 Espressif Systems (Shanghai) PTE LTD
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import os
import subprocess
import sys
import argparse
import re
import platform
import hashlib
import tarfile
import zipfile
import errno
import shutil
import functools
import copy
from collections import OrderedDict, namedtuple
import ssl
import contextlib
try:
import typing # noqa: F401
except ImportError:
pass
try:
from urllib.parse import splittype
from urllib.request import urlopen
from urllib.error import ContentTooShortError
except ImportError:
from urllib import urlopen, splittype, ContentTooShortError
try:
from exceptions import WindowsError
except ImportError:
class WindowsError(OSError):
pass
TOOLS_FILE = 'tools/tools.json'
TOOLS_SCHEMA_FILE = 'tools/tools_schema.json'
TOOLS_FILE_NEW = 'tools/tools.new.json'
TOOLS_FILE_VERSION = 1
IDF_TOOLS_PATH_DEFAULT = os.path.join('~', '.espressif')
UNKNOWN_VERSION = 'unknown'
SUBST_TOOL_PATH_REGEX = re.compile(r'\${TOOL_PATH}')
VERSION_REGEX_REPLACE_DEFAULT = r'\1'
IDF_MAINTAINER = os.environ.get('IDF_MAINTAINER') or False
TODO_MESSAGE = 'TODO'
DOWNLOAD_RETRY_COUNT = 3
URL_PREFIX_MAP_SEPARATOR = ','
IDF_TOOLS_INSTALL_CMD = os.environ.get('IDF_TOOLS_INSTALL_CMD')
IDF_TOOLS_EXPORT_CMD = os.environ.get('IDF_TOOLS_INSTALL_CMD')
PYTHON_PLATFORM = platform.system() + '-' + platform.machine()
# Identifiers used in tools.json for different platforms.
PLATFORM_WIN32 = 'win32'
PLATFORM_WIN64 = 'win64'
PLATFORM_MACOS = 'macos'
PLATFORM_LINUX32 = 'linux-i686'
PLATFORM_LINUX64 = 'linux-amd64'
PLATFORM_LINUX_ARM32 = 'linux-armel'
PLATFORM_LINUX_ARM64 = 'linux-arm64'
# Mappings from various other names these platforms are known as, to the identifiers above.
# This includes strings produced from "platform.system() + '-' + platform.machine()", see PYTHON_PLATFORM
# definition above.
# This list also includes various strings used in release archives of xtensa-esp32-elf-gcc, OpenOCD, etc.
PLATFORM_FROM_NAME = {
# Windows
PLATFORM_WIN32: PLATFORM_WIN32,
'Windows-i686': PLATFORM_WIN32,
'Windows-x86': PLATFORM_WIN32,
PLATFORM_WIN64: PLATFORM_WIN64,
'Windows-x86_64': PLATFORM_WIN64,
'Windows-AMD64': PLATFORM_WIN64,
# macOS
PLATFORM_MACOS: PLATFORM_MACOS,
'osx': PLATFORM_MACOS,
'darwin': PLATFORM_MACOS,
'Darwin-x86_64': PLATFORM_MACOS,
# Linux
PLATFORM_LINUX64: PLATFORM_LINUX64,
'linux64': PLATFORM_LINUX64,
'Linux-x86_64': PLATFORM_LINUX64,
PLATFORM_LINUX32: PLATFORM_LINUX32,
'linux32': PLATFORM_LINUX32,
'Linux-i686': PLATFORM_LINUX32,
PLATFORM_LINUX_ARM32: PLATFORM_LINUX_ARM32,
'Linux-arm': PLATFORM_LINUX_ARM32,
'Linux-armv7l': PLATFORM_LINUX_ARM32,
PLATFORM_LINUX_ARM64: PLATFORM_LINUX_ARM64,
'Linux-arm64': PLATFORM_LINUX_ARM64,
'Linux-aarch64': PLATFORM_LINUX_ARM64,
'Linux-armv8l': PLATFORM_LINUX_ARM64,
}
UNKNOWN_PLATFORM = 'unknown'
CURRENT_PLATFORM = PLATFORM_FROM_NAME.get(PYTHON_PLATFORM, UNKNOWN_PLATFORM)
EXPORT_SHELL = 'shell'
EXPORT_KEY_VALUE = 'key-value'
ISRG_X1_ROOT_CERT = u"""
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn
jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw
qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
-----END CERTIFICATE-----
"""
global_quiet = False
global_non_interactive = False
global_idf_path = None # type: typing.Optional[str]
global_idf_tools_path = None # type: typing.Optional[str]
global_tools_json = None # type: typing.Optional[str]
def fatal(text, *args):
if not global_quiet:
sys.stderr.write('ERROR: ' + text + '\n', *args)
def warn(text, *args):
if not global_quiet:
sys.stderr.write('WARNING: ' + text + '\n', *args)
def info(text, f=None, *args):
if not global_quiet:
if f is None:
f = sys.stdout
f.write(text + '\n', *args)
def run_cmd_check_output(cmd, input_text=None, extra_paths=None):
# If extra_paths is given, locate the executable in one of these directories.
# Note: it would seem logical to add extra_paths to env[PATH], instead, and let OS do the job of finding the
# executable for us. However this does not work on Windows: https://bugs.python.org/issue8557.
if extra_paths:
found = False
extensions = ['']
if sys.platform == 'win32':
extensions.append('.exe')
for path in extra_paths:
for ext in extensions:
fullpath = os.path.join(path, cmd[0] + ext)
if os.path.exists(fullpath):
cmd[0] = fullpath
found = True
break
if found:
break
try:
if input_text:
input_text = input_text.encode()
result = subprocess.run(cmd, capture_output=True, check=True, input=input_text)
return result.stdout + result.stderr
except (AttributeError, TypeError):
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate(input_text)
if p.returncode != 0:
try:
raise subprocess.CalledProcessError(p.returncode, cmd, stdout, stderr)
except TypeError:
raise subprocess.CalledProcessError(p.returncode, cmd, stdout)
return stdout + stderr
def to_shell_specific_paths(paths_list):
if sys.platform == 'win32':
paths_list = [p.replace('/', os.path.sep) if os.path.sep in p else p for p in paths_list]
if 'MSYSTEM' in os.environ:
paths_msys = run_cmd_check_output(['cygpath', '-u', '-f', '-'],
input_text='\n'.join(paths_list))
paths_list = paths_msys.decode().strip().split('\n')
return paths_list
def get_env_for_extra_paths(extra_paths):
"""
Return a copy of environment variables dict, prepending paths listed in extra_paths
to the PATH environment variable.
"""
env_arg = os.environ.copy()
new_path = os.pathsep.join(extra_paths) + os.pathsep + env_arg['PATH']
if sys.version_info.major == 2:
env_arg['PATH'] = new_path.encode('utf8')
else:
env_arg['PATH'] = new_path
return env_arg
def get_file_size_sha256(filename, block_size=65536):
sha256 = hashlib.sha256()
size = 0
with open(filename, 'rb') as f:
for block in iter(lambda: f.read(block_size), b''):
sha256.update(block)
size += len(block)
return size, sha256.hexdigest()
def report_progress(count, block_size, total_size):
percent = int(count * block_size * 100 / total_size)
percent = min(100, percent)
sys.stdout.write("\r%d%%" % percent)
sys.stdout.flush()
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc:
if exc.errno != errno.EEXIST or not os.path.isdir(path):
raise
def unpack(filename, destination):
info('Extracting {0} to {1}'.format(filename, destination))
if filename.endswith(('.tar.gz', '.tgz')):
archive_obj = tarfile.open(filename, 'r:gz')
elif filename.endswith('zip'):
archive_obj = zipfile.ZipFile(filename)
else:
raise NotImplementedError('Unsupported archive type')
if sys.version_info.major == 2:
# This is a workaround for the issue that unicode destination is not handled:
# https://bugs.python.org/issue17153
destination = str(destination)
archive_obj.extractall(destination)
# An alternative version of urlretrieve which takes SSL context as an argument
def urlretrieve_ctx(url, filename, reporthook=None, data=None, context=None):
url_type, path = splittype(url)
# urlopen doesn't have context argument in Python <=2.7.9
extra_urlopen_args = {}
if context:
extra_urlopen_args["context"] = context
with contextlib.closing(urlopen(url, data, **extra_urlopen_args)) as fp:
headers = fp.info()
# Just return the local path and the "headers" for file://
# URLs. No sense in performing a copy unless requested.
if url_type == "file" and not filename:
return os.path.normpath(path), headers
# Handle temporary file setup.
tfp = open(filename, 'wb')
with tfp:
result = filename, headers
bs = 1024 * 8
size = int(headers.get("content-length", -1))
read = 0
blocknum = 0
if reporthook:
reporthook(blocknum, bs, size)
while True:
block = fp.read(bs)
if not block:
break
read += len(block)
tfp.write(block)
blocknum += 1
if reporthook:
reporthook(blocknum, bs, size)
if size >= 0 and read < size:
raise ContentTooShortError(
"retrieval incomplete: got only %i out of %i bytes"
% (read, size), result)
return result
# Sometimes renaming a directory on Windows (randomly?) causes a PermissionError.
# This is confirmed to be a workaround:
# https://github.com/espressif/esp-idf/issues/3819#issuecomment-515167118
# https://github.com/espressif/esp-idf/issues/4063#issuecomment-531490140
# https://stackoverflow.com/a/43046729
def rename_with_retry(path_from, path_to):
if sys.platform.startswith('win'):
retry_count = 100
else:
retry_count = 1
for retry in range(retry_count):
try:
os.rename(path_from, path_to)
return
except (OSError, WindowsError): # WindowsError until Python 3.3, then OSError
if retry == retry_count - 1:
raise
warn('Rename {} to {} failed, retrying...'.format(path_from, path_to))
def strip_container_dirs(path, levels):
assert levels > 0
# move the original directory out of the way (add a .tmp suffix)
tmp_path = path + '.tmp'
if os.path.exists(tmp_path):
shutil.rmtree(tmp_path)
rename_with_retry(path, tmp_path)
os.mkdir(path)
base_path = tmp_path
# walk given number of levels down
for level in range(levels):
contents = os.listdir(base_path)
if len(contents) > 1:
raise RuntimeError('at level {}, expected 1 entry, got {}'.format(level, contents))
base_path = os.path.join(base_path, contents[0])
if not os.path.isdir(base_path):
raise RuntimeError('at level {}, {} is not a directory'.format(level, contents[0]))
# get the list of directories/files to move
contents = os.listdir(base_path)
for name in contents:
move_from = os.path.join(base_path, name)
move_to = os.path.join(path, name)
rename_with_retry(move_from, move_to)
shutil.rmtree(tmp_path)
class ToolNotFound(RuntimeError):
pass
class ToolExecError(RuntimeError):
pass
class DownloadError(RuntimeError):
pass
class IDFToolDownload(object):
def __init__(self, platform_name, url, size, sha256):
self.platform_name = platform_name
self.url = url
self.size = size
self.sha256 = sha256
self.platform_name = platform_name
@functools.total_ordering
class IDFToolVersion(object):
STATUS_RECOMMENDED = 'recommended'
STATUS_SUPPORTED = 'supported'
STATUS_DEPRECATED = 'deprecated'
STATUS_VALUES = [STATUS_RECOMMENDED, STATUS_SUPPORTED, STATUS_DEPRECATED]
def __init__(self, version, status):
self.version = version
self.status = status
self.downloads = OrderedDict()
self.latest = False
def __lt__(self, other):
if self.status != other.status:
return self.status > other.status
else:
assert not (self.status == IDFToolVersion.STATUS_RECOMMENDED
and other.status == IDFToolVersion.STATUS_RECOMMENDED)
return self.version < other.version
def __eq__(self, other):
return self.status == other.status and self.version == other.version
def add_download(self, platform_name, url, size, sha256):
self.downloads[platform_name] = IDFToolDownload(platform_name, url, size, sha256)
def get_download_for_platform(self, platform_name): # type: (str) -> IDFToolDownload
if platform_name in PLATFORM_FROM_NAME.keys():
platform_name = PLATFORM_FROM_NAME[platform_name]
if platform_name in self.downloads.keys():
return self.downloads[platform_name]
if 'any' in self.downloads.keys():
return self.downloads['any']
return None
def compatible_with_platform(self, platform_name=PYTHON_PLATFORM):
return self.get_download_for_platform(platform_name) is not None
def get_supported_platforms(self): # type: () -> typing.Set[str]
return set(self.downloads.keys())
OPTIONS_LIST = ['version_cmd',
'version_regex',
'version_regex_replace',
'export_paths',
'export_vars',
'install',
'info_url',
'license',
'strip_container_dirs']
IDFToolOptions = namedtuple('IDFToolOptions', OPTIONS_LIST)
class IDFTool(object):
# possible values of 'install' field
INSTALL_ALWAYS = 'always'
INSTALL_ON_REQUEST = 'on_request'
INSTALL_NEVER = 'never'
def __init__(self, name, description, install, info_url, license, version_cmd, version_regex, version_regex_replace=None,
strip_container_dirs=0):
self.name = name
self.description = description
self.versions = OrderedDict() # type: typing.Dict[str, IDFToolVersion]
self.version_in_path = None
self.versions_installed = []
if version_regex_replace is None:
version_regex_replace = VERSION_REGEX_REPLACE_DEFAULT
self.options = IDFToolOptions(version_cmd, version_regex, version_regex_replace,
[], OrderedDict(), install, info_url, license, strip_container_dirs)
self.platform_overrides = []
self._platform = CURRENT_PLATFORM
self._update_current_options()
def copy_for_platform(self, platform): # type: (str) -> IDFTool
result = copy.deepcopy(self)
result._platform = platform
result._update_current_options()
return result
def _update_current_options(self):
self._current_options = IDFToolOptions(*self.options)
for override in self.platform_overrides:
if self._platform not in override['platforms']:
continue
override_dict = override.copy()
del override_dict['platforms']
self._current_options = self._current_options._replace(**override_dict)
def add_version(self, version):
assert(type(version) is IDFToolVersion)
self.versions[version.version] = version
def get_path(self): # type: () -> str
return os.path.join(global_idf_tools_path, 'tools', self.name)
def get_path_for_version(self, version): # type: (str) -> str
assert(version in self.versions)
return os.path.join(self.get_path(), version)
def get_export_paths(self, version): # type: (str) -> typing.List[str]
tool_path = self.get_path_for_version(version)
return [os.path.join(tool_path, *p) for p in self._current_options.export_paths]
def get_export_vars(self, version): # type: (str) -> typing.Dict[str]
"""
Get the dictionary of environment variables to be exported, for the given version.
Expands:
- ${TOOL_PATH} => the actual path where the version is installed
"""
result = {}
for k, v in self._current_options.export_vars.items():
replace_path = self.get_path_for_version(version).replace('\\', '\\\\')
v_repl = re.sub(SUBST_TOOL_PATH_REGEX, replace_path, v)
if v_repl != v:
v_repl = to_shell_specific_paths([v_repl])[0]
result[k] = v_repl
return result
def check_version(self, extra_paths=None): # type: (typing.Optional[typing.List[str]]) -> str
"""
Execute the tool, optionally prepending extra_paths to PATH,
extract the version string and return it as a result.
Raises ToolNotFound if the tool is not found (not present in the paths).
Raises ToolExecError if the tool returns with a non-zero exit code.
Returns 'unknown' if tool returns something from which version string
can not be extracted.
"""
# this function can not be called for a different platform
assert self._platform == CURRENT_PLATFORM
cmd = self._current_options.version_cmd
try:
version_cmd_result = run_cmd_check_output(cmd, None, extra_paths)
except OSError:
# tool is not on the path
raise ToolNotFound('Tool {} not found'.format(self.name))
except subprocess.CalledProcessError as e:
raise ToolExecError('Command {} has returned non-zero exit code ({})\n'.format(
' '.join(self._current_options.version_cmd), e.returncode))
in_str = version_cmd_result.decode("utf-8")
match = re.search(self._current_options.version_regex, in_str)
if not match:
return UNKNOWN_VERSION
return re.sub(self._current_options.version_regex, self._current_options.version_regex_replace, match.group(0))
def get_install_type(self):
return self._current_options.install
def compatible_with_platform(self):
return any([v.compatible_with_platform() for v in self.versions.values()])
def get_supported_platforms(self): # type: () -> typing.Set[str]
result = set()
for v in self.versions.values():
result.update(v.get_supported_platforms())
return result
def get_recommended_version(self):
recommended_versions = [k for k, v in self.versions.items()
if v.status == IDFToolVersion.STATUS_RECOMMENDED
and v.compatible_with_platform(self._platform)]
assert len(recommended_versions) <= 1
if recommended_versions:
return recommended_versions[0]
return None
def get_preferred_installed_version(self):
recommended_versions = [k for k in self.versions_installed
if self.versions[k].status == IDFToolVersion.STATUS_RECOMMENDED
and self.versions[k].compatible_with_platform(self._platform)]
assert len(recommended_versions) <= 1
if recommended_versions:
return recommended_versions[0]
return None
def find_installed_versions(self):
"""
Checks whether the tool can be found in PATH and in global_idf_tools_path.
Writes results to self.version_in_path and self.versions_installed.
"""
# this function can not be called for a different platform
assert self._platform == CURRENT_PLATFORM
# First check if the tool is in system PATH
try:
ver_str = self.check_version()
except ToolNotFound:
# not in PATH
pass
except ToolExecError:
warn('tool {} found in path, but failed to run'.format(self.name))
else:
self.version_in_path = ver_str
# Now check all the versions installed in global_idf_tools_path
self.versions_installed = []
for version, version_obj in self.versions.items():
if not version_obj.compatible_with_platform():
continue
tool_path = self.get_path_for_version(version)
if not os.path.exists(tool_path):
# version not installed
continue
try:
ver_str = self.check_version(self.get_export_paths(version))
except ToolNotFound:
warn('directory for tool {} version {} is present, but tool was not found'.format(
self.name, version))
except ToolExecError:
warn('tool {} version {} is installed, but the tool failed to run'.format(
self.name, version))
else:
if ver_str != version:
warn('tool {} version {} is installed, but has reported version {}'.format(
self.name, version, ver_str))
else:
self.versions_installed.append(version)
def download(self, version):
assert(version in self.versions)
download_obj = self.versions[version].get_download_for_platform(self._platform)
if not download_obj:
fatal('No packages for tool {} platform {}!'.format(self.name, self._platform))
raise DownloadError()
url = download_obj.url
archive_name = os.path.basename(url)
local_path = os.path.join(global_idf_tools_path, 'dist', archive_name)
mkdir_p(os.path.dirname(local_path))
if os.path.isfile(local_path):
if not self.check_download_file(download_obj, local_path):
warn('removing downloaded file {0} and downloading again'.format(archive_name))
os.unlink(local_path)
else:
info('file {0} is already downloaded'.format(archive_name))
return
downloaded = False
for retry in range(DOWNLOAD_RETRY_COUNT):
local_temp_path = local_path + '.tmp'
info('Downloading {} to {}'.format(archive_name, local_temp_path))
try:
ctx = None
# For dl.espressif.com, add the ISRG x1 root certificate.
# This works around the issue with outdated certificate stores in some installations.
if "dl.espressif.com" in url:
try:
ctx = ssl.create_default_context()
ctx.load_verify_locations(cadata=ISRG_X1_ROOT_CERT)
except AttributeError:
# no ssl.create_default_context or load_verify_locations cadata argument
# in Python <=2.7.8
pass
urlretrieve_ctx(url, local_temp_path, report_progress if not global_non_interactive else None, context=ctx)
sys.stdout.write("\rDone\n")
except Exception as e:
# urlretrieve could throw different exceptions, e.g. IOError when the server is down
# Errors are ignored because the downloaded file is checked a couple of lines later.
warn('Download failure {}'.format(e))
sys.stdout.flush()
if not os.path.isfile(local_temp_path) or not self.check_download_file(download_obj, local_temp_path):
warn('Failed to download {} to {}'.format(url, local_temp_path))
continue
rename_with_retry(local_temp_path, local_path)
downloaded = True
break
if not downloaded:
fatal('Failed to download, and retry count has expired')
raise DownloadError()
def install(self, version):
# Currently this is called after calling 'download' method, so here are a few asserts
# for the conditions which should be true once that method is done.
assert (version in self.versions)
download_obj = self.versions[version].get_download_for_platform(self._platform)
assert (download_obj is not None)
archive_name = os.path.basename(download_obj.url)
archive_path = os.path.join(global_idf_tools_path, 'dist', archive_name)
assert (os.path.isfile(archive_path))
dest_dir = self.get_path_for_version(version)
if os.path.exists(dest_dir):
warn('destination path already exists, removing')
shutil.rmtree(dest_dir)
mkdir_p(dest_dir)
unpack(archive_path, dest_dir)
if self._current_options.strip_container_dirs:
strip_container_dirs(dest_dir, self._current_options.strip_container_dirs)
@staticmethod
def check_download_file(download_obj, local_path):
expected_sha256 = download_obj.sha256
expected_size = download_obj.size
file_size, file_sha256 = get_file_size_sha256(local_path)
if file_size != expected_size:
warn('file size mismatch for {}, expected {}, got {}'.format(local_path, expected_size, file_size))
return False
if file_sha256 != expected_sha256:
warn('hash mismatch for {}, expected {}, got {}'.format(local_path, expected_sha256, file_sha256))
return False
return True
@classmethod
def from_json(cls, tool_dict):
# json.load will return 'str' types in Python 3 and 'unicode' in Python 2
expected_str_type = type(u'')
# Validate json fields
tool_name = tool_dict.get('name')
if type(tool_name) is not expected_str_type:
raise RuntimeError('tool_name is not a string')
description = tool_dict.get('description')
if type(description) is not expected_str_type:
raise RuntimeError('description is not a string')
version_cmd = tool_dict.get('version_cmd')
if type(version_cmd) is not list:
raise RuntimeError('version_cmd for tool %s is not a list of strings' % tool_name)
version_regex = tool_dict.get('version_regex')
if type(version_regex) is not expected_str_type or not version_regex:
raise RuntimeError('version_regex for tool %s is not a non-empty string' % tool_name)
version_regex_replace = tool_dict.get('version_regex_replace')
if version_regex_replace and type(version_regex_replace) is not expected_str_type:
raise RuntimeError('version_regex_replace for tool %s is not a string' % tool_name)
export_paths = tool_dict.get('export_paths')
if type(export_paths) is not list:
raise RuntimeError('export_paths for tool %s is not a list' % tool_name)
export_vars = tool_dict.get('export_vars', {})
if type(export_vars) is not dict:
raise RuntimeError('export_vars for tool %s is not a mapping' % tool_name)
versions = tool_dict.get('versions')
if type(versions) is not list:
raise RuntimeError('versions for tool %s is not an array' % tool_name)
install = tool_dict.get('install', False)
if type(install) is not expected_str_type:
raise RuntimeError('install for tool %s is not a string' % tool_name)
info_url = tool_dict.get('info_url', False)
if type(info_url) is not expected_str_type:
raise RuntimeError('info_url for tool %s is not a string' % tool_name)
license = tool_dict.get('license', False)
if type(license) is not expected_str_type:
raise RuntimeError('license for tool %s is not a string' % tool_name)
strip_container_dirs = tool_dict.get('strip_container_dirs', 0)
if strip_container_dirs and type(strip_container_dirs) is not int:
raise RuntimeError('strip_container_dirs for tool %s is not an int' % tool_name)
overrides_list = tool_dict.get('platform_overrides', [])
if type(overrides_list) is not list:
raise RuntimeError('platform_overrides for tool %s is not a list' % tool_name)
# Create the object
tool_obj = cls(tool_name, description, install, info_url, license,
version_cmd, version_regex, version_regex_replace,
strip_container_dirs)
for path in export_paths:
tool_obj.options.export_paths.append(path)
for name, value in export_vars.items():
tool_obj.options.export_vars[name] = value
for index, override in enumerate(overrides_list):
platforms_list = override.get('platforms')
if type(platforms_list) is not list:
raise RuntimeError('platforms for override %d of tool %s is not a list' % (index, tool_name))
install = override.get('install')
if install is not None and type(install) is not expected_str_type:
raise RuntimeError('install for override %d of tool %s is not a string' % (index, tool_name))
version_cmd = override.get('version_cmd')
if version_cmd is not None and type(version_cmd) is not list:
raise RuntimeError('version_cmd for override %d of tool %s is not a list of strings' %
(index, tool_name))
version_regex = override.get('version_regex')
if version_regex is not None and (type(version_regex) is not expected_str_type or not version_regex):
raise RuntimeError('version_regex for override %d of tool %s is not a non-empty string' %
(index, tool_name))
version_regex_replace = override.get('version_regex_replace')
if version_regex_replace is not None and type(version_regex_replace) is not expected_str_type:
raise RuntimeError('version_regex_replace for override %d of tool %s is not a string' %
(index, tool_name))
export_paths = override.get('export_paths')
if export_paths is not None and type(export_paths) is not list:
raise RuntimeError('export_paths for override %d of tool %s is not a list' % (index, tool_name))
export_vars = override.get('export_vars')
if export_vars is not None and type(export_vars) is not dict:
raise RuntimeError('export_vars for override %d of tool %s is not a mapping' % (index, tool_name))
tool_obj.platform_overrides.append(override)
recommended_versions = {}
for version_dict in versions:
version = version_dict.get('name')
if type(version) is not expected_str_type:
raise RuntimeError('version name for tool {} is not a string'.format(tool_name))
version_status = version_dict.get('status')
if type(version_status) is not expected_str_type and version_status not in IDFToolVersion.STATUS_VALUES:
raise RuntimeError('tool {} version {} status is not one of {}', tool_name, version,
IDFToolVersion.STATUS_VALUES)
version_obj = IDFToolVersion(version, version_status)
for platform_id, platform_dict in version_dict.items():
if platform_id in ['name', 'status']:
continue
if platform_id not in PLATFORM_FROM_NAME.keys():
raise RuntimeError('invalid platform %s for tool %s version %s' %
(platform_id, tool_name, version))
version_obj.add_download(platform_id,
platform_dict['url'], platform_dict['size'], platform_dict['sha256'])
if version_status == IDFToolVersion.STATUS_RECOMMENDED:
if platform_id not in recommended_versions:
recommended_versions[platform_id] = []
recommended_versions[platform_id].append(version)
tool_obj.add_version(version_obj)
for platform_id, version_list in recommended_versions.items():
if len(version_list) > 1:
raise RuntimeError('tool {} for platform {} has {} recommended versions'.format(
tool_name, platform_id, len(recommended_versions)))
if install != IDFTool.INSTALL_NEVER and len(recommended_versions) == 0:
raise RuntimeError('required/optional tool {} for platform {} has no recommended versions'.format(
tool_name, platform_id))
tool_obj._update_current_options()
return tool_obj
def to_json(self):
versions_array = []
for version, version_obj in self.versions.items():
version_json = {
'name': version,
'status': version_obj.status
}
for platform_id, download in version_obj.downloads.items():
version_json[platform_id] = {
'url': download.url,
'size': download.size,
'sha256': download.sha256
}
versions_array.append(version_json)
overrides_array = self.platform_overrides
tool_json = {
'name': self.name,
'description': self.description,
'export_paths': self.options.export_paths,
'export_vars': self.options.export_vars,
'install': self.options.install,
'info_url': self.options.info_url,
'license': self.options.license,
'version_cmd': self.options.version_cmd,
'version_regex': self.options.version_regex,
'versions': versions_array,
}
if self.options.version_regex_replace != VERSION_REGEX_REPLACE_DEFAULT:
tool_json['version_regex_replace'] = self.options.version_regex_replace
if overrides_array:
tool_json['platform_overrides'] = overrides_array
if self.options.strip_container_dirs:
tool_json['strip_container_dirs'] = self.options.strip_container_dirs
return tool_json
def load_tools_info(): # type: () -> typing.Dict[str, IDFTool]
"""
Load tools metadata from tools.json, return a dictionary: tool name - tool info
"""
tool_versions_file_name = global_tools_json
with open(tool_versions_file_name, 'r') as f:
tools_info = json.load(f)
return parse_tools_info_json(tools_info)
def parse_tools_info_json(tools_info):
"""
Parse and validate the dictionary obtained by loading the tools.json file.
Returns a dictionary of tools (key: tool name, value: IDFTool object).
"""
if tools_info['version'] != TOOLS_FILE_VERSION:
raise RuntimeError('Invalid version')
tools_dict = OrderedDict()
tools_array = tools_info.get('tools')
if type(tools_array) is not list:
raise RuntimeError('tools property is missing or not an array')
for tool_dict in tools_array:
tool = IDFTool.from_json(tool_dict)
tools_dict[tool.name] = tool
return tools_dict
def dump_tools_json(tools_info):
tools_array = []
for tool_name, tool_obj in tools_info.items():
tool_json = tool_obj.to_json()
tools_array.append(tool_json)
file_json = {'version': TOOLS_FILE_VERSION, 'tools': tools_array}
return json.dumps(file_json, indent=2, separators=(',', ': '), sort_keys=True)
def get_python_env_path():
python_ver_major_minor = '{}.{}'.format(sys.version_info.major, sys.version_info.minor)
version_file_path = os.path.join(global_idf_path, 'version.txt')
if os.path.exists(version_file_path):
with open(version_file_path, "r") as version_file:
idf_version_str = version_file.read()
else:
try:
idf_version_str = subprocess.check_output(['git', 'describe'],
cwd=global_idf_path, env=os.environ).decode()
except subprocess.CalledProcessError as e:
warn('Git describe was unsuccessul: {}'.format(e))
idf_version_str = ''
match = re.match(r'^v([0-9]+\.[0-9]+).*', idf_version_str)
if match:
idf_version = match.group(1)
else:
idf_version = None
# fallback when IDF is a shallow clone
try:
with open(os.path.join(global_idf_path, 'components', 'esp_common', 'include', 'esp_idf_version.h')) as f:
m = re.search(r'^#define\s+ESP_IDF_VERSION_MAJOR\s+(\d+).+?^#define\s+ESP_IDF_VERSION_MINOR\s+(\d+)',
f.read(), re.DOTALL | re.MULTILINE)
if m:
idf_version = '.'.join((m.group(1), m.group(2)))
else:
warn('Reading IDF version from C header file failed!')
except Exception as e:
warn('Is it not possible to determine the IDF version: {}'.format(e))
if idf_version is None:
fatal('IDF version cannot be determined')
raise SystemExit(1)
idf_python_env_path = os.path.join(global_idf_tools_path, 'python_env',
'idf{}_py{}_env'.format(idf_version, python_ver_major_minor))
if sys.platform == 'win32':
subdir = 'Scripts'
python_exe = 'python.exe'
else:
subdir = 'bin'
python_exe = 'python'
idf_python_export_path = os.path.join(idf_python_env_path, subdir)
virtualenv_python = os.path.join(idf_python_export_path, python_exe)
return idf_python_env_path, idf_python_export_path, virtualenv_python
def action_list(args):
tools_info = load_tools_info()