Compare commits

...
This repository has been archived on 2026-09-13. You can view files and clone it, but cannot push or open issues or pull requests.

1 Commits

Author SHA1 Message Date
Dandaedre 47c0e64a73 Rewrites the priorities.
Adds two helper function to get the path&name os Pathbuf
2023-05-28 19:11:29 +02:00
4 changed files with 89 additions and 59 deletions

12
TODO.md
View File

@ -1,18 +1,16 @@
## TODO ## TODO
[ ] Benchmarks
[ ] Better use of file modes [ ] Better use of file modes
[ ] Find a solution for the .badpocalypse [ ] Find a solution for the .badpocalypse
[ ] Edit args only
[ ] Case sensitivity windows [ ] Case sensitivity windows
[ ] Use Ok for results instead of prints
[ ] Use priority instead of a cursed match statement
[ ] Have a method to get name, path and all with a custom error on unwrap
### Currently working on ### Currently working on
[ ] Have an actual human give feedback on the error name readability [ ] Use Ok for results instead of prints
[ ] Edit args only
## Finished ## Finished
[*] Add some examples with --example [*] Add some examples with --example
[*] Use priority instead of a cursed match statement
[*] Have a method to get name, path and all with a custom error on unwrap
## Posponed or rendered useless ## Posponed or rendered useless
[x] Chain the methods when possible with result ? [x] Chain the methods when possible with result ?
@ -21,3 +19,5 @@
[ ] Document non coverage [ ] Document non coverage
[ ] Correct the newline problem (with toml ?) [ ] Correct the newline problem (with toml ?)
[*] Error: Delete, unclear ? [*] Error: Delete, unclear ?
[ ] Benchmarks
[-] Have an actual human give feedback on the error name readability

View File

