-
Notifications
You must be signed in to change notification settings - Fork 7.4k
/
idf_tools.py
executable file
·3262 lines (2783 loc) · 139 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
#
# SPDX-FileCopyrightText: 2019-2024 Espressif Systems (Shanghai) CO LTD
#
# SPDX-License-Identifier: Apache-2.0
#
# 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.
import argparse
import contextlib
import copy
import datetime
import errno
import fnmatch
import functools
import hashlib
import json
import os
import platform
import re
import shutil
import ssl
import subprocess
import sys
import tarfile
import tempfile
import time
from collections import namedtuple
from collections import OrderedDict
from json import JSONEncoder
from ssl import SSLContext
from tarfile import TarFile
from zipfile import ZipFile
# Important notice: Please keep the lines above compatible with old Pythons so it won't fail with ImportError but with
# a nice message printed by python_version_checker.check()
try:
import python_version_checker
# check the Python version before it will fail with an exception on syntax or package incompatibility.
python_version_checker.check()
except RuntimeError as e:
print(e)
raise SystemExit(1)
from typing import IO, Any, Callable, Dict, Iterator, List, Optional, Set, Tuple, Union
from urllib.error import ContentTooShortError
from urllib.parse import urljoin, urlparse
from urllib.request import urlopen
from urllib.response import addinfourl
try:
from exceptions import WindowsError
except ImportError:
# Unix
class WindowsError(OSError): # type: ignore
pass
TOOLS_FILE = 'tools/tools.json'
TOOLS_SCHEMA_FILE = 'tools/tools_schema.json'
TOOLS_FILE_NEW = 'tools/tools.new.json'
IDF_ENV_FILE = 'idf-env.json'
TOOLS_FILE_VERSION = 2
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')
IDF_DL_URL = 'https://dl.espressif.com/dl/esp-idf'
IDF_PIP_WHEELS_URL = os.environ.get('IDF_PIP_WHEELS_URL', 'https://dl.espressif.com/pypi')
PYTHON_VENV_DIR_TEMPLATE = 'idf{}_py{}_env'
PYTHON_VER_MAJOR_MINOR = f'{sys.version_info.major}.{sys.version_info.minor}'
VENV_VER_FILE = 'idf_version.txt'
class GlobalVarsStore:
"""
Pythonic way how to handle global variables.
One global instance of this class is initialized and used as an entrypoint (store)
It handles string and boolean properties.
"""
_instance: Optional['GlobalVarsStore'] = None
_bool_properties = ['quiet', 'non_interactive']
_string_properties = ['idf_path', 'idf_tools_path', 'tools_json']
def __new__(cls, *args: Any, **kwargs: Any) -> 'GlobalVarsStore':
if not cls._instance:
cls._instance = super(GlobalVarsStore, cls).__new__(cls, *args, **kwargs)
cls._instance._initialize_properties()
return cls._instance
def _initialize_properties(self) -> None:
# Initialize boolean properties to False
for prop in self._bool_properties:
setattr(self, f'_{prop}', False)
# Initialize string properties to None
for prop in self._string_properties:
setattr(self, f'_{prop}', None)
def __getattr__(self, name: str) -> Any:
if name in self._bool_properties + self._string_properties:
value: Union[str, bool] = getattr(self, f'_{name}')
if value is None and name in self._string_properties:
raise ReferenceError(f'Variable {name} accessed before initialization.')
return value
raise AttributeError(f'{name} is not a valid attribute')
def __setattr__(self, name: str, value: Any) -> None:
if name in self._bool_properties + self._string_properties:
super().__setattr__(f'_{name}', value)
else:
super().__setattr__(name, value)
g = GlobalVarsStore()
def fatal(text: str, *args: str) -> None:
"""
Writes ERROR: + text to sys.stderr.
"""
if not g.quiet:
sys.stderr.write(f'ERROR: {text}\n', *args)
def warn(text: str, *args: str) -> None:
"""
Writes WARNING: + text to sys.stderr.
"""
if not g.quiet:
sys.stderr.write(f'WARNING: {text}\n', *args)
def info(text: str, f: Optional[IO[str]]=None, *args: str) -> None:
"""
Writes text to a stream specified by second arg, sys.stdout by default.
"""
if not g.quiet:
if f is None:
f = sys.stdout
f.write(f'{text}\n', *args)
def print_hints_on_download_error(err: str) -> None:
"""
Prints hint on download error. Tries to specify the message depending on the error.
"""
info('Please make sure you have a working Internet connection.')
if 'CERTIFICATE' in err:
info('Certificate issues are usually caused by an outdated certificate database on your computer.')
info('Please check the documentation of your operating system for how to upgrade it.')
if sys.platform == 'darwin':
info('Running "./Install\\ Certificates.command" might be able to fix this issue.')
info(f'Running "{sys.executable} -m pip install --upgrade certifi" can also resolve this issue in some cases.')
# Certificate issue on Windows can be hidden under different errors which might be even translated,
# e.g. "[WinError -2146881269] ASN1 valor de tag inválido encontrado"
if sys.platform == 'win32':
info('By downloading and using the offline installer from https://dl.espressif.com/dl/esp-idf '
'you might be able to work around this issue.')
PYTHON_PLATFORM = f'{platform.system()}-{platform.machine()}'
# Identifiers used in tools.json for different platforms.
PLATFORM_WIN32 = 'win32'
PLATFORM_WIN64 = 'win64'
PLATFORM_MACOS = 'macos'
PLATFORM_MACOS_ARM64 = 'macos-arm64'
PLATFORM_LINUX32 = 'linux-i686'
PLATFORM_LINUX64 = 'linux-amd64'
PLATFORM_LINUX_ARM32 = 'linux-armel'
PLATFORM_LINUX_ARMHF = 'linux-armhf'
PLATFORM_LINUX_ARM64 = 'linux-arm64'
class Platforms:
"""
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.
"""
# 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,
'i686-w64-mingw32': PLATFORM_WIN32,
PLATFORM_WIN64: PLATFORM_WIN64,
'Windows-x86_64': PLATFORM_WIN64,
'Windows-AMD64': PLATFORM_WIN64,
'x86_64-w64-mingw32': PLATFORM_WIN64,
'Windows-ARM64': PLATFORM_WIN64,
# macOS
PLATFORM_MACOS: PLATFORM_MACOS,
'osx': PLATFORM_MACOS,
'darwin': PLATFORM_MACOS,
'Darwin-x86_64': PLATFORM_MACOS,
'x86_64-apple-darwin': PLATFORM_MACOS,
PLATFORM_MACOS_ARM64: PLATFORM_MACOS_ARM64,
'Darwin-arm64': PLATFORM_MACOS_ARM64,
'aarch64-apple-darwin': PLATFORM_MACOS_ARM64,
'arm64-apple-darwin': PLATFORM_MACOS_ARM64,
# Linux
PLATFORM_LINUX64: PLATFORM_LINUX64,
'linux64': PLATFORM_LINUX64,
'Linux-x86_64': PLATFORM_LINUX64,
'FreeBSD-amd64': PLATFORM_LINUX64,
'x86_64-linux-gnu': PLATFORM_LINUX64,
PLATFORM_LINUX32: PLATFORM_LINUX32,
'linux32': PLATFORM_LINUX32,
'Linux-i686': PLATFORM_LINUX32,
'FreeBSD-i386': PLATFORM_LINUX32,
'i586-linux-gnu': PLATFORM_LINUX32,
'i686-linux-gnu': PLATFORM_LINUX32,
PLATFORM_LINUX_ARM64: PLATFORM_LINUX_ARM64,
'Linux-arm64': PLATFORM_LINUX_ARM64,
'Linux-aarch64': PLATFORM_LINUX_ARM64,
'Linux-armv8l': PLATFORM_LINUX_ARM64,
'aarch64': PLATFORM_LINUX_ARM64,
PLATFORM_LINUX_ARMHF: PLATFORM_LINUX_ARMHF,
'arm-linux-gnueabihf': PLATFORM_LINUX_ARMHF,
PLATFORM_LINUX_ARM32: PLATFORM_LINUX_ARM32,
'arm-linux-gnueabi': PLATFORM_LINUX_ARM32,
'Linux-armv7l': PLATFORM_LINUX_ARM32,
'Linux-arm': PLATFORM_LINUX_ARM32,
}
# List of platforms that are not supported by ESP-IDF
UNSUPPORTED_PLATFORMS = [
'Linux-armv6l'
]
@staticmethod
def detect_linux_arm_platform(supposed_platform: Optional[str]) -> Optional[str]:
"""
We probe the python binary to check exactly what environment the script is running in.
ARM platform may run on armhf hardware but having armel installed packages.
To avoid possible armel/armhf libraries mixing need to define user's
packages architecture to use the same
See note section in https://gcc.gnu.org/onlinedocs/gcc/ARM-Options.html#index-mfloat-abi
ARM platform may run on aarch64 hardware but having armhf installed packages
(it happens if a docker container is running on arm64 hardware, but using an armhf image).
"""
if supposed_platform not in (PLATFORM_LINUX_ARM32, PLATFORM_LINUX_ARMHF, PLATFORM_LINUX_ARM64):
return supposed_platform
# suppose that installed python was built with the right ABI
with open(sys.executable, 'rb') as f:
# see ELF header description in https://man7.org/linux/man-pages/man5/elf.5.html, offsets depend on ElfN size
if int.from_bytes(f.read(4), sys.byteorder) != int.from_bytes(b'\x7fELF', sys.byteorder):
return supposed_platform # ELF magic not found. Use the default platform name from PLATFORM_FROM_NAME
f.seek(18) # seek to e_machine
e_machine = int.from_bytes(f.read(2), sys.byteorder)
if e_machine == 183: # EM_AARCH64, https://github.com/ARM-software/abi-aa/blob/main/aaelf64/aaelf64.rst
supposed_platform = PLATFORM_LINUX_ARM64
elif e_machine == 40: # EM_ARM, https://github.com/ARM-software/abi-aa/blob/main/aaelf32/aaelf32.rst
f.seek(36) # seek to e_flags
e_flags = int.from_bytes(f.read(4), sys.byteorder)
if e_flags & 0x400:
supposed_platform = PLATFORM_LINUX_ARMHF
else:
supposed_platform = PLATFORM_LINUX_ARM32
return supposed_platform
@staticmethod
def get(platform_alias: Optional[str]) -> str:
"""
Get a proper platform name based on PLATFORM_FROM_NAME dict.
"""
if not platform_alias:
raise ValueError('System platform could not be identified.')
if platform_alias in Platforms.UNSUPPORTED_PLATFORMS:
raise ValueError(f'Platform \'{platform_alias}\' is not supported by ESP-IDF.')
if platform_alias == 'any' and CURRENT_PLATFORM:
platform_alias = CURRENT_PLATFORM
platform_name = Platforms.PLATFORM_FROM_NAME.get(platform_alias, None)
if sys.platform == 'linux':
platform_name = Platforms.detect_linux_arm_platform(platform_name)
if not platform_name:
raise ValueError(f'Support for platform \'{platform_alias}\' hasn\'t been added yet.')
return platform_name
@staticmethod
def get_by_filename(file_name: str) -> str:
"""
Guess the right platform based on the file name.
"""
found_alias = ''
for platform_alias in Platforms.PLATFORM_FROM_NAME:
# Find the longest alias which matches with file name to avoid mismatching
if platform_alias in file_name and len(found_alias) < len(platform_alias):
found_alias = platform_alias
return Platforms.get(found_alias)
def parse_platform_arg(platform_str: str) -> str:
"""
Parses platform from input string and checks whether it is a valid platform.
If not, raises SystemExit exception with error message.
"""
try:
platform = Platforms.get(platform_str)
except ValueError as e:
fatal(str(e))
raise SystemExit(1)
return platform
CURRENT_PLATFORM = parse_platform_arg(PYTHON_PLATFORM)
EXPORT_SHELL = 'shell'
EXPORT_KEY_VALUE = 'key-value'
# the older "DigiCert Global Root CA" certificate used with github.com
DIGICERT_ROOT_CA_CERT = """
-----BEGIN CERTIFICATE-----
MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD
QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT
MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j
b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG
9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB
CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97
nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt
43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P
T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4
gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO
BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR
TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw
DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr
hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg
06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF
PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls
YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk
CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=
-----END CERTIFICATE-----
"""
# the newer "DigiCert Global Root G2" certificate used with dl.espressif.com
DIGICERT_ROOT_G2_CERT = """
-----BEGIN CERTIFICATE-----
MIIDjjCCAnagAwIBAgIQAzrx5qcRqaC7KGSxHQn65TANBgkqhkiG9w0BAQsFADBh
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBH
MjAeFw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVT
MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j
b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEcyMIIBIjANBgkqhkiG
9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzfNNNx7a8myaJCtSnX/RrohCgiN9RlUyfuI
2/Ou8jqJkTx65qsGGmvPrC3oXgkkRLpimn7Wo6h+4FR1IAWsULecYxpsMNzaHxmx
1x7e/dfgy5SDN67sH0NO3Xss0r0upS/kqbitOtSZpLYl6ZtrAGCSYP9PIUkY92eQ
q2EGnI/yuum06ZIya7XzV+hdG82MHauVBJVJ8zUtluNJbd134/tJS7SsVQepj5Wz
tCO7TG1F8PapspUwtP1MVYwnSlcUfIKdzXOS0xZKBgyMUNGPHgm+F6HmIcr9g+UQ
vIOlCsRnKPZzFBQ9RnbDhxSJITRNrw9FDKZJobq7nMWxM4MphQIDAQABo0IwQDAP
BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUTiJUIBiV
5uNu5g/6+rkS7QYXjzkwDQYJKoZIhvcNAQELBQADggEBAGBnKJRvDkhj6zHd6mcY
1Yl9PMWLSn/pvtsrF9+wX3N3KjITOYFnQoQj8kVnNeyIv/iPsGEMNKSuIEyExtv4
NeF22d+mQrvHRAiGfzZ0JFrabA0UWTW98kndth/Jsw1HKj2ZL7tcu7XUIOGZX1NG
Fdtom/DzMNU+MeKNhJ7jitralj41E6Vf8PlwUHBHQRFXGU7Aj64GxJUTFy8bJZ91
8rGOmaFvE7FBcf6IKshPECBV1/MUReXgRPTqh5Uykw7+U0b6LJ3/iyK5S9kJRaTe
pLiaWN0bfVKfjllDiIGknibVb63dDcY3fe0Dkhvld1927jyNxF1WW6LZZm6zNTfl
MrY=
-----END CERTIFICATE-----
"""
DL_CERT_DICT = {'dl.espressif.com': DIGICERT_ROOT_G2_CERT,
'github.com': DIGICERT_ROOT_CA_CERT}
def run_cmd_check_output(cmd: List[str], input_text: Optional[str]=None, extra_paths: Optional[List[str]]=None) -> bytes:
"""
Runs command and checks output for exceptions. If AttributeError or TypeError occurs, function re-runs the process.
If return code was not 0, subprocess.CalledProcessError is raised, otherwise, the original error is masked.
Returns both stdout and stderr of the run command.
"""
# 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:
input_bytes = None
if input_text:
input_bytes = input_text.encode()
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, input=input_bytes)
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_bytes)
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: List[str]) -> List[str]:
"""
Converts / (linux) to \\ (Windows) if called under win32 platform.
"""
if sys.platform == 'win32':
paths_list = [p.replace('/', os.path.sep) if os.path.sep in p else p for p in paths_list]
return paths_list
def get_env_for_extra_paths(extra_paths: List[str]) -> Dict[str, str]:
"""
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') # type: ignore
else:
env_arg['PATH'] = new_path
return env_arg
def get_file_size_sha256(filename: str, block_size: int=65536) -> Tuple[int, str]:
"""
Gets file size and its sha256.
"""
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: int, block_size: int, total_size: int) -> None:
"""
Prints progress (count * block_size * 100 / total_size) to stdout.
"""
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: str) -> None:
"""
Makes directory in given path.
Suppresses error when directory is already created or path is a path to file.
"""
try:
os.makedirs(path)
except OSError as exc:
if exc.errno != errno.EEXIST or not os.path.isdir(path):
raise
def unpack(filename: str, destination: str) -> None:
"""
Extracts file specified by filename into destination depending on its type.
"""
info(f'Extracting {filename} to {destination}')
if filename.endswith(('.tar.gz', '.tgz')):
archive_obj: Union[TarFile, ZipFile] = tarfile.open(filename, 'r:gz')
elif filename.endswith(('.tar.xz')):
archive_obj = tarfile.open(filename, 'r:xz')
elif filename.endswith(('.tar.bz2')):
archive_obj = tarfile.open(filename, 'r:bz2')
elif filename.endswith('zip'):
archive_obj = 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)
# ZipFile on Unix systems does not preserve file permissions while extracting it
# We need to reset the permissions afterward
if sys.platform != 'win32' and filename.endswith('zip') and isinstance(archive_obj, ZipFile):
for file_info in archive_obj.infolist():
extracted_file = os.path.join(destination, file_info.filename)
extracted_permissions = file_info.external_attr >> 16 & 0o777 # Extract Unix permissions
if os.path.exists(extracted_file):
os.chmod(extracted_file, extracted_permissions)
def splittype(url: str) -> Tuple[Optional[str], str]:
"""
Splits given url into its type (e.g. https, file) and the rest.
"""
match = re.match('([^/:]+):(.*)', url, re.DOTALL)
if match:
scheme, data = match.groups()
return scheme.lower(), data
return None, url
def urlretrieve_ctx(url: str,
filename: str,
reporthook: Optional[Callable[[int, int, int], None]]=None,
data: Optional[bytes]=None,
context: Optional[SSLContext]=None) -> Tuple[str, addinfourl]:
"""
Retrieve data from given URL. An alternative version of urlretrieve which takes SSL context as an argument.
"""
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: # type: ignore
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
def download(url: str, destination: str) -> Union[None, Exception]:
"""
Download from given url and save into given destination.
"""
info(f'Downloading {url}')
info(f'Destination: {destination}')
try:
for site, cert in DL_CERT_DICT.items():
# For dl.espressif.com and github.com, add the DigiCert root certificate.
# This works around the issue with outdated certificate stores in some installations.
if site in url:
ctx = ssl.create_default_context()
ctx.load_verify_locations(cadata=cert)
break
else:
ctx = None
urlretrieve_ctx(url, destination, report_progress if not g.non_interactive else None, context=ctx)
sys.stdout.write('\rDone\n')
return None
except Exception as e:
# urlretrieve could throw different exceptions, e.g. IOError when the server is down
return e
finally:
sys.stdout.flush()
def rename_with_retry(path_from: str, path_to: str) -> None:
"""
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
"""
retry_count = 20 if sys.platform.startswith('win') else 1
for retry in range(retry_count):
try:
os.rename(path_from, path_to)
return
except OSError:
msg = f'Rename {path_from} to {path_to} failed'
if retry == retry_count - 1:
fatal(f'{msg}. Antivirus software might be causing this. Disabling it temporarily could solve the issue.')
raise
warn(f'{msg}, retrying...')
# Sleep before the next try in order to pass the antivirus check on Windows
time.sleep(0.5)
def do_strip_container_dirs(path: str, levels: int) -> None:
"""
The number of top directory levels specified by levels argument will be removed when extracting.
E.g. if levels=2, archive path a/b/c/d.txt will be extracted as c/d.txt.
"""
assert levels > 0
# move the original directory out of the way (add a .tmp suffix)
tmp_path = f'{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(f'at level {level}, expected 1 entry, got {contents}')
base_path = os.path.join(base_path, contents[0])
if not os.path.isdir(base_path):
raise RuntimeError(f'at level {level}, {contents[0]} is not a directory')
# 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 ToolNotFoundError(RuntimeError):
"""
Raise when the tool is not found (not present in the paths etc.).
"""
pass
class ToolExecError(RuntimeError):
"""
Raise when the tool returns with a non-zero exit code.
"""
pass
class ToolBinaryError(RuntimeError):
""""
Raise when an error occurred when running any version of the tool.
"""
pass
class IDFToolDownload(object):
"""
Structure to store all the relevant information about particular download.
"""
def __init__(self, platform_name: str, url: str, size: int, sha256: str, rename_dist: str) -> None:
self.platform_name = platform_name
self.url = url
self.size = size
self.sha256 = sha256
self.rename_dist = rename_dist
@functools.total_ordering
class IDFToolVersion(object):
"""
Used for storing information about version; status (recommended, supported, deprecated)
and easy way of comparing different versions. Also allows platform compatibility check
and getting right download for given platform, if available.
"""
STATUS_RECOMMENDED = 'recommended'
STATUS_SUPPORTED = 'supported'
STATUS_DEPRECATED = 'deprecated'
STATUS_VALUES = [STATUS_RECOMMENDED, STATUS_SUPPORTED, STATUS_DEPRECATED]
def __init__(self, version: str, status: str) -> None:
self.version = version
self.status = status
self.downloads: OrderedDict[str, IDFToolDownload] = OrderedDict()
self.latest = False
def __lt__(self, other: 'IDFToolVersion') -> bool:
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: object) -> bool:
if not isinstance(other, IDFToolVersion):
return NotImplemented
return self.status == other.status and self.version == other.version
def add_download(self, platform_name: str, url: str, size: int, sha256: str, rename_dist: str = '') -> None:
"""
Add download entry of type IDFToolDownload into self.downloads.
"""
self.downloads[platform_name] = IDFToolDownload(platform_name, url, size, sha256, rename_dist)
def get_download_for_platform(self, platform_name: Optional[str]) -> Optional[IDFToolDownload]:
"""
Get download for given platform if usable download already exists.
"""
try:
platform_name = Platforms.get(platform_name)
if platform_name in self.downloads.keys():
return self.downloads[platform_name]
# exception can be omitted, as not detected platform is handled without err message
except ValueError:
pass
if 'any' in self.downloads.keys():
return self.downloads['any']
return None
def compatible_with_platform(self, platform_name: Optional[str] = PYTHON_PLATFORM) -> bool:
"""
Check whether this version is compatible with given platform name.
"""
return self.get_download_for_platform(platform_name) is not None
def get_supported_platforms(self) -> Set[str]:
"""
Get all platforms for which this version has a valid download record.
"""
return set(self.downloads.keys())
IDFToolOptions = namedtuple('IDFToolOptions', [
'version_cmd',
'version_regex',
'version_regex_replace',
'is_executable',
'export_paths',
'export_vars',
'install',
'info_url',
'license',
'strip_container_dirs',
'supported_targets'])
class IDFTool(object):
"""
Used to store info about IDF tools from tools.json file in a Python-accesible form.
The term "IDF tool" is used for e.g. CMake, ninja, QUEMU and toolchains.
"""
# possible values of 'install' field
INSTALL_ALWAYS = 'always'
INSTALL_ON_REQUEST = 'on_request'
INSTALL_NEVER = 'never'
def __init__(self, name: str,
description: str,
install: str,
info_url: str,
license: str,
version_cmd: List[str],
version_regex: str,
supported_targets: List[str],
version_regex_replace: Optional[str] = None,
strip_container_dirs: int = 0,
is_executable: bool = True) -> None:
self.name = name
self.description = description
self.drop_versions()
self.version_in_path: Optional[str] = None
self.versions_installed: List[str] = []
if version_regex_replace is None:
version_regex_replace = VERSION_REGEX_REPLACE_DEFAULT
self.options = IDFToolOptions(version_cmd, version_regex, version_regex_replace, is_executable,
[], OrderedDict(), install, info_url, license, strip_container_dirs, supported_targets) # type: ignore
self.platform_overrides: List[Dict[str, str]] = []
self._platform = CURRENT_PLATFORM
self._update_current_options()
self.is_executable = is_executable
def copy_for_platform(self, platform: str) -> 'IDFTool':
"""
Copy the IDFTool record in respect to given platform (e.g. apply platform overrides).
"""
result = copy.deepcopy(self)
result._platform = platform
result._update_current_options()
return result
def _update_current_options(self) -> None:
"""
Update current options by platform overrides, if applicable for current platform.
"""
self._current_options = IDFToolOptions(*self.options)
for override in self.platform_overrides:
if self._platform and self._platform not in override['platforms']:
continue
override_dict = override.copy()
del override_dict['platforms']
self._current_options = self._current_options._replace(**override_dict) # type: ignore
def drop_versions(self) -> None:
"""
Clear self.versions dictionary.
"""
self.versions: Dict[str, IDFToolVersion] = OrderedDict()
def add_version(self, version: IDFToolVersion) -> None:
"""
Add new IDFVersion to self.versions.
"""
assert type(version) is IDFToolVersion
self.versions[version.version] = version
def get_path(self) -> str:
"""
Returns path where the tool is installed.
"""
return os.path.join(g.idf_tools_path, 'tools', self.name)
def get_path_for_version(self, version: str) -> str:
"""
Returns path for the tool of given version.
"""
assert version in self.versions
return os.path.join(self.get_path(), version)
def get_export_paths(self, version: str) -> List[str]:
"""
Returns a list of paths that need to be exported.
"""
tool_path = self.get_path_for_version(version)
return [os.path.join(tool_path, *p) for p in self._current_options.export_paths] # type: ignore
def get_export_vars(self, version: str) -> Dict[str, 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(): # type: ignore
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]
old_v = os.environ.get(k)
if old_v is None or old_v != v_repl:
result[k] = v_repl
return result
def get_version(self, extra_paths: Optional[List[str]] = None, executable_path: Optional[str] = None) -> str:
"""
Execute the tool, optionally prepending extra_paths to PATH,
extract the version string and return it as a result.
Raises ToolNotFoundError 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 # type: ignore
if executable_path:
cmd[0] = executable_path
if not cmd[0]:
# There is no command available, so return early. It seems that
# within some very strange context empty [''] may actually execute
# something https://github.com/espressif/esp-idf/issues/11880
raise ToolNotFoundError(f'Tool {self.name} not found')
try:
version_cmd_result = run_cmd_check_output(cmd, None, extra_paths)
except OSError as e:
# tool is not on the path
raise ToolNotFoundError(f'Tool {self.name} not found with error: {e}')
except subprocess.CalledProcessError as e:
raise ToolExecError(f'non-zero exit code ({e.returncode}) with message: {e.stderr.decode("utf-8",errors="ignore")}') # type: ignore
in_str = version_cmd_result.decode('utf-8')
match = re.search(self._current_options.version_regex, in_str) # type: ignore
if not match:
return UNKNOWN_VERSION
return re.sub(self._current_options.version_regex, self._current_options.version_regex_replace, match.group(0)) # type: ignore
def check_binary_valid(self, version: str) -> bool:
if not self.is_executable:
return True
try:
ver_str = self.get_version(self.get_export_paths(version))
except (ToolNotFoundError, ToolExecError) as e:
fatal(f'tool {self.name} version {version} is installed, but getting error: {e}')
return False
if ver_str != version:
# just print, state is still valid
warn(f'tool {self.name} version {version} is installed, but reporting version {ver_str}')
return True
def check_version(self, executable_path: Optional[str]) -> bool:
"""
Check if tool's version from executable path is in self.version dictionary.
"""
version = self.get_version(executable_path=executable_path)
return version in self.versions
def get_install_type(self) -> Callable[[str], None]:
"""
Returns whether the tools are installed always, on request or never.
"""
return self._current_options.install # type: ignore
def get_supported_targets(self) -> List[str]:
"""
Returns list of supported targets with current options.
"""
return self._current_options.supported_targets # type: ignore
def is_supported_for_any_of_targets(self, targets: List[str]) -> bool:
"""
Checks whether the tool is suitable for at least one of the specified targets.
"""
supported_targets = self.get_supported_targets()
return (any(item in targets for item in supported_targets) or supported_targets == ['all'])
def compatible_with_platform(self) -> bool:
"""
Checks whether this tool (any version) is compatible with the platform.
"""
return any([v.compatible_with_platform() for v in self.versions.values()])
def get_supported_platforms(self) -> Set[str]:
"""
Return set of platforms that are supported by at least one version of the tool.
"""
result = set()
for v in self.versions.values():
result.update(v.get_supported_platforms())
return result
def get_recommended_version(self) -> Optional[str]:
"""
Get all recommended versions of the tool. If more versions are recommended, highest version is returned.
"""
recommended_versions = [k for k, v in self.versions.items()