Switch to TOML as configuration language behind the scenes

This commit is contained in:
Matthias Beyer 2016-03-05 12:30:40 +01:00
parent a6406d6b88
commit 192b3b5885
3 changed files with 47 additions and 14 deletions

View file

@ -5,7 +5,7 @@ authors = ["Matthias Beyer <mail@beyermatthias.de>"]
[dependencies]
clap = "2.1.1"
config = "0.1.3"
toml = "0.1.27"
log = "0.3.4"
xdg-basedir = "0.2.2"
itertools = "0.4.6"

View file

@ -2,8 +2,7 @@ use std::default::Default;
use std::path::PathBuf;
use std::result::Result as RResult;
pub use config::types::Config;
pub use config::reader::from_file;
use toml::{Parser, Value};
/**
* Errors which are related to configuration-file loading
@ -133,9 +132,9 @@ impl Configuration {
*/
pub fn new(rtp: &PathBuf) -> Result<Configuration> {
fetch_config(&rtp).map(|cfg| {
let verbosity = cfg.lookup_boolean("verbosity").unwrap_or(false);
let editor = cfg.lookup_str("editor").map(String::from);
let editor_opts = String::from(cfg.lookup_str("editor-opts").unwrap_or(""));
let verbosity = get_verbosity(&cfg);
let editor = get_editor(&cfg);
let editor_opts = get_editor_opts(&cfg);
debug!("Building configuration");
debug!(" - verbosity : {:?}", verbosity);
@ -152,13 +151,41 @@ impl Configuration {
}
fn get_verbosity(v: &Value) -> bool {
match v {
&Value::Table(ref t) => t.get("verbose")
.map(|v| match v { &Value::Boolean(b) => b, _ => false, })
.unwrap_or(false),
_ => false,
}
}
fn get_editor(v: &Value) -> Option<String> {
match v {
&Value::Table(ref t) => t.get("editor")
.and_then(|v| match v { &Value::String(ref s) => Some(s.clone()), _ => None, }),
_ => None,
}
}
fn get_editor_opts(v: &Value) -> String {
match v {
&Value::Table(ref t) => t.get("editor-opts")
.and_then(|v| match v { &Value::String(ref s) => Some(s.clone()), _ => None, })
.unwrap_or(String::new()),
_ => String::new(),
}
}
/**
* 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<Config> {
fn fetch_config(rtp: &PathBuf) -> Result<Value> {
use std::env;
use std::fs::File;
use std::io::Read;
use xdg_basedir;
use itertools::Itertools;
@ -184,14 +211,20 @@ fn fetch_config(rtp: &PathBuf) -> Result<Config> {
.flatten()
.filter(|path| path.exists())
.map(|path| {
from_file(&path)
.map_err(|e| {
ConfigError::new(ConfigErrorKind::ConfigParsingFailed, Some(Box::new(e)))
})
let content = {
let mut s = String::new();
let mut f = File::open(path);
if f.is_err() {
}
let mut f = f.unwrap();
f.read_to_string(&mut s);
s
};
Parser::new(&content[..]).parse()
})
.filter(|loaded| loaded.is_ok())
.filter(|loaded| loaded.is_some())
.nth(0)
.map(|inner| inner.unwrap())
.map(|inner| Value::Table(inner.unwrap()))
.ok_or(ConfigError::new(ConfigErrorKind::NoConfigFileFound, None))
}

View file

@ -3,7 +3,7 @@
#[cfg(unix)] extern crate xdg_basedir;
extern crate clap;
extern crate config;
extern crate toml;
extern crate libimagstore;
extern crate libimagutil;