dds formating and printing

This commit is contained in:
Dandaedre 2023-05-22 15:23:55 +02:00
parent c83dfd8f80
commit b4513f7bd3
7 changed files with 96 additions and 55 deletions

View File

@ -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.

27
TODO.md
View File

@ -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 ?

View File

@ -1,6 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" width="96" height="20" role="img" aria-label="coverage: 89%">
<title>coverage: 89%</title>
xmlns:xlink="http://www.w3.org/1999/xlink" width="96" height="20" role="img" aria-label="coverage: 64%">
<title>coverage: 64%</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
@ -10,14 +10,14 @@
</clipPath>
<g clip-path="url(#r)">
<rect width="61" height="20" fill="#555"/>
<rect x="61" width="35" height="20" fill="#dfb317"/>
<rect x="61" width="35" height="20" fill="#e05d44"/>
<rect width="96" height="20" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110">
<text aria-hidden="true" x="315" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="510">coverage</text>
<text x="315" y="140" transform="scale(.1)" fill="#fff" textLength="510">coverage</text>
<text aria-hidden="true" x="775" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">89%</text>
<text x="775" y="140" transform="scale(.1)" fill="#fff" textLength="250">89%</text>
<text aria-hidden="true" x="775" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">64%</text>
<text x="775" y="140" transform="scale(.1)" fill="#fff" textLength="250">64%</text>
</g>
<script xmlns=""/>
</svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -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<T>(format_string: &str, vector: Vec<T>) -> Result<String,
where
T: std::fmt::Display,
{
// TODO: RESTART FROM HERE, do the permutation
// Implement a to_str or a collect for vec<Formatter>
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

View File

@ -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,
}
}
}

View File

@ -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<usize>,
}
@ -21,11 +23,16 @@ impl CustFormatter {
id: Some(text.parse::<usize>().unwrap()),
}
}
/// Return an option of the Id
pub fn id(&self) -> Option<usize> {
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<Vec<SnippetToken>, 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<usize>,
) -> Option<Token> {
) -> Option<SnippetToken> {
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!()
}
}

View File

@ -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 <name>
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)?;