Skip to content

Commit

Permalink
Feat(download.rs): Added Downloading Bar
Browse files Browse the repository at this point in the history
  • Loading branch information
WillKirkmanM committed Apr 29, 2023
1 parent 7e8cca7 commit 7648f7e
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion src/download.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,16 @@ use std::error::Error;
use std::fs::File;
use std::io;
use std::path::Path;
use std::thread;
use std::time::Duration;
use std::{cmp::min, fmt::Write};


use reqwest::Client;
use flate2::read::GzDecoder;
use tar::Archive;
use tokio::fs;
use indicatif::{ProgressBar, ProgressState, ProgressStyle};

use crate::get_path;

Expand All @@ -18,13 +23,33 @@ pub async fn download_environment(id: String) -> Result<(), Box<dyn Error>> {
let download_path = format!("{}{}", base_path, environment_path);

let client = Client::new();
let response = client.get(&download_url).send().await?;

let response = client.get(download_url).send().await?;

if response.status().is_success() {
let language_path = Path::new(&download_path).parent().unwrap().to_str().unwrap();
fs::create_dir_all(language_path).await?;

let mut file = File::create(&download_path)?;

let mut downloaded = 0;
let total_size = response.content_length().unwrap();

let pb = ProgressBar::new(total_size);
pb.set_style(ProgressStyle::with_template("{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({eta})")
.unwrap()
.with_key("eta", |state: &ProgressState, w: &mut dyn Write| write!(w, "{:.1}s", state.eta().as_secs_f64()).unwrap())
.progress_chars("#>-"));

while downloaded < total_size {
let new = min(downloaded + 223211, total_size);
downloaded = new;
pb.set_position(new);
thread::sleep(Duration::from_millis(12));
}

pb.finish_with_message("downloaded");

let content = response.bytes().await?;

io::copy(&mut content.as_ref(), &mut file)?;
Expand All @@ -37,6 +62,8 @@ pub async fn download_environment(id: String) -> Result<(), Box<dyn Error>> {

archive.unpack(&unzip_path)?;
fs::remove_file(&download_path).await?;

println!("Installed {}! Run it with: sandbox --new {}", id, id)
}
Ok(())
}
Expand Down

0 comments on commit 7648f7e

Please sign in to comment.