Adds basic coverage, corrects tests and correct bad function for Edit & edit

This commit is contained in:
Dandaedre 2023-05-22 03:08:12 +02:00
parent 6aa6a1ddd9
commit 92b3ccf730
8 changed files with 122 additions and 41 deletions

2
.gitignore vendored
View File

@ -19,3 +19,5 @@ Cargo.lock
# Added by cargo
/target
/coverage
/llvm

View File

@ -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/",
]

View File

@ -1,8 +1,8 @@
# 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 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

25
TODO.md
View File

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

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: 89%">
<title>coverage: 89%</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="#dfb317"/>
<rect width="96" height="20" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110">
<text aria-hidden="true" x="315" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="510">coverage</text>
<text x="315" y="140" transform="scale(.1)" fill="#fff" textLength="510">coverage</text>
<text aria-hidden="true" x="775" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">89%</text>
<text x="775" y="140" transform="scale(.1)" fill="#fff" textLength="250">89%</text>
</g>
<script xmlns=""/>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -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<Actions> {
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

View File

@ -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<Self, SnippetError> {
pub fn from_file(f: &File) -> Result<Self, SnippetError> {
let snp: Snippet = serde_yaml::from_reader(f)?;
Ok(snp)
}

View File

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