src: Better error handling

Should make it more Rusty™. Solves #2. Thank you @j0 for the help. (i'm
big stupid lol)
This commit is contained in:
Lux Aliaga 2022-09-19 00:23:54 -03:00
parent 756c56ea9f
commit 76ad4aad5a
Signed by: lux
GPG Key ID: B56C805968637437
4 changed files with 67 additions and 63 deletions

View File

@ -17,11 +17,11 @@
* *
*/ */
use anyhow::{bail, Result};
use colored::Colorize; use colored::Colorize;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process;
pub fn env_config() -> Vec<PathBuf> { pub fn env_config() -> Result<Vec<PathBuf>> {
// Configures the directories for Vento // Configures the directories for Vento
let emptypath = PathBuf::new(); let emptypath = PathBuf::new();
let home = match dirs::home_dir() { let home = match dirs::home_dir() {
@ -29,17 +29,15 @@ pub fn env_config() -> Vec<PathBuf> {
_ => PathBuf::new(), _ => PathBuf::new(),
}; };
if home == emptypath { if home == emptypath {
println!("{}", format!("Vento was unable to detect your home folder. Have you configured your environment correctly?").red()); bail!("❌ {}", format!("Vento was unable to detect your home folder. Have you configured your environment correctly?").red());
process::exit(1);
} else {
let vento_dir = [home, Path::new(".vento").to_path_buf()].iter().collect();
let active_dir = [&vento_dir, &Path::new("active").to_path_buf()]
.iter()
.collect();
let inactive_dir = [&vento_dir, &Path::new("inactive").to_path_buf()]
.iter()
.collect();
return vec![vento_dir, active_dir, inactive_dir];
}; };
let vento_dir = [home, Path::new(".vento").to_path_buf()].iter().collect();
let active_dir = [&vento_dir, &Path::new("active").to_path_buf()]
.iter()
.collect();
let inactive_dir = [&vento_dir, &Path::new("inactive").to_path_buf()]
.iter()
.collect();
Ok(vec![vento_dir, active_dir, inactive_dir])
} }

View File

@ -18,15 +18,16 @@
*/ */
use super::common; use super::common;
use anyhow::{bail, Context, Result};
use colored::Colorize; use colored::Colorize;
use size_format::SizeFormatterBinary; use size_format::SizeFormatterBinary;
use std::io::{self, Write}; use std::io::{self, Write};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::{fs, process}; use std::{fs, process};
pub fn init() { pub fn init() -> Result<()> {
// Initializes Vento // Initializes Vento
let ventodir = &common::env_config()[0]; let ventodir = &common::env_config()?[0];
if ventodir.is_dir() { if ventodir.is_dir() {
// Checks if Vento has already been initialized and prompts the user if they want to initialize it again // Checks if Vento has already been initialized and prompts the user if they want to initialize it again
@ -37,23 +38,20 @@ pub fn init() {
.read_line(&mut answer) .read_line(&mut answer)
.expect("❌ Failed to read input"); .expect("❌ Failed to read input");
match answer.as_str().trim() { match answer.as_str().trim() {
"y" | "Y" => { "y" | "Y" => fs::remove_dir_all(&ventodir)?,
fs::remove_dir_all(&ventodir).expect( _ => process::exit(0),
"❌ Vento was unable to initalize. Do you have the correct permissions?",
);
}
"n" | "N" | _ => process::exit(0),
}; };
}; };
create_slots(); create_slots()?;
Ok(())
} }
pub fn list(slot: &str, dir: &str) { pub fn list(slot: &str, dir: &str) -> Result<()> {
// Lists files in inventory // Lists files in inventory
let mut slotdir: PathBuf = match slot { let mut slotdir: PathBuf = match slot {
"active" | "a" => common::env_config()[1].clone(), "active" | "a" => common::env_config()?[1].clone(),
"inactive" | "i" => common::env_config()[2].clone(), "inactive" | "i" => common::env_config()?[2].clone(),
_ => PathBuf::new(), _ => PathBuf::new(),
}; };
@ -62,8 +60,8 @@ pub fn list(slot: &str, dir: &str) {
} }
if dir.to_string().contains("..") { if dir.to_string().contains("..") {
println!("{}", format!("Cannot access parent.").red()); bail!("{}", format!("Cannot access parent.").red());
process::exit(1); // process::exit(1);
} }
if slotdir.is_dir() { if slotdir.is_dir() {
@ -153,13 +151,14 @@ pub fn list(slot: &str, dir: &str) {
.red() .red()
); );
} }
Ok(())
} }
pub fn switch() { pub fn switch() -> Result<()> {
// Switches between inventory slots // Switches between inventory slots
let ventodir = &common::env_config()[0]; let ventodir = &common::env_config()?[0];
let active = &common::env_config()[1]; let active = &common::env_config()?[1];
let inactive = &common::env_config()[2]; let inactive = &common::env_config()?[2];
let temp: PathBuf = [ventodir.to_path_buf(), Path::new("temp").to_path_buf()] let temp: PathBuf = [ventodir.to_path_buf(), Path::new("temp").to_path_buf()]
.iter() .iter()
.collect(); .collect();
@ -172,20 +171,21 @@ pub fn switch() {
.expect("❌ Vento was unable to switch slots. Try running vento init and try again"); .expect("❌ Vento was unable to switch slots. Try running vento init and try again");
println!("🎉 {}", format!("Switched inventory slots!").green()); println!("🎉 {}", format!("Switched inventory slots!").green());
Ok(())
} }
fn create_slots() { fn create_slots() -> Result<()> {
// Used only on init. Creates all required directories. // Used only on init. Creates all required directories.
let active = &common::env_config()[1]; let active = &common::env_config()?[1];
let inactive = &common::env_config()[2]; let inactive = &common::env_config()?[2];
fs::create_dir_all(active) fs::create_dir_all(active)
.expect("❌ Vento was unable to initalize. Do you have the correct permissions?"); .context("❌ Vento was unable to initalize. Do you have the correct permissions?")?;
fs::create_dir_all(inactive) fs::create_dir_all(inactive)
.expect("❌ Vento was unable to initalize. Do you have the correct permissions?"); .context("❌ Vento was unable to initalize. Do you have the correct permissions?")?;
println!( println!(
"🎉 {}", "🎉 {}", format!("Vento has been succesfully initialized!").green()
format!("Vento has been succesfully initialized!").green()
); );
Ok(())
} }

View File

@ -18,20 +18,21 @@
*/ */
use super::common; use super::common;
use anyhow::{bail, Context, Result};
use colored::Colorize; use colored::Colorize;
use fs_extra::dir::{move_dir, CopyOptions}; use fs_extra::dir::{move_dir, CopyOptions};
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
pub fn take(file: &String) { pub fn take(file: &String) -> Result<()> {
// Takes a file or directory // Takes a file or directory
let active = &common::env_config()[1]; let active = &common::env_config()?[1];
let sourcepath: PathBuf = Path::new(&file).to_path_buf(); let sourcepath: PathBuf = Path::new(&file).to_path_buf();
let destpath: PathBuf = [&active, &Path::new(file).to_path_buf()].iter().collect(); let destpath: PathBuf = [&active, &Path::new(file).to_path_buf()].iter().collect();
if Path::exists(&destpath) { if Path::exists(&destpath) {
println!( bail!(
"❌ {}", "❌ {}",
format!("A file with the same name already exists in your inventory!").red() format!("A file with the same name already exists in your inventory!").red()
); );
@ -44,11 +45,12 @@ pub fn take(file: &String) {
} else { } else {
println!("{}", format!("No such file or directory.").red()); println!("{}", format!("No such file or directory.").red());
} }
Ok(())
} }
pub fn drop(file: &String, dest: PathBuf) { pub fn drop(file: &String, dest: PathBuf) -> Result<()> {
// Drops a file or directory // Drops a file or directory
let active = &common::env_config()[1]; let active = &common::env_config()?[1];
let sourcepath: PathBuf = [&active, &Path::new(file).to_path_buf()].iter().collect(); let sourcepath: PathBuf = [&active, &Path::new(file).to_path_buf()].iter().collect();
let destpath: PathBuf = [ let destpath: PathBuf = [
@ -60,16 +62,17 @@ pub fn drop(file: &String, dest: PathBuf) {
if Path::exists(&destpath) { if Path::exists(&destpath) {
// HAHA YANDEREDEV MOMENT. This checks what method to use for the file/directory the user has picked // HAHA YANDEREDEV MOMENT. This checks what method to use for the file/directory the user has picked
println!("{}", format!("A file with the same name already exists in the destination! Try renaming it or dropping this file somewhere else.").red()); bail!("{}", format!("A file with the same name already exists in the destination! Try renaming it or dropping this file somewhere else.").red());
} else if sourcepath.is_file() | sourcepath.is_symlink() { } else if sourcepath.is_file() | sourcepath.is_symlink() {
fs::copy(&sourcepath, &destpath).expect("❌ Vento was unable to copy the file."); fs::copy(&sourcepath, &destpath).context("❌ Vento was unable to copy the file.")?;
fs::remove_file(&sourcepath).expect("❌ Vento was unable to remove the file."); fs::remove_file(&sourcepath).context("❌ Vento was unable to remove the file.")?;
} else if sourcepath.is_dir() { } else if sourcepath.is_dir() {
let destpath: PathBuf = Path::new(&dest).to_path_buf(); let destpath: PathBuf = Path::new(&dest).to_path_buf();
let options = CopyOptions::new(); let options = CopyOptions::new();
move_dir(&sourcepath, &destpath, &options) move_dir(&sourcepath, &destpath, &options)
.expect("❌ Vento was unable to move the directory."); .expect("❌ Vento was unable to move the directory.");
} else { } else {
println!("{}", format!("No such file or directory.").red()); bail!("{}", format!("No such file or directory.").red());
} }
Ok(())
} }

View File

@ -17,6 +17,7 @@
* *
*/ */
use anyhow::{bail, Result};
use colored::Colorize; use colored::Colorize;
use std::env; use std::env;
use std::path::Path; use std::path::Path;
@ -26,29 +27,29 @@ mod common;
mod inv; mod inv;
mod item; mod item;
fn main() { fn main() -> Result<()> {
let args: Vec<String> = env::args().collect(); let args: Vec<String> = env::args().collect();
if args.len() >= 2 { if args.len() >= 2 {
// If the vector for the arguments the command is taking is larger than 2, it most likely means the user has provided an argument // If the vector for the arguments the command is taking is larger than 2, it most likely means the user has provided an argument
match args[1].as_str() { match args[1].as_str() {
"help" | "h" => help(), "help" | "h" => help()?,
"init" | "i" => inv::init(), "init" | "i" => inv::init()?,
"list" | "l" => match args.len() { "list" | "l" => match args.len() {
4 => inv::list(args[2].as_str(), args[3].as_str()), 4 => inv::list(args[2].as_str(), args[3].as_str())?,
3 => match args[2].as_str() { 3 => match args[2].as_str() {
"active" | "a" | "inactive" | "i" => inv::list(args[2].as_str(), ""), "active" | "a" | "inactive" | "i" => inv::list(args[2].as_str(), "")?,
_ => inv::list("active", args[2].as_str()), _ => inv::list("active", args[2].as_str())?,
}, },
2 => inv::list("active", ""), 2 => inv::list("active", "")?,
_ => println!("{}", format!("Too many arguments.").red()), _ => bail!("{}", format!("Too many arguments.").red()),
}, },
"switch" | "s" => inv::switch(), "switch" | "s" => inv::switch()?,
"take" | "t" => { "take" | "t" => {
if args.len() == 3 { if args.len() == 3 {
// Similar thing with list, but change it with a file and it will show an error instead of defaulting to anything // Similar thing with list, but change it with a file and it will show an error instead of defaulting to anything
item::take(&args[2]); item::take(&args[2])?;
} else { } else {
println!("{}", format!("You need to specify a file.").red()) bail!("{}", format!("You need to specify a file.").red())
}; };
} }
"drop" | "d" => { "drop" | "d" => {
@ -63,9 +64,9 @@ fn main() {
process::exit(1); process::exit(1);
} }
}, },
); )?;
} else if args.len() == 4 { } else if args.len() == 4 {
item::drop(&args[2], Path::new(&args[3]).to_path_buf()); item::drop(&args[2], Path::new(&args[3]).to_path_buf())?;
} else { } else {
println!("{}", format!("You need to specify a file.").red()) println!("{}", format!("You need to specify a file.").red())
}; };
@ -76,11 +77,12 @@ fn main() {
} }
} else { } else {
// If the user provides no commands, it'll fall back to the help guide // If the user provides no commands, it'll fall back to the help guide
help(); help()?;
} }
Ok(())
} }
fn help() { fn help() -> Result<()> {
// A quick guide to move around in Vento // A quick guide to move around in Vento
println!( println!(
"{}, a CLI inventory for your files "{}, a CLI inventory for your files
@ -104,4 +106,5 @@ fn help() {
format!("init | i").bold().green(), format!("init | i").bold().green(),
format!("help | h").bold().green() format!("help | h").bold().green()
); );
Ok(())
} }