Skip to content

Commit 96d13bb

Browse files
PilnyTomasme-no-dev
authored andcommitted
Updated get.py with ability to verify extracted files and skip if ok
1 parent 6f7a1ca commit 96d13bb

File tree

1 file changed

+107
-18
lines changed

1 file changed

+107
-18
lines changed

tools/get.py

Lines changed: 107 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import tarfile
2323
import zipfile
2424
import re
25+
import time
2526

2627
if sys.version_info[0] == 3:
2728
from urllib.request import urlretrieve
@@ -58,44 +59,131 @@ def mkdir_p(path):
5859
if exc.errno != errno.EEXIST or not os.path.isdir(path):
5960
raise
6061

61-
def report_progress(count, blockSize, totalSize):
62+
def report_progress(block_count, block_size, total_size):
63+
downloaded_size = block_count * block_size
64+
current_speed = downloaded_size / (time.time() - start_time)
65+
time_elapsed = time.time() - start_time
66+
6267
if sys.stdout.isatty():
63-
if totalSize > 0:
64-
percent = int(count*blockSize*100/totalSize)
65-
percent = min(100, percent)
66-
sys.stdout.write("\r%d%%" % percent)
67-
else:
68-
sofar = (count*blockSize) / 1024
69-
if sofar >= 1000:
70-
sofar /= 1024
71-
sys.stdout.write("\r%dMB " % (sofar))
72-
else:
73-
sys.stdout.write("\r%dKB" % (sofar))
68+
if total_size > 0:
69+
percent_complete = min((downloaded_size / total_size) * 100, 100)
70+
sys.stdout.write(f"\rDownloading... {percent_complete:.2f}% - {downloaded_size / 1024 / 1024:.2f} MB downloaded - Elapsed Time: {time_elapsed:.2f} seconds - Speed: {current_speed / 1024 / 1024:.2f} MB/s")
7471
sys.stdout.flush()
7572

