From d2cb3f4295c98c7a2813b3095b8ffbfd8fa07e49 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 19 May 2023 21:09:18 +0200 Subject: [PATCH 01/20] Adds a lot of features - Helper function - Small refactor - regexes --- Cargo.toml | 2 + TODO.md | 18 +++---- src/main.rs | 138 ++++++++++++++++++++++++++++++++++++++++++++++++---- 3 files changed, 139 insertions(+), 19 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index d9ab9a6..59b6af3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,5 +7,7 @@ edition = "2021" [dependencies] clap = { version = "4.2.7", features = ["derive"] } +edit = "0.1.4" +regex = "1.8.1" serde = { version = "1.0.163", features = ["derive"] } serde_yaml = "0.9.21" diff --git a/TODO.md b/TODO.md index 635ade8..8f43f5e 100644 --- a/TODO.md +++ b/TODO.md @@ -1,15 +1,15 @@ ## Features ### --new (name) -- Create a new snippet with given name at the default location (where tho ?) + [ ] Create a new snippet with given name at the default location (where tho ?) ### name args -- Use the snippet name with one or more args -- Args must be split up -- + [ ] Use the snippet name with one or more args + [ ] Args must be split up + [ ] ## TODO -- Make a lib for dynamic_format -- Make custom errors -- Transform all panic in errors -- Make functions into methods -- Have identical attributes with {0} {1} {0} (^^^^^) \ No newline at end of file + [ ] Make a lib for dynamic_format + [ ] Make custom errors + [ ] Transform all panic in errors + [ ] Make functions into methods + [ ] Have identical attributes with {0} {1} {0} (^^^^^) \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index a705de5..74bf55f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,13 +4,14 @@ #![allow(clippy::result_unit_err)] use clap::Parser; +use regex::Regex; use serde::{Deserialize, Serialize}; use std::{ env, fs::{create_dir_all, File}, io::{self, Write}, - path::PathBuf, + path::{Path, PathBuf}, }; // use serde_yaml; @@ -34,10 +35,102 @@ struct Cli { /// 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, + + /// Launch the editor and edit the snippet + #[arg(short, default_value_t = false)] + edit: bool, +} + +/// The parsed snippet +#[derive(Debug)] +enum Token<'a> { + /// A subsitution token, containing either an index or nothing (and being "positional") + Substitution(CustFormatter), + /// A text token, the inbetween + Text(&'a str), +} + +/// A formatter, containing (or not) an argument to be subsitued with +#[derive(Debug)] +struct CustFormatter { + /// The positional id of the element to replace with + pub id: Option, +} + +impl CustFormatter { + /// Create a CustomFormatter from a string, either void (positional) with a parsable (fixed) + fn new(text: &str) -> CustFormatter { + if text.is_empty() { + return CustFormatter { id: None }; + } + CustFormatter { + id: Some(text.parse::().unwrap()), + } + } +} +/// Assert where the read head is +enum Status { + /// Read head in inside a formatter + Formater, + /// Read head is outside a formatter + Text, +} + +/// Add not empty values only +macro_rules! push_if_some { + ($vec:ident, $val:expr) => { + if let Some(x) = $val { + $vec.push(x); + }; + }; +} +/// Create a token list from the snippet given and return it +pub fn create_tokens_from_string(snippet: &str) { + let re = Regex::new(r"(\{(\d*)\})").unwrap(); + let matches = re.find_iter(snippet); + let mut readhead = 0; // Starting to read at zero + let mut token_list = Vec::new(); + for r in matches { + // Assume we matched text from read to here + push_if_some!( + token_list, + create_token_from_pos(snippet, Status::Text, readhead, Some(r.start())) + ); + push_if_some!( + token_list, + create_token_from_pos(snippet, Status::Formater, r.start(), Some(r.end()),) + ); + readhead = r.end(); + } + create_token_from_pos(snippet, Status::Text, readhead, None); + println!("{:?}", token_list); +} + +/// Create a single token from the current positions +fn create_token_from_pos( + text: &str, + status: Status, + start: usize, + stop: Option, +) -> Option { + let text = match (stop, status) { + (None, Status::Formater) => Token::Substitution(CustFormatter::new(&text[start + 1..])), + (None, Status::Text) => Token::Text(&text[start..]), + (Some(stop), Status::Formater) => { + Token::Substitution(CustFormatter::new(&text[start + 1..stop - 1])) + } + (Some(stop), Status::Text) => Token::Text(&text[start..stop]), + }; + + println!("{:?}", text); + Some(text) } fn main() { let cli = Cli::parse(); + // let origin = "Fill the blank bébé"; + // let edited = edit::edit(origin).unwrap(); + // println!("{}", edited); match cli.create { true => create_snippet(cli), false => print_snippet(&cli), @@ -58,10 +151,14 @@ fn create_snippet(args: Cli) { ), }; // if args.verbose println!("{}",save_path); + let string = if args.edit { + edit::edit("").unwrap() + } else { + String::from("") + }; // Create a snippet with the given data - let snp = Snippet::new(args.snipplet.clone(), args.args, String::from("")); - // println!("{}", serde_yaml::to_string(&snp).unwrap()); + let snp = Snippet::new(args.snipplet.clone(), args.args, string); let mut file = match create_dir_all(&save_path) { Ok(()) => { @@ -75,7 +172,7 @@ fn create_snippet(args: Cli) { } Err(e) => panic!("Couldn't write to path {:?}. {}", save_path, e), }; - + // snp.save() // Write the snippet write!( file, @@ -85,6 +182,8 @@ fn create_snippet(args: Cli) { .unwrap_or_else(|_| panic!("Couldn't write yaml to file {:?}", save_path)); } +// fn open_path() + /// Find a configuration folder/name for the given snippet name fn config_folder() -> io::Result { let exe = env::current_exe()?; @@ -114,11 +213,30 @@ fn print_snippet(args: &Cli) { Err(_) => panic!("Couldn't format the snippet !"), Ok(sn) => sn, }; - if args.locate { - println!("{}", path.to_string_lossy()); - } else { - println!("{}", f_str); + match (args.locate, args.edit) { + (true, true) => { + print_path(&path); + edit::edit(snp.content).unwrap(); + } + (true, false) => print_path(&path), + (false, true) => edit_snippet(&snp), + (false, false) => (), } + create_tokens_from_string(&f_str); + println!("{}", f_str); +} + +/// Print the path of the current snippet +fn print_path(path: &Path) { + println!("{}", path.to_string_lossy()); +} + +/// Edit the snippet and write it again +fn edit_snippet(snp: &Snippet) { + let test = edit::edit(&snp.content).expect("Couldn't edit the snippet with the editor"); + let snp = Snippet::new(snp.name.clone(), snp.arguments.clone(), test); + // TODO: Write snippet . Destroy original ? Return new ? + // snp.save(); } /// A snippet ready to be Serialized/Deserialized @@ -230,8 +348,8 @@ 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 ob bigger vecs") + if let Ok(_x) = complete_vec(&big, &deff) { + panic!("Complete vec should return an error of bigger vecs") }; } } -- 2.45.1 From 8937ce7fd40547c2a7a4afeaa1f4b26dd79ddf65 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 19 May 2023 21:59:06 +0200 Subject: [PATCH 02/20] Updates TODO and Adds a lot of progress on rework --- TODO.md | 5 +-- src/main.rs | 90 +++++++++++++++++++++++++++-------------------------- 2 files changed, 49 insertions(+), 46 deletions(-) diff --git a/TODO.md b/TODO.md index 8f43f5e..724b70e 100644 --- a/TODO.md +++ b/TODO.md @@ -8,8 +8,9 @@ [ ] ## TODO - [ ] Make a lib for dynamic_format + [ ] Make a lib for dynamic_format and snippets (impl make a trait for have .id() and other future t) [ ] Make custom errors [ ] Transform all panic in errors [ ] Make functions into methods - [ ] Have identical attributes with {0} {1} {0} (^^^^^) \ No newline at end of file + [-] Have identical attributes with {0} {1} {0} (^^^^^) + [ ] Update tests \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 74bf55f..291e790 100644 --- a/src/main.rs +++ b/src/main.rs @@ -86,12 +86,13 @@ macro_rules! push_if_some { } /// Create a token list from the snippet given and return it pub fn create_tokens_from_string(snippet: &str) { - let re = Regex::new(r"(\{(\d*)\})").unwrap(); + let re = Regex::new(r"\{\d*\}").unwrap(); let matches = re.find_iter(snippet); let mut readhead = 0; // Starting to read at zero let mut token_list = Vec::new(); for r in matches { // Assume we matched text from read to here + println!("{:?}", r); push_if_some!( token_list, create_token_from_pos(snippet, Status::Text, readhead, Some(r.start())) @@ -128,9 +129,6 @@ fn create_token_from_pos( fn main() { let cli = Cli::parse(); - // let origin = "Fill the blank bébé"; - // let edited = edit::edit(origin).unwrap(); - // println!("{}", edited); match cli.create { true => create_snippet(cli), false => print_snippet(&cli), @@ -142,14 +140,6 @@ fn main() { /// * Create a snippet with the given data /// * Write the snippet fn create_snippet(args: Cli) { - // Find if the snippet exists - let mut save_path = match config_folder() { - Ok(path) => path, - Err(e) => panic!( - "The OS couldn't locate a place to save the snippets.\n {}", - e - ), - }; // if args.verbose println!("{}",save_path); let string = if args.edit { edit::edit("").unwrap() @@ -159,31 +149,39 @@ fn create_snippet(args: Cli) { // Create a snippet with the given data let snp = Snippet::new(args.snipplet.clone(), args.args, string); + let (file, save_path) = open_path(&snp); + if args.locate { + println!("Saving snippet to {:?}", save_path); + } - let mut file = match create_dir_all(&save_path) { + // Write the snippet + snp.save(file) + .unwrap_or_else(|_| panic!("Couldn't write yaml to file {:?}", save_path)); +} + +/// Open the path linked to a snippet +fn open_path(snp: &Snippet) -> (File, PathBuf) { + // Find if the snippet exists + let mut save_path = match config_folder() { + Ok(path) => path, + Err(e) => panic!( + "The OS couldn't locate a place to save the snippets.\n {}", + e + ), + }; + + let file = match create_dir_all(&save_path) { Ok(()) => { - save_path.push(format!("{}.yaml", args.snipplet)); - if args.locate { - println!("Saving snippet to {:?}", save_path); - } + save_path.push(format!("{}.yaml", snp.name)); File::create(&save_path).unwrap_or_else(|e| { panic!("Couldn't create snippet file at {:?} {:}", save_path, e) }) } Err(e) => panic!("Couldn't write to path {:?}. {}", save_path, e), }; - // snp.save() - // Write the snippet - write!( - file, - "{}", - serde_yaml::to_string(&snp).expect("Couldn't convert the given arguments into a yaml") - ) - .unwrap_or_else(|_| panic!("Couldn't write yaml to file {:?}", save_path)); + (file, save_path) } -// fn open_path() - /// Find a configuration folder/name for the given snippet name fn config_folder() -> io::Result { let exe = env::current_exe()?; @@ -203,7 +201,7 @@ fn print_snippet(args: &Cli) { let snp: Snippet = serde_yaml::from_reader(f).expect("Couldn't parse values"); // Add the given arguments to the snippet - let final_args = match complete_vec(&args.args, &snp.arguments) { + let final_args = match complete_vec(&args.args, &snp.default_values) { Err(_) => panic!("Too many arguments given to the snippet, aborting"), Ok(argg) => argg, }; @@ -222,7 +220,6 @@ fn print_snippet(args: &Cli) { (false, true) => edit_snippet(&snp), (false, false) => (), } - create_tokens_from_string(&f_str); println!("{}", f_str); } @@ -234,9 +231,11 @@ fn print_path(path: &Path) { /// Edit the snippet and write it again fn edit_snippet(snp: &Snippet) { let test = edit::edit(&snp.content).expect("Couldn't edit the snippet with the editor"); - let snp = Snippet::new(snp.name.clone(), snp.arguments.clone(), test); + let snp = Snippet::new(snp.name.clone(), snp.default_values.clone(), test); // TODO: Write snippet . Destroy original ? Return new ? - // snp.save(); + let (file, path) = open_path(&snp); + snp.save(file) + .unwrap_or_else(|e| println!("Coudln't save to file {:?} {}", path, e)); } /// A snippet ready to be Serialized/Deserialized @@ -246,7 +245,7 @@ pub struct Snippet { name: String, /// The default value of all args - arguments: Vec, + default_values: Vec, /// The base string to format content: String, @@ -254,18 +253,22 @@ pub struct Snippet { impl Snippet { /// Create a new snippet - pub fn new(name: String, arguments: Vec, content: String) -> Self { + pub fn new(name: String, default_values: Vec, content: String) -> Self { Snippet { name, - arguments, + default_values, content, } } - // /// Save the snippet at the default location under it's name - // pub fn save(&self) -> Result<(), ()> { - // Ok(()) - // } + /// Save the snippet at the default location under it's name + pub fn save(&self, mut file: File) -> Result<(), std::io::Error> { + write!( + file, + "{}", + serde_yaml::to_string(self).expect("Couldn't convert the given arguments into a yaml") + ) + } /// Tries to load a path and return a snippet // pub fn load(path: String) -> Result { @@ -278,10 +281,6 @@ impl Snippet { } } -// pub struct AccessError{ - -// } - /// A dynamic formatter, formatting a string with any number of /// {} with element of a Vec, by default the search doen't need to /// be exhaustive and wont fail if either the array or format string don't @@ -290,8 +289,11 @@ pub fn dynamic_format(format_string: &str, vector: Vec) -> Result = format_string.split/*_inclusive*/("{}").collect(); - // println!("{:?}", collected_format_string); + // TODO: RESTART FROM HERE, do the permutation + // Implement a to_str or a collect for vec + create_tokens_from_string(format_string); + // println!("{}",); + let collected_format_string: Vec<&str> = format_string.split("{}").collect(); let size_str = collected_format_string.len(); let size_vec = vector.len(); -- 2.45.1 From be8fca56be67a2f0c5824b649c206e8557543ea3 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 19 May 2023 22:04:59 +0200 Subject: [PATCH 03/20] Updates todo --- TODO.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/TODO.md b/TODO.md index 724b70e..76b6f52 100644 --- a/TODO.md +++ b/TODO.md @@ -13,4 +13,6 @@ [ ] Transform all panic in errors [ ] Make functions into methods [-] Have identical attributes with {0} {1} {0} (^^^^^) - [ ] Update tests \ No newline at end of file + [ ] Update tests + [ ] Benchmarks + [ ] Better modes \ No newline at end of file -- 2.45.1 From ac4f58f929c83e6218eb4abc5c5a958072091366 Mon Sep 17 00:00:00 2001 From: beffroi Date: Sat, 20 May 2023 10:04:58 +0200 Subject: [PATCH 04/20] Refactors in 2 modules --- README.md | 21 ++- src/dynamic_formatter.rs | 52 +++++++ src/main.rs | 320 +-------------------------------------- src/snippet.rs | 272 +++++++++++++++++++++++++++++++++ 4 files changed, 348 insertions(+), 317 deletions(-) create mode 100644 src/dynamic_formatter.rs create mode 100644 src/snippet.rs diff --git a/README.md b/README.md index bfc62bd..4d141db 100644 --- a/README.md +++ b/README.md @@ -2,5 +2,24 @@ drawing -A simple cli utility to manage snippet +A simple cli utility to manage snippets + +## Usage + +```sh +To create a new snippet and edit it immediately +$ snp snippet_name -c -e list of default tokens + +To edit the content of a snippet +$ snp snippet_name -e + +To edit the whole snippet (allow for editing of name and list of args) +$ snp snippet_name -E + +To delete a snippet +$ snp snippet_name -d + +To use a snippet +$ snp snippet_name +``` diff --git a/src/dynamic_formatter.rs b/src/dynamic_formatter.rs new file mode 100644 index 0000000..a0fc617 --- /dev/null +++ b/src/dynamic_formatter.rs @@ -0,0 +1,52 @@ +//! A lib of vector operators +//! Allow for replacement and formatting of strings + +use crate::snippet::create_tokens_from_string; +/// A dynamic formatter, formatting a string with any number of +/// {} with element of a Vec, by default the search doen't need to +/// be exhaustive and wont fail if either the array or format string don't +/// match up in length, use dynamic_format_strict for this behaviour + +/// A pseudo dynamic formatter, tries to fill all {} in a string with the values +/// in a vector +pub fn dynamic_formatter(format_string: &str, vector: Vec) -> Result +where + T: std::fmt::Display, +{ + // TODO: RESTART FROM HERE, do the permutation + // Implement a to_str or a collect for vec + create_tokens_from_string(format_string); + // println!("{}",); + let collected_format_string: Vec<&str> = format_string.split("{}").collect(); + let size_str = collected_format_string.len(); + let size_vec = vector.len(); + + let mut fmt_vec = Vec::new(); + for (i, text) in collected_format_string.iter().enumerate() { + fmt_vec.push(text.to_string()); + if i < size_vec && i < size_str - 1 { + fmt_vec.push(format!("{}", vector[i])); + } + } + Ok(fmt_vec.join("")) +} + +/// Fill the argument vector with a list of defaults values if needed +pub fn complete_vec(to_fill: &Vec, defaults: &Vec) -> Result, ()> +where + T: Clone, +{ + let size_o = to_fill.len(); + let size_d = defaults.len(); + match size_o.cmp(&size_d) { + std::cmp::Ordering::Greater => Err(()), + std::cmp::Ordering::Equal => Ok(to_fill.clone()), + std::cmp::Ordering::Less => { + let mut output = to_fill.clone(); + (size_o..size_d).for_each(|i| { + output.push(defaults[i].clone()); + }); + Ok(output) + } + } +} diff --git a/src/main.rs b/src/main.rs index 291e790..72365b6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,21 +4,16 @@ #![allow(clippy::result_unit_err)] use clap::Parser; -use regex::Regex; -use serde::{Deserialize, Serialize}; +mod dynamic_formatter; +mod snippet; -use std::{ - env, - fs::{create_dir_all, File}, - io::{self, Write}, - path::{Path, PathBuf}, -}; +use crate::snippet::{create_snippet, print_snippet}; // use serde_yaml; /// The cli arguments to give to the utility #[derive(Parser, Debug)] #[command(author, version, about)] -struct Cli { +pub struct Cli { /// The snippet name (and therefore his path) #[arg()] snipplet: String, @@ -41,92 +36,6 @@ struct Cli { edit: bool, } -/// The parsed snippet -#[derive(Debug)] -enum Token<'a> { - /// A subsitution token, containing either an index or nothing (and being "positional") - Substitution(CustFormatter), - /// A text token, the inbetween - Text(&'a str), -} - -/// A formatter, containing (or not) an argument to be subsitued with -#[derive(Debug)] -struct CustFormatter { - /// The positional id of the element to replace with - pub id: Option, -} - -impl CustFormatter { - /// Create a CustomFormatter from a string, either void (positional) with a parsable (fixed) - fn new(text: &str) -> CustFormatter { - if text.is_empty() { - return CustFormatter { id: None }; - } - CustFormatter { - id: Some(text.parse::().unwrap()), - } - } -} -/// Assert where the read head is -enum Status { - /// Read head in inside a formatter - Formater, - /// Read head is outside a formatter - Text, -} - -/// Add not empty values only -macro_rules! push_if_some { - ($vec:ident, $val:expr) => { - if let Some(x) = $val { - $vec.push(x); - }; - }; -} -/// Create a token list from the snippet given and return it -pub fn create_tokens_from_string(snippet: &str) { - let re = Regex::new(r"\{\d*\}").unwrap(); - let matches = re.find_iter(snippet); - let mut readhead = 0; // Starting to read at zero - let mut token_list = Vec::new(); - for r in matches { - // Assume we matched text from read to here - println!("{:?}", r); - push_if_some!( - token_list, - create_token_from_pos(snippet, Status::Text, readhead, Some(r.start())) - ); - push_if_some!( - token_list, - create_token_from_pos(snippet, Status::Formater, r.start(), Some(r.end()),) - ); - readhead = r.end(); - } - create_token_from_pos(snippet, Status::Text, readhead, None); - println!("{:?}", token_list); -} - -/// Create a single token from the current positions -fn create_token_from_pos( - text: &str, - status: Status, - start: usize, - stop: Option, -) -> Option { - let text = match (stop, status) { - (None, Status::Formater) => Token::Substitution(CustFormatter::new(&text[start + 1..])), - (None, Status::Text) => Token::Text(&text[start..]), - (Some(stop), Status::Formater) => { - Token::Substitution(CustFormatter::new(&text[start + 1..stop - 1])) - } - (Some(stop), Status::Text) => Token::Text(&text[start..stop]), - }; - - println!("{:?}", text); - Some(text) -} - fn main() { let cli = Cli::parse(); match cli.create { @@ -134,224 +43,3 @@ fn main() { false => print_snippet(&cli), } } - -/// Create a new snippet with the given cli args -/// * Find if the snippet exists -/// * Create a snippet with the given data -/// * Write the snippet -fn create_snippet(args: Cli) { - // if args.verbose println!("{}",save_path); - let string = if args.edit { - edit::edit("").unwrap() - } else { - String::from("") - }; - - // Create a snippet with the given data - let snp = Snippet::new(args.snipplet.clone(), args.args, string); - let (file, save_path) = open_path(&snp); - if args.locate { - println!("Saving snippet to {:?}", save_path); - } - - // Write the snippet - snp.save(file) - .unwrap_or_else(|_| panic!("Couldn't write yaml to file {:?}", save_path)); -} - -/// Open the path linked to a snippet -fn open_path(snp: &Snippet) -> (File, PathBuf) { - // Find if the snippet exists - let mut save_path = match config_folder() { - Ok(path) => path, - Err(e) => panic!( - "The OS couldn't locate a place to save the snippets.\n {}", - e - ), - }; - - let file = match create_dir_all(&save_path) { - Ok(()) => { - save_path.push(format!("{}.yaml", snp.name)); - File::create(&save_path).unwrap_or_else(|e| { - panic!("Couldn't create snippet file at {:?} {:}", save_path, e) - }) - } - Err(e) => panic!("Couldn't write to path {:?}. {}", save_path, e), - }; - (file, save_path) -} - -/// Find a configuration folder/name for the given snippet name -fn config_folder() -> io::Result { - let exe = env::current_exe()?; - let dir = exe.parent().expect("Executable must be in some directory"); - let mut dir = dir.join(".config"); - dir.push("snp_config"); - // dir.push(format!("{}.yaml", name)); - Ok(dir) -} - -/// Print the snippet to stdout -fn print_snippet(args: &Cli) { - // Try to load the snippet - let mut path = config_folder().expect("Coudln't open config folder"); - path.push(format!("{}.yaml", args.snipplet)); - let f = std::fs::File::open(&path).expect("Could not open snippet file."); - let snp: Snippet = serde_yaml::from_reader(f).expect("Couldn't parse values"); - - // Add the given arguments to the snippet - let final_args = match complete_vec(&args.args, &snp.default_values) { - Err(_) => panic!("Too many arguments given to the snippet, aborting"), - Ok(argg) => argg, - }; - - // Print the snippet - let f_str = match dynamic_format(&snp.content, final_args) { - Err(_) => panic!("Couldn't format the snippet !"), - Ok(sn) => sn, - }; - match (args.locate, args.edit) { - (true, true) => { - print_path(&path); - edit::edit(snp.content).unwrap(); - } - (true, false) => print_path(&path), - (false, true) => edit_snippet(&snp), - (false, false) => (), - } - println!("{}", f_str); -} - -/// Print the path of the current snippet -fn print_path(path: &Path) { - println!("{}", path.to_string_lossy()); -} - -/// Edit the snippet and write it again -fn edit_snippet(snp: &Snippet) { - 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, path) = open_path(&snp); - snp.save(file) - .unwrap_or_else(|e| println!("Coudln't save to file {:?} {}", path, e)); -} - -/// A snippet ready to be Serialized/Deserialized -#[derive(Deserialize, Serialize, Debug)] -pub struct Snippet { - /// Akin to path, the name of the snippet is where to store it - name: String, - - /// The default value of all args - default_values: Vec, - - /// The base string to format - content: String, -} - -impl Snippet { - /// Create a new snippet - pub fn new(name: String, default_values: Vec, content: String) -> Self { - Snippet { - name, - default_values, - content, - } - } - - /// Save the snippet at the default location under it's name - pub fn save(&self, mut file: File) -> Result<(), std::io::Error> { - write!( - file, - "{}", - serde_yaml::to_string(self).expect("Couldn't convert the given arguments into a yaml") - ) - } - - /// Tries to load a path and return a snippet - // pub fn load(path: String) -> Result { - // Err(()) - // } - - /// Write to stdout the snipped with either default arguments or given arguments - pub fn print(&self) -> Result<(), ()> { - Ok(()) - } -} - -/// A dynamic formatter, formatting a string with any number of -/// {} with element of a Vec, by default the search doen't need to -/// be exhaustive and wont fail if either the array or format string don't -/// match up in length, use dynamic_format_strict for this behaviour -pub fn dynamic_format(format_string: &str, vector: Vec) -> Result -where - T: std::fmt::Display, -{ - // TODO: RESTART FROM HERE, do the permutation - // Implement a to_str or a collect for vec - create_tokens_from_string(format_string); - // println!("{}",); - let collected_format_string: Vec<&str> = format_string.split("{}").collect(); - let size_str = collected_format_string.len(); - let size_vec = vector.len(); - - let mut fmt_vec = Vec::new(); - for (i, text) in collected_format_string.iter().enumerate() { - fmt_vec.push(text.to_string()); - if i < size_vec && i < size_str - 1 { - fmt_vec.push(format!("{}", vector[i])); - } - } - Ok(fmt_vec.join("")) -} - -/// Fill the argument vector with a list of defaults values if needed -pub fn complete_vec(to_fill: &Vec, defaults: &Vec) -> Result, ()> -where - T: Clone, -{ - let size_o = to_fill.len(); - let size_d = defaults.len(); - match size_o.cmp(&size_d) { - std::cmp::Ordering::Greater => Err(()), - std::cmp::Ordering::Equal => Ok(to_fill.clone()), - std::cmp::Ordering::Less => { - let mut output = to_fill.clone(); - (size_o..size_d).for_each(|i| { - output.push(defaults[i].clone()); - }); - Ok(output) - } - } -} - -#[cfg(test)] -mod test { - use super::*; - #[test] - fn test_dynamic_format() { - let res = dynamic_format( - "big str {} with many {} formatters", - vec!["aaa", "bbb", "ccc", "dddd"], - ); - assert_eq!(res, Ok("big str aaa with many bbb formatters".to_string())); - } - - #[test] - fn test_complete_vec() { - let smol = vec!["A"]; - let big = vec!["a", "b", "c", "d", "e", "f"]; - let eq = vec!["T", "U", "I", "O"]; - let deff = vec!["AA", "BB", "CC", "DD"]; - assert_eq!( - complete_vec(&smol, &deff).unwrap(), - 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") - }; - } -} diff --git a/src/snippet.rs b/src/snippet.rs new file mode 100644 index 0000000..4eed4b7 --- /dev/null +++ b/src/snippet.rs @@ -0,0 +1,272 @@ +use regex::Regex; +use serde::{Deserialize, Serialize}; + +use std::{ + env, + fs::{create_dir_all, File}, + io::{self, Write}, + path::{Path, PathBuf}, +}; + +use crate::dynamic_formatter::{complete_vec, dynamic_formatter}; +use crate::Cli; +/// The parsed snippet +#[derive(Debug)] +enum Token<'a> { + /// A subsitution token, containing either an index or nothing (and being "positional") + Substitution(CustFormatter), + /// A text token, the inbetween + Text(&'a str), +} + +/// A formatter, containing (or not) an argument to be subsitued with +#[derive(Debug)] +struct CustFormatter { + /// The positional id of the element to replace with + pub id: Option, +} + +impl CustFormatter { + /// Create a CustomFormatter from a string, either void (positional) with a parsable (fixed) + fn new(text: &str) -> CustFormatter { + if text.is_empty() { + return CustFormatter { id: None }; + } + CustFormatter { + id: Some(text.parse::().unwrap()), + } + } +} +/// Assert where the read head is +enum Status { + /// Read head in inside a formatter + Formater, + /// Read head is outside a formatter + Text, +} + +/// Add not empty values only +macro_rules! push_if_some { + ($vec:ident, $val:expr) => { + if let Some(x) = $val { + $vec.push(x); + }; + }; +} +/// Create a token list from the snippet given and return it +pub fn create_tokens_from_string(snippet: &str) { + let re = Regex::new(r"\{\d*\}").unwrap(); + let matches = re.find_iter(snippet); + let mut readhead = 0; // Starting to read at zero + let mut token_list = Vec::new(); + for r in matches { + // Assume we matched text from read to here + println!("{:?}", r); + push_if_some!( + token_list, + create_token_from_pos(snippet, Status::Text, readhead, Some(r.start())) + ); + push_if_some!( + token_list, + create_token_from_pos(snippet, Status::Formater, r.start(), Some(r.end()),) + ); + readhead = r.end(); + } + create_token_from_pos(snippet, Status::Text, readhead, None); + println!("{:?}", token_list); +} + +/// Create a single token from the current positions +fn create_token_from_pos( + text: &str, + status: Status, + start: usize, + stop: Option, +) -> Option { + let text = match (stop, status) { + (None, Status::Formater) => Token::Substitution(CustFormatter::new(&text[start + 1..])), + (None, Status::Text) => Token::Text(&text[start..]), + (Some(stop), Status::Formater) => { + Token::Substitution(CustFormatter::new(&text[start + 1..stop - 1])) + } + (Some(stop), Status::Text) => Token::Text(&text[start..stop]), + }; + + println!("{:?}", text); + Some(text) +} + +/// 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(crate) fn create_snippet(args: Cli) { + // if args.verbose println!("{}",save_path); + let string = if args.edit { + edit::edit("").unwrap() + } else { + String::from("") + }; + + // Create a snippet with the given data + let snp = Snippet::new(args.snipplet.clone(), args.args, string); + let (file, save_path) = open_path(&snp); + if args.locate { + println!("Saving snippet to {:?}", save_path); + } + + // Write the snippet + snp.save(file) + .unwrap_or_else(|_| panic!("Couldn't write yaml to file {:?}", save_path)); +} + +/// Open the path linked to a snippet +fn open_path(snp: &Snippet) -> (File, PathBuf) { + // Find if the snippet exists + let mut save_path = match config_folder() { + Ok(path) => path, + Err(e) => panic!( + "The OS couldn't locate a place to save the snippets.\n {}", + e + ), + }; + + let file = match create_dir_all(&save_path) { + Ok(()) => { + save_path.push(format!("{}.yaml", snp.name)); + File::create(&save_path).unwrap_or_else(|e| { + panic!("Couldn't create snippet file at {:?} {:}", save_path, e) + }) + } + Err(e) => panic!("Couldn't write to path {:?}. {}", save_path, e), + }; + (file, save_path) +} + +/// Find a configuration folder/name for the given snippet name +fn config_folder() -> io::Result { + let exe = env::current_exe()?; + let dir = exe.parent().expect("Executable must be in some directory"); + let mut dir = dir.join(".config"); + dir.push("snp_config"); + // dir.push(format!("{}.yaml", name)); + Ok(dir) +} + +/// Print the snippet to stdout +pub fn print_snippet(args: &Cli) { + // Try to load the snippet + let mut path = config_folder().expect("Coudln't open config folder"); + path.push(format!("{}.yaml", args.snipplet)); + let f = std::fs::File::open(&path).expect("Could not open snippet file."); + let snp: Snippet = serde_yaml::from_reader(f).expect("Couldn't parse values"); + + // Add the given arguments to the snippet + let final_args = match complete_vec(&args.args, &snp.default_values) { + Err(_) => panic!("Too many arguments given to the snippet, aborting"), + Ok(argg) => argg, + }; + + // Print the snippet + let f_str = match dynamic_formatter(&snp.content, final_args) { + Err(_) => panic!("Couldn't format the snippet !"), + Ok(sn) => sn, + }; + match (args.locate, args.edit) { + (true, true) => { + print_path(&path); + edit::edit(snp.content).unwrap(); + } + (true, false) => print_path(&path), + (false, true) => edit_snippet(&snp), + (false, false) => (), + } + println!("{}", f_str); +} + +/// Print the path of the current snippet +fn print_path(path: &Path) { + println!("{}", path.to_string_lossy()); +} + +/// Edit the snippet and write it again +fn edit_snippet(snp: &Snippet) { + 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, path) = open_path(&snp); + snp.save(file) + .unwrap_or_else(|e| println!("Coudln't save to file {:?} {}", path, e)); +} + +/// A snippet ready to be Serialized/Deserialized +#[derive(Deserialize, Serialize, Debug)] +pub struct Snippet { + /// Akin to path, the name of the snippet is where to store it + name: String, + + /// The default value of all args + default_values: Vec, + + /// The base string to format + content: String, +} + +impl Snippet { + /// Create a new snippet + pub fn new(name: String, default_values: Vec, content: String) -> Self { + Snippet { + name, + default_values, + content, + } + } + + /// Save the snippet at the default location under it's name + pub fn save(&self, mut file: File) -> Result<(), std::io::Error> { + write!( + file, + "{}", + serde_yaml::to_string(self).expect("Couldn't convert the given arguments into a yaml") + ) + } + + /// Tries to load a path and return a snippet + // pub fn load(path: String) -> Result { + // Err(()) + // } + + /// Write to stdout the snipped with either default arguments or given arguments + pub fn print(&self) -> Result<(), ()> { + Ok(()) + } +} + +#[cfg(test)] +mod test { + use super::*; + #[test] + fn test_dynamic_format() { + let res = dynamic_formatter( + "big str {} with many {} formatters", + vec!["aaa", "bbb", "ccc", "dddd"], + ); + assert_eq!(res, Ok("big str aaa with many bbb formatters".to_string())); + } + + #[test] + fn test_complete_vec() { + let smol = vec!["A"]; + let big = vec!["a", "b", "c", "d", "e", "f"]; + let eq = vec!["T", "U", "I", "O"]; + let deff = vec!["AA", "BB", "CC", "DD"]; + assert_eq!( + complete_vec(&smol, &deff).unwrap(), + 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") + }; + } +} -- 2.45.1 From f16e6e4ffd19e005ca5b895a882ba24386ca4d93 Mon Sep 17 00:00:00 2001 From: beffroi Date: Sat, 20 May 2023 13:20:04 +0200 Subject: [PATCH 05/20] Adds error module (as a stub) and implements a true action mutex-ish --- TODO.md | 3 ++- src/errors.rs | 32 ++++++++++++++++++++++++++++ src/main.rs | 58 ++++++++++++++++++++++++++++++++++++++++++++------ src/snippet.rs | 22 +++++++++++++++---- 4 files changed, 104 insertions(+), 11 deletions(-) create mode 100644 src/errors.rs diff --git a/TODO.md b/TODO.md index 76b6f52..fe289d6 100644 --- a/TODO.md +++ b/TODO.md @@ -15,4 +15,5 @@ [-] Have identical attributes with {0} {1} {0} (^^^^^) [ ] Update tests [ ] Benchmarks - [ ] Better modes \ No newline at end of file + [ ] Better modes + [ ] Test populate_actions \ No newline at end of file diff --git a/src/errors.rs b/src/errors.rs new file mode 100644 index 0000000..b52ea84 --- /dev/null +++ b/src/errors.rs @@ -0,0 +1,32 @@ +//! A general error module for the snp program + +/// Snippet error, general error wrapper for the Snippet module +/// All error are wrapper with more information available with the source() method +#[derive(Debug)] +enum SnippetError { + Unknown, + Parse(PlaceHolder), +} + +struct PlaceHolder {} +impl fmt::Display for SnippetError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + SnippetError::Unknown => write!(f, "An unknonw error occured"), + // DoubleError::Parse(..) => + // write!(f, "the provided string could not be parsed as int"), + } + } +} + +impl error::Error for DoubleError { + fn source(&self) -> Option<&(dyn error::Error + 'static)> { + match *self { + SnippetError::Unknown => None, + // The cause is the underlying implementation error type. Is implicitly + // cast to the trait object `&error::Error`. This works because the + // underlying type already implements the `Error` trait. + DoubleError::Parse(ref e) => Some(e), + } + } +} diff --git a/src/main.rs b/src/main.rs index 72365b6..059729d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -26,20 +26,66 @@ pub struct Cli { #[arg(short, long, default_value_t = false)] locate: bool, + /// Launch the editor and edit the snippet + #[arg(short, long, default_value_t = false)] + edit: bool, + + /// Launch the editor and edit the whole snippet + #[arg(short = 'E', long = "Edit", default_value_t = false)] + 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(help = "List of args to give to the snipplet")] args: Vec, +} - /// Launch the editor and edit the snippet - #[arg(short, default_value_t = false)] - edit: bool, +/// List of all possible actions, some are mutually exclusive +#[derive(Debug)] +pub enum Actions { + /// Edit the content of the snippet only + Edit, + /// Edit the whole snippet + EditAll, + /// Locate the snippet and show the position + Locate, + /// Show the snippet (with replacement done) + Show, + /// Create the snippet with the given name and arguments + Create, } fn main() { let cli = Cli::parse(); - match cli.create { - true => create_snippet(cli), - false => print_snippet(&cli), + + let list_actions = populate_actions(&cli); + for action in list_actions.iter() { + match action { + Actions::Edit => snippet::edit_snippet(&cli), + Actions::EditAll => snippet::edit_whole_snippet(&cli), + Actions::Locate => snippet::locate_snippet(&cli), + Actions::Show => snippet::print_snippet(&cli), + Actions::Create => snippet::create_snippet(&cli), + } } + // match cli.create { + // true => create_snippet(cli), + // false => print_snippet(&cli), + // } +} + +/// Populate a logical vec of succesive actions to perform depending on arguments +/// 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.append(&mut vec![Actions::Create, Actions::EditAll]), + (_, true, true, false) => actions.append(&mut vec![Actions::Create, Actions::Edit]), + (_, true, false, false) => actions.push(Actions::Create), + (_, false, true, _) => actions.push(Actions::EditAll), + (_, false, false, true) => actions.push(Actions::Edit), + (false, false, false, false) => (), + } + actions } diff --git a/src/snippet.rs b/src/snippet.rs index 4eed4b7..aaf65c5 100644 --- a/src/snippet.rs +++ b/src/snippet.rs @@ -10,6 +10,7 @@ use std::{ use crate::dynamic_formatter::{complete_vec, dynamic_formatter}; use crate::Cli; + /// The parsed snippet #[derive(Debug)] enum Token<'a> { @@ -37,6 +38,7 @@ impl CustFormatter { } } } + /// Assert where the read head is enum Status { /// Read head in inside a formatter @@ -53,6 +55,10 @@ macro_rules! push_if_some { }; }; } + +pub fn edit_whole_snippet(cli: &Cli) {} +pub fn locate_snippet(cli: &Cli) {} + /// Create a token list from the snippet given and return it pub fn create_tokens_from_string(snippet: &str) { let re = Regex::new(r"\{\d*\}").unwrap(); @@ -100,7 +106,7 @@ fn create_token_from_pos( /// * Find if the snippet exists /// * Create a snippet with the given data /// * Write the snippet -pub(crate) fn create_snippet(args: Cli) { +pub fn create_snippet(args: &Cli) { // if args.verbose println!("{}",save_path); let string = if args.edit { edit::edit("").unwrap() @@ -109,7 +115,7 @@ pub(crate) fn create_snippet(args: Cli) { }; // Create a snippet with the given data - let snp = Snippet::new(args.snipplet.clone(), args.args, string); + let snp = Snippet::new(args.snipplet.clone(), args.args.clone(), string); let (file, save_path) = open_path(&snp); if args.locate { println!("Saving snippet to {:?}", save_path); @@ -178,7 +184,7 @@ pub fn print_snippet(args: &Cli) { edit::edit(snp.content).unwrap(); } (true, false) => print_path(&path), - (false, true) => edit_snippet(&snp), + (false, true) => edit_snippet_content(&snp), (false, false) => (), } println!("{}", f_str); @@ -189,8 +195,16 @@ fn print_path(path: &Path) { println!("{}", path.to_string_lossy()); } +/// 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) { + // Load snippet + // Edit content + // Write snippet +} + /// Edit the snippet and write it again -fn edit_snippet(snp: &Snippet) { +fn edit_snippet_content(snp: &Snippet) { 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 ? -- 2.45.1 From 8b5b1719e60b2607add0e1aceb460223ca1ed484 Mon Sep 17 00:00:00 2001 From: beffroi Date: Sat, 20 May 2023 13:55:36 +0200 Subject: [PATCH 06/20] adds a part of the error Implementation --- src/errors.rs | 33 +++++++++++++++++++++++++++------ src/main.rs | 10 ++++------ src/snippet.rs | 29 ++++++++++++++++++++--------- 3 files changed, 51 insertions(+), 21 deletions(-) diff --git a/src/errors.rs b/src/errors.rs index b52ea84..e818013 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -1,32 +1,53 @@ //! A general error module for the snp program +use std::{error, fmt}; + /// Snippet error, general error wrapper for the Snippet module /// All error are wrapper with more information available with the source() method #[derive(Debug)] -enum SnippetError { +pub enum SnippetError { + /// A supposedly impossible to trigger error + #[allow(dead_code)] Unknown, - Parse(PlaceHolder), + /// Clap error, originating from the Cli parser + ClapError(clap::error::Error), + /// A generic IOError, the source is mandatory to get the specifics + IOError(std::io::Error), } +#[derive(Debug)] struct PlaceHolder {} impl fmt::Display for SnippetError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { SnippetError::Unknown => write!(f, "An unknonw error occured"), - // DoubleError::Parse(..) => - // write!(f, "the provided string could not be parsed as int"), + SnippetError::ClapError(..) => write!(f, "A known error occured"), + SnippetError::IOError(..) => write!(f, "An error occured while editing the file"), } } } -impl error::Error for DoubleError { +impl error::Error for SnippetError { fn source(&self) -> Option<&(dyn error::Error + 'static)> { match *self { SnippetError::Unknown => None, // The cause is the underlying implementation error type. Is implicitly // cast to the trait object `&error::Error`. This works because the // underlying type already implements the `Error` trait. - DoubleError::Parse(ref e) => Some(e), + SnippetError::ClapError(ref e) => Some(e), + SnippetError::IOError(ref e) => Some(e), } } } + +impl From for SnippetError { + fn from(err: clap::error::Error) -> SnippetError { + SnippetError::ClapError(err) + } +} + +impl From for SnippetError { + fn from(err: std::io::Error) -> SnippetError { + SnippetError::IOError(err) + } +} diff --git a/src/main.rs b/src/main.rs index 059729d..b11296b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,6 +5,7 @@ use clap::Parser; mod dynamic_formatter; +mod errors; mod snippet; use crate::snippet::{create_snippet, print_snippet}; @@ -55,7 +56,7 @@ pub enum Actions { Create, } -fn main() { +fn main() -> Result<(), errors::SnippetError> { let cli = Cli::parse(); let list_actions = populate_actions(&cli); @@ -66,12 +67,9 @@ fn main() { Actions::Locate => snippet::locate_snippet(&cli), Actions::Show => snippet::print_snippet(&cli), Actions::Create => snippet::create_snippet(&cli), - } + }?; } - // match cli.create { - // true => create_snippet(cli), - // false => print_snippet(&cli), - // } + Ok(()) } /// Populate a logical vec of succesive actions to perform depending on arguments diff --git a/src/snippet.rs b/src/snippet.rs index aaf65c5..78c066f 100644 --- a/src/snippet.rs +++ b/src/snippet.rs @@ -1,3 +1,4 @@ +use clap::error::Result; use regex::Regex; use serde::{Deserialize, Serialize}; @@ -8,8 +9,11 @@ use std::{ path::{Path, PathBuf}, }; -use crate::dynamic_formatter::{complete_vec, dynamic_formatter}; use crate::Cli; +use crate::{ + dynamic_formatter::{complete_vec, dynamic_formatter}, + errors, +}; /// The parsed snippet #[derive(Debug)] @@ -56,8 +60,12 @@ macro_rules! push_if_some { }; } -pub fn edit_whole_snippet(cli: &Cli) {} -pub fn locate_snippet(cli: &Cli) {} +pub fn edit_whole_snippet(cli: &Cli) -> Result<(), errors::SnippetError> { + Ok(()) +} +pub fn locate_snippet(cli: &Cli) -> Result<(), errors::SnippetError> { + Ok(()) +} /// Create a token list from the snippet given and return it pub fn create_tokens_from_string(snippet: &str) { @@ -106,10 +114,10 @@ fn create_token_from_pos( /// * Find if the snippet exists /// * Create a snippet with the given data /// * Write the snippet -pub fn create_snippet(args: &Cli) { +pub fn create_snippet(args: &Cli) -> Result<(), errors::SnippetError> { // if args.verbose println!("{}",save_path); let string = if args.edit { - edit::edit("").unwrap() + edit::edit("")? } else { String::from("") }; @@ -122,8 +130,9 @@ pub fn create_snippet(args: &Cli) { } // Write the snippet - snp.save(file) - .unwrap_or_else(|_| panic!("Couldn't write yaml to file {:?}", save_path)); + snp.save(file)?; + // .unwrap_or_else(|_| panic!("Couldn't write yaml to file {:?}", save_path)); + Ok(()) } /// Open the path linked to a snippet @@ -160,7 +169,7 @@ fn config_folder() -> io::Result { } /// Print the snippet to stdout -pub fn print_snippet(args: &Cli) { +pub fn print_snippet(args: &Cli) -> Result<(), errors::SnippetError> { // Try to load the snippet let mut path = config_folder().expect("Coudln't open config folder"); path.push(format!("{}.yaml", args.snipplet)); @@ -188,6 +197,7 @@ pub fn print_snippet(args: &Cli) { (false, false) => (), } println!("{}", f_str); + Ok(()) } /// Print the path of the current snippet @@ -197,10 +207,11 @@ fn print_path(path: &Path) { /// 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) { +pub fn edit_snippet(cli: &Cli) -> Result<(), errors::SnippetError> { // Load snippet // Edit content // Write snippet + Ok(()) } /// Edit the snippet and write it again -- 2.45.1 From 95d7ec95ba5bf1094b9c539251a389f99cceca7c Mon Sep 17 00:00:00 2001 From: beffroi Date: Sat, 20 May 2023 16:55:47 +0200 Subject: [PATCH 07/20] Adds all custom errors (for now) transforms all panics in errors --- TODO.md | 10 +- src/dynamic_formatter.rs | 39 +++++- src/errors.rs | 18 +++ src/main.rs | 15 +- src/snippet.rs | 288 ++++----------------------------------- src/tokenizer.rs | 93 +++++++++++++ src/wrapper_functions.rs | 140 +++++++++++++++++++ 7 files changed, 324 insertions(+), 279 deletions(-) create mode 100644 src/tokenizer.rs create mode 100644 src/wrapper_functions.rs diff --git a/TODO.md b/TODO.md index fe289d6..ddc664f 100644 --- a/TODO.md +++ b/TODO.md @@ -9,11 +9,15 @@ ## TODO [ ] Make a lib for dynamic_format and snippets (impl make a trait for have .id() and other future t) - [ ] Make custom errors - [ ] Transform all panic in errors [ ] Make functions into methods [-] Have identical attributes with {0} {1} {0} (^^^^^) [ ] Update tests [ ] Benchmarks [ ] Better modes - [ ] Test populate_actions \ No newline at end of file + [ ] Test populate_actions + [ ] Coverage + +### Currently working on + [ ] Make custom errors + [ ] Transform all panic in errors + diff --git a/src/dynamic_formatter.rs b/src/dynamic_formatter.rs index a0fc617..f8ae20e 100644 --- a/src/dynamic_formatter.rs +++ b/src/dynamic_formatter.rs @@ -1,7 +1,8 @@ //! A lib of vector operators //! Allow for replacement and formatting of strings -use crate::snippet::create_tokens_from_string; +use crate::{errors::SnippetError, tokenizer::create_tokens_from_string}; + /// A dynamic formatter, formatting a string with any number of /// {} with element of a Vec, by default the search doen't need to /// be exhaustive and wont fail if either the array or format string don't @@ -9,7 +10,7 @@ use crate::snippet::create_tokens_from_string; /// A pseudo dynamic formatter, tries to fill all {} in a string with the values /// in a vector -pub fn dynamic_formatter(format_string: &str, vector: Vec) -> Result +pub fn dynamic_format(format_string: &str, vector: Vec) -> Result where T: std::fmt::Display, { @@ -32,14 +33,14 @@ where } /// Fill the argument vector with a list of defaults values if needed -pub fn complete_vec(to_fill: &Vec, defaults: &Vec) -> Result, ()> +pub fn complete_vec(to_fill: &Vec, defaults: &Vec) -> Result, SnippetError> where T: Clone, { let size_o = to_fill.len(); let size_d = defaults.len(); match size_o.cmp(&size_d) { - std::cmp::Ordering::Greater => Err(()), + std::cmp::Ordering::Greater => Err(SnippetError::Unknown), //TODO: Fix this error std::cmp::Ordering::Equal => Ok(to_fill.clone()), std::cmp::Ordering::Less => { let mut output = to_fill.clone(); @@ -50,3 +51,33 @@ where } } } + +#[cfg(test)] +mod test { + use super::*; + #[test] + fn test_dynamic_format() { + let res = dynamic_format( + "big str {} with many {} formatters", + vec!["aaa", "bbb", "ccc", "dddd"], + ) + .unwrap(); + assert_eq!(res, ("big str aaa with many bbb formatters".to_string())); + } + + #[test] + fn test_complete_vec() { + let smol = vec!["A"]; + let big = vec!["a", "b", "c", "d", "e", "f"]; + let eq = vec!["T", "U", "I", "O"]; + let deff = vec!["AA", "BB", "CC", "DD"]; + assert_eq!( + complete_vec(&smol, &deff).unwrap(), + 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") + }; + } +} diff --git a/src/errors.rs b/src/errors.rs index e818013..f6c1cad 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -13,6 +13,8 @@ pub enum SnippetError { ClapError(clap::error::Error), /// A generic IOError, the source is mandatory to get the specifics IOError(std::io::Error), + /// Yaml error, generated during serialisation of snippets + YAMLError(serde_yaml::Error), } #[derive(Debug)] @@ -23,6 +25,9 @@ impl fmt::Display for SnippetError { SnippetError::Unknown => write!(f, "An unknonw error occured"), SnippetError::ClapError(..) => write!(f, "A known error occured"), SnippetError::IOError(..) => write!(f, "An error occured while editing the file"), + SnippetError::YAMLError(..) => { + write!(f, "Couldn't convert the given arguments into a yaml") + } } } } @@ -36,6 +41,7 @@ impl error::Error for SnippetError { // underlying type already implements the `Error` trait. SnippetError::ClapError(ref e) => Some(e), SnippetError::IOError(ref e) => Some(e), + SnippetError::YAMLError(ref e) => Some(e), } } } @@ -51,3 +57,15 @@ impl From for SnippetError { SnippetError::IOError(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/main.rs b/src/main.rs index b11296b..175fff4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,9 +7,8 @@ use clap::Parser; mod dynamic_formatter; mod errors; mod snippet; - -use crate::snippet::{create_snippet, print_snippet}; -// use serde_yaml; +mod tokenizer; +mod wrapper_functions; /// The cli arguments to give to the utility #[derive(Parser, Debug)] @@ -62,11 +61,11 @@ fn main() -> Result<(), errors::SnippetError> { let list_actions = populate_actions(&cli); for action in list_actions.iter() { match action { - Actions::Edit => snippet::edit_snippet(&cli), - Actions::EditAll => snippet::edit_whole_snippet(&cli), - Actions::Locate => snippet::locate_snippet(&cli), - Actions::Show => snippet::print_snippet(&cli), - Actions::Create => snippet::create_snippet(&cli), + Actions::Edit => wrapper_functions::edit_snippet(&cli), + Actions::EditAll => wrapper_functions::edit_whole_snippet(&cli), + Actions::Locate => wrapper_functions::locate_snippet(&cli), + Actions::Show => wrapper_functions::print_snippet(&cli), + Actions::Create => wrapper_functions::create_snippet(&cli), }?; } Ok(()) diff --git a/src/snippet.rs b/src/snippet.rs index 78c066f..5e8abdb 100644 --- a/src/snippet.rs +++ b/src/snippet.rs @@ -1,240 +1,24 @@ +//! Snippet module, holding most of the logic of the snippet +//! +//! Saving, loading, writing etc... + use clap::error::Result; -use regex::Regex; use serde::{Deserialize, Serialize}; +use std::io::Write; -use std::{ - env, - fs::{create_dir_all, File}, - io::{self, Write}, - path::{Path, PathBuf}, -}; - -use crate::Cli; -use crate::{ - dynamic_formatter::{complete_vec, dynamic_formatter}, - errors, -}; - -/// The parsed snippet -#[derive(Debug)] -enum Token<'a> { - /// A subsitution token, containing either an index or nothing (and being "positional") - Substitution(CustFormatter), - /// A text token, the inbetween - Text(&'a str), -} - -/// A formatter, containing (or not) an argument to be subsitued with -#[derive(Debug)] -struct CustFormatter { - /// The positional id of the element to replace with - pub id: Option, -} - -impl CustFormatter { - /// Create a CustomFormatter from a string, either void (positional) with a parsable (fixed) - fn new(text: &str) -> CustFormatter { - if text.is_empty() { - return CustFormatter { id: None }; - } - CustFormatter { - id: Some(text.parse::().unwrap()), - } - } -} - -/// Assert where the read head is -enum Status { - /// Read head in inside a formatter - Formater, - /// Read head is outside a formatter - Text, -} - -/// Add not empty values only -macro_rules! push_if_some { - ($vec:ident, $val:expr) => { - if let Some(x) = $val { - $vec.push(x); - }; - }; -} - -pub fn edit_whole_snippet(cli: &Cli) -> Result<(), errors::SnippetError> { - Ok(()) -} -pub fn locate_snippet(cli: &Cli) -> Result<(), errors::SnippetError> { - Ok(()) -} - -/// Create a token list from the snippet given and return it -pub fn create_tokens_from_string(snippet: &str) { - let re = Regex::new(r"\{\d*\}").unwrap(); - let matches = re.find_iter(snippet); - let mut readhead = 0; // Starting to read at zero - let mut token_list = Vec::new(); - for r in matches { - // Assume we matched text from read to here - println!("{:?}", r); - push_if_some!( - token_list, - create_token_from_pos(snippet, Status::Text, readhead, Some(r.start())) - ); - push_if_some!( - token_list, - create_token_from_pos(snippet, Status::Formater, r.start(), Some(r.end()),) - ); - readhead = r.end(); - } - create_token_from_pos(snippet, Status::Text, readhead, None); - println!("{:?}", token_list); -} - -/// Create a single token from the current positions -fn create_token_from_pos( - text: &str, - status: Status, - start: usize, - stop: Option, -) -> Option { - let text = match (stop, status) { - (None, Status::Formater) => Token::Substitution(CustFormatter::new(&text[start + 1..])), - (None, Status::Text) => Token::Text(&text[start..]), - (Some(stop), Status::Formater) => { - Token::Substitution(CustFormatter::new(&text[start + 1..stop - 1])) - } - (Some(stop), Status::Text) => Token::Text(&text[start..stop]), - }; - - println!("{:?}", text); - Some(text) -} - -/// 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<(), errors::SnippetError> { - // if args.verbose println!("{}",save_path); - let string = if args.edit { - edit::edit("")? - } else { - String::from("") - }; - - // Create a snippet with the given data - let snp = Snippet::new(args.snipplet.clone(), args.args.clone(), string); - let (file, save_path) = open_path(&snp); - if args.locate { - println!("Saving snippet to {:?}", save_path); - } - - // Write the snippet - snp.save(file)?; - // .unwrap_or_else(|_| panic!("Couldn't write yaml to file {:?}", save_path)); - Ok(()) -} - -/// Open the path linked to a snippet -fn open_path(snp: &Snippet) -> (File, PathBuf) { - // Find if the snippet exists - let mut save_path = match config_folder() { - Ok(path) => path, - Err(e) => panic!( - "The OS couldn't locate a place to save the snippets.\n {}", - e - ), - }; - - let file = match create_dir_all(&save_path) { - Ok(()) => { - save_path.push(format!("{}.yaml", snp.name)); - File::create(&save_path).unwrap_or_else(|e| { - panic!("Couldn't create snippet file at {:?} {:}", save_path, e) - }) - } - Err(e) => panic!("Couldn't write to path {:?}. {}", save_path, e), - }; - (file, save_path) -} - -/// Find a configuration folder/name for the given snippet name -fn config_folder() -> io::Result { - let exe = env::current_exe()?; - let dir = exe.parent().expect("Executable must be in some directory"); - let mut dir = dir.join(".config"); - dir.push("snp_config"); - // dir.push(format!("{}.yaml", name)); - Ok(dir) -} - -/// Print the snippet to stdout -pub fn print_snippet(args: &Cli) -> Result<(), errors::SnippetError> { - // Try to load the snippet - let mut path = config_folder().expect("Coudln't open config folder"); - path.push(format!("{}.yaml", args.snipplet)); - let f = std::fs::File::open(&path).expect("Could not open snippet file."); - let snp: Snippet = serde_yaml::from_reader(f).expect("Couldn't parse values"); - - // Add the given arguments to the snippet - let final_args = match complete_vec(&args.args, &snp.default_values) { - Err(_) => panic!("Too many arguments given to the snippet, aborting"), - Ok(argg) => argg, - }; - - // Print the snippet - let f_str = match dynamic_formatter(&snp.content, final_args) { - Err(_) => panic!("Couldn't format the snippet !"), - Ok(sn) => sn, - }; - match (args.locate, args.edit) { - (true, true) => { - print_path(&path); - edit::edit(snp.content).unwrap(); - } - (true, false) => print_path(&path), - (false, true) => edit_snippet_content(&snp), - (false, false) => (), - } - println!("{}", f_str); - Ok(()) -} - -/// Print the path of the current snippet -fn print_path(path: &Path) { - println!("{}", path.to_string_lossy()); -} - -/// 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<(), errors::SnippetError> { - // Load snippet - // Edit content - // Write snippet - Ok(()) -} - -/// Edit the snippet and write it again -fn edit_snippet_content(snp: &Snippet) { - 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, path) = open_path(&snp); - snp.save(file) - .unwrap_or_else(|e| println!("Coudln't save to file {:?} {}", path, e)); -} +use crate::errors::{self, SnippetError}; /// A snippet ready to be Serialized/Deserialized #[derive(Deserialize, Serialize, Debug)] pub struct Snippet { /// Akin to path, the name of the snippet is where to store it - name: String, + pub name: String, /// The default value of all args - default_values: Vec, + pub default_values: Vec, /// The base string to format - content: String, + pub content: String, } impl Snippet { @@ -248,50 +32,26 @@ impl Snippet { } /// Save the snippet at the default location under it's name - pub fn save(&self, mut file: File) -> Result<(), std::io::Error> { - write!( - file, - "{}", - serde_yaml::to_string(self).expect("Couldn't convert the given arguments into a yaml") - ) + pub fn save(&self, mut file: std::fs::File) -> Result<(), errors::SnippetError> { + write!(file, "{}", serde_yaml::to_string(self)?)?; + Ok(()) } + /// Force the write of a file + // pub fn force_save(&self) + /// Tries to load a path and return a snippet - // pub fn load(path: String) -> Result { - // Err(()) - // } + pub fn load(path: String) -> Result { + todo!(); + } /// Write to stdout the snipped with either default arguments or given arguments - pub fn print(&self) -> Result<(), ()> { + pub fn print(&self) -> Result<(), SnippetError> { + Ok(()) + } + + /// Delete a snippet + pub fn delete(&self) -> Result<(), SnippetError> { Ok(()) } } - -#[cfg(test)] -mod test { - use super::*; - #[test] - fn test_dynamic_format() { - let res = dynamic_formatter( - "big str {} with many {} formatters", - vec!["aaa", "bbb", "ccc", "dddd"], - ); - assert_eq!(res, Ok("big str aaa with many bbb formatters".to_string())); - } - - #[test] - fn test_complete_vec() { - let smol = vec!["A"]; - let big = vec!["a", "b", "c", "d", "e", "f"]; - let eq = vec!["T", "U", "I", "O"]; - let deff = vec!["AA", "BB", "CC", "DD"]; - assert_eq!( - complete_vec(&smol, &deff).unwrap(), - 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") - }; - } -} diff --git a/src/tokenizer.rs b/src/tokenizer.rs new file mode 100644 index 0000000..57d3959 --- /dev/null +++ b/src/tokenizer.rs @@ -0,0 +1,93 @@ +//! Tokenizer module, tasked to parse a string and return a list of tokens +//! +//! As the dynamic formatter, the tokenizer is supposedly format agnostic + +use regex::Regex; + +/// A formatter, containing (or not) an argument to be subsitued with +#[derive(Debug)] +struct CustFormatter { + /// The positional id of the element to replace with + pub id: Option, +} + +impl CustFormatter { + /// Create a CustomFormatter from a string, either void (positional) with a parsable (fixed) + fn new(text: &str) -> CustFormatter { + if text.is_empty() { + return CustFormatter { id: None }; + } + CustFormatter { + id: Some(text.parse::().unwrap()), + } + } +} + +/// The parsed snippet +#[derive(Debug)] +enum Token<'a> { + /// A subsitution token, containing either an index or nothing (and being "positional") + Substitution(CustFormatter), + /// A text token, the inbetween + Text(&'a str), +} + +/// Assert where the read head is +enum Status { + /// Read head in inside a formatter + Formater, + /// Read head is outside a formatter + Text, +} + +/// Add not empty values only +macro_rules! push_if_some { + ($vec:ident, $val:expr) => { + if let Some(x) = $val { + $vec.push(x); + }; + }; +} + +/// Create a Token list from the snippet given and return it as a vector of token +pub fn create_tokens_from_string(snippet: &str) { + let re = Regex::new(r"\{\d*\}").unwrap(); + let matches = re.find_iter(snippet); + let mut readhead = 0; // Starting to read at zero + let mut token_list = Vec::new(); + for r in matches { + // Assume we matched text from read to here + println!("{:?}", r); + push_if_some!( + token_list, + create_token_from_pos(snippet, Status::Text, readhead, Some(r.start())) + ); + push_if_some!( + token_list, + create_token_from_pos(snippet, Status::Formater, r.start(), Some(r.end()),) + ); + readhead = r.end(); + } + create_token_from_pos(snippet, Status::Text, readhead, None); + println!("{:?}", token_list); +} + +/// Create a single Token from the current positions +fn create_token_from_pos( + text: &str, + status: Status, + start: usize, + stop: Option, +) -> Option { + let text = match (stop, status) { + (None, Status::Formater) => Token::Substitution(CustFormatter::new(&text[start + 1..])), + (None, Status::Text) => Token::Text(&text[start..]), + (Some(stop), Status::Formater) => { + Token::Substitution(CustFormatter::new(&text[start + 1..stop - 1])) + } + (Some(stop), Status::Text) => Token::Text(&text[start..stop]), + }; + + println!("{:?}", text); + Some(text) +} diff --git a/src/wrapper_functions.rs b/src/wrapper_functions.rs new file mode 100644 index 0000000..8cdd6f3 --- /dev/null +++ b/src/wrapper_functions.rs @@ -0,0 +1,140 @@ +//! Module holding the wrapper function called from the main functions +//! +//! All functions included should either take a Cli object and return a SnippetError +//! or be a helper function for such a function + +use std::{ + env, + fs::{create_dir_all, File}, + io, + path::{Path, PathBuf}, +}; + +use crate::dynamic_formatter; +use crate::{dynamic_formatter::complete_vec, errors::SnippetError, snippet::Snippet, Cli}; + +/// Edit the whole snippet and save it where neededi +/// Note that the snippet can be saved with another name and might trigger +/// a creation or an override +pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> { + Ok(()) +} + +/// Locate and print a snippet location +pub fn locate_snippet(cli: &Cli) -> Result<(), SnippetError> { + Ok(()) +} + +/// Print the path of the current snippet +fn print_path(path: &Path) { + println!("{}", path.to_string_lossy()); +} + +/// Print the snippet to stdout +pub fn print_snippet(args: &Cli) -> Result<(), SnippetError> { + // Try to load the snippet + let mut path = config_folder()?; //.expect("Coudn't open config forder"); + path.push(format!("{}.yaml", args.snipplet)); + let f = std::fs::File::open(&path)?; //.expect("Could not open snippet file."); + let snp: Snippet = serde_yaml::from_reader(f)?; //.expect("Couldn't parse values"); + + // Add the given arguments to the snippet + // let final_args = match complete_vec(&args.args, &snp.default_values) { + // Err(_) => panic!("Too many arguments given to the snippet, aborting"), + // Ok(argg) => argg, + // }; + let final_args = complete_vec(&args.args, &snp.default_values)?; + + // Print the snippet + // let f_str = match dynamic_formatter::dynamic_formatter(&snp.content, final_args) { + // Err(_) => panic!("Couldn't format the snippet !"), + // Ok(sn) => sn, + // }; + let f_str = dynamic_formatter::dynamic_format(&snp.content, final_args)?; + + match (args.locate, args.edit) { + (true, true) => { + print_path(&path); + edit::edit(snp.content)?; + } + (true, false) => print_path(&path), + (false, true) => edit_snippet_content(&snp)?, + (false, false) => (), + } + println!("{}", f_str); + 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> { + // Load snippet + // Edit content + // Write snippet + 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(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> { + // if args.verbose println!("{}",save_path); + let string = if args.edit { + edit::edit("")? + } else { + String::from("") + }; + + // Create a snippet with the given data + let snp = Snippet::new(args.snipplet.clone(), args.args.clone(), string); + let file = open_path(&snp)?; + // TODO: LOCATE + // if args.locate { + // println!("Saving snippet to {:?}", save_path); + // } + + // Write the snippet + snp.save(file)?; + // .unwrap_or_else(|_| panic!("Couldn't write yaml to file {:?}", save_path)); + Ok(()) +} + +/// Open the path linked to a snippet +fn open_path(snp: &Snippet) -> Result { + // Find if the snippet exists + let mut save_path = config_folder()?; + // Err(e) => panic!("The OS couldn't locate a place to save the snippets.\n {}"), + + let file = match create_dir_all(&save_path) { + Ok(()) => { + save_path.push(format!("{}.yaml", snp.name)); + File::create(&save_path).unwrap_or_else(|e| { + panic!("Couldn't create snippet file at {:?} {:}", save_path, e) + }) + } + Err(e) => panic!("Couldn't write to path {:?}. {}", save_path, e), + }; + Ok(file) +} + +/// Find a configuration folder/name for the given snippet name +fn config_folder() -> Result { + let exe = env::current_exe()?; + let dir = exe.parent().expect("Executable must be in some directory"); + let mut dir = dir.join(".config"); + dir.push("snp_config"); + // dir.push(format!("{}.yaml", name)); + Ok(dir) +} -- 2.45.1 From 700ea029feeb6c341830b3df3a62fc22549a0b64 Mon Sep 17 00:00:00 2001 From: beffroi Date: Sat, 20 May 2023 19:18:39 +0200 Subject: [PATCH 08/20] Adds massive amount of refactor --- TODO.md | 17 +++++++++++--- src/errors.rs | 13 +++++++++++ src/main.rs | 2 +- src/snippet.rs | 50 +++++++++++++++++++++++++++++++++++++--- src/wrapper_functions.rs | 38 ++++++++++++++++++++++++------ 5 files changed, 106 insertions(+), 14 deletions(-) diff --git a/TODO.md b/TODO.md index ddc664f..32840cb 100644 --- a/TODO.md +++ b/TODO.md @@ -16,8 +16,19 @@ [ ] Better modes [ ] Test populate_actions [ ] Coverage - + [ ] Remake all methods + [ ] + ### Currently working on - [ ] Make custom errors - [ ] Transform all panic in errors + [ ] Remake all helper functions + [ ] edit_snippet + [ ] edit_whole_snippet + [ ] locate_snippet + [ ] print_snippet + [ ] create_snippet + + +## Finished + [*] Make custom errors + [*] Transform all panic in errors diff --git a/src/errors.rs b/src/errors.rs index f6c1cad..d8d311a 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -15,6 +15,8 @@ pub enum SnippetError { IOError(std::io::Error), /// Yaml error, generated during serialisation of snippets YAMLError(serde_yaml::Error), + /// The file already exists and no creation flag was set + ExistsError(std::io::Error), } #[derive(Debug)] @@ -28,6 +30,10 @@ impl fmt::Display for SnippetError { SnippetError::YAMLError(..) => { write!(f, "Couldn't convert the given arguments into a yaml") } + SnippetError::ExistsError(..) => write!( + f, + "The file already exists. Use -c or -f to create it or force overwrite." + ), } } } @@ -42,6 +48,7 @@ impl error::Error for SnippetError { SnippetError::ClapError(ref e) => Some(e), SnippetError::IOError(ref e) => Some(e), SnippetError::YAMLError(ref e) => Some(e), + SnippetError::ExistsError(ref e) => Some(e), } } } @@ -64,6 +71,12 @@ impl From for SnippetError { } } +// 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/main.rs b/src/main.rs index 175fff4..b6e60b6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,7 +16,7 @@ mod wrapper_functions; pub struct Cli { /// The snippet name (and therefore his path) #[arg()] - snipplet: String, + snippet: String, /// Wether to try to load or instead create a new one #[arg(short, long, default_value_t = false)] diff --git a/src/snippet.rs b/src/snippet.rs index 5e8abdb..4de839c 100644 --- a/src/snippet.rs +++ b/src/snippet.rs @@ -4,11 +4,18 @@ use clap::error::Result; use serde::{Deserialize, Serialize}; -use std::io::Write; +use std::{fs::File, io::Write}; -use crate::errors::{self, SnippetError}; +use crate::{ + errors::{self, SnippetError}, + wrapper_functions::config_folder, + Cli, +}; /// A snippet ready to be Serialized/Deserialized +/// +/// No conditionnal behaviour is handle by this module, +/// all calls will force, override and delete by default #[derive(Deserialize, Serialize, Debug)] pub struct Snippet { /// Akin to path, the name of the snippet is where to store it @@ -32,7 +39,35 @@ impl Snippet { } /// Save the snippet at the default location under it's name - pub fn save(&self, mut file: std::fs::File) -> Result<(), errors::SnippetError> { + pub fn save(&self, options: &Cli) -> Result<(), errors::SnippetError> { + let mut file = self.open(&self.name, options)?; + write!(file, "{}", serde_yaml::to_string(self)?)?; + Ok(()) + } + + /// Open the file, will create on empty + pub fn open(&self, name: &str, options: &Cli) -> Result { + // Find the config folder + let mut path = config_folder()?; //.expect("Coudn't open config forder"); + // Add path + path.push(format!("{}.yaml", options.snippet)); + // Open the file + let f = match std::fs::File::open(&path) { + Ok(f) => f, + Err(e) => { + if options.create { + File::create(path)? + } else { + return Err(SnippetError::IOError(e)); + } + } + }; //.expect("Could not open snippet file."); + let snp: Snippet = serde_yaml::from_reader(&f)?; //.expect("Couldn't parse values"); + Ok(f) + } + + /// Save the snippet under a path, errors on existing file + pub fn save_as(&self, mut file: std::fs::File) -> Result<(), SnippetError> { write!(file, "{}", serde_yaml::to_string(self)?)?; Ok(()) } @@ -54,4 +89,13 @@ impl Snippet { pub fn delete(&self) -> Result<(), SnippetError> { Ok(()) } + + pub fn from_str(taw_content: &str) -> Result { + // Parse the string + + // Try to create + + // Return the snippet + todo!(); + } } diff --git a/src/wrapper_functions.rs b/src/wrapper_functions.rs index 8cdd6f3..1ebb06b 100644 --- a/src/wrapper_functions.rs +++ b/src/wrapper_functions.rs @@ -6,10 +6,12 @@ use std::{ env, fs::{create_dir_all, File}, - io, + io::{self, Read}, path::{Path, PathBuf}, }; +use edit::edit; + use crate::dynamic_formatter; use crate::{dynamic_formatter::complete_vec, errors::SnippetError, snippet::Snippet, Cli}; @@ -17,6 +19,18 @@ use crate::{dynamic_formatter::complete_vec, errors::SnippetError, snippet::Snip /// Note that the snippet can be saved with another name and might trigger /// a creation or an override pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> { + // Find location + let path = snippet_path(&cli.snippet)?; + // Edit the whole file as str + + let mut f = std::fs::File::open(&path)?; //.expect("Could not open snippet file."); + let mut raw_snippet = String::from(""); + f.read_to_string(&mut raw_snippet)?; + let edited_str = edit(raw_snippet)?; + // Parse the result + let snp = Snippet::from_str(&edited_str)?; + // If no error save with snp.save() + snp.save(cli); Ok(()) } @@ -34,7 +48,7 @@ fn print_path(path: &Path) { pub fn print_snippet(args: &Cli) -> Result<(), SnippetError> { // Try to load the snippet let mut path = config_folder()?; //.expect("Coudn't open config forder"); - path.push(format!("{}.yaml", args.snipplet)); + path.push(format!("{}.yaml", args.snippet)); let f = std::fs::File::open(&path)?; //.expect("Could not open snippet file."); let snp: Snippet = serde_yaml::from_reader(f)?; //.expect("Couldn't parse values"); @@ -68,8 +82,11 @@ pub fn print_snippet(args: &Cli) -> Result<(), SnippetError> { /// 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> { - // Load snippet + // Try loading, if not existant check if create or error + + // let file = File::open(snippet_path(&cli.snippet)?)?; // Edit content + // let content = // Write snippet Ok(()) } @@ -80,7 +97,7 @@ fn edit_snippet_content(snp: &Snippet) -> Result<(), SnippetError> { 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(file)?; + snp.save_as(file)?; // .unwrap_or_else(|e| println!("Coudln't save to file {:?} {}", path, e)); Ok(()) } @@ -98,7 +115,7 @@ pub fn create_snippet(args: &Cli) -> Result<(), SnippetError> { }; // Create a snippet with the given data - let snp = Snippet::new(args.snipplet.clone(), args.args.clone(), string); + let snp = Snippet::new(args.snippet.clone(), args.args.clone(), string); let file = open_path(&snp)?; // TODO: LOCATE // if args.locate { @@ -106,7 +123,7 @@ pub fn create_snippet(args: &Cli) -> Result<(), SnippetError> { // } // Write the snippet - snp.save(file)?; + snp.save_as(file)?; // .unwrap_or_else(|_| panic!("Couldn't write yaml to file {:?}", save_path)); Ok(()) } @@ -130,7 +147,7 @@ fn open_path(snp: &Snippet) -> Result { } /// Find a configuration folder/name for the given snippet name -fn config_folder() -> Result { +pub fn config_folder() -> Result { let exe = env::current_exe()?; let dir = exe.parent().expect("Executable must be in some directory"); let mut dir = dir.join(".config"); @@ -138,3 +155,10 @@ fn config_folder() -> Result { // dir.push(format!("{}.yaml", name)); Ok(dir) } + +/// Find the path of the given snippet +fn snippet_path(snp: &str) -> Result { + let mut dir = config_folder()?; + dir.push(format!("{}.yaml", snp)); + Ok(dir) +} -- 2.45.1 From e8d0119e945fab1efdc40e276151d13884ee3c51 Mon Sep 17 00:00:00 2001 From: beffroi Date: Sat, 20 May 2023 22:27:18 +0200 Subject: [PATCH 09/20] Adds refactor and most function call --- TODO.md | 12 ++-- src/errors.rs | 1 + src/main.rs | 10 ++- src/snippet.rs | 12 +++- src/wrapper_functions.rs | 142 +++++++++++++++++++++------------------ 5 files changed, 99 insertions(+), 78 deletions(-) diff --git a/TODO.md b/TODO.md index 32840cb..42ce03f 100644 --- a/TODO.md +++ b/TODO.md @@ -9,23 +9,23 @@ ## TODO [ ] Make a lib for dynamic_format and snippets (impl make a trait for have .id() and other future t) - [ ] Make functions into methods + [-] Make functions into methods [-] Have identical attributes with {0} {1} {0} (^^^^^) [ ] Update tests [ ] Benchmarks [ ] Better modes [ ] Test populate_actions [ ] Coverage - [ ] Remake all methods + [ ] Remake all Snippet methods [ ] ### Currently working on [ ] Remake all helper functions - [ ] edit_snippet - [ ] edit_whole_snippet - [ ] locate_snippet + [*] locate_snippet + [*] create_snippet + [*] edit_snippet + [*] edit_whole_snippet [ ] print_snippet - [ ] create_snippet ## Finished diff --git a/src/errors.rs b/src/errors.rs index d8d311a..7e923ee 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -5,6 +5,7 @@ use std::{error, fmt}; /// Snippet error, general error wrapper for the Snippet module /// All error are wrapper with more information available with the source() method #[derive(Debug)] +#[allow(dead_code)] pub enum SnippetError { /// A supposedly impossible to trigger error #[allow(dead_code)] diff --git a/src/main.rs b/src/main.rs index b6e60b6..8d891db 100644 --- a/src/main.rs +++ b/src/main.rs @@ -38,6 +38,10 @@ pub struct Cli { /// 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 + #[arg(short, long, default_value_t = false)] + force: bool, } /// List of all possible actions, some are mutually exclusive @@ -61,11 +65,11 @@ fn main() -> Result<(), errors::SnippetError> { let list_actions = populate_actions(&cli); for action in list_actions.iter() { match action { + Actions::Locate => 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::Locate => wrapper_functions::locate_snippet(&cli), - Actions::Show => wrapper_functions::print_snippet(&cli), - Actions::Create => wrapper_functions::create_snippet(&cli), }?; } Ok(()) diff --git a/src/snippet.rs b/src/snippet.rs index 4de839c..5b600ab 100644 --- a/src/snippet.rs +++ b/src/snippet.rs @@ -82,15 +82,15 @@ impl Snippet { /// Write to stdout the snipped with either default arguments or given arguments pub fn print(&self) -> Result<(), SnippetError> { - Ok(()) + todo!(); } /// Delete a snippet pub fn delete(&self) -> Result<(), SnippetError> { - Ok(()) + todo!(); } - pub fn from_str(taw_content: &str) -> Result { + pub fn from_str(raw_content: &str) -> Result { // Parse the string // Try to create @@ -98,4 +98,10 @@ impl Snippet { // Return the snippet todo!(); } + + /// Mutate the contents in place + pub fn edit(&mut self) -> Result<(), SnippetError> { + self.content = edit::edit(self.content.clone())?; + Ok(()) + } } diff --git a/src/wrapper_functions.rs b/src/wrapper_functions.rs index 1ebb06b..76bf6ac 100644 --- a/src/wrapper_functions.rs +++ b/src/wrapper_functions.rs @@ -6,7 +6,7 @@ use std::{ env, fs::{create_dir_all, File}, - io::{self, Read}, + io::Read, path::{Path, PathBuf}, }; @@ -15,6 +15,49 @@ use edit::edit; use crate::dynamic_formatter; use crate::{dynamic_formatter::complete_vec, errors::SnippetError, snippet::Snippet, Cli}; +/// Locate and print a snippet location +/// +/// Will error on snippet not existing +pub fn locate_snippet(cli: &Cli) -> Result<(), SnippetError> { + println!("{}", snippet_path(&cli.snippet)?.to_string_lossy()); + Ok(()) +} + +/// Print the path of the current snippet +fn print_path(path: &Path) { + println!("{}", path.to_string_lossy()); +} + +/// 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, + Err(e) => { + if cli.force { + File::create(&path)? + } else { + return Err(e.into()); + } + } + }; + + let mut snp: Snippet = match serde_yaml::from_reader(f) { + Ok(yaml) => yaml, + Err(e) => { + if cli.create { + Snippet::new(cli.snippet.clone(), cli.args.clone(), String::from("")) + } else { + return Err(e.into()); + } + } + }; + snp.edit()?; + Ok(()) +} + /// Edit the whole snippet and save it where neededi /// Note that the snippet can be saved with another name and might trigger /// a creation or an override @@ -22,7 +65,6 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> { // Find location let path = snippet_path(&cli.snippet)?; // Edit the whole file as str - let mut f = std::fs::File::open(&path)?; //.expect("Could not open snippet file."); let mut raw_snippet = String::from(""); f.read_to_string(&mut raw_snippet)?; @@ -30,18 +72,44 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> { // Parse the result let snp = Snippet::from_str(&edited_str)?; // If no error save with snp.save() - snp.save(cli); + snp.save(cli)?; Ok(()) } -/// Locate and print a snippet location -pub fn locate_snippet(cli: &Cli) -> Result<(), SnippetError> { +/// 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(()) } -/// 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 +/// * 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 @@ -66,68 +134,10 @@ pub fn print_snippet(args: &Cli) -> Result<(), SnippetError> { // }; let f_str = dynamic_formatter::dynamic_format(&snp.content, final_args)?; - match (args.locate, args.edit) { - (true, true) => { - print_path(&path); - edit::edit(snp.content)?; - } - (true, false) => print_path(&path), - (false, true) => edit_snippet_content(&snp)?, - (false, false) => (), - } println!("{}", f_str); 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 file = File::open(snippet_path(&cli.snippet)?)?; - // Edit content - // let content = - // Write snippet - 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> { - // if args.verbose println!("{}",save_path); - let string = if args.edit { - edit::edit("")? - } else { - String::from("") - }; - - // Create a snippet with the given data - let snp = Snippet::new(args.snippet.clone(), args.args.clone(), string); - let file = open_path(&snp)?; - // TODO: LOCATE - // if args.locate { - // println!("Saving snippet to {:?}", save_path); - // } - - // Write the snippet - snp.save_as(file)?; - // .unwrap_or_else(|_| panic!("Couldn't write yaml to file {:?}", save_path)); - Ok(()) -} - /// Open the path linked to a snippet fn open_path(snp: &Snippet) -> Result { // Find if the snippet exists -- 2.45.1 From 3304ba34d82fc1b4c564ef1465cb63406b91680e Mon Sep 17 00:00:00 2001 From: beffroi Date: Sat, 20 May 2023 23:00:25 +0200 Subject: [PATCH 10/20] Cleans up a lot of code --- TODO.md | 4 ++- src/snippet.rs | 44 +++++++++++++------------ src/wrapper_functions.rs | 70 +++++++++++++++++++--------------------- 3 files changed, 59 insertions(+), 59 deletions(-) diff --git a/TODO.md b/TODO.md index 42ce03f..1434ed0 100644 --- a/TODO.md +++ b/TODO.md @@ -18,7 +18,9 @@ [ ] Coverage [ ] Remake all Snippet methods [ ] - + [ ] Chain the methods when possible with result ? + [ ] Change all uncatchables errors to expect to be more helpful or change them to better errors + ### Currently working on [ ] Remake all helper functions [*] locate_snippet diff --git a/src/snippet.rs b/src/snippet.rs index 5b600ab..4818132 100644 --- a/src/snippet.rs +++ b/src/snippet.rs @@ -38,15 +38,17 @@ impl Snippet { } } + // TODO: rewrite as a helper function /// Save the snippet at the default location under it's name pub fn save(&self, options: &Cli) -> Result<(), errors::SnippetError> { - let mut file = self.open(&self.name, options)?; + // Try to open the feed + let mut file = self.open(options)?; write!(file, "{}", serde_yaml::to_string(self)?)?; Ok(()) } /// Open the file, will create on empty - pub fn open(&self, name: &str, options: &Cli) -> Result { + pub fn open(&self, options: &Cli) -> Result { // Find the config folder let mut path = config_folder()?; //.expect("Coudn't open config forder"); // Add path @@ -62,7 +64,7 @@ impl Snippet { } } }; //.expect("Could not open snippet file."); - let snp: Snippet = serde_yaml::from_reader(&f)?; //.expect("Couldn't parse values"); + // let snp: Snippet = serde_yaml::from_reader(&f)?; //.expect("Couldn't parse values"); Ok(f) } @@ -75,29 +77,29 @@ impl Snippet { /// Force the write of a file // pub fn force_save(&self) - /// Tries to load a path and return a snippet - pub fn load(path: String) -> Result { - todo!(); - } + // /// Tries to load a path and return a snippet + // pub fn load(path: String) -> Result { + // todo!(); + // } - /// Write to stdout the snipped with either default arguments or given arguments - pub fn print(&self) -> Result<(), SnippetError> { - todo!(); - } + // /// Write to stdout the snipped with either default arguments or given arguments + // pub fn print(&self) -> Result<(), SnippetError> { + // todo!(); + // } - /// Delete a snippet - pub fn delete(&self) -> Result<(), SnippetError> { - todo!(); - } + // /// Delete a snippet + // pub fn delete(&self) -> Result<(), SnippetError> { + // todo!(); + // } - pub fn from_str(raw_content: &str) -> Result { - // Parse the string + // pub fn from_str(raw_content: &str) -> Result { + // // Parse the string - // Try to create + // // Try to create - // Return the snippet - todo!(); - } + // // Return the snippet + // todo!(); + // } /// Mutate the contents in place pub fn edit(&mut self) -> Result<(), SnippetError> { diff --git a/src/wrapper_functions.rs b/src/wrapper_functions.rs index 76bf6ac..2575918 100644 --- a/src/wrapper_functions.rs +++ b/src/wrapper_functions.rs @@ -3,12 +3,7 @@ //! All functions included should either take a Cli object and return a SnippetError //! or be a helper function for such a function -use std::{ - env, - fs::{create_dir_all, File}, - io::Read, - path::{Path, PathBuf}, -}; +use std::{env, fs::File, io::Read, path::PathBuf}; use edit::edit; @@ -23,10 +18,10 @@ pub fn locate_snippet(cli: &Cli) -> Result<(), SnippetError> { Ok(()) } -/// Print the path of the current snippet -fn print_path(path: &Path) { - println!("{}", path.to_string_lossy()); -} +// /// Print the path of the current snippet +// fn print_path(path: &Path) { +// println!("{}", path.to_string_lossy()); +// } /// Open and load snippet and edit it /// If chained with create, the file will be created, closed and opened again @@ -70,22 +65,22 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> { f.read_to_string(&mut raw_snippet)?; let edited_str = edit(raw_snippet)?; // Parse the result - let snp = Snippet::from_str(&edited_str)?; + let snp: Snippet = serde_yaml::from_str(&edited_str)?; // If no error save with snp.save() snp.save(cli)?; 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(()) -} +// /// 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 @@ -138,23 +133,24 @@ pub fn print_snippet(args: &Cli) -> Result<(), SnippetError> { Ok(()) } -/// Open the path linked to a snippet -fn open_path(snp: &Snippet) -> Result { - // Find if the snippet exists - let mut save_path = config_folder()?; - // Err(e) => panic!("The OS couldn't locate a place to save the snippets.\n {}"), +// TODO: Remove as the opening can't be generalized +// /// Open the path linked to a snippet +// fn open_path(snp: &Snippet) -> Result { +// // Find if the snippet exists +// let mut save_path = config_folder()?; +// // Err(e) => panic!("The OS couldn't locate a place to save the snippets.\n {}"), - let file = match create_dir_all(&save_path) { - Ok(()) => { - save_path.push(format!("{}.yaml", snp.name)); - File::create(&save_path).unwrap_or_else(|e| { - panic!("Couldn't create snippet file at {:?} {:}", save_path, e) - }) - } - Err(e) => panic!("Couldn't write to path {:?}. {}", save_path, e), - }; - Ok(file) -} +// let file = match create_dir_all(&save_path) { +// Ok(()) => { +// save_path.push(format!("{}.yaml", snp.name)); +// File::create(&save_path).unwrap_or_else(|e| { +// panic!("Couldn't create snippet file at {:?} {:}", save_path, e) +// }) +// } +// Err(e) => panic!("Couldn't write to path {:?}. {}", save_path, e), +// }; +// Ok(file) +// } /// Find a configuration folder/name for the given snippet name pub fn config_folder() -> Result { -- 2.45.1 From dd802cdcbcc7e24983251f7cd6f26be098e91a28 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 21 May 2023 16:31:00 +0200 Subject: [PATCH 11/20] Adds test for locate --- Makefile.toml | 10 ++++++ TODO.md | 1 + src/errors.rs | 14 ++++++-- src/wrapper_functions.rs | 75 ++++++++++++++++++++++++++++++++++++++-- 4 files changed, 94 insertions(+), 6 deletions(-) create mode 100644 Makefile.toml diff --git a/Makefile.toml b/Makefile.toml new file mode 100644 index 0000000..92d84ac --- /dev/null +++ b/Makefile.toml @@ -0,0 +1,10 @@ +[tasks.testcov] +script_runner = "@shell" +ignore_errors = true +script = [ +"mkdir -p coverage", +"mkdir -p coverage/html", +"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", +"grcov . --binary-path ./target/debug/deps/ -s . -t html --branch --ignore-not-existing --ignore '../*' --ignore '/*' --ignore '*xiv_csolver.rs' --ignore '*python*.rs' -o coverage/html/", +] \ No newline at end of file diff --git a/TODO.md b/TODO.md index 1434ed0..cd36001 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,7 @@ [ ] Change all uncatchables errors to expect to be more helpful or change them to better errors ### Currently working on + [ ] Proceed one by one and catch errors [ ] Remake all helper functions [*] locate_snippet [*] create_snippet diff --git a/src/errors.rs b/src/errors.rs index 7e923ee..a046f47 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -1,6 +1,6 @@ //! A general error module for the snp program -use std::{error, fmt}; +use std::{error, fmt, path::PathBuf}; /// Snippet error, general error wrapper for the Snippet module /// All error are wrapper with more information available with the source() method @@ -18,10 +18,10 @@ pub enum SnippetError { YAMLError(serde_yaml::Error), /// The file already exists and no creation flag was set ExistsError(std::io::Error), + /// The file doen't exist and no creation was asked + NotFoundNoRetryError(PathBuf), } -#[derive(Debug)] -struct PlaceHolder {} impl fmt::Display for SnippetError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { @@ -35,6 +35,13 @@ impl fmt::Display for SnippetError { f, "The file already exists. Use -c or -f to create it or force overwrite." ), + SnippetError::NotFoundNoRetryError(ref p) => { + write!( + f, + "The config {:?} doen't exists. Use -c to create it.", + p.file_name(), + ) + } } } } @@ -50,6 +57,7 @@ impl error::Error for SnippetError { SnippetError::IOError(ref e) => Some(e), SnippetError::YAMLError(ref e) => Some(e), SnippetError::ExistsError(ref e) => Some(e), + SnippetError::NotFoundNoRetryError(_) => None, } } } diff --git a/src/wrapper_functions.rs b/src/wrapper_functions.rs index 2575918..0189f64 100644 --- a/src/wrapper_functions.rs +++ b/src/wrapper_functions.rs @@ -3,6 +3,7 @@ //! All functions included should either take a Cli object and return a SnippetError //! or be a helper function for such a function +use std::fs::create_dir_all; use std::{env, fs::File, io::Read, path::PathBuf}; use edit::edit; @@ -14,8 +15,14 @@ use crate::{dynamic_formatter::complete_vec, errors::SnippetError, snippet::Snip /// /// Will error on snippet not existing pub fn locate_snippet(cli: &Cli) -> Result<(), SnippetError> { - println!("{}", snippet_path(&cli.snippet)?.to_string_lossy()); - Ok(()) + let status = check_dir_and_open(&cli.snippet)?; + match status { + FileStatus::Opened((p, _)) => { + println!("{:?}", p.as_os_str()); + Ok(()) + } + FileStatus::NotFound(p) => Err(SnippetError::NotFoundNoRetryError(p)), + } } // /// Print the path of the current snippet @@ -60,7 +67,7 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> { // Find location let path = snippet_path(&cli.snippet)?; // Edit the whole file as str - let mut f = std::fs::File::open(&path)?; //.expect("Could not open snippet file."); + let mut f = std::fs::File::open(path)?; let mut raw_snippet = String::from(""); f.read_to_string(&mut raw_snippet)?; let edited_str = edit(raw_snippet)?; @@ -152,6 +159,30 @@ pub fn print_snippet(args: &Cli) -> Result<(), SnippetError> { // Ok(file) // } +/// 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 + /// because the path is sometimes usefull to know, but may be dropped + /// when not + Opened((PathBuf, File)), + /// The file didn't exists and might need to be created + NotFound(PathBuf), +} + +/// Full wrapper function, tries to open the config +/// Create the folder and tries to open the file +/// On sucess return a FileStatus::File and a FileStatus::Path or error +/// The rest of the logic is handled by the caller +pub fn check_dir_and_open(name: &str) -> Result { + let mut dir_path = config_folder()?; + create_dir_all(&dir_path)?; + dir_path.push(format!("{}.yaml", name)); + match File::open(&dir_path) { + Ok(f) => Ok(FileStatus::Opened((dir_path, f))), + Err(_e) => Ok(FileStatus::NotFound(dir_path)), + } +} + /// Find a configuration folder/name for the given snippet name pub fn config_folder() -> Result { let exe = env::current_exe()?; @@ -163,8 +194,46 @@ pub fn config_folder() -> Result { } /// Find the path of the given snippet +/// This function should suceed in every situation where a config folder can be set fn snippet_path(snp: &str) -> Result { let mut dir = config_folder()?; dir.push(format!("{}.yaml", snp)); Ok(dir) } + +#[cfg(test)] +mod test { + use std::io::Write; + + use clap::Parser; + + use super::*; + + #[test] + fn test_config_creation() { + // Try to locate where to set the config + let _ = match check_dir_and_open("test_config_creation").expect("Can't open config") { + FileStatus::Opened((_, f)) => f, + FileStatus::NotFound(p) => File::create(p).expect("Can't create path"), + }; + } + + #[test] + fn test_locate() { + // Try to locate an unexisting snippet + let theorical_path = snippet_path("test_locate").expect("Can't find config path"); + if let Err(e) = std::fs::remove_file(&theorical_path) { + println!("[Info] File didn't exist {:?}", e); + } + + // Locating the snippet should fail + assert!(locate_snippet(&Cli::parse_from(vec!["-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()); + } +} -- 2.45.1 From 8e5d6a0e819a5b47f79f8f63562d3272410ed258 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 21 May 2023 18:23:04 +0200 Subject: [PATCH 12/20] 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()); } } -- 2.45.1 From e1e46765a0b695f3bec2431a99601237780be99e Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 21 May 2023 18:52:18 +0200 Subject: [PATCH 13/20] Adds and tests snippet creation --- TODO.md | 2 +- src/snippet.rs | 33 ++++++--------------------------- src/wrapper_functions.rs | 39 ++++++++++++++++++--------------------- 3 files changed, 25 insertions(+), 49 deletions(-) diff --git a/TODO.md b/TODO.md index c50f5c8..e37d4ed 100644 --- a/TODO.md +++ b/TODO.md @@ -23,7 +23,7 @@ ### Currently working on [ ] Proceed one by one and catch errors - [ ] Remake all helper functions + [-] Remake all helper functions [*] locate_snippet [*] create_snippet [-] edit_snippet diff --git a/src/snippet.rs b/src/snippet.rs index 4818132..0106c99 100644 --- a/src/snippet.rs +++ b/src/snippet.rs @@ -74,36 +74,15 @@ impl Snippet { Ok(()) } - /// Force the write of a file - // pub fn force_save(&self) - - // /// Tries to load a path and return a snippet - // pub fn load(path: String) -> Result { - // todo!(); - // } - - // /// Write to stdout the snipped with either default arguments or given arguments - // pub fn print(&self) -> Result<(), SnippetError> { - // todo!(); - // } - - // /// Delete a snippet - // pub fn delete(&self) -> Result<(), SnippetError> { - // todo!(); - // } - - // pub fn from_str(raw_content: &str) -> Result { - // // Parse the string - - // // Try to create - - // // Return the snippet - // todo!(); - // } - /// Mutate the contents in place pub fn edit(&mut self) -> Result<(), SnippetError> { self.content = edit::edit(self.content.clone())?; Ok(()) } + + /// Create snippet from file buffer (deserialize) + pub fn from_file(f: File) -> Result { + let snp: Snippet = serde_yaml::from_reader(f)?; + Ok(snp) + } } diff --git a/src/wrapper_functions.rs b/src/wrapper_functions.rs index bc72253..f408739 100644 --- a/src/wrapper_functions.rs +++ b/src/wrapper_functions.rs @@ -60,26 +60,14 @@ pub fn create_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 path = snippet_path(&cli.snippet)?; - let f = match File::open(&path) { - Ok(f) => f, - Err(e) => { + let status = check_dir_and_open(&cli.snippet)?; + let mut snp = match status { + FileStatus::Opened((p, f)) => Snippet::from_file(f)?, + FileStatus::NotFound(p) => { if cli.force { - File::create(&path)? - } else { - return Err(e.into()); - } - } - }; - - let mut snp: Snippet = match serde_yaml::from_reader(f) { - Ok(yaml) => yaml, - Err(e) => { - if cli.create { Snippet::new(cli.snippet.clone(), cli.args.clone(), String::from("")) } else { - return Err(e.into()); + return Err(SnippetError::NotFoundNoRetryError(p)); } } }; @@ -194,11 +182,9 @@ fn snippet_path(snp: &str) -> Result { #[cfg(test)] mod test { - use std::io::Write; - - use clap::Parser; - use super::*; + use clap::Parser; + use std::io::Write; macro_rules! false_cli { ($($arg:expr),+) => { @@ -236,6 +222,7 @@ mod test { #[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()); @@ -245,4 +232,14 @@ mod test { // Test to create with force assert!(create_snippet(false_cli!("-c", "-f", "create_snippet")).is_ok()); } + + #[test] + fn test_edit() { + // Test edit non existant + + // Test edit with create + + // Test + // todo!() + } } -- 2.45.1 From 6aa6a1ddd955aa00892a0d32f1180fa41ddda661 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 21 May 2023 23:36:22 +0200 Subject: [PATCH 14/20] Adds support for test on editions, adds edit_whole --- Cargo.toml | 2 + TODO.md | 10 +++- src/errors.rs | 6 ++- src/snippet.rs | 65 ++++++++++------------- src/wrapper_functions.rs | 108 +++++++++++++++++++++++---------------- 5 files changed, 106 insertions(+), 85 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 59b6af3..8459a25 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,6 +3,8 @@ name = "snp" version = "0.1.0" edition = "2021" +[features] +test = [] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] diff --git a/TODO.md b/TODO.md index e37d4ed..ed721db 100644 --- a/TODO.md +++ b/TODO.md @@ -26,9 +26,15 @@ [-] Remake all helper functions [*] locate_snippet [*] create_snippet - [-] edit_snippet - [-] edit_whole_snippet + [*] edit_snippet + [*] edit_whole_snippet [x] print_snippet + [-] Finish tests on + [ ] locate_snippet + [ ] create_snippet + [ ] edit_snippet + [ ] edit_whole_snippet + [ ] print_snippet ## Finished diff --git a/src/errors.rs b/src/errors.rs index 2700d25..2393200 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -22,8 +22,8 @@ pub enum SnippetError { 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) + /// The snippet couldn't be reparsed + ReparsingError, } impl fmt::Display for SnippetError { @@ -51,6 +51,7 @@ impl fmt::Display for SnippetError { "The snippet {:?} already exists. Use -f/--force to overwrite it.", p.file_name(), ), + 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.") } } } @@ -68,6 +69,7 @@ impl error::Error for SnippetError { SnippetError::ExistsError(ref e) => Some(e), SnippetError::NotFoundNoRetryError(_) => None, SnippetError::FoundNoEraseError(_) => None, + SnippetError::ReparsingError => None, } } } diff --git a/src/snippet.rs b/src/snippet.rs index 0106c99..98b95c6 100644 --- a/src/snippet.rs +++ b/src/snippet.rs @@ -6,11 +6,7 @@ use clap::error::Result; use serde::{Deserialize, Serialize}; use std::{fs::File, io::Write}; -use crate::{ - errors::{self, SnippetError}, - wrapper_functions::config_folder, - Cli, -}; +use crate::errors::SnippetError; /// A snippet ready to be Serialized/Deserialized /// @@ -38,44 +34,15 @@ impl Snippet { } } - // TODO: rewrite as a helper function - /// Save the snippet at the default location under it's name - pub fn save(&self, options: &Cli) -> Result<(), errors::SnippetError> { - // Try to open the feed - let mut file = self.open(options)?; - write!(file, "{}", serde_yaml::to_string(self)?)?; - Ok(()) - } - - /// Open the file, will create on empty - pub fn open(&self, options: &Cli) -> Result { - // Find the config folder - let mut path = config_folder()?; //.expect("Coudn't open config forder"); - // Add path - path.push(format!("{}.yaml", options.snippet)); - // Open the file - let f = match std::fs::File::open(&path) { - Ok(f) => f, - Err(e) => { - if options.create { - File::create(path)? - } else { - return Err(SnippetError::IOError(e)); - } - } - }; //.expect("Could not open snippet file."); - // let snp: Snippet = serde_yaml::from_reader(&f)?; //.expect("Couldn't parse values"); - Ok(f) - } - - /// Save the snippet under a path, errors on existing file - pub fn save_as(&self, mut file: std::fs::File) -> Result<(), SnippetError> { + /// Save the snippet in a file, errors on write error + pub fn save_in(&self, mut file: std::fs::File) -> Result<(), SnippetError> { write!(file, "{}", serde_yaml::to_string(self)?)?; Ok(()) } /// Mutate the contents in place pub fn edit(&mut self) -> Result<(), SnippetError> { + // #[cfg(not(test))] self.content = edit::edit(self.content.clone())?; Ok(()) } @@ -85,4 +52,28 @@ impl Snippet { let snp: Snippet = serde_yaml::from_reader(f)?; Ok(snp) } + + /// Create a snippet from a String reference (typically used for edits) + pub fn from_string(buffer: &str) -> std::result::Result { + let snp: Snippet = serde_yaml::from_str(buffer)?; + Ok(snp) + } + + /// Forcefully save a snippet, will erase the file if already existing + pub fn write_over(&self, path: &std::path::PathBuf) -> Result<(), SnippetError> { + let mut f = File::create(path)?; + write!(f, "{}", serde_yaml::to_string(self)?)?; + Ok(()) + } + + /// Create an empty snippet and immediately serialize it + pub fn empty(name: String, default_values: Vec) -> String { + serde_yaml::to_string(&Snippet { + name, + default_values, + content: String::new(), + //..Snippet::default(), + }) + .unwrap() + } } diff --git a/src/wrapper_functions.rs b/src/wrapper_functions.rs index f408739..fca9069 100644 --- a/src/wrapper_functions.rs +++ b/src/wrapper_functions.rs @@ -4,6 +4,7 @@ //! or be a helper function for such a function use std::fs::create_dir_all; +use std::io::{read_to_string, Write}; use std::{env, fs::File, io::Read, path::PathBuf}; use edit::edit; @@ -53,7 +54,7 @@ pub fn create_snippet(cli: &Cli) -> Result<(), SnippetError> { } FileStatus::NotFound(p) => File::create(p)?, // Create a new snippet }; - snp.save_as(f)?; + snp.save_in(f)?; Ok(()) } @@ -62,7 +63,7 @@ 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 mut snp = match status { - FileStatus::Opened((p, f)) => Snippet::from_file(f)?, + FileStatus::Opened((_, f)) => Snippet::from_file(f)?, FileStatus::NotFound(p) => { if cli.force { Snippet::new(cli.snippet.clone(), cli.args.clone(), String::from("")) @@ -79,18 +80,48 @@ pub fn edit_snippet(cli: &Cli) -> Result<(), SnippetError> { /// Note that the snippet can be saved with another name and might trigger /// a creation or an override pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> { - // Find location - let path = snippet_path(&cli.snippet)?; - // Edit the whole file as str - let mut f = std::fs::File::open(path)?; - let mut raw_snippet = String::from(""); - f.read_to_string(&mut raw_snippet)?; - let edited_str = edit(raw_snippet)?; - // Parse the result - let snp: Snippet = serde_yaml::from_str(&edited_str)?; - // If no error save with snp.save() - snp.save(cli)?; - Ok(()) + // Try loading the snippet + let status = check_dir_and_open(&cli.snippet); + let (buf, mut 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) + } else { + return Err(SnippetError::NotFoundNoRetryError(p)); + } + } + }; + + // During tests, the editor cannot be tested + #[cfg(not(feature = "test"))] + let buf = edit::edit(buf)?; + + // Try reparsing, on error no modifications will be made + match Snippet::from_string(&buf) { + Ok(snp) => { + snp.write_over(&p)?; + println!( + "The snippet {:?} was succesfully saved", + p.file_name().unwrap() + ); + 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)?; + write!(failover, "{}", &buf)?; + + println!( + "The snippet was saved under {:?} in your config", + p.file_name().unwrap() + ); + Err(SnippetError::ReparsingError) + } + } } /// Print the snippet to stdout @@ -119,25 +150,6 @@ pub fn print_snippet(args: &Cli) -> Result<(), SnippetError> { Ok(()) } -// TODO: Remove as the opening can't be generalized -// /// Open the path linked to a snippet -// fn open_path(snp: &Snippet) -> Result { -// // Find if the snippet exists -// let mut save_path = config_folder()?; -// // Err(e) => panic!("The OS couldn't locate a place to save the snippets.\n {}"), - -// let file = match create_dir_all(&save_path) { -// Ok(()) => { -// save_path.push(format!("{}.yaml", snp.name)); -// File::create(&save_path).unwrap_or_else(|e| { -// panic!("Couldn't create snippet file at {:?} {:}", save_path, e) -// }) -// } -// Err(e) => panic!("Couldn't write to path {:?}. {}", save_path, e), -// }; -// Ok(file) -// } - /// 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 @@ -172,14 +184,6 @@ pub fn config_folder() -> Result { Ok(dir) } -/// Find the path of the given snippet -/// This function should suceed in every situation where a config folder can be set -fn snippet_path(snp: &str) -> Result { - let mut dir = config_folder()?; - dir.push(format!("{}.yaml", snp)); - Ok(dir) -} - #[cfg(test)] mod test { use super::*; @@ -192,6 +196,14 @@ mod test { }; } + /// Find the path of the given snippet + /// This function should suceed in every situation where a config folder can be set + fn snippet_path(snp: &str) -> Result { + let mut dir = config_folder()?; + dir.push(format!("{}.yaml", snp)); + Ok(dir) + } + #[test] fn test_config_creation() { // Try to locate where to set the config @@ -234,12 +246,20 @@ mod test { } #[test] + #[ignore] fn test_edit() { + // TODO: Finish this test // Test edit non existant - // Test edit with create - // Test - // todo!() + } + + #[test] + fn test_edit_whole() { + _ = std::fs::remove_file(snippet_path("edit_whole").unwrap()); + // Test to create empty + assert!(edit_whole_snippet(false_cli!("-e", "-c", "edit_whole")).is_ok()); + + // TODO: Finish this test } } -- 2.45.1 From 92b3ccf73057c45c29eccaeec2e0322118a6ebac Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 22 May 2023 03:08:12 +0200 Subject: [PATCH 15/20] Adds basic coverage, corrects tests and correct bad function for Edit & edit --- .gitignore | 2 + Makefile.toml | 4 +- README.md | 4 +- TODO.md | 25 ++++++------ coverage/html/badges/flat.svg | 23 +++++++++++ src/main.rs | 25 +++++++++--- src/snippet.rs | 5 +-- src/wrapper_functions.rs | 75 ++++++++++++++++++++++++++++------- 8 files changed, 122 insertions(+), 41 deletions(-) create mode 100644 coverage/html/badges/flat.svg diff --git a/.gitignore b/.gitignore index 193d30e..ecaefb4 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,5 @@ Cargo.lock # Added by cargo /target +/coverage +/llvm \ No newline at end of file diff --git a/Makefile.toml b/Makefile.toml index 92d84ac..284b84b 100644 --- a/Makefile.toml +++ b/Makefile.toml @@ -5,6 +5,6 @@ script = [ "mkdir -p coverage", "mkdir -p coverage/html", "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", -"grcov . --binary-path ./target/debug/deps/ -s . -t html --branch --ignore-not-existing --ignore '../*' --ignore '/*' --ignore '*xiv_csolver.rs' --ignore '*python*.rs' -o coverage/html/", +"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 diff --git a/README.md b/README.md index 4d141db..87d90c2 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # snp - +![coverage/html/badges/flat.svg](coverage/html/badges/flat.svg) drawing -A simple cli utility to manage snippets +A simple cli utility to manage snippets, while it was created to be used with Helix, it can work with any tool integrating input from stdout ## Usage diff --git a/TODO.md b/TODO.md index ed721db..39db303 100644 --- a/TODO.md +++ b/TODO.md @@ -9,19 +9,15 @@ ## TODO [ ] Make a lib for dynamic_format and snippets (impl make a trait for have .id() and other future t) - [-] Make functions into methods [-] Have identical attributes with {0} {1} {0} (^^^^^) - [ ] Update tests [ ] Benchmarks [ ] Better modes [ ] 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 - + [ ] Document non coverage + ### Currently working on + [-] Coverage [ ] Proceed one by one and catch errors [-] Remake all helper functions [*] locate_snippet @@ -30,14 +26,17 @@ [*] edit_whole_snippet [x] print_snippet [-] Finish tests on - [ ] locate_snippet - [ ] create_snippet - [ ] edit_snippet - [ ] edit_whole_snippet - [ ] print_snippet - + [*] locate_snippet + [*] create_snippet + [*] edit_snippet + [*] edit_whole_snippet + [x] print_snippet + [ ] Cargo test must always have the test feature ## Finished [*] Make custom errors [*] Transform all panic in errors + [*] Make functions into methods +## Posponed or rendered useless + [x] Chain the methods when possible with result ? diff --git a/coverage/html/badges/flat.svg b/coverage/html/badges/flat.svg new file mode 100644 index 0000000..f4a8de8 --- /dev/null +++ b/coverage/html/badges/flat.svg @@ -0,0 +1,23 @@ + + coverage: 89% + + + + + + + + + + + + + + + coverage + + 89% + + + \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 8d891db..e6cf156 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,6 +3,8 @@ #![warn(clippy::missing_docs_in_private_items, missing_docs)] #![allow(clippy::result_unit_err)] +use std::error::Error; + use clap::Parser; mod dynamic_formatter; mod errors; @@ -59,18 +61,29 @@ pub enum Actions { Create, } +/// Main entry point, everything is defered for testing and coverage fn main() -> Result<(), errors::SnippetError> { let cli = Cli::parse(); + execute_parsed_cli(cli) +} +/// The main worker, execute all commands given as Args +fn execute_parsed_cli(cli: Cli) -> Result<(), errors::SnippetError> { let list_actions = populate_actions(&cli); for action in list_actions.iter() { - match action { + if let Err(e) = match action { Actions::Locate => 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), - }?; + } { + println!("An error occured during runtime {:?}", e); + if let Some(e) = e.source() { + println!("This error was caused by {:?}", e); + } + return Err(e); + }; } Ok(()) } @@ -81,11 +94,11 @@ 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.append(&mut vec![Actions::Create, Actions::EditAll]), - (_, true, true, false) => actions.append(&mut vec![Actions::Create, Actions::Edit]), + (_, 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::EditAll), - (_, false, false, true) => actions.push(Actions::Edit), + (_, false, true, _) => actions.push(Actions::Edit), + (_, false, false, true) => actions.push(Actions::EditAll), (false, false, false, false) => (), } actions diff --git a/src/snippet.rs b/src/snippet.rs index 98b95c6..1e3046b 100644 --- a/src/snippet.rs +++ b/src/snippet.rs @@ -35,20 +35,19 @@ impl Snippet { } /// Save the snippet in a file, errors on write error - pub fn save_in(&self, mut file: std::fs::File) -> Result<(), SnippetError> { + pub fn save_in(&self, mut file: &std::fs::File) -> Result<(), SnippetError> { write!(file, "{}", serde_yaml::to_string(self)?)?; Ok(()) } /// Mutate the contents in place pub fn edit(&mut self) -> Result<(), SnippetError> { - // #[cfg(not(test))] self.content = edit::edit(self.content.clone())?; Ok(()) } /// Create snippet from file buffer (deserialize) - pub fn from_file(f: File) -> Result { + pub fn from_file(f: &File) -> Result { let snp: Snippet = serde_yaml::from_reader(f)?; Ok(snp) } diff --git a/src/wrapper_functions.rs b/src/wrapper_functions.rs index fca9069..139f282 100644 --- a/src/wrapper_functions.rs +++ b/src/wrapper_functions.rs @@ -5,7 +5,7 @@ use std::fs::create_dir_all; use std::io::{read_to_string, Write}; -use std::{env, fs::File, io::Read, path::PathBuf}; +use std::{env, fs::File, path::PathBuf}; use edit::edit; @@ -54,7 +54,7 @@ pub fn create_snippet(cli: &Cli) -> Result<(), SnippetError> { } FileStatus::NotFound(p) => File::create(p)?, // Create a new snippet }; - snp.save_in(f)?; + snp.save_in(&f)?; Ok(()) } @@ -62,17 +62,30 @@ pub fn create_snippet(cli: &Cli) -> Result<(), SnippetError> { 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 mut snp = match status { - FileStatus::Opened((_, f)) => Snippet::from_file(f)?, + let (mut snp, f, p) = match status { + FileStatus::Opened((p, f)) => (Snippet::from_file(&f)?, f, p), FileStatus::NotFound(p) => { - if cli.force { - Snippet::new(cli.snippet.clone(), cli.args.clone(), String::from("")) + if cli.create { + ( + Snippet::new(cli.snippet.clone(), cli.args.clone(), String::from("")), + File::create(&p)?, + p, + ) } else { return Err(SnippetError::NotFoundNoRetryError(p)); } } }; + + // During tests, the editor cannot be tested + #[cfg(not(feature = "test"))] snp.edit()?; + + snp.write_over(&p)?; + println!( + "The snippet {:?} was succesfully saved", + p.file_name().unwrap() + ); Ok(()) } @@ -101,7 +114,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) => { - snp.write_over(&p)?; + snp.write_over(&p)?; // TODO: Consider not giving a path, as name can be changed in config println!( "The snippet {:?} was succesfully saved", p.file_name().unwrap() @@ -124,6 +137,28 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> { } } +// 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(args: &Cli) -> Result<(), SnippetError> { // Try to load the snippet @@ -246,20 +281,30 @@ mod test { } #[test] - #[ignore] fn test_edit() { - // TODO: Finish this test - // Test edit non existant - // Test edit with create - // Test + _ = std::fs::remove_file(snippet_path("edit_content").unwrap()); + // Open unnexitant + assert!(edit_snippet(false_cli!("-e", "edit_content")).is_err()); + + // Force creation + assert!(edit_snippet(false_cli!("-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()); } #[test] fn test_edit_whole() { _ = std::fs::remove_file(snippet_path("edit_whole").unwrap()); - // Test to create empty - assert!(edit_whole_snippet(false_cli!("-e", "-c", "edit_whole")).is_ok()); + // Open unnexitant + assert!(edit_whole_snippet(false_cli!("-E", "edit_whole")).is_err()); - // TODO: Finish this test + // Force creation + assert!(edit_whole_snippet(false_cli!("-E", "-c", "edit_whole")).is_ok()); + + // Edit when created + assert!(edit_whole_snippet(false_cli!("-E", "edit_whole")).is_ok()); } } -- 2.45.1 From c83dfd8f80e0358c705104b36d9036c33a7238b4 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 22 May 2023 03:30:49 +0200 Subject: [PATCH 16/20] Adds entry point for print --- src/errors.rs | 10 +++++----- src/main.rs | 2 +- src/wrapper_functions.rs | 28 +++++++++++----------------- 3 files changed, 17 insertions(+), 23 deletions(-) diff --git a/src/errors.rs b/src/errors.rs index 2393200..33d6f89 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -16,8 +16,8 @@ pub enum SnippetError { IOError(std::io::Error), /// Yaml error, generated during serialisation of snippets YAMLError(serde_yaml::Error), - /// The file already exists and no creation flag was set - ExistsError(std::io::Error), + /// The file doesn't exits and can't be used + NotFound(PathBuf), /// The file doen't exist and no creation was asked NotFoundNoRetryError(PathBuf), /// The snippet was found but shouldn't be erased because of flags @@ -35,9 +35,9 @@ impl fmt::Display for SnippetError { SnippetError::YAMLError(..) => { write!(f, "Couldn't convert the given arguments into a yaml") } - SnippetError::ExistsError(..) => write!( + SnippetError::NotFound(ref p) => write!( f, - "The file already exists. Use -c or -f to create it or force overwrite." + "The file {:?} doesn't exists",p.file_name().unwrap(), ), SnippetError::NotFoundNoRetryError(ref p) => { write!( @@ -66,7 +66,7 @@ impl error::Error for SnippetError { SnippetError::ClapError(ref e) => Some(e), SnippetError::IOError(ref e) => Some(e), SnippetError::YAMLError(ref e) => Some(e), - SnippetError::ExistsError(ref e) => Some(e), + SnippetError::NotFound(_) => None, SnippetError::NotFoundNoRetryError(_) => None, SnippetError::FoundNoEraseError(_) => None, SnippetError::ReparsingError => None, diff --git a/src/main.rs b/src/main.rs index e6cf156..c15f6e8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -99,7 +99,7 @@ fn populate_actions(cli: &Cli) -> Vec { (_, true, false, false) => actions.push(Actions::Create), (_, false, true, _) => actions.push(Actions::Edit), (_, false, false, true) => actions.push(Actions::EditAll), - (false, false, false, false) => (), + (false, false, false, false) => actions.push(Actions::Show), } actions } diff --git a/src/wrapper_functions.rs b/src/wrapper_functions.rs index 139f282..77e2f69 100644 --- a/src/wrapper_functions.rs +++ b/src/wrapper_functions.rs @@ -3,12 +3,13 @@ //! All functions included should either take a Cli object and return a SnippetError //! or be a helper function for such a function +#[allow(unused)] // Mandatory because of how test and rust-analyser work +use edit::edit; + use std::fs::create_dir_all; use std::io::{read_to_string, Write}; use std::{env, fs::File, path::PathBuf}; -use edit::edit; - use crate::dynamic_formatter; use crate::{dynamic_formatter::complete_vec, errors::SnippetError, snippet::Snippet, Cli}; @@ -160,25 +161,19 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> { // } /// Print the snippet to stdout -pub fn print_snippet(args: &Cli) -> Result<(), SnippetError> { +pub fn print_snippet(cli: &Cli) -> Result<(), SnippetError> { // Try to load the snippet - let mut path = config_folder()?; //.expect("Coudn't open config forder"); - path.push(format!("{}.yaml", args.snippet)); - let f = std::fs::File::open(&path)?; //.expect("Could not open snippet file."); - let snp: Snippet = serde_yaml::from_reader(f)?; //.expect("Couldn't parse values"); + let (p, f) = match check_dir_and_open(&cli.snippet)? { + FileStatus::Opened((p, f)) => (p, f), + FileStatus::NotFound(p) => return Err(SnippetError::NotFound(p)), + }; + + let snp = Snippet::from_file(&f)?; // Add the given arguments to the snippet - // let final_args = match complete_vec(&args.args, &snp.default_values) { - // Err(_) => panic!("Too many arguments given to the snippet, aborting"), - // Ok(argg) => argg, - // }; - let final_args = complete_vec(&args.args, &snp.default_values)?; + let final_args = complete_vec(&cli.args, &snp.default_values)?; // Print the snippet - // let f_str = match dynamic_formatter::dynamic_formatter(&snp.content, final_args) { - // Err(_) => panic!("Couldn't format the snippet !"), - // Ok(sn) => sn, - // }; let f_str = dynamic_formatter::dynamic_format(&snp.content, final_args)?; println!("{}", f_str); @@ -215,7 +210,6 @@ pub fn config_folder() -> Result { let dir = exe.parent().expect("Executable must be in some directory"); let mut dir = dir.join(".config"); dir.push("snp_config"); - // dir.push(format!("{}.yaml", name)); Ok(dir) } -- 2.45.1 From b4513f7bd36745e0a334b19bc4398bcf162359b5 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 22 May 2023 15:23:55 +0200 Subject: [PATCH 17/20] dds formating and printing --- README.md | 4 +++ TODO.md | 27 +++++++----------- coverage/html/badges/flat.svg | 10 +++---- src/dynamic_formatter.rs | 39 ++++++++++++++++--------- src/errors.rs | 6 +++- src/tokenizer.rs | 54 ++++++++++++++++++++++++++--------- src/wrapper_functions.rs | 11 +++---- 7 files changed, 96 insertions(+), 55 deletions(-) diff --git a/README.md b/README.md index 87d90c2..bdfbe18 100644 --- a/README.md +++ b/README.md @@ -23,3 +23,7 @@ To use a snippet $ snp snippet_name ``` +## Testing + +For reasons too long to explain here, test must be run with the optional feature ``--feature "test"`. +Failure to do so will result in the editor popping in during tests. diff --git a/TODO.md b/TODO.md index 39db303..b3d676b 100644 --- a/TODO.md +++ b/TODO.md @@ -1,42 +1,35 @@ -## Features -### --new (name) - [ ] Create a new snippet with given name at the default location (where tho ?) - -### name args - [ ] Use the snippet name with one or more args - [ ] Args must be split up - [ ] - ## TODO [ ] Make a lib for dynamic_format and snippets (impl make a trait for have .id() and other future t) - [-] Have identical attributes with {0} {1} {0} (^^^^^) [ ] Benchmarks [ ] Better 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 ### Currently working on [-] Coverage [ ] Proceed one by one and catch errors - [-] Remake all helper functions - [*] locate_snippet - [*] create_snippet - [*] edit_snippet - [*] edit_whole_snippet - [x] print_snippet [-] Finish tests on [*] locate_snippet [*] create_snippet [*] edit_snippet [*] edit_whole_snippet - [x] print_snippet + [-] print_snippet [ ] Cargo test must always have the test feature ## 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 + [-] Have identical attributes with {0} {1} {0} (^^^^^) ## Posponed or rendered useless [x] Chain the methods when possible with result ? diff --git a/coverage/html/badges/flat.svg b/coverage/html/badges/flat.svg index f4a8de8..d0e421f 100644 --- a/coverage/html/badges/flat.svg +++ b/coverage/html/badges/flat.svg @@ -1,6 +1,6 @@ - coverage: 89% + xmlns:xlink="http://www.w3.org/1999/xlink" width="96" height="20" role="img" aria-label="coverage: 64%"> + coverage: 64% @@ -10,14 +10,14 @@ - + coverage - - 89% + + 64% \ No newline at end of file diff --git a/src/dynamic_formatter.rs b/src/dynamic_formatter.rs index f8ae20e..ecb7223 100644 --- a/src/dynamic_formatter.rs +++ b/src/dynamic_formatter.rs @@ -1,7 +1,7 @@ //! A lib of vector operators //! Allow for replacement and formatting of strings -use crate::{errors::SnippetError, tokenizer::create_tokens_from_string}; +use crate::{errors::SnippetError, tokenizer}; /// A dynamic formatter, formatting a string with any number of /// {} with element of a Vec, by default the search doen't need to @@ -14,22 +14,33 @@ pub fn dynamic_format(format_string: &str, vector: Vec) -> Result - create_tokens_from_string(format_string); - // println!("{}",); - let collected_format_string: Vec<&str> = format_string.split("{}").collect(); - let size_str = collected_format_string.len(); - let size_vec = vector.len(); + let token_list = tokenizer::create_tokens_from_string(format_string)?; - let mut fmt_vec = Vec::new(); - for (i, text) in collected_format_string.iter().enumerate() { - fmt_vec.push(text.to_string()); - if i < size_vec && i < size_str - 1 { - fmt_vec.push(format!("{}", vector[i])); + let cap = format_string.len() + 5 * vector.len(); + let mut final_string = String::with_capacity(cap); + let mut moving_index = 0; + for tok in token_list { + match tok { + tokenizer::SnippetToken::Substitution(s) => { + let index; + match s.id() { + Some(i) => index = i, + None => { + // TODO: Get rid of this wonky hack + index = moving_index; + moving_index += 1 + } + }; + if let Some(text) = vector.get(index) { + final_string.push_str(&text.to_string()) + } else { + return Err(SnippetError::IndexError(index)); + } + } + tokenizer::SnippetToken::Text(t) => final_string.push_str(t), } } - Ok(fmt_vec.join("")) + Ok(final_string) } /// Fill the argument vector with a list of defaults values if needed diff --git a/src/errors.rs b/src/errors.rs index 33d6f89..1277f92 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -24,6 +24,8 @@ pub enum SnippetError { FoundNoEraseError(PathBuf), /// The snippet couldn't be reparsed ReparsingError, + /// The custom formatter coulnd't access an index + IndexError(usize), } impl fmt::Display for SnippetError { @@ -51,7 +53,8 @@ impl fmt::Display for SnippetError { "The snippet {:?} already exists. Use -f/--force to overwrite it.", p.file_name(), ), - 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::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), } } } @@ -70,6 +73,7 @@ impl error::Error for SnippetError { SnippetError::NotFoundNoRetryError(_) => None, SnippetError::FoundNoEraseError(_) => None, SnippetError::ReparsingError => None, + SnippetError::IndexError(_) => None, } } } diff --git a/src/tokenizer.rs b/src/tokenizer.rs index 57d3959..5466f6d 100644 --- a/src/tokenizer.rs +++ b/src/tokenizer.rs @@ -4,9 +4,11 @@ use regex::Regex; +use crate::errors::SnippetError; + /// A formatter, containing (or not) an argument to be subsitued with #[derive(Debug)] -struct CustFormatter { +pub struct CustFormatter { /// The positional id of the element to replace with pub id: Option, } @@ -21,11 +23,16 @@ impl CustFormatter { id: Some(text.parse::().unwrap()), } } + + /// Return an option of the Id + pub fn id(&self) -> Option { + self.id + } } /// The parsed snippet #[derive(Debug)] -enum Token<'a> { +pub enum SnippetToken<'a> { /// A subsitution token, containing either an index or nothing (and being "positional") Substitution(CustFormatter), /// A text token, the inbetween @@ -50,14 +57,13 @@ macro_rules! push_if_some { } /// Create a Token list from the snippet given and return it as a vector of token -pub fn create_tokens_from_string(snippet: &str) { +pub fn create_tokens_from_string(snippet: &str) -> Result, SnippetError> { let re = Regex::new(r"\{\d*\}").unwrap(); let matches = re.find_iter(snippet); let mut readhead = 0; // Starting to read at zero let mut token_list = Vec::new(); for r in matches { // Assume we matched text from read to here - println!("{:?}", r); push_if_some!( token_list, create_token_from_pos(snippet, Status::Text, readhead, Some(r.start())) @@ -68,8 +74,12 @@ pub fn create_tokens_from_string(snippet: &str) { ); readhead = r.end(); } - create_token_from_pos(snippet, Status::Text, readhead, None); - println!("{:?}", token_list); + push_if_some!( + token_list, + create_token_from_pos(snippet, Status::Text, readhead, None) + ); + + Ok(token_list) } /// Create a single Token from the current positions @@ -78,16 +88,34 @@ fn create_token_from_pos( status: Status, start: usize, stop: Option, -) -> Option { +) -> Option { let text = match (stop, status) { - (None, Status::Formater) => Token::Substitution(CustFormatter::new(&text[start + 1..])), - (None, Status::Text) => Token::Text(&text[start..]), - (Some(stop), Status::Formater) => { - Token::Substitution(CustFormatter::new(&text[start + 1..stop - 1])) + (None, Status::Formater) => { + SnippetToken::Substitution(CustFormatter::new(&text[start + 1..])) } - (Some(stop), Status::Text) => Token::Text(&text[start..stop]), + (None, Status::Text) => SnippetToken::Text(&text[start..]), + (Some(stop), Status::Formater) => { + SnippetToken::Substitution(CustFormatter::new(&text[start + 1..stop - 1])) + } + (Some(stop), Status::Text) => SnippetToken::Text(&text[start..stop]), }; - println!("{:?}", text); Some(text) } + +#[cfg(test)] +mod test { + // use super::*; + + #[ignore] + #[test] + fn test_create_token_from_pos() { + todo!() + } + + #[ignore] + #[test] + fn test_create_token_from_string() { + todo!() + } +} diff --git a/src/wrapper_functions.rs b/src/wrapper_functions.rs index 77e2f69..50cb13e 100644 --- a/src/wrapper_functions.rs +++ b/src/wrapper_functions.rs @@ -10,8 +10,9 @@ use std::fs::create_dir_all; use std::io::{read_to_string, Write}; use std::{env, fs::File, path::PathBuf}; -use crate::dynamic_formatter; -use crate::{dynamic_formatter::complete_vec, errors::SnippetError, snippet::Snippet, Cli}; +use crate::errors::SnippetError; +use crate::snippet::Snippet; +use crate::{dynamic_formatter, Cli}; // Potential way to chain all actions without re-opening // /// The status of the snippet in memory @@ -63,7 +64,7 @@ pub fn create_snippet(cli: &Cli) -> Result<(), SnippetError> { 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 (mut snp, f, p) = match status { + let (mut snp, _, p) = match status { FileStatus::Opened((p, f)) => (Snippet::from_file(&f)?, f, p), FileStatus::NotFound(p) => { if cli.create { @@ -163,7 +164,7 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> { /// Print the snippet to stdout pub fn print_snippet(cli: &Cli) -> Result<(), SnippetError> { // Try to load the snippet - let (p, f) = match check_dir_and_open(&cli.snippet)? { + let (_, f) = match check_dir_and_open(&cli.snippet)? { FileStatus::Opened((p, f)) => (p, f), FileStatus::NotFound(p) => return Err(SnippetError::NotFound(p)), }; @@ -171,7 +172,7 @@ pub fn print_snippet(cli: &Cli) -> Result<(), SnippetError> { let snp = Snippet::from_file(&f)?; // Add the given arguments to the snippet - let final_args = complete_vec(&cli.args, &snp.default_values)?; + let final_args = dynamic_formatter::complete_vec(&cli.args, &snp.default_values)?; // Print the snippet let f_str = dynamic_formatter::dynamic_format(&snp.content, final_args)?; -- 2.45.1 From 56fdb061165fd1e3fa9581702f285b698713cbc1 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 22 May 2023 21:12:11 +0200 Subject: [PATCH 18/20] 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 -- 2.45.1 From cca03908961ba08131f0d33928676bab24997951 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 23 May 2023 00:03:01 +0200 Subject: [PATCH 19/20] Adds coverage and updates todo Squashes several bug and inconsistencies, mostly on test tho --- .gitignore | 3 +- Makefile.toml | 17 +- TODO.md | 26 +- coverage/html/badges/flat.svg | 10 +- src/actions.rs | 145 ++++++++ src/main.rs | 61 +--- src/wrapper_functions.rs | 49 ++- tarpaulin-report.html | 660 ---------------------------------- 8 files changed, 224 insertions(+), 747 deletions(-) create mode 100644 src/actions.rs delete mode 100644 tarpaulin-report.html diff --git a/.gitignore b/.gitignore index ecaefb4..d9773dc 100644 --- a/.gitignore +++ b/.gitignore @@ -20,4 +20,5 @@ Cargo.lock /target /coverage -/llvm \ No newline at end of file +/llvm +tarpaulin-report.html \ No newline at end of file diff --git a/Makefile.toml b/Makefile.toml index a6f5dc6..ae00fbc 100644 --- a/Makefile.toml +++ b/Makefile.toml @@ -6,7 +6,7 @@ script = [ "mkdir -p coverage/html", "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/", +"grcov . --binary-path ./target/debug/deps/ -s . -t html --branch --ignore-not-existing --ignore '../*' --ignore '/*' --ignore '*/main.rs' --ignore '*/errors.rs' -o coverage/html/", ] [tasks.testing] @@ -15,3 +15,18 @@ ignore_errors = true script = [ "cargo test --features \"test\"", ] + +[tasks.win_build] +script_runner = "@shell" +ignore_errors = true +script = [ + "CROSS_CONTAINER_ENGINE=podman cross build --target x86_64-pc-windows-gnu" +] + +[tasks.win_test] +script_runner = "@shell" +ignore_errors = true +script = [ + "CROSS_CONTAINER_ENGINE=podman cross test --features test --target x86_64-pc-windows-gnu" +] + diff --git a/TODO.md b/TODO.md index 4b8cb86..03757a7 100644 --- a/TODO.md +++ b/TODO.md @@ -1,21 +1,11 @@ ## TODO [ ] Benchmarks [ ] Better use of file modes - [ ] Test populate_actions [ ] 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 - + [ ] Find a solution for the .badpocalypse + ### Currently working on - [-] Coverage - [ ] Proceed one by one and catch errors - [-] Finish tests on - [*] locate_snippet - [*] create_snippet - [*] edit_snippet - [*] edit_whole_snippet - [*] print_snippet - [ ] delete snippet ## Finished [*] Make custom errors @@ -27,7 +17,17 @@ [*] edit_snippet [*] edit_whole_snippet [*] print_snippet - [-] Have identical attributes with {0} {1} {0} (^^^^^) + [*] Finish tests on + [*] locate_snippet + [*] create_snippet + [*] edit_snippet + [*] edit_whole_snippet + [*] print_snippet + [*] delete snippet + [*] Have identical attributes with {0} {1} {0} (^^^^^) + [*] Add an option to delete a snippet + [*] Coverage + [*] Test populate_actions ## Posponed or rendered useless [x] Chain the methods when possible with result ? diff --git a/coverage/html/badges/flat.svg b/coverage/html/badges/flat.svg index 1ed2da4..a43354b 100644 --- a/coverage/html/badges/flat.svg +++ b/coverage/html/badges/flat.svg @@ -1,6 +1,6 @@ - coverage: 79% + xmlns:xlink="http://www.w3.org/1999/xlink" width="96" height="20" role="img" aria-label="coverage: 99%"> + coverage: 99% @@ -10,14 +10,14 @@ - + coverage - - 79% + + 99% \ No newline at end of file diff --git a/src/actions.rs b/src/actions.rs new file mode 100644 index 0000000..0a734b8 --- /dev/null +++ b/src/actions.rs @@ -0,0 +1,145 @@ +//! 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 +#[derive(Debug)] +#[cfg_attr(test, derive(PartialEq))] +pub enum Actions { + /// Edit the content of the snippet only + Edit, + /// Edit the whole snippet + EditAll, + /// Locate the snippet and show the position + Locate, + /// Show the snippet (with replacement done) + Show, + /// Create the snippet with the given name and arguments + Create, + /// Deletes the snippet + Delete, +} + +/// The main worker, execute all commands given as Args +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::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), + } { + 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); + }; + } + Ok(()) +} + +/// Populate a logical vec of succesive actions to perform depending on arguments +/// 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, cli.delete) { + (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) => actions.push(Actions::Show), + (_, _, _, _, true) => actions.push(Actions::Delete), + } + actions +} + +#[cfg(test)] +mod test { + use super::*; + use clap::Parser; + + macro_rules! false_cli { + ($($arg:expr),+) => { + Cli::parse_from(vec![$($arg),+]) + }; + } + + macro_rules! group_actions{ + ($(($cli:expr, $expect:expr),)*) => { + vec![$(($cli,$expect)),+] + }; + } + + #[test] + fn test_populate_actions() { + // false_cli!("snp", "name", "-l"), Actions::Locate + let group = group_actions!( + ( + false_cli!("snp", "name", "-l", "-c", "-e", "-E"), + vec![Actions::Locate] + ), + (false_cli!("snp", "name", "-l"), vec![Actions::Locate]), + (false_cli!("snp", "name", "-d"), vec![Actions::Delete]), + ( + false_cli!("snp", "name", "-d", "-e", "e", "-E", "-l"), + 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", "-c"), + vec![Actions::EditAll] + ), + (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", "-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"), + vec![Actions::Delete] + ), + ); + for (cli, res) in group.iter() { + println!("Testing {:?}..actions expected {:?}", cli, res); + let fnd = populate_actions(cli); + println!("... found {:?}", fnd); + assert!(res.iter().zip(fnd).all(|(a, b)| *a == b)); + } + } + #[test] + fn test_execute_parsed_cli() { + let list_cli = vec![ + false_cli!("snp", "parsed_cli", "-e", "-c"), + false_cli!("snp", "parsed_cli", "-c", "-f"), + false_cli!("snp", "parsed_cli"), + false_cli!("snp", "parsed_cli", "-E", "-f"), + false_cli!("snp", "parsed_cli", "-d"), + ]; + + let bad_cli = vec![ + false_cli!("snp", "parsed_cli_bad", "-l"), + false_cli!("snp", "-d", "parsed_cli_bad"), + ]; + + for cl in list_cli { + println!("Testing {:?} expecting success", cl); + assert!(execute_parsed_cli(cl).is_ok()); + } + + for cl in bad_cli { + println!("Testing {:?} expecting failure", cl); + assert!(execute_parsed_cli(cl).is_err()); + } + } +} diff --git a/src/main.rs b/src/main.rs index e98749c..63a7e9b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,9 +3,8 @@ #![warn(clippy::missing_docs_in_private_items, missing_docs)] #![allow(clippy::result_unit_err)] -use std::error::Error; - use clap::Parser; +mod actions; mod dynamic_formatter; mod errors; mod snippet; @@ -50,64 +49,8 @@ pub struct Cli { delete: bool, } -/// List of all possible actions, some are mutually exclusive -#[derive(Debug)] -pub enum Actions { - /// Edit the content of the snippet only - Edit, - /// Edit the whole snippet - EditAll, - /// Locate the snippet and show the position - Locate, - /// Show the snippet (with replacement done) - 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 fn main() -> Result<(), errors::SnippetError> { let cli = Cli::parse(); - execute_parsed_cli(cli) -} - -/// The main worker, execute all commands given as Args -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::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), - } { - 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); - }; - } - Ok(()) -} - -/// Populate a logical vec of succesive actions to perform depending on arguments -/// 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, 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 + actions::execute_parsed_cli(cli) } diff --git a/src/wrapper_functions.rs b/src/wrapper_functions.rs index 5b33454..f42480d 100644 --- a/src/wrapper_functions.rs +++ b/src/wrapper_functions.rs @@ -223,7 +223,7 @@ pub fn config_folder() -> Result { } #[cfg(test)] -mod test { +pub mod test { use super::*; use clap::Parser; use std::io::Write; @@ -245,19 +245,26 @@ mod test { #[test] fn test_config_creation() { // Try to locate where to set the config - let _ = match check_dir_and_open("test_config_creation").expect("Can't open config") { - FileStatus::Opened((_, f)) => f, - FileStatus::NotFound(p) => File::create(p).expect("Can't create path"), - }; + let path: PathBuf = snippet_path("test_config_creation").unwrap(); + create_dir_all(path.parent().unwrap()).unwrap(); + let _f = File::create(path).unwrap(); + assert!(matches!( + check_dir_and_open("test_config_creation").expect("Can't open config"), + FileStatus::Opened(_) + )); + } + + #[test] + fn test_delete_snippet() { + assert!(create_snippet(false_cli!("-c", "delete_snippet")).is_ok()); + assert!(delete_snippet(false_cli!("-d", "delete_snippet")).is_ok()); } #[test] fn test_locate() { // Try to locate an unexisting snippet let theorical_path = snippet_path("test_locate").expect("Can't find config path"); - if let Err(e) = std::fs::remove_file(&theorical_path) { - println!("[Info] File didn't exist {:?}", e); - } + _ = std::fs::remove_file(&theorical_path); // Locating the snippet should fail assert!(locate_snippet(false_cli!("-l", "test_locate")).is_err()); @@ -270,6 +277,20 @@ mod test { assert!(locate_snippet(false_cli!("-l", "test_locate")).is_ok()); } + #[test] + fn test_print_snippet() { + let theorical_path = snippet_path("test_print").expect("Can't find config path"); + _ = std::fs::remove_file(theorical_path); + + // Print non existing snippet + assert!(print_snippet(false_cli!("snp", "test_print")).is_err()); + + // Create snippet + assert!(create_snippet(false_cli!("-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()); @@ -309,5 +330,17 @@ mod test { // Edit when created assert!(edit_whole_snippet(false_cli!("-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!(matches!( + check_dir_and_open("edit_whole.bad").unwrap(), + FileStatus::Opened(_) + )); + }; } } diff --git a/tarpaulin-report.html b/tarpaulin-report.html deleted file mode 100644 index 470d8e2..0000000 --- a/tarpaulin-report.html +++ /dev/null @@ -1,660 +0,0 @@ - - - - - - - -
- - - - - - \ No newline at end of file -- 2.45.1 From b2ebab85a4bedcf27314169748cba14ae5874433 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 23 May 2023 00:07:42 +0200 Subject: [PATCH 20/20] updates cargo manifest --- Cargo.toml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index a4a91cf..9479535 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,7 @@ [package] name = "snp" -version = "0.1.0" +author = "Dandaedre" +version = "1.0.1" edition = "2021" [features] -- 2.45.1