This repository has been archived on 2026-09-13. You can view files and clone it, but cannot push or open issues or pull requests.
snp/src/snippet.rs

287 lines
8.4 KiB
Rust

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<usize>,
}
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::<usize>().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) {}
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();
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<usize>,
) -> Option<Token> {
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) {
// 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.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));
}
/// 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<PathBuf> {
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 <name>
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);
}
/// 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) {
// Load snippet
// Edit content
// Write snippet
}
/// 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));
}
/// 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<String>,
/// The base string to format
content: String,
}
impl Snippet {
/// Create a new snippet
pub fn new(name: String, default_values: Vec<String>, 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<Self, ()> {
// 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")
};
}
}