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
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
//! Provide yaml [`PropertySource`].
use crate::source::*;
use crate::*;
use std::path::PathBuf;
use yaml_rust::ScanError;

/// [`PropertySource`] read properties from yaml file.
#[cfg_attr(docsrs, doc(cfg(feature = "enable_yaml")))]
#[derive(Debug, Copy, Clone)]
pub struct Yaml;

struct YamlItem {
    name: String,
    path: PathBuf,
    value: yaml_rust::yaml::Yaml,
}
impl YamlItem {
    fn new(path: PathBuf) -> Result<Self, PropertyError> {
        Ok(YamlItem {
            name: path.display().to_string(),
            path: path.clone(),
            value: yaml_rust::YamlLoader::load_from_str(&std::fs::read_to_string(path)?)?
                .pop()
                .ok_or(PropertyError::ParseFail("Empty yaml".to_owned()))?,
        })
    }
}

impl FileToPropertySource for Yaml {
    fn to_property_source(
        &self,
        path: PathBuf,
    ) -> Result<Option<Box<(dyn PropertySource)>>, PropertyError> {
        Ok(Some(Box::new(YamlItem::new(path)?)))
    }
    fn extention(&self) -> &'static str {
        "yaml"
    }
}
lazy_static::lazy_static! {
    static ref P: &'static [char] = &['.', '[', ']'];
}

impl PropertySource for YamlItem {
    fn name(&self) -> String {
        self.name.to_owned()
    }
    fn get_property(&self, name: &str) -> Option<Property> {
        use yaml_rust::yaml::Yaml;
        let mut v = &self.value;
        for n in name.split(&P[..]) {
            if n.is_empty() {
                continue;
            }
            match v {
                Yaml::Hash(t) => v = t.get(&Yaml::String(n.to_owned()))?,
                Yaml::Array(vs) => v = vs.get(n.parse::<usize>().ok()?)?,
                _ => return None,
            }
        }
        match v {
            Yaml::String(vs) => Some(Property::Str(vs.to_owned())),
            Yaml::Integer(vs) => Some(Property::Int(*vs)),
            Yaml::Real(vs) => Some(Property::Str(vs.to_owned())),
            Yaml::Boolean(vs) => Some(Property::Bool(*vs)),
            _ => None,
        }
    }
    fn is_empty(&self) -> bool {
        use yaml_rust::yaml::Yaml;
        match &self.value {
            Yaml::Hash(t) => t.is_empty(),
            _ => false,
        }
    }

    fn get_keys(&self, prefix: &str) -> Vec<String> {
        use yaml_rust::yaml::Yaml;
        let mut v = &self.value;
        for n in prefix.split(&P[..]) {
            if n.is_empty() {
                continue;
            }
            match v {
                Yaml::Hash(t) => {
                    if let Some(x) = t.get(&Yaml::String(n.to_string())) {
                        v = x;
                    } else {
                        return vec![];
                    }
                }
                _ => return vec![],
            }
        }
        match v {
            Yaml::Hash(t) => t
                .keys()
                .map(|x| match x {
                    Yaml::String(v) => Some(v.to_string()),
                    _ => None,
                })
                .flatten()
                .collect(),
            _ => vec![],
        }
    }
    fn load(&self) -> Result<Option<Box<dyn PropertySource>>, PropertyError> {
        Yaml.to_property_source(self.path.clone())
    }
}

impl From<ScanError> for PropertyError {
    fn from(err: ScanError) -> Self {
        Self::ParseFail(err.to_string())
    }
}