1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
extern crate curl;
#[macro_use]
extern crate failure;
extern crate dirs;
extern crate flate2;
extern crate fs2;
extern crate hex;
extern crate is_executable;
extern crate siphasher;
extern crate tar;
extern crate zip;
use failure::{Error, ResultExt};
use fs2::FileExt;
use siphasher::sip::SipHasher13;
use std::collections::HashSet;
use std::env;
use std::ffi;
use std::fs;
use std::fs::File;
use std::hash::{Hash, Hasher};
use std::io;
use std::path::{Path, PathBuf};
#[derive(Debug)]
pub struct Cache {
destination: PathBuf,
}
#[derive(Debug)]
pub struct Download {
root: PathBuf,
}
impl Cache {
pub fn new(name: &str) -> Result<Cache, Error> {
let cache_name = format!(".{}", name);
let destination = dirs::cache_dir()
.map(|p| p.join(&cache_name))
.or_else(|| {
let home = dirs::home_dir()?;
Some(home.join(&cache_name))
})
.ok_or_else(|| format_err!("couldn't find your home directory, is $HOME not set?"))?;
if !destination.exists() {
fs::create_dir_all(&destination)?;
}
Ok(Cache::at(&destination))
}
pub fn at(path: &Path) -> Cache {
Cache {
destination: path.to_path_buf(),
}
}
pub fn join(&self, path: &Path) -> PathBuf {
self.destination.join(path)
}
pub fn download(
&self,
install_permitted: bool,
name: &str,
binaries: &[&str],
url: &str,
) -> Result<Option<Download>, Error> {
let dirname = hashed_dirname(url, name);
let destination = self.destination.join(&dirname);
let flock = File::create(self.destination.join(&format!(".{}.lock", dirname)))?;
flock.lock_exclusive()?;
if destination.exists() {
return Ok(Some(Download { root: destination }));
}
if !install_permitted {
return Ok(None);
}
let data = curl(&url).with_context(|_| format!("failed to download from {}", url))?;
let temp = self.destination.join(&format!(".{}", dirname));
drop(fs::remove_dir_all(&temp));
fs::create_dir_all(&temp)?;
if url.ends_with(".tar.gz") {
self.extract_tarball(&data, &temp, binaries)
.with_context(|_| format!("failed to extract tarball from {}", url))?;
} else if url.ends_with(".zip") {
self.extract_zip(&data, &temp, binaries)
.with_context(|_| format!("failed to extract zip from {}", url))?;
} else {
panic!("don't know how to extract {}", url)
}
fs::rename(&temp, &destination)?;
flock.unlock()?;
Ok(Some(Download { root: destination }))
}
pub fn download_artifact(&self, name: &str, url: &str) -> Result<Option<Download>, Error> {
let dirname = hashed_dirname(url, name);
let destination = self.destination.join(&dirname);
if destination.exists() {
return Ok(Some(Download { root: destination }));
}
let data = curl(&url).with_context(|_| format!("failed to download from {}", url))?;
let temp = self.destination.join(&format!(".{}", dirname));
drop(fs::remove_dir_all(&temp));
fs::create_dir_all(&temp)?;
if url.ends_with(".tar.gz") {
self.extract_tarball_all(&data, &temp)
.with_context(|_| format!("failed to extract tarball from {}", url))?;
} else {
panic!("don't know how to extract {}", url)
}
fs::rename(&temp, &destination)?;
Ok(Some(Download { root: destination }))
}
fn extract_tarball_all(&self, tarball: &[u8], dst: &Path) -> Result<(), Error> {
let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(tarball));
for entry in archive.entries()? {
let mut entry = entry?;
let dest = match entry.path()?.file_stem() {
Some(_) => dst.join(entry.path()?.file_name().unwrap()),
_ => continue,
};
entry.unpack(dest)?;
}
Ok(())
}
fn extract_tarball(&self, tarball: &[u8], dst: &Path, binaries: &[&str]) -> Result<(), Error> {
let mut binaries: HashSet<_> = binaries.into_iter().map(ffi::OsStr::new).collect();
let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(tarball));
for entry in archive.entries()? {
let mut entry = entry?;
let dest = match entry.path()?.file_stem() {
Some(f) if binaries.contains(f) => {
binaries.remove(f);
dst.join(entry.path()?.file_name().unwrap())
}
_ => continue,
};
entry.unpack(dest)?;
}
if !binaries.is_empty() {
bail!(
"the tarball was missing expected executables: {}",
binaries
.into_iter()
.map(|s| s.to_string_lossy())
.collect::<Vec<_>>()
.join(", "),
)
}
Ok(())
}
fn extract_zip(&self, zip: &[u8], dst: &Path, binaries: &[&str]) -> Result<(), Error> {
let mut binaries: HashSet<_> = binaries.into_iter().map(ffi::OsStr::new).collect();
let data = io::Cursor::new(zip);
let mut zip = zip::ZipArchive::new(data)?;
for i in 0..zip.len() {
let mut entry = zip.by_index(i).unwrap();
let entry_path = entry.sanitized_name();
match entry_path.file_stem() {
Some(f) if binaries.contains(f) => {
binaries.remove(f);
let mut dest = bin_open_options()
.write(true)
.create_new(true)
.open(dst.join(entry_path.file_name().unwrap()))?;
io::copy(&mut entry, &mut dest)?;
}
_ => continue,
};
}
if !binaries.is_empty() {
bail!(
"the zip was missing expected executables: {}",
binaries
.into_iter()
.map(|s| s.to_string_lossy())
.collect::<Vec<_>>()
.join(", "),
)
}
return Ok(());
#[cfg(unix)]
fn bin_open_options() -> fs::OpenOptions {
use std::os::unix::fs::OpenOptionsExt;
let mut opts = fs::OpenOptions::new();
opts.mode(0o755);
opts
}
#[cfg(not(unix))]
fn bin_open_options() -> fs::OpenOptions {
fs::OpenOptions::new()
}
}
}
impl Download {
pub fn at(path: &Path) -> Download {
Download {
root: path.to_path_buf(),
}
}
pub fn binary(&self, name: &str) -> Result<PathBuf, Error> {
use is_executable::IsExecutable;
let ret = self
.root
.join(name)
.with_extension(env::consts::EXE_EXTENSION);
if !ret.is_file() {
bail!("{} binary does not exist", ret.display());
}
if !ret.is_executable() {
bail!("{} is not executable", ret.display());
}
Ok(ret)
}
pub fn path(&self) -> PathBuf {
self.root.clone()
}
}
fn curl(url: &str) -> Result<Vec<u8>, Error> {
let mut data = Vec::new();
let mut easy = curl::easy::Easy::new();
easy.follow_location(true)?;
easy.url(url)?;
easy.get(true)?;
{
let mut transfer = easy.transfer();
transfer.write_function(|part| {
data.extend_from_slice(part);
Ok(part.len())
})?;
transfer.perform()?;
}
let status_code = easy.response_code()?;
if 200 <= status_code && status_code < 300 {
Ok(data)
} else {
bail!(
"received a bad HTTP status code ({}) when requesting {}",
status_code,
url
)
}
}
fn hashed_dirname(url: &str, name: &str) -> String {
let mut hasher = SipHasher13::new();
url.hash(&mut hasher);
let result = hasher.finish();
let hex = hex::encode(&[
(result >> 0) as u8,
(result >> 8) as u8,
(result >> 16) as u8,
(result >> 24) as u8,
(result >> 32) as u8,
(result >> 40) as u8,
(result >> 48) as u8,
(result >> 56) as u8,
]);
format!("{}-{}", name, hex)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_returns_same_hash_for_same_name_and_url() {
let name = "wasm-pack";
let url = "http://localhost:7878/wasm-pack-v0.6.0.tar.gz";
let first = hashed_dirname(url, name);
let second = hashed_dirname(url, name);
assert!(!first.is_empty());
assert!(!second.is_empty());
assert_eq!(first, second);
}
#[test]
fn it_returns_different_hashes_for_different_urls() {
let name = "wasm-pack";
let url = "http://localhost:7878/wasm-pack-v0.5.1.tar.gz";
let second_url = "http://localhost:7878/wasm-pack-v0.6.0.tar.gz";
let first = hashed_dirname(url, name);
let second = hashed_dirname(second_url, name);
assert_ne!(first, second);
}
#[test]
fn it_returns_cache_dir() {
let name = "wasm-pack";
let cache = Cache::new(name);
let expected = dirs::cache_dir()
.unwrap()
.join(PathBuf::from(".".to_owned() + name));
assert!(cache.is_ok());
assert_eq!(cache.unwrap().destination, expected);
}
#[test]
fn it_returns_destination_if_binary_already_exists() {
use std::fs;
let binary_name = "wasm-pack";
let binaries = vec![binary_name];
let dir = tempfile::TempDir::new().unwrap();
let cache = Cache::at(dir.path());
let url = &format!("{}/{}.tar.gz", "http://localhost:7878", binary_name);
let dirname = hashed_dirname(&url, &binary_name);
let full_path = dir.path().join(dirname);
fs::create_dir_all(full_path).unwrap();
let dl = cache.download(true, binary_name, &binaries, url);
assert!(dl.is_ok());
assert!(dl.unwrap().is_some())
}
}