summaryrefslogtreecommitdiffstats
path: root/src/file/mod.rs
blob: 7534ddb28edde2eb3090d25061bd94f7a26c8f2e (plain)
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
mod format;
pub mod source;

use source::Source;
use error::*;
use value::Value;

use self::source::FileSource;
pub use self::format::FileFormat;

pub struct File<T>
    where T: FileSource
{
    source: T,

    /// Namespace to restrict configuration from the file
    namespace: Option<String>,

    /// Format of file (which dictates what driver to use).
    format: Option<FileFormat>,

    /// A required File will error if it cannot be found
    required: bool,
}

impl File<source::string::FileSourceString> {
    pub fn from_str(s: &str, format: FileFormat) -> Self {
        File {
            format: Some(format),
            required: true,
            namespace: None,
            source: s.into(),
        }
    }
}

impl File<source::file::FileSourceFile> {
    pub fn new(name: &str, format: FileFormat) -> Self {
        File {
            format: Some(format),
            required: true,
            namespace: None,
            source: source::file::FileSourceFile::new(name),
        }
    }
}

impl<T: FileSource> File<T> {
    pub fn required(&mut self, required: bool) -> &mut Self {
        self.required = required;
        self
    }

    pub fn namespace(&mut self, namespace: &str) -> &mut Self {
        self.namespace = Some(namespace.into());
        self
    }
}

impl<T: FileSource> Source for File<T> {
    fn collect(&self) -> Result<Value> {
        // Coerce the file contents to a string
        let (uri, contents) = self.source.resolve(self.format).map_err(|err| {
            ConfigError::Foreign(err)
        })?;

        // Parse the string using the given format
        self.format.unwrap().parse(uri.as_ref(), &contents, self.namespace.as_ref()).map_err(|cause| {
            ConfigError::FileParse {
                uri: uri,
                cause: cause
            }
        })
    }
}