2016-10-01 15:35:06 +00:00
|
|
|
//
|
|
|
|
// imag - the personal information management suite for the commandline
|
|
|
|
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
|
|
|
|
//
|
|
|
|
// This library is free software; you can redistribute it and/or
|
|
|
|
// modify it under the terms of the GNU Lesser General Public
|
|
|
|
// License as published by the Free Software Foundation; version
|
|
|
|
// 2.1 of the License.
|
|
|
|
//
|
|
|
|
// This library is distributed in the hope that it will be useful,
|
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
|
|
|
// Lesser General Public License for more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU Lesser General Public
|
|
|
|
// License along with this library; if not, write to the Free Software
|
|
|
|
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
|
|
|
//
|
|
|
|
|
2016-01-10 14:04:06 +00:00
|
|
|
use std::path::PathBuf;
|
2016-01-19 17:05:00 +00:00
|
|
|
use std::result::Result as RResult;
|
2016-03-26 18:49:58 +00:00
|
|
|
use std::ops::Deref;
|
2016-01-10 14:04:06 +00:00
|
|
|
|
2016-03-05 11:30:40 +00:00
|
|
|
use toml::{Parser, Value};
|
2016-01-10 14:04:06 +00:00
|
|
|
|
2016-05-27 08:21:56 +00:00
|
|
|
generate_error_module!(
|
|
|
|
generate_error_types!(ConfigError, ConfigErrorKind,
|
2016-07-24 16:04:51 +00:00
|
|
|
NoConfigFileFound => "No config file found",
|
|
|
|
|
|
|
|
ConfigOverrideError => "Config override error",
|
|
|
|
ConfigOverrideKeyNotAvailable => "Key not available",
|
|
|
|
ConfigOverrideTypeNotMatching => "Configuration Type not matching"
|
|
|
|
|
2016-05-27 08:21:56 +00:00
|
|
|
);
|
|
|
|
);
|
2016-01-19 17:05:00 +00:00
|
|
|
|
|
|
|
use self::error::{ConfigError, ConfigErrorKind};
|
|
|
|
|
2016-01-21 20:19:31 +00:00
|
|
|
/**
|
2016-05-03 21:10:32 +00:00
|
|
|
* Result type of this module. Either `T` or `ConfigError`
|
2016-01-21 20:19:31 +00:00
|
|
|
*/
|
2016-01-19 17:05:00 +00:00
|
|
|
pub type Result<T> = RResult<T, ConfigError>;
|
|
|
|
|
2016-05-03 21:10:32 +00:00
|
|
|
/// `Configuration` object
|
|
|
|
///
|
|
|
|
/// Holds all config variables which are globally available plus the configuration object from the
|
|
|
|
/// config parser, which can be accessed.
|
2016-01-19 17:25:13 +00:00
|
|
|
#[derive(Debug)]
|
2016-01-10 14:04:06 +00:00
|
|
|
pub struct Configuration {
|
2016-01-21 20:19:31 +00:00
|
|
|
|
2016-05-03 21:10:32 +00:00
|
|
|
/// The plain configuration object for direct access if necessary
|
2016-03-05 11:36:11 +00:00
|
|
|
config: Value,
|
|
|
|
|
2016-05-03 21:10:32 +00:00
|
|
|
/// The verbosity the program should run with
|
2016-01-10 14:04:06 +00:00
|
|
|
verbosity: bool,
|
2016-01-21 20:19:31 +00:00
|
|
|
|
2016-05-03 21:10:32 +00:00
|
|
|
/// The editor which should be used
|
2016-01-10 14:04:06 +00:00
|
|
|
editor: Option<String>,
|
2016-01-21 20:19:31 +00:00
|
|
|
|
2016-05-03 21:10:32 +00:00
|
|
|
///The options the editor should get when opening some file
|
2016-01-10 14:04:06 +00:00
|
|
|
editor_opts: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Configuration {
|
|
|
|
|
2016-05-03 21:10:32 +00:00
|
|
|
/// Get a new configuration object.
|
|
|
|
///
|
|
|
|
/// The passed runtimepath is used for searching the configuration file, whereas several file
|
|
|
|
/// names are tested. If that does not work, the home directory and the XDG basedir are tested
|
|
|
|
/// with all variants.
|
|
|
|
///
|
|
|
|
/// If that doesn't work either, an error is returned.
|
2016-01-19 17:05:00 +00:00
|
|
|
pub fn new(rtp: &PathBuf) -> Result<Configuration> {
|
|
|
|
fetch_config(&rtp).map(|cfg| {
|
2016-03-05 11:30:40 +00:00
|
|
|
let verbosity = get_verbosity(&cfg);
|
|
|
|
let editor = get_editor(&cfg);
|
|
|
|
let editor_opts = get_editor_opts(&cfg);
|
2016-01-10 14:04:06 +00:00
|
|
|
|
|
|
|
debug!("Building configuration");
|
|
|
|
debug!(" - verbosity : {:?}", verbosity);
|
|
|
|
debug!(" - editor : {:?}", editor);
|
|
|
|
debug!(" - editor-opts: {}", editor_opts);
|
|
|
|
|
2016-01-19 17:05:00 +00:00
|
|
|
Configuration {
|
2016-03-05 11:36:11 +00:00
|
|
|
config: cfg,
|
2016-01-10 14:04:06 +00:00
|
|
|
verbosity: verbosity,
|
|
|
|
editor: editor,
|
|
|
|
editor_opts: editor_opts,
|
2016-01-19 17:05:00 +00:00
|
|
|
}
|
2016-01-10 14:04:06 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2016-03-21 09:19:03 +00:00
|
|
|
pub fn editor(&self) -> Option<&String> {
|
|
|
|
self.editor.as_ref()
|
|
|
|
}
|
|
|
|
|
2016-04-17 18:48:03 +00:00
|
|
|
#[allow(dead_code)] // Why do I actually need this annotation on a pub function?
|
2016-03-05 11:36:11 +00:00
|
|
|
pub fn config(&self) -> &Value {
|
|
|
|
&self.config
|
|
|
|
}
|
|
|
|
|
2016-03-05 17:42:59 +00:00
|
|
|
pub fn store_config(&self) -> Option<&Value> {
|
2016-05-03 21:10:32 +00:00
|
|
|
match self.config {
|
|
|
|
Value::Table(ref tabl) => tabl.get("store"),
|
2016-03-05 17:42:59 +00:00
|
|
|
_ => None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-07-24 16:05:06 +00:00
|
|
|
/// Override the configuration.
|
|
|
|
/// The `v` parameter is expected to contain 'key=value' pairs where the key is a path in the
|
|
|
|
/// TOML tree, the value to be an appropriate value.
|
|
|
|
///
|
|
|
|
/// The override fails if the configuration which is about to be overridden does not exist or
|
|
|
|
/// the `value` part cannot be converted to the type of the configuration value.
|
|
|
|
///
|
|
|
|
/// If `v` is empty, this is considered to be a successful `override_config()` call.
|
|
|
|
pub fn override_config(&mut self, v: Vec<String>) -> Result<()> {
|
|
|
|
use libimagutil::key_value_split::*;
|
|
|
|
use libimagutil::iter::*;
|
|
|
|
use self::error::ConfigErrorKind as CEK;
|
|
|
|
use libimagerror::into::IntoError;
|
|
|
|
|
|
|
|
v.into_iter()
|
|
|
|
.map(|s| { debug!("Trying to process '{}'", s); s })
|
|
|
|
.filter_map(|s| {
|
|
|
|
match s.into_kv() {
|
|
|
|
Some(kv) => Some(kv.into()),
|
|
|
|
None => {
|
|
|
|
warn!("Could split at '=' - will be ignore override");
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.map(|(k, v)| {
|
|
|
|
match self.config.lookup_mut(&k[..]) {
|
|
|
|
Some(value) => {
|
|
|
|
match into_value(value, v) {
|
|
|
|
Some(v) => {
|
|
|
|
*value = v;
|
|
|
|
info!("Successfully overridden: {} = {}", k, value);
|
|
|
|
Ok(())
|
|
|
|
},
|
|
|
|
None => Err(CEK::ConfigOverrideTypeNotMatching.into_error()),
|
|
|
|
}
|
|
|
|
},
|
|
|
|
None => Err(CEK::ConfigOverrideKeyNotAvailable.into_error()),
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.fold_defresult(|i| i)
|
|
|
|
.map_err(Box::new)
|
|
|
|
.map_err(|e| CEK::ConfigOverrideError.into_error_with_cause(e))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Tries to convert the String `s` into the same type as `value`.
|
|
|
|
///
|
|
|
|
/// Returns None if string cannot be converted.
|
|
|
|
///
|
|
|
|
/// Arrays and Tables are not supported and will yield `None`.
|
|
|
|
fn into_value(value: &Value, s: String) -> Option<Value> {
|
|
|
|
use std::str::FromStr;
|
|
|
|
|
|
|
|
match value {
|
|
|
|
&Value::String(_) => Some(Value::String(s)),
|
|
|
|
&Value::Integer(_) => FromStr::from_str(&s[..]).ok().map(|i| Value::Integer(i)),
|
|
|
|
&Value::Float(_) => FromStr::from_str(&s[..]).ok().map(|f| Value::Float(f)),
|
|
|
|
&Value::Boolean(_) => {
|
|
|
|
if s == "true" { Some(Value::Boolean(true)) }
|
|
|
|
else if s == "false" { Some(Value::Boolean(false)) }
|
|
|
|
else { None }
|
|
|
|
}
|
|
|
|
&Value::Datetime(_) => Some(Value::Datetime(s)),
|
|
|
|
_ => None,
|
|
|
|
}
|
2016-01-10 14:04:06 +00:00
|
|
|
}
|
|
|
|
|
2016-03-26 18:49:58 +00:00
|
|
|
impl Deref for Configuration {
|
|
|
|
type Target = Value;
|
|
|
|
|
|
|
|
fn deref(&self) -> &Value {
|
|
|
|
&self.config
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2016-03-05 11:30:40 +00:00
|
|
|
fn get_verbosity(v: &Value) -> bool {
|
2016-05-03 21:10:32 +00:00
|
|
|
match *v {
|
|
|
|
Value::Table(ref t) => t.get("verbose")
|
|
|
|
.map_or(false, |v| match *v { Value::Boolean(b) => b, _ => false, }),
|
2016-03-05 11:30:40 +00:00
|
|
|
_ => false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_editor(v: &Value) -> Option<String> {
|
2016-05-03 21:10:32 +00:00
|
|
|
match *v {
|
|
|
|
Value::Table(ref t) => t.get("editor")
|
|
|
|
.and_then(|v| match *v { Value::String(ref s) => Some(s.clone()), _ => None, }),
|
2016-03-05 11:30:40 +00:00
|
|
|
_ => None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_editor_opts(v: &Value) -> String {
|
2016-05-03 21:10:32 +00:00
|
|
|
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_default(),
|
2016-03-05 11:30:40 +00:00
|
|
|
_ => String::new(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-01-21 20:19:31 +00:00
|
|
|
/**
|
|
|
|
* Helper to fetch the config file
|
|
|
|
*
|
|
|
|
* Tests several variants for the config file path and uses the first one which works.
|
|
|
|
*/
|
2016-03-05 11:30:40 +00:00
|
|
|
fn fetch_config(rtp: &PathBuf) -> Result<Value> {
|
2016-01-10 14:04:06 +00:00
|
|
|
use std::env;
|
2016-03-05 11:30:40 +00:00
|
|
|
use std::fs::File;
|
|
|
|
use std::io::Read;
|
2016-03-25 14:10:54 +00:00
|
|
|
use std::io::Write;
|
|
|
|
use std::io::stderr;
|
2016-01-10 14:04:06 +00:00
|
|
|
|
|
|
|
use xdg_basedir;
|
|
|
|
use itertools::Itertools;
|
|
|
|
|
|
|
|
use libimagutil::variants::generate_variants as gen_vars;
|
|
|
|
|
|
|
|
let variants = vec!["config", "config.toml", "imagrc", "imagrc.toml"];
|
|
|
|
let modifier = |base: &PathBuf, v: &'static str| {
|
|
|
|
let mut base = base.clone();
|
2016-05-03 21:10:32 +00:00
|
|
|
base.push(String::from(v));
|
2016-01-10 14:04:06 +00:00
|
|
|
base
|
|
|
|
};
|
|
|
|
|
|
|
|
vec![
|
2016-05-28 21:03:04 +00:00
|
|
|
vec![rtp.clone()],
|
2016-01-10 14:04:06 +00:00
|
|
|
gen_vars(rtp.clone(), variants.clone(), &modifier),
|
|
|
|
|
|
|
|
env::var("HOME").map(|home| gen_vars(PathBuf::from(home), variants.clone(), &modifier))
|
|
|
|
.unwrap_or(vec![]),
|
|
|
|
|
|
|
|
xdg_basedir::get_data_home().map(|data_dir| gen_vars(data_dir, variants.clone(), &modifier))
|
|
|
|
.unwrap_or(vec![]),
|
|
|
|
].iter()
|
|
|
|
.flatten()
|
2016-03-25 14:10:32 +00:00
|
|
|
.filter(|path| path.exists() && path.is_file())
|
2016-01-19 17:05:00 +00:00
|
|
|
.map(|path| {
|
2016-03-05 11:30:40 +00:00
|
|
|
let content = {
|
|
|
|
let mut s = String::new();
|
2016-03-25 15:01:11 +00:00
|
|
|
let f = File::open(path);
|
2016-03-05 11:30:40 +00:00
|
|
|
if f.is_err() {
|
2016-05-09 15:12:55 +00:00
|
|
|
return None
|
2016-03-05 11:30:40 +00:00
|
|
|
}
|
|
|
|
let mut f = f.unwrap();
|
2016-03-25 15:01:42 +00:00
|
|
|
f.read_to_string(&mut s).ok();
|
2016-03-05 11:30:40 +00:00
|
|
|
s
|
|
|
|
};
|
2016-05-09 15:12:55 +00:00
|
|
|
|
2016-03-25 14:10:54 +00:00
|
|
|
let mut parser = Parser::new(&content[..]);
|
|
|
|
let res = parser.parse();
|
2016-05-09 15:12:55 +00:00
|
|
|
|
2016-03-25 14:10:54 +00:00
|
|
|
if res.is_none() {
|
2016-04-17 18:48:17 +00:00
|
|
|
write!(stderr(), "Config file parser error:").ok();
|
2016-03-25 14:10:54 +00:00
|
|
|
for error in parser.errors {
|
2016-04-17 18:48:17 +00:00
|
|
|
write!(stderr(), "At [{}][{}] <> {}", error.lo, error.hi, error).ok();
|
|
|
|
write!(stderr(), "in: '{}'", &content[error.lo..error.hi]).ok();
|
2016-03-25 14:10:54 +00:00
|
|
|
}
|
|
|
|
None
|
|
|
|
} else {
|
|
|
|
res
|
|
|
|
}
|
2016-01-19 17:05:00 +00:00
|
|
|
})
|
2016-03-05 11:30:40 +00:00
|
|
|
.filter(|loaded| loaded.is_some())
|
2016-01-10 14:04:06 +00:00
|
|
|
.nth(0)
|
2016-03-05 11:30:40 +00:00
|
|
|
.map(|inner| Value::Table(inner.unwrap()))
|
2016-05-27 08:27:06 +00:00
|
|
|
.ok_or(ConfigErrorKind::NoConfigFileFound.into())
|
2016-01-10 14:04:06 +00:00
|
|
|
}
|
|
|
|
|