Adds support for test on editions, adds edit_whole

This commit is contained in:
Dandaedre 2023-05-21 23:36:22 +02:00
parent e1e46765a0
commit 6aa6a1ddd9
5 changed files with 106 additions and 85 deletions

View File

@ -3,6 +3,8 @@ name = "snp"
version = "0.1.0"
edition = "2021"
[features]
test = []
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

10
TODO.md
View File

@ -26,9 +26,15 @@
[-] Remake all helper functions
[*] locate_snippet
[*] create_snippet
[-] edit_snippet
[-] edit_whole_snippet
[*] edit_snippet
[*] edit_whole_snippet
[x] print_snippet
[-] Finish tests on
[ ] locate_snippet
[ ] create_snippet
[ ] edit_snippet
[ ] edit_whole_snippet
[ ] print_snippet
## Finished

View File

@ -22,8 +22,8 @@ pub enum SnippetError {
NotFoundNoRetryError(PathBuf),
/// The snippet was found but shouldn't be erased because of flags
FoundNoEraseError(PathBuf),
// /// An error occured while handling file operations
// FileError(std::fs::File)
/// The snippet couldn't be reparsed
ReparsingError,
}
impl fmt::Display for SnippetError {
@ -51,6 +51,7 @@ impl fmt::Display for SnippetError {
"The snippet {:?} already exists. Use -f/--force to overwrite it.",
p.file_name(),
),
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.")
}
}
}
@ -68,6 +69,7 @@ impl error::Error for SnippetError {
SnippetError::ExistsError(ref e) => Some(e),
SnippetError::NotFoundNoRetryError(_) => None,
SnippetError::FoundNoEraseError(_) => None,
SnippetError::ReparsingError => None,
}
}
}

View File

@ -6,11 +6,7 @@ use clap::error::Result;
use serde::{Deserialize, Serialize};
use std::{fs::File, io::Write};
use crate::{
errors::{self, SnippetError},
wrapper_functions::config_folder,
Cli,
};
use crate::errors::SnippetError;
/// A snippet ready to be Serialized/Deserialized
///
@ -38,44 +34,15 @@ impl Snippet {
}
}
// TODO: rewrite as a helper function
/// Save the snippet at the default location under it's name
pub fn save(&self, options: &Cli) -> Result<(), errors::SnippetError> {
// Try to open the feed
let mut file = self.open(options)?;
write!(file, "{}", serde_yaml::to_string(self)?)?;
Ok(())
}
/// Open the file, will create on empty
pub fn open(&self, options: &Cli) -> Result<File, SnippetError> {
// Find the config folder
let mut path = config_folder()?; //.expect("Coudn't open config forder");
// Add path
path.push(format!("{}.yaml", options.snippet));
// Open the file
let f = match std::fs::File::open(&path) {
Ok(f) => f,
Err(e) => {
if options.create {
File::create(path)?
} else {
return Err(SnippetError::IOError(e));
}
}
}; //.expect("Could not open snippet file.");
// let snp: Snippet = serde_yaml::from_reader(&f)?; //.expect("Couldn't parse values");
Ok(f)
}
/// Save the snippet under a path, errors on existing file
pub fn save_as(&self, mut file: std::fs::File) -> Result<(), SnippetError> {
/// Save the snippet in a file, errors on write error
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(())
}
@ -85,4 +52,28 @@ impl Snippet {
let snp: Snippet = serde_yaml::from_reader(f)?;
Ok(snp)
}
/// Create a snippet from a String reference (typically used for edits)
pub fn from_string(buffer: &str) -> std::result::Result<Self, SnippetError> {
let snp: Snippet = serde_yaml::from_str(buffer)?;
Ok(snp)
}
/// Forcefully save a snippet, will erase the file if already existing
pub fn write_over(&self, path: &std::path::PathBuf) -> Result<(), SnippetError> {
let mut f = File::create(path)?;
write!(f, "{}", serde_yaml::to_string(self)?)?;
Ok(())
}
/// Create an empty snippet and immediately serialize it
pub fn empty(name: String, default_values: Vec<String>) -> String {
serde_yaml::to_string(&Snippet {
name,
default_values,
content: String::new(),
//..Snippet::default(),
})
.unwrap()
}
}

