use anyhow::anyhow;
use yaml_rust2::Yaml;
use yaml_rust2::yaml::Hash;
pub fn type_name(yaml: &Yaml) -> String {
match yaml {
Yaml::Real(_) => "Real",
Yaml::Integer(_) => "Integer",
Yaml::String(_) => "String",
Yaml::Boolean(_) => "Boolean",
Yaml::Array(_) => "Array",
Yaml::Hash(_) => "Hash",
Yaml::Alias(_) => "Alias",
Yaml::Null => "Null",
Yaml::BadValue => "BadValue"
}.to_string()
}
pub fn hash_lookup_string(hash: &Hash, key: &str) -> Option<String> {
if let Some(value) = hash.get(&Yaml::String(key.to_string())) {
match value {
Yaml::Real(s) => Some(s.clone()),
Yaml::Integer(i) => Some(i.to_string()),
Yaml::String(s) => Some(s.clone()),
Yaml::Boolean(b) => Some(b.to_string()),
_ => None
}
} else {
None
}
}
pub fn hash_require_string(hash: &Hash, key: &str) -> anyhow::Result<String> {
if let Some(value) = hash.get(&Yaml::String(key.to_string())) {
if let Some(value) = value.as_str() {
Ok(value.to_string())
} else {
Err(anyhow!("Value for key '{}' in hash was not a string, was {}", key, type_name(value)))
}
} else {
Err(anyhow!("Did not find key '{}' in hash", key))
}
}
pub fn hash_lookup<F, U>(
hash: &Hash,
key: &str,
callback: F
) -> Option<U> where F: FnOnce(&Yaml) -> Option<U> {
if let Some(value) = hash.get(&Yaml::String(key.to_string())) {
callback(value)
} else {
None
}
}