edition_and_parse #1

Merged
Dandaedre merged 20 commits from edition_and_parse into main 2023-05-23 00:08:36 +02:00
13 changed files with 1070 additions and 226 deletions

3
.gitignore vendored
View File

@ -19,3 +19,6 @@ Cargo.lock
# Added by cargo
/target
/coverage
/llvm
tarpaulin-report.html

View File

@ -1,11 +1,18 @@
[package]
name = "snp"
version = "0.1.0"
author = "Dandaedre"
version = "1.0.1"
edition = "2021"
[features]
test = []
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[profile.test]
opt-level = 0
[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"

32
Makefile.toml Normal file
View File

@ -0,0 +1,32 @@
[tasks.testcov]
script_runner = "@shell"
ignore_errors = true
script = [
"mkdir -p coverage",
"mkdir -p coverage/html",
"mkdir -p coverage/",
"CARGO_INCREMENTAL=0 RUSTFLAGS='-Cinstrument-coverage -Ccodegen-units=1 -Copt-level=0 -Coverflow-checks=off' LLVM_PROFILE_FILE='llvm/cargo-test-%p-%m.profraw' cargo test --features test",
"grcov . --binary-path ./target/debug/deps/ -s . -t html --branch --ignore-not-existing --ignore '../*' --ignore '/*' --ignore '*/main.rs' --ignore '*/errors.rs' -o coverage/html/",
]
[tasks.testing]
script_runner = "@shell"
ignore_errors = true
script = [
"cargo test --features \"test\"",
]
[tasks.win_build]
script_runner = "@shell"
ignore_errors = true
script = [
"CROSS_CONTAINER_ENGINE=podman cross build --target x86_64-pc-windows-gnu"
]
[tasks.win_test]
script_runner = "@shell"
ignore_errors = true
script = [
"CROSS_CONTAINER_ENGINE=podman cross test --features test --target x86_64-pc-windows-gnu"
]

View File

@ -1,6 +1,29 @@
# snp
![coverage/html/badges/flat.svg](coverage/html/badges/flat.svg)
<img src="https://proxy.dandaedre.com/gitea/repo-avatars/30-fed01296b47bdd2e84f8f0a1a96e4094" alt="drawing" width="140" align="right"/>
A simple cli utility to manage snippet
A simple cli utility to manage snippets, while it was created to be used with Helix, it can work with any tool integrating input from stdout
## Usage
```sh
To create a new snippet and edit it immediately
$ snp snippet_name -c -e list of default tokens
To edit the content of a snippet
$ snp snippet_name -e
To edit the whole snippet (allow for editing of name and list of args)
$ snp snippet_name -E
To delete a snippet
$ snp snippet_name -d
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.

49
TODO.md
View File

@ -1,15 +1,36 @@
## 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
- Make custom errors
- Transform all panic in errors
- Make functions into methods
- Have identical attributes with {0} {1} {0} (^^^^^)
[ ] Benchmarks
[ ] Better use of file modes
[ ] Document non coverage
[ ] Have the the EditWhole save under a different path if name was changed (and edit too)
[ ] Find a solution for the .badpocalypse
### Currently working on
## 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
[*] Finish tests on
[*] locate_snippet
[*] create_snippet
[*] edit_snippet
[*] edit_whole_snippet
[*] print_snippet
[*] delete snippet
[*] Have identical attributes with {0} {1} {0} (^^^^^)
[*] Add an option to delete a snippet
[*] Coverage
[*] Test populate_actions
## Posponed or rendered useless
[x] Chain the methods when possible with result ?
[ ] Make a lib for dynamic_format and snippets (impl make a trait for have .id() and other future t)
[ ] Change all uncatchables errors to expect to be more helpful or change them to better errors

View File

@ -0,0 +1,23 @@
<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: 99%">
<title>coverage: 99%</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
</linearGradient>
<clipPath id="r">
<rect width="96" height="20" rx="3" fill="#fff"/>
</clipPath>
<g clip-path="url(#r)">
<rect width="61" height="20" fill="#555"/>
<rect x="61" width="35" height="20" fill="#97ca00"/>
<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">99%</text>
<text x="775" y="140" transform="scale(.1)" fill="#fff" textLength="250">99%</text>
</g>
<script xmlns=""/>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

145
src/actions.rs Normal file
View File

@ -0,0 +1,145 @@
//! The action module, including all the logic to jump to a specific action
//! depending on the CLI arguments
use std::error::Error;
use crate::{errors, wrapper_functions, Cli};
/// List of all possible actions, some are mutually exclusive
#[derive(Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub enum Actions {
/// Edit the content of the snippet only
Edit,
/// Edit the whole snippet
EditAll,
/// Locate the snippet and show the position
Locate,
/// Show the snippet (with replacement done)
Show,
/// Create the snippet with the given name and arguments
Create,
/// Deletes the snippet
Delete,
}
/// The main worker, execute all commands given as Args
pub fn execute_parsed_cli(cli: Cli) -> Result<(), errors::SnippetError> {
let list_actions = populate_actions(&cli);
for action in list_actions.iter() {
if let Err(e) = match action {
Actions::Locate => wrapper_functions::locate_snippet(&cli),
Actions::Create => wrapper_functions::create_snippet(&cli),
Actions::Show => wrapper_functions::print_snippet(&cli),
Actions::Edit => wrapper_functions::edit_snippet(&cli),
Actions::EditAll => wrapper_functions::edit_whole_snippet(&cli),
Actions::Delete => wrapper_functions::delete_snippet(&cli),
} {
println!("An error occured during runtime:\n\t{}", e);
if let Some(e) = e.source() {
println!("This error was caused by: \n\t{}", e);
}
return Err(e);
};
}
Ok(())
}
/// Populate a logical vec of succesive actions to perform depending on arguments
/// even when the arguments don't make sense
fn populate_actions(cli: &Cli) -> Vec<Actions> {
let mut actions = Vec::new();
match (cli.locate, cli.create, cli.edit, cli.edit_all, cli.delete) {
(true, _, _, _, false) => actions.push(Actions::Locate),
(_, false, false, true, false) => actions.push(Actions::EditAll),
(_, true, _, true, false) => actions.push(Actions::EditAll),
(_, true, false, false, false) => actions.push(Actions::Create),
(_, false, true, _, false) => actions.push(Actions::Edit),
(_, true, true, false, false) => actions.push(Actions::Edit),
(false, false, false, false, false) => actions.push(Actions::Show),
(_, _, _, _, true) => actions.push(Actions::Delete),
}
actions
}
#[cfg(test)]
mod test {
use super::*;
use clap::Parser;
macro_rules! false_cli {
($($arg:expr),+) => {
Cli::parse_from(vec![$($arg),+])
};
}
macro_rules! group_actions{
($(($cli:expr, $expect:expr),)*) => {
vec![$(($cli,$expect)),+]
};
}
#[test]
fn test_populate_actions() {
// false_cli!("snp", "name", "-l"), Actions::Locate
let group = group_actions!(
(
false_cli!("snp", "name", "-l", "-c", "-e", "-E"),
vec![Actions::Locate]
),
(false_cli!("snp", "name", "-l"), vec![Actions::Locate]),
(false_cli!("snp", "name", "-d"), vec![Actions::Delete]),
(
false_cli!("snp", "name", "-d", "-e", "e", "-E", "-l"),
vec![Actions::Delete]
),
(false_cli!("snp", "name", "-E"), vec![Actions::EditAll]),
(false_cli!("snp", "name", "-E", "-e"), vec![Actions::Edit]),
(
false_cli!("snp", "name", "-E", "-e", "-c"),
vec![Actions::EditAll]
),
(false_cli!("snp", "name", "-e"), vec![Actions::Edit]),
(false_cli!("snp", "name", "-e", "-c"), vec![Actions::Edit]),
(false_cli!("snp", "name", "-l"), vec![Actions::Locate]),
(false_cli!("snp", "name", "-c"), vec![Actions::Create]),
(false_cli!("snp", "name"), vec![Actions::Show]),
(false_cli!("snp", "name", "-d"), vec![Actions::Delete]),
(
false_cli!("snp", "name", "-d", "-c", "-E", "-e", "-l"),
vec![Actions::Delete]
),
);
for (cli, res) in group.iter() {
println!("Testing {:?}..actions expected {:?}", cli, res);
let fnd = populate_actions(cli);
println!("... found {:?}", fnd);
assert!(res.iter().zip(fnd).all(|(a, b)| *a == b));
}
}
#[test]
fn test_execute_parsed_cli() {
let list_cli = vec![
false_cli!("snp", "parsed_cli", "-e", "-c"),
false_cli!("snp", "parsed_cli", "-c", "-f"),
false_cli!("snp", "parsed_cli"),
false_cli!("snp", "parsed_cli", "-E", "-f"),
false_cli!("snp", "parsed_cli", "-d"),
];
let bad_cli = vec![
false_cli!("snp", "parsed_cli_bad", "-l"),
false_cli!("snp", "-d", "parsed_cli_bad"),
];
for cl in list_cli {
println!("Testing {:?} expecting success", cl);
assert!(execute_parsed_cli(cl).is_ok());
}
for cl in bad_cli {
println!("Testing {:?} expecting failure", cl);
assert!(execute_parsed_cli(cl).is_err());
}
}
}

99
src/dynamic_formatter.rs Normal file
View File

@ -0,0 +1,99 @@
//! A lib of vector operators
//! Allow for replacement and formatting of strings
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
/// 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
/// A pseudo dynamic formatter, tries to fill all {} in a string with the values
/// in a vector
pub fn dynamic_format<T>(format_string: &str, vector: Vec<T>) -> Result<String, SnippetError>
where
T: std::fmt::Display,
{
let token_list = tokenizer::create_tokens_from_string(format_string)?;
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 => {
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(final_string)
}
/// Fill the argument vector with a list of defaults values if needed
pub fn complete_vec<T>(to_fill: &Vec<T>, defaults: &Vec<T>) -> Result<Vec<T>, SnippetError>
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(SnippetError::Unknown), //TODO: Fix this error
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"],
)
.unwrap();
assert_eq!(res, ("big str aaa with many bbb formatters".to_string()));
let res =
dynamic_format("{} {0} {0} {2} {d} {1}", vec!["aaa", "bbb", "ccc", "dddd"]).unwrap();
assert_eq!(res, ("aaa aaa aaa ccc {d} bbb".to_string()));
let res = dynamic_format("{100}", vec!["a"]);
assert!(res.is_err());
let res = dynamic_format("", vec!["a"]).unwrap();
assert_eq!(res, "".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);
assert!(complete_vec(&big, &deff).is_err());
}
}

97
src/errors.rs Normal file
View File

@ -0,0 +1,97 @@
//! A general error module for the snp program
#![cfg(not(tarpaulin_include))]
use std::{error, fmt, path::PathBuf};
/// Snippet error, general error wrapper for the Snippet module
/// All error are wrapper with more information available with the source() method
#[derive(Debug)]
#[allow(dead_code)]
pub enum SnippetError {
/// A supposedly impossible to trigger error
#[allow(dead_code)]
Unknown,
/// Clap error, originating from the Cli parser
ClapError(clap::error::Error),
/// A generic IOError, the source is mandatory to get the specifics
IOError(std::io::Error),
/// Yaml error, generated during serialisation of snippets
YAMLError(serde_yaml::Error),
/// The file doesn't exits and can't be used
NotFound(PathBuf),
/// The file doen't exist and no creation was asked
NotFoundNoRetryError(PathBuf),
/// The snippet was found but shouldn't be erased because of flags
FoundNoEraseError(PathBuf),
/// The snippet couldn't be reparsed
ReparsingError,
/// The custom formatter coulnd't access an index
IndexError(usize),
}
impl fmt::Display for SnippetError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
SnippetError::Unknown => write!(f, "An unknonw error occured"),
SnippetError::ClapError(..) => write!(f, "An error occured while parsing the input"),
SnippetError::IOError(..) => write!(f, "An error occured while editing the file"),
SnippetError::YAMLError(..) => {
write!(f, "Couldn't convert the given arguments into a yaml")
}
SnippetError::NotFound(ref p) => write!(
f,
"The file {:?} doesn't exists",p.file_name().unwrap(),
),
SnippetError::NotFoundNoRetryError(ref p) => {
write!(
f,
"The config {:?} doen't exists. Use -c to create it.",
p.file_name(),
)
}
SnippetError::FoundNoEraseError(ref p) => write!(
f,
"The snippet {:?} already exists. Use -f/--force to overwrite it.",
p.file_name().unwrap(),
),
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),
}
}
}
impl error::Error for SnippetError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match *self {
SnippetError::Unknown => None,
// The cause is the underlying implementation error type. Is implicitly
// cast to the trait object `&error::Error`. This works because the
// underlying type already implements the `Error` trait.
SnippetError::ClapError(ref e) => Some(e),
SnippetError::IOError(ref e) => Some(e),
SnippetError::YAMLError(ref e) => Some(e),
SnippetError::NotFound(_) => None,
SnippetError::NotFoundNoRetryError(_) => None,
SnippetError::FoundNoEraseError(_) => None,
SnippetError::ReparsingError => None,
SnippetError::IndexError(_) => None,
}
}
}
impl From<clap::error::Error> for SnippetError {
fn from(err: clap::error::Error) -> SnippetError {
SnippetError::ClapError(err)
}
}
impl From<std::io::Error> for SnippetError {
fn from(err: std::io::Error) -> SnippetError {
SnippetError::IOError(err)
}
}
impl From<serde_yaml::Error> for SnippetError {
fn from(err: serde_yaml::Error) -> SnippetError {
SnippetError::YAMLError(err)
}
}

View File

@ -4,23 +4,20 @@
#![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;
mod actions;
mod dynamic_formatter;
mod errors;
mod snippet;
mod tokenizer;
mod wrapper_functions;
/// The cli arguments to give to the utility
#[derive(Parser, Debug)]
#[command(author, version, about)]
struct Cli {
pub struct Cli {
/// The snippet name (and therefore his path)
#[arg()]
snipplet: String,
snippet: String,
/// Wether to try to load or instead create a new one
#[arg(short, long, default_value_t = false)]
@ -30,208 +27,30 @@ struct Cli {
#[arg(short, long, default_value_t = false)]
locate: bool,
/// Launch the editor and edit the snippet
#[arg(short, long, default_value_t = false)]
edit: bool,
/// Launch the editor and edit the whole snippet
#[arg(short = 'E', long = "Edit", default_value_t = false)]
edit_all: 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<String>,
/// Wether to force the creation or save and overwrite existing data
#[arg(short, long, default_value_t = false)]
force: bool,
/// Wether to delete a snippet, takes precedence over everything
#[arg(short, long, default_value_t = false)]
delete: bool,
}
fn main() {
/// Main entry point, everything is defered for testing and coverage
fn main() -> Result<(), errors::SnippetError> {
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<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
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.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<String>,
/// The base string to format
content: String,
}
impl Snippet {
/// Create a new snippet
pub fn new(name: String, arguments: Vec<String>, 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<Self, ()> {
// 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<T>(format_string: &str, vector: Vec<T>) -> Result<String, ()>
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<T>(to_fill: &Vec<T>, defaults: &Vec<T>) -> Result<Vec<T>, ()>
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")
};
}
actions::execute_parsed_cli(cli)
}

78
src/snippet.rs Normal file
View File

@ -0,0 +1,78 @@
//! Snippet module, holding most of the logic of the snippet
//!
//! Saving, loading, writing etc...
use clap::error::Result;
use serde::{Deserialize, Serialize};
use std::{fs::File, io::Write};
use crate::errors::SnippetError;
/// A snippet ready to be Serialized/Deserialized
///
/// No conditionnal behaviour is handle by this module,
/// all calls will force, override and delete by default
#[derive(Deserialize, Serialize, Debug)]
pub struct Snippet {
/// Akin to path, the name of the snippet is where to store it
pub name: String,
/// The default value of all args
pub default_values: Vec<String>,
/// The base string to format
pub 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 in a file, errors on write error
pub fn save_in(&self, mut file: &std::fs::File) -> Result<(), SnippetError> {
write!(file, "{}", serde_yaml::to_string(self)?)?;
Ok(())
}
/// Mutate the contents in place
pub fn edit(&mut self) -> Result<(), SnippetError> {
self.content = edit::edit(self.content.clone())?;
Ok(())
}
/// Create snippet from file buffer (deserialize)
pub fn from_file(f: &File) -> Result<Self, SnippetError> {
let snp: Snippet = serde_yaml::from_reader(f)?;
Ok(snp)
}
/// Create a snippet from a String reference (typically used for edits)
pub fn from_string(buffer: &str) -> std::result::Result<Self, SnippetError> {
let snp: Snippet = serde_yaml::from_str(buffer)?;
Ok(snp)
}
/// Forcefully save a snippet, will erase the file if already existing
pub fn write_over(&self, path: &std::path::PathBuf) -> Result<(), SnippetError> {
let mut f = File::create(path)?;
write!(f, "{}", serde_yaml::to_string(self)?)?;
Ok(())
}
/// Create an empty snippet and immediately serialize it
pub fn empty(name: String, default_values: Vec<String>) -> String {
serde_yaml::to_string(&Snippet {
name,
default_values,
content: String::new(),
//..Snippet::default(),
})
.unwrap()
}
}

151
src/tokenizer.rs Normal file
View File

@ -0,0 +1,151 @@
//! Tokenizer module, tasked to parse a string and return a list of tokens
//!
//! As the dynamic formatter, the tokenizer is supposedly format agnostic
use regex::Regex;
use crate::errors::SnippetError;
/// A formatter, containing (or not) an argument to be subsitued with
#[derive(Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub 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()),
}
}
/// Return an option of the Id
pub fn id(&self) -> Option<usize> {
self.id
}
}
/// The parsed snippet
#[derive(Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub enum SnippetToken<'a> {
/// A subsitution token, containing either an index or nothing (and being "positional")
Substitution(CustFormatter),
/// A text token, the inbetween
Text(&'a str),
}
/// 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 as a vector of token
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
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();
}
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
fn create_token_from_pos(
text: &str,
status: Status,
start: usize,
stop: Option<usize>,
) -> Option<SnippetToken> {
let text = match (stop, status) {
(None, Status::Formater) => {
SnippetToken::Substitution(CustFormatter::new(&text[start + 1..]))
}
(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]),
};
Some(text)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_create_token_from_pos() {
// All calls
let text = String::from("0123456789");
assert_eq!(
create_token_from_pos(&text, Status::Formater, 5, None),
Some(SnippetToken::Substitution(CustFormatter::new("6789")))
);
assert_eq!(
create_token_from_pos(&text, Status::Text, 7, None),
Some(SnippetToken::Text("789"))
);
assert_eq!(
create_token_from_pos(&text, Status::Formater, 2, Some(5)), //Need at least 2 digits
Some(SnippetToken::Substitution(CustFormatter::new("3")))
);
assert_eq!(
create_token_from_pos(&text, Status::Text, 0, Some(1)),
Some(SnippetToken::Text("0"))
);
}
#[test]
fn test_create_token_from_string() {
let v = create_tokens_from_string("{} {1} { {{}}").unwrap();
assert_eq!(
v,
vec![
SnippetToken::Text(""),
SnippetToken::Substitution(CustFormatter { id: None }),
SnippetToken::Text(" "),
SnippetToken::Substitution(CustFormatter { id: Some(1) }),
SnippetToken::Text(" { {"),
SnippetToken::Substitution(CustFormatter { id: None }),
SnippetToken::Text("}"),
]
);
}
}

346
src/wrapper_functions.rs Normal file
View File

@ -0,0 +1,346 @@
//! Module holding the wrapper function called from the main functions
//!
//! All functions included should either take a Cli object and return a SnippetError
//! or be a helper function for such a function
#[allow(unused)] // Mandatory because of how test and rust-analyser work
use edit::edit;
use std::fs::create_dir_all;
use std::io::{read_to_string, Write};
use std::{env, fs::File, path::PathBuf};
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
// pub enum PotentialSnippet {
// /// The snippet wasn't loaded
// FileDest(File),
// /// The snippet was loaded
// LoadedSnippet(Snippet),
// /// No snippet currently exists
// None,
// }
/// Locate and print a snippet location
///
/// Will error on snippet not existing
pub fn locate_snippet(cli: &Cli) -> Result<(), SnippetError> {
let status = check_dir_and_open(&cli.snippet)?;
match status {
FileStatus::Opened((p, _)) => {
println!("{:?}", p.as_os_str());
Ok(())
}
FileStatus::NotFound(p) => Err(SnippetError::NotFoundNoRetryError(p)),
}
}
/// Create a new snippet with the given cli args
pub fn create_snippet(cli: &Cli) -> Result<(), SnippetError> {
// Create a snippet with the given data
let snp = Snippet::new(cli.snippet.clone(), cli.args.clone(), String::from(""));
let status = check_dir_and_open(&cli.snippet)?;
let (f, p) = match status {
FileStatus::Opened((p, _)) => {
if cli.force {
// Overwrite the snippet
(File::create(&p)?, p)
} else {
// Do not overrite and return an error
return Err(SnippetError::FoundNoEraseError(p));
}
}
FileStatus::NotFound(p) => (File::create(&p)?, p), // Create a new snippet
};
snp.save_in(&f)?;
println!("The snippet {:?} was created successfully", p);
Ok(())
}
/// Open and load snippet and edit it
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, _, p) = match status {
FileStatus::Opened((p, f)) => (Snippet::from_file(&f)?, f, p),
FileStatus::NotFound(p) => {
if cli.create {
(
Snippet::new(cli.snippet.clone(), cli.args.clone(), String::from("")),
File::create(&p)?,
p,
)
} else {
return Err(SnippetError::NotFoundNoRetryError(p));
}
}
};
// During tests, the editor cannot be tested
#[cfg(not(feature = "test"))]
snp.edit()?;
snp.write_over(&p)?;
println!(
"The snippet {:?} was succesfully saved",
p.file_name().unwrap()
);
Ok(())
}
/// Edit the whole snippet and save it where neededi
/// Note that the snippet can be saved with another name and might trigger
/// a creation or an override
pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> {
// Try loading the snippet
let status = check_dir_and_open(&cli.snippet);
let (buf, mut p) = match status? {
FileStatus::Opened((p, f)) => (read_to_string(f)?, p),
FileStatus::NotFound(p) => {
if cli.create {
File::create(&p)?;
(Snippet::empty(cli.snippet.clone(), cli.args.clone()), p)
} else {
return Err(SnippetError::NotFoundNoRetryError(p));
}
}
};
// During tests, the editor cannot be tested
#[cfg(not(feature = "test"))]
let buf = edit::edit(buf)?;
// Try reparsing, on error no modifications will be made
match Snippet::from_string(&buf) {
Ok(snp) => {
snp.write_over(&p)?; // TODO: Consider not giving a path, as name can be changed in config
println!(
"The snippet {:?} was succesfully saved",
p.file_name().unwrap()
);
Ok(())
}
Err(_) => {
// The snippet is incorrect, however it should still be saved, just under another name ?
p.set_extension("bad.yaml");
let mut failover = File::create(&p)?;
write!(failover, "{}", &buf)?;
println!(
"The snippet was saved under {:?} in your config",
p.file_name().unwrap()
);
Err(SnippetError::ReparsingError)
}
}
}
// This code is used to check if the name changed but should be moved to a separate function
// let old_name = snp.name.clone();
// // During tests, the editor cannot be tested
// #[cfg(not(feature = "test"))]
// snp.edit()?;
// if snp.name == old_name {
// snp.write_over(&p)
// } else {
// match check_dir_and_open(&snp.name)? {
// FileStatus::Opened((p, _f)) => {
// if cli.force {
// std::fs::remove_file(&p)?;
// snp.write_over(&p)
// } else {
// Err(SnippetError::NotFoundNoRetryError(p))
// }
// }
// FileStatus::NotFound(p) => snp.write_over(&p),
// }
// }
/// Print the snippet to stdout
pub fn print_snippet(cli: &Cli) -> Result<(), SnippetError> {
// Try to load the snippet <name>
let (_, f) = match check_dir_and_open(&cli.snippet)? {
FileStatus::Opened((p, f)) => (p, f),
FileStatus::NotFound(p) => return Err(SnippetError::NotFound(p)),
};
let snp = Snippet::from_file(&f)?;
// Add the given arguments to the snippet
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)?;
println!("{}", f_str);
Ok(())
}
/// Delete a given snippet, errors if the snippet doesn't exists
pub fn delete_snippet(cli: &Cli) -> Result<(), SnippetError> {
let mut path = config_folder()?;
path.push(format!("{}.yaml", cli.snippet));
std::fs::remove_file(path)?;
Ok(())
}
/// The status of the request after the path was attempted to be opened
pub enum FileStatus {
/// The file was opened with success a tuple is returned
/// because the path is sometimes usefull to know, but may be dropped
/// when not
Opened((PathBuf, File)),
/// The file didn't exists and might need to be created
NotFound(PathBuf),
}
/// Full wrapper function, tries to open the config
/// Create the folder and tries to open the file
/// On sucess return a FileStatus::File and a FileStatus::Path or error
/// The rest of the logic is handled by the caller
pub fn check_dir_and_open(name: &str) -> Result<FileStatus, SnippetError> {
let mut dir_path = config_folder()?;
create_dir_all(&dir_path)?;
dir_path.push(format!("{}.yaml", name));
match File::open(&dir_path) {
Ok(f) => Ok(FileStatus::Opened((dir_path, f))),
Err(_e) => Ok(FileStatus::NotFound(dir_path)),
}
}
/// Find a configuration folder/name for the given snippet name
pub fn config_folder() -> Result<PathBuf, SnippetError> {
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");
Ok(dir)
}
#[cfg(test)]
pub mod test {
use super::*;
use clap::Parser;
use std::io::Write;
macro_rules! false_cli {
($($arg:expr),+) => {
&Cli::parse_from(vec![$($arg),+])
};
}
/// Find the path of the given snippet
/// This function should suceed in every situation where a config folder can be set
fn snippet_path(snp: &str) -> Result<PathBuf, SnippetError> {
let mut dir = config_folder()?;
dir.push(format!("{}.yaml", snp));
Ok(dir)
}
#[test]
fn test_config_creation() {
// Try to locate where to set the config
let path: PathBuf = snippet_path("test_config_creation").unwrap();
create_dir_all(path.parent().unwrap()).unwrap();
let _f = File::create(path).unwrap();
assert!(matches!(
check_dir_and_open("test_config_creation").expect("Can't open config"),
FileStatus::Opened(_)
));
}
#[test]
fn test_delete_snippet() {
assert!(create_snippet(false_cli!("-c", "delete_snippet")).is_ok());
assert!(delete_snippet(false_cli!("-d", "delete_snippet")).is_ok());
}
#[test]
fn test_locate() {
// Try to locate an unexisting snippet
let theorical_path = snippet_path("test_locate").expect("Can't find config path");
_ = std::fs::remove_file(&theorical_path);
// Locating the snippet should fail
assert!(locate_snippet(false_cli!("-l", "test_locate")).is_err());
let mut f = File::create(&theorical_path).expect("Couldn't create file");
write!(f, "N").expect("Couldn't write on the new file");
f.sync_data().expect("Can't sync file");
// Locating the snippet should now suceed
assert!(locate_snippet(false_cli!("-l", "test_locate")).is_ok());
}
#[test]
fn test_print_snippet() {
let theorical_path = snippet_path("test_print").expect("Can't find config path");
_ = std::fs::remove_file(theorical_path);
// Print non existing snippet
assert!(print_snippet(false_cli!("snp", "test_print")).is_err());
// Create snippet
assert!(create_snippet(false_cli!("-c", "test_print")).is_ok());
assert!(print_snippet(false_cli!("snp", "test_print")).is_ok());
// assert!(print_snippet(false_cli!("-l", "test_print")).is_ok());
}
#[test]
fn test_create() {
_ = std::fs::remove_file(snippet_path("create_snippet").unwrap());
// Test to create empty
assert!(create_snippet(false_cli!("-c", "create_snippet")).is_ok());
// Test to create again
assert!(create_snippet(false_cli!("-c", "create_snippet")).is_err());
// Test to create with force
assert!(create_snippet(false_cli!("-c", "-f", "create_snippet")).is_ok());
}
#[test]
fn test_edit() {
_ = std::fs::remove_file(snippet_path("edit_content").unwrap());
// Open unnexitant
assert!(edit_snippet(false_cli!("-e", "edit_content")).is_err());
// Force creation
assert!(edit_snippet(false_cli!("-e", "-c", "edit_content")).is_ok());
// Edit when created
println!("{:?}", edit_snippet(false_cli!("-e", "edit_content")));
assert!(edit_snippet(false_cli!("-e", "edit_content")).is_ok());
}
#[test]
fn test_edit_whole() {
_ = std::fs::remove_file(snippet_path("edit_whole").unwrap());
// Open unnexitant
assert!(edit_whole_snippet(false_cli!("-E", "edit_whole")).is_err());
// Force creation
assert!(edit_whole_snippet(false_cli!("-E", "-c", "edit_whole")).is_ok());
// Edit when created
assert!(edit_whole_snippet(false_cli!("-E", "edit_whole")).is_ok());
// Create a badly formatted file
if let FileStatus::Opened((p, _)) = check_dir_and_open("edit_whole").unwrap() {
let mut f = File::create(p).unwrap();
write!(f, "badly formatter yaml").unwrap();
assert!(edit_whole_snippet(false_cli!("-E", "edit_whole")).is_err());
assert!(matches!(
check_dir_and_open("edit_whole.bad").unwrap(),
FileStatus::Opened(_)
));
};
}
}