@ -55,29 +55,30 @@ pub fn execute_parsed_cli(cli: Cli) -> Result<(), errors::SnippetError> {
/// Populate a logical vec of succesive actions to perform depending on arguments /// Populate a logical vec of succesive actions to perform depending on arguments
/// even when the arguments don't make sense /// even when the arguments don't make sense
/// Note that this function return a Vec<Actions> to be done in sucession even
/// if there is no such usage (for now)
fn populate_actions(cli: &Cli) -> Vec<Actions> { fn populate_actions(cli: &Cli) -> Vec<Actions> {
let mut actions = Vec::new(); let mut actions = Vec::new();
// Priority is left to right
match ( match (
cli.path,
cli.create,
cli.edit,
cli.edit_all,
cli.delete,
&cli.rename,
cli.list,
cli.example, cli.example,
cli.delete,
cli.list,
cli.path,
cli.edit_all,
cli.edit,
&cli.rename,
cli.create,
) { ) {
(true, _, _, _, false, _, false, false) => actions.push(Actions::Find), (true, _, _, _, _, _, _, _) => actions.push(Actions::Example),
(_, false, false, true, false, _, false, false) => actions.push(Actions::EditAll), (_, true, _, _, _, _, _, _) => actions.push(Actions::Delete),
(_, true, _, true, false, _, false, false) => actions.push(Actions::EditAll), (_, _, true, _, _, _, _, _) => actions.push(Actions::List),
(_, true, false, false, false, _, false, false) => actions.push(Actions::Create), (_, _, _, true, _, _, _, _) => actions.push(Actions::Find),
(_, false, true, _, false, _, false, false) => actions.push(Actions::Edit), (_, _, _, _, true, _, _, _) => actions.push(Actions::EditAll),
(_, true, true, false, false, _, false, false) => actions.push(Actions::Edit), (_, _, _, _, _, true, _, _) => actions.push(Actions::Edit),
(false, false, false, false, false, None, false, false) => actions.push(Actions::Show), (_, _, _, _, _, _, Some(_), _) => actions.push(Actions::Rename),
(_, _, _, _, true, _, false, false) => actions.push(Actions::Delete), (_, _, _, _, _, _, _, true) => actions.push(Actions::Create),
(_, _, _, _, _, Some(_), false, false) => actions.push(Actions::Rename), (_, _, _, _, _, _, _, _) => actions.push(Actions::Show),
(_, _, _, _, _, _, true, false) => actions.push(Actions::List),
(_, _, _, _, _, _, _, true) => actions.push(Actions::Example),
} }
actions actions
} }
@ -115,7 +116,10 @@ mod test {
vec![Actions::Delete] vec![Actions::Delete]
), ),
(false_cli!("snp", "name", "-E"), vec![Actions::EditAll]), (false_cli!("snp", "name", "-E"), vec![Actions::EditAll]),
(false_cli!("snp", "name", "-E", "-e"), vec![Actions::Edit]), (
false_cli!("snp", "name", "-E", "-e"),
vec![Actions::EditAll]
),
( (
false_cli!("snp", "name", "-E", "-e", "-c"), false_cli!("snp", "name", "-E", "-e", "-c"),
vec![Actions::EditAll] vec![Actions::EditAll]
@ -140,7 +144,7 @@ mod test {
), ),
( (
false_cli!("snp", "name", "-c", "-r", "new_name", "-f"), false_cli!("snp", "name", "-c", "-r", "new_name", "-f"),
vec![Actions::Create] vec![Actions::Rename]
), ),
(false_cli!("snp", "-l"), vec![Actions::List]), (false_cli!("snp", "-l"), vec![Actions::List]),
(false_cli!("snp", "--example"), vec![Actions::Example]), (false_cli!("snp", "--example"), vec![Actions::Example]),

View File

@ -2,6 +2,7 @@
#![cfg(not(tarpaulin_include))] #![cfg(not(tarpaulin_include))]
use std::{error, fmt, path::PathBuf}; use std::{error, fmt, path::PathBuf};
use crate::wrapper_functions::{self, path_to_name};
/// Snippet error, general error wrapper for the Snippet module /// Snippet error, general error wrapper for the Snippet module
/// All error are wrapper with more information available with the source() method /// All error are wrapper with more information available with the source() method
#[derive(Debug)] #[derive(Debug)]
@ -26,6 +27,10 @@ pub enum SnippetError {
ReparsingError, ReparsingError,
/// The custom formatter coulnd't access an index /// The custom formatter coulnd't access an index
IndexError(usize), IndexError(usize),
/// An error occured while trying to convert an OsStr to a str
UtfError(std::ffi::OsString),
/// An error prevented to convert a path to a string
PathError(PathBuf),
} }
impl fmt::Display for SnippetError { impl fmt::Display for SnippetError {
@ -39,22 +44,24 @@ impl fmt::Display for SnippetError {
} }
SnippetError::NotFound(ref p) => write!( SnippetError::NotFound(ref p) => write!(
f, f,
"The Snippet {} doesn't exists. Use -c to create it and/or -E to edit it.",p.file_name().unwrap().to_str().unwrap(), "The Snippet {} doesn't exists. Use -c to create it and/or -E to edit it.", wrapper_functions::path_to_name(p).unwrap(),
), ),
SnippetError::NotFoundNoRetryError(ref p) => { SnippetError::NotFoundNoRetryError(ref p) => {
write!( write!(
f, f,
"The Snippet {} doen't exists. Use -c to create it.", "The Snippet {} doen't exists. Use -c to create it.",
p.file_name().unwrap().to_str().unwrap(), path_to_name(p).unwrap(),
) )
} }
SnippetError::FoundNoEraseError(ref p) => write!( SnippetError::FoundNoEraseError(ref p) => write!(
f, f,
"The Snippet {} already exists. Use -f/--force to overwrite it.", "The Snippet {} already exists. Use -f/--force to overwrite it.",
p.file_name().unwrap().to_str().unwrap(), path_to_name(p).unwrap(),
), ),
SnippetError::ReparsingError => write!(f,"The Snippet couldn't be re-parsed, it might be caused by a bad value in your edit. \nThe snipped was saved as a raw file instead but cant be used as is."), SnippetError::ReparsingError => write!(f,"The Snippet couldn't be re-parsed, it might be caused by a bad value in your edit. \nThe snipped was saved as a raw file instead but cant be used as is."),
SnippetError::IndexError(ref i) => write!(f,"An error occured while trying to access the index {} of the given arguments.\nThe default arguments for this command likely do not support {} arguments.",i,i+1), SnippetError::IndexError(ref i) => write!(f,"An error occured while trying to access the index {} of the given arguments.\nThe default arguments for this command likely do not support {} arguments.",i,i+1),
SnippetError::UtfError(ref p) => write!(f, "An error occured while converting the path {:?} to a string.", p),
SnippetError::PathError(ref p) => write!(f,"An error occured while trying to convert the path {:?} to an OsStr.",p),
} }
} }
} }
@ -74,6 +81,8 @@ impl error::Error for SnippetError {
SnippetError::FoundNoEraseError(_) => None, SnippetError::FoundNoEraseError(_) => None,
SnippetError::ReparsingError => None, SnippetError::ReparsingError => None,
SnippetError::IndexError(_) => None, SnippetError::IndexError(_) => None,
SnippetError::UtfError(_) => None,
SnippetError::PathError(_) => None,
} }
} }
} }

View File

