(WIP) Showing better error messages

This commit is contained in:
Vinícius Rodrigues Miguel 2021-03-29 23:11:22 -03:00
parent 7997c07ed0
commit 2dc828c0ff
8 changed files with 78 additions and 41 deletions

View File

@ -29,7 +29,7 @@ pub enum Flags {
// Flag -y, --yes supplied
AlwaysYes,
// Flag -n, --no supplied
AlwaysNo
AlwaysNo,
}
#[derive(PartialEq, Eq, Debug)]
@ -104,7 +104,7 @@ pub fn parse_matches(matches: clap::ArgMatches<'static>) -> crate::Result<(Comma
(true, true) => unreachable!(),
(true, _) => Flags::AlwaysYes,
(_, true) => Flags::AlwaysNo,
(_, _) => Flags::None
(_, _) => Flags::None,
};
Ok((Command::try_from(matches)?, flag))

View File

@ -1,9 +1,6 @@
use std::path::PathBuf;
use crate::{
cli::Flags,
file::File
};
use crate::{cli::Flags, file::File};
pub enum DecompressionResult {
FilesUnpacked(Vec<PathBuf>),
@ -11,5 +8,10 @@ pub enum DecompressionResult {
}
pub trait Decompressor {
fn decompress(&self, from: File, into: &Option<File>, flags: Flags) -> crate::Result<DecompressionResult>;
fn decompress(
&self,
from: File,
into: &Option<File>,
flags: Flags,
) -> crate::Result<DecompressionResult>;
}

View File

@ -24,9 +24,7 @@ impl TarDecompressor {
let confirm = Confirmation::new("Do you want to overwrite 'FILE'?", Some("FILE"));
let mut archive: Archive<Box<dyn Read>> = match from.contents_in_memory {
Some(bytes) => {
tar::Archive::new(Box::new(Cursor::new(bytes)))
},
Some(bytes) => tar::Archive::new(Box::new(Cursor::new(bytes))),
None => {
let file = fs::File::open(&from.path)?;
tar::Archive::new(Box::new(file))
@ -35,7 +33,7 @@ impl TarDecompressor {
for file in archive.entries()? {
let mut file = file?;
let file_path = PathBuf::from(into).join(file.path()?);
if file_path.exists() {
if !utils::permission_for_overwriting(&file_path, flags, &confirm)? {
@ -43,7 +41,7 @@ impl TarDecompressor {
continue;
}
}
file.unpack_in(into)?;
println!(
@ -62,7 +60,12 @@ impl TarDecompressor {
}
impl Decompressor for TarDecompressor {
fn decompress(&self, from: File, into: &Option<File>, flags: Flags) -> crate::Result<DecompressionResult> {
fn decompress(
&self,
from: File,
into: &Option<File>,
flags: Flags,
) -> crate::Result<DecompressionResult> {
let destination_path = utils::get_destination_path(into);
utils::create_path_if_non_existent(destination_path)?;

View File

@ -62,19 +62,34 @@ impl DecompressorToMemory {
}
impl Decompressor for GzipDecompressor {
fn decompress(&self, from: File, into: &Option<File>, _: Flags) -> crate::Result<DecompressionResult> {
fn decompress(
&self,
from: File,
into: &Option<File>,
_: Flags,
) -> crate::Result<DecompressionResult> {
DecompressorToMemory::decompress(from, CompressionFormat::Gzip, into)
}
}
impl Decompressor for BzipDecompressor {
fn decompress(&self, from: File, into: &Option<File>, _: Flags) -> crate::Result<DecompressionResult> {
fn decompress(
&self,
from: File,
into: &Option<File>,
_: Flags,
) -> crate::Result<DecompressionResult> {
DecompressorToMemory::decompress(from, CompressionFormat::Bzip, into)
}
}
impl Decompressor for LzmaDecompressor {
fn decompress(&self, from: File, into: &Option<File>, _: Flags) -> crate::Result<DecompressionResult> {
fn decompress(
&self,
from: File,
into: &Option<File>,
_: Flags,
) -> crate::Result<DecompressionResult> {
DecompressorToMemory::decompress(from, CompressionFormat::Lzma, into)
}
}

View File

@ -95,11 +95,7 @@ impl ZipDecompressor {
}
fn unpack_files(from: File, into: &Path, flags: Flags) -> crate::Result<Vec<PathBuf>> {
println!(
"{} decompressing {:?}",
"[OUCH]".bright_blue(),
&from.path
);
println!("{} decompressing {:?}", "[OUCH]".bright_blue(), &from.path);
match from.contents_in_memory {
Some(bytes) => {

View File

@ -2,7 +2,7 @@ use std::{fmt, path::PathBuf};
use colored::Colorize;
#[derive(PartialEq, Eq, Debug)]
#[derive(PartialEq, Eq)]
pub enum Error {
UnknownExtensionError(String),
MissingExtensionError(String),
@ -17,10 +17,25 @@ pub enum Error {
UnsupportedZipArchive(&'static str),
InputsMustHaveBeenDecompressible(PathBuf),
InternalError,
CompressingRootFolder,
}
pub type Result<T> = std::result::Result<T, Error>;
// impl std::error::Error for Error {
// fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
// // TODO: get rid of PartialEq and Eq in self::Error in order to
// // correctly use `source`.
// None
// }
// }
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} ", "[ERROR]".red())?;
@ -35,6 +50,15 @@ impl fmt::Display for Error {
// TODO: check if file == ""
write!(f, "file {:?} not found!", file)
}
Error::CompressingRootFolder => {
let spacing = " ";
writeln!(f, "It seems you're trying to compress the root folder.")?;
writeln!(f, "{}This is unadvisable since ouch does compressions in-memory.", spacing)?;
write!(f, "{}Use a more appropriate tool for this, such as {}.", spacing, "rsync".green())
}
Error::InternalError => {
write!(f, "You've reached an internal error! This really should not have happened.\nPlease file an issue at {}", "https://github.com/vrmiguel/ouch".green())
}
_err => {
// TODO
write!(f, "")

View File

@ -12,7 +12,14 @@ mod utils;
use error::{Error, Result};
use evaluator::Evaluator;
fn main() -> crate::Result<()> {
fn main() {
if let Err(err) = run() {
println!("{}", err);
std::process::exit(127);
}
}
fn run() -> crate::Result<()> {
let matches = cli::get_matches();
let (command, flags) = cli::parse_matches(matches)?;
Evaluator::evaluate(command, flags)

View File

@ -70,34 +70,24 @@ pub(crate) fn change_dir_and_return_parent(filename: &PathBuf) -> crate::Result<
let parent = if let Some(parent) = filename.parent() {
parent
} else {
let spacing = " ";
println!(
"{} It seems you're trying to compress the root folder.",
"[WARNING]".red()
);
println!(
"{}This is unadvisable since ouch does compressions in-memory.",
spacing
);
println!(
"{}Use a more appropriate tool for this, such as {}.",
spacing,
"rsync".green()
);
return Err(crate::Error::InvalidInput);
return Err(crate::Error::CompressingRootFolder);
};
env::set_current_dir(parent)?;
Ok(previous_location)
}
pub fn permission_for_overwriting(path: &PathBuf, flags: Flags, confirm: &Confirmation) -> crate::Result<bool> {
pub fn permission_for_overwriting(
path: &PathBuf,
flags: Flags,
confirm: &Confirmation,
) -> crate::Result<bool> {
match flags {
Flags::AlwaysYes => return Ok(true),
Flags::AlwaysNo => return Ok(false),
Flags::None => {}
}
let file_path_str = &*path.as_path().to_string_lossy();
Ok(confirm.ask(Some(file_path_str))?)
}
}