Compare commits

...

12 Commits
1.0.4 ... main

5 changed files with 129 additions and 40 deletions

View File

@ -1,7 +1,7 @@
[package] [package]
name = "snp" name = "snp"
authors = ["Dandaedre"] authors = ["Dandaedre"]
version = "1.0.4" version = "1.0.6"
edition = "2021" edition = "2021"
[features] [features]

16
TODO.md
View File

@ -1,19 +1,23 @@
## TODO ## TODO
[ ] Benchmarks [ ] Benchmarks
[ ] Better use of file modes [ ] Better use of file modes
[ ] Document non coverage
[ ] Find a solution for the .badpocalypse [ ] Find a solution for the .badpocalypse
[ ] Edit args only [ ] Edit args only
[ ] Double backslash win [ ] Case sensitivity windows
[ ] Remove last return [ ] Use Ok for results instead of prints
[ ] Remove the prerequiste of name for --list [ ] Use priority instead of a cursed match statement
[ ] Have a method to get name, path and all with a custom error on unwrap
### Currently working on ### Currently working on
[ ] Have an actual human give feedback on the error name readability
## Finished ## Finished
[*] Add some examples with --example
## Posponed or rendered useless ## Posponed or rendered useless
[x] Chain the methods when possible with result ? [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) [ ] 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 [ ] Change all uncatchables errors to expect to be more helpful or change them to better errors
[ ] Document non coverage
[ ] Correct the newline problem (with toml ?)
[*] Error: Delete, unclear ?

View File

