75 lines
2.2 KiB
Rust
75 lines
2.2 KiB
Rust
|
|
use std::{
|
|
cell::RefCell,
|
|
fs::File,
|
|
path::Path,
|
|
io::{
|
|
BufWriter,
|
|
},
|
|
};
|
|
use zip::{
|
|
CompressionMethod,
|
|
write::{
|
|
ZipWriter,
|
|
FileOptions,
|
|
},
|
|
};
|
|
use rust_util::{
|
|
XResult,
|
|
new_box_ioerror,
|
|
util_msg::*,
|
|
util_io::*,
|
|
util_file::*,
|
|
};
|
|
|
|
// http://mvdnes.github.io/rust-docs/zip-rs/zip/index.html
|
|
pub fn zip_file(target: &str, zip_file: &str) -> XResult<()> {
|
|
if Path::new(zip_file).exists() {
|
|
return Err(new_box_ioerror(&format!("Zip file exists: {}", zip_file)));
|
|
}
|
|
|
|
let target_path = Path::new(target);
|
|
if !target_path.exists() {
|
|
return Err(new_box_ioerror(&format!("Zip path NOT exists: {}", target)));
|
|
}
|
|
if !(target_path.is_file() || target_path.is_dir()) {
|
|
return Err(new_box_ioerror(&format!("Zip path NOT file or dir: {}", target)));
|
|
}
|
|
|
|
let bw = BufWriter::new(File::create(zip_file)?);
|
|
let mut zip = ZipWriter::new(bw);
|
|
if target_path.is_file() {
|
|
let options = FileOptions::default().compression_method(CompressionMethod::Stored);
|
|
let zip_fn = get_file_name(target_path);
|
|
zip.start_file(zip_fn, options)?;
|
|
copy_io_with_head(&mut File::open(target_path)?, &mut zip, -1, "Compressing")?;
|
|
|
|
zip.finish()?;
|
|
} else {
|
|
let mut_zip = RefCell::new(zip);
|
|
walk_dir(&target_path, &|p, e| {
|
|
print_message(MessageType::WARN, &format!("Compress {} failed: {}", &p.display(), &e));
|
|
}, &|f| {
|
|
let options = FileOptions::default().compression_method(CompressionMethod::Stored);
|
|
let mut m_zip = mut_zip.borrow_mut();
|
|
match m_zip.start_file("", options) { // TODO filename
|
|
Ok(_) => (),
|
|
Err(e) => print_message(MessageType::WARN, &format!("Compress {} failed: {}", &f.display(), &e)),
|
|
};
|
|
}, &|_| { true })?;
|
|
|
|
mut_zip.borrow_mut().finish()?;
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
pub fn get_file_name(path: &Path) -> String {
|
|
match path.file_name() {
|
|
None => "no_file_name".to_string(),
|
|
Some(f) => match f.to_os_string().into_string().ok() {
|
|
None => "unknown_file_name".to_string(),
|
|
Some(f) => f,
|
|
},
|
|
}
|
|
} |