1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
use serde_yaml::{from_str, Value}; use std::collections::HashMap; pub struct Yaml { key_list: Vec<String>, yaml_text: String, } impl Yaml { pub fn new(key_list: Vec<String>, yaml_text: String) -> Yaml { Yaml { key_list: key_list, yaml_text: yaml_text, } } pub fn parse(&self) -> HashMap<String, String> { let yaml_data: Value = from_str(&self.yaml_text).expect("could not parse this yaml header"); let mut parsed_yaml: HashMap<String, String> = HashMap::new(); for key in &self.key_list { parsed_yaml.insert(key.to_string(), Yaml::get_value_by_key(&key, &yaml_data)); } parsed_yaml } fn get_value_by_key(key: &str, yaml_data: &Value) -> String { yaml_data[key] .as_str() .map(|value| value.to_string()) .expect(&format!("could not find key {} in your yaml header", key)) } } #[cfg(test)] mod tests { use super::Yaml; use std::collections::HashMap; #[test] fn yaml_parser_test() { let yaml = Yaml::new( vec![ String::from("title"), String::from("date"), String::from("author"), ], String::from( r#"title: The first!! date: 2027-12-27 author: Somebody"#, ), ); let mut expected_result: HashMap<String, String> = HashMap::new(); expected_result.insert(String::from("title"), String::from("The first!!")); expected_result.insert(String::from("date"), String::from("2027-12-27")); expected_result.insert(String::from("author"), String::from("Somebody")); assert_eq!(expected_result, yaml.parse()); } }