diff --git a/Cargo.toml b/Cargo.toml index 38d1ed7..d9ab9a6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,3 +8,4 @@ edition = "2021" [dependencies] clap = { version = "4.2.7", features = ["derive"] } serde = { version = "1.0.163", features = ["derive"] } +serde_yaml = "0.9.21" diff --git a/README.md b/README.md index 7c3ddc3..bfc62bd 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,6 @@ # snp -A snippet making and usage tool \ No newline at end of file +drawing + +A simple cli utility to manage snippet + diff --git a/TODO.md b/TODO.md index 39c482c..e0bb6c3 100644 --- a/TODO.md +++ b/TODO.md @@ -6,3 +6,7 @@ - Use the snippet name with one or more args - Args must be split up - + +## TODO +- Make a lib for dynamic_format +- Make custom errors \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 619c994..e507962 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,15 +1,33 @@ +//! A simple cli utility to manage snippet + +#![warn(clippy::missing_docs_in_private_items, missing_docs)] +#![allow(clippy::result_unit_err)] + use clap::Parser; use serde::{Deserialize, Serialize}; +use std::{ + env, + fs::{create_dir_all, File}, + io::{self, Write}, + path::PathBuf, +}; +// use serde_yaml; + +/// The cli arguments to give to the utility #[derive(Parser, Debug)] #[command(author, version, about)] struct Cli { + /// The snippet name (and therefore his path) #[arg()] snipplet: String, - #[arg(long, default_value_t = false)] + /// Wether to try to load or instead create a new one + #[arg(short, long, default_value_t = false)] create: 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, } @@ -17,29 +35,93 @@ struct Cli { fn main() { let cli = Cli::parse(); match cli.create { - true => create_snippet(), - false => print_snipped(), + true => create_snippet(cli), + false => print_snippet(&cli), } - println!("{:?}", 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) { + // 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); + + // 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 mut file = match create_dir_all(&save_path) { + Ok(()) => { + save_path.push(format!("{}.yaml", args.snipplet)); + 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), + }; + + // 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)); +} + +/// 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 + // Print the snippet + println!("{:?}", snp); } /// A snippet ready to be Serialized/Deserialized -#[derive(Deserialize, Serialize)] +#[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 - args: Vec, + arguments: Vec, /// The base string to format - string: String, + content: String, } impl Snippet { /// Create a new snippet - pub fn new(name: String, args: Vec, string: String) -> Self { - Snippet { name, args, string } + pub fn new(name: String, arguments: Vec, content: String) -> Self { + Snippet { + name, + arguments, + content, + } } /// Save the snippet at the default location under it's name @@ -47,6 +129,11 @@ impl Snippet { Ok(()) } + /// 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(()) @@ -56,3 +143,39 @@ 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 +/// 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, +{ + let collected_format_string: Vec<&str> = format_string.split/*_inclusive*/("{}").collect(); + println!("{:?}", collected_format_string); + 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("")) +} + +#[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())); + } +}