Skip to content

Commit

Permalink
Clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
sigmaSd committed Nov 18, 2021
1 parent e1db2b6 commit aa8c149
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 25 deletions.
7 changes: 3 additions & 4 deletions src/archive/tar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub fn unpack_archive(
output_folder: &Path,
mut display_handle: impl Write,
) -> crate::Result<Vec<PathBuf>> {
assert!(output_folder.read_dir().unwrap().count() == 0);
assert!(output_folder.read_dir().expect("dir exists").count() == 0);
let mut archive = tar::Archive::new(reader);

let mut files_unpacked = vec![];
Expand All @@ -33,9 +33,8 @@ pub fn unpack_archive(
let file_path = output_folder.join(file.path()?);
file.unpack_in(output_folder)?;

write!(display_handle, "{:?} extracted. ({})", output_folder.join(file.path()?), Bytes::new(file.size()))
.unwrap();
display_handle.flush().unwrap();
write!(display_handle, "{:?} extracted. ({})", output_folder.join(file.path()?), Bytes::new(file.size()))?;
display_handle.flush()?;

files_unpacked.push(file_path);
}
Expand Down
10 changes: 5 additions & 5 deletions src/archive/zip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ where
R: Read + Seek,
D: Write,
{
assert!(output_folder.read_dir().unwrap().count() == 0);
assert!(output_folder.read_dir().expect("dir exists").count() == 0);
let mut unpacked_files = vec![];
for idx in 0..archive.len() {
let mut file = archive.by_index(idx)?;
Expand All @@ -46,8 +46,8 @@ where

match (&*file.name()).ends_with('/') {
_is_dir @ true => {
write!(display_handle, "File {} extracted to \"{}\"", idx, file_path.display()).unwrap();
display_handle.flush().unwrap();
write!(display_handle, "File {} extracted to \"{}\"", idx, file_path.display())?;
display_handle.flush()?;
fs::create_dir_all(&file_path)?;
}
_is_file @ false => {
Expand All @@ -58,8 +58,8 @@ where
}
let file_path = strip_cur_dir(file_path.as_path());

write!(display_handle, "{:?} extracted. ({})", file_path.display(), Bytes::new(file.size())).unwrap();
display_handle.flush().unwrap();
write!(display_handle, "{:?} extracted. ({})", file_path.display(), Bytes::new(file.size()))?;
display_handle.flush()?;

let mut output_file = fs::File::create(&file_path)?;
io::copy(&mut file, &mut output_file)?;
Expand Down
12 changes: 7 additions & 5 deletions src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -276,16 +276,18 @@ pub fn run(args: Opts, question_policy: QuestionPolicy) -> crate::Result<()> {
// formats contains each format necessary for compression, example: [Tar, Gz] (in compression order)
// output_file is the resulting compressed file name, example: "compressed.tar.gz"
fn compress_files(files: Vec<PathBuf>, formats: Vec<Extension>, output_file: fs::File) -> crate::Result<()> {
// The next lines are for displaying the progress bar
// If the input files contain a directory, then the total size will be underestimated
let (total_input_size, precise) = files
.iter()
.map(|f| (f.metadata().unwrap().len(), f.is_file()))
.map(|f| (f.metadata().expect("file exists").len(), f.is_file()))
.fold((0, true), |(total_size, and_precise), (size, precise)| (total_size + size, and_precise & precise));
//NOTE: canonicalize is here to avoid a weird bug:
// > If output_file_path is a nested path and it exists and the user overwrite it
// >> output_file_path.exists() will always return false (somehow)
// - canonicalize seems to fix this
let output_file_path = output_file.path().canonicalize()?;

let file_writer = BufWriter::with_capacity(BUFFER_CAPACITY, output_file);

let mut writer: Box<dyn Write> = Box::new(file_writer);
Expand Down Expand Up @@ -318,7 +320,7 @@ fn compress_files(files: Vec<PathBuf>, formats: Vec<Extension>, output_file: fs:
let _progress = progress::Progress::new(
total_input_size,
precise,
Some(Box::new(move || output_file_path.metadata().unwrap().len())),
Some(Box::new(move || output_file_path.metadata().expect("file exists").len())),
);
writer = chain_writer_encoder(&formats[0].compression_formats[0], writer)?;
let mut reader = fs::File::open(&files[0]).unwrap();
Expand All @@ -328,7 +330,7 @@ fn compress_files(files: Vec<PathBuf>, formats: Vec<Extension>, output_file: fs:
let mut progress = progress::Progress::new(
total_input_size,
precise,
Some(Box::new(move || output_file_path.metadata().unwrap().len())),
Some(Box::new(move || output_file_path.metadata().expect("file exists").len())),
);
archive::tar::build_archive_from_paths(&files, &mut writer, progress.display_handle())?;
writer.flush()?;
Expand Down Expand Up @@ -381,7 +383,7 @@ fn decompress_file(
question_policy: QuestionPolicy,
) -> crate::Result<()> {
assert!(output_dir.exists());
let input_total_size = input_file_path.metadata().unwrap().len();
let input_total_size = input_file_path.metadata().expect("file exists").len();
let reader = fs::File::open(&input_file_path)?;
// Zip archives are special, because they require io::Seek, so it requires it's logic separated
// from decoder chaining.
Expand Down Expand Up @@ -445,7 +447,7 @@ fn decompress_file(

let current_position_fn = Box::new({
let output_file_path = output_file_path.clone();
move || output_file_path.clone().metadata().unwrap().len()
move || output_file_path.clone().metadata().expect("file exists").len()
});
let _progress = progress::Progress::new(input_total_size, true, Some(current_position_fn));
io::copy(&mut reader, &mut writer)?;
Expand Down
26 changes: 15 additions & 11 deletions src/progress.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ use std::{

use indicatif::{ProgressBar, ProgressStyle};

/// Draw a ProgressBar using a function that checks periodically for the progress
pub struct Progress {
draw_stop: Sender<()>,
clean_done: Receiver<()>,
display_handle: DisplayHandle,
}

/// Writes to this struct will be displayed on the progress bar.
struct DisplayHandle {
buf: Vec<u8>,
sender: Sender<String>,
Expand All @@ -19,17 +27,13 @@ impl io::Write for DisplayHandle {
}

fn flush(&mut self) -> io::Result<()> {
self.sender.send(String::from_utf8(self.buf.drain(..).collect()).unwrap()).unwrap();
Ok(())
fn io_error<X>(_: X) -> io::Error {
io::Error::new(io::ErrorKind::Other, "failed to flush buffer")
}
self.sender.send(String::from_utf8(self.buf.drain(..).collect()).map_err(io_error)?).map_err(io_error)
}
}

/// Draw a ProgressBar using an function that checks periodically for the progress
pub struct Progress {
draw_stop: Sender<()>,
cleaning_done: Receiver<()>,
display_handle: DisplayHandle,
}
impl Progress {
/// Create a ProgressBar using a function that checks periodically for the progress
/// If precise is true, the total_input_size will be displayed as the total_bytes size
Expand Down Expand Up @@ -71,11 +75,11 @@ impl Progress {
thread::sleep(Duration::from_millis(100));
}
pb.finish();
clean_tx.send(()).unwrap();
let _ = clean_tx.send(());
});
Progress {
draw_stop: draw_tx,
cleaning_done: clean_rx,
clean_done: clean_rx,
display_handle: DisplayHandle { buf: Vec::new(), sender: msg_tx },
}
}
Expand All @@ -87,6 +91,6 @@ impl Progress {
impl Drop for Progress {
fn drop(&mut self) {
let _ = self.draw_stop.send(());
let _ = self.cleaning_done.recv();
let _ = self.clean_done.recv();
}
}

0 comments on commit aa8c149

Please sign in to comment.