#[cfg(test)]
#[path = "config_tests.rs"]
mod config_tests;
use crate::parser::group::ParserGroup;
use crate::parser::regex_parser::RegexParser;
use serde::Deserialize;
use std::path::Path;
#[derive(Debug, Deserialize)]
pub struct ParserConfig {
pub groups: Vec<ParserGroupDef>,
}
#[derive(Debug, Deserialize)]
pub struct ParserGroupDef {
pub name: String,
pub parsers: Vec<ParserDef>,
}
#[derive(Debug, Deserialize)]
pub struct ParserDef {
pub name: String,
pub pattern: String,
#[serde(default)]
pub timestamp_format: Option<String>,
}
pub fn from_yaml(yaml: &str) -> Result<ParserConfig, String> {
serde_yaml::from_str(yaml).map_err(|e| format!("Failed to parse YAML config: {}", e))
}
pub fn from_file(path: &Path) -> Result<ParserConfig, String> {
let content = std::fs::read_to_string(path)
.map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
from_yaml(&content)
}
pub fn build_groups(config: &ParserConfig) -> Result<Vec<ParserGroup>, String> {
let mut groups = Vec::new();
for group_def in &config.groups {
let mut group = ParserGroup::new(&group_def.name);
for parser_def in &group_def.parsers {
let parser = RegexParser::new(
&parser_def.name,
&parser_def.pattern,
parser_def.timestamp_format.clone(),
)
.map_err(|e| {
format!(
"Invalid regex in parser '{}' of group '{}': {}",
parser_def.name, group_def.name, e
)
})?;
group.add_parser(Box::new(parser));
}
groups.push(group);
}
Ok(groups)
}
pub fn load_from_yaml(yaml: &str) -> Result<Vec<ParserGroup>, String> {
let config = from_yaml(yaml)?;
build_groups(&config)
}
pub fn load_from_file(path: &Path) -> Result<Vec<ParserGroup>, String> {
let config = from_file(path)?;
build_groups(&config)
}