73+
def format_time(seconds):
74+
minutes, seconds = divmod(seconds, 60)
75+
return "{:02}:{:05.2f}".format(int(minutes), seconds)
76+
77+
def verify_files(filename, destination, rename_to):
78+
# Set the path of the extracted directory
79+
extracted_dir_path = destination
80+
81+
t1 = time.time()
82+
83+
if filename.endswith(".zip"):
84+
try:
85+
with zipfile.ZipFile(filename, 'r') as archive:
86+
first_dir = archive.namelist()[0].split('/')[0]
87+
total_files = len(archive.namelist())
88+
for i, zipped_file in enumerate(archive.namelist(), 1):
89+
local_path = os.path.join(extracted_dir_path, zipped_file.replace(first_dir, rename_to, 1))
90+
if not os.path.exists(local_path):
91+
print(f'\nMissing {zipped_file} on location: {extracted_dir_path}')
92+
print(f"\nVerification failed; aborted in {format_time(time.time() - t1)}")
93+
return False
94+
#print(f'\rVerification progress: {i/total_files*100:.2f}%', end='')
95+
if sys.stdout.isatty():
96+
sys.stdout.write(f'\rVerification progress: {i/total_files*100:.2f}%')
97+
sys.stdout.flush()
98+
except zipfile.BadZipFile:
99+
print(f"\nVerification failed; aborted in {format_time(time.time() - t1)}")
100+
return False
101+
elif filename.endswith(".tar.gz"):
102+
try:
103+
with tarfile.open(filename, 'r:gz') as archive:
104+
first_dir = archive.getnames()[0].split('/')[0]
105+
total_files = len(archive.getnames())
106+
for i, zipped_file in enumerate(archive.getnames(), 1):
107+
local_path = os.path.join(extracted_dir_path, zipped_file.replace(first_dir, rename_to, 1))
108+
if not os.path.exists(local_path):
109+
print(f'\nMissing {zipped_file} on location: {extracted_dir_path}')
110+
print(f"\nVerification failed; aborted in {format_time(time.time() - t1)}")
111+
return False
112+
#print(f'\rVerification progress: {i/total_files*100:.2f}%', end='')
113+
if sys.stdout.isatty():
114+
sys.stdout.write(f'\rVerification progress: {i/total_files*100:.2f}%')
115+
sys.stdout.flush()
116+
except tarfile.ReadError:
117+
print(f"\nVerification failed; aborted in {format_time(time.time() - t1)}")
118+
return False
119+
elif filename.endswith(".tar.xz"):
120+
try:
121+
with tarfile.open(filename, 'r:xz') as archive:
122+
first_dir = archive.getnames()[0].split('/')[0]
123+
total_files = len(archive.getnames())
124+
for i, zipped_file in enumerate(archive.getnames(), 1):
125+
local_path = os.path.join(extracted_dir_path, zipped_file.replace(first_dir, rename_to, 1))
126+
if not os.path.exists(local_path):
127+
print(f'\nMissing {zipped_file} on location: {extracted_dir_path}')
128+
print(f"\nVerification failed; aborted in {format_time(time.time() - t1)}")
129+
return False
130+
#print(f'\rVerification progress: {i/total_files*100:.2f}%', end='')
131+
if sys.stdout.isatty():
132+
sys.stdout.write(f'\rVerification progress: {i/total_files*100:.2f}%')
133+
sys.stdout.flush()
134+
except tarfile.ReadError:
135+
print(f"\nVerification failed; aborted in {format_time(time.time() - t1)}")
136+
return False
137+
else:
138+
raise NotImplementedError('Unsupported archive type')
139+
140+
if(verobse):
141+
print(f"\nVerification passed; completed in {format_time(time.time() - t1)}")
142+
143+
return True
144+
76145
def unpack(filename, destination):
77146
dirname = ''
78-
print('Extracting {0} ...'.format(os.path.basename(filename)))
79-
sys.stdout.flush()
147+
print(' > Verify... ')
148+
80149
if filename.endswith('tar.gz'):
81150
tfile = tarfile.open(filename, 'r:gz')
82-
tfile.extractall(destination)
83151
dirname = tfile.getnames()[0]
84152
elif filename.endswith('tar.xz'):
85153
tfile = tarfile.open(filename, 'r:xz')
86-
tfile.extractall(destination)
87154
dirname = tfile.getnames()[0]
88155
elif filename.endswith('zip'):
89156
zfile = zipfile.ZipFile(filename)
90-
zfile.extractall(destination)
91157
dirname = zfile.namelist()[0]
92158
else:
93159
raise NotImplementedError('Unsupported archive type')
94160

95-
# a little trick to rename tool directories so they don't contain version number
161+
# A little trick to rename tool directories so they don't contain version number
96162
rename_to = re.match(r'^([a-z][^\-]*\-*)+', dirname).group(0).strip('-')
97163
if rename_to == dirname and dirname.startswith('esp32-arduino-libs-'):
98164
rename_to = 'esp32-arduino-libs'
165+
166+
if(verify_files(filename, destination, rename_to)):
167+
print(" Files ok. Skipping Extraction")
168+
return
169+
else:
170+
print(" Failed. extracting")
171+
172+
if filename.endswith('tar.gz'):
173+
tfile = tarfile.open(filename, 'r:gz')
174+
tfile.extractall(destination)
175+
dirname = tfile.getnames()[0]
176+
elif filename.endswith('tar.xz'):
177+
tfile = tarfile.open(filename, 'r:xz')
178+
tfile.extractall(destination)
179+
dirname = tfile.getnames()[0]
180+
elif filename.endswith('zip'):
181+
zfile = zipfile.ZipFile(filename)
182+
zfile.extractall(destination)
183+
dirname = zfile.namelist()[0]
184+
else:
185+
raise NotImplementedError('Unsupported archive type')
186+
99187
if rename_to != dirname:
100188
print('Renaming {0} to {1} ...'.format(dirname, rename_to))
101189
if os.path.isdir(rename_to):
@@ -225,6 +313,7 @@ def identify_platform():
225313
return arduino_platform_names[sys_name][bits]
226314

227315
if __name__ == '__main__':
316+
verbose = "-v" in sys.argv
228317
is_test = (len(sys.argv) > 1 and sys.argv[1] == '-h')
229318
if is_test:
230319
print('Test run!')

0 commit comments

Comments
 (0)