1
0
Fork 0
mirror of https://git.sr.ht/~nixgoat/vento synced 2024-11-21 22:33:01 +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};
fn main() -> Result<()> {
// Handles args in Drop
let args: Vec<String> = env::args().collect();
if args.len() >= 2 {
if args[1].contains("--slot=") {
// Checks if the user has provided the long argument "--slot="
match args.len() {
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() {
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()),
_ => bail!("{}", "Too many arguments".red()),
2 => bail!("{}", "You need to specify a file".red()),
_ => bail!("{}", "Too many arguments".red()),
};
} else {
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())?,
4 => item::drop(&args[3], &args[2], match env::current_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()),
2 => bail!("{}", "You need to specify a slot".red()),
_ => bail!("{}", "Too many arguments".red()),
3 => bail!("{}", "You need to specify a file".red()),
2 => bail!("{}", "You need to specify a slot".red()),
_ => bail!("{}", "Too many arguments".red()),
},
_ => match args.len() {
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() {
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 {
// If the user provides no arguments, Drop will display the help message.
help::drop()?;
}
Ok(())

View file

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

View file

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

View file

@ -29,7 +29,7 @@ pub fn env_config() -> Result<Vec<PathBuf>> {
_ => 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 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> {
// Handles reading the config file or variables for Vento.
let mut result = String::new();
let mut config = match dirs::config_dir() {
Option::Some(dir) => dir,

View file

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

View file

@ -36,7 +36,7 @@ pub fn init() -> Result<()> {
let _ = io::stdout().flush();
io::stdin()
.read_line(&mut answer)
.context("Failed to read input")?;
.context("Failed to read input")?;
match answer.as_str().trim() {
"y" | "Y" => fs::remove_dir_all(&ventodir)?,
_ => process::exit(0),
@ -49,108 +49,36 @@ pub fn init() -> Result<()> {
pub fn list(slot: &str, dir: &str) -> Result<()> {
// 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 {
"active" | "a" => common::env_config()?[1].clone(),
"inactive" | "i" => common::env_config()?[2].clone(),
_ => 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 != "" {
// 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();
}
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 fs::read_dir(&slotdir).unwrap().count() == 0 {
println!(
"🗃️ {}",
format!(
"No files in {}{}.",
match slot {
"active" => format!("{}", slot).bold(),
"inactive" | _ => format!("{}", slot).blue().bold(),
},
if dir != "" {
if cfg!(windows) {
format!("\\{}", dir.to_string())
} else {
format!("/{}", dir.to_string())
}
} else {
"".to_string()
}
)
.green()
);
} else {
// Checks if inventory selected exists
println!(
"🗃️ {}",
format!(
"Files in {}{} ({}):",
match slot {
"active" => format!("{}", slot).bold(),
"inactive" | _ => format!("{}", slot).blue().bold(),
},
if dir != "" {
if cfg!(windows) {
format!("\\{}", dir.to_string())
} else {
format!("/{}", dir.to_string())
}
} else {
" inventory".to_string()
},
format!("{}", fs::read_dir(&slotdir).unwrap().count())
.white()
.bold()
)
.green()
);
for file in fs::read_dir(&slotdir).unwrap() {
let file = file.unwrap().path();
println!(
" - [{}] {}{}",
if file.clone().is_dir() {
"D".blue()
} else if file.clone().is_symlink() {
"S".yellow()
} else {
"F".green()
},
file.clone()
.file_name()
.unwrap()
.to_os_string()
.into_string()
.unwrap(),
if file.clone().is_file() {
format!(
" ({}B)",
SizeFormatterBinary::new(file.clone().metadata().unwrap().len())
)
} else {
format!("")
}
);
}
}
} else {
println!(
"❌ {}",
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(),
@ -158,6 +86,82 @@ pub fn list(slot: &str, dir: &str) -> Result<()> {
)
.red()
);
};
if fs::read_dir(&slotdir).unwrap().count() == 0 {
// Detects if the slot or directory has any contents
println!(
"🗃️ {}",
format!(
"No files in {}{}.",
match slot {
"active" => format!("{}", slot).bold(),
"inactive" | _ => format!("{}", slot).blue().bold(),
},
if dir != "" {
if cfg!(windows) {
format!("\\{}", dir.to_string())
} else {
format!("/{}", dir.to_string())
}
} else {
"".to_string()
}
)
.green()
);
} else {
println!(
"🗃️ {}",
format!(
"Files in {}{} ({}):",
match slot {
"active" => format!("{}", slot).bold(),
"inactive" | _ => format!("{}", slot).blue().bold(),
},
if dir != "" {
if cfg!(windows) {
format!("\\{}", dir.to_string())
} else {
format!("/{}", dir.to_string())
}
} else {
" inventory".to_string()
},
format!("{}", fs::read_dir(&slotdir).unwrap().count())
.white()
.bold()
)
.green()
);
for file in fs::read_dir(&slotdir).unwrap() {
let file = file.unwrap().path();
println!(
" - [{}] {}{}",
if file.clone().is_dir() {
"D".blue()
} else if file.clone().is_symlink() {
"S".yellow()
} else {
"F".green()
},
file.clone()
.file_name()
.unwrap()
.to_os_string()
.into_string()
.unwrap(),
if file.clone().is_file() {
format!(
" ({}B)",
SizeFormatterBinary::new(file.clone().metadata().unwrap().len())
)
} else {
format!("")
}
);
}
}
Ok(())
}
@ -171,7 +175,7 @@ pub fn switch() -> Result<()> {
.iter()
.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(&inactive, &active).context(rename_error)?;
@ -182,11 +186,11 @@ pub fn switch() -> 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 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(inactive).context(initialize_error)?;

View file

@ -26,39 +26,90 @@ use std::path::{Path, PathBuf};
pub fn take(file: &String, slot: &String) -> Result<()> {
// 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() {
"active" | "a" => common::env_config()?[1].clone(),
"inactive" | "i" => common::env_config()?[2].clone(),
_ => 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 destpath: PathBuf = [&slotdir, &Path::new(file).to_path_buf()].iter().collect();
if Path::exists(&destpath) {
// Checks if there's a file with the same name in the inventory.
bail!(
"❌ {}",
"{}",
"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() {
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 {
println!("{}", "No such file or directory.".red());
bail!("{}", "No such file or directory.".red());
}
Ok(())
}
pub fn drop(file: &String, slot: &String, dest: PathBuf) -> Result<()> {
// 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() {
"active" | "a" => common::env_config()?[1].clone(),
"inactive" | "i" => common::env_config()?[2].clone(),
_ => 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 destpath: PathBuf = [
Path::new(&dest).to_path_buf(),
@ -68,18 +119,21 @@ pub fn drop(file: &String, slot: &String, dest: PathBuf) -> Result<()> {
.collect();
if Path::exists(&destpath) {
// HAHA YANDEREDEV MOMENT. This checks what method to use for the file/directory the user has picked
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.")?;
// 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());
}
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() {
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.");
.context("Vento was unable to move the directory.")?;
} else {
bail!("{}", "No such file or directory.".red());
bail!("{}", "No such file or directory.".red());
}
Ok(())
}