@ -23,6 +23,8 @@ pub enum Actions {
Rename, Rename,
/// Find a snippet matching a name/regex /// Find a snippet matching a name/regex
Find, Find,
/// Create an example snippet
Example,
} }
/// The main worker, execute all commands given as Args /// The main worker, execute all commands given as Args
@ -38,8 +40,9 @@ pub fn execute_parsed_cli(cli: Cli) -> Result<(), errors::SnippetError> {
Actions::Delete => wrapper_functions::delete_snippet(&cli), Actions::Delete => wrapper_functions::delete_snippet(&cli),
Actions::Rename => wrapper_functions::rename_snippet(&cli), Actions::Rename => wrapper_functions::rename_snippet(&cli),
Actions::List => wrapper_functions::list_snippets(&cli), Actions::List => wrapper_functions::list_snippets(&cli),
Actions::Example => wrapper_functions::create_example(&cli),
} { } {
// println!("An error occured during runtime:\n\t{}", e); println!("An error occured during runtime:\n\t{}", e);
// if let Some(e) = e.source() { // if let Some(e) = e.source() {
// println!("This error was caused by: \n\t{}", e); // println!("This error was caused by: \n\t{}", e);
// } // }
@ -62,17 +65,19 @@ fn populate_actions(cli: &Cli) -> Vec<Actions> {
cli.delete, cli.delete,
&cli.rename, &cli.rename,
cli.list, cli.list,
cli.example,
) { ) {
(true, _, _, _, false, _, false) => actions.push(Actions::Find), (true, _, _, _, false, _, false, false) => actions.push(Actions::Find),
(_, false, false, true, false, _, false) => actions.push(Actions::EditAll), (_, false, false, true, false, _, false, false) => actions.push(Actions::EditAll),
(_, true, _, true, false, _, false) => actions.push(Actions::EditAll), (_, true, _, true, false, _, false, false) => actions.push(Actions::EditAll),
(_, true, false, false, false, _, false) => actions.push(Actions::Create), (_, true, false, false, false, _, false, false) => actions.push(Actions::Create),
(_, false, true, _, false, _, false) => actions.push(Actions::Edit), (_, false, true, _, false, _, false, false) => actions.push(Actions::Edit),
(_, true, true, false, false, _, false) => actions.push(Actions::Edit), (_, true, true, false, false, _, false, false) => actions.push(Actions::Edit),
(false, false, false, false, false, None, false) => actions.push(Actions::Show), (false, false, false, false, false, None, false, false) => actions.push(Actions::Show),
(_, _, _, _, true, _, false) => actions.push(Actions::Delete), (_, _, _, _, true, _, false, false) => actions.push(Actions::Delete),
(_, _, _, _, _, Some(_), false) => actions.push(Actions::Rename), (_, _, _, _, _, Some(_), false, false) => actions.push(Actions::Rename),
(_, _, _, _, _, _, true) => actions.push(Actions::List), (_, _, _, _, _, _, true, false) => actions.push(Actions::List),
(_, _, _, _, _, _, _, true) => actions.push(Actions::Example),
} }
actions actions
} }
@ -138,7 +143,9 @@ mod test {
vec![Actions::Create] vec![Actions::Create]
), ),
(false_cli!("snp", "-l"), vec![Actions::List]), (false_cli!("snp", "-l"), vec![Actions::List]),
// (false_cli!("snp", "-l"), vec![Actions::List]), (false_cli!("snp", "--example"), vec![Actions::Example]),
(false_cli!("snp"), vec![Actions::Show]), // It's an acceptable error
// (false_cli!("snp", "-l"), vec![Actions::List]),
); );
for (cli, res) in group.iter() { for (cli, res) in group.iter() {
println!("Testing {:?}..actions expected {:?}", cli, res); println!("Testing {:?}..actions expected {:?}", cli, res);
@ -161,6 +168,8 @@ mod test {
false_cli!("snp", "parsed_cli", "-r", "new_name", "-f"), false_cli!("snp", "parsed_cli", "-r", "new_name", "-f"),
false_cli!("snp", "new_name", "-d"), false_cli!("snp", "new_name", "-d"),
false_cli!("snp", "-l"), false_cli!("snp", "-l"),
false_cli!("snp"),
false_cli!("snp", "--example"),
]; ];
let bad_cli = vec![ let bad_cli = vec![

View File

@ -11,11 +11,17 @@ mod snippet;
mod tokenizer; mod tokenizer;
mod wrapper_functions; mod wrapper_functions;
/// SNP an utility to create and manage Snippets of code /// SNP an utility to create and manage Snippets of code
/// /// _
/// Use "snp -c -E snippet_name" to create a new Snippet and start editing it and "snp snippet_name argument" to use it /// Use "snp -c -E snippet_name" to create a new Snippet and
/// You can use "{}" or "{0}" in your Snippet to later format it to your needs as would python .format() or rust format!("",) work /// directly start editing it, then use"snp snippet_name" to use it.
/// Doing so will need as many default arguments to fill the command than the total count of {} /// You can use "{}" or "{0}" in your Snippet to later format it to
/// your needs as would python .format() or rust format!("",) work
/// Doing so will need as many default arguments to fill the command
/// than the total count of {}
/// -
/// You can get a working example with --example witch will guide you
/// through all the basic steps for snippet creation and edition
#[derive(Parser, Debug)] #[derive(Parser, Debug)]
#[command(author, version, about, verbatim_doc_comment)] #[command(author, version, about, verbatim_doc_comment)]
pub struct Cli { pub struct Cli {
@ -38,14 +44,13 @@ pub struct Cli {
/// Launch the editor and edit the whole snippet /// Launch the editor and edit the whole snippet
#[arg( #[arg(
short = 'E', short = 'E',
long = "Edit", long = "edit-all",
default_value_t = false, default_value_t = false,
requires = "mandatory" requires = "mandatory"
)] )]
edit_all: bool, edit_all: bool,
/// The list of arguments to give to the snippet /// The list of arguments to give to the snippet or the snippet creator
/// if the -c flag is used, it's used to create the default arguments
#[arg(requires = "mandatory")] #[arg(requires = "mandatory")]
args: Vec<String>, args: Vec<String>,
@ -64,6 +69,10 @@ pub struct Cli {
/// List all snippets in the snippet folder /// List all snippets in the snippet folder
#[arg(short, long, default_value_t = false, group = "mutex")] #[arg(short, long, default_value_t = false, group = "mutex")]
list: bool, list: bool,
/// Create an example snippet named example with some basic documentation
#[arg(long, default_value_t = false, group = "mutex")]
example: bool,
} }
/// Main entry point, everything is defered for testing and coverage /// Main entry point, everything is defered for testing and coverage

View File

@ -3,11 +3,12 @@
//! All functions included should either take a Cli object and return a SnippetError //! All functions included should either take a Cli object and return a SnippetError
//! or be a helper function for such a function //! or be a helper function for such a function
use clap::CommandFactory;
#[allow(unused)] // Mandatory because of how test and rust-analyser work #[allow(unused)] // Mandatory because of how test and rust-analyser work
use edit::edit; use edit::edit;
use std::fs::{self, create_dir_all}; use std::fs::{self, create_dir_all};
use std::io::{read_to_string, Write}; use std::io::{self, read_to_string, Write};
use std::{env, fs::File, path::PathBuf}; use std::{env, fs::File, path::PathBuf};
use crate::errors::SnippetError; use crate::errors::SnippetError;
@ -21,7 +22,11 @@ pub fn locate_snippet(cli: &Cli) -> Result<(), SnippetError> {
let status = check_dir_and_open(cli.snippet.as_ref().unwrap())?; let status = check_dir_and_open(cli.snippet.as_ref().unwrap())?;
match status { match status {
FileStatus::Opened((p, _)) => { FileStatus::Opened((p, _)) => {
println!("{:?}", p.as_os_str()); println!(
"The snippet {} is located at \"{}\"",
cli.snippet.as_ref().unwrap(),
p.as_os_str().to_str().unwrap()
);
Ok(()) Ok(())
} }
FileStatus::NotFound(p) => Err(SnippetError::NotFoundNoRetryError(p)), FileStatus::NotFound(p) => Err(SnippetError::NotFoundNoRetryError(p)),
@ -50,7 +55,10 @@ pub fn create_snippet(cli: &Cli) -> Result<(), SnippetError> {
FileStatus::NotFound(p) => (File::create(&p)?, p), // Create a new snippet FileStatus::NotFound(p) => (File::create(&p)?, p), // Create a new snippet
}; };
snp.save_in(&f)?; snp.save_in(&f)?;
println!("The snippet {:?} was created successfully", p); println!(
"The snippet {} was created successfully",
p.as_os_str().to_str().unwrap()
);
Ok(()) Ok(())
} }
@ -59,6 +67,7 @@ pub fn rename_snippet(cli: &Cli) -> Result<(), SnippetError> {
// Check wether the snippet exitsts // Check wether the snippet exitsts
let new_name = cli.rename.as_ref().unwrap(); let new_name = cli.rename.as_ref().unwrap();
if new_name == cli.snippet.as_ref().unwrap() { if new_name == cli.snippet.as_ref().unwrap() {
println!("The original and new snippet name are the same, skipping...");
return Ok(()); // The noop is a success ? return Ok(()); // The noop is a success ?
} }
let (f, oldpath) = match check_dir_and_open(cli.snippet.as_ref().unwrap())? { let (f, oldpath) = match check_dir_and_open(cli.snippet.as_ref().unwrap())? {
@ -122,8 +131,8 @@ pub fn edit_snippet(cli: &Cli) -> Result<(), SnippetError> {
snp.write_over(&p)?; snp.write_over(&p)?;
println!( println!(
"The snippet {:?} was succesfully saved", "The snippet {} was succesfully saved",
p.file_name().unwrap() p.file_name().unwrap().to_str().unwrap()
); );
Ok(()) Ok(())
} }
@ -159,8 +168,8 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> {
// No renaming has occured, the file can safely be overriten // No renaming has occured, the file can safely be overriten
snp.write_over(&origin_p)?; snp.write_over(&origin_p)?;
println!( println!(
"The snippet {:?} was succesfully saved", "The snippet {} was succesfully saved",
origin_p.file_name().unwrap() origin_p.file_name().unwrap().to_str().unwrap()
); );
Ok(()) Ok(())
} else { } else {
@ -181,7 +190,10 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> {
FileStatus::NotFound(p) => (File::create(&p)?, p), FileStatus::NotFound(p) => (File::create(&p)?, p),
}; };
snp.save_in(&dest_f)?; snp.save_in(&dest_f)?;
println!("The snippet was successfuly saved in {:?}", dest_p); println!(
"The snippet was successfuly saved in {}",
dest_p.into_os_string().to_str().unwrap()
);
Ok(()) Ok(())
} }
} }
@ -193,8 +205,8 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> {
write!(failover, "{}", &buf)?; write!(failover, "{}", &buf)?;
println!( println!(
"The snippet was saved under {:?} in your config", "The snippet was saved under {} in your config",
origin_p.file_name().unwrap() origin_p.file_name().unwrap().to_str().unwrap()
); );
Err(SnippetError::ReparsingError) Err(SnippetError::ReparsingError)
} }
@ -224,7 +236,14 @@ pub fn list_snippets(_cli: &Cli) -> Result<(), SnippetError> {
/// Print the snippet to stdout /// Print the snippet to stdout
pub fn print_snippet(cli: &Cli) -> Result<(), SnippetError> { pub fn print_snippet(cli: &Cli) -> Result<(), SnippetError> {
// Try to load the snippet <name> // Try to load the snippet <name>i
if cli.snippet.is_none() {
// This wonky hack exists because of subcommands
// It could also be checked when populating, but is way easier this
#[cfg(not(feature = "test"))]
Cli::command().print_long_help()?;
return Ok(());
}
let (_, f) = match check_dir_and_open(cli.snippet.as_ref().unwrap())? { let (_, f) = match check_dir_and_open(cli.snippet.as_ref().unwrap())? {
FileStatus::Opened((p, f)) => (p, f), FileStatus::Opened((p, f)) => (p, f),
FileStatus::NotFound(p) => return Err(SnippetError::NotFound(p)), FileStatus::NotFound(p) => return Err(SnippetError::NotFound(p)),
@ -238,7 +257,8 @@ pub fn print_snippet(cli: &Cli) -> Result<(), SnippetError> {
// Print the snippet // Print the snippet
let f_str = dynamic_formatter::dynamic_format(&snp.content, final_args)?; let f_str = dynamic_formatter::dynamic_format(&snp.content, final_args)?;
println!("{}", f_str); print!("{}", f_str);
io::stdout().flush()?;
Ok(()) Ok(())
} }
@ -246,7 +266,54 @@ pub fn print_snippet(cli: &Cli) -> Result<(), SnippetError> {
pub fn delete_snippet(cli: &Cli) -> Result<(), SnippetError> { pub fn delete_snippet(cli: &Cli) -> Result<(), SnippetError> {
let mut path = config_folder()?; let mut path = config_folder()?;
path.push(format!("{}.yaml", cli.snippet.as_ref().unwrap())); path.push(format!("{}.yaml", cli.snippet.as_ref().unwrap()));
std::fs::remove_file(path)?; std::fs::remove_file(&path)?;
println!(
"The snippet \"{}\" was successfully deleted.",
// path.file_name().unwrap().to_str().unwrap()
cli.snippet.as_ref().unwrap()
);
Ok(())
}
/// Create an example snippet with a small guide and the next step printed out
pub fn create_example(_cli: &Cli) -> Result<(), SnippetError> {
let mut path = config_folder()?;
path.push("unique_example.yaml");
println!(
"The snippet unique_example was created. You can use the following command to launch an editor and begin editing the content of the example:
$ snp unique_example -e
Note that only the content of the text is editable in this mode, to edit the whole snippet use:
$ snp unique_example -E
Once you are done with the editing, you can try using the snippet with:
$ snp unique_example
or
$ snp unique_example random parameters separated by spaces
If you wish to delete the snippet, you can use the following command:
$ snp -d unique_example"
);
let arguments = vec!["Argument 1", "Argument 2", "Foo", "Bar"];
let text = "This is a snippet created as an example.
You can type several lines of code to help you in your daily coding process.
This snippet manager accepts either {} as a argument placeholder
and will fill it with every subsequent argument provided.
You can also write {0}, {3}, etc. to use a specific argument
instead of using them in order.
To edit only this text and not the whole code, you can use
`snp unique_example -e` and to edit all parameters
(name, default arguments and content) use -E or --edit-all.
Please consult the --help for the full list of commands !";
let snp = Snippet::new(
"unique_example".to_string(),
arguments.iter().map(|s| s.to_string()).collect(),
text.to_string(),
);
_ = std::fs::remove_file(&path);
let f = File::create(path)?;
snp.save_in(&f)?;
Ok(()) Ok(())
} }
/// The status of the request after the path was attempted to be opened /// The status of the request after the path was attempted to be opened