miau/source/
file.rs

1use crate::{error::ConfigurationError, source::Source};
2use std::{
3    convert::AsRef,
4    fs::File,
5    io::Read,
6    path::{Path, PathBuf},
7};
8
9/// Represents configuration file source.
10pub struct FileSource {
11    path: PathBuf,
12}
13
14impl FileSource {
15    /// Constructs new instance of `FileSource` pointing to file at `path`.
16    pub fn from_path<T: AsRef<Path>>(path: T) -> Self {
17        FileSource {
18            path: path.as_ref().to_path_buf(),
19        }
20    }
21}
22
23impl Source for FileSource {
24    fn collect(&self) -> Result<Vec<u8>, ConfigurationError> {
25        let mut buffer = Vec::new();
26
27        let mut f = File::open(&self.path)
28            .map_err(|e| -> ConfigurationError { e.into() })
29            .map_err(|e| {
30                e.enrich_with_context(format!("Failed to open file : {}", self.path.display()))
31            })?;
32
33        f.read_to_end(&mut buffer)
34            .map_err(|e| -> ConfigurationError { e.into() })
35            .map_err(|e| {
36                e.enrich_with_context(format!("Failed to read file : {}", self.path.display()))
37            })?;
38
39        Ok(buffer)
40    }
41
42    fn describe(&self) -> String {
43        std::fs::canonicalize(&self.path)
44            .unwrap_or_else(|_| self.path.clone())
45            .display()
46            .to_string()
47    }
48}