diff --git a/TODO.md b/TODO.md index fcc3252..fba854c 100644 --- a/TODO.md +++ b/TODO.md @@ -1,18 +1,16 @@ ## TODO - [ ] Benchmarks [ ] Better use of file modes [ ] Find a solution for the .badpocalypse - [ ] Edit args only [ ] 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 - [ ] Have an actual human give feedback on the error name readability + [ ] Use Ok for results instead of prints + [ ] Edit args only ## Finished [*] 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 [x] Chain the methods when possible with result ? @@ -20,4 +18,6 @@ [ ] Change all uncatchables errors to expect to be more helpful or change them to better errors [ ] Document non coverage [ ] Correct the newline problem (with toml ?) - [*] Error: Delete, unclear ? \ No newline at end of file + [*] Error: Delete, unclear ? + [ ] Benchmarks + [-] Have an actual human give feedback on the error name readability diff --git a/src/actions.rs b/src/actions.rs index 0052612..16fa731 100644 --- a/src/actions.rs +++ b/src/actions.rs @@ -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 /// even when the arguments don't make sense +/// Note that this function return a Vec to be done in sucession even +/// if there is no such usage (for now) fn populate_actions(cli: &Cli) -> Vec { let mut actions = Vec::new(); + // Priority is left to right match ( - cli.path, - cli.create, - cli.edit, - cli.edit_all, - cli.delete, - &cli.rename, - cli.list, 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), - (_, false, false, true, false, _, false, false) => actions.push(Actions::EditAll), - (_, true, _, true, false, _, false, false) => actions.push(Actions::EditAll), - (_, true, false, false, false, _, false, false) => actions.push(Actions::Create), - (_, false, true, _, false, _, false, false) => actions.push(Actions::Edit), - (_, true, true, false, false, _, false, false) => actions.push(Actions::Edit), - (false, false, false, false, false, None, false, false) => actions.push(Actions::Show), - (_, _, _, _, true, _, false, false) => actions.push(Actions::Delete), - (_, _, _, _, _, Some(_), false, false) => actions.push(Actions::Rename), - (_, _, _, _, _, _, true, false) => actions.push(Actions::List), - (_, _, _, _, _, _, _, true) => actions.push(Actions::Example), + (true, _, _, _, _, _, _, _) => actions.push(Actions::Example), + (_, true, _, _, _, _, _, _) => actions.push(Actions::Delete), + (_, _, true, _, _, _, _, _) => actions.push(Actions::List), + (_, _, _, true, _, _, _, _) => actions.push(Actions::Find), + (_, _, _, _, true, _, _, _) => actions.push(Actions::EditAll), + (_, _, _, _, _, true, _, _) => actions.push(Actions::Edit), + (_, _, _, _, _, _, Some(_), _) => actions.push(Actions::Rename), + (_, _, _, _, _, _, _, true) => actions.push(Actions::Create), + (_, _, _, _, _, _, _, _) => actions.push(Actions::Show), } actions } @@ -115,7 +116,10 @@ mod test { vec![Actions::Delete] ), (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"), vec![Actions::EditAll] @@ -140,7 +144,7 @@ mod test { ), ( 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", "--example"), vec![Actions::Example]), diff --git a/src/errors.rs b/src/errors.rs index 0eacd0f..fb1e04c 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -2,6 +2,7 @@ #![cfg(not(tarpaulin_include))] use std::{error, fmt, path::PathBuf}; +use crate::wrapper_functions::{self, path_to_name}; /// Snippet error, general error wrapper for the Snippet module /// All error are wrapper with more information available with the source() method #[derive(Debug)] @@ -26,6 +27,10 @@ pub enum SnippetError { ReparsingError, /// The custom formatter coulnd't access an index 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 { @@ -39,22 +44,24 @@ impl fmt::Display for SnippetError { } SnippetError::NotFound(ref p) => write!( 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) => { write!( f, "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!( f, "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::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::ReparsingError => None, SnippetError::IndexError(_) => None, + SnippetError::UtfError(_) => None, + SnippetError::PathError(_) => None, } } } diff --git a/src/wrapper_functions.rs b/src/wrapper_functions.rs index c87966b..d136e80 100644 --- a/src/wrapper_functions.rs +++ b/src/wrapper_functions.rs @@ -9,6 +9,7 @@ use edit::edit; use std::fs::{self, create_dir_all}; use std::io::{self, read_to_string, Write}; +use std::path::Path; use std::{env, fs::File, path::PathBuf}; use crate::errors::SnippetError; @@ -25,7 +26,7 @@ pub fn locate_snippet(cli: &Cli) -> Result<(), SnippetError> { println!( "The snippet {} is located at \"{}\"", cli.snippet.as_ref().unwrap(), - p.as_os_str().to_str().unwrap() + path_to_str(&p)?, ); Ok(()) } @@ -55,10 +56,7 @@ pub fn create_snippet(cli: &Cli) -> Result<(), SnippetError> { FileStatus::NotFound(p) => (File::create(&p)?, p), // Create a new snippet }; snp.save_in(&f)?; - println!( - "The snippet {} was created successfully", - p.as_os_str().to_str().unwrap() - ); + println!("The snippet {} was created successfully", path_to_str(&p)?,); Ok(()) } @@ -130,10 +128,7 @@ pub fn edit_snippet(cli: &Cli) -> Result<(), SnippetError> { snp.edit()?; snp.write_over(&p)?; - println!( - "The snippet {} was succesfully saved", - p.file_name().unwrap().to_str().unwrap() - ); + println!("The snippet {} was succesfully saved", path_to_name(&p)?,); Ok(()) } @@ -169,7 +164,7 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> { snp.write_over(&origin_p)?; println!( "The snippet {} was succesfully saved", - origin_p.file_name().unwrap().to_str().unwrap() + path_to_name(&origin_p)?, ); Ok(()) } else { @@ -182,7 +177,7 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> { // No erasing/overriting 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: {}", - snp.name,origin_p.file_name().unwrap().to_str().unwrap() + snp.name,path_to_name(&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)?; println!( "The snippet was successfuly saved in {}", - dest_p.into_os_string().to_str().unwrap() + path_to_str(&dest_p)?, ); Ok(()) } @@ -206,7 +201,7 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> { println!( "The snippet was saved under {} in your config", - origin_p.file_name().unwrap().to_str().unwrap() + path_to_name(&origin_p)? ); Err(SnippetError::ReparsingError) } @@ -216,21 +211,22 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> { pub fn list_snippets(_cli: &Cli) -> Result<(), SnippetError> { let dirpath = config_folder()?; let paths = fs::read_dir(&dirpath).unwrap(); - println!( - "Snippet list at {}:\n {}", - dirpath.parent().unwrap().to_str().unwrap(), - paths - .map(|p| p - .unwrap() - .path() - .file_name() - .unwrap() - .to_str() - .unwrap() - .to_owned()) - .collect::>() - .join(", ") - ); + if let Some(name) = dirpath.parent() { + if let Some(str) = name.to_str() { + println!( + "Snippet list at {}:\n {}", + str, + paths + .map(|p| path_to_name(&p.unwrap().path()).unwrap().to_owned()) + .collect::>() + .join(", ") + ) + } else { + return Err(SnippetError::PathError(name.to_path_buf())); + } + } else { + return Err(SnippetError::PathError(dirpath)); + } Ok(()) } @@ -269,7 +265,6 @@ pub fn delete_snippet(cli: &Cli) -> Result<(), SnippetError> { std::fs::remove_file(&path)?; println!( "The snippet \"{}\" was successfully deleted.", - // path.file_name().unwrap().to_str().unwrap() cli.snippet.as_ref().unwrap() ); Ok(()) @@ -349,6 +344,28 @@ pub fn config_folder() -> Result { 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)] pub mod test { use super::*;