zipping.rs
1 use std::{fs::File, io::Write, path::PathBuf}; 2 use zip::{unstable::write::FileOptionsExt, write::FileOptions, ZipWriter}; 3 4 5 pub struct Zipper { 6 pub dir: PathBuf 7 } 8 9 impl Zipper { 10 11 pub fn compress_directory(&self) -> Result<(), Box<dyn std::error::Error>> { 12 let open_attempt = File::open(&self.dir).expect("Failed to open directory"); 13 let zipfile_path = self.get_zipfile_path(); 14 let zipfile = File::create(&zipfile_path)?; 15 16 let mut zip = ZipWriter::new(zipfile); 17 18 let compression_options: FileOptions<'_, _> = FileOptions::default().compression_method(zip::CompressionMethod::Deflated); 19 20 for file_retrieval in std::fs::read_dir(&self.dir)? { 21 let file_path = file_retrieval.unwrap().path(); 22 let mut file = File::open(file_path)?; 23 24 zip.start_file::<T: FileOptionsExt>( 25 file_path.file_name().unwrap().to_str().unwrap(), 26 compression_options 27 )?; 28 29 let mut buffer = Vec::new(); 30 std::io::copy(&mut file, &mut buffer); 31 zip.write_all(&buffer); 32 } 33 34 zip.finish(); 35 36 Ok(()) 37 } 38 39 fn construct_zipfile_name(&self) -> String { 40 let zipfile_name = self.dir 41 .file_name() 42 .expect("Failed to get the directory's base name") 43 .to_str() 44 .unwrap(); 45 46 format!("{}.zip", zipfile_name) 47 } 48 49 fn get_zipfile_path(&self) -> PathBuf { 50 let zipfile_name = self.construct_zipfile_name(); 51 52 self.dir 53 .parent() 54 .unwrap_or(&self.dir) 55 .join(zipfile_name) 56 } 57 } 58