diff --git a/README.md b/README.md
index 87d90c2..bdfbe18 100644
--- a/README.md
+++ b/README.md
@@ -23,3 +23,7 @@ To use a snippet
$ snp snippet_name
```
+## Testing
+
+For reasons too long to explain here, test must be run with the optional feature ``--feature "test"`.
+Failure to do so will result in the editor popping in during tests.
diff --git a/TODO.md b/TODO.md
index 39db303..b3d676b 100644
--- a/TODO.md
+++ b/TODO.md
@@ -1,42 +1,35 @@
-## Features
-### --new (name)
- [ ] 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
- [ ]
-
## TODO
[ ] Make a lib for dynamic_format and snippets (impl make a trait for have .id() and other future t)
- [-] Have identical attributes with {0} {1} {0} (^^^^^)
[ ] Benchmarks
[ ] Better modes
[ ] Test populate_actions
[ ] Change all uncatchables errors to expect to be more helpful or change them to better errors
[ ] Document non coverage
+ [ ] Have the the EditWhole save under a different path if name was changed (and edit too)
+ [ ] Add an option to delete a snippet
### Currently working on
[-] Coverage
[ ] Proceed one by one and catch errors
- [-] Remake all helper functions
- [*] locate_snippet
- [*] create_snippet
- [*] edit_snippet
- [*] edit_whole_snippet
- [x] print_snippet
[-] Finish tests on
[*] locate_snippet
[*] create_snippet
[*] edit_snippet
[*] edit_whole_snippet
- [x] print_snippet
+ [-] print_snippet
[ ] Cargo test must always have the test feature
## Finished
[*] Make custom errors
[*] Transform all panic in errors
[*] Make functions into methods
+ [*] Remake all helper functions
+ [*] locate_snippet
+ [*] create_snippet
+ [*] edit_snippet
+ [*] edit_whole_snippet
+ [*] print_snippet
+ [-] Have identical attributes with {0} {1} {0} (^^^^^)
## Posponed or rendered useless
[x] Chain the methods when possible with result ?
diff --git a/coverage/html/badges/flat.svg b/coverage/html/badges/flat.svg
index f4a8de8..d0e421f 100644
--- a/coverage/html/badges/flat.svg
+++ b/coverage/html/badges/flat.svg
@@ -1,6 +1,6 @@
\ No newline at end of file
diff --git a/src/dynamic_formatter.rs b/src/dynamic_formatter.rs
index f8ae20e..ecb7223 100644
--- a/src/dynamic_formatter.rs
+++ b/src/dynamic_formatter.rs
@@ -1,7 +1,7 @@
//! A lib of vector operators
//! Allow for replacement and formatting of strings
-use crate::{errors::SnippetError, tokenizer::create_tokens_from_string};
+use crate::{errors::SnippetError, tokenizer};
/// A dynamic formatter, formatting a string with any number of
/// {} with element of a Vec, by default the search doen't need to
@@ -14,22 +14,33 @@ pub fn dynamic_format(format_string: &str, vector: Vec) -> Result
- 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 token_list = tokenizer::create_tokens_from_string(format_string)?;
- 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]));
+ let cap = format_string.len() + 5 * vector.len();
+ let mut final_string = String::with_capacity(cap);
+ let mut moving_index = 0;
+ for tok in token_list {
+ match tok {
+ tokenizer::SnippetToken::Substitution(s) => {
+ let index;
+ match s.id() {
+ Some(i) => index = i,
+ None => {
+ // TODO: Get rid of this wonky hack
+ index = moving_index;
+ moving_index += 1
+ }
+ };
+ if let Some(text) = vector.get(index) {
+ final_string.push_str(&text.to_string())
+ } else {
+ return Err(SnippetError::IndexError(index));
+ }
+ }
+ tokenizer::SnippetToken::Text(t) => final_string.push_str(t),
}
}
- Ok(fmt_vec.join(""))
+ Ok(final_string)
}
/// Fill the argument vector with a list of defaults values if needed
diff --git a/src/errors.rs b/src/errors.rs
index 33d6f89..1277f92 100644
--- a/src/errors.rs
+++ b/src/errors.rs
@@ -24,6 +24,8 @@ pub enum SnippetError {
FoundNoEraseError(PathBuf),
/// The snippet couldn't be reparsed
ReparsingError,
+ /// The custom formatter coulnd't access an index
+ IndexError(usize),
}
impl fmt::Display for SnippetError {
@@ -51,7 +53,8 @@ impl fmt::Display for SnippetError {
"The snippet {:?} already exists. Use -f/--force to overwrite it.",
p.file_name(),
),
- SnippetError::ReparsingError => write!(f,"The snipped couldn't be re-parsed, it might be caused by a bad value in your edit. \nThe snipped was saved as a raw file instead but cant be used as is.")
+ SnippetError::ReparsingError => write!(f,"The snipped couldn't be re-parsed, it might be caused by a bad value in your edit. \nThe snipped was saved as a raw file instead but cant be used as is."),
+ SnippetError::IndexError(ref i) => write!(f,"An error occured while trying to access the index {} of the given arguments.\nThe default arguments for this command likely do not support {0} arguments",i),
}
}
}
@@ -70,6 +73,7 @@ impl error::Error for SnippetError {
SnippetError::NotFoundNoRetryError(_) => None,
SnippetError::FoundNoEraseError(_) => None,
SnippetError::ReparsingError => None,
+ SnippetError::IndexError(_) => None,
}
}
}
diff --git a/src/tokenizer.rs b/src/tokenizer.rs
index 57d3959..5466f6d 100644
--- a/src/tokenizer.rs
+++ b/src/tokenizer.rs
@@ -4,9 +4,11 @@
use regex::Regex;
+use crate::errors::SnippetError;
+
/// A formatter, containing (or not) an argument to be subsitued with
#[derive(Debug)]
-struct CustFormatter {
+pub struct CustFormatter {
/// The positional id of the element to replace with
pub id: Option,
}
@@ -21,11 +23,16 @@ impl CustFormatter {
id: Some(text.parse::().unwrap()),
}
}
+
+ /// Return an option of the Id
+ pub fn id(&self) -> Option {
+ self.id
+ }
}
/// The parsed snippet
#[derive(Debug)]
-enum Token<'a> {
+pub enum SnippetToken<'a> {
/// A subsitution token, containing either an index or nothing (and being "positional")
Substitution(CustFormatter),
/// A text token, the inbetween
@@ -50,14 +57,13 @@ macro_rules! push_if_some {
}
/// Create a Token list from the snippet given and return it as a vector of token
-pub fn create_tokens_from_string(snippet: &str) {
+pub fn create_tokens_from_string(snippet: &str) -> Result, SnippetError> {
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()))
@@ -68,8 +74,12 @@ pub fn create_tokens_from_string(snippet: &str) {
);
readhead = r.end();
}
- create_token_from_pos(snippet, Status::Text, readhead, None);
- println!("{:?}", token_list);
+ push_if_some!(
+ token_list,
+ create_token_from_pos(snippet, Status::Text, readhead, None)
+ );
+
+ Ok(token_list)
}
/// Create a single Token from the current positions
@@ -78,16 +88,34 @@ fn create_token_from_pos(
status: Status,
start: usize,
stop: Option,
-) -> 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]))
+ (None, Status::Formater) => {
+ SnippetToken::Substitution(CustFormatter::new(&text[start + 1..]))
}
- (Some(stop), Status::Text) => Token::Text(&text[start..stop]),
+ (None, Status::Text) => SnippetToken::Text(&text[start..]),
+ (Some(stop), Status::Formater) => {
+ SnippetToken::Substitution(CustFormatter::new(&text[start + 1..stop - 1]))
+ }
+ (Some(stop), Status::Text) => SnippetToken::Text(&text[start..stop]),
};
- println!("{:?}", text);
Some(text)
}
+
+#[cfg(test)]
+mod test {
+ // use super::*;
+
+ #[ignore]
+ #[test]
+ fn test_create_token_from_pos() {
+ todo!()
+ }
+
+ #[ignore]
+ #[test]
+ fn test_create_token_from_string() {
+ todo!()
+ }
+}
diff --git a/src/wrapper_functions.rs b/src/wrapper_functions.rs
index 77e2f69..50cb13e 100644
--- a/src/wrapper_functions.rs
+++ b/src/wrapper_functions.rs
@@ -10,8 +10,9 @@ use std::fs::create_dir_all;
use std::io::{read_to_string, Write};
use std::{env, fs::File, path::PathBuf};
-use crate::dynamic_formatter;
-use crate::{dynamic_formatter::complete_vec, errors::SnippetError, snippet::Snippet, Cli};
+use crate::errors::SnippetError;
+use crate::snippet::Snippet;
+use crate::{dynamic_formatter, Cli};
// Potential way to chain all actions without re-opening
// /// The status of the snippet in memory
@@ -63,7 +64,7 @@ pub fn create_snippet(cli: &Cli) -> Result<(), SnippetError> {
pub fn edit_snippet(cli: &Cli) -> Result<(), SnippetError> {
// Try loading, if not existant check if create or error
let status = check_dir_and_open(&cli.snippet)?;
- let (mut snp, f, p) = match status {
+ let (mut snp, _, p) = match status {
FileStatus::Opened((p, f)) => (Snippet::from_file(&f)?, f, p),
FileStatus::NotFound(p) => {
if cli.create {
@@ -163,7 +164,7 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> {
/// Print the snippet to stdout
pub fn print_snippet(cli: &Cli) -> Result<(), SnippetError> {
// Try to load the snippet
- let (p, f) = match check_dir_and_open(&cli.snippet)? {
+ let (_, f) = match check_dir_and_open(&cli.snippet)? {
FileStatus::Opened((p, f)) => (p, f),
FileStatus::NotFound(p) => return Err(SnippetError::NotFound(p)),
};
@@ -171,7 +172,7 @@ pub fn print_snippet(cli: &Cli) -> Result<(), SnippetError> {
let snp = Snippet::from_file(&f)?;
// Add the given arguments to the snippet
- let final_args = complete_vec(&cli.args, &snp.default_values)?;
+ let final_args = dynamic_formatter::complete_vec(&cli.args, &snp.default_values)?;
// Print the snippet
let f_str = dynamic_formatter::dynamic_format(&snp.content, final_args)?;