diff --git a/crates/tarball/src/lib.rs b/crates/tarball/src/lib.rs index e80d7f0be..c90002031 100644 --- a/crates/tarball/src/lib.rs +++ b/crates/tarball/src/lib.rs @@ -1,4 +1,8 @@ -use std::{fs::File, io::Write, path::Path}; +use std::{ + fs::{self, File}, + io::{self, Write}, + path::Path, +}; use flate2::read::GzDecoder; use futures_util::StreamExt; @@ -9,9 +13,21 @@ use thiserror::Error; #[non_exhaustive] pub enum TarballError { #[error("network error while downloading `${0}`")] - Network(String), - #[error("filesystem error: `{0}`")] - FileSystem(String), + Network(reqwest::Error), + #[error("io error: `{0}`")] + Io(io::Error), +} + +impl From for TarballError { + fn from(value: io::Error) -> Self { + TarballError::Io(value) + } +} + +impl From for TarballError { + fn from(value: reqwest::Error) -> Self { + TarballError::Network(value) + } } pub async fn download_and_extract( @@ -28,28 +44,21 @@ pub async fn download_and_extract( // For now: .pacquet/fast-querystring/1.0.0 let extract_location = cache_directory.join(name).join(version); - let mut stream = - reqwest::get(url).await.or(Err(TarballError::Network(url.to_owned())))?.bytes_stream(); + let mut stream = reqwest::get(url).await.map_err(TarballError::Network)?.bytes_stream(); - let mut file = File::create(&tarball_location) - .or(Err(TarballError::FileSystem("failed to create file".to_owned()))) - .unwrap(); + let mut file = File::create(&tarball_location).map_err(TarballError::Io)?; while let Some(item) = stream.next().await { - let chunk = - item.map_err(|_| TarballError::Network("error while downloading file".to_owned()))?; - file.write_all(&chunk) - .map_err(|_| TarballError::FileSystem("error while writing to file".to_owned()))?; + let chunk = item.map_err(TarballError::Network)?; + file.write_all(&chunk).map_err(TarballError::Io)?; } - let tar_gz = File::open(&tarball_location).unwrap(); + let tar_gz = File::open(&tarball_location)?; let tar = GzDecoder::new(tar_gz); let mut archive = Archive::new(tar); - archive.unpack(&extract_location).unwrap(); + archive.unpack(&extract_location)?; - std::fs::remove_file(&tarball_location) - .or(Err(TarballError::FileSystem("removing tarball failed".to_owned()))) - .unwrap(); + std::fs::remove_file(&tarball_location).map_err(TarballError::Io)?; // Tarball contains the source code of the package inside a "package" folder // We need to move the contents of this folder to the appropriate node_modules folder. @@ -59,10 +68,10 @@ pub async fn download_and_extract( let node_modules_path = node_modules.to_owned().join(name); if !node_modules_path.exists() { - std::fs::rename(&package_folder, &node_modules_path).unwrap(); + fs::rename(&package_folder, &node_modules_path)?; } - std::fs::remove_dir_all(cache_directory.join(name)).unwrap(); + fs::remove_dir_all(cache_directory.join(name))?; } Ok(())