1
0
Fork 0
mirror of https://git.sr.ht/~nixgoat/vento synced 2024-11-24 15:55:17 +00:00

Compare commits

...

4 commits

Author SHA1 Message Date
Lux Aliaga 6ec32037db
src: Code comments and cleanup
Basically some last refinements to make the code look a bit more
readable and presentable.
2022-09-27 20:05:08 -03:00
Lux Aliaga 6fa0cba8ca
item: Pre-init error handling
Also adds another error handler for invalid slots. Solves #8.
2022-09-27 19:38:44 -03:00
Lux Aliaga 45dfcc9f19
fixup! src: Universal error handling 2022-09-27 19:29:54 -03:00
Lux Aliaga 8fe5bca167
src: Universal error handling
This commit should unify the way Vento handles errors. Solves #7.
2022-09-27 19:16:18 -03:00
7 changed files with 195 additions and 128 deletions

View file

@ -24,17 +24,19 @@ use std::path::Path;
use vento::{help, item}; use vento::{help, item};
fn main() -> Result<()> { fn main() -> Result<()> {
// Handles args in Drop
let args: Vec<String> = env::args().collect(); let args: Vec<String> = env::args().collect();
if args.len() >= 2 { if args.len() >= 2 {
if args[1].contains("--slot=") { if args[1].contains("--slot=") {
// Checks if the user has provided the long argument "--slot="
match args.len() { match args.len() {
4 => item::drop(&args[2], &args[1].as_str().replace("--slot=", ""), Path::new(&args[4]).to_path_buf())?, 4 => item::drop(&args[2], &args[1].as_str().replace("--slot=", ""), Path::new(&args[4]).to_path_buf())?,
3 => item::drop(&args[2], &args[1].as_str().replace("--slot=", ""), match env::current_dir() { 3 => item::drop(&args[2], &args[1].as_str().replace("--slot=", ""), match env::current_dir() {
Ok(dir) => dir, Ok(dir) => dir,
Err(_) => bail!("{}", "Vento was unable to detect your current directory. Have you configured your environment correctly?".red()) Err(_) => bail!("{}", "Vento was unable to detect your current directory. Have you configured your environment correctly?".red())
})?, })?,
2 => bail!("{}", "You need to specify a file".red()), 2 => bail!("{}", "You need to specify a file".red()),
_ => bail!("{}", "Too many arguments".red()), _ => bail!("{}", "Too many arguments".red()),
}; };
} else { } else {
match args[1].as_str() { match args[1].as_str() {
@ -43,23 +45,24 @@ fn main() -> Result<()> {
5 => item::drop(&args[3], &args[2], Path::new(&args[4]).to_path_buf())?, 5 => item::drop(&args[3], &args[2], Path::new(&args[4]).to_path_buf())?,
4 => item::drop(&args[3], &args[2], match env::current_dir() { 4 => item::drop(&args[3], &args[2], match env::current_dir() {
Ok(dir) => dir, Ok(dir) => dir,
Err(_) => bail!("{}", "Vento was unable to detect your current directory. Have you configured your environment correctly?".red()) Err(_) => bail!("{}", "Vento was unable to detect your current directory. Have you configured your environment correctly?".red())
})?, })?,
3 => bail!("{}", "You need to specify a file".red()), 3 => bail!("{}", "You need to specify a file".red()),
2 => bail!("{}", "You need to specify a slot".red()), 2 => bail!("{}", "You need to specify a slot".red()),
_ => bail!("{}", "Too many arguments".red()), _ => bail!("{}", "Too many arguments".red()),
}, },
_ => match args.len() { _ => match args.len() {
3 => item::drop(&args[1], &String::from("active"), Path::new(&args[2]).to_path_buf())?, 3 => item::drop(&args[1], &String::from("active"), Path::new(&args[2]).to_path_buf())?,
2 => item::drop(&args[1], &String::from("active"), match env::current_dir() { 2 => item::drop(&args[1], &String::from("active"), match env::current_dir() {
Ok(dir) => dir, Ok(dir) => dir,
Err(_) => bail!("{}", "Vento was unable to detect your current directory. Have you configured your environment correctly?".red()) Err(_) => bail!("{}", "Vento was unable to detect your current directory. Have you configured your environment correctly?".red())
})?, })?,
_ => bail!("{}", "Too many arguments".red()), _ => bail!("{}", "Too many arguments".red()),
}, },
} }
} }
} else { } else {
// If the user provides no arguments, Drop will display the help message.
help::drop()?; help::drop()?;
} }
Ok(()) Ok(())

View file

@ -23,30 +23,33 @@ use std::env;
use vento::{help, item}; use vento::{help, item};
fn main() -> Result<()> { fn main() -> Result<()> {
// Handles args in Vento
let args: Vec<String> = env::args().collect(); let args: Vec<String> = env::args().collect();
if args.len() >= 2 { if args.len() >= 2 {
if args[1].contains("--slot=") { if args[1].contains("--slot=") {
// Checks if the user has provided the long argument "--slot="
match args.len() { match args.len() {
3 => item::take(&args[2], &args[1].replace("--slot=", ""))?, 3 => item::take(&args[2], &args[1].replace("--slot=", ""))?,
2 => bail!("{}", "You need to specify a file".red()), 2 => bail!("{}", "You need to specify a file".red()),
_ => bail!("{}", "Too many arguments".red()), _ => bail!("{}", "Too many arguments".red()),
}; };
} else { } else {
match args[1].as_str() { match args[1].as_str() {
"--help" | "-h" => help::take()?, "--help" | "-h" => help::take()?,
"-s" => match args.len() { "-s" => match args.len() {
4 => item::take(&args[3], &args[2])?, 4 => item::take(&args[3], &args[2])?,
3 => bail!("{}", "You need to specify a file".red()), 3 => bail!("{}", "You need to specify a file".red()),
2 => bail!("{}", "You need to specify a slot".red()), 2 => bail!("{}", "You need to specify a slot".red()),
_ => bail!("{}", "Too many arguments".red()), _ => bail!("{}", "Too many arguments".red()),
}, },
_ => match args.len() { _ => match args.len() {
2 => item::take(&args[1], &String::from("active"))?, 2 => item::take(&args[1], &String::from("active"))?,
_ => bail!("{}", "Too many arguments".red()), _ => bail!("{}", "Too many arguments".red()),
}, },
} }
} }
} else { } else {
// If the user provides no arguments, Take will display the help message.
help::take()?; help::take()?;
} }
Ok(()) Ok(())

View file

@ -23,14 +23,16 @@ use std::env;
use vento::{help, inv}; use vento::{help, inv};
fn main() -> Result<()> { fn main() -> Result<()> {
// Handles args in Vento
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
if args[1].contains("--slot=") { if args[1].contains("--slot=") {
// Checks if the user has provided the long argument "--slot="
match args.len() { match args.len() {
3 => inv::list(&args[1].replace("--slot=", ""), &args[2])?, 3 => inv::list(&args[1].replace("--slot=", ""), &args[2])?,
2 => inv::list(&args[1].replace("--slot=", ""), "")?, 2 => inv::list(&args[1].replace("--slot=", ""), "")?,
_ => bail!("{}", "Too many arguments".red()), _ => bail!("{}", "Too many arguments".red()),
}; };
} else { } else {
match args[1].as_str() { match args[1].as_str() {
@ -40,14 +42,14 @@ fn main() -> Result<()> {
"-s" => match args.len() { "-s" => match args.len() {
4 => inv::list(&args[2], &args[3])?, 4 => inv::list(&args[2], &args[3])?,
3 => inv::list(&args[2], "")?, 3 => inv::list(&args[2], "")?,
2 => bail!("{}", "You need to specify a slot.".red()), 2 => bail!("{}", "You need to specify a slot.".red()),
_ => bail!("{}", "Too many arguments".red()), _ => bail!("{}", "Too many arguments".red()),
}, },
_ => inv::list("active", args[1].as_str())?, _ => inv::list("active", args[1].as_str())?,
} }
} }
} else { } else {
// If the user provides no commands, Vento will display the files in the active slot. // If the user provides no arguments, Vento will display the files in the active slot.
inv::list("active", "")?; inv::list("active", "")?;
} }
Ok(()) Ok(())

View file

@ -29,7 +29,7 @@ pub fn env_config() -> Result<Vec<PathBuf>> {
_ => PathBuf::new(), _ => PathBuf::new(),
}; };
if home == PathBuf::new() { if home == PathBuf::new() {
bail!("{}", "Vento was unable to detect your home folder. Have you configured your environment correctly?".red()); bail!("{}", "Vento was unable to detect your home folder. Have you configured your environment correctly?".red());
}; };
let vento_dir: PathBuf; let vento_dir: PathBuf;
let custom_dir = Path::new(&dir_config()?).to_path_buf(); let custom_dir = Path::new(&dir_config()?).to_path_buf();
@ -49,6 +49,7 @@ pub fn env_config() -> Result<Vec<PathBuf>> {
} }
fn dir_config() -> Result<String> { fn dir_config() -> Result<String> {
// Handles reading the config file or variables for Vento.
let mut result = String::new(); let mut result = String::new();
let mut config = match dirs::config_dir() { let mut config = match dirs::config_dir() {
Option::Some(dir) => dir, Option::Some(dir) => dir,

View file

@ -44,7 +44,7 @@ pub fn vento() -> Result<()> {
} }
pub fn take() -> Result<()> { pub fn take() -> Result<()> {
// A quick guide to move around in Vento // A quick guide to move around in Take
println!( println!(
"{}, a file grabber for Vento "{}, a file grabber for Vento
© 2022 Lux Aliaga. Licensed under GPLv3 © 2022 Lux Aliaga. Licensed under GPLv3
@ -63,7 +63,7 @@ pub fn take() -> Result<()> {
} }
pub fn drop() -> Result<()> { pub fn drop() -> Result<()> {
// A quick guide to move around in Vento // A quick guide to move around in Drop
println!( println!(
"{}, a file dropper for Vento "{}, a file dropper for Vento
© 2022 Lux Aliaga. Licensed under GPLv3 © 2022 Lux Aliaga. Licensed under GPLv3

View file

@ -36,7 +36,7 @@ pub fn init() -> Result<()> {
let _ = io::stdout().flush(); let _ = io::stdout().flush();
io::stdin() io::stdin()
.read_line(&mut answer) .read_line(&mut answer)
.context("Failed to read input")?; .context("Failed to read input")?;
match answer.as_str().trim() { match answer.as_str().trim() {
"y" | "Y" => fs::remove_dir_all(&ventodir)?, "y" | "Y" => fs::remove_dir_all(&ventodir)?,
_ => process::exit(0), _ => process::exit(0),
@ -49,31 +49,47 @@ pub fn init() -> Result<()> {
pub fn list(slot: &str, dir: &str) -> Result<()> { pub fn list(slot: &str, dir: &str) -> Result<()> {
// Lists files in inventory // Lists files in inventory
let ventodir = &common::env_config()?[0];
if !ventodir.is_dir() {
// Detects if Vento hasn't been initialized and bails if so
bail!(
"{}",
"Vento not initialized. Run \"vento -i\" to initialize Vento.".red()
);
}
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(),
}; };
let ventodir = &common::env_config()?[0];
if !ventodir.is_dir() {
bail!(
"❌ {}",
"Vento not initialized. Run \"vento -i\" to initialize Vento.".red()
);
}
if dir != "" { if dir != "" {
// Detects if the directory argument is not empty, and if so appends the path provided to the slot directory variable
slotdir = [&slotdir, &Path::new(dir).to_path_buf()].iter().collect(); slotdir = [&slotdir, &Path::new(dir).to_path_buf()].iter().collect();
} }
if dir.to_string().contains("..") { if dir.to_string().contains("..") {
bail!("❌ {}", "Cannot access parent.".red()); // Basically preventing from listing anything out of bounds. ls and dir exist for that
bail!("{}", "Cannot access parent.".red());
} }
if slotdir.is_dir() { if !slotdir.is_dir() {
// Detects if the consulted slot or directory exists
bail!(
"{}",
format!(
"No such slot or directory. Valid slots are {} and {}.",
"active".green().bold(),
"inactive".blue().bold()
)
.red()
);
};
if fs::read_dir(&slotdir).unwrap().count() == 0 { if fs::read_dir(&slotdir).unwrap().count() == 0 {
// Detects if the slot or directory has any contents
println!( println!(
"🗃️ {}", "🗃️ {}",
format!( format!(
@ -95,7 +111,6 @@ pub fn list(slot: &str, dir: &str) -> Result<()> {
.green() .green()
); );
} else { } else {
// Checks if inventory selected exists
println!( println!(
"🗃️ {}", "🗃️ {}",
format!( format!(
@ -148,17 +163,6 @@ pub fn list(slot: &str, dir: &str) -> Result<()> {
); );
} }
} }
} else {
println!(
"❌ {}",
format!(
"No such slot or directory. Valid slots are {} and {}.",
"active".green().bold(),
"inactive".blue().bold()
)
.red()
);
}
Ok(()) Ok(())
} }
@ -171,7 +175,7 @@ pub fn switch() -> Result<()> {
.iter() .iter()
.collect(); .collect();
let rename_error = "❌ Vento was unable to switch slots. Try running vento init and try again"; let rename_error = "Vento was unable to switch slots. Try running \"vento -i\" and try again";
fs::rename(&active, &temp).context(rename_error)?; fs::rename(&active, &temp).context(rename_error)?;
fs::rename(&inactive, &active).context(rename_error)?; fs::rename(&inactive, &active).context(rename_error)?;
@ -182,11 +186,11 @@ pub fn switch() -> Result<()> {
} }
fn create_slots() -> Result<()> { 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];
let initialize_error = "Vento was unable to initalize. Do you have the correct permissions"; let initialize_error = "Vento was unable to initalize. Do you have the correct permissions?";
fs::create_dir_all(active).context(initialize_error)?; fs::create_dir_all(active).context(initialize_error)?;
fs::create_dir_all(inactive).context(initialize_error)?; fs::create_dir_all(inactive).context(initialize_error)?;

View file

@ -26,39 +26,90 @@ use std::path::{Path, PathBuf};
pub fn take(file: &String, slot: &String) -> Result<()> { pub fn take(file: &String, slot: &String) -> Result<()> {
// Takes a file or directory // Takes a file or directory
let ventodir = &common::env_config()?[0];
if !ventodir.is_dir() {
// Detects if Vento hasn't been initialized and bails if so
bail!(
"{}",
"Vento not initialized. Run \"vento -i\" to initialize Vento.".red()
);
};
let slotdir: PathBuf = match slot.as_str() { let slotdir: PathBuf = match slot.as_str() {
"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(),
}; };
if !slotdir.is_dir() {
// Detects if the slot provided exists
bail!(
"{}",
format!(
"No such slot. Valid slots are {} and {}.",
"active".green().bold(),
"inactive".blue().bold()
)
.red()
);
};
let sourcepath: PathBuf = Path::new(&file).to_path_buf(); let sourcepath: PathBuf = Path::new(&file).to_path_buf();
let destpath: PathBuf = [&slotdir, &Path::new(file).to_path_buf()].iter().collect(); let destpath: PathBuf = [&slotdir, &Path::new(file).to_path_buf()].iter().collect();
if Path::exists(&destpath) { if Path::exists(&destpath) {
// Checks if there's a file with the same name in the inventory.
bail!( bail!(
"❌ {}", "{}",
"A file with the same name already exists in your inventory!".red() "A file with the same name already exists in your inventory!".red()
); );
} else if sourcepath.is_file() | sourcepath.is_symlink() { }
fs::copy(&file, &destpath).expect("❌ Vento was unable to copy the file.");
fs::remove_file(&file).expect("❌ Vento was unable to remove the file."); if sourcepath.is_file() | sourcepath.is_symlink() {
// Checks the path's file type
fs::copy(&file, &destpath).context("Vento was unable to copy the file.")?;
fs::remove_file(&file).context("Vento was unable to remove the file.")?;
} else if sourcepath.is_dir() { } else if sourcepath.is_dir() {
let options = CopyOptions::new(); let options = CopyOptions::new();
move_dir(&file, &slotdir, &options).expect("❌ Vento was unable to move the directory."); move_dir(&file, &slotdir, &options).context("Vento was unable to move the directory.")?;
} else { } else {
println!("{}", "No such file or directory.".red()); bail!("{}", "No such file or directory.".red());
} }
Ok(()) Ok(())
} }
pub fn drop(file: &String, slot: &String, dest: PathBuf) -> Result<()> { pub fn drop(file: &String, slot: &String, dest: PathBuf) -> Result<()> {
// Drops a file or directory // Drops a file or directory
let ventodir = &common::env_config()?[0];
if !ventodir.is_dir() {
// Detects if Vento hasn't been initialized and bails if so
bail!(
"{}",
"Vento not initialized. Run \"vento -i\" to initialize Vento.".red()
);
};
let slotdir: PathBuf = match slot.as_str() { let slotdir: PathBuf = match slot.as_str() {
"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(),
}; };
if !slotdir.is_dir() {
// Detects if the slot provided exists
bail!(
"{}",
format!(
"No such slot. Valid slots are {} and {}.",
"active".green().bold(),
"inactive".blue().bold()
)
.red()
);
};
let sourcepath: PathBuf = [&slotdir, &Path::new(file).to_path_buf()].iter().collect(); let sourcepath: PathBuf = [&slotdir, &Path::new(file).to_path_buf()].iter().collect();
let destpath: PathBuf = [ let destpath: PathBuf = [
Path::new(&dest).to_path_buf(), Path::new(&dest).to_path_buf(),
@ -68,18 +119,21 @@ pub fn drop(file: &String, slot: &String, dest: PathBuf) -> Result<()> {
.collect(); .collect();
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 // Checks if there's a file with the same name in the destination path.
bail!("❌ {}", "A file with the same name already exists in the destination! Try renaming it or dropping this file somewhere else.".red()); bail!("{}", "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).context("❌ Vento was unable to copy the file.")?;
fs::remove_file(&sourcepath).context("❌ Vento was unable to remove the file.")?; if sourcepath.is_file() | sourcepath.is_symlink() {
// Checks the path's file type
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() { } 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."); .context("Vento was unable to move the directory.")?;
} else { } else {
bail!("{}", "No such file or directory.".red()); bail!("{}", "No such file or directory.".red());
} }
Ok(()) Ok(())
} }