240 lines
8.1 KiB
Rust
240 lines
8.1 KiB
Rust
//! 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 std::fs::create_dir_all;
|
|
use std::{env, fs::File, io::Read, path::PathBuf};
|
|
|
|
use edit::edit;
|
|
|
|
use crate::dynamic_formatter;
|
|
use crate::{dynamic_formatter::complete_vec, errors::SnippetError, snippet::Snippet, 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)),
|
|
}
|
|
}
|
|
|
|
// /// Print the path of the current snippet
|
|
// fn print_path(path: &Path) {
|
|
// println!("{}", path.to_string_lossy());
|
|
// }
|
|
|
|
/// Open and load snippet and edit it
|
|
/// If chained with create, the file will be created, closed and opened again
|
|
pub fn edit_snippet(cli: &Cli) -> Result<(), SnippetError> {
|
|
// Try loading, if not existant check if create or error
|
|
let path = snippet_path(&cli.snippet)?;
|
|
let f = match File::open(&path) {
|
|
Ok(f) => f,
|
|
Err(e) => {
|
|
if cli.force {
|
|
File::create(&path)?
|
|
} else {
|
|
return Err(e.into());
|
|
}
|
|
}
|
|
};
|
|
|
|
let mut snp: Snippet = match serde_yaml::from_reader(f) {
|
|
Ok(yaml) => yaml,
|
|
Err(e) => {
|
|
if cli.create {
|
|
Snippet::new(cli.snippet.clone(), cli.args.clone(), String::from(""))
|
|
} else {
|
|
return Err(e.into());
|
|
}
|
|
}
|
|
};
|
|
snp.edit()?;
|
|
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> {
|
|
// 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(())
|
|
}
|
|
|
|
// /// Edit the snippet and write it again
|
|
// fn edit_snippet_content(snp: &Snippet) -> Result<(), SnippetError> {
|
|
// let test = edit::edit(&snp.content)?; //.expect("Couldn't edit the snippet with the editor");
|
|
// let snp = Snippet::new(snp.name.clone(), snp.default_values.clone(), test);
|
|
// // TODO: Write snippet . Destroy original ? Return new ?
|
|
// let file = open_path(&snp)?;
|
|
// snp.save_as(file)?;
|
|
// // .unwrap_or_else(|e| println!("Coudln't save to file {:?} {}", path, e));
|
|
// Ok(())
|
|
// }
|
|
|
|
/// Create a new snippet with the given cli args
|
|
/// * Find if the snippet exists
|
|
/// * Create a snippet with the given data
|
|
/// * Write the snippet
|
|
pub fn create_snippet(args: &Cli) -> Result<(), SnippetError> {
|
|
// Create a snippet with the given data
|
|
// TODO: Remove clone ?
|
|
let snp = Snippet::new(args.snippet.clone(), args.args.clone(), String::from(""));
|
|
let path = snippet_path(&args.snippet)?;
|
|
let f = match File::open(&path) {
|
|
Ok(f) => f,
|
|
Err(e) => {
|
|
if args.force {
|
|
File::create(&path)?
|
|
} else {
|
|
return Err(e.into());
|
|
}
|
|
}
|
|
};
|
|
|
|
// Write the snippet
|
|
snp.save_as(f)?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Print the snippet to stdout
|
|
pub fn print_snippet(args: &Cli) -> Result<(), SnippetError> {
|
|
// Try to load the snippet <name>
|
|
let mut path = config_folder()?; //.expect("Coudn't open config forder");
|
|
path.push(format!("{}.yaml", args.snippet));
|
|
let f = std::fs::File::open(&path)?; //.expect("Could not open snippet file.");
|
|
let snp: Snippet = serde_yaml::from_reader(f)?; //.expect("Couldn't parse values");
|
|
|
|
// Add the given arguments to the snippet
|
|
// let final_args = match complete_vec(&args.args, &snp.default_values) {
|
|
// Err(_) => panic!("Too many arguments given to the snippet, aborting"),
|
|
// Ok(argg) => argg,
|
|
// };
|
|
let final_args = complete_vec(&args.args, &snp.default_values)?;
|
|
|
|
// Print the snippet
|
|
// let f_str = match dynamic_formatter::dynamic_formatter(&snp.content, final_args) {
|
|
// Err(_) => panic!("Couldn't format the snippet !"),
|
|
// Ok(sn) => sn,
|
|
// };
|
|
let f_str = dynamic_formatter::dynamic_format(&snp.content, final_args)?;
|
|
|
|
println!("{}", f_str);
|
|
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
|
|
/// 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()?;
|
|
let dir = exe.parent().expect("Executable must be in some directory");
|
|
let mut dir = dir.join(".config");
|
|
dir.push("snp_config");
|
|
// dir.push(format!("{}.yaml", name));
|
|
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 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());
|
|
}
|
|
}
|