add Downloader

This commit is contained in:
Adrian Malacoda 2017-10-25 21:37:20 -05:00
parent 3e38dff62d
commit 5cc0e7e178
3 changed files with 37 additions and 6 deletions

4
Cargo.lock generated
View File

@ -1,4 +0,0 @@
[root]
name = "plushie-narwhal"
version = "0.0.1"

View File

@ -2,3 +2,6 @@
name = "plushie-narwhal"
version = "0.0.1"
authors = ["A. Malacoda <malacoda@monarch-pass.net>"]
[dependencies]
reqwest = "0.8.0"

View File

@ -1,10 +1,12 @@
extern crate reqwest;
use std::process::Command;
use std::env;
use std::path::{Path, PathBuf};
use std::fs::canonicalize;
use std::fs::File;
use std::io::Write;
use std::fs::{File, create_dir_all};
use std::io::{Write, copy};
pub fn yarn_install () {
Command::new("yarn").output().expect("failed to execute yarn process");
@ -137,3 +139,33 @@ pub struct ResourceMount {
endpoint: &'static str,
content_type: &'static str
}
pub struct Downloader {
cache: PathBuf
}
impl Downloader {
pub fn new<P: AsRef<Path>>(cache: P) -> Downloader {
Downloader {
cache: cache.as_ref().to_path_buf()
}
}
pub fn get(&self, url: &str) -> PathBuf {
if !self.cache.exists() {
create_dir_all(self.cache.as_path()).expect("failed to create cache directory");
}
let filename = url.get((url.rfind('/').expect("not a valid url")..)).expect("failed to parse filename");
let mut out_path = self.cache.clone();
out_path.push(filename);
if !out_path.exists() {
let mut res = reqwest::get(url).expect("failed to download url");
let mut file = File::open(out_path.as_path()).expect("failed to open file");
copy(&mut res, &mut file).expect("failed to write file");
}
out_path
}
}