diff --git a/.gitignore b/.gitignore
index 193d30e..ecaefb4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -19,3 +19,5 @@ Cargo.lock
# Added by cargo
/target
+/coverage
+/llvm
\ No newline at end of file
diff --git a/Makefile.toml b/Makefile.toml
index 92d84ac..284b84b 100644
--- a/Makefile.toml
+++ b/Makefile.toml
@@ -5,6 +5,6 @@ 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",
-"grcov . --binary-path ./target/debug/deps/ -s . -t html --branch --ignore-not-existing --ignore '../*' --ignore '/*' --ignore '*xiv_csolver.rs' --ignore '*python*.rs' -o coverage/html/",
+"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 '*/errors.rs' -o coverage/html/",
]
\ No newline at end of file
diff --git a/README.md b/README.md
index 4d141db..87d90c2 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,8 @@
# snp
-
+
-A simple cli utility to manage snippets
+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
diff --git a/TODO.md b/TODO.md
index ed721db..39db303 100644
--- a/TODO.md
+++ b/TODO.md
@@ -9,19 +9,15 @@
## TODO
[ ] Make a lib for dynamic_format and snippets (impl make a trait for have .id() and other future t)
- [-] Make functions into methods
[-] Have identical attributes with {0} {1} {0} (^^^^^)
- [ ] Update tests
[ ] Benchmarks
[ ] Better modes
[ ] Test populate_actions
- [ ] Coverage
- [ ] Remake all Snippet methods
- [ ] save_as => save a snippet in a file desc
- [ ] Chain the methods when possible with result ?
[ ] Change all uncatchables errors to expect to be more helpful or change them to better errors
-
+ [ ] Document non coverage
+
### Currently working on
+ [-] Coverage
[ ] Proceed one by one and catch errors
[-] Remake all helper functions
[*] locate_snippet
@@ -30,14 +26,17 @@
[*] edit_whole_snippet
[x] print_snippet
[-] Finish tests on
- [ ] locate_snippet
- [ ] create_snippet
- [ ] edit_snippet
- [ ] edit_whole_snippet
- [ ] print_snippet
-
+ [*] locate_snippet
+ [*] create_snippet
+ [*] edit_snippet
+ [*] edit_whole_snippet
+ [x] print_snippet
+ [ ] Cargo test must always have the test feature
## Finished
[*] Make custom errors
[*] Transform all panic in errors
+ [*] Make functions into methods
+## Posponed or rendered useless
+ [x] Chain the methods when possible with result ?
diff --git a/coverage/html/badges/flat.svg b/coverage/html/badges/flat.svg
new file mode 100644
index 0000000..f4a8de8
--- /dev/null
+++ b/coverage/html/badges/flat.svg
@@ -0,0 +1,23 @@
+
\ No newline at end of file
diff --git a/src/main.rs b/src/main.rs
index 8d891db..e6cf156 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -3,6 +3,8 @@
#![warn(clippy::missing_docs_in_private_items, missing_docs)]
#![allow(clippy::result_unit_err)]
+use std::error::Error;
+
use clap::Parser;
mod dynamic_formatter;
mod errors;
@@ -59,18 +61,29 @@ pub enum Actions {
Create,
}
+/// Main entry point, everything is defered for testing and coverage
fn main() -> Result<(), errors::SnippetError> {
let cli = Cli::parse();
+ execute_parsed_cli(cli)
+}
+/// The main worker, execute all commands given as Args
+fn execute_parsed_cli(cli: Cli) -> Result<(), errors::SnippetError> {
let list_actions = populate_actions(&cli);
for action in list_actions.iter() {
- match action {
+ 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),
- }?;
+ } {
+ println!("An error occured during runtime {:?}", e);
+ if let Some(e) = e.source() {
+ println!("This error was caused by {:?}", e);
+ }
+ return Err(e);
+ };
}
Ok(())
}
@@ -81,11 +94,11 @@ fn populate_actions(cli: &Cli) -> Vec {
let mut actions = Vec::new();
match (cli.locate, cli.create, cli.edit, cli.edit_all) {
(true, _, _, _) => actions.push(Actions::Locate),
- (_, true, _, true) => actions.append(&mut vec![Actions::Create, Actions::EditAll]),
- (_, true, true, false) => actions.append(&mut vec![Actions::Create, Actions::Edit]),
+ (_, true, _, true) => actions.push(Actions::EditAll),
+ (_, true, true, false) => actions.push(Actions::Edit),
(_, true, false, false) => actions.push(Actions::Create),
- (_, false, true, _) => actions.push(Actions::EditAll),
- (_, false, false, true) => actions.push(Actions::Edit),
+ (_, false, true, _) => actions.push(Actions::Edit),
+ (_, false, false, true) => actions.push(Actions::EditAll),
(false, false, false, false) => (),
}
actions
diff --git a/src/snippet.rs b/src/snippet.rs
index 98b95c6..1e3046b 100644
--- a/src/snippet.rs
+++ b/src/snippet.rs
@@ -35,20 +35,19 @@ impl Snippet {
}
/// Save the snippet in a file, errors on write error
- pub fn save_in(&self, mut file: std::fs::File) -> Result<(), SnippetError> {
+ 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> {
- // #[cfg(not(test))]
self.content = edit::edit(self.content.clone())?;
Ok(())
}
/// Create snippet from file buffer (deserialize)
- pub fn from_file(f: File) -> Result {
+ pub fn from_file(f: &File) -> Result {
let snp: Snippet = serde_yaml::from_reader(f)?;
Ok(snp)
}
diff --git a/src/wrapper_functions.rs b/src/wrapper_functions.rs
index fca9069..139f282 100644
--- a/src/wrapper_functions.rs
+++ b/src/wrapper_functions.rs
@@ -5,7 +5,7 @@
use std::fs::create_dir_all;
use std::io::{read_to_string, Write};
-use std::{env, fs::File, io::Read, path::PathBuf};
+use std::{env, fs::File, path::PathBuf};
use edit::edit;
@@ -54,7 +54,7 @@ pub fn create_snippet(cli: &Cli) -> Result<(), SnippetError> {
}
FileStatus::NotFound(p) => File::create(p)?, // Create a new snippet
};
- snp.save_in(f)?;
+ snp.save_in(&f)?;
Ok(())
}
@@ -62,17 +62,30 @@ pub fn create_snippet(cli: &Cli) -> Result<(), SnippetError> {
pub fn edit_snippet(cli: &Cli) -> Result<(), SnippetError> {
// Try loading, if not existant check if create or error
let status = check_dir_and_open(&cli.snippet)?;
- let mut snp = match status {
- FileStatus::Opened((_, f)) => Snippet::from_file(f)?,
+ let (mut snp, f, p) = match status {
+ FileStatus::Opened((p, f)) => (Snippet::from_file(&f)?, f, p),
FileStatus::NotFound(p) => {
- if cli.force {
- Snippet::new(cli.snippet.clone(), cli.args.clone(), String::from(""))
+ 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(())
}
@@ -101,7 +114,7 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> {
// Try reparsing, on error no modifications will be made
match Snippet::from_string(&buf) {
Ok(snp) => {
- snp.write_over(&p)?;
+ 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()
@@ -124,6 +137,28 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> {
}
}
+// 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(args: &Cli) -> Result<(), SnippetError> {
// Try to load the snippet
@@ -246,20 +281,30 @@ mod test {
}
#[test]
- #[ignore]
fn test_edit() {
- // TODO: Finish this test
- // Test edit non existant
- // Test edit with create
- // Test
+ _ = 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());
- // Test to create empty
- assert!(edit_whole_snippet(false_cli!("-e", "-c", "edit_whole")).is_ok());
+ // Open unnexitant
+ assert!(edit_whole_snippet(false_cli!("-E", "edit_whole")).is_err());
- // TODO: Finish this test
+ // 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());
}
}