| 1 |
#!/usr/bin/python3 |
| 2 |
|
| 3 |
import hashlib |
| 4 |
import json |
| 5 |
import logging |
| 6 |
import shutil |
| 7 |
import datetime |
| 8 |
|
| 9 |
from concurrent.futures import ProcessPoolExecutor as Pool, as_completed |
| 10 |
from pathlib import Path |
| 11 |
from urllib.request import urlopen, Request |
| 12 |
from urllib.parse import urljoin |
| 13 |
|
| 14 |
logger = logging.getLogger() |
| 15 |
|
| 16 |
PARALLEL_DOWNLOADS = 6 |
| 17 |
GITHUB_API_URL = "https://api.github.com/repos/lxml/lxml" |
| 18 |
|
| 19 |
|
| 20 |
def find_github_files(version, api_url=GITHUB_API_URL): |
| 21 |
url = f"{api_url}/releases/tags/lxml-{version}" |
| 22 |
release, _ = read_url(url, accept="application/vnd.github+json", as_json=True) |
| 23 |
|
| 24 |
for asset in release.get('assets', ()): |
| 25 |
yield (asset['browser_download_url'], asset['size'], asset['digest']) |
| 26 |
|
| 27 |
|
| 28 |
def read_url(url, decode=True, accept=None, as_json=False): |
| 29 |
if accept: |
| 30 |
request = Request(url, headers={'Accept': accept}) |
| 31 |
else: |
| 32 |
request = Request(url) |
| 33 |
|
| 34 |
with urlopen(request) as res: |
| 35 |
charset = _find_content_encoding(res) |
| 36 |
content_type = res.headers.get('Content-Type') |
| 37 |
data = res.read() |
| 38 |
|
| 39 |
if decode: |
| 40 |
data = data.decode(charset) |
| 41 |
if as_json: |
| 42 |
data = json.loads(data) |
| 43 |
return data, content_type |
| 44 |
|
| 45 |
|
| 46 |
def _find_content_encoding(response, default='iso8859-1'): |
| 47 |
from email.message import Message |
| 48 |
content_type = response.headers.get('Content-Type') |
| 49 |
if content_type: |
| 50 |
msg = Message() |
| 51 |
msg.add_header('Content-Type', content_type) |
| 52 |
charset = msg.get_content_charset(default) |
| 53 |
else: |
| 54 |
charset = default |
| 55 |
return charset |
| 56 |
|
| 57 |
|
| 58 |
def download1(wheel_metadata, dest_dir): |
| 59 |
wheel_url, size, digest = wheel_metadata |
| 60 |
wheel_name = wheel_url.rsplit("/", 1)[1] |
| 61 |
file_path = dest_dir / wheel_name |
| 62 |
|
| 63 |
if file_exists(file_path, size=size, digest=digest): |
| 64 |
logger.info(f"Already have {wheel_name}") |
| 65 |
return wheel_name |
| 66 |
|
| 67 |
logger.info(f"Downloading {wheel_url} ...") |
| 68 |
with urlopen(wheel_url) as w: |
| 69 |
temp_file_path = file_path.with_suffix(".tmp") |
| 70 |
try: |
| 71 |
with open(temp_file_path, "wb") as f: |
| 72 |
shutil.copyfileobj(w, f) |
| 73 |
except: |
| 74 |
if temp_file_path.exists(): |
| 75 |
temp_file_path.unlink() |
| 76 |
raise |
| 77 |
else: |
| 78 |
temp_file_path.replace(file_path) |
| 79 |
logger.info(f"Finished downloading {wheel_name}") |
| 80 |
return wheel_name |
| 81 |
|
| 82 |
|
| 83 |
def download(urls, dest_dir, jobs=PARALLEL_DOWNLOADS): |
| 84 |
with Pool(max_workers=jobs) as pool: |
| 85 |
futures = [pool.submit(download1, url, dest_dir) for url in urls] |
| 86 |
try: |
| 87 |
for future in as_completed(futures): |
| 88 |
wheel_name = future.result() |
| 89 |
yield wheel_name |
| 90 |
except KeyboardInterrupt: |
| 91 |
for future in futures: |
| 92 |
future.cancel() |
| 93 |
raise |
| 94 |
|
| 95 |
|
| 96 |
def file_exists(file_path: Path, size=None, digest=None): |
| 97 |
if not file_path.exists(): |
| 98 |
return False |
| 99 |
if size is not None: |
| 100 |
if file_path.stat().st_size != size: |
| 101 |
return False |
| 102 |
if digest is not None: |
| 103 |
hash_alg = 'sha256' |
| 104 |
if ':' in digest: |
| 105 |
hash_alg, _, digest = digest.partition(':') |
| 106 |
with file_path.open(mode='rb') as f: |
| 107 |
file_digest = hashlib.file_digest(f, hash_alg) |
| 108 |
if digest != file_digest.hexdigest(): |
| 109 |
return False |
| 110 |
return True |
| 111 |
|
| 112 |
|
| 113 |
def dedup(it): |
| 114 |
seen = set() |
| 115 |
for value in it: |
| 116 |
if value not in seen: |
| 117 |
seen.add(value) |
| 118 |
yield value |
| 119 |
|
| 120 |
|
| 121 |
def main(*args): |
| 122 |
if not args: |
| 123 |
print("Please pass the version to download") |
| 124 |
return |
| 125 |
|
| 126 |
version = args[0] |
| 127 |
dest_dir = Path("dist") / version |
| 128 |
if not dest_dir.is_dir(): |
| 129 |
dest_dir.mkdir() |
| 130 |
|
| 131 |
start_time = datetime.datetime.now().replace(microsecond=0) |
| 132 |
urls = dedup(find_github_files(version)) |
| 133 |
count = sum(1 for _ in enumerate(download(urls, dest_dir))) |
| 134 |
duration = datetime.datetime.now().replace(microsecond=0) - start_time |
| 135 |
logger.info(f"Downloaded {count} files in {duration}.") |
| 136 |
|
| 137 |
|
| 138 |
if __name__ == "__main__": |
| 139 |
import sys |
| 140 |
logging.basicConfig( |
| 141 |
stream=sys.stderr, |
| 142 |
level=logging.INFO, |
| 143 |
format="%(asctime)-15s %(message)s", |
| 144 |
) |
| 145 |
main(*sys.argv[1:]) |