From 98580f3a7ffc8e6880e8028dec634ec426935634 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 23 May 2023 17:31:17 +0200 Subject: [PATCH 1/6] Updates readme --- src/actions.rs | 3 ++- src/errors.rs | 18 +++++++++--------- src/main.rs | 23 +++++++++++++---------- 3 files changed, 24 insertions(+), 20 deletions(-) diff --git a/src/actions.rs b/src/actions.rs index 4066e97..5531f13 100644 --- a/src/actions.rs +++ b/src/actions.rs @@ -42,7 +42,8 @@ pub fn execute_parsed_cli(cli: Cli) -> Result<(), errors::SnippetError> { if let Some(e) = e.source() { println!("This error was caused by: \n\t{}", e); } - return Err(e); + // return Err(e); + return Ok(()); // Very unconvinced by this }; } Ok(()) diff --git a/src/errors.rs b/src/errors.rs index 72d62da..d1c0d41 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -31,30 +31,30 @@ pub enum SnippetError { 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, "An error occured while parsing the input"), - SnippetError::IOError(..) => write!(f, "An error occured while editing the file"), + SnippetError::Unknown => write!(f, "An unknonw 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") + write!(f, "Couldn't convert the given arguments into a yaml.") } SnippetError::NotFound(ref p) => write!( f, - "The file {:?} doesn't exists",p.file_name().unwrap(), + "The Snippet {:?} doesn't exists. Use -c to create it and/or -E to edit it.",p.file_name().unwrap(), ), SnippetError::NotFoundNoRetryError(ref p) => { write!( f, - "The config {:?} doen't exists. Use -c to create it.", + "The Snippet {:?} doen't exists. Use -c to create it.", p.file_name(), ) } SnippetError::FoundNoEraseError(ref p) => write!( 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(), ), - 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 {} arguments",i,i+1), + 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), } } } diff --git a/src/main.rs b/src/main.rs index b07f945..652c2f2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,23 +11,27 @@ mod snippet; mod tokenizer; mod wrapper_functions; -/// The cli arguments to give to the utility +/// SNP an utility to create and manage Snippets of code +/// +/// Use "snp -c -E snippet_name" to create a new Snippet and start editing it and "snp snippet_name argument" to use it +/// You can use "{}" or "{0}" in your Snippet to later format it to your needs as would python .format() or rust format!("",) work +/// Doing so will need as many default arguments to fill the command than the total count of {} #[derive(Parser, Debug)] -#[command(author, version, about)] +#[command(author, version, about, verbatim_doc_comment)] pub struct Cli { - /// The snippet name (and therefore his path) + /// The Snippet name (and therefore his path) #[arg()] snippet: String, - /// Wether to try to load or instead create a new one + /// Try to create a Snippet with the given name and default arguments #[arg(short, long, default_value_t = false)] create: bool, - /// Show where the snippet is located + /// Show where the Snippet is located #[arg(short, long, default_value_t = false)] locate: bool, - /// Launch the editor and edit the snippet + /// Launch the editor and edit the Snippet content #[arg(short, long, default_value_t = false)] edit: bool, @@ -37,18 +41,17 @@ pub struct Cli { /// The list of arguments to give to the snippet /// if the -c flag is used, it's used to create the default arguments - #[arg(help = "List of args to give to the snipplet")] args: Vec, - /// Wether to force the creation or save and overwrite existing data + /// Force the creation/moving/renaming of a Snippet even if it mean overwriting an existing one #[arg(short, long, default_value_t = false)] force: bool, - /// Wether to delete a snippet, takes precedence over everything + /// Delete a snippet, takes precedence over everything #[arg(short, long, default_value_t = false)] delete: bool, - /// Wether to rename the snippet + /// Try to rename the Snippet (Use -f if the destination name already exist) #[arg(short, long)] rename: Option, } -- 2.45.1 From 1ed8e65de73fe4b2f2e1aa9b34767c0be93e31fa Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 23 May 2023 18:03:10 +0200 Subject: [PATCH 2/6] Corrects the save/replace error when dest was taken --- src/actions.rs | 14 +++++------ src/wrapper_functions.rs | 50 +++++++++++----------------------------- 2 files changed, 20 insertions(+), 44 deletions(-) diff --git a/src/actions.rs b/src/actions.rs index 5531f13..f8b3165 100644 --- a/src/actions.rs +++ b/src/actions.rs @@ -1,8 +1,6 @@ //! The action module, including all the logic to jump to a specific action //! depending on the CLI arguments -use std::error::Error; - use crate::{errors, wrapper_functions, Cli}; /// List of all possible actions, some are mutually exclusive @@ -38,12 +36,12 @@ pub fn execute_parsed_cli(cli: Cli) -> Result<(), errors::SnippetError> { Actions::Delete => wrapper_functions::delete_snippet(&cli), Actions::Rename => wrapper_functions::rename_snippet(&cli), } { - println!("An error occured during runtime:\n\t{}", e); - if let Some(e) = e.source() { - println!("This error was caused by: \n\t{}", e); - } - // return Err(e); - return Ok(()); // Very unconvinced by this + // println!("An error occured during runtime:\n\t{}", e); + // if let Some(e) = e.source() { + // println!("This error was caused by: \n\t{}", e); + // } + _ = ""; // No op to calm clippy while I decide wether or not delete this + return Err(e); }; } Ok(()) diff --git a/src/wrapper_functions.rs b/src/wrapper_functions.rs index ac3de9a..f9375c1 100644 --- a/src/wrapper_functions.rs +++ b/src/wrapper_functions.rs @@ -125,7 +125,7 @@ pub fn edit_snippet(cli: &Cli) -> Result<(), SnippetError> { pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> { // Try loading the snippet let status = check_dir_and_open(&cli.snippet); - let (buf, mut p) = match status? { + let (buf, mut origin_p) = match status? { FileStatus::Opened((p, f)) => (read_to_string(f)?, p), FileStatus::NotFound(p) => { if cli.create { @@ -145,72 +145,50 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> { Ok(snp) => { if cli.snippet == snp.name { // No renaming has occured, the file can safely be overriten - snp.write_over(&p)?; + snp.write_over(&origin_p)?; println!( "The snippet {:?} was succesfully saved", - p.file_name().unwrap() + origin_p.file_name().unwrap() ); Ok(()) } else { - let (f, p) = match check_dir_and_open(&snp.name)? { - FileStatus::Opened((p, f)) => { + let (dest_f, dest_p) = match check_dir_and_open(&snp.name)? { + FileStatus::Opened((dest_p, _dest_f)) => { if cli.force { // Erasing will take place - (File::create(&p)?, p) + (File::create(&dest_p)?, dest_p) } else { // No erasing/overriting println!( - "Impossible to save the snippet as {:}, as it already exists. The snippet will be saved under it's old name.", - snp.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() ); - (f, p) + (File::create(&origin_p)?, origin_p) } } FileStatus::NotFound(p) => (File::create(&p)?, p), }; - snp.save_in(&f)?; - println!("The snippet was successfuly saved in {:?}", p); + snp.save_in(&dest_f)?; + println!("The snippet was successfuly saved in {:?}", dest_p); Ok(()) } } Err(_) => { // The snippet is incorrect, however it should still be saved, just under another name ? - p.set_extension("bad.yaml"); - let mut failover = File::create(&p)?; + origin_p.set_extension("bad.yaml"); + let mut failover = File::create(&origin_p)?; write!(failover, "{}", &buf)?; println!( "The snippet was saved under {:?} in your config", - p.file_name().unwrap() + origin_p.file_name().unwrap() ); Err(SnippetError::ReparsingError) } } } -// This code is used to check if the name changed but should be moved to a separate function -// let old_name = snp.name.clone(); -// // During tests, the editor cannot be tested -// #[cfg(not(feature = "test"))] -// snp.edit()?; - -// if snp.name == old_name { -// snp.write_over(&p) -// } else { -// match check_dir_and_open(&snp.name)? { -// FileStatus::Opened((p, _f)) => { -// if cli.force { -// std::fs::remove_file(&p)?; -// snp.write_over(&p) -// } else { -// Err(SnippetError::NotFoundNoRetryError(p)) -// } -// } -// FileStatus::NotFound(p) => snp.write_over(&p), -// } -// } - /// Print the snippet to stdout pub fn print_snippet(cli: &Cli) -> Result<(), SnippetError> { // Try to load the snippet -- 2.45.1 From c4185e848af7e5392bf1b8b93484f38886d426fa Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 23 May 2023 18:56:37 +0200 Subject: [PATCH 3/6] Adds a lot of cosmetic improvement and --list --- TODO.md | 27 +++----------------- src/actions.rs | 53 ++++++++++++++++++++++++---------------- src/main.rs | 8 ++++-- src/wrapper_functions.rs | 25 +++++++++++++++++-- 4 files changed, 65 insertions(+), 48 deletions(-) diff --git a/TODO.md b/TODO.md index 0583431..67a3aac 100644 --- a/TODO.md +++ b/TODO.md @@ -3,33 +3,14 @@ [ ] Better use of file modes [ ] Document non coverage [ ] Find a solution for the .badpocalypse + [ ] Edit args only + [ ] Double backslash win + [ ] Remove last return + [ ] Remove the prerequiste of name for --list ### Currently working on ## Finished - [*] Make custom errors - [*] Transform all panic in errors - [*] Make functions into methods - [*] Remake all helper functions - [*] locate_snippet - [*] create_snippet - [*] edit_snippet - [*] edit_whole_snippet - [*] print_snippet - [*] rename_snippet - [*] Finish tests on - [*] locate_snippet - [*] create_snippet - [*] edit_snippet - [*] edit_whole_snippet - [*] print_snippet - [*] delete snippet - [*] rename snippet - [*] Have identical attributes with {0} {1} {0} (^^^^^) - [*] Add an option to delete a snippet - [*] Coverage - [*] Test populate_actions - [*] Have the the EditWhole save under a different path if name was changed (and edit too) ## Posponed or rendered useless [x] Chain the methods when possible with result ? diff --git a/src/actions.rs b/src/actions.rs index f8b3165..6295d5c 100644 --- a/src/actions.rs +++ b/src/actions.rs @@ -11,8 +11,8 @@ pub enum Actions { Edit, /// Edit the whole snippet EditAll, - /// Locate the snippet and show the position - Locate, + /// List all snippets + List, /// Show the snippet (with replacement done) Show, /// Create the snippet with the given name and arguments @@ -21,6 +21,8 @@ pub enum Actions { Delete, /// Renames the snippet Rename, + /// Find a snippet matching a name/regex + Find, } /// The main worker, execute all commands given as Args @@ -28,13 +30,14 @@ pub fn execute_parsed_cli(cli: Cli) -> Result<(), errors::SnippetError> { let list_actions = populate_actions(&cli); for action in list_actions.iter() { if let Err(e) = match action { - Actions::Locate => wrapper_functions::locate_snippet(&cli), + Actions::Find => wrapper_functions::locate_snippet(&cli), Actions::Create => wrapper_functions::create_snippet(&cli), 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), Actions::Rename => wrapper_functions::rename_snippet(&cli), + Actions::List => wrapper_functions::list_snippets(&cli), } { // println!("An error occured during runtime:\n\t{}", e); // if let Some(e) = e.source() { @@ -52,22 +55,24 @@ pub fn execute_parsed_cli(cli: Cli) -> Result<(), errors::SnippetError> { fn populate_actions(cli: &Cli) -> Vec { let mut actions = Vec::new(); match ( - cli.locate, + cli.path, cli.create, cli.edit, cli.edit_all, cli.delete, &cli.rename, + cli.list, ) { - (true, _, _, _, false, _) => actions.push(Actions::Locate), - (_, false, false, true, false, _) => actions.push(Actions::EditAll), - (_, true, _, true, false, _) => actions.push(Actions::EditAll), - (_, true, false, false, false, _) => actions.push(Actions::Create), - (_, false, true, _, false, _) => actions.push(Actions::Edit), - (_, true, true, false, false, _) => actions.push(Actions::Edit), - (false, false, false, false, false, None) => actions.push(Actions::Show), - (_, _, _, _, true, _) => actions.push(Actions::Delete), - (_, _, _, _, _, Some(_)) => actions.push(Actions::Rename), + (true, _, _, _, false, _, false) => actions.push(Actions::Find), + (_, false, false, true, false, _, false) => actions.push(Actions::EditAll), + (_, true, _, true, false, _, false) => actions.push(Actions::EditAll), + (_, true, false, false, false, _, false) => actions.push(Actions::Create), + (_, false, true, _, false, _, false) => actions.push(Actions::Edit), + (_, true, true, false, false, _, false) => actions.push(Actions::Edit), + (false, false, false, false, false, None, false) => actions.push(Actions::Show), + (_, _, _, _, true, _, false) => actions.push(Actions::Delete), + (_, _, _, _, _, Some(_), false) => actions.push(Actions::Rename), + (_, _, _, _, _, _, true) => actions.push(Actions::List), } actions } @@ -91,16 +96,16 @@ mod test { #[test] fn test_populate_actions() { - // false_cli!("snp", "name", "-l"), Actions::Locate + // false_cli!("snp", "name", "-p"), Actions::Locate let group = group_actions!( ( - false_cli!("snp", "name", "-l", "-c", "-e", "-E"), - vec![Actions::Locate] + false_cli!("snp", "name", "-p", "-c", "-e", "-E"), + vec![Actions::Find] ), - (false_cli!("snp", "name", "-l"), vec![Actions::Locate]), + (false_cli!("snp", "name", "-p"), vec![Actions::Find]), (false_cli!("snp", "name", "-d"), vec![Actions::Delete]), ( - false_cli!("snp", "name", "-d", "-e", "e", "-E", "-l"), + false_cli!("snp", "name", "-d", "-e", "e", "-E", "-p"), vec![Actions::Delete] ), (false_cli!("snp", "name", "-E"), vec![Actions::EditAll]), @@ -111,12 +116,12 @@ mod test { ), (false_cli!("snp", "name", "-e"), vec![Actions::Edit]), (false_cli!("snp", "name", "-e", "-c"), vec![Actions::Edit]), - (false_cli!("snp", "name", "-l"), vec![Actions::Locate]), + (false_cli!("snp", "name", "-p"), vec![Actions::Find]), (false_cli!("snp", "name", "-c"), vec![Actions::Create]), (false_cli!("snp", "name"), vec![Actions::Show]), (false_cli!("snp", "name", "-d"), vec![Actions::Delete]), ( - false_cli!("snp", "name", "-d", "-c", "-E", "-e", "-l"), + false_cli!("snp", "name", "-d", "-c", "-E", "-e", "-p"), vec![Actions::Delete] ), ( @@ -131,6 +136,11 @@ mod test { false_cli!("snp", "name", "-c", "-r", "new_name", "-f"), vec![Actions::Create] ), + (false_cli!("snp", "name", "-l"), vec![Actions::List]), + ( + false_cli!("snp", "name", "-l", "-c", "-e", "-E"), + vec![Actions::List] + ), ); for (cli, res) in group.iter() { println!("Testing {:?}..actions expected {:?}", cli, res); @@ -150,10 +160,11 @@ mod test { false_cli!("snp", "parsed_cli", "-c"), false_cli!("snp", "parsed_cli", "-r", "new_name", "-f"), false_cli!("snp", "new_name", "-d"), + false_cli!("snp", "new_name", "-l"), ]; let bad_cli = vec![ - false_cli!("snp", "parsed_cli_bad", "-l"), + false_cli!("snp", "parsed_cli_bad", "-p"), false_cli!("snp", "-d", "parsed_cli_bad"), ]; diff --git a/src/main.rs b/src/main.rs index 652c2f2..945586e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -27,9 +27,9 @@ pub struct Cli { #[arg(short, long, default_value_t = false)] create: bool, - /// Show where the Snippet is located + /// Find the path of the snippet with the given name #[arg(short, long, default_value_t = false)] - locate: bool, + path: bool, /// Launch the editor and edit the Snippet content #[arg(short, long, default_value_t = false)] @@ -54,6 +54,10 @@ pub struct Cli { /// Try to rename the Snippet (Use -f if the destination name already exist) #[arg(short, long)] rename: Option, + + /// List all snippets in the snippet folder + #[arg(short, long, default_value_t = false)] + list: bool, } /// Main entry point, everything is defered for testing and coverage diff --git a/src/wrapper_functions.rs b/src/wrapper_functions.rs index f9375c1..6d76c2d 100644 --- a/src/wrapper_functions.rs +++ b/src/wrapper_functions.rs @@ -6,7 +6,7 @@ #[allow(unused)] // Mandatory because of how test and rust-analyser work use edit::edit; -use std::fs::create_dir_all; +use std::fs::{self, create_dir_all}; use std::io::{read_to_string, Write}; use std::{env, fs::File, path::PathBuf}; @@ -188,6 +188,26 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> { } } } +/// List all snippets in the snippet config directory +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::>() + ); + Ok(()) +} /// Print the snippet to stdout pub fn print_snippet(cli: &Cli) -> Result<(), SnippetError> { @@ -437,6 +457,7 @@ pub mod test { let res = edit_whole_snippet(false_cli!("snp", "resave_snippet")); println!("Failing to overwrite {:?}", res); - assert!(res.is_err()); + assert!(res.is_ok()); // The failure just means it wasn't overriten + // TODO: Check no overwrite occurs } } -- 2.45.1 From 3c7f672a55fd70c87ed8b647fb3b1223367a3dde Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 23 May 2023 19:04:04 +0200 Subject: [PATCH 4/6] Adds a little eye candy for the paths and listing --- src/errors.rs | 10 +++++----- src/wrapper_functions.rs | 5 +++-- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/errors.rs b/src/errors.rs index d1c0d41..0eacd0f 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -39,19 +39,19 @@ 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(), + "The Snippet {} doesn't exists. Use -c to create it and/or -E to edit it.",p.file_name().unwrap().to_str().unwrap(), ), SnippetError::NotFoundNoRetryError(ref p) => { write!( f, - "The Snippet {:?} doen't exists. Use -c to create it.", - p.file_name(), + "The Snippet {} doen't exists. Use -c to create it.", + p.file_name().unwrap().to_str().unwrap(), ) } SnippetError::FoundNoEraseError(ref p) => write!( f, - "The Snippet {:?} already exists. Use -f/--force to overwrite it.", - p.file_name().unwrap(), + "The Snippet {} already exists. Use -f/--force to overwrite it.", + p.file_name().unwrap().to_str().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), diff --git a/src/wrapper_functions.rs b/src/wrapper_functions.rs index 6d76c2d..90bea6c 100644 --- a/src/wrapper_functions.rs +++ b/src/wrapper_functions.rs @@ -160,7 +160,7 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> { } else { // 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: {}", + "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() ); (File::create(&origin_p)?, origin_p) @@ -193,7 +193,7 @@ pub fn list_snippets(_cli: &Cli) -> Result<(), SnippetError> { let dirpath = config_folder()?; let paths = fs::read_dir(&dirpath).unwrap(); println!( - "Snippet list at {:?}:\n {:?}", + "Snippet list at {}:\n {}", dirpath.parent().unwrap().to_str().unwrap(), paths .map(|p| p @@ -205,6 +205,7 @@ pub fn list_snippets(_cli: &Cli) -> Result<(), SnippetError> { .unwrap() .to_owned()) .collect::>() + .join(", ") ); Ok(()) } -- 2.45.1 From 9efba4311274f5a7e93fdd72ee4c281e72f4b35d Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 23 May 2023 21:08:40 +0200 Subject: [PATCH 5/6] Makes -l as an alternative to . Also changes to optionnal and mandatory --- Cargo.toml | 2 +- coverage/html/badges/flat.svg | 8 ++-- src/actions.rs | 12 +++--- src/main.rs | 39 ++++++++++++----- src/wrapper_functions.rs | 81 +++++++++++++++++++++-------------- 5 files changed, 88 insertions(+), 54 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5b5d1e5..415fde2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "snp" authors = ["Dandaedre"] -version = "1.0.1" +version = "1.0.2" edition = "2021" [features] diff --git a/coverage/html/badges/flat.svg b/coverage/html/badges/flat.svg index a43354b..849843f 100644 --- a/coverage/html/badges/flat.svg +++ b/coverage/html/badges/flat.svg @@ -1,6 +1,6 @@ - coverage: 99% + xmlns:xlink="http://www.w3.org/1999/xlink" width="96" height="20" role="img" aria-label="coverage: 95%"> + coverage: 95% @@ -16,8 +16,8 @@ coverage - - 99% + + 95% \ No newline at end of file diff --git a/src/actions.rs b/src/actions.rs index 6295d5c..9ee4d72 100644 --- a/src/actions.rs +++ b/src/actions.rs @@ -94,6 +94,7 @@ mod test { }; } + // #[ignore] #[test] fn test_populate_actions() { // false_cli!("snp", "name", "-p"), Actions::Locate @@ -136,11 +137,8 @@ mod test { false_cli!("snp", "name", "-c", "-r", "new_name", "-f"), vec![Actions::Create] ), - (false_cli!("snp", "name", "-l"), vec![Actions::List]), - ( - false_cli!("snp", "name", "-l", "-c", "-e", "-E"), - vec![Actions::List] - ), + (false_cli!("snp", "-l"), vec![Actions::List]), + // (false_cli!("snp", "-l"), vec![Actions::List]), ); for (cli, res) in group.iter() { println!("Testing {:?}..actions expected {:?}", cli, res); @@ -149,8 +147,10 @@ mod test { assert!(res.iter().zip(fnd).all(|(a, b)| *a == b)); } } + #[test] fn test_execute_parsed_cli() { + // println!("Executing test for cli"); let list_cli = vec![ false_cli!("snp", "parsed_cli", "-e", "-c"), false_cli!("snp", "parsed_cli", "-c", "-f"), @@ -160,7 +160,7 @@ mod test { false_cli!("snp", "parsed_cli", "-c"), false_cli!("snp", "parsed_cli", "-r", "new_name", "-f"), false_cli!("snp", "new_name", "-d"), - false_cli!("snp", "new_name", "-l"), + false_cli!("snp", "-l"), ]; let bad_cli = vec![ diff --git a/src/main.rs b/src/main.rs index 945586e..af8c9cb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -20,43 +20,49 @@ mod wrapper_functions; #[command(author, version, about, verbatim_doc_comment)] pub struct Cli { /// The Snippet name (and therefore his path) - #[arg()] - snippet: String, + #[arg(group = "mandatory", group = "mutex")] + snippet: Option, /// Try to create a Snippet with the given name and default arguments - #[arg(short, long, default_value_t = false)] + #[arg(short, long, default_value_t = false, requires = "mandatory")] create: bool, /// Find the path of the snippet with the given name - #[arg(short, long, default_value_t = false)] + #[arg(short, long, default_value_t = false, requires = "mandatory")] path: bool, /// Launch the editor and edit the Snippet content - #[arg(short, long, default_value_t = false)] + #[arg(short, long, default_value_t = false, requires = "mandatory")] edit: bool, /// Launch the editor and edit the whole snippet - #[arg(short = 'E', long = "Edit", default_value_t = false)] + #[arg( + short = 'E', + long = "Edit", + default_value_t = false, + requires = "mandatory" + )] edit_all: bool, /// The list of arguments to give to the snippet /// if the -c flag is used, it's used to create the default arguments + #[arg(requires = "mandatory")] args: Vec, /// Force the creation/moving/renaming of a Snippet even if it mean overwriting an existing one - #[arg(short, long, default_value_t = false)] + #[arg(short, long, default_value_t = false, requires = "mandatory")] force: bool, /// Delete a snippet, takes precedence over everything - #[arg(short, long, default_value_t = false)] + #[arg(short, long, default_value_t = false, requires = "mandatory")] delete: bool, /// Try to rename the Snippet (Use -f if the destination name already exist) - #[arg(short, long)] + #[arg(short, long, requires = "mandatory")] rename: Option, /// List all snippets in the snippet folder - #[arg(short, long, default_value_t = false)] + #[arg(short, long, default_value_t = false, group = "mutex")] list: bool, } @@ -65,3 +71,16 @@ fn main() -> Result<(), errors::SnippetError> { let cli = Cli::parse(); actions::execute_parsed_cli(cli) } + +#[cfg(test)] +mod test { + use clap::CommandFactory; + + use super::*; + + #[test] + fn test_cli_main() { + let cmd = Cli::command_for_update(); + cmd.debug_assert(); + } +} diff --git a/src/wrapper_functions.rs b/src/wrapper_functions.rs index 90bea6c..f82254e 100644 --- a/src/wrapper_functions.rs +++ b/src/wrapper_functions.rs @@ -18,7 +18,7 @@ use crate::{dynamic_formatter, Cli}; /// /// Will error on snippet not existing pub fn locate_snippet(cli: &Cli) -> Result<(), SnippetError> { - let status = check_dir_and_open(&cli.snippet)?; + let status = check_dir_and_open(cli.snippet.as_ref().unwrap())?; match status { FileStatus::Opened((p, _)) => { println!("{:?}", p.as_os_str()); @@ -31,8 +31,12 @@ pub fn locate_snippet(cli: &Cli) -> Result<(), SnippetError> { /// 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 snp = Snippet::new( + cli.snippet.as_ref().unwrap().clone(), + cli.args.clone(), + String::from(""), + ); + let status = check_dir_and_open(cli.snippet.as_ref().unwrap())?; let (f, p) = match status { FileStatus::Opened((p, _)) => { if cli.force { @@ -54,10 +58,10 @@ pub fn create_snippet(cli: &Cli) -> Result<(), SnippetError> { pub fn rename_snippet(cli: &Cli) -> Result<(), SnippetError> { // Check wether the snippet exitsts let new_name = cli.rename.as_ref().unwrap(); - if new_name == &cli.snippet { + if new_name == cli.snippet.as_ref().unwrap() { return Ok(()); // The noop is a success ? } - let (f, oldpath) = match check_dir_and_open(&cli.snippet)? { + let (f, oldpath) = match check_dir_and_open(cli.snippet.as_ref().unwrap())? { FileStatus::Opened((p, f)) => (f, p), FileStatus::NotFound(e) => return Err(SnippetError::NotFound(e)), }; @@ -83,7 +87,8 @@ pub fn rename_snippet(cli: &Cli) -> Result<(), SnippetError> { // Save snippet println!( "The snippet {} was sucessfuly renamed as {}", - cli.snippet, new_name + cli.snippet.as_ref().unwrap(), + new_name ); Ok(()) } @@ -91,13 +96,17 @@ pub fn rename_snippet(cli: &Cli) -> Result<(), SnippetError> { /// Open and load snippet and edit it pub fn edit_snippet(cli: &Cli) -> Result<(), SnippetError> { // Try loading, if not existant check if create or error - let status = check_dir_and_open(&cli.snippet)?; + let status = check_dir_and_open(cli.snippet.as_ref().unwrap())?; let (mut snp, _, p) = match status { FileStatus::Opened((p, f)) => (Snippet::from_file(&f)?, f, p), FileStatus::NotFound(p) => { if cli.create { ( - Snippet::new(cli.snippet.clone(), cli.args.clone(), String::from("")), + Snippet::new( + cli.snippet.as_ref().unwrap().clone(), + cli.args.clone(), + String::from(""), + ), File::create(&p)?, p, ) @@ -124,13 +133,16 @@ pub fn edit_snippet(cli: &Cli) -> Result<(), SnippetError> { /// a creation or an override pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> { // Try loading the snippet - let status = check_dir_and_open(&cli.snippet); + let status = check_dir_and_open(cli.snippet.as_ref().unwrap()); let (buf, mut origin_p) = match status? { FileStatus::Opened((p, f)) => (read_to_string(f)?, p), FileStatus::NotFound(p) => { if cli.create { File::create(&p)?; - (Snippet::empty(cli.snippet.clone(), cli.args.clone()), p) + ( + Snippet::empty(cli.snippet.clone().unwrap(), cli.args.clone()), + p, + ) } else { return Err(SnippetError::NotFoundNoRetryError(p)); } @@ -143,7 +155,7 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> { // Try reparsing, on error no modifications will be made match Snippet::from_string(&buf) { Ok(snp) => { - if cli.snippet == snp.name { + if cli.snippet.as_ref().unwrap() == &snp.name { // No renaming has occured, the file can safely be overriten snp.write_over(&origin_p)?; println!( @@ -213,7 +225,7 @@ pub fn list_snippets(_cli: &Cli) -> Result<(), SnippetError> { /// Print the snippet to stdout pub fn print_snippet(cli: &Cli) -> Result<(), SnippetError> { // Try to load the snippet - let (_, f) = match check_dir_and_open(&cli.snippet)? { + let (_, f) = match check_dir_and_open(cli.snippet.as_ref().unwrap())? { FileStatus::Opened((p, f)) => (p, f), FileStatus::NotFound(p) => return Err(SnippetError::NotFound(p)), }; @@ -233,7 +245,7 @@ pub fn print_snippet(cli: &Cli) -> Result<(), SnippetError> { /// 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)); + path.push(format!("{}.yaml", cli.snippet.as_ref().unwrap())); std::fs::remove_file(path)?; Ok(()) } @@ -308,6 +320,7 @@ pub mod test { assert!(delete_snippet(false_cli!("snp", "-d", "delete_snippet")).is_ok()); } + // #[ignore] #[test] fn test_locate() { // Try to locate an unexisting snippet @@ -315,14 +328,14 @@ pub mod test { _ = std::fs::remove_file(&theorical_path); // Locating the snippet should fail - assert!(locate_snippet(false_cli!("-l", "test_locate")).is_err()); + assert!(locate_snippet(false_cli!("snp", "-f", "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(false_cli!("-l", "test_locate")).is_ok()); + assert!(locate_snippet(false_cli!("-f", "test_locate")).is_ok()); } #[test] @@ -334,57 +347,59 @@ pub mod test { assert!(print_snippet(false_cli!("snp", "test_print")).is_err()); // Create snippet - assert!(create_snippet(false_cli!("-c", "test_print")).is_ok()); + assert!(create_snippet(false_cli!("snp", "-c", "test_print")).is_ok()); assert!(print_snippet(false_cli!("snp", "test_print")).is_ok()); - // assert!(print_snippet(false_cli!("-l", "test_print")).is_ok()); } #[test] fn test_create() { _ = std::fs::remove_file(snippet_path("create_snippet").unwrap()); // Test to create empty - assert!(create_snippet(false_cli!("-c", "create_snippet")).is_ok()); + assert!(create_snippet(false_cli!("snp", "-c", "create_snippet")).is_ok()); // Test to create again - assert!(create_snippet(false_cli!("-c", "create_snippet")).is_err()); + assert!(create_snippet(false_cli!("snp", "-c", "create_snippet")).is_err()); // Test to create with force - assert!(create_snippet(false_cli!("-c", "-f", "create_snippet")).is_ok()); + assert!(create_snippet(false_cli!("snp", "-c", "-f", "create_snippet")).is_ok()); } #[test] fn test_edit() { _ = std::fs::remove_file(snippet_path("edit_content").unwrap()); // Open unnexitant - assert!(edit_snippet(false_cli!("-e", "edit_content")).is_err()); + assert!(edit_snippet(false_cli!("snp", "-e", "edit_content")).is_err()); // Force creation - assert!(edit_snippet(false_cli!("-e", "-c", "edit_content")).is_ok()); + assert!(edit_snippet(false_cli!("snp", "-e", "-c", "edit_content")).is_ok()); // Edit when created - println!("{:?}", edit_snippet(false_cli!("-e", "edit_content"))); - assert!(edit_snippet(false_cli!("-e", "edit_content")).is_ok()); + println!( + "{:?}", + edit_snippet(false_cli!("snp", "-e", "edit_content")) + ); + assert!(edit_snippet(false_cli!("snp", "-e", "edit_content")).is_ok()); } #[test] fn test_edit_whole() { _ = std::fs::remove_file(snippet_path("edit_whole").unwrap()); // Open unnexitant - assert!(edit_whole_snippet(false_cli!("-E", "edit_whole")).is_err()); + assert!(edit_whole_snippet(false_cli!("snp", "-E", "edit_whole")).is_err()); // Force creation - assert!(edit_whole_snippet(false_cli!("-E", "-c", "edit_whole")).is_ok()); + assert!(edit_whole_snippet(false_cli!("snp", "-E", "-c", "edit_whole")).is_ok()); // Edit when created - assert!(edit_whole_snippet(false_cli!("-E", "edit_whole")).is_ok()); + assert!(edit_whole_snippet(false_cli!("snp", "-E", "edit_whole")).is_ok()); // Create a badly formatted file if let FileStatus::Opened((p, _)) = check_dir_and_open("edit_whole").unwrap() { let mut f = File::create(p).unwrap(); write!(f, "badly formatter yaml").unwrap(); - assert!(edit_whole_snippet(false_cli!("-E", "edit_whole")).is_err()); + assert!(edit_whole_snippet(false_cli!("snp", "-E", "edit_whole")).is_err()); assert!(matches!( check_dir_and_open("edit_whole.bad").unwrap(), FileStatus::Opened(_) @@ -400,7 +415,7 @@ pub mod test { _ = std::fs::remove_file(&oldpath); _ = std::fs::remove_file(&newpath); _ = std::fs::remove_file(filledpath); - assert!(create_snippet(false_cli!("-c", "rename_snippet", "-f")).is_ok()); + assert!(create_snippet(false_cli!("snp", "-c", "rename_snippet", "-f")).is_ok()); assert!( rename_snippet(false_cli!("snp", "-r", "renamed_snippet", "rename_snippet")).is_ok() ); @@ -410,8 +425,8 @@ pub mod test { assert!(rename_snippet(false_cli!("snp", "-r", "non_ex", "non_ex")).is_ok()); assert!(rename_snippet(false_cli!("snp", "-r", "non_ex", "renamed_snippet")).is_err()); - assert!(create_snippet(false_cli!("-c", "filled_destination", "-f")).is_ok()); - assert!(create_snippet(false_cli!("-c", "rename_snippet", "-f")).is_ok()); + assert!(create_snippet(false_cli!("snp", "-c", "filled_destination", "-f")).is_ok()); + assert!(create_snippet(false_cli!("snp", "-c", "rename_snippet", "-f")).is_ok()); assert!(matches!( rename_snippet(false_cli!( "snp", @@ -449,8 +464,8 @@ pub mod test { println!("Trying to resave without destination {:?}", res); assert!(res.is_ok()); - assert!(create_snippet(false_cli!("-c", "new_snippet")).is_err()); - assert!(create_snippet(false_cli!("-c", "resave_snippet")).is_err()); + assert!(create_snippet(false_cli!("snp", "-c", "new_snippet")).is_err()); + assert!(create_snippet(false_cli!("snp", "-c", "resave_snippet")).is_err()); let res = edit_whole_snippet(false_cli!("snp", "resave_snippet", "-f")); println!("Sucessfully erasing {:?}", res); -- 2.45.1 From 5cd297b1da44a1aaca0dedfa7f41b3e16879650e Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 23 May 2023 21:11:55 +0200 Subject: [PATCH 6/6] Updates coverage and version --- Cargo.toml | 2 +- coverage/html/badges/flat.svg | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 415fde2..0819a21 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "snp" authors = ["Dandaedre"] -version = "1.0.2" +version = "1.0.4" edition = "2021" [features] diff --git a/coverage/html/badges/flat.svg b/coverage/html/badges/flat.svg index 849843f..a43354b 100644 --- a/coverage/html/badges/flat.svg +++ b/coverage/html/badges/flat.svg @@ -1,6 +1,6 @@ - coverage: 95% + xmlns:xlink="http://www.w3.org/1999/xlink" width="96" height="20" role="img" aria-label="coverage: 99%"> + coverage: 99% @@ -16,8 +16,8 @@ coverage - - 95% + + 99% \ No newline at end of file -- 2.45.1