process_files refactor

This commit is contained in:
Dmitry Belyaev 2022-09-13 11:38:04 +03:00
parent d44ccdffa3
commit eedcf9a1b1
Signed by: b4tman
GPG Key ID: 41A00BF15EA7E5F3
1 changed files with 25 additions and 35 deletions

View File

@ -22,22 +22,6 @@ struct OutFileDescr<'a> {
trap: EncoderTrap,
}
impl<'a> OutFileDescr<'a> {
fn new(
name: String,
options: &'a FileOptions,
enc: &'a dyn Encoding,
trap: EncoderTrap,
) -> OutFileDescr<'a> {
OutFileDescr {
name,
options,
encoding: enc,
trap,
}
}
}
fn read_file(file: impl Read, enc: &dyn Encoding) -> Result<String, Box<dyn std::error::Error>> {
let buf = io::BufReader::new(file);
let mut reader = TextReader::new(buf, enc, DecoderTrap::Ignore);
@ -58,9 +42,9 @@ fn write_file<T: Seek + Write>(
Ok(())
}
fn process_files(files: &[PathBuf]) {
fn process_files(files: &[PathBuf]) -> Result<(), Box<dyn std::error::Error>> {
if files.is_empty() {
return;
return Ok(());
}
let enc_input = KOI8_R;
@ -68,32 +52,38 @@ fn process_files(files: &[PathBuf]) {
let options = zip::write::FileOptions::default()
.compression_method(zip::CompressionMethod::Deflated)
.compression_level(Some(9));
let file_def = OutFileDescr {
name: String::new(),
options: &options,
encoding: enc_output,
trap: EncoderTrap::Ignore,
};
let zip_file = fs::File::open(INPUT_FILENAME).unwrap();
let zip_file = fs::File::open(INPUT_FILENAME)?;
let zip_reader = io::BufReader::new(zip_file);
let mut archive = zip::ZipArchive::new(zip_reader).unwrap();
let mut archive = zip::ZipArchive::new(zip_reader)?;
let mut outfile = fs::File::create(OUTPUT_FILENAME).unwrap();
let mut outfile = fs::File::create(OUTPUT_FILENAME)?;
let mut zip_writer = ZipWriter::new(&mut outfile);
files.iter().for_each(|name| {
let name_str = name.to_str().unwrap();
for name in files {
let name_str = name.to_str().ok_or("name to str err")?;
// read string from file in input zip
let file = archive.by_name(name_str).unwrap();
let data = read_file(file, enc_input).unwrap();
let file = archive.by_name(name_str)?;
let data = read_file(file, enc_input)?;
// write string to file in output zip
let out_file = OutFileDescr::new(
name_str.to_string(),
&options,
enc_output,
EncoderTrap::Ignore,
);
write_file(&mut zip_writer, out_file, data).unwrap();
});
let out_file = OutFileDescr {
name: name_str.to_string(),
..file_def
};
write_file(&mut zip_writer, out_file, data)?;
}
zip_writer.finish().unwrap();
zip_writer.finish()?;
Ok(())
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
@ -122,7 +112,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
source_files.sort();
let source_files = source_files;
process_files(&source_files);
process_files(&source_files)?;
println!("done");
Ok(())