From 28b512ae3fbc651cb268cccf13e32f6ddfd5302e Mon Sep 17 00:00:00 2001 From: Nbiba Bedis Date: Fri, 12 Nov 2021 09:15:21 +0100 Subject: [PATCH 1/2] Skip compressing file if its the same file as the output --- src/commands.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/commands.rs b/src/commands.rs index 5a2dcee..851ab8a 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -44,7 +44,16 @@ fn represents_several_files(files: &[PathBuf]) -> bool { /// Entrypoint of ouch, receives cli options and matches Subcommand to decide what to do pub fn run(args: Opts, question_policy: QuestionPolicy) -> crate::Result<()> { match args.cmd { - Subcommand::Compress { files, output: output_path } => { + Subcommand::Compress { mut files, output: output_path } => { + // If the output_path file exists and is the same as some of the input files, warn the user and skip those inputs (in order to avoid compression recursion) + if output_path.exists() { + clean_input_files_if_needed(&mut files, &output_path.canonicalize()?); + } + // After cleaning, if there are no input files left, exit + if files.is_empty() { + return Err(FinalError::with_title("No files to compress").into()); + } + // Formats from path extension, like "file.tar.gz.xz" -> vec![Tar, Gzip, Lzma] let mut formats = extension::extensions_from_path(&output_path); @@ -526,3 +535,15 @@ fn check_mime_type( } Ok(ControlFlow::Continue(())) } + +fn clean_input_files_if_needed(files: &mut Vec, output_path: &Path) { + let mut idx = 0; + while idx < files.len() { + if files[idx] == output_path { + warning!("The output file and the input file are the same: `{}`, skipping...", output_path.display()); + files.remove(idx); + } else { + idx += 1; + } + } +} From 3e52eb6deb62a5cc171eba10d1ad8e001d8df593 Mon Sep 17 00:00:00 2001 From: Nbiba Bedis Date: Sun, 14 Nov 2021 07:21:54 +0100 Subject: [PATCH 2/2] use fs_err canonicalize --- src/commands.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/commands.rs b/src/commands.rs index 851ab8a..ebc41d7 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -47,7 +47,7 @@ pub fn run(args: Opts, question_policy: QuestionPolicy) -> crate::Result<()> { Subcommand::Compress { mut files, output: output_path } => { // If the output_path file exists and is the same as some of the input files, warn the user and skip those inputs (in order to avoid compression recursion) if output_path.exists() { - clean_input_files_if_needed(&mut files, &output_path.canonicalize()?); + clean_input_files_if_needed(&mut files, &fs::canonicalize(&output_path)?); } // After cleaning, if there are no input files left, exit if files.is_empty() {