View File

@ -4,6 +4,7 @@
//! or be a helper function for such a function
use std::fs::create_dir_all;
use std::io::{read_to_string, Write};
use std::{env, fs::File, io::Read, path::PathBuf};
use edit::edit;
@ -53,7 +54,7 @@ pub fn create_snippet(cli: &Cli) -> Result<(), SnippetError> {
}
FileStatus::NotFound(p) => File::create(p)?, // Create a new snippet
};
snp.save_as(f)?;
snp.save_in(f)?;
Ok(())
}
@ -62,7 +63,7 @@ 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((p, f)) => Snippet::from_file(f)?,
FileStatus::Opened((_, f)) => Snippet::from_file(f)?,
FileStatus::NotFound(p) => {
if cli.force {
Snippet::new(cli.snippet.clone(), cli.args.clone(), String::from(""))
@ -79,18 +80,48 @@ pub fn edit_snippet(cli: &Cli) -> Result<(), SnippetError> {
/// Note that the snippet can be saved with another name and might trigger
/// a creation or an override
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)?;
let mut raw_snippet = String::from("");
f.read_to_string(&mut raw_snippet)?;
let edited_str = edit(raw_snippet)?;
// Parse the result
let snp: Snippet = serde_yaml::from_str(&edited_str)?;
// If no error save with snp.save()
snp.save(cli)?;
Ok(())
// Try loading the snippet
let status = check_dir_and_open(&cli.snippet);
let (buf, mut p) = match status? {
FileStatus::Opened((p, f)) => (read_to_string(f)?, p),
FileStatus::NotFound(p) => {
if cli.create {
File::create(&p)?;
(Snippet::empty(cli.snippet.clone(), cli.args.clone()), p)
} else {
return Err(SnippetError::NotFoundNoRetryError(p));
}
}
};
// During tests, the editor cannot be tested
#[cfg(not(feature = "test"))]
let buf = edit::edit(buf)?;
// Try reparsing, on error no modifications will be made
match Snippet::from_string(&buf) {
Ok(snp) => {
snp.write_over(&p)?;
println!(
"The snippet {:?} was succesfully saved",
p.file_name().unwrap()
);
Ok(())
}
Err(_) => {
// The snippet is incorrect, however it should still be saved, just under another name ?
p.set_extension("bad.yaml");
let mut failover = File::create(&p)?;
write!(failover, "{}", &buf)?;
println!(
"The snippet was saved under {:?} in your config",
p.file_name().unwrap()
);
Err(SnippetError::ReparsingError)
}
}
}
/// Print the snippet to stdout
@ -119,25 +150,6 @@ pub fn print_snippet(args: &Cli) -> Result<(), SnippetError> {
Ok(())
}
// TODO: Remove as the opening can't be generalized
// /// Open the path linked to a snippet
// fn open_path(snp: &Snippet) -> Result<File, SnippetError> {
// // Find if the snippet exists
// let mut save_path = config_folder()?;
// // Err(e) => panic!("The OS couldn't locate a place to save the snippets.\n {}"),
// let file = match create_dir_all(&save_path) {
// Ok(()) => {
// save_path.push(format!("{}.yaml", snp.name));
// File::create(&save_path).unwrap_or_else(|e| {
// panic!("Couldn't create snippet file at {:?} {:}", save_path, e)
// })
// }
// Err(e) => panic!("Couldn't write to path {:?}. {}", save_path, e),
// };
// 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
@ -172,14 +184,6 @@ pub fn config_folder() -> Result<PathBuf, SnippetError> {
Ok(dir)
}
/// 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 super::*;
@ -192,6 +196,14 @@ mod test {
};
}
/// 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)
}
#[test]
fn test_config_creation() {
// Try to locate where to set the config
@ -234,12 +246,20 @@ mod test {
}
#[test]
#[ignore]
fn test_edit() {
// TODO: Finish this test
// Test edit non existant
// Test edit with create
// Test
// todo!()
}
#[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());
// TODO: Finish this test
}
}