@ -9,6 +9,7 @@ use edit::edit;
use std::fs::{self, create_dir_all}; use std::fs::{self, create_dir_all};
use std::io::{self, read_to_string, Write}; use std::io::{self, read_to_string, Write};
use std::path::Path;
use std::{env, fs::File, path::PathBuf}; use std::{env, fs::File, path::PathBuf};
use crate::errors::SnippetError; use crate::errors::SnippetError;
@ -25,7 +26,7 @@ pub fn locate_snippet(cli: &Cli) -> Result<(), SnippetError> {
println!( println!(
"The snippet {} is located at \"{}\"", "The snippet {} is located at \"{}\"",
cli.snippet.as_ref().unwrap(), cli.snippet.as_ref().unwrap(),
p.as_os_str().to_str().unwrap() path_to_str(&p)?,
); );
Ok(()) Ok(())
} }
@ -55,10 +56,7 @@ pub fn create_snippet(cli: &Cli) -> Result<(), SnippetError> {
FileStatus::NotFound(p) => (File::create(&p)?, p), // Create a new snippet FileStatus::NotFound(p) => (File::create(&p)?, p), // Create a new snippet
}; };
snp.save_in(&f)?; snp.save_in(&f)?;
println!( println!("The snippet {} was created successfully", path_to_str(&p)?,);
"The snippet {} was created successfully",
p.as_os_str().to_str().unwrap()
);
Ok(()) Ok(())
} }
@ -130,10 +128,7 @@ pub fn edit_snippet(cli: &Cli) -> Result<(), SnippetError> {
snp.edit()?; snp.edit()?;
snp.write_over(&p)?; snp.write_over(&p)?;
println!( println!("The snippet {} was succesfully saved", path_to_name(&p)?,);
"The snippet {} was succesfully saved",
p.file_name().unwrap().to_str().unwrap()
);
Ok(()) Ok(())
} }
@ -169,7 +164,7 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> {
snp.write_over(&origin_p)?; snp.write_over(&origin_p)?;
println!( println!(
"The snippet {} was succesfully saved", "The snippet {} was succesfully saved",
origin_p.file_name().unwrap().to_str().unwrap() path_to_name(&origin_p)?,
); );
Ok(()) Ok(())
} else { } else {
@ -182,7 +177,7 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> {
// No erasing/overriting // No erasing/overriting
println!( println!(
"The snippet could not be saved as {}.yaml, as this Snippet already exists. The Snippet will be saved under it's original name name: {}", "The snippet could not be saved as {}.yaml, as this Snippet already exists. The Snippet will be saved under it's original name name: {}",
snp.name,origin_p.file_name().unwrap().to_str().unwrap() snp.name,path_to_name(&origin_p)?
); );
(File::create(&origin_p)?, origin_p) (File::create(&origin_p)?, origin_p)
} }
@ -192,7 +187,7 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> {
snp.save_in(&dest_f)?; snp.save_in(&dest_f)?;
println!( println!(
"The snippet was successfuly saved in {}", "The snippet was successfuly saved in {}",
dest_p.into_os_string().to_str().unwrap() path_to_str(&dest_p)?,
); );
Ok(()) Ok(())
} }
@ -206,7 +201,7 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> {
println!( println!(
"The snippet was saved under {} in your config", "The snippet was saved under {} in your config",
origin_p.file_name().unwrap().to_str().unwrap() path_to_name(&origin_p)?
); );
Err(SnippetError::ReparsingError) Err(SnippetError::ReparsingError)
} }
@ -216,21 +211,22 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> {
pub fn list_snippets(_cli: &Cli) -> Result<(), SnippetError> { pub fn list_snippets(_cli: &Cli) -> Result<(), SnippetError> {
let dirpath = config_folder()?; let dirpath = config_folder()?;
let paths = fs::read_dir(&dirpath).unwrap(); let paths = fs::read_dir(&dirpath).unwrap();
if let Some(name) = dirpath.parent() {
if let Some(str) = name.to_str() {
println!( println!(
"Snippet list at {}:\n {}", "Snippet list at {}:\n {}",
dirpath.parent().unwrap().to_str().unwrap(), str,
paths paths
.map(|p| p .map(|p| path_to_name(&p.unwrap().path()).unwrap().to_owned())
.unwrap()
.path()
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_owned())
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(", ") .join(", ")
); )
} else {
return Err(SnippetError::PathError(name.to_path_buf()));
}
} else {
return Err(SnippetError::PathError(dirpath));
}
Ok(()) Ok(())
} }
@ -269,7 +265,6 @@ pub fn delete_snippet(cli: &Cli) -> Result<(), SnippetError> {
std::fs::remove_file(&path)?; std::fs::remove_file(&path)?;
println!( println!(
"The snippet \"{}\" was successfully deleted.", "The snippet \"{}\" was successfully deleted.",
// path.file_name().unwrap().to_str().unwrap()
cli.snippet.as_ref().unwrap() cli.snippet.as_ref().unwrap()
); );
Ok(()) Ok(())
@ -349,6 +344,28 @@ pub fn config_folder() -> Result<PathBuf, SnippetError> {
Ok(dir) Ok(dir)
} }
/// Return the name of a path
pub fn path_to_name(path: &Path) -> Result<&str, SnippetError> {
if let Some(name) = path.file_name() {
if let Some(str) = name.to_str() {
Ok(str)
} else {
Err(SnippetError::UtfError(name.to_owned()))
}
} else {
Err(SnippetError::PathError(path.to_owned()))
}
}
/// Return the string associated with a path
pub fn path_to_str(path: &Path) -> Result<&str, SnippetError> {
if let Some(name) = path.to_str() {
Ok(name)
} else {
Err(SnippetError::PathError(path.to_owned()))
}
}
#[cfg(test)] #[cfg(test)]
pub mod test { pub mod test {
use super::*; use super::*;