7
7
import sys
8
8
import urllib .request
9
9
from urllib .parse import urljoin
10
+ from urllib .error import HTTPError
10
11
import json
11
12
import hashlib
12
13
import logging
13
14
14
15
INDEX_URL = os .getenv ("ASDF_ZIG_INDEX_URL" , "https://ziglang.org/download/index.json" )
15
16
HTTP_TIMEOUT = int (os .getenv ("ASDF_ZIG_HTTP_TIMEOUT" , "30" ))
17
+ USER_AGENT = "asdf-zig (https://github.com/zigcc/asdf-zig)"
16
18
17
19
# https://github.com/mlugg/setup-zig/blob/main/mirrors.json
18
20
# If any of these mirrors are down, please open an issue!
32
34
"arm64" : "aarch64" ,
33
35
}
34
36
37
+ class HTTPAccessError (Exception ):
38
+ def __init__ (self , url , code , reason , body ):
39
+ super ().__init__ (f"{ url } access failed, code:{ code } , reason:{ reason } , body:{ body } " )
40
+ self .url = url
41
+ self .code = code
42
+ self .reason = reason
43
+ self .body = body
44
+
45
+ def http_get (url , timeout = HTTP_TIMEOUT ):
46
+ try :
47
+ req = urllib .request .Request (url , headers = {'User-Agent' : USER_AGENT })
48
+ return urllib .request .urlopen (req , timeout = timeout )
49
+ except HTTPError as e :
50
+ body = e .read ().decode ("utf-8" )
51
+ raise HTTPAccessError (url , e .code , e .reason , body )
35
52
36
53
def fetch_index ():
37
- with urllib .request .urlopen (INDEX_URL , timeout = HTTP_TIMEOUT ) as response :
38
- if response .getcode () == 200 :
39
- body = response .read ().decode ("utf-8" )
40
- return json .loads (body )
41
- else :
42
- raise Exception (f"Fetch index.json error: { response .getcode ()} " )
54
+ with http_get (INDEX_URL ) as response :
55
+ body = response .read ().decode ("utf-8" )
56
+ return json .loads (body )
43
57
44
58
45
- def all_versions (index = fetch_index ()):
59
+ def all_versions ():
60
+ index = fetch_index ()
46
61
versions = [k for k in index .keys () if k != "master" ]
47
62
versions .sort (key = lambda v : tuple (map (int , v .split ("." ))))
48
63
return versions
@@ -52,10 +67,7 @@ def download_and_check(url, out_file, expected_shasum, total_size):
52
67
logging .info (f"Begin download tarball({ total_size } ) from { url } to { out_file } ..." )
53
68
chunk_size = 1024 * 1024 # 1M chunks
54
69
sha256_hash = hashlib .sha256 ()
55
- with urllib .request .urlopen (url , timeout = HTTP_TIMEOUT ) as response :
56
- if response .getcode () != 200 :
57
- raise Exception (f"Fetch index.json error: { response .getcode ()} " )
58
-
70
+ with http_get (url ) as response :
59
71
read_size = 0
60
72
with open (out_file , "wb" ) as f :
61
73
while True :
@@ -113,7 +125,7 @@ def download(version, out_file):
113
125
114
126
115
127
def main (args ):
116
- command = args [0 ] if args else "default "
128
+ command = args [0 ] if args else "all-versions "
117
129
if command == "all-versions" :
118
130
versions = all_versions ()
119
131
print (" " .join (versions ))
0 commit comments