//! 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 use clap::CommandFactory; #[allow(unused)] // Mandatory because of how test and rust-analyser work use edit::edit; use std::fs::{self, create_dir_all}; use std::io::{self, 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.as_ref().unwrap())?; match status { FileStatus::Opened((p, _)) => { println!( "The snippet {} is located at \"{}\"", cli.snippet.as_ref().unwrap(), p.as_os_str().to_str().unwrap() ); 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.as_ref().unwrap().clone(), cli.args.clone(), String::from(""), ); let status = check_dir_and_open(cli.snippet.as_ref().unwrap())?; 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.as_os_str().to_str().unwrap() ); 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.as_ref().unwrap() { println!("The original and new snippet name are the same, skipping..."); return Ok(()); // The noop is a success ? } let (f, oldpath) = match check_dir_and_open(cli.snippet.as_ref().unwrap())? { 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.as_ref().unwrap(), 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.as_ref().unwrap())?; 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.as_ref().unwrap().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().to_str().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.as_ref().unwrap()); let (buf, mut origin_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().unwrap(), 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.as_ref().unwrap() == &snp.name { // No renaming has occured, the file can safely be overriten snp.write_over(&origin_p)?; println!( "The snippet {} was succesfully saved", origin_p.file_name().unwrap().to_str().unwrap() ); Ok(()) } else { let (dest_f, dest_p) = match check_dir_and_open(&snp.name)? { FileStatus::Opened((dest_p, _dest_f)) => { if cli.force { // Erasing will take place (File::create(&dest_p)?, dest_p) } else { // No erasing/overriting println!( "The snippet could not be saved as {}.yaml, as this Snippet already exists. The Snippet will be saved under it's original name name: {}", snp.name,origin_p.file_name().unwrap().to_str().unwrap() ); (File::create(&origin_p)?, origin_p) } } FileStatus::NotFound(p) => (File::create(&p)?, p), }; snp.save_in(&dest_f)?; println!( "The snippet was successfuly saved in {}", dest_p.into_os_string().to_str().unwrap() ); Ok(()) } } Err(_) => { // The snippet is incorrect, however it should still be saved, just under another name ? origin_p.set_extension("bad.yaml"); let mut failover = File::create(&origin_p)?; write!(failover, "{}", &buf)?; println!( "The snippet was saved under {} in your config", origin_p.file_name().unwrap().to_str().unwrap() ); Err(SnippetError::ReparsingError) } } } /// List all snippets in the snippet config directory pub fn list_snippets(_cli: &Cli) -> Result<(), SnippetError> { let dirpath = config_folder()?; let paths = fs::read_dir(&dirpath).unwrap(); println!( "Snippet list at {}:\n {}", dirpath.parent().unwrap().to_str().unwrap(), paths .map(|p| p .unwrap() .path() .file_name() .unwrap() .to_str() .unwrap() .to_owned()) .collect::>() .join(", ") ); Ok(()) } /// Print the snippet to stdout pub fn print_snippet(cli: &Cli) -> Result<(), SnippetError> { // Try to load the snippet i if cli.snippet.is_none() { // This wonky hack exists because of subcommands // It could also be checked when populating, but is way easier this #[cfg(not(feature = "test"))] Cli::command().print_long_help()?; return Ok(()); } let (_, f) = match check_dir_and_open(cli.snippet.as_ref().unwrap())? { 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)?; print!("{}", f_str); io::stdout().flush()?; 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.as_ref().unwrap())); std::fs::remove_file(&path)?; println!( "The snippet \"{}\" was successfully deleted.", // path.file_name().unwrap().to_str().unwrap() cli.snippet.as_ref().unwrap() ); Ok(()) } /// Create an example snippet with a small guide and the next step printed out pub fn create_example(_cli: &Cli) -> Result<(), SnippetError> { let mut path = config_folder()?; path.push("unique_example.yaml"); println!( "The snippet unique_example was created. You can use the following command to launch an editor and begin editing it: $ snp unique_example -E Once you are done with the editing, you can try using the snippet with: $ snp unique_example If you wish to delete the snippet, you can use the following command: $ snp -d unique_example" ); let arguments = vec!["Argument 1", "Argument 2", "Foo", "Bar"]; let text = "This is a snippet created as an example. You can type several lines of code to help you in your daily coding process. This snippet manager accepts either {} as a argument placeholder and will fill it with Argument 1, the first argument. You can also use {0} to have the first argument somewhere else. Or {3} to skip to the last argument and finish with {} {} {} If you only needed to edit this code part and not the snippet, you can use instead `snp unique_example -e` (not -E). Please consult the --help for the full list of commands ! "; let snp = Snippet::new( "unique_example".to_string(), arguments.iter().map(|s| s.to_string()).collect(), text.to_string(), ); _ = std::fs::remove_file(&path); let f = File::create(path)?; snp.save_in(&f)?; 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()); } // #[ignore] #[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!("snp", "-f", "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!("-f", "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!("snp", "-c", "test_print")).is_ok()); assert!(print_snippet(false_cli!("snp", "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!("snp", "-c", "create_snippet")).is_ok()); // Test to create again assert!(create_snippet(false_cli!("snp", "-c", "create_snippet")).is_err()); // Test to create with force assert!(create_snippet(false_cli!("snp", "-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!("snp", "-e", "edit_content")).is_err()); // Force creation assert!(edit_snippet(false_cli!("snp", "-e", "-c", "edit_content")).is_ok()); // Edit when created println!( "{:?}", edit_snippet(false_cli!("snp", "-e", "edit_content")) ); assert!(edit_snippet(false_cli!("snp", "-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!("snp", "-E", "edit_whole")).is_err()); // Force creation assert!(edit_whole_snippet(false_cli!("snp", "-E", "-c", "edit_whole")).is_ok()); // Edit when created assert!(edit_whole_snippet(false_cli!("snp", "-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!("snp", "-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!("snp", "-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!("snp", "-c", "filled_destination", "-f")).is_ok()); assert!(create_snippet(false_cli!("snp", "-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!("snp", "-c", "new_snippet")).is_err()); assert!(create_snippet(false_cli!("snp", "-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_ok()); // The failure just means it wasn't overriten // TODO: Check no overwrite occurs } }