#[cfg(feature = "cmd")]
pub mod cmd;
#[cfg(feature = "env")]
pub mod env;
#[cfg(feature = "json")]
pub mod json;
#[cfg(feature = "json5-parser")]
pub mod json5;
#[cfg(test)]
mod tests;
#[cfg(feature = "toml-parser")]
pub mod toml;
#[cfg(feature = "yaml")]
pub mod yaml;
use crate::{AnyResult, Case, CowString, Parse, Value, DEFAULT_KEYS_SEPARATOR};
use derive_builder::Builder;
use std::fs::File;
use std::io::{BufReader, Error, ErrorKind, Read, Result};
use std::path::PathBuf;
pub trait Load: Case {
fn load(&mut self, reader: impl Read) -> AnyResult<Value>;
}
#[derive(Builder)]
#[builder(setter(into, strip_option))]
pub struct FileParser<L> {
default_path: PathBuf,
#[builder(default = "None")]
path_option: Option<String>,
#[builder(default = "DEFAULT_KEYS_SEPARATOR.to_string()")]
keys_delimiter: String,
#[builder(default = "false")]
ignore_missing_file: bool,
loader: L,
}
impl<L: Load> Case for FileParser<L> {
#[inline]
fn is_case_sensitive(&self) -> bool {
self.loader.is_case_sensitive()
}
}
impl<L: Load> Parse for FileParser<L> {
fn parse(&mut self, value: &Value) -> AnyResult<Value> {
let path = if let Some(ref p) = self.path_option {
value.get_by_key_path_with_delim(p, &self.keys_delimiter)?
} else {
None
}
.map(CowString::Owned)
.unwrap_or_else(|| self.default_path.to_string_lossy());
let file = match try_open_file(path.as_ref()) {
Ok(f) => f,
Err(_) if self.ignore_missing_file => return Ok(Value::default()),
Err(e) => return Err(e.into()),
};
self.loader.load(BufReader::new(file))
}
}
fn try_open_file(path: &str) -> Result<File> {
let file = File::open(path)?;
if file.metadata()?.is_file() {
return Ok(file);
}
Err(Error::new(ErrorKind::InvalidData, "Is not a file"))
}