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) +}