Drop dependency on Colored

This commit is contained in:
Vinícius Miguel 2021-04-07 02:02:50 -03:00
parent 8a4ac5d6d1
commit 0026e4d4de
12 changed files with 69 additions and 56 deletions

View File

@ -13,7 +13,6 @@ description = "A command-line utility for easily compressing and decompressing f
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
colored = "2.0.0"
walkdir = "2.3.2" walkdir = "2.3.2"
strsim = "0.10.0" strsim = "0.10.0"
flate2 = "1.0.14" flate2 = "1.0.14"

View File

@ -4,7 +4,7 @@ use std::{
path::{Path, PathBuf}, path::{Path, PathBuf},
}; };
use colored::Colorize; use utils::colors;
use crate::{ use crate::{
cli::Command, cli::Command,
@ -88,8 +88,9 @@ fn get_decompressor(file: &File) -> crate::Result<(Option<BoxedDecompressor>, Bo
None => { None => {
// This block *should* be unreachable // This block *should* be unreachable
eprintln!( eprintln!(
"{} reached Evaluator::get_decompressor without known extension.", "{}[internal error]{} reached Evaluator::get_decompressor without known extension.",
"[internal error]".red() colors::red(),
colors::reset()
); );
return Err(crate::Error::InvalidInput); return Err(crate::Error::InvalidInput);
} }
@ -143,7 +144,7 @@ fn decompress_file_in_memory(
None => { None => {
// There is no more processing to be done on the input file (or there is but currently unsupported) // There is no more processing to be done on the input file (or there is but currently unsupported)
// Therefore, we'll save what we have in memory into a file. // Therefore, we'll save what we have in memory into a file.
println!("{}: saving to {:?}.", "info".yellow(), file_name); println!("{}[INFO]{} saving to {:?}.", colors::yellow(), colors::reset(), file_name);
if file_name.exists() { if file_name.exists() {
let confirm = Confirmation::new("Do you want to overwrite 'FILE'?", Some("FILE")); let confirm = Confirmation::new("Do you want to overwrite 'FILE'?", Some("FILE"));
@ -203,8 +204,9 @@ fn compress_files(
}; };
println!( println!(
"{}: writing to {:?}. ({})", "{}[INFO]{} writing to {:?}. ({})",
"info".yellow(), colors::yellow(),
colors::reset(),
output_path, output_path,
utils::Bytes::new(bytes.len() as u64) utils::Bytes::new(bytes.len() as u64)
); );

View File

@ -1,6 +1,6 @@
use std::{fs, io::Write, path::PathBuf}; use std::{fs, io::Write, path::PathBuf};
use colored::Colorize; use utils::colors;
use super::{Compressor, Entry}; use super::{Compressor, Entry};
use crate::{extension::CompressionFormat, file::File, utils}; use crate::{extension::CompressionFormat, file::File, utils};
@ -18,8 +18,9 @@ impl BzipCompressor {
}; };
println!( println!(
"{}: compressed {:?} into memory ({})", "{}[INFO]{} compressed {:?} into memory ({})",
"info".yellow(), colors::yellow(),
colors::reset(),
&path, &path,
utils::Bytes::new(contents.len() as u64) utils::Bytes::new(contents.len() as u64)
); );

View File

@ -1,6 +1,6 @@
use std::{fs, io::Write, path::PathBuf}; use std::{fs, io::Write, path::PathBuf};
use colored::Colorize; use utils::colors;
use super::{Compressor, Entry}; use super::{Compressor, Entry};
use crate::{extension::CompressionFormat, file::File, utils}; use crate::{extension::CompressionFormat, file::File, utils};
@ -23,8 +23,9 @@ impl GzipCompressor {
}; };
println!( println!(
"{}: compressed {:?} into memory ({})", "{}[INFO]{} compressed {:?} into memory ({})",
"info".yellow(), colors::yellow(),
colors::reset(),
&path, &path,
utils::Bytes::new(bytes.len() as u64) utils::Bytes::new(bytes.len() as u64)
); );

View File

@ -1,6 +1,6 @@
use std::{fs, io::Write, path::PathBuf}; use std::{fs, io::Write, path::PathBuf};
use colored::Colorize; use utils::colors;
use super::{Compressor, Entry}; use super::{Compressor, Entry};
use crate::{extension::CompressionFormat, file::File, utils}; use crate::{extension::CompressionFormat, file::File, utils};
@ -23,8 +23,9 @@ impl LzmaCompressor {
}; };
println!( println!(
"{}: compressed {:?} into memory ({})", "{}[INFO]{} compressed {:?} into memory ({})",
"info".yellow(), colors::yellow(),
colors::reset(),
&path, &path,
utils::Bytes::new(bytes.len() as u64) utils::Bytes::new(bytes.len() as u64)
); );

View File

@ -1,7 +1,7 @@
use std::{env, fs, path::PathBuf}; use std::{env, fs, path::PathBuf};
use colored::Colorize;
use tar::Builder; use tar::Builder;
use utils::colors;
use walkdir::WalkDir; use walkdir::WalkDir;
use super::compressor::Entry; use super::compressor::Entry;
@ -13,8 +13,9 @@ impl TarCompressor {
// TODO: implement this // TODO: implement this
fn make_archive_from_memory(_input: File) -> crate::Result<Vec<u8>> { fn make_archive_from_memory(_input: File) -> crate::Result<Vec<u8>> {
println!( println!(
"{} .tar.tar and .zip.tar is currently unimplemented.", "{}[ERROR]{} .tar.tar and .zip.tar is currently unimplemented.",
"[ERROR]".red() colors::red(),
colors::reset()
); );
Err(crate::Error::InvalidZipArchive("")) Err(crate::Error::InvalidZipArchive(""))
} }

View File

@ -4,8 +4,9 @@ use std::{
path::{Path, PathBuf}, path::{Path, PathBuf},
}; };
use colored::Colorize;
use tar::{self, Archive}; use tar::{self, Archive};
use utils::colors;
use super::decompressor::{DecompressionResult, Decompressor}; use super::decompressor::{DecompressionResult, Decompressor};
use crate::{dialogs::Confirmation, file::File, utils}; use crate::{dialogs::Confirmation, file::File, utils};
@ -16,8 +17,9 @@ pub struct TarDecompressor;
impl TarDecompressor { impl TarDecompressor {
fn unpack_files(from: File, into: &Path, flags: &oof::Flags) -> crate::Result<Vec<PathBuf>> { fn unpack_files(from: File, into: &Path, flags: &oof::Flags) -> crate::Result<Vec<PathBuf>> {
println!( println!(
"{}: attempting to decompress {:?}", "{}[INFO]{} attempting to decompress {:?}",
"ouch".bright_blue(), colors::blue(),
colors::reset(),
&from.path &from.path
); );
let mut files_unpacked = vec![]; let mut files_unpacked = vec![];
@ -45,8 +47,9 @@ impl TarDecompressor {
file.unpack_in(into)?; file.unpack_in(into)?;
println!( println!(
"{}: {:?} extracted. ({})", "{}[INFO]{} {:?} extracted. ({})",
"info".yellow(), colors::yellow(),
colors::reset(),
into.join(file.path()?), into.join(file.path()?),
utils::Bytes::new(file.size()) utils::Bytes::new(file.size())
); );

View File

@ -3,7 +3,8 @@ use std::{
path::Path, path::Path,
}; };
use colored::Colorize;
use utils::colors;
use super::decompressor::{DecompressionResult, Decompressor}; use super::decompressor::{DecompressionResult, Decompressor};
use crate::{extension::CompressionFormat, file::File, utils}; use crate::{extension::CompressionFormat, file::File, utils};
@ -35,8 +36,9 @@ impl DecompressorToMemory {
let bytes_read = reader.read_to_end(&mut buffer)?; let bytes_read = reader.read_to_end(&mut buffer)?;
println!( println!(
"{}: {:?} extracted into memory ({}).", "{}[INFO]{} {:?} extracted into memory ({}).",
"info".yellow(), colors::yellow(),
colors::reset(),
path, path,
utils::Bytes::new(bytes_read as u64) utils::Bytes::new(bytes_read as u64)
); );

View File

@ -4,7 +4,7 @@ use std::{
path::{Path, PathBuf}, path::{Path, PathBuf},
}; };
use colored::Colorize; use utils::colors;
use zip::{self, read::ZipFile, ZipArchive}; use zip::{self, read::ZipFile, ZipArchive};
use super::decompressor::{DecompressionResult, Decompressor}; use super::decompressor::{DecompressionResult, Decompressor};
@ -26,8 +26,9 @@ impl ZipDecompressor {
let comment = file.comment(); let comment = file.comment();
if !comment.is_empty() { if !comment.is_empty() {
println!( println!(
"{}: Comment in {}: {}", "{}[INFO]{} Comment in {}: {}",
"info".yellow(), colors::yellow(),
colors::reset(),
file.name(), file.name(),
comment comment
); );
@ -73,8 +74,9 @@ impl ZipDecompressor {
} }
} }
println!( println!(
"{}: \"{}\" extracted. ({})", "{}[INFO]{} \"{}\" extracted. ({})",
"info".yellow(), colors::yellow(),
colors::reset(),
file_path.display(), file_path.display(),
utils::Bytes::new(file.size()) utils::Bytes::new(file.size())
); );
@ -95,7 +97,7 @@ impl ZipDecompressor {
} }
fn unpack_files(from: File, into: &Path, flags: &oof::Flags) -> crate::Result<Vec<PathBuf>> { fn unpack_files(from: File, into: &Path, flags: &oof::Flags) -> crate::Result<Vec<PathBuf>> {
println!("{} decompressing {:?}", "[OUCH]".bright_blue(), &from.path); println!("{}[INFO]{} decompressing {:?}", colors::blue(), colors::reset(), &from.path);
match from.contents_in_memory { match from.contents_in_memory {
Some(bytes) => { Some(bytes) => {

View File

@ -1,6 +1,6 @@
use std::io::{self, Write}; use std::io::{self, Write};
use colored::Colorize; use crate::utils::colors;
pub struct Confirmation<'a> { pub struct Confirmation<'a> {
pub prompt: &'a str, pub prompt: &'a str,
@ -26,7 +26,7 @@ impl<'a> Confirmation<'a> {
}; };
loop { loop {
print!("{} [{}/{}] ", message, "Y".bright_green(), "n".bright_red()); print!("{} [{}Y{}/{}n{}] ", message, colors::green(), colors::reset(), colors::red(), colors::reset());
io::stdout().flush()?; io::stdout().flush()?;
let mut answer = String::new(); let mut answer = String::new();

View File

@ -1,6 +1,5 @@
use std::{fmt, path::PathBuf}; use std::{fmt, path::PathBuf};
use crate::utils::colors;
use colored::Colorize;
#[derive(PartialEq, Eq)] #[derive(PartialEq, Eq)]
pub enum Error { pub enum Error {
@ -33,7 +32,7 @@ impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match self {
Error::MissingExtensionError(filename) => { Error::MissingExtensionError(filename) => {
write!(f, "{} ", "[ERROR]".red())?; write!(f, "{}[ERROR]{} ", colors::red(), colors::reset())?;
// TODO: show MIME type of the unsupported file // TODO: show MIME type of the unsupported file
write!(f, "cannot compress to {:?}, likely because it has an unsupported (or missing) extension.", filename) write!(f, "cannot compress to {:?}, likely because it has an unsupported (or missing) extension.", filename)
} }
@ -42,14 +41,14 @@ impl fmt::Display for Error {
write!(f, "") write!(f, "")
} }
Error::FileNotFound(file) => { Error::FileNotFound(file) => {
write!(f, "{} ", "[ERROR]".red())?; write!(f, "{}[ERROR]{} ", colors::red(), colors::reset())?;
if file == &PathBuf::from("") { if file == &PathBuf::from("") {
return write!(f, "file not found!"); return write!(f, "file not found!");
} }
write!(f, "file {:?} not found!", file) write!(f, "file {:?} not found!", file)
} }
Error::CompressingRootFolder => { Error::CompressingRootFolder => {
write!(f, "{} ", "[ERROR]".red())?; write!(f, "{}[ERROR]{} ", colors::red(), colors::reset())?;
let spacing = " "; let spacing = " ";
writeln!(f, "It seems you're trying to compress the root folder.")?; writeln!(f, "It seems you're trying to compress the root folder.")?;
writeln!( writeln!(
@ -59,21 +58,22 @@ impl fmt::Display for Error {
)?; )?;
write!( write!(
f, f,
"{}Use a more appropriate tool for this, such as {}.", "{}Use a more appropriate tool for this, such as {}rsync{}.",
spacing, spacing,
"rsync".green() colors::green(),
colors::reset()
) )
} }
Error::MissingArgumentsForCompression => { Error::MissingArgumentsForCompression => {
write!(f, "{} ", "[ERROR]".red())?; write!(f, "{}[ERROR]{} ", colors::red(), colors::reset())?;
let spacing = " "; let spacing = " ";
writeln!(f,"The compress subcommands demands at least 2 arguments, an input file and an output file.")?; writeln!(f,"The compress subcommands demands at least 2 arguments, an input file and an output file.")?;
writeln!(f,"{}Example: `ouch compress img.jpeg img.zip", spacing)?; writeln!(f,"{}Example: `ouch compress img.jpeg img.zip", spacing)?;
write!(f,"{}For more information, run `ouch --help`", spacing) write!(f,"{}For more information, run `ouch --help`", spacing)
} }
Error::InternalError => { Error::InternalError => {
write!(f, "{} ", "[ERROR]".red())?; write!(f, "{}[ERROR]{} ", colors::red(), colors::reset())?;
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()) write!(f, "You've reached an internal error! This really should not have happened.\nPlease file an issue at {}https://github.com/vrmiguel/ouch{}", colors::green(), colors::reset())
} }
_err => { _err => {
// TODO // TODO
@ -90,7 +90,7 @@ impl From<std::io::Error> for Error {
std::io::ErrorKind::PermissionDenied => Self::PermissionDenied, std::io::ErrorKind::PermissionDenied => Self::PermissionDenied,
std::io::ErrorKind::AlreadyExists => Self::AlreadyExists, std::io::ErrorKind::AlreadyExists => Self::AlreadyExists,
_other => { _other => {
println!("{} {}", "[IO error]".red(), err); println!("{}[IO error]{} {}", colors::red(), colors::reset(), err);
Self::IoError Self::IoError
} }
} }
@ -111,7 +111,7 @@ impl From<zip::result::ZipError> for Error {
impl From<walkdir::Error> for Error { impl From<walkdir::Error> for Error {
fn from(err: walkdir::Error) -> Self { fn from(err: walkdir::Error) -> Self {
eprintln!("{} {}", "[ERROR]".red(), err); eprintln!("{}[ERROR]{} {}", colors::red(), colors::reset(), err);
Self::WalkdirError Self::WalkdirError
} }
} }

View File

@ -5,8 +5,6 @@ use std::{
path::{Path, PathBuf}, path::{Path, PathBuf},
}; };
use colored::Colorize;
use crate::{dialogs::Confirmation, extension::CompressionFormat, file::File}; use crate::{dialogs::Confirmation, extension::CompressionFormat, file::File};
#[macro_export] #[macro_export]
@ -42,10 +40,11 @@ pub fn check_for_multiple_files(
) -> crate::Result<()> { ) -> crate::Result<()> {
if files.len() != 1 { if files.len() != 1 {
eprintln!( eprintln!(
"{}: cannot compress multiple files directly to {:#?}.\n\ "{}[ERROR]{} cannot compress multiple files directly to {:#?}.\n\
Try using an intermediate archival method such as Tar.\n\ Try using an intermediate archival method such as Tar.\n\
Example: filename.tar{}", Example: filename.tar{}",
"[ERROR]".red(), colors::red(),
colors::reset(),
format, format,
format format
); );
@ -58,14 +57,16 @@ pub fn check_for_multiple_files(
pub fn create_path_if_non_existent(path: &Path) -> crate::Result<()> { pub fn create_path_if_non_existent(path: &Path) -> crate::Result<()> {
if !path.exists() { if !path.exists() {
println!( println!(
"{}: attempting to create folder {:?}.", "{}[INFO]{} attempting to create folder {:?}.",
"[INFO]".yellow(), colors::yellow(),
colors::reset(),
&path &path
); );
std::fs::create_dir_all(path)?; std::fs::create_dir_all(path)?;
println!( println!(
"{}: directory {:#?} created.", "{}[INFO]{} directory {:#?} created.",
"[INFO]".yellow(), colors::yellow(),
colors::reset(),
fs::canonicalize(&path)? fs::canonicalize(&path)?
); );
} }
@ -106,7 +107,7 @@ pub fn permission_for_overwriting(
) -> crate::Result<bool> { ) -> crate::Result<bool> {
match (flags.is_present("yes"), flags.is_present("false")) { match (flags.is_present("yes"), flags.is_present("false")) {
(true, true) => { (true, true) => {
unreachable!("This shoul've been cutted out in the ~/src/cli.rs filter flags function.") unreachable!("This should've been cutted out in the ~/src/cli.rs filter flags function.")
} }
(true, _) => return Ok(true), (true, _) => return Ok(true),
(_, true) => return Ok(false), (_, true) => return Ok(false),