From 56fdb061165fd1e3fa9581702f285b698713cbc1 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 22 May 2023 21:12:11 +0200 Subject: [PATCH] Finishes a first version of snp --- Cargo.toml | 4 +- Makefile.toml | 9 +- TODO.md | 11 +- coverage/html/badges/flat.svg | 10 +- src/dynamic_formatter.rs | 13 +- src/errors.rs | 4 +- src/main.rs | 28 +- src/tokenizer.rs | 40 ++- src/wrapper_functions.rs | 14 +- tarpaulin-report.html | 660 ++++++++++++++++++++++++++++++++++ 10 files changed, 757 insertions(+), 36 deletions(-) create mode 100644 tarpaulin-report.html diff --git a/Cargo.toml b/Cargo.toml index 8459a25..a4a91cf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,9 @@ edition = "2021" [features] test = [] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - +[profile.test] +opt-level = 0 + [dependencies] clap = { version = "4.2.7", features = ["derive"] } edit = "0.1.4" diff --git a/Makefile.toml b/Makefile.toml index 284b84b..a6f5dc6 100644 --- a/Makefile.toml +++ b/Makefile.toml @@ -7,4 +7,11 @@ script = [ "mkdir -p coverage/", "CARGO_INCREMENTAL=0 RUSTFLAGS='-Cinstrument-coverage -Ccodegen-units=1 -Copt-level=0 -Coverflow-checks=off' LLVM_PROFILE_FILE='llvm/cargo-test-%p-%m.profraw' cargo test --features test", "grcov . --binary-path ./target/debug/deps/ -s . -t html --branch --ignore-not-existing --ignore '../*' --ignore '/*' --ignore '*/errors.rs' -o coverage/html/", -] \ No newline at end of file +] + +[tasks.testing] +script_runner = "@shell" +ignore_errors = true +script = [ +"cargo test --features \"test\"", +] diff --git a/TODO.md b/TODO.md index b3d676b..4b8cb86 100644 --- a/TODO.md +++ b/TODO.md @@ -1,9 +1,7 @@ ## TODO - [ ] Make a lib for dynamic_format and snippets (impl make a trait for have .id() and other future t) [ ] Benchmarks - [ ] Better modes + [ ] Better use of file modes [ ] Test populate_actions - [ ] Change all uncatchables errors to expect to be more helpful or change them to better errors [ ] Document non coverage [ ] Have the the EditWhole save under a different path if name was changed (and edit too) [ ] Add an option to delete a snippet @@ -16,8 +14,8 @@ [*] create_snippet [*] edit_snippet [*] edit_whole_snippet - [-] print_snippet - [ ] Cargo test must always have the test feature + [*] print_snippet + [ ] delete snippet ## Finished [*] Make custom errors @@ -33,3 +31,6 @@ ## Posponed or rendered useless [x] Chain the methods when possible with result ? + [ ] Make a lib for dynamic_format and snippets (impl make a trait for have .id() and other future t) + [ ] Change all uncatchables errors to expect to be more helpful or change them to better errors + diff --git a/coverage/html/badges/flat.svg b/coverage/html/badges/flat.svg index d0e421f..1ed2da4 100644 --- a/coverage/html/badges/flat.svg +++ b/coverage/html/badges/flat.svg @@ -1,6 +1,6 @@ - coverage: 64% + xmlns:xlink="http://www.w3.org/1999/xlink" width="96" height="20" role="img" aria-label="coverage: 79%"> + coverage: 79% @@ -10,14 +10,14 @@ - + coverage - - 64% + + 79% \ No newline at end of file diff --git a/src/dynamic_formatter.rs b/src/dynamic_formatter.rs index ecb7223..b7d37ac 100644 --- a/src/dynamic_formatter.rs +++ b/src/dynamic_formatter.rs @@ -26,7 +26,6 @@ where match s.id() { Some(i) => index = i, None => { - // TODO: Get rid of this wonky hack index = moving_index; moving_index += 1 } @@ -74,6 +73,14 @@ mod test { ) .unwrap(); assert_eq!(res, ("big str aaa with many bbb formatters".to_string())); + let res = + dynamic_format("{} {0} {0} {2} {d} {1}", vec!["aaa", "bbb", "ccc", "dddd"]).unwrap(); + assert_eq!(res, ("aaa aaa aaa ccc {d} bbb".to_string())); + let res = dynamic_format("{100}", vec!["a"]); + assert!(res.is_err()); + + let res = dynamic_format("", vec!["a"]).unwrap(); + assert_eq!(res, "".to_string()); } #[test] @@ -87,8 +94,6 @@ mod test { vec!["A", "BB", "CC", "DD"] ); assert_eq!(complete_vec(&eq, &deff).unwrap(), eq); - if let Ok(_x) = complete_vec(&big, &deff) { - panic!("Complete vec should return an error of bigger vecs") - }; + assert!(complete_vec(&big, &deff).is_err()); } } diff --git a/src/errors.rs b/src/errors.rs index 1277f92..ca4ee10 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -1,5 +1,5 @@ //! A general error module for the snp program - +#![cfg(not(tarpaulin_include))] use std::{error, fmt, path::PathBuf}; /// Snippet error, general error wrapper for the Snippet module @@ -51,7 +51,7 @@ impl fmt::Display for SnippetError { SnippetError::FoundNoEraseError(ref p) => write!( f, "The snippet {:?} already exists. Use -f/--force to overwrite it.", - p.file_name(), + p.file_name().unwrap(), ), SnippetError::ReparsingError => write!(f,"The snipped 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 {0} arguments",i), diff --git a/src/main.rs b/src/main.rs index c15f6e8..e98749c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -44,6 +44,10 @@ pub struct Cli { /// Wether to force the creation or save and overwrite existing data #[arg(short, long, default_value_t = false)] force: bool, + + /// Wether to delete a snippet, takes precedence over everything + #[arg(short, long, default_value_t = false)] + delete: bool, } /// List of all possible actions, some are mutually exclusive @@ -59,6 +63,8 @@ pub enum Actions { Show, /// Create the snippet with the given name and arguments Create, + /// Deletes the snippet + Delete, } /// Main entry point, everything is defered for testing and coverage @@ -77,10 +83,11 @@ fn execute_parsed_cli(cli: Cli) -> Result<(), errors::SnippetError> { Actions::Show => wrapper_functions::print_snippet(&cli), Actions::Edit => wrapper_functions::edit_snippet(&cli), Actions::EditAll => wrapper_functions::edit_whole_snippet(&cli), + Actions::Delete => wrapper_functions::delete_snippet(&cli), } { - println!("An error occured during runtime {:?}", e); + println!("An error occured during runtime:\n\t{}", e); if let Some(e) = e.source() { - println!("This error was caused by {:?}", e); + println!("This error was caused by: \n\t{}", e); } return Err(e); }; @@ -92,14 +99,15 @@ fn execute_parsed_cli(cli: Cli) -> Result<(), errors::SnippetError> { /// even when the arguments don't make sense fn populate_actions(cli: &Cli) -> Vec { let mut actions = Vec::new(); - match (cli.locate, cli.create, cli.edit, cli.edit_all) { - (true, _, _, _) => actions.push(Actions::Locate), - (_, true, _, true) => actions.push(Actions::EditAll), - (_, true, true, false) => actions.push(Actions::Edit), - (_, true, false, false) => actions.push(Actions::Create), - (_, false, true, _) => actions.push(Actions::Edit), - (_, false, false, true) => actions.push(Actions::EditAll), - (false, false, false, false) => actions.push(Actions::Show), + match (cli.locate, cli.create, cli.edit, cli.edit_all, cli.delete) { + (true, _, _, _, false) => actions.push(Actions::Locate), + (_, true, _, true, false) => actions.push(Actions::EditAll), + (_, true, true, false, false) => actions.push(Actions::Edit), + (_, true, false, false, false) => actions.push(Actions::Create), + (_, false, true, _, false) => actions.push(Actions::Edit), + (_, false, false, true, false) => actions.push(Actions::EditAll), + (false, false, false, false, false) => actions.push(Actions::Show), + (_, _, _, _, true) => actions.push(Actions::Delete), } actions } diff --git a/src/tokenizer.rs b/src/tokenizer.rs index 5466f6d..598738a 100644 --- a/src/tokenizer.rs +++ b/src/tokenizer.rs @@ -8,6 +8,7 @@ use crate::errors::SnippetError; /// A formatter, containing (or not) an argument to be subsitued with #[derive(Debug)] +#[cfg_attr(test, derive(PartialEq))] pub struct CustFormatter { /// The positional id of the element to replace with pub id: Option, @@ -32,6 +33,7 @@ impl CustFormatter { /// The parsed snippet #[derive(Debug)] +#[cfg_attr(test, derive(PartialEq))] pub enum SnippetToken<'a> { /// A subsitution token, containing either an index or nothing (and being "positional") Substitution(CustFormatter), @@ -105,17 +107,45 @@ fn create_token_from_pos( #[cfg(test)] mod test { - // use super::*; + use super::*; - #[ignore] #[test] fn test_create_token_from_pos() { - todo!() + // All calls + let text = String::from("0123456789"); + assert_eq!( + create_token_from_pos(&text, Status::Formater, 5, None), + Some(SnippetToken::Substitution(CustFormatter::new("6789"))) + ); + assert_eq!( + create_token_from_pos(&text, Status::Text, 7, None), + Some(SnippetToken::Text("789")) + ); + assert_eq!( + create_token_from_pos(&text, Status::Formater, 2, Some(5)), //Need at least 2 digits + Some(SnippetToken::Substitution(CustFormatter::new("3"))) + ); + + assert_eq!( + create_token_from_pos(&text, Status::Text, 0, Some(1)), + Some(SnippetToken::Text("0")) + ); } - #[ignore] #[test] fn test_create_token_from_string() { - todo!() + let v = create_tokens_from_string("{} {1} { {{}}").unwrap(); + assert_eq!( + v, + vec![ + SnippetToken::Text(""), + SnippetToken::Substitution(CustFormatter { id: None }), + SnippetToken::Text(" "), + SnippetToken::Substitution(CustFormatter { id: Some(1) }), + SnippetToken::Text(" { {"), + SnippetToken::Substitution(CustFormatter { id: None }), + SnippetToken::Text("}"), + ] + ); } } diff --git a/src/wrapper_functions.rs b/src/wrapper_functions.rs index 50cb13e..5b33454 100644 --- a/src/wrapper_functions.rs +++ b/src/wrapper_functions.rs @@ -44,19 +44,20 @@ 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 { + let (f, p) = match status { FileStatus::Opened((p, _)) => { if cli.force { // Overwrite the snippet - File::create(p)? + (File::create(&p)?, p) } else { // Do not overrite and return an error return Err(SnippetError::FoundNoEraseError(p)); } } - FileStatus::NotFound(p) => File::create(p)?, // Create a new snippet + FileStatus::NotFound(p) => (File::create(&p)?, p), // Create a new snippet }; snp.save_in(&f)?; + println!("The snippet {:?} was created successfully", p); Ok(()) } @@ -181,6 +182,13 @@ pub fn print_snippet(cli: &Cli) -> Result<(), SnippetError> { Ok(()) } +/// Delete a given snippet, errors if the snippet doesn't exists +pub fn delete_snippet(cli: &Cli) -> Result<(), SnippetError> { + let mut path = config_folder()?; + path.push(format!("{}.yaml", cli.snippet)); + std::fs::remove_file(path)?; + Ok(()) +} /// The status of the request after the path was attempted to be opened pub enum FileStatus { /// The file was opened with success a tuple is returned diff --git a/tarpaulin-report.html b/tarpaulin-report.html new file mode 100644 index 0000000..470d8e2 --- /dev/null +++ b/tarpaulin-report.html @@ -0,0 +1,660 @@ + + + + + + + +
+ + + + + + \ No newline at end of file