|
1 | 1 | from os.path import basename, dirname, exists, isdir, isfile, join, realpath, split |
2 | 2 | import glob |
3 | | - |
4 | 3 | import hashlib |
| 4 | +import json |
5 | 5 | from re import match |
6 | 6 |
|
7 | 7 | import sh |
@@ -59,6 +59,21 @@ class Recipe(metaclass=RecipeMeta): |
59 | 59 | if you want. |
60 | 60 | ''' |
61 | 61 |
|
| 62 | + _download_headers = None |
| 63 | + '''Add additional headers used when downloading the package, typically |
| 64 | + for authorization purposes. |
| 65 | +
|
| 66 | + Specified as an array of tuples: |
| 67 | + [("header1", "foo"), ("header2", "bar")] |
| 68 | +
|
| 69 | + When specifying as an environment variable (DOWNLOAD_HEADER_my-package-name), use a JSON formatted fragement: |
| 70 | + [["header1","foo"],["header2", "bar"]] |
| 71 | +
|
| 72 | + For example, when downloading from a private |
| 73 | + github repository, you can specify the following: |
| 74 | + [('Authorization', 'token <your personal access token>'), ('Accept', 'application/vnd.github+json')] |
| 75 | + ''' |
| 76 | + |
62 | 77 | _version = None |
63 | 78 | '''A string giving the version of the software the recipe describes, |
64 | 79 | e.g. ``2.0.3`` or ``master``.''' |
@@ -170,6 +185,18 @@ def versioned_url(self): |
170 | 185 | return None |
171 | 186 | return self.url.format(version=self.version) |
172 | 187 |
|
| 188 | + @property |
| 189 | + def download_headers(self): |
| 190 | + key = "DOWNLOAD_HEADERS_" + self.name |
| 191 | + env_headers = environ.get(key) |
| 192 | + if env_headers: |
| 193 | + try: |
| 194 | + return [tuple(h) for h in json.loads(env_headers)] |
| 195 | + except Exception as ex: |
| 196 | + raise ValueError(f'Invalid Download headers for {key} - must be JSON formatted as [["header1","foo"],["header2","bar"]]: {ex}') |
| 197 | + |
| 198 | + return environ.get(key, self._download_headers) |
| 199 | + |
173 | 200 | def download_file(self, url, target, cwd=None): |
174 | 201 | """ |
175 | 202 | (internal) Download an ``url`` to a ``target``. |
@@ -205,6 +232,8 @@ def report_hook(index, blksize, size): |
205 | 232 | # jqueryui.com returns a 403 w/ the default user agent |
206 | 233 | # Mozilla/5.0 does not handle redirection for liblzma |
207 | 234 | url_opener.addheaders = [('User-agent', 'Wget/1.0')] |
| 235 | + if self.download_headers: |
| 236 | + url_opener.addheaders += self.download_headers |
208 | 237 | urlretrieve(url, target, report_hook) |
209 | 238 | except OSError as e: |
210 | 239 | attempts += 1 |
|
0 commit comments