From ac4f58f929c83e6218eb4abc5c5a958072091366 Mon Sep 17 00:00:00 2001 From: beffroi Date: Sat, 20 May 2023 10:04:58 +0200 Subject: [PATCH] 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") + }; + } +}