Skip to content

Commit 15de207

Browse files
committed
Better error handling for bootstrap file downloads.
Remove the temp files if something goes wrong.
1 parent 18dafe8 commit 15de207

File tree

1 file changed

+20
-14
lines changed

1 file changed

+20
-14
lines changed

src/bootstrap/bootstrap.py

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -21,17 +21,23 @@
2121

2222
def get(url, path, verbose=False):
2323
sha_url = url + ".sha256"
24-
temp_file = tempfile.NamedTemporaryFile(delete=False)
25-
temp_path = temp_file.name
26-
sha_file = tempfile.NamedTemporaryFile(suffix=".sha256", delete=True)
27-
sha_path = sha_file.name
28-
download(sha_path, sha_url, verbose)
29-
download(temp_path, url, verbose)
30-
verify(sha_path, temp_path, verbose)
31-
sha_file.close()
32-
print("moving " + temp_path + " to " + path)
33-
shutil.move(temp_path, path)
34-
temp_file.close()
24+
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
25+
temp_path = temp_file.name
26+
with tempfile.NamedTemporaryFile(suffix=".sha256", delete=False) as sha_file:
27+
sha_path = sha_file.name
28+
29+
try:
30+
download(sha_path, sha_url, verbose)
31+
download(temp_path, url, verbose)
32+
verify(temp_path, sha_path, verbose)
33+
print("moving " + temp_path + " to " + path)
34+
shutil.move(temp_path, path)
35+
finally:
36+
print("removing " + sha_path)
37+
os.unlink(sha_path)
38+
if os.path.isfile(temp_path):
39+
print("removing " + temp_path)
40+
os.unlink(temp_path)
3541

3642

3743
def download(path, url, verbose):
@@ -46,9 +52,9 @@ def download(path, url, verbose):
4652
run(["curl", "-o", path, url], verbose=verbose)
4753

4854

49-
def verify(sha_path, temp_path, verbose):
50-
print("verifying " + temp_path)
51-
with open(temp_path, "rb") as f:
55+
def verify(path, sha_path, verbose):
56+
print("verifying " + path)
57+
with open(path, "rb") as f:
5258
found = hashlib.sha256(f.read()).hexdigest()
5359
with open(sha_path, "r") as f:
5460
expected, _ = f.readline().split()

0 commit comments

Comments
 (0)