Adds test for locate

This commit is contained in:
Dandaedre 2023-05-21 16:31:00 +02:00
parent 3304ba34d8
commit dd802cdcbc
4 changed files with 94 additions and 6 deletions

10
Makefile.toml Normal file
View File

@ -0,0 +1,10 @@
[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",
"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/",
]

View File

@ -22,6 +22,7 @@
[ ] Change all uncatchables errors to expect to be more helpful or change them to better errors
### Currently working on
[ ] Proceed one by one and catch errors
[ ] Remake all helper functions
[*] locate_snippet
[*] create_snippet

View File

@ -1,6 +1,6 @@
//! A general error module for the snp program
use std::{error, fmt};
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
@ -18,10 +18,10 @@ pub enum SnippetError {
YAMLError(serde_yaml::Error),
/// The file already exists and no creation flag was set
ExistsError(std::io::Error),
/// The file doen't exist and no creation was asked
NotFoundNoRetryError(PathBuf),
}
#[derive(Debug)]
struct PlaceHolder {}
impl fmt::Display for SnippetError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
@ -35,6 +35,13 @@ impl fmt::Display for SnippetError {
f,
"The file already exists. Use -c or -f to create it or force overwrite."
),
SnippetError::NotFoundNoRetryError(ref p) => {
write!(
f,
"The config {:?} doen't exists. Use -c to create it.",
p.file_name(),
)
}
}
}
}
@ -50,6 +57,7 @@ impl error::Error for SnippetError {
SnippetError::IOError(ref e) => Some(e),
SnippetError::YAMLError(ref e) => Some(e),
SnippetError::ExistsError(ref e) => Some(e),
SnippetError::NotFoundNoRetryError(_) => None,
}
}
}

View File

@ -3,6 +3,7 @@
//! All functions included should either take a Cli object and return a SnippetError
//! or be a helper function for such a function
use std::fs::create_dir_all;
use std::{env, fs::File, io::Read, path::PathBuf};
use edit::edit;
@ -14,8 +15,14 @@ use crate::{dynamic_formatter::complete_vec, errors::SnippetError, snippet::Snip
///
/// Will error on snippet not existing
pub fn locate_snippet(cli: &Cli) -> Result<(), SnippetError> {
println!("{}", snippet_path(&cli.snippet)?.to_string_lossy());
Ok(())
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)),
}
}
// /// Print the path of the current snippet
@ -60,7 +67,7 @@ pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> {
// Find location
let path = snippet_path(&cli.snippet)?;
// Edit the whole file as str
let mut f = std::fs::File::open(&path)?; //.expect("Could not open snippet file.");
let mut f = std::fs::File::open(path)?;
let mut raw_snippet = String::from("");
f.read_to_string(&mut raw_snippet)?;
let edited_str = edit(raw_snippet)?;
@ -152,6 +159,30 @@ pub fn print_snippet(args: &Cli) -> Result<(), SnippetError> {
// Ok(file)
// }
/// 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()?;
@ -163,8 +194,46 @@ pub fn config_folder() -> Result<PathBuf, SnippetError> {
}
/// 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)
}
#[cfg(test)]
mod test {
use std::io::Write;
use clap::Parser;
use super::*;
#[test]
fn test_config_creation() {
// Try to locate where to set the config
let _ = match check_dir_and_open("test_config_creation").expect("Can't open config") {
FileStatus::Opened((_, f)) => f,
FileStatus::NotFound(p) => File::create(p).expect("Can't create path"),
};
}
#[test]
fn test_locate() {
// Try to locate an unexisting snippet
let theorical_path = snippet_path("test_locate").expect("Can't find config path");
if let Err(e) = std::fs::remove_file(&theorical_path) {
println!("[Info] File didn't exist {:?}", e);
}
// Locating the snippet should fail
assert!(locate_snippet(&Cli::parse_from(vec!["-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(&Cli::parse_from(vec!["-l", "test_locate"])).is_ok());
}
}