Debian Codegraph @

contrib/packaging/hgpackaging/downloads.py

raw
1 # downloads.py - Code for downloading dependencies.
2 #
3 # Copyright 2019 Gregory Szorc <[email protected]>
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7
8 # no-check-code because Python 3 native.
9
10 import gzip
11 import hashlib
12 import pathlib
13 import typing
14 import urllib.request
15
16
17 DOWNLOADS = {
18 'gettext': {
19 'url': 'https://www.mercurial-scm.org/release/windows/gettext-0.14.4-bin.zip',
20 'size': 1606131,
21 'sha256': '60b9ef26bc5cceef036f0424e542106cf158352b2677f43a01affd6d82a1d641',
22 'version': '0.14.4',
23 },
24 'gettext-dep': {
25 'url': 'https://www.mercurial-scm.org/release/windows/gettext-0.14.4-dep.zip',
26 'size': 715086,
27 'sha256': '411f94974492fd2ecf52590cb05b1023530aec67e64154a88b1e4ebcd9c28588',
28 },
29 }
30
31
32 def hash_path(p: pathlib.Path):
33 h = hashlib.sha256()
34
35 with p.open('rb') as fh:
36 while True:
37 chunk = fh.read(65536)
38 if not chunk:
39 break
40
41 h.update(chunk)
42
43 return h.hexdigest()
44
45
46 class IntegrityError(Exception):
47 """Represents an integrity error when downloading a URL."""
48
49
50 def secure_download_stream(url, size, sha256):
51 """Securely download a URL to a stream of chunks.
52
53 If the integrity of the download fails, an IntegrityError is
54 raised.
55 """
56 h = hashlib.sha256()
57 length = 0
58
59 with urllib.request.urlopen(url) as fh:
60 if (
61 not url.endswith('.gz')
62 and fh.info().get('Content-Encoding') == 'gzip'
63 ):
64 fh = gzip.GzipFile(fileobj=fh)
65
66 while True:
67 chunk = fh.read(65536)
68 if not chunk:
69 break
70
71 h.update(chunk)
72 length += len(chunk)
73
74 yield chunk
75
76 digest = h.hexdigest()
77
78 if length != size:
79 raise IntegrityError(
80 'size mismatch on %s: wanted %d; got %d' % (url, size, length)
81 )
82
83 if digest != sha256:
84 raise IntegrityError(
85 'sha256 mismatch on %s: wanted %s; got %s' % (url, sha256, digest)
86 )
87
88
89 def download_to_path(url: str, path: pathlib.Path, size: int, sha256: str):
90 """Download a URL to a filesystem path, possibly with verification."""
91
92 # We download to a temporary file and rename at the end so there's
93 # no chance of the final file being partially written or containing
94 # bad data.
95 print('downloading %s to %s' % (url, path))
96
97 if path.exists():
98 good = True
99
100 if path.stat().st_size != size:
101 print('existing file size is wrong; removing')
102 good = False
103
104 if good:
105 if hash_path(path) != sha256:
106 print('existing file hash is wrong; removing')
107 good = False
108
109 if good:
110 print('%s exists and passes integrity checks' % path)
111 return
112
113 path.unlink()
114
115 tmp = path.with_name('%s.tmp' % path.name)
116
117 try:
118 with tmp.open('wb') as fh:
119 for chunk in secure_download_stream(url, size, sha256):
120 fh.write(chunk)
121 except IntegrityError:
122 tmp.unlink()
123 raise
124
125 tmp.rename(path)
126 print('successfully downloaded %s' % url)
127
128
129 def download_entry(
130 name: str, dest_path: pathlib.Path, local_name=None
131 ) -> tuple[pathlib.Path, dict[str, typing.Union[str, int]]]:
132 entry = DOWNLOADS[name]
133
134 url = entry['url']
135
136 local_name = local_name or url[url.rindex('/') + 1 :]
137
138 local_path = dest_path / local_name
139 download_to_path(url, local_path, entry['size'], entry['sha256'])
140
141 return local_path, entry