25
25
from mongodl import LOGGER as DL_LOGGER
26
26
from mongodl import (
27
27
SSL_CONTEXT ,
28
+ Cache ,
28
29
DownloadRetrier ,
29
30
ExpandResult ,
30
31
_expand_archive ,
32
+ default_cache_dir ,
31
33
infer_arch ,
32
34
)
33
35
@@ -40,7 +42,7 @@ def _get_latest_version():
40
42
url = "https://api.github.com/repos/mongodb-js/mongosh/releases"
41
43
req = urllib .request .Request (url , headers = headers )
42
44
try :
43
- resp = urllib .request .urlopen (req , context = SSL_CONTEXT )
45
+ resp = urllib .request .urlopen (req , context = SSL_CONTEXT , timeout = 30 )
44
46
except Exception :
45
47
return _get_latest_version_git ()
46
48
@@ -73,6 +75,7 @@ def _get_latest_version_git():
73
75
74
76
75
77
def _download (
78
+ cache : Cache ,
76
79
out_dir : Path ,
77
80
version : str ,
78
81
target : str ,
@@ -108,24 +111,15 @@ def _download(
108
111
if no_download :
109
112
return ExpandResult .Okay
110
113
111
- req = urllib .request .Request (dl_url )
112
114
retrier = DownloadRetrier (retries )
113
115
while True :
114
116
try :
115
- resp = urllib .request .urlopen (req )
116
- with tempfile .NamedTemporaryFile (suffix = suffix , delete = False ) as fp :
117
- four_mebibytes = 1024 * 1024 * 4
118
- buf = resp .read (four_mebibytes )
119
- while buf :
120
- fp .write (buf )
121
- buf = resp .read (four_mebibytes )
122
- fp .close ()
123
- resp = _expand_archive (
124
- Path (fp .name ), out_dir , pattern , strip_components , test = test
125
- )
126
- os .remove (fp .name )
127
- return resp
128
- except Exception :
117
+ cached = cache .download_file (dl_url ).path
118
+ return _expand_archive (
119
+ cached , out_dir , pattern , strip_components , test = test
120
+ )
121
+ except Exception as e :
122
+ LOGGER .exception (e )
129
123
if not retrier .retry ():
130
124
raise
131
125
@@ -140,6 +134,12 @@ def main(argv=None):
140
134
parser .add_argument (
141
135
"--quiet" , "-q" , action = "store_true" , help = "Whether to log at the WARNING level"
142
136
)
137
+ parser .add_argument (
138
+ "--cache-dir" ,
139
+ type = Path ,
140
+ default = default_cache_dir (),
141
+ help = "Directory where download caches and metadata will be stored" ,
142
+ )
143
143
dl_grp = parser .add_argument_group (
144
144
"Download arguments" ,
145
145
description = "Select what to download and extract. "
@@ -220,7 +220,10 @@ def main(argv=None):
220
220
elif args .quiet :
221
221
LOGGER .setLevel (logging .WARNING )
222
222
DL_LOGGER .setLevel (logging .WARNING )
223
+
224
+ cache = Cache .open_in (args .cache_dir )
223
225
result = _download (
226
+ cache ,
224
227
out ,
225
228
version = args .version ,
226
229
target = target ,
0 commit comments