use std::{error::Error, path::Path};
pub fn read_config_file(filepath: &str) -> Result<String, Box<dyn Error>> {
let contents = std::fs::read_to_string(filepath)?;
Ok(contents)
}
pub fn find_config_file() -> Result<&'static Path, Box<dyn Error>> {
let local_config = Path::new("./morfo.toml");
if local_config.exists() {
return Ok(local_config);
}
let home_config = Path::new("~/.config/morfo/config.toml");
if home_config.exists() {
Ok(home_config)
} else {
Err("No config file found".into())
}
}
pub fn parse_config_file(config: &str) -> Result<(), Box<dyn Error>> {
let config: toml::Value = toml::from_str(config)?;
println!("{:?}", config);
Ok(())
}
#[cfg(test)]
mod tests {
use std::{
fs::{self, File},
io::Write,
};
use tempfile::NamedTempFile;
use super::*;
#[test]
fn test_read_config_file() {
let toml_contents = r#"
[morfo]
key = 'value'"#;
let mut temp_file = NamedTempFile::new().unwrap();
write!(temp_file, "{}", toml_contents).unwrap();
let temp_path = temp_file.path().to_str().unwrap();
let contents = read_config_file(temp_path);
assert!(contents.is_ok());
assert_eq!(contents.unwrap(), toml_contents);
}
#[test]
fn test_find_local_config_file() {
let original_dir = std::env::current_dir().unwrap();
let cargo_manifest_dir = env!("CARGO_MANIFEST_DIR");
let working_dir = Path::new("examples/custom_build");
if !cargo_manifest_dir.starts_with("error") {
let working_dir = Path::new(cargo_manifest_dir).join(working_dir);
std::env::set_current_dir(working_dir).unwrap();
} else {
std::env::set_current_dir(working_dir).unwrap();
}
let config_file = find_config_file();
assert!(config_file.is_ok());
assert_eq!(config_file.unwrap().to_str().unwrap(), "./morfo.toml");
std::env::set_current_dir(original_dir).unwrap();
}
#[test]
fn test_find_global_config_file() {
let original_dir = std::env::current_dir().unwrap();
let cargo_manifest_dir = env!("CARGO_MANIFEST_DIR");
let working_dir = Path::new("examples/hello_world");
if !cargo_manifest_dir.starts_with("error") {
let working_dir = Path::new(cargo_manifest_dir).join(working_dir);
std::env::set_current_dir(working_dir).unwrap();
} else {
std::env::set_current_dir(working_dir).unwrap();
}
let global_config = "~/.config/morfo/config.toml";
let file_path = Path::new(global_config);
let original_file = if file_path.exists() {
Some(file_path.to_str().unwrap())
} else {
None
};
if let Some(parent) = file_path.parent() {
fs::create_dir_all(parent).unwrap();
}
let _file = File::create(file_path).unwrap();
let config_file = find_config_file();
assert!(config_file.is_ok());
assert_eq!(config_file.unwrap().to_str().unwrap(), global_config);
if let Some(data) = original_file {
fs::write(file_path, data).unwrap();
} else {
fs::remove_file(file_path).unwrap();
}
std::env::set_current_dir(original_dir).unwrap();
}
}