From 8e5d6a0e819a5b47f79f8f63562d3272410ed258 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 21 May 2023 18:23:04 +0200 Subject: [PATCH] Adds and tests locate and edit --- TODO.md | 8 ++-- src/errors.rs | 24 +++++----- src/wrapper_functions.rs | 95 ++++++++++++++++++++++------------------ 3 files changed, 67 insertions(+), 60 deletions(-) diff --git a/TODO.md b/TODO.md index cd36001..c50f5c8 100644 --- a/TODO.md +++ b/TODO.md @@ -17,7 +17,7 @@ [ ] Test populate_actions [ ] Coverage [ ] Remake all Snippet methods - [ ] + [ ] save_as => save a snippet in a file desc [ ] Chain the methods when possible with result ? [ ] Change all uncatchables errors to expect to be more helpful or change them to better errors @@ -26,9 +26,9 @@ [ ] Remake all helper functions [*] locate_snippet [*] create_snippet - [*] edit_snippet - [*] edit_whole_snippet - [ ] print_snippet + [-] edit_snippet + [-] edit_whole_snippet + [x] print_snippet ## Finished diff --git a/src/errors.rs b/src/errors.rs index a046f47..2700d25 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -20,13 +20,17 @@ pub enum SnippetError { ExistsError(std::io::Error), /// The file doen't exist and no creation was asked NotFoundNoRetryError(PathBuf), + /// The snippet was found but shouldn't be erased because of flags + FoundNoEraseError(PathBuf), + // /// An error occured while handling file operations + // FileError(std::fs::File) } impl fmt::Display for SnippetError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { SnippetError::Unknown => write!(f, "An unknonw error occured"), - SnippetError::ClapError(..) => write!(f, "A known error occured"), + SnippetError::ClapError(..) => write!(f, "An error occured while parsing the input"), SnippetError::IOError(..) => write!(f, "An error occured while editing the file"), SnippetError::YAMLError(..) => { write!(f, "Couldn't convert the given arguments into a yaml") @@ -42,6 +46,11 @@ impl fmt::Display for SnippetError { p.file_name(), ) } + SnippetError::FoundNoEraseError(ref p) => write!( + f, + "The snippet {:?} already exists. Use -f/--force to overwrite it.", + p.file_name(), + ), } } } @@ -58,6 +67,7 @@ impl error::Error for SnippetError { SnippetError::YAMLError(ref e) => Some(e), SnippetError::ExistsError(ref e) => Some(e), SnippetError::NotFoundNoRetryError(_) => None, + SnippetError::FoundNoEraseError(_) => None, } } } @@ -79,15 +89,3 @@ impl From for SnippetError { SnippetError::YAMLError(err) } } - -// impl From for SnippetError { -// fn from(err: serde_yaml::Error) -> SnippetError { -// SnippetError::YAMLError(err) -// } -// } - -// impl From<()> for SnippetError { -// fn from(_: ()) -> SnippetError { -// SnippetError::Unknown -// } -// } diff --git a/src/wrapper_functions.rs b/src/wrapper_functions.rs index 0189f64..bc72253 100644 --- a/src/wrapper_functions.rs +++ b/src/wrapper_functions.rs @@ -11,6 +11,17 @@ use edit::edit; use crate::dynamic_formatter; use crate::{dynamic_formatter::complete_vec, errors::SnippetError, snippet::Snippet, Cli}; +// Potential way to chain all actions without re-opening +// /// The status of the snippet in memory +// pub enum PotentialSnippet { +// /// The snippet wasn't loaded +// FileDest(File), +// /// The snippet was loaded +// LoadedSnippet(Snippet), +// /// No snippet currently exists +// None, +// } + /// Locate and print a snippet location /// /// Will error on snippet not existing @@ -25,15 +36,31 @@ pub fn locate_snippet(cli: &Cli) -> Result<(), SnippetError> { } } -// /// Print the path of the current snippet -// fn print_path(path: &Path) { -// println!("{}", path.to_string_lossy()); -// } +/// Create a new snippet with the given cli args +pub fn create_snippet(cli: &Cli) -> Result<(), SnippetError> { + // Create a snippet with the given data + let snp = Snippet::new(cli.snippet.clone(), cli.args.clone(), String::from("")); + let status = check_dir_and_open(&cli.snippet)?; + let f = match status { + FileStatus::Opened((p, _)) => { + if cli.force { + // Overwrite the snippet + File::create(p)? + } else { + // Do not overrite and return an error + return Err(SnippetError::FoundNoEraseError(p)); + } + } + FileStatus::NotFound(p) => File::create(p)?, // Create a new snippet + }; + snp.save_as(f)?; + Ok(()) +} /// Open and load snippet and edit it -/// If chained with create, the file will be created, closed and opened again pub fn edit_snippet(cli: &Cli) -> Result<(), SnippetError> { // Try loading, if not existant check if create or error + let path = snippet_path(&cli.snippet)?; let f = match File::open(&path) { Ok(f) => f, @@ -78,42 +105,6 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> { Ok(()) } -// /// Edit the snippet and write it again -// fn edit_snippet_content(snp: &Snippet) -> Result<(), SnippetError> { -// let test = edit::edit(&snp.content)?; //.expect("Couldn't edit the snippet with the editor"); -// let snp = Snippet::new(snp.name.clone(), snp.default_values.clone(), test); -// // TODO: Write snippet . Destroy original ? Return new ? -// let file = open_path(&snp)?; -// snp.save_as(file)?; -// // .unwrap_or_else(|e| println!("Coudln't save to file {:?} {}", path, e)); -// Ok(()) -// } - -/// Create a new snippet with the given cli args -/// * Find if the snippet exists -/// * Create a snippet with the given data -/// * Write the snippet -pub fn create_snippet(args: &Cli) -> Result<(), SnippetError> { - // Create a snippet with the given data - // TODO: Remove clone ? - let snp = Snippet::new(args.snippet.clone(), args.args.clone(), String::from("")); - let path = snippet_path(&args.snippet)?; - let f = match File::open(&path) { - Ok(f) => f, - Err(e) => { - if args.force { - File::create(&path)? - } else { - return Err(e.into()); - } - } - }; - - // Write the snippet - snp.save_as(f)?; - Ok(()) -} - /// Print the snippet to stdout pub fn print_snippet(args: &Cli) -> Result<(), SnippetError> { // Try to load the snippet @@ -209,6 +200,12 @@ mod test { use super::*; + macro_rules! false_cli { + ($($arg:expr),+) => { + &Cli::parse_from(vec![$($arg),+]) + }; + } + #[test] fn test_config_creation() { // Try to locate where to set the config @@ -227,13 +224,25 @@ mod test { } // Locating the snippet should fail - assert!(locate_snippet(&Cli::parse_from(vec!["-l", "test_locate"])).is_err()); + assert!(locate_snippet(false_cli!("-l", "test_locate")).is_err()); let mut f = File::create(&theorical_path).expect("Couldn't create file"); write!(f, "N").expect("Couldn't write on the new file"); f.sync_data().expect("Can't sync file"); // Locating the snippet should now suceed - assert!(locate_snippet(&Cli::parse_from(vec!["-l", "test_locate"])).is_ok()); + assert!(locate_snippet(false_cli!("-l", "test_locate")).is_ok()); + } + + #[test] + fn test_create() { + // Test to create empty + assert!(create_snippet(false_cli!("-c", "create_snippet")).is_ok()); + + // Test to create again + assert!(create_snippet(false_cli!("-c", "create_snippet")).is_err()); + + // Test to create with force + assert!(create_snippet(false_cli!("-c", "-f", "create_snippet")).is_ok()); } }