77import sys
88import urllib .request
99from urllib .parse import urljoin
10+ from urllib .error import HTTPError
1011import json
1112import hashlib
1213import logging
1314
1415INDEX_URL = os .getenv ("ASDF_ZIG_INDEX_URL" , "https://ziglang.org/download/index.json" )
1516HTTP_TIMEOUT = int (os .getenv ("ASDF_ZIG_HTTP_TIMEOUT" , "30" ))
17+ USER_AGENT = "asdf-zig (https://github.com/zigcc/asdf-zig)"
1618
1719# https://github.com/mlugg/setup-zig/blob/main/mirrors.json
1820# If any of these mirrors are down, please open an issue!
3234 "arm64" : "aarch64" ,
3335}
3436
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 )
3552
3653def 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 )
4357
4458
45- def all_versions (index = fetch_index ()):
59+ def all_versions ():
60+ index = fetch_index ()
4661 versions = [k for k in index .keys () if k != "master" ]
4762 versions .sort (key = lambda v : tuple (map (int , v .split ("." ))))
4863 return versions
@@ -52,10 +67,7 @@ def download_and_check(url, out_file, expected_shasum, total_size):
5267 logging .info (f"Begin download tarball({ total_size } ) from { url } to { out_file } ..." )
5368 chunk_size = 1024 * 1024 # 1M chunks
5469 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 :
5971 read_size = 0
6072 with open (out_file , "wb" ) as f :
6173 while True :
@@ -113,7 +125,7 @@ def download(version, out_file):
113125
114126
115127def main (args ):
116- command = args [0 ] if args else "default "
128+ command = args [0 ] if args else "all-versions "
117129 if command == "all-versions" :
118130 versions = all_versions ()
119131 print (" " .join (versions ))
0 commit comments