toml_loader/
lib.rs

1extern crate toml;
2#[macro_use] extern crate quick_error;
3
4use toml::{Parser, Value, ParserError};
5use std::path::Path;
6use std::fs::File;
7use std::io;
8use std::io::Read;
9
10quick_error! {
11    /// Wraps all errors this library can produce
12    #[derive(Debug)]
13    pub enum LoadError {
14        /// IO Error
15        Io(err: io::Error) {
16            from()
17        }
18        /// TOML parsing error
19        Parse(err: Vec<ParserError>) {
20            from()
21        }
22    }
23}
24
25/// Imlements helper functions for loading and parsing .toml files
26pub struct Loader;
27
28impl Loader {
29    /// Create Toml::Value from file specified by path
30    ///
31    /// # Example
32    /// ```no_run
33    /// use toml_loader::Loader;
34    /// use std::path::Path;
35    ///
36    /// let toml = Loader::from_file(Path::new("some.toml")).unwrap();
37    /// ```
38    pub fn from_file(path: &Path) -> Result<Value, LoadError> {
39       let mut f = try!(File::open(path));
40       let mut s = String::new();
41       try!(f.read_to_string(&mut s));
42       let mut parser = Parser::new(&s);
43       let res = try!(parser.parse().map(Value::Table).ok_or(parser.errors));
44       Ok(res)
45    }
46}
47
48#[cfg(test)]
49mod test {
50    extern crate tempfile;
51
52    use super::Loader;
53    use self::tempfile::NamedTempFile;
54    use std::io::Write;
55    use std::path::Path;
56
57    macro_rules! tmp_toml_file {
58        ($content:expr) => {
59            {
60                let mut f = NamedTempFile::new().unwrap();
61                f.write_all($content.as_bytes()).unwrap();
62                f.flush().unwrap();
63                f
64            }
65        }
66    }
67
68    #[test]
69    fn loads_valid_toml_single() {
70        let f = tmp_toml_file!("a = 1");
71        Loader::from_file(f.path()).unwrap();
72    }
73
74    #[test]
75    #[should_panic]
76    fn fails_to_load_invalid_toml_single() {
77        let f = tmp_toml_file!("a - 1");
78        Loader::from_file(f.path()).unwrap();
79    }
80
81    #[test]
82    #[should_panic]
83    fn fails_to_load_non_existing_file() {
84        // Path "?\0" is invalid on both windows and linux (windows can't have ? and unix can't have \0)
85        Loader::from_file(Path::new("?\0")).unwrap();
86    }
87}