imag/src/configuration.rs

123 lines
3.2 KiB
Rust

use std::fmt::{Debug, Formatter, Error};
use std::path::Path;
use config::reader::from_file;
use config::types::Config as Cfg;
use cli::CliConfig;
pub struct Configuration {
pub rtp : String,
pub store_sub : String,
pub verbose : bool,
pub debugging : bool,
pub editor : Option<String>,
pub editor_opts : String,
}
impl Configuration {
pub fn new(config: &CliConfig) -> Configuration {
let rtp = rtp_path(config).or(default_path());
let mut verbose = false;
let mut debugging = false;
let mut store_sub = String::from("/store");
let mut editor = None;
let mut editor_opts = String::from("");
if let Some(cfg) = fetch_config(rtp.clone()) {
if let Some(v) = cfg.lookup_boolean("verbose") {
verbose = v;
}
if let Some(d) = cfg.lookup_boolean("debug") {
debugging = d;
}
if let Some(s) = cfg.lookup_str("store") {
store_sub = String::from(s);
}
if let Some(s) = cfg.lookup_str("editor") {
editor = Some(String::from(s));
}
if let Some(s) = cfg.lookup_str("editor-opts") {
editor_opts = String::from(s);
}
}
let runtimepath = rtp.unwrap_or(String::from("/tmp/"));
debug!("Building configuration");
debug!(" - verbose : {}", verbose);
debug!(" - debugging : {}", debugging);
debug!(" - store sub : {}", store_sub);
debug!(" - runtimepath: {}", runtimepath);
debug!(" - editor : {:?}", editor);
debug!(" - editor-opts: {}", editor_opts);
Configuration {
verbose: verbose,
debugging: debugging,
store_sub: store_sub,
rtp: runtimepath,
editor: editor,
editor_opts: editor_opts,
}
}
pub fn is_verbose(&self) -> bool {
self.verbose
}
pub fn is_debugging(&self) -> bool {
self.debugging
}
pub fn store_path(&self) -> String {
format!("{}{}", self.rtp, self.store_sub)
}
pub fn get_rtp(&self) -> String {
self.rtp.clone()
}
pub fn editor(&self) -> Option<String> {
self.editor.clone()
}
pub fn editor_opts(&self) -> &String {
&self.editor_opts
}
}
fn rtp_path(config: &CliConfig) -> Option<String> {
config.cli_matches.value_of("rtp")
.and_then(|s| Some(String::from(s)))
}
fn fetch_config(rtp: Option<String>) -> Option<Cfg> {
rtp.and_then(|r| from_file(Path::new(&(r.clone() + "/config"))).ok())
}
fn default_path() -> Option<String> {
use std::env::home_dir;
home_dir().and_then(|mut buf| {
buf.push("/.imag");
buf.to_str().map(|s| String::from(s))
})
}
impl Debug for Configuration {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
write!(f, "Configuration (verbose: {}, debugging: {}, rtp: {}, store path: {})",
self.is_verbose(),
self.is_debugging(),
self.get_rtp(),
self.store_path()
)
}
}