Move fetch_config into GetConfiguration trait

This commit is contained in:
Robert Ignat 2017-06-06 22:30:49 +02:00 committed by Matthias Beyer
parent 60e3038874
commit 7375f3c6ac

View file

@ -211,19 +211,23 @@ fn get_editor_opts(v: &Value) -> String {
}
}
/// Helper to fetch the config file
///
/// Tests several variants for the config file path and uses the first one which works.
fn fetch_config(rtp: &PathBuf) -> Result<Value> {
pub trait GetConfiguration {
/// Helper to fetch the config file
///
/// Default implementation tests several variants for the config file path and uses the first
/// one which works.
fn get_configuration(rtp: &PathBuf) -> Result<Configuration> {
use std::env;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::io::stderr;
use xdg_basedir;
use itertools::Itertools;
use libimagutil::variants::generate_variants as gen_vars;
use self::error::MapErrInto;
use libimagerror::trace::trace_error;
let variants = vec!["config", "config.toml", "imagrc", "imagrc.toml"];
let modifier = |base: &PathBuf, v: &'static str| {
@ -244,8 +248,7 @@ fn fetch_config(rtp: &PathBuf) -> Result<Value> {
].iter()
.flatten()
.filter(|path| path.exists() && path.is_file())
.filter_map(|path| if path.exists() && path.is_file() {
debug!("Reading {:?}", path);
.map(|path| {
let content = {
let mut s = String::new();
let f = File::open(path);
@ -257,26 +260,20 @@ fn fetch_config(rtp: &PathBuf) -> Result<Value> {
s
};
trace!("Contents of config file: \n---\n{}\n---", content);
let toml = ::toml::de::from_str(&content[..])
.map_err_into(ConfigErrorKind::TOMLParserError)
.map_err(Box::new)
.map_err(|e| REK::Instantiate.into_error_with_cause(e));
Some(toml)
} else {
match ::toml::de::from_str(&content[..]) {
Ok(res) => res,
Err(e) => {
write!(stderr(), "Config file parser error:").ok();
trace_error(&e);
None
}
}
})
.filter(|loaded| loaded.is_ok())
.map(|inner| Value::Table(inner.unwrap()))
.filter(|loaded| loaded.is_some())
.nth(0)
.map(|inner| Value::Table(inner.unwrap()))
.ok_or(ConfigErrorKind::NoConfigFileFound.into())
}
pub trait GetConfiguration {
fn get_configuration(rtp: &PathBuf) -> Result<Configuration> {
fetch_config(rtp).map(Configuration::new)
.map(Configuration::new)
}
}