//! 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, /// Wether to try to load or instead create a new one #[arg(short, long, default_value_t = false)] create: bool, /// Show where the snippet is located #[arg(short, long, default_value_t = false)] locate: 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, } fn main() { let cli = Cli::parse(); match cli.create { true => create_snippet(cli), 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) { // 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)); if args.locate { println!("Saving snippet to {:?}", save_path); } 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 let final_args = match complete_vec(&args.args, &snp.arguments) { 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, }; if args.locate { println!("{}", path.to_string_lossy()); } else { println!("{}", f_str); } } /// 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 arguments: Vec, /// The base string to format content: String, } impl Snippet { /// Create a new snippet 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 // pub fn save(&self) -> Result<(), ()> { // 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(()) } } // 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("")) } /// 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 ob bigger vecs") }; } }