Add functionality to load prefs.json from profile-dir (as set with

--profile-dir on launch)

Use T: Read rather than File, so that read_prefs_from_file can be tested
This commit is contained in:
Matthew Bentley 2016-03-21 21:33:00 -04:00
parent 0397e2a24d
commit 3b93c9dde9
2 changed files with 42 additions and 10 deletions

View file

@ -4,9 +4,12 @@
use resource_files::resources_dir_path;
use rustc_serialize::json::{Json, ToJson};
use opts;
use std::borrow::ToOwned;
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
lazy_static! {
@ -66,7 +69,8 @@ impl ToJson for PrefValue {
}
}
enum Pref {
#[derive(Debug)]
pub enum Pref {
NoDefault(Arc<PrefValue>),
WithDefault(Arc<PrefValue>, Option<Arc<PrefValue>>)
}
@ -118,14 +122,8 @@ impl ToJson for Pref {
}
}
fn read_prefs() -> Result<HashMap<String, Pref>, ()> {
let mut path = resources_dir_path();
path.push("prefs.json");
let mut file = try!(File::open(path).or_else(|e| {
println!("Error opening preferences: {:?}.", e);
Err(())
}));
pub fn read_prefs_from_file<T>(mut file: T)
-> Result<HashMap<String, Pref>, ()> where T: Read {
let json = try!(Json::from_reader(&mut file).or_else(|e| {
println!("Ignoring invalid JSON in preferences: {:?}.", e);
Err(())
@ -145,6 +143,36 @@ fn read_prefs() -> Result<HashMap<String, Pref>, ()> {
Ok(prefs)
}
pub fn extend_prefs(extension: HashMap<String, Pref>) {
PREFS.lock().unwrap().extend(extension);
}
pub fn add_user_prefs() {
if let Some(ref dir) = opts::get().profile_dir {
let mut path = PathBuf::from(dir);
path.push("prefs.json");
if let Ok(file) = File::open(path) {
if let Ok(prefs) = read_prefs_from_file(file) {
extend_prefs(prefs);
}
} else {
println!("Error opening prefs.json from profile_dir");
}
}
}
fn read_prefs() -> Result<HashMap<String, Pref>, ()> {
let mut path = resources_dir_path();
path.push("prefs.json");
let file = try!(File::open(path).or_else(|e| {
println!("Error opening preferences: {:?}.", e);
Err(())
}));
read_prefs_from_file(file)
}
pub fn get_pref(name: &str) -> Arc<PrefValue> {
PREFS.lock().unwrap().get(name).map_or(Arc::new(PrefValue::Missing), |x| x.value().clone())
}