59 lines
1.6 KiB
Rust
59 lines
1.6 KiB
Rust
use std::collections::HashMap;
|
|
use std::path::PathBuf;
|
|
use std::fs::File;
|
|
|
|
use regex::Regex;
|
|
use rand::seq::SliceRandom;
|
|
|
|
use crate::error::ManifoldResult;
|
|
use std::io::{BufReader, BufRead};
|
|
|
|
#[derive(Debug)]
|
|
pub struct Responses {
|
|
file_content: HashMap<String, Vec<String>>
|
|
}
|
|
|
|
impl Responses {
|
|
pub fn new() -> Self {
|
|
Responses {
|
|
file_content: HashMap::<String, Vec<String>>::new()
|
|
}
|
|
}
|
|
|
|
pub fn reload(&mut self, file_path: &PathBuf) -> ManifoldResult<()> {
|
|
self.file_content = HashMap::<String, Vec<String>>::new();
|
|
|
|
let file = File::open(file_path)?;
|
|
|
|
let reader = BufReader::new(file);
|
|
let section_pattern = Regex::new(r"^\[([\w\s]+)]$")?;
|
|
let mut current_section = "".to_string();
|
|
let mut last_section_content = Vec::<String>::new();
|
|
|
|
for line in reader.lines() {
|
|
if let Ok(l) = line {
|
|
debug!("{:?}", &l);
|
|
if let Some(c) = section_pattern.captures(&*l) {
|
|
self.file_content.insert(current_section, last_section_content);
|
|
current_section = c.get(1).unwrap().as_str().to_string();
|
|
last_section_content = Vec::<String>::new();
|
|
} else {
|
|
last_section_content.push(l)
|
|
}
|
|
}
|
|
}
|
|
|
|
debug!("{:?}", self.file_content);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
pub fn get_response(&self, section: &String) -> Option<&String> {
|
|
if let Some(s) = self.file_content.get(section) {
|
|
s.choose(&mut rand::thread_rng())
|
|
} else {
|
|
None
|
|
}
|
|
}
|
|
}
|