cfg_rs/source/
yaml.rs

1//! Yaml config source.
2use yaml_rust2::YamlLoader;
3
4use super::{memory::ConfigSourceBuilder, ConfigSourceAdaptor, ConfigSourceParser};
5use crate::ConfigError;
6
7impl ConfigSourceAdaptor for yaml_rust2::Yaml {
8    fn convert_source(self, source: &mut ConfigSourceBuilder<'_>) -> Result<(), ConfigError> {
9        match self {
10            yaml_rust2::Yaml::Real(v) => source.insert(v),
11            yaml_rust2::Yaml::Integer(v) => source.insert(v),
12            yaml_rust2::Yaml::String(v) => source.insert(v),
13            yaml_rust2::Yaml::Boolean(v) => source.insert(v),
14            yaml_rust2::Yaml::Array(v) => source.insert_array(v)?,
15            yaml_rust2::Yaml::Hash(v) => source.insert_map(
16                v.into_iter()
17                    .filter_map(|(k, v)| k.as_str().map(|k| (k.to_string(), v))),
18            )?,
19            _ => {}
20        }
21        Ok(())
22    }
23}
24
25impl ConfigSourceAdaptor for Yaml {
26    fn convert_source(self, builder: &mut ConfigSourceBuilder<'_>) -> Result<(), ConfigError> {
27        for y in self.0 {
28            y.convert_source(builder)?;
29        }
30        Ok(())
31    }
32}
33
34impl ConfigSourceParser for Yaml {
35    type Adaptor = Yaml;
36    fn parse_source(content: &str) -> Result<Self::Adaptor, ConfigError> {
37        Ok(Yaml(YamlLoader::load_from_str(content)?))
38    }
39
40    fn file_extensions() -> Vec<&'static str> {
41        vec!["yaml", "yml"]
42    }
43}
44
45/// Yaml source.
46#[allow(missing_debug_implementations)]
47pub struct Yaml(Vec<yaml_rust2::Yaml>);
48
49#[cfg(test)]
50mod test {
51    use super::*;
52    use crate::{source::inline_source, test::source_test_suit};
53
54    #[test]
55    #[allow(unused_qualifications)]
56    fn inline_test() -> Result<(), ConfigError> {
57        source_test_suit(inline_source!("../../app.yaml")?)
58    }
59}