Downloads a file if it does not exist, optionally checking its SHA-256 hash.
(path, url, digest=None)
| 55 | |
| 56 | |
| 57 | def download_file(path, url, digest=None): |
| 58 | """Downloads a file if it does not exist, optionally checking its SHA-256 hash.""" |
| 59 | path = Path(path) |
| 60 | path.parent.mkdir(parents=True, exist_ok=True) |
| 61 | if not path.exists(): |
| 62 | with urllib.request.urlopen(url) as response, open(path, 'wb') as f: |
| 63 | shutil.copyfileobj(response, f) |
| 64 | if digest is not None: |
| 65 | file_digest = hashlib.sha256(open(path, 'rb').read()).hexdigest() |
| 66 | if digest != file_digest: |
| 67 | raise OSError(f'hash of {path} (url: {url}) failed to validate') |
| 68 | return path |
| 69 | |
| 70 | |
| 71 | @contextmanager |
nothing calls this directly
no outgoing calls
no test coverage detected