Adds a lot of features
- Helper function - Small refactor - regexes
This commit is contained in:
parent
ce19f7703f
commit
d2cb3f4295
|
|
@ -7,5 +7,7 @@ edition = "2021"
|
|||
|
||||
[dependencies]
|
||||
clap = { version = "4.2.7", features = ["derive"] }
|
||||
edit = "0.1.4"
|
||||
regex = "1.8.1"
|
||||
serde = { version = "1.0.163", features = ["derive"] }
|
||||
serde_yaml = "0.9.21"
|
||||
|
|
|
|||
18
TODO.md
18
TODO.md
|
|
@ -1,15 +1,15 @@
|
|||
## Features
|
||||
### --new (name)
|
||||
- Create a new snippet with given name at the default location (where tho ?)
|
||||
[ ] Create a new snippet with given name at the default location (where tho ?)
|
||||
|
||||
### name args
|
||||
- Use the snippet name with one or more args
|
||||
- Args must be split up
|
||||
-
|
||||
[ ] Use the snippet name with one or more args
|
||||
[ ] Args must be split up
|
||||
[ ]
|
||||
|
||||
## TODO
|
||||
- Make a lib for dynamic_format
|
||||
- Make custom errors
|
||||
- Transform all panic in errors
|
||||
- Make functions into methods
|
||||
- Have identical attributes with {0} {1} {0} (^^^^^)
|
||||
[ ] Make a lib for dynamic_format
|
||||
[ ] Make custom errors
|
||||
[ ] Transform all panic in errors
|
||||
[ ] Make functions into methods
|
||||
[ ] Have identical attributes with {0} {1} {0} (^^^^^)
|
||||
138
src/main.rs
138
src/main.rs
|
|
@ -4,13 +4,14 @@
|
|||
#![allow(clippy::result_unit_err)]
|
||||
|
||||
use clap::Parser;
|
||||
use regex::Regex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use std::{
|
||||
env,
|
||||
fs::{create_dir_all, File},
|
||||
io::{self, Write},
|
||||
path::PathBuf,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
// use serde_yaml;
|
||||
|
||||
|
|
@ -34,10 +35,102 @@ struct Cli {
|
|||
/// 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<String>,
|
||||
|
||||
/// Launch the editor and edit the snippet
|
||||
#[arg(short, default_value_t = false)]
|
||||
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<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);
|
||||
};
|
||||
};
|
||||
}
|
||||
/// 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
|
||||
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)
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let cli = Cli::parse();
|
||||
// let origin = "Fill the blank bébé";
|
||||
// let edited = edit::edit(origin).unwrap();
|
||||
// println!("{}", edited);
|
||||
match cli.create {
|
||||
true => create_snippet(cli),
|
||||
false => print_snippet(&cli),
|
||||
|
|
@ -58,10 +151,14 @@ 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::from(""));
|
||||
// println!("{}", serde_yaml::to_string(&snp).unwrap());
|
||||
let snp = Snippet::new(args.snipplet.clone(), args.args, string);
|
||||
|
||||
let mut file = match create_dir_all(&save_path) {
|
||||
Ok(()) => {
|
||||
|
|
@ -75,7 +172,7 @@ fn create_snippet(args: Cli) {
|
|||
}
|
||||
Err(e) => panic!("Couldn't write to path {:?}. {}", save_path, e),
|
||||
};
|
||||
|
||||
// snp.save()
|
||||
// Write the snippet
|
||||
write!(
|
||||
file,
|
||||
|
|
@ -85,6 +182,8 @@ fn create_snippet(args: Cli) {
|
|||
.unwrap_or_else(|_| panic!("Couldn't write yaml to file {:?}", save_path));
|
||||
}
|
||||
|
||||
// fn open_path()
|
||||
|
||||
/// Find a configuration folder/name for the given snippet name
|
||||
fn config_folder() -> io::Result<PathBuf> {
|
||||
let exe = env::current_exe()?;
|
||||
|
|
@ -114,11 +213,30 @@ fn print_snippet(args: &Cli) {
|
|||
Err(_) => panic!("Couldn't format the snippet !"),
|
||||
Ok(sn) => sn,
|
||||
};
|
||||
if args.locate {
|
||||
println!("{}", path.to_string_lossy());
|
||||
} else {
|
||||
println!("{}", f_str);
|
||||
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) => (),
|
||||
}
|
||||
create_tokens_from_string(&f_str);
|
||||
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.arguments.clone(), test);
|
||||
// TODO: Write snippet . Destroy original ? Return new ?
|
||||
// snp.save();
|
||||
}
|
||||
|
||||
/// A snippet ready to be Serialized/Deserialized
|
||||
|
|
@ -230,8 +348,8 @@ mod test {
|
|||
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")
|
||||
if let Ok(_x) = complete_vec(&big, &deff) {
|
||||
panic!("Complete vec should return an error of bigger vecs")
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Reference in New Issue