Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Skip compressing file if its the same file as the output
Browse files Browse the repository at this point in the history
sigmaSd committed Nov 12, 2021
1 parent 9238b8e commit 6b2e4db
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/commands.rs
Original file line number Diff line number Diff line change
@@ -44,7 +44,14 @@ 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 output_path exists and contains some of the input files, warn the user and remove them from the input list (in order to avoid compression recursion)
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 +533,19 @@ fn check_mime_type(
}
Ok(ControlFlow::Continue(()))
}

fn clean_input_files_if_needed(files: &mut Vec<PathBuf>, output_path: &Path) {
if !output_path.exists() {
return;
}

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;
}
}
}

0 comments on commit 6b2e4db

Please sign in to comment.