use serde::{Deserialize, Serialize};
use toml;
use crate::{stream::StreamConfig, Error};
#[derive(Debug, Clone, Copy)]
pub enum ConfigFormat {
YAML,
JSON,
TOML,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingConfig {
pub level: String,
pub file_output: Option<bool>,
pub file_path: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EngineConfig {
pub streams: Vec<StreamConfig>,
pub logging: Option<LoggingConfig>,
}
impl EngineConfig {
pub fn from_file(path: &str) -> Result<Self, Error> {
let content = std::fs::read_to_string(path)
.map_err(|e| Error::Config(format!("Unable to read configuration file: {}", e)))?;
if let Some(format) = get_format_from_path(path) {
return match format {
ConfigFormat::YAML => serde_yaml::from_str(&content)
.map_err(|e| Error::Config(format!("YAML parsing error: {}", e))),
ConfigFormat::JSON => serde_json::from_str(&content)
.map_err(|e| Error::Config(format!("JSON parsing error: {}", e))),
ConfigFormat::TOML => toml::from_str(&content)
.map_err(|e| Error::Config(format!("TOML parsing error: {}", e))),
};
};
Err(Error::Config("The configuration file format cannot be determined. Please use YAML, JSON, or TOML format.".to_string()))
}
}
fn get_format_from_path(path: &str) -> Option<ConfigFormat> {
let path = path.to_lowercase();
if path.ends_with(".yaml") || path.ends_with(".yml") {
Some(ConfigFormat::YAML)
} else if path.ends_with(".json") {
Some(ConfigFormat::JSON)
} else if path.ends_with(".toml") {
Some(ConfigFormat::TOML)
} else {
None
}
}