//! Module holding the wrapper function called from the main functions //! //! All functions included should either take a Cli object and return a SnippetError //! or be a helper function for such a function #[allow(unused)] // Mandatory because of how test and rust-analyser work use edit::edit; use std::fs::create_dir_all; use std::io::{read_to_string, Write}; use std::{env, fs::File, path::PathBuf}; use crate::errors::SnippetError; use crate::snippet::Snippet; use crate::{dynamic_formatter, Cli}; /// Locate and print a snippet location /// /// Will error on snippet not existing pub fn locate_snippet(cli: &Cli) -> Result<(), SnippetError> { 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)), } } /// Create a new snippet with the given cli args pub fn create_snippet(cli: &Cli) -> Result<(), SnippetError> { // Create a snippet with the given data let snp = Snippet::new(cli.snippet.clone(), cli.args.clone(), String::from("")); let status = check_dir_and_open(&cli.snippet)?; let (f, p) = match status { FileStatus::Opened((p, _)) => { if cli.force { // Overwrite the snippet (File::create(&p)?, p) } else { // Do not overrite and return an error return Err(SnippetError::FoundNoEraseError(p)); } } FileStatus::NotFound(p) => (File::create(&p)?, p), // Create a new snippet }; snp.save_in(&f)?; println!("The snippet {:?} was created successfully", p); Ok(()) } /// Rename a snippet with the new given name pub fn rename_snippet(cli: &Cli) -> Result<(), SnippetError> { // Check wether the snippet exitsts let new_name = cli.rename.as_ref().unwrap(); if new_name == &cli.snippet { return Ok(()); // The noop is a success ? } let (f, oldpath) = match check_dir_and_open(&cli.snippet)? { FileStatus::Opened((p, f)) => (f, p), FileStatus::NotFound(e) => return Err(SnippetError::NotFound(e)), }; let mut snp = Snippet::from_file(&f)?; // Check whether the destination is writable let (f, _) = match check_dir_and_open(new_name)? { FileStatus::Opened((p, _)) => { if cli.force { snp.name = new_name.clone(); (File::create(&p)?, p) } else { return Err(SnippetError::FoundNoEraseError(p)); } } FileStatus::NotFound(p) => { snp.name = new_name.clone(); (File::create(&p)?, p) } }; // Save and delete snp.save_in(&f)?; std::fs::remove_file(oldpath)?; // Save snippet println!( "The snippet {} was sucessfuly renamed as {}", cli.snippet, new_name ); Ok(()) } /// Open and load snippet and edit it 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, _, p) = match status { FileStatus::Opened((p, f)) => (Snippet::from_file(&f)?, f, p), FileStatus::NotFound(p) => { 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(()) } /// Edit the whole snippet and save it where neededi /// 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> { // 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) => { if cli.snippet == snp.name { // No renaming has occured, the file can safely be overriten snp.write_over(&p)?; println!( "The snippet {:?} was succesfully saved", p.file_name().unwrap() ); Ok(()) } else { let (f, p) = match check_dir_and_open(&snp.name)? { FileStatus::Opened((p, f)) => { if cli.force { // Erasing will take place (File::create(&p)?, p) } else { // No erasing/overriting println!( "Impossible to save the snippet as {:}, as it already exists. The snippet will be saved under it's old name.", snp.name ); (f, p) } } FileStatus::NotFound(p) => (File::create(&p)?, p), }; snp.save_in(&f)?; println!("The snippet was successfuly saved in {:?}", p); 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) } } } // 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(cli: &Cli) -> Result<(), SnippetError> { // Try to load the snippet let (_, f) = match check_dir_and_open(&cli.snippet)? { FileStatus::Opened((p, f)) => (p, f), FileStatus::NotFound(p) => return Err(SnippetError::NotFound(p)), }; let snp = Snippet::from_file(&f)?; // Add the given arguments to the snippet let final_args = dynamic_formatter::complete_vec(&cli.args, &snp.default_values)?; // Print the snippet let f_str = dynamic_formatter::dynamic_format(&snp.content, final_args)?; println!("{}", f_str); Ok(()) } /// Delete a given snippet, errors if the snippet doesn't exists pub fn delete_snippet(cli: &Cli) -> Result<(), SnippetError> { let mut path = config_folder()?; path.push(format!("{}.yaml", cli.snippet)); std::fs::remove_file(path)?; Ok(()) } /// 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 { 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 { let exe = env::current_exe()?; let dir = exe.parent().expect("Executable must be in some directory"); let mut dir = dir.join(".config"); dir.push("snp_config"); Ok(dir) } #[cfg(test)] pub mod test { use super::*; use clap::Parser; use std::io::Write; macro_rules! false_cli { ($($arg:expr),+) => { &Cli::parse_from(vec![$($arg),+]) }; } /// 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 { 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 let path: PathBuf = snippet_path("test_config_creation").unwrap(); create_dir_all(path.parent().unwrap()).unwrap(); let _f = File::create(path).unwrap(); assert!(matches!( check_dir_and_open("test_config_creation").expect("Can't open config"), FileStatus::Opened(_) )); } #[test] fn test_delete_snippet() { assert!(create_snippet(false_cli!("snp", "-c", "-f", "delete_snippet")).is_ok()); assert!(delete_snippet(false_cli!("snp", "-d", "delete_snippet")).is_ok()); } #[test] fn test_locate() { // Try to locate an unexisting snippet let theorical_path = snippet_path("test_locate").expect("Can't find config path"); _ = std::fs::remove_file(&theorical_path); // Locating the snippet should fail assert!(locate_snippet(false_cli!("-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(false_cli!("-l", "test_locate")).is_ok()); } #[test] fn test_print_snippet() { let theorical_path = snippet_path("test_print").expect("Can't find config path"); _ = std::fs::remove_file(theorical_path); // Print non existing snippet assert!(print_snippet(false_cli!("snp", "test_print")).is_err()); // Create snippet 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!("-l", "test_print")).is_ok()); } #[test] fn test_create() { _ = std::fs::remove_file(snippet_path("create_snippet").unwrap()); // Test to create empty assert!(create_snippet(false_cli!("-c", "create_snippet")).is_ok()); // Test to create again assert!(create_snippet(false_cli!("-c", "create_snippet")).is_err()); // Test to create with force assert!(create_snippet(false_cli!("-c", "-f", "create_snippet")).is_ok()); } #[test] fn test_edit() { _ = 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()); // Open unnexitant assert!(edit_whole_snippet(false_cli!("-E", "edit_whole")).is_err()); // 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()); // Create a badly formatted file if let FileStatus::Opened((p, _)) = check_dir_and_open("edit_whole").unwrap() { let mut f = File::create(p).unwrap(); write!(f, "badly formatter yaml").unwrap(); assert!(edit_whole_snippet(false_cli!("-E", "edit_whole")).is_err()); assert!(matches!( check_dir_and_open("edit_whole.bad").unwrap(), FileStatus::Opened(_) )); }; } #[test] fn test_rename_snippet() { let oldpath = snippet_path("rename_snippet").unwrap(); let newpath = snippet_path("renamed_snippet").unwrap(); let filledpath = snippet_path("filled_destination").unwrap(); _ = std::fs::remove_file(&oldpath); _ = std::fs::remove_file(&newpath); _ = std::fs::remove_file(filledpath); assert!(create_snippet(false_cli!("-c", "rename_snippet", "-f")).is_ok()); assert!( rename_snippet(false_cli!("snp", "-r", "renamed_snippet", "rename_snippet")).is_ok() ); assert!(std::fs::remove_file(oldpath).is_err()); assert!(std::fs::remove_file(newpath).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!(create_snippet(false_cli!("-c", "filled_destination", "-f")).is_ok()); assert!(create_snippet(false_cli!("-c", "rename_snippet", "-f")).is_ok()); assert!(matches!( rename_snippet(false_cli!( "snp", "rename_snippet", "-r", "filled_destination" )), Err(SnippetError::FoundNoEraseError(_)) )); let res = rename_snippet(false_cli!( "snp", "rename_snippet", "-r", "filled_destination", "-f" )); println!("{:?}", res); assert!(res.is_ok()); } #[test] fn test_resaving_new_name() { // Try to resave under another name _ = std::fs::remove_file(snippet_path("resave_snippet").unwrap()); _ = std::fs::remove_file(snippet_path("new_snippet").unwrap()); let p = snippet_path("resave_snippet").unwrap(); let mut f = File::create(p).unwrap(); // Populate file with another name let snp_str = Snippet::empty("new_snippet".to_string(), vec![]); write!(f, "{}", snp_str).unwrap(); // Try to resave let res = edit_whole_snippet(false_cli!("snp", "resave_snippet")); println!("Trying to resave without destination {:?}", res); assert!(res.is_ok()); assert!(create_snippet(false_cli!("-c", "new_snippet")).is_err()); assert!(create_snippet(false_cli!("-c", "resave_snippet")).is_err()); let res = edit_whole_snippet(false_cli!("snp", "resave_snippet", "-f")); println!("Sucessfully erasing {:?}", res); assert!(res.is_ok()); let res = edit_whole_snippet(false_cli!("snp", "resave_snippet")); println!("Failing to overwrite {:?}", res); assert!(res.is_err()); } }