encryptify_lib/zipper.rs
1use std::{
2 fs::{self, File},
3 io::{Read, Write},
4};
5
6use zip::{
7 write::{ExtendedFileOptions, FileOptions},
8 ZipWriter,
9};
10
11/// Creates a ZIP archive of a folder without deleting the original folder.
12///
13/// # Arguments
14///
15/// * `folder_path` - The path of the folder to zip.
16/// * `output_path` - The output file path for the resulting zip archive.
17///
18/// # Panics
19///
20/// This function will panic if:
21/// - The folder cannot be read.
22/// - The zip file cannot be created.
23/// - Any file inside the folder cannot be read or added to the zip file.
24///
25/// # Examples
26///
27/// ```
28/// use encryptify_lib::zip_folder;
29/// use std::fs::{self};
30///
31/// // Create a test folder and file
32/// let folder_path = "test_folder";
33/// let output_path = "test_folder.zip";
34/// fs::create_dir_all(folder_path).unwrap();
35/// std::fs::write(format!("{}/file.txt", folder_path), b"Hello, world!").unwrap();
36///
37/// // Zip the folder
38/// zip_folder(folder_path, output_path);
39///
40/// // Verify the output zip exists
41/// assert!(std::path::Path::new(output_path).exists());
42///
43/// // Cleanup
44/// fs::remove_file(output_path).unwrap();
45/// fs::remove_dir_all(folder_path).unwrap();
46/// ```
47pub fn zip_folder(folder_path: &str, output_path: &str) {
48 let file = File::create(output_path).expect("Failed to create the output ZIP file");
49
50 let mut zip = ZipWriter::new(file);
51
52 let options: FileOptions<'_, ExtendedFileOptions> =
53 FileOptions::default().compression_method(zip::CompressionMethod::Deflated);
54
55 for entry in fs::read_dir(folder_path).expect("Failed to read files from the directory.") {
56 let entry = entry.expect("Failed to get the entry");
57 let path = entry.path();
58
59 if path.is_file() {
60 let file_name = path.file_name().unwrap().to_str().unwrap();
61
62 zip.start_file(file_name, options.clone())
63 .expect("Failed to add the file to zip");
64
65 let mut f = File::open(path).expect("Failed to open the file");
66 let mut buffer = Vec::new();
67
68 f.read_to_end(&mut buffer).expect("Failed to read the file");
69
70 zip.write_all(&buffer)
71 .expect("Failed to write the file to zip...");
72 }
73 }
74
75 zip.finish().expect("Failed to finalize the zip file");
76}