Compare commits
No commits in common. "main" and "1.0.2" have entirely different histories.
|
|
@ -1,7 +1,7 @@
|
||||||
[package]
|
[package]
|
||||||
name = "snp"
|
name = "snp"
|
||||||
authors = ["Dandaedre"]
|
authors = ["Dandaedre"]
|
||||||
version = "1.0.6"
|
version = "1.0.1"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
|
|
|
||||||
35
TODO.md
35
TODO.md
|
|
@ -1,23 +1,38 @@
|
||||||
## 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
|
|
||||||
[ ] Case sensitivity windows
|
|
||||||
[ ] Use Ok for results instead of prints
|
|
||||||
[ ] 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
|
[*] 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
|
||||||
|
[*] rename_snippet
|
||||||
|
[*] Finish tests on
|
||||||
|
[*] locate_snippet
|
||||||
|
[*] create_snippet
|
||||||
|
[*] edit_snippet
|
||||||
|
[*] edit_whole_snippet
|
||||||
|
[*] print_snippet
|
||||||
|
[*] delete snippet
|
||||||
|
[*] rename snippet
|
||||||
|
[*] Have identical attributes with {0} {1} {0} (^^^^^)
|
||||||
|
[*] Add an option to delete a snippet
|
||||||
|
[*] Coverage
|
||||||
|
[*] Test populate_actions
|
||||||
|
[*] Have the the EditWhole save under a different path if name was changed (and edit too)
|
||||||
|
|
||||||
## 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 ?
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,8 @@
|
||||||
//! The action module, including all the logic to jump to a specific action
|
//! The action module, including all the logic to jump to a specific action
|
||||||
//! depending on the CLI arguments
|
//! depending on the CLI arguments
|
||||||
|
|
||||||
|
use std::error::Error;
|
||||||
|
|
||||||
use crate::{errors, wrapper_functions, Cli};
|
use crate::{errors, wrapper_functions, Cli};
|
||||||
|
|
||||||
/// List of all possible actions, some are mutually exclusive
|
/// List of all possible actions, some are mutually exclusive
|
||||||
|
|
@ -11,8 +13,8 @@ pub enum Actions {
|
||||||
Edit,
|
Edit,
|
||||||
/// Edit the whole snippet
|
/// Edit the whole snippet
|
||||||
EditAll,
|
EditAll,
|
||||||
/// List all snippets
|
/// Locate the snippet and show the position
|
||||||
List,
|
Locate,
|
||||||
/// Show the snippet (with replacement done)
|
/// Show the snippet (with replacement done)
|
||||||
Show,
|
Show,
|
||||||
/// Create the snippet with the given name and arguments
|
/// Create the snippet with the given name and arguments
|
||||||
|
|
@ -21,10 +23,6 @@ pub enum Actions {
|
||||||
Delete,
|
Delete,
|
||||||
/// Renames the snippet
|
/// Renames the snippet
|
||||||
Rename,
|
Rename,
|
||||||
/// Find a snippet matching a name/regex
|
|
||||||
Find,
|
|
||||||
/// Create an example snippet
|
|
||||||
Example,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The main worker, execute all commands given as Args
|
/// The main worker, execute all commands given as Args
|
||||||
|
|
@ -32,21 +30,18 @@ pub fn execute_parsed_cli(cli: Cli) -> Result<(), errors::SnippetError> {
|
||||||
let list_actions = populate_actions(&cli);
|
let list_actions = populate_actions(&cli);
|
||||||
for action in list_actions.iter() {
|
for action in list_actions.iter() {
|
||||||
if let Err(e) = match action {
|
if let Err(e) = match action {
|
||||||
Actions::Find => wrapper_functions::locate_snippet(&cli),
|
Actions::Locate => wrapper_functions::locate_snippet(&cli),
|
||||||
Actions::Create => wrapper_functions::create_snippet(&cli),
|
Actions::Create => wrapper_functions::create_snippet(&cli),
|
||||||
Actions::Show => wrapper_functions::print_snippet(&cli),
|
Actions::Show => wrapper_functions::print_snippet(&cli),
|
||||||
Actions::Edit => wrapper_functions::edit_snippet(&cli),
|
Actions::Edit => wrapper_functions::edit_snippet(&cli),
|
||||||
Actions::EditAll => wrapper_functions::edit_whole_snippet(&cli),
|
Actions::EditAll => wrapper_functions::edit_whole_snippet(&cli),
|
||||||
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::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);
|
||||||
// }
|
}
|
||||||
_ = ""; // No op to calm clippy while I decide wether or not delete this
|
|
||||||
return Err(e);
|
return Err(e);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
@ -58,26 +53,22 @@ pub fn execute_parsed_cli(cli: Cli) -> Result<(), errors::SnippetError> {
|
||||||
fn populate_actions(cli: &Cli) -> Vec<Actions> {
|
fn populate_actions(cli: &Cli) -> Vec<Actions> {
|
||||||
let mut actions = Vec::new();
|
let mut actions = Vec::new();
|
||||||
match (
|
match (
|
||||||
cli.path,
|
cli.locate,
|
||||||
cli.create,
|
cli.create,
|
||||||
cli.edit,
|
cli.edit,
|
||||||
cli.edit_all,
|
cli.edit_all,
|
||||||
cli.delete,
|
cli.delete,
|
||||||
&cli.rename,
|
&cli.rename,
|
||||||
cli.list,
|
|
||||||
cli.example,
|
|
||||||
) {
|
) {
|
||||||
(true, _, _, _, false, _, false, false) => actions.push(Actions::Find),
|
(true, _, _, _, false, _) => actions.push(Actions::Locate),
|
||||||
(_, false, false, true, false, _, false, false) => actions.push(Actions::EditAll),
|
(_, false, false, true, false, _) => actions.push(Actions::EditAll),
|
||||||
(_, true, _, true, false, _, false, false) => actions.push(Actions::EditAll),
|
(_, true, _, true, false, _) => actions.push(Actions::EditAll),
|
||||||
(_, true, false, false, false, _, false, false) => actions.push(Actions::Create),
|
(_, true, false, false, false, _) => actions.push(Actions::Create),
|
||||||
(_, false, true, _, false, _, false, false) => actions.push(Actions::Edit),
|
(_, false, true, _, false, _) => actions.push(Actions::Edit),
|
||||||
(_, true, true, false, false, _, false, false) => actions.push(Actions::Edit),
|
(_, true, true, false, false, _) => actions.push(Actions::Edit),
|
||||||
(false, false, false, false, false, None, false, false) => actions.push(Actions::Show),
|
(false, false, false, false, false, None) => actions.push(Actions::Show),
|
||||||
(_, _, _, _, true, _, false, false) => actions.push(Actions::Delete),
|
(_, _, _, _, true, _) => actions.push(Actions::Delete),
|
||||||
(_, _, _, _, _, Some(_), false, false) => actions.push(Actions::Rename),
|
(_, _, _, _, _, Some(_)) => actions.push(Actions::Rename),
|
||||||
(_, _, _, _, _, _, true, false) => actions.push(Actions::List),
|
|
||||||
(_, _, _, _, _, _, _, true) => actions.push(Actions::Example),
|
|
||||||
}
|
}
|
||||||
actions
|
actions
|
||||||
}
|
}
|
||||||
|
|
@ -99,19 +90,18 @@ mod test {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// #[ignore]
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_populate_actions() {
|
fn test_populate_actions() {
|
||||||
// false_cli!("snp", "name", "-p"), Actions::Locate
|
// false_cli!("snp", "name", "-l"), Actions::Locate
|
||||||
let group = group_actions!(
|
let group = group_actions!(
|
||||||
(
|
(
|
||||||
false_cli!("snp", "name", "-p", "-c", "-e", "-E"),
|
false_cli!("snp", "name", "-l", "-c", "-e", "-E"),
|
||||||
vec![Actions::Find]
|
vec![Actions::Locate]
|
||||||
),
|
),
|
||||||
(false_cli!("snp", "name", "-p"), vec![Actions::Find]),
|
(false_cli!("snp", "name", "-l"), vec![Actions::Locate]),
|
||||||
(false_cli!("snp", "name", "-d"), vec![Actions::Delete]),
|
(false_cli!("snp", "name", "-d"), vec![Actions::Delete]),
|
||||||
(
|
(
|
||||||
false_cli!("snp", "name", "-d", "-e", "e", "-E", "-p"),
|
false_cli!("snp", "name", "-d", "-e", "e", "-E", "-l"),
|
||||||
vec![Actions::Delete]
|
vec![Actions::Delete]
|
||||||
),
|
),
|
||||||
(false_cli!("snp", "name", "-E"), vec![Actions::EditAll]),
|
(false_cli!("snp", "name", "-E"), vec![Actions::EditAll]),
|
||||||
|
|
@ -122,12 +112,12 @@ mod test {
|
||||||
),
|
),
|
||||||
(false_cli!("snp", "name", "-e"), vec![Actions::Edit]),
|
(false_cli!("snp", "name", "-e"), vec![Actions::Edit]),
|
||||||
(false_cli!("snp", "name", "-e", "-c"), vec![Actions::Edit]),
|
(false_cli!("snp", "name", "-e", "-c"), vec![Actions::Edit]),
|
||||||
(false_cli!("snp", "name", "-p"), vec![Actions::Find]),
|
(false_cli!("snp", "name", "-l"), vec![Actions::Locate]),
|
||||||
(false_cli!("snp", "name", "-c"), vec![Actions::Create]),
|
(false_cli!("snp", "name", "-c"), vec![Actions::Create]),
|
||||||
(false_cli!("snp", "name"), vec![Actions::Show]),
|
(false_cli!("snp", "name"), vec![Actions::Show]),
|
||||||
(false_cli!("snp", "name", "-d"), vec![Actions::Delete]),
|
(false_cli!("snp", "name", "-d"), vec![Actions::Delete]),
|
||||||
(
|
(
|
||||||
false_cli!("snp", "name", "-d", "-c", "-E", "-e", "-p"),
|
false_cli!("snp", "name", "-d", "-c", "-E", "-e", "-l"),
|
||||||
vec![Actions::Delete]
|
vec![Actions::Delete]
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
|
|
@ -142,10 +132,6 @@ mod test {
|
||||||
false_cli!("snp", "name", "-c", "-r", "new_name", "-f"),
|
false_cli!("snp", "name", "-c", "-r", "new_name", "-f"),
|
||||||
vec![Actions::Create]
|
vec![Actions::Create]
|
||||||
),
|
),
|
||||||
(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);
|
||||||
|
|
@ -154,10 +140,8 @@ mod test {
|
||||||
assert!(res.iter().zip(fnd).all(|(a, b)| *a == b));
|
assert!(res.iter().zip(fnd).all(|(a, b)| *a == b));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_execute_parsed_cli() {
|
fn test_execute_parsed_cli() {
|
||||||
// println!("Executing test for cli");
|
|
||||||
let list_cli = vec![
|
let list_cli = vec![
|
||||||
false_cli!("snp", "parsed_cli", "-e", "-c"),
|
false_cli!("snp", "parsed_cli", "-e", "-c"),
|
||||||
false_cli!("snp", "parsed_cli", "-c", "-f"),
|
false_cli!("snp", "parsed_cli", "-c", "-f"),
|
||||||
|
|
@ -167,13 +151,10 @@ mod test {
|
||||||
false_cli!("snp", "parsed_cli", "-c"),
|
false_cli!("snp", "parsed_cli", "-c"),
|
||||||
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"),
|
|
||||||
false_cli!("snp", "--example"),
|
|
||||||
];
|
];
|
||||||
|
|
||||||
let bad_cli = vec![
|
let bad_cli = vec![
|
||||||
false_cli!("snp", "parsed_cli_bad", "-p"),
|
false_cli!("snp", "parsed_cli_bad", "-l"),
|
||||||
false_cli!("snp", "-d", "parsed_cli_bad"),
|
false_cli!("snp", "-d", "parsed_cli_bad"),
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -31,30 +31,30 @@ pub enum SnippetError {
|
||||||
impl fmt::Display for SnippetError {
|
impl fmt::Display for SnippetError {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
match *self {
|
match *self {
|
||||||
SnippetError::Unknown => write!(f, "An unknonw error occured."),
|
SnippetError::Unknown => write!(f, "An unknonw error occured"),
|
||||||
SnippetError::ClapError(..) => write!(f, "An error occured while parsing the input."),
|
SnippetError::ClapError(..) => write!(f, "An error occured while parsing the input"),
|
||||||
SnippetError::IOError(..) => write!(f, "An error occured while editing the file."),
|
SnippetError::IOError(..) => write!(f, "An error occured while editing the file"),
|
||||||
SnippetError::YAMLError(..) => {
|
SnippetError::YAMLError(..) => {
|
||||||
write!(f, "Couldn't convert the given arguments into a yaml.")
|
write!(f, "Couldn't convert the given arguments into a yaml")
|
||||||
}
|
}
|
||||||
SnippetError::NotFound(ref p) => write!(
|
SnippetError::NotFound(ref p) => write!(
|
||||||
f,
|
f,
|
||||||
"The Snippet {} doesn't exists. Use -c to create it and/or -E to edit it.",p.file_name().unwrap().to_str().unwrap(),
|
"The file {:?} doesn't exists",p.file_name().unwrap(),
|
||||||
),
|
),
|
||||||
SnippetError::NotFoundNoRetryError(ref p) => {
|
SnippetError::NotFoundNoRetryError(ref p) => {
|
||||||
write!(
|
write!(
|
||||||
f,
|
f,
|
||||||
"The Snippet {} doen't exists. Use -c to create it.",
|
"The config {:?} doen't exists. Use -c to create it.",
|
||||||
p.file_name().unwrap().to_str().unwrap(),
|
p.file_name(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
SnippetError::FoundNoEraseError(ref p) => write!(
|
SnippetError::FoundNoEraseError(ref p) => write!(
|
||||||
f,
|
f,
|
||||||
"The Snippet {} already exists. Use -f/--force to overwrite it.",
|
"The snippet {:?} already exists. Use -f/--force to overwrite it.",
|
||||||
p.file_name().unwrap().to_str().unwrap(),
|
p.file_name().unwrap(),
|
||||||
),
|
),
|
||||||
SnippetError::ReparsingError => write!(f,"The Snippet 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 {} arguments.",i,i+1),
|
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 {} arguments",i,i+1),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
79
src/main.rs
79
src/main.rs
|
|
@ -11,68 +11,46 @@ mod snippet;
|
||||||
mod tokenizer;
|
mod tokenizer;
|
||||||
mod wrapper_functions;
|
mod wrapper_functions;
|
||||||
|
|
||||||
/// SNP an utility to create and manage Snippets of code
|
/// The cli arguments to give to the utility
|
||||||
/// _
|
|
||||||
/// Use "snp -c -E snippet_name" to create a new Snippet and
|
|
||||||
/// directly start editing it, then use"snp snippet_name" to use it.
|
|
||||||
/// 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)]
|
||||||
pub struct Cli {
|
pub struct Cli {
|
||||||
/// The Snippet name (and therefore his path)
|
/// The snippet name (and therefore his path)
|
||||||
#[arg(group = "mandatory", group = "mutex")]
|
#[arg()]
|
||||||
snippet: Option<String>,
|
snippet: String,
|
||||||
|
|
||||||
/// Try to create a Snippet with the given name and default arguments
|
/// Wether to try to load or instead create a new one
|
||||||
#[arg(short, long, default_value_t = false, requires = "mandatory")]
|
#[arg(short, long, default_value_t = false)]
|
||||||
create: bool,
|
create: bool,
|
||||||
|
|
||||||
/// Find the path of the snippet with the given name
|
/// Show where the snippet is located
|
||||||
#[arg(short, long, default_value_t = false, requires = "mandatory")]
|
#[arg(short, long, default_value_t = false)]
|
||||||
path: bool,
|
locate: bool,
|
||||||
|
|
||||||
/// Launch the editor and edit the Snippet content
|
/// Launch the editor and edit the snippet
|
||||||
#[arg(short, long, default_value_t = false, requires = "mandatory")]
|
#[arg(short, long, default_value_t = false)]
|
||||||
edit: bool,
|
edit: bool,
|
||||||
|
|
||||||
/// Launch the editor and edit the whole snippet
|
/// Launch the editor and edit the whole snippet
|
||||||
#[arg(
|
#[arg(short = 'E', long = "Edit", default_value_t = false)]
|
||||||
short = 'E',
|
|
||||||
long = "edit-all",
|
|
||||||
default_value_t = false,
|
|
||||||
requires = "mandatory"
|
|
||||||
)]
|
|
||||||
edit_all: bool,
|
edit_all: bool,
|
||||||
|
|
||||||
/// The list of arguments to give to the snippet or the snippet creator
|
/// The list of arguments to give to the snippet
|
||||||
#[arg(requires = "mandatory")]
|
/// 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>,
|
args: Vec<String>,
|
||||||
|
|
||||||
/// Force the creation/moving/renaming of a Snippet even if it mean overwriting an existing one
|
/// Wether to force the creation or save and overwrite existing data
|
||||||
#[arg(short, long, default_value_t = false, requires = "mandatory")]
|
#[arg(short, long, default_value_t = false)]
|
||||||
force: bool,
|
force: bool,
|
||||||
|
|
||||||
/// Delete a snippet, takes precedence over everything
|
/// Wether to delete a snippet, takes precedence over everything
|
||||||
#[arg(short, long, default_value_t = false, requires = "mandatory")]
|
#[arg(short, long, default_value_t = false)]
|
||||||
delete: bool,
|
delete: bool,
|
||||||
|
|
||||||
/// Try to rename the Snippet (Use -f if the destination name already exist)
|
/// Wether to rename the snippet
|
||||||
#[arg(short, long, requires = "mandatory")]
|
#[arg(short, long)]
|
||||||
rename: Option<String>,
|
rename: Option<String>,
|
||||||
|
|
||||||
/// List all snippets in the snippet folder
|
|
||||||
#[arg(short, long, default_value_t = false, group = "mutex")]
|
|
||||||
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
|
||||||
|
|
@ -80,16 +58,3 @@ fn main() -> Result<(), errors::SnippetError> {
|
||||||
let cli = Cli::parse();
|
let cli = Cli::parse();
|
||||||
actions::execute_parsed_cli(cli)
|
actions::execute_parsed_cli(cli)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod test {
|
|
||||||
use clap::CommandFactory;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_cli_main() {
|
|
||||||
let cmd = Cli::command_for_update();
|
|
||||||
cmd.debug_assert();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -3,12 +3,11 @@
|
||||||
//! 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::create_dir_all;
|
||||||
use std::io::{self, read_to_string, Write};
|
use std::io::{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;
|
||||||
|
|
@ -19,14 +18,10 @@ use crate::{dynamic_formatter, Cli};
|
||||||
///
|
///
|
||||||
/// Will error on snippet not existing
|
/// Will error on snippet not existing
|
||||||
pub fn locate_snippet(cli: &Cli) -> Result<(), SnippetError> {
|
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)?;
|
||||||
match status {
|
match status {
|
||||||
FileStatus::Opened((p, _)) => {
|
FileStatus::Opened((p, _)) => {
|
||||||
println!(
|
println!("{:?}", p.as_os_str());
|
||||||
"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)),
|
||||||
|
|
@ -36,12 +31,8 @@ pub fn locate_snippet(cli: &Cli) -> Result<(), SnippetError> {
|
||||||
/// Create a new snippet with the given cli args
|
/// Create a new snippet with the given cli args
|
||||||
pub fn create_snippet(cli: &Cli) -> Result<(), SnippetError> {
|
pub fn create_snippet(cli: &Cli) -> Result<(), SnippetError> {
|
||||||
// Create a snippet with the given data
|
// Create a snippet with the given data
|
||||||
let snp = Snippet::new(
|
let snp = Snippet::new(cli.snippet.clone(), cli.args.clone(), String::from(""));
|
||||||
cli.snippet.as_ref().unwrap().clone(),
|
let status = check_dir_and_open(&cli.snippet)?;
|
||||||
cli.args.clone(),
|
|
||||||
String::from(""),
|
|
||||||
);
|
|
||||||
let status = check_dir_and_open(cli.snippet.as_ref().unwrap())?;
|
|
||||||
let (f, p) = match status {
|
let (f, p) = match status {
|
||||||
FileStatus::Opened((p, _)) => {
|
FileStatus::Opened((p, _)) => {
|
||||||
if cli.force {
|
if cli.force {
|
||||||
|
|
@ -55,10 +46,7 @@ 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!(
|
println!("The snippet {:?} was created successfully", p);
|
||||||
"The snippet {} was created successfully",
|
|
||||||
p.as_os_str().to_str().unwrap()
|
|
||||||
);
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -66,11 +54,10 @@ pub fn create_snippet(cli: &Cli) -> Result<(), SnippetError> {
|
||||||
pub fn rename_snippet(cli: &Cli) -> Result<(), SnippetError> {
|
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 {
|
||||||
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)? {
|
||||||
FileStatus::Opened((p, f)) => (f, p),
|
FileStatus::Opened((p, f)) => (f, p),
|
||||||
FileStatus::NotFound(e) => return Err(SnippetError::NotFound(e)),
|
FileStatus::NotFound(e) => return Err(SnippetError::NotFound(e)),
|
||||||
};
|
};
|
||||||
|
|
@ -96,8 +83,7 @@ pub fn rename_snippet(cli: &Cli) -> Result<(), SnippetError> {
|
||||||
// Save snippet
|
// Save snippet
|
||||||
println!(
|
println!(
|
||||||
"The snippet {} was sucessfuly renamed as {}",
|
"The snippet {} was sucessfuly renamed as {}",
|
||||||
cli.snippet.as_ref().unwrap(),
|
cli.snippet, new_name
|
||||||
new_name
|
|
||||||
);
|
);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
@ -105,17 +91,13 @@ pub fn rename_snippet(cli: &Cli) -> Result<(), SnippetError> {
|
||||||
/// Open and load snippet and edit it
|
/// Open and load snippet and edit it
|
||||||
pub fn edit_snippet(cli: &Cli) -> Result<(), SnippetError> {
|
pub fn edit_snippet(cli: &Cli) -> Result<(), SnippetError> {
|
||||||
// Try loading, if not existant check if create or error
|
// Try loading, if not existant check if create or error
|
||||||
let status = check_dir_and_open(cli.snippet.as_ref().unwrap())?;
|
let status = check_dir_and_open(&cli.snippet)?;
|
||||||
let (mut snp, _, p) = match status {
|
let (mut snp, _, p) = match status {
|
||||||
FileStatus::Opened((p, f)) => (Snippet::from_file(&f)?, f, p),
|
FileStatus::Opened((p, f)) => (Snippet::from_file(&f)?, f, p),
|
||||||
FileStatus::NotFound(p) => {
|
FileStatus::NotFound(p) => {
|
||||||
if cli.create {
|
if cli.create {
|
||||||
(
|
(
|
||||||
Snippet::new(
|
Snippet::new(cli.snippet.clone(), cli.args.clone(), String::from("")),
|
||||||
cli.snippet.as_ref().unwrap().clone(),
|
|
||||||
cli.args.clone(),
|
|
||||||
String::from(""),
|
|
||||||
),
|
|
||||||
File::create(&p)?,
|
File::create(&p)?,
|
||||||
p,
|
p,
|
||||||
)
|
)
|
||||||
|
|
@ -131,8 +113,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().to_str().unwrap()
|
p.file_name().unwrap()
|
||||||
);
|
);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
@ -142,16 +124,13 @@ pub fn edit_snippet(cli: &Cli) -> Result<(), SnippetError> {
|
||||||
/// a creation or an override
|
/// a creation or an override
|
||||||
pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> {
|
pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> {
|
||||||
// Try loading the snippet
|
// Try loading the snippet
|
||||||
let status = check_dir_and_open(cli.snippet.as_ref().unwrap());
|
let status = check_dir_and_open(&cli.snippet);
|
||||||
let (buf, mut origin_p) = match status? {
|
let (buf, mut p) = match status? {
|
||||||
FileStatus::Opened((p, f)) => (read_to_string(f)?, p),
|
FileStatus::Opened((p, f)) => (read_to_string(f)?, p),
|
||||||
FileStatus::NotFound(p) => {
|
FileStatus::NotFound(p) => {
|
||||||
if cli.create {
|
if cli.create {
|
||||||
File::create(&p)?;
|
File::create(&p)?;
|
||||||
(
|
(Snippet::empty(cli.snippet.clone(), cli.args.clone()), p)
|
||||||
Snippet::empty(cli.snippet.clone().unwrap(), cli.args.clone()),
|
|
||||||
p,
|
|
||||||
)
|
|
||||||
} else {
|
} else {
|
||||||
return Err(SnippetError::NotFoundNoRetryError(p));
|
return Err(SnippetError::NotFoundNoRetryError(p));
|
||||||
}
|
}
|
||||||
|
|
@ -164,87 +143,78 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> {
|
||||||
// Try reparsing, on error no modifications will be made
|
// Try reparsing, on error no modifications will be made
|
||||||
match Snippet::from_string(&buf) {
|
match Snippet::from_string(&buf) {
|
||||||
Ok(snp) => {
|
Ok(snp) => {
|
||||||
if cli.snippet.as_ref().unwrap() == &snp.name {
|
if cli.snippet == snp.name {
|
||||||
// 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(&p)?;
|
||||||
println!(
|
println!(
|
||||||
"The snippet {} was succesfully saved",
|
"The snippet {:?} was succesfully saved",
|
||||||
origin_p.file_name().unwrap().to_str().unwrap()
|
p.file_name().unwrap()
|
||||||
);
|
);
|
||||||
Ok(())
|
Ok(())
|
||||||
} else {
|
} else {
|
||||||
let (dest_f, dest_p) = match check_dir_and_open(&snp.name)? {
|
let (f, p) = match check_dir_and_open(&snp.name)? {
|
||||||
FileStatus::Opened((dest_p, _dest_f)) => {
|
FileStatus::Opened((p, f)) => {
|
||||||
if cli.force {
|
if cli.force {
|
||||||
// Erasing will take place
|
// Erasing will take place
|
||||||
(File::create(&dest_p)?, dest_p)
|
(File::create(&p)?, p)
|
||||||
} else {
|
} else {
|
||||||
// No erasing/overriting
|
// No erasing/overriting
|
||||||
println!(
|
println!(
|
||||||
"The snippet could not be saved as {}.yaml, as this Snippet already exists. The Snippet will be saved under it's original name name: {}",
|
"Impossible to save the snippet as {:}, as it already exists. The snippet will be saved under it's old name.",
|
||||||
snp.name,origin_p.file_name().unwrap().to_str().unwrap()
|
snp.name
|
||||||
);
|
);
|
||||||
(File::create(&origin_p)?, origin_p)
|
(f, p)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
FileStatus::NotFound(p) => (File::create(&p)?, p),
|
FileStatus::NotFound(p) => (File::create(&p)?, p),
|
||||||
};
|
};
|
||||||
snp.save_in(&dest_f)?;
|
snp.save_in(&f)?;
|
||||||
println!(
|
println!("The snippet was successfuly saved in {:?}", p);
|
||||||
"The snippet was successfuly saved in {}",
|
|
||||||
dest_p.into_os_string().to_str().unwrap()
|
|
||||||
);
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
// The snippet is incorrect, however it should still be saved, just under another name ?
|
// The snippet is incorrect, however it should still be saved, just under another name ?
|
||||||
origin_p.set_extension("bad.yaml");
|
p.set_extension("bad.yaml");
|
||||||
let mut failover = File::create(&origin_p)?;
|
let mut failover = File::create(&p)?;
|
||||||
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().to_str().unwrap()
|
p.file_name().unwrap()
|
||||||
);
|
);
|
||||||
Err(SnippetError::ReparsingError)
|
Err(SnippetError::ReparsingError)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// List all snippets in the snippet config directory
|
|
||||||
pub fn list_snippets(_cli: &Cli) -> Result<(), SnippetError> {
|
// This code is used to check if the name changed but should be moved to a separate function
|
||||||
let dirpath = config_folder()?;
|
// let old_name = snp.name.clone();
|
||||||
let paths = fs::read_dir(&dirpath).unwrap();
|
// // During tests, the editor cannot be tested
|
||||||
println!(
|
// #[cfg(not(feature = "test"))]
|
||||||
"Snippet list at {}:\n {}",
|
// snp.edit()?;
|
||||||
dirpath.parent().unwrap().to_str().unwrap(),
|
|
||||||
paths
|
// if snp.name == old_name {
|
||||||
.map(|p| p
|
// snp.write_over(&p)
|
||||||
.unwrap()
|
// } else {
|
||||||
.path()
|
// match check_dir_and_open(&snp.name)? {
|
||||||
.file_name()
|
// FileStatus::Opened((p, _f)) => {
|
||||||
.unwrap()
|
// if cli.force {
|
||||||
.to_str()
|
// std::fs::remove_file(&p)?;
|
||||||
.unwrap()
|
// snp.write_over(&p)
|
||||||
.to_owned())
|
// } else {
|
||||||
.collect::<Vec<String>>()
|
// Err(SnippetError::NotFoundNoRetryError(p))
|
||||||
.join(", ")
|
// }
|
||||||
);
|
// }
|
||||||
Ok(())
|
// FileStatus::NotFound(p) => snp.write_over(&p),
|
||||||
}
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
/// 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>i
|
// Try to load the snippet <name>
|
||||||
if cli.snippet.is_none() {
|
let (_, f) = match check_dir_and_open(&cli.snippet)? {
|
||||||
// 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())? {
|
|
||||||
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)),
|
||||||
};
|
};
|
||||||
|
|
@ -257,63 +227,15 @@ 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)?;
|
||||||
|
|
||||||
print!("{}", f_str);
|
println!("{}", f_str);
|
||||||
io::stdout().flush()?;
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Delete a given snippet, errors if the snippet doesn't exists
|
/// Delete a given snippet, errors if the snippet doesn't exists
|
||||||
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));
|
||||||
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
|
||||||
|
|
@ -387,7 +309,6 @@ pub mod test {
|
||||||
assert!(delete_snippet(false_cli!("snp", "-d", "delete_snippet")).is_ok());
|
assert!(delete_snippet(false_cli!("snp", "-d", "delete_snippet")).is_ok());
|
||||||
}
|
}
|
||||||
|
|
||||||
// #[ignore]
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_locate() {
|
fn test_locate() {
|
||||||
// Try to locate an unexisting snippet
|
// Try to locate an unexisting snippet
|
||||||
|
|
@ -395,14 +316,14 @@ pub mod test {
|
||||||
_ = std::fs::remove_file(&theorical_path);
|
_ = std::fs::remove_file(&theorical_path);
|
||||||
|
|
||||||
// Locating the snippet should fail
|
// Locating the snippet should fail
|
||||||
assert!(locate_snippet(false_cli!("snp", "-f", "test_locate")).is_err());
|
assert!(locate_snippet(false_cli!("-l", "test_locate")).is_err());
|
||||||
|
|
||||||
let mut f = File::create(&theorical_path).expect("Couldn't create file");
|
let mut f = File::create(&theorical_path).expect("Couldn't create file");
|
||||||
write!(f, "N").expect("Couldn't write on the new file");
|
write!(f, "N").expect("Couldn't write on the new file");
|
||||||
f.sync_data().expect("Can't sync file");
|
f.sync_data().expect("Can't sync file");
|
||||||
|
|
||||||
// Locating the snippet should now suceed
|
// Locating the snippet should now suceed
|
||||||
assert!(locate_snippet(false_cli!("-f", "test_locate")).is_ok());
|
assert!(locate_snippet(false_cli!("-l", "test_locate")).is_ok());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -414,59 +335,57 @@ pub mod test {
|
||||||
assert!(print_snippet(false_cli!("snp", "test_print")).is_err());
|
assert!(print_snippet(false_cli!("snp", "test_print")).is_err());
|
||||||
|
|
||||||
// Create snippet
|
// Create snippet
|
||||||
assert!(create_snippet(false_cli!("snp", "-c", "test_print")).is_ok());
|
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!("snp", "test_print")).is_ok());
|
||||||
|
// assert!(print_snippet(false_cli!("-l", "test_print")).is_ok());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_create() {
|
fn test_create() {
|
||||||
_ = std::fs::remove_file(snippet_path("create_snippet").unwrap());
|
_ = std::fs::remove_file(snippet_path("create_snippet").unwrap());
|
||||||
// Test to create empty
|
// Test to create empty
|
||||||
assert!(create_snippet(false_cli!("snp", "-c", "create_snippet")).is_ok());
|
assert!(create_snippet(false_cli!("-c", "create_snippet")).is_ok());
|
||||||
|
|
||||||
// Test to create again
|
// Test to create again
|
||||||
assert!(create_snippet(false_cli!("snp", "-c", "create_snippet")).is_err());
|
assert!(create_snippet(false_cli!("-c", "create_snippet")).is_err());
|
||||||
|
|
||||||
// Test to create with force
|
// Test to create with force
|
||||||
assert!(create_snippet(false_cli!("snp", "-c", "-f", "create_snippet")).is_ok());
|
assert!(create_snippet(false_cli!("-c", "-f", "create_snippet")).is_ok());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_edit() {
|
fn test_edit() {
|
||||||
_ = std::fs::remove_file(snippet_path("edit_content").unwrap());
|
_ = std::fs::remove_file(snippet_path("edit_content").unwrap());
|
||||||
// Open unnexitant
|
// Open unnexitant
|
||||||
assert!(edit_snippet(false_cli!("snp", "-e", "edit_content")).is_err());
|
assert!(edit_snippet(false_cli!("-e", "edit_content")).is_err());
|
||||||
|
|
||||||
// Force creation
|
// Force creation
|
||||||
assert!(edit_snippet(false_cli!("snp", "-e", "-c", "edit_content")).is_ok());
|
assert!(edit_snippet(false_cli!("-e", "-c", "edit_content")).is_ok());
|
||||||
|
|
||||||
// Edit when created
|
// Edit when created
|
||||||
|
|
||||||
println!(
|
println!("{:?}", edit_snippet(false_cli!("-e", "edit_content")));
|
||||||
"{:?}",
|
assert!(edit_snippet(false_cli!("-e", "edit_content")).is_ok());
|
||||||
edit_snippet(false_cli!("snp", "-e", "edit_content"))
|
|
||||||
);
|
|
||||||
assert!(edit_snippet(false_cli!("snp", "-e", "edit_content")).is_ok());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_edit_whole() {
|
fn test_edit_whole() {
|
||||||
_ = std::fs::remove_file(snippet_path("edit_whole").unwrap());
|
_ = std::fs::remove_file(snippet_path("edit_whole").unwrap());
|
||||||
// Open unnexitant
|
// Open unnexitant
|
||||||
assert!(edit_whole_snippet(false_cli!("snp", "-E", "edit_whole")).is_err());
|
assert!(edit_whole_snippet(false_cli!("-E", "edit_whole")).is_err());
|
||||||
|
|
||||||
// Force creation
|
// Force creation
|
||||||
assert!(edit_whole_snippet(false_cli!("snp", "-E", "-c", "edit_whole")).is_ok());
|
assert!(edit_whole_snippet(false_cli!("-E", "-c", "edit_whole")).is_ok());
|
||||||
|
|
||||||
// Edit when created
|
// Edit when created
|
||||||
assert!(edit_whole_snippet(false_cli!("snp", "-E", "edit_whole")).is_ok());
|
assert!(edit_whole_snippet(false_cli!("-E", "edit_whole")).is_ok());
|
||||||
|
|
||||||
// Create a badly formatted file
|
// Create a badly formatted file
|
||||||
if let FileStatus::Opened((p, _)) = check_dir_and_open("edit_whole").unwrap() {
|
if let FileStatus::Opened((p, _)) = check_dir_and_open("edit_whole").unwrap() {
|
||||||
let mut f = File::create(p).unwrap();
|
let mut f = File::create(p).unwrap();
|
||||||
write!(f, "badly formatter yaml").unwrap();
|
write!(f, "badly formatter yaml").unwrap();
|
||||||
|
|
||||||
assert!(edit_whole_snippet(false_cli!("snp", "-E", "edit_whole")).is_err());
|
assert!(edit_whole_snippet(false_cli!("-E", "edit_whole")).is_err());
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
check_dir_and_open("edit_whole.bad").unwrap(),
|
check_dir_and_open("edit_whole.bad").unwrap(),
|
||||||
FileStatus::Opened(_)
|
FileStatus::Opened(_)
|
||||||
|
|
@ -482,7 +401,7 @@ pub mod test {
|
||||||
_ = std::fs::remove_file(&oldpath);
|
_ = std::fs::remove_file(&oldpath);
|
||||||
_ = std::fs::remove_file(&newpath);
|
_ = std::fs::remove_file(&newpath);
|
||||||
_ = std::fs::remove_file(filledpath);
|
_ = std::fs::remove_file(filledpath);
|
||||||
assert!(create_snippet(false_cli!("snp", "-c", "rename_snippet", "-f")).is_ok());
|
assert!(create_snippet(false_cli!("-c", "rename_snippet", "-f")).is_ok());
|
||||||
assert!(
|
assert!(
|
||||||
rename_snippet(false_cli!("snp", "-r", "renamed_snippet", "rename_snippet")).is_ok()
|
rename_snippet(false_cli!("snp", "-r", "renamed_snippet", "rename_snippet")).is_ok()
|
||||||
);
|
);
|
||||||
|
|
@ -492,8 +411,8 @@ pub mod test {
|
||||||
|
|
||||||
assert!(rename_snippet(false_cli!("snp", "-r", "non_ex", "non_ex")).is_ok());
|
assert!(rename_snippet(false_cli!("snp", "-r", "non_ex", "non_ex")).is_ok());
|
||||||
assert!(rename_snippet(false_cli!("snp", "-r", "non_ex", "renamed_snippet")).is_err());
|
assert!(rename_snippet(false_cli!("snp", "-r", "non_ex", "renamed_snippet")).is_err());
|
||||||
assert!(create_snippet(false_cli!("snp", "-c", "filled_destination", "-f")).is_ok());
|
assert!(create_snippet(false_cli!("-c", "filled_destination", "-f")).is_ok());
|
||||||
assert!(create_snippet(false_cli!("snp", "-c", "rename_snippet", "-f")).is_ok());
|
assert!(create_snippet(false_cli!("-c", "rename_snippet", "-f")).is_ok());
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
rename_snippet(false_cli!(
|
rename_snippet(false_cli!(
|
||||||
"snp",
|
"snp",
|
||||||
|
|
@ -531,8 +450,8 @@ pub mod test {
|
||||||
println!("Trying to resave without destination {:?}", res);
|
println!("Trying to resave without destination {:?}", res);
|
||||||
assert!(res.is_ok());
|
assert!(res.is_ok());
|
||||||
|
|
||||||
assert!(create_snippet(false_cli!("snp", "-c", "new_snippet")).is_err());
|
assert!(create_snippet(false_cli!("-c", "new_snippet")).is_err());
|
||||||
assert!(create_snippet(false_cli!("snp", "-c", "resave_snippet")).is_err());
|
assert!(create_snippet(false_cli!("-c", "resave_snippet")).is_err());
|
||||||
|
|
||||||
let res = edit_whole_snippet(false_cli!("snp", "resave_snippet", "-f"));
|
let res = edit_whole_snippet(false_cli!("snp", "resave_snippet", "-f"));
|
||||||
println!("Sucessfully erasing {:?}", res);
|
println!("Sucessfully erasing {:?}", res);
|
||||||
|
|
@ -540,7 +459,6 @@ pub mod test {
|
||||||
|
|
||||||
let res = edit_whole_snippet(false_cli!("snp", "resave_snippet"));
|
let res = edit_whole_snippet(false_cli!("snp", "resave_snippet"));
|
||||||
println!("Failing to overwrite {:?}", res);
|
println!("Failing to overwrite {:?}", res);
|
||||||
assert!(res.is_ok()); // The failure just means it wasn't overriten
|
assert!(res.is_err());
|
||||||
// TODO: Check no overwrite occurs
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Reference in New Issue