Merge branch 'pr/fix-archive-format-detection'

This commit is contained in:
João M. Bezerra 2021-10-31 01:59:41 -03:00
commit 77873cde15
2 changed files with 71 additions and 83 deletions

View File

@ -56,7 +56,9 @@ pub fn run(args: Opts, question_policy: QuestionPolicy) -> crate::Result<()> {
return Err(Error::with_reason(reason));
}
if matches!(&formats[0], Bzip | Gzip | Lzma) && represents_several_files(&files) {
if !formats.get(0).map(CompressionFormat::is_archive_format).unwrap_or(false)
&& represents_several_files(&files)
{
// This piece of code creates a suggestion for compressing multiple files
// It says:
// Change from file.bz.xz
@ -84,7 +86,7 @@ pub fn run(args: Opts, question_policy: QuestionPolicy) -> crate::Result<()> {
return Err(Error::with_reason(reason));
}
if let Some(format) = formats.iter().skip(1).find(|format| matches!(format, Tar | Zip)) {
if let Some(format) = formats.iter().skip(1).find(|format| format.is_archive_format()) {
let reason = FinalError::with_title(format!("Cannot compress to '{}'.", to_utf(&output_path)))
.detail(format!("Found the format '{}' in an incorrect position.", format))
.detail(format!("'{}' can only be used at the start of the file extension.", format))
@ -186,25 +188,6 @@ pub fn run(args: Opts, question_policy: QuestionPolicy) -> crate::Result<()> {
fn compress_files(files: Vec<PathBuf>, formats: Vec<CompressionFormat>, output_file: fs::File) -> crate::Result<()> {
let file_writer = BufWriter::with_capacity(BUFFER_CAPACITY, output_file);
if let [Tar | Tgz | Zip] = *formats.as_slice() {
match formats[0] {
Tar => {
let mut bufwriter = archive::tar::build_archive_from_paths(&files, file_writer)?;
bufwriter.flush()?;
}
Tgz => {
// Wrap it into an gz_decoder, and pass to the tar archive builder
let gz_decoder = flate2::write::GzEncoder::new(file_writer, Default::default());
let mut bufwriter = archive::tar::build_archive_from_paths(&files, gz_decoder)?;
bufwriter.flush()?;
}
Zip => {
let mut bufwriter = archive::zip::build_archive_from_paths(&files, file_writer)?;
bufwriter.flush()?;
}
_ => unreachable!(),
};
} else {
let mut writer: Box<dyn Write> = Box::new(file_writer);
// Grab previous encoder and wrap it inside of a new one
@ -275,7 +258,6 @@ fn compress_files(files: Vec<PathBuf>, formats: Vec<CompressionFormat>, output_f
io::copy(&mut vec_buffer.as_slice(), &mut writer)?;
}
}
}
Ok(())
}

View File

@ -19,6 +19,12 @@ pub enum CompressionFormat {
Zip, // .zip
}
impl CompressionFormat {
pub fn is_archive_format(&self) -> bool {
matches!(self, Tar | Tgz | Tbz | Tlzma | Tzst | Zip)
}
}
impl fmt::Display for CompressionFormat {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(