From 76ad4aad5a345e44b836f71a26cc6cec37ac3b70 Mon Sep 17 00:00:00 2001 From: Lux Aliaga Date: Mon, 19 Sep 2022 00:23:54 -0300 Subject: [PATCH] src: Better error handling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Should make it more Rusty™. Solves #2. Thank you @j0 for the help. (i'm big stupid lol) --- src/common.rs | 26 ++++++++++++-------------- src/inv.rs | 50 +++++++++++++++++++++++++------------------------- src/item.rs | 21 ++++++++++++--------- src/main.rs | 33 ++++++++++++++++++--------------- 4 files changed, 67 insertions(+), 63 deletions(-) diff --git a/src/common.rs b/src/common.rs index b566d39..e5735c5 100644 --- a/src/common.rs +++ b/src/common.rs @@ -17,11 +17,11 @@ * */ +use anyhow::{bail, Result}; use colored::Colorize; use std::path::{Path, PathBuf}; -use std::process; -pub fn env_config() -> Vec { +pub fn env_config() -> Result> { // Configures the directories for Vento let emptypath = PathBuf::new(); let home = match dirs::home_dir() { @@ -29,17 +29,15 @@ pub fn env_config() -> Vec { _ => PathBuf::new(), }; if home == emptypath { - println!("❌ {}", 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]; + bail!("❌ {}", format!("Vento was unable to detect your home folder. Have you configured your environment correctly?").red()); }; + 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]) } diff --git a/src/inv.rs b/src/inv.rs index 8044637..4f24c8e 100644 --- a/src/inv.rs +++ b/src/inv.rs @@ -18,15 +18,16 @@ */ use super::common; +use anyhow::{bail, Context, Result}; use colored::Colorize; use size_format::SizeFormatterBinary; use std::io::{self, Write}; use std::path::{Path, PathBuf}; use std::{fs, process}; -pub fn init() { +pub fn init() -> Result<()> { // Initializes Vento - let ventodir = &common::env_config()[0]; + let ventodir = &common::env_config()?[0]; if ventodir.is_dir() { // 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) .expect("❌ Failed to read input"); match answer.as_str().trim() { - "y" | "Y" => { - fs::remove_dir_all(&ventodir).expect( - "❌ Vento was unable to initalize. Do you have the correct permissions?", - ); - } - "n" | "N" | _ => process::exit(0), + "y" | "Y" => fs::remove_dir_all(&ventodir)?, + _ => 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 let mut slotdir: PathBuf = match slot { - "active" | "a" => common::env_config()[1].clone(), - "inactive" | "i" => common::env_config()[2].clone(), + "active" | "a" => common::env_config()?[1].clone(), + "inactive" | "i" => common::env_config()?[2].clone(), _ => PathBuf::new(), }; @@ -62,8 +60,8 @@ pub fn list(slot: &str, dir: &str) { } if dir.to_string().contains("..") { - println!("❌ {}", format!("Cannot access parent.").red()); - process::exit(1); + bail!("❌ {}", format!("Cannot access parent.").red()); + // process::exit(1); } if slotdir.is_dir() { @@ -153,13 +151,14 @@ pub fn list(slot: &str, dir: &str) { .red() ); } + Ok(()) } -pub fn switch() { +pub fn switch() -> Result<()> { // Switches between inventory slots - let ventodir = &common::env_config()[0]; - let active = &common::env_config()[1]; - let inactive = &common::env_config()[2]; + let ventodir = &common::env_config()?[0]; + let active = &common::env_config()?[1]; + let inactive = &common::env_config()?[2]; let temp: PathBuf = [ventodir.to_path_buf(), Path::new("temp").to_path_buf()] .iter() .collect(); @@ -172,20 +171,21 @@ pub fn switch() { .expect("❌ Vento was unable to switch slots. Try running vento init and try again"); println!("🎉 {}", format!("Switched inventory slots!").green()); + Ok(()) } -fn create_slots() { +fn create_slots() -> Result<()> { // Used only on init. Creates all required directories. - let active = &common::env_config()[1]; - let inactive = &common::env_config()[2]; + let active = &common::env_config()?[1]; + let inactive = &common::env_config()?[2]; 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) - .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!( - "🎉 {}", - format!("Vento has been succesfully initialized!").green() + "🎉 {}", format!("Vento has been succesfully initialized!").green() ); + Ok(()) } diff --git a/src/item.rs b/src/item.rs index acd837d..11238f6 100644 --- a/src/item.rs +++ b/src/item.rs @@ -18,20 +18,21 @@ */ use super::common; +use anyhow::{bail, Context, Result}; use colored::Colorize; use fs_extra::dir::{move_dir, CopyOptions}; use std::fs; use std::path::{Path, PathBuf}; -pub fn take(file: &String) { +pub fn take(file: &String) -> Result<()> { // 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 destpath: PathBuf = [&active, &Path::new(file).to_path_buf()].iter().collect(); if Path::exists(&destpath) { - println!( + bail!( "❌ {}", format!("A file with the same name already exists in your inventory!").red() ); @@ -44,11 +45,12 @@ pub fn take(file: &String) { } else { 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 - 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 destpath: PathBuf = [ @@ -60,16 +62,17 @@ pub fn drop(file: &String, dest: PathBuf) { if Path::exists(&destpath) { // 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() { - fs::copy(&sourcepath, &destpath).expect("❌ Vento was unable to copy the file."); - fs::remove_file(&sourcepath).expect("❌ Vento was unable to remove the file."); + fs::copy(&sourcepath, &destpath).context("❌ Vento was unable to copy the file.")?; + fs::remove_file(&sourcepath).context("❌ Vento was unable to remove the file.")?; } else if sourcepath.is_dir() { let destpath: PathBuf = Path::new(&dest).to_path_buf(); let options = CopyOptions::new(); move_dir(&sourcepath, &destpath, &options) .expect("❌ Vento was unable to move the directory."); } else { - println!("❌ {}", format!("No such file or directory.").red()); + bail!("❌ {}", format!("No such file or directory.").red()); } + Ok(()) } diff --git a/src/main.rs b/src/main.rs index fd75920..5bc08b8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -17,6 +17,7 @@ * */ +use anyhow::{bail, Result}; use colored::Colorize; use std::env; use std::path::Path; @@ -26,29 +27,29 @@ mod common; mod inv; mod item; -fn main() { +fn main() -> Result<()> { let args: Vec = env::args().collect(); 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 match args[1].as_str() { - "help" | "h" => help(), - "init" | "i" => inv::init(), + "help" | "h" => help()?, + "init" | "i" => inv::init()?, "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() { - "active" | "a" | "inactive" | "i" => inv::list(args[2].as_str(), ""), - _ => inv::list("active", args[2].as_str()), + "active" | "a" | "inactive" | "i" => inv::list(args[2].as_str(), "")?, + _ => inv::list("active", args[2].as_str())?, }, - 2 => inv::list("active", ""), - _ => println!("❌ {}", format!("Too many arguments.").red()), + 2 => inv::list("active", "")?, + _ => bail!("❌ {}", format!("Too many arguments.").red()), }, - "switch" | "s" => inv::switch(), + "switch" | "s" => inv::switch()?, "take" | "t" => { 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 - item::take(&args[2]); + item::take(&args[2])?; } else { - println!("❌ {}", format!("You need to specify a file.").red()) + bail!("❌ {}", format!("You need to specify a file.").red()) }; } "drop" | "d" => { @@ -63,9 +64,9 @@ fn main() { process::exit(1); } }, - ); + )?; } 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 { println!("❌ {}", format!("You need to specify a file.").red()) }; @@ -76,11 +77,12 @@ fn main() { } } else { // 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 println!( "{}, a CLI inventory for your files @@ -104,4 +106,5 @@ fn help() { format!("init | i").bold().green(), format!("help | h").bold().green() ); + Ok(()) }