config_maint/file/format/
mod.rs

1// If no features are used, there is an "unused mut" warning in `ALL_EXTENSIONS`
2// BUG: ? For some reason this doesn't do anything if I try and function scope this
3#![allow(unused_mut)]
4
5use source::Source;
6use std::collections::HashMap;
7use std::error::Error;
8use value::Value;
9
10#[cfg(feature = "toml")]
11mod toml;
12
13#[cfg(feature = "json")]
14mod json;
15
16#[cfg(feature = "yaml")]
17mod yaml;
18
19#[cfg(feature = "hjson")]
20mod hjson;
21
22#[cfg(feature = "ini")]
23mod ini;
24
25#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
26pub enum FileFormat {
27    /// TOML (parsed with toml)
28    #[cfg(feature = "toml")]
29    Toml,
30
31    /// JSON (parsed with serde_json)
32    #[cfg(feature = "json")]
33    Json,
34
35    /// YAML (parsed with yaml_rust)
36    #[cfg(feature = "yaml")]
37    Yaml,
38
39    /// HJSON (parsed with serde_hjson)
40    #[cfg(feature = "hjson")]
41    Hjson,
42    /// INI (parsed with rust_ini)
43    #[cfg(feature = "ini")]
44    Ini,
45}
46
47lazy_static! {
48    #[doc(hidden)]
49    // #[allow(unused_mut)] ?
50    pub static ref ALL_EXTENSIONS: HashMap<FileFormat, Vec<&'static str>> = {
51        let mut formats: HashMap<FileFormat, Vec<_>> = HashMap::new();
52
53        #[cfg(feature = "toml")]
54        formats.insert(FileFormat::Toml, vec!["toml"]);
55
56        #[cfg(feature = "json")]
57        formats.insert(FileFormat::Json, vec!["json"]);
58
59        #[cfg(feature = "yaml")]
60        formats.insert(FileFormat::Yaml, vec!["yaml", "yml"]);
61
62        #[cfg(feature = "hjson")]
63        formats.insert(FileFormat::Hjson, vec!["hjson"]);
64
65        #[cfg(feature = "ini")]
66        formats.insert(FileFormat::Ini, vec!["ini"]);
67
68        formats
69    };
70}
71
72impl FileFormat {
73    // TODO: pub(crate)
74    #[doc(hidden)]
75    pub fn extensions(self) -> &'static Vec<&'static str> {
76        // It should not be possible for this to fail
77        // A FileFormat would need to be declared without being added to the
78        // ALL_EXTENSIONS map.
79        ALL_EXTENSIONS.get(&self).unwrap()
80    }
81
82    // TODO: pub(crate)
83    #[doc(hidden)]
84    #[allow(unused_variables)]
85    pub fn parse(
86        self,
87        uri: Option<&String>,
88        text: &str,
89    ) -> Result<HashMap<String, Value>, Box<dyn Error + Send + Sync>> {
90        match self {
91            #[cfg(feature = "toml")]
92            FileFormat::Toml => toml::parse(uri, text),
93
94            #[cfg(feature = "json")]
95            FileFormat::Json => json::parse(uri, text),
96
97            #[cfg(feature = "yaml")]
98            FileFormat::Yaml => yaml::parse(uri, text),
99
100            #[cfg(feature = "hjson")]
101            FileFormat::Hjson => hjson::parse(uri, text),
102
103            #[cfg(feature = "ini")]
104            FileFormat::Ini => ini::parse(uri, text),
105        }
106    }
107}