rustyphoenixreplace 1.4.1

This project aims to provide a simple a powerfull multilines replace via a toml configuration
/***************************************
	Auteur : Pierre Aubert
	Mail : pierre.aubert@lapp.in2p3.fr
	Licence : CeCILL-C
****************************************/

use std::fs;
use serde::Deserialize;
// use std::collections::HashMap;
use toml::{self, de::Error};

///Replace configuration
#[derive(Debug, Deserialize)]
pub struct ReplaceConfig{
	///Patter to be searched
	pub pattern: String,
	///String to replace the pattern
	pub replace: String,
}

///Simulation of the world
#[derive(Debug, Deserialize)]
pub struct FullReplace{
	///Vector of files pattern to be searched (.yml, .toml, .cpp, .txt, .cmake)
	pub vec_file_pattern: Vec<String>,
	///Vector of all replace to be performed
	pub replace: Vec<ReplaceConfig>,
}

///Load the configuration file
/// # Parameters
/// - `filename` : name of the configuration file (in toml)
/// # Returns
/// Replace parsed configuration or error on fail
pub fn load_configuration(filename: &String) -> Result<FullReplace, Error>{
	let simu: FullReplace = match fs::read_to_string(filename) {
		Ok(str) => match toml::from_str(&str){
			Ok(value) => value,
			Err(error) => panic!("load_configuration : parsing error {}", error)
		},
		Err(err) => panic!("load_configuration : cannot read file '{}', error: {}", filename, err)
	};
	Ok(simu)
}

#[cfg(test)]
mod tests {
	use super::*;
	
	///Test the load of the configuration
	#[test]
	fn test_load_configuration() {
		let config_content = r#"# Defining files to look at for a inplace replacement
vec_file_pattern = ["*.txt", "*.cpp", "*.yml", "*.toml", "*.txt", "*.cmake", "*.dox"]

# Then, define multiline pattern and replace string
[[replace]]
pattern = "some\nmultiline\npattern to search"
replace = "some\nreplace\npattern"

# You can define as many replace section as you want
"#;
		let output_dir = "generated/";
		let configfile = format!("{}/config.toml", output_dir);
		fs::create_dir_all(output_dir).unwrap();
		fs::write(&configfile, config_content).unwrap();
		
		let _ = load_configuration(&configfile).unwrap();
	}
	
	///Test the load of the configuration (file not found error test)
	#[test]
	#[should_panic]
	fn test_load_configuration_file_not_found_error() {
		let _ = load_configuration(&String::from("unexisting_config.toml"));
	}
	
	///Test the load of the configuration (parsing error test)
	#[test]
	#[should_panic]
	fn test_load_configuration_parsing_error() {
		let config_content = r#"# Defining files to look at for a inplace replacement
vec_file_pattern = ["*.txt", "*.cpp", "*.yml", "*.toml", "*.txt", "*.cmake", "*.dox"]

"#;
		let output_dir = "generated/";
		let configfile = format!("{}/wrong_config.toml", output_dir);
		fs::create_dir_all(output_dir).unwrap();
		fs::write(&configfile, config_content).unwrap();
		
		let _ = load_configuration(&configfile);
	}
}