Check if a folder is being compressed to a non-archive format (#79)

This commit is contained in:
Vinícius Miguel 2021-10-07 17:09:33 -03:00 committed by GitHub
parent a739b5a482
commit 14961bed65
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 31 additions and 14 deletions

View File

@ -11,7 +11,7 @@ use zip::{self, read::ZipFile, ZipArchive};
use crate::{ use crate::{
info, oof, info, oof,
utils::{self, Bytes}, utils::{self, dir_is_empty, Bytes},
}; };
use self::utf8::get_invalid_utf8_paths; use self::utf8::get_invalid_utf8_paths;
@ -93,7 +93,7 @@ where
info!("Compressing '{}'.", utils::to_utf(path)); info!("Compressing '{}'.", utils::to_utf(path));
if path.is_dir() { if path.is_dir() {
if dir_is_empty(path)? { if dir_is_empty(path) {
writer.add_directory(path.to_str().unwrap().to_owned(), options)?; writer.add_directory(path.to_str().unwrap().to_owned(), options)?;
} }
// If a dir has files, the files are responsible for creating them. // If a dir has files, the files are responsible for creating them.
@ -119,10 +119,6 @@ fn check_for_comments(file: &ZipFile) {
} }
} }
fn dir_is_empty(dir_path: &Path) -> crate::Result<bool> {
Ok(dir_path.read_dir()?.next().is_none())
}
#[cfg(unix)] #[cfg(unix)]
fn __unix_set_permissions(file_path: &Path, file: &ZipFile) -> crate::Result<()> { fn __unix_set_permissions(file_path: &Path, file: &ZipFile) -> crate::Result<()> {
use std::os::unix::fs::PermissionsExt; use std::os::unix::fs::PermissionsExt;

View File

@ -18,14 +18,25 @@ use crate::{
self, self,
CompressionFormat::{self, *}, CompressionFormat::{self, *},
}, },
info, oof, utils, info, oof,
utils::to_utf, utils::to_utf,
utils::{self, dir_is_empty},
Error, Error,
}; };
// Used in BufReader and BufWriter to perform less syscalls // Used in BufReader and BufWriter to perform less syscalls
const BUFFER_CAPACITY: usize = 1024 * 64; const BUFFER_CAPACITY: usize = 1024 * 64;
fn represents_several_files(files: &[PathBuf]) -> bool {
let is_non_empty_dir = |path: &PathBuf| {
let is_non_empty = || !dir_is_empty(&path);
path.is_dir().then(is_non_empty).unwrap_or_default()
};
files.iter().any(is_non_empty_dir) || files.len() > 1
}
pub fn run(command: Command, flags: &oof::Flags) -> crate::Result<()> { pub fn run(command: Command, flags: &oof::Flags) -> crate::Result<()> {
match command { match command {
Command::Compress { files, output_path } => { Command::Compress { files, output_path } => {
@ -45,7 +56,7 @@ pub fn run(command: Command, flags: &oof::Flags) -> crate::Result<()> {
return Err(Error::with_reason(reason)); return Err(Error::with_reason(reason));
} }
if matches!(&formats[0], Bzip | Gzip | Lzma) && files.len() > 1 { if matches!(&formats[0], Bzip | Gzip | Lzma) && represents_several_files(&files) {
// This piece of code creates a sugestion for compressing multiple files // This piece of code creates a sugestion for compressing multiple files
// It says: // It says:
// Change from file.bz.xz // Change from file.bz.xz
@ -205,7 +216,7 @@ fn compress_files(
Zip => { Zip => {
eprintln!("{yellow}Warning:{reset}", yellow = colors::yellow(), reset = colors::reset()); eprintln!("{yellow}Warning:{reset}", yellow = colors::yellow(), reset = colors::reset());
eprintln!("\tCompressing .zip entirely in memory."); eprintln!("\tCompressing .zip entirely in memory.");
eprintln!("\tIf the file is too big, your pc might freeze!"); eprintln!("\tIf the file is too big, your PC might freeze!");
eprintln!( eprintln!(
"\tThis is a limitation for formats like '{}'.", "\tThis is a limitation for formats like '{}'.",
formats.iter().map(|format| format.to_string()).collect::<String>() formats.iter().map(|format| format.to_string()).collect::<String>()

View File

@ -35,7 +35,7 @@ pub enum Error {
pub type Result<T> = std::result::Result<T, Error>; pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Default, PartialEq)] #[derive(Clone, Debug, Default, PartialEq)]
pub struct FinalError { pub struct FinalError {
title: String, title: String,
details: Vec<String>, details: Vec<String>,
@ -153,9 +153,12 @@ impl fmt::Display for Error {
Error::CompressionTypo => FinalError::with_title("Possible typo detected") Error::CompressionTypo => FinalError::with_title("Possible typo detected")
.hint(format!("Did you mean '{}ouch compress{}'?", magenta(), reset())) .hint(format!("Did you mean '{}ouch compress{}'?", magenta(), reset()))
.into_owned(), .into_owned(),
_err => { Error::UnknownExtensionError(_) => todo!(),
todo!(); Error::AlreadyExists => todo!(),
} Error::InvalidZipArchive(_) => todo!(),
Error::PermissionDenied => todo!(),
Error::UnsupportedZipArchive(_) => todo!(),
Error::Custom { reason } => reason.clone(),
}; };
write!(f, "{}", err) write!(f, "{}", err)

View File

@ -1,12 +1,19 @@
use std::{ use std::{
cmp, env, cmp, env,
ffi::OsStr, ffi::OsStr,
fs, fs::{self, ReadDir},
path::{Path, PathBuf}, path::{Path, PathBuf},
}; };
use crate::{dialogs::Confirmation, info, oof}; use crate::{dialogs::Confirmation, info, oof};
/// Checks if the given path represents an empty directory.
pub fn dir_is_empty(dir_path: &Path) -> bool {
let is_empty = |mut rd: ReadDir| rd.next().is_none();
dir_path.read_dir().ok().map(is_empty).unwrap_or_default()
}
pub fn create_dir_if_non_existent(path: &Path) -> crate::Result<()> { pub fn create_dir_if_non_existent(path: &Path) -> crate::Result<()> {
if !path.exists() { if !path.exists() {
fs::create_dir_all(path)?; fs::create_dir_all(path)?;