summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRyan Leckey <leckey.ryan@gmail.com>2017-02-12 10:02:07 -0800
committerRyan Leckey <leckey.ryan@gmail.com>2017-02-12 10:02:07 -0800
commitccae9b09fa9d4650de3cf91013162a7277e46060 (patch)
treef2ff7c58a32f5418b48dd8327e6c45b74d20356c
parentbcd0737e15726f3ad324c3cf26c5d04fe5f75766 (diff)
Remove global API
-rw-r--r--examples/basic/src/main.rs30
-rw-r--r--examples/file-json/src/main.rs10
-rw-r--r--examples/file-toml/Settings.toml3
-rw-r--r--examples/file-toml/src/main.rs11
-rw-r--r--examples/file-yaml/src/main.rs10
-rw-r--r--src/config.rs18
-rw-r--r--src/file/mod.rs15
-rw-r--r--src/file/yaml.rs4
-rw-r--r--src/lib.rs125
9 files changed, 104 insertions, 122 deletions
diff --git a/examples/basic/src/main.rs b/examples/basic/src/main.rs
index 6690f0e..2f947d8 100644
--- a/examples/basic/src/main.rs
+++ b/examples/basic/src/main.rs
@@ -1,31 +1,33 @@
extern crate config;
fn main() {
+ let mut c = config::Config::new();
+
// Set defaults for `window.width` and `window.height`
- config::set_default("window.title", "Basic").unwrap();
- config::set_default("window.width", 640).unwrap();
- config::set_default("window.height", 480).unwrap();
- config::set_default("debug", true).unwrap();
+ c.set_default("window.title", "Basic").unwrap();
+ c.set_default("window.width", 640).unwrap();
+ c.set_default("window.height", 480).unwrap();
+ c.set_default("debug", true).unwrap();
// Note that you can retrieve the stored values as any type as long
// as there exists a reasonable conversion
- println!("window.title : {:?}", config::get_str("window.title"));
- println!("window.width : {:?}", config::get_str("window.width"));
- println!("window.width : {:?}", config::get_int("window.width"));
- println!("debug : {:?}", config::get_bool("debug"));
- println!("debug : {:?}", config::get_str("debug"));
- println!("debug : {:?}", config::get_int("debug"));
+ println!("window.title : {:?}", c.get_str("window.title"));
+ println!("window.width : {:?}", c.get_str("window.width"));
+ println!("window.width : {:?}", c.get_int("window.width"));
+ println!("debug : {:?}", c.get_bool("debug"));
+ println!("debug : {:?}", c.get_str("debug"));
+ println!("debug : {:?}", c.get_int("debug"));
// Attempting to get a value as a type that cannot be reasonably
// converted to will return None
- println!("window.title : {:?}", config::get_bool("window.title"));
+ println!("window.title : {:?}", c.get_bool("window.title"));
// Instead of using a get_* function you can get the variant
// directly
- println!("debug : {:?}", config::get("debug"));
+ println!("debug : {:?}", c.get("debug"));
println!("debug : {:?}",
- config::get("debug").unwrap().as_int());
+ c.get("debug").unwrap().into_int());
// Attempting to get a value that does not exist will return None
- println!("not-found : {:?}", config::get("not-found"));
+ println!("not-found : {:?}", c.get("not-found"));
}
diff --git a/examples/file-json/src/main.rs b/examples/file-json/src/main.rs
index 9c636ac..e4ff809 100644
--- a/examples/file-json/src/main.rs
+++ b/examples/file-json/src/main.rs
@@ -1,10 +1,12 @@
extern crate config;
fn main() {
+ let mut c = config::Config::new();
+
// Read configuration from "Settings.json"
- config::merge(config::File::new("Settings", config::FileFormat::Json)).unwrap();
+ c.merge(config::File::new("Settings", config::FileFormat::Json)).unwrap();
- println!("debug = {:?}", config::get("debug"));
- println!("pi = {:?}", config::get("pi"));
- println!("weight = {:?}", config::get("weight"));
+ println!("debug = {:?}", c.get("debug"));
+ println!("pi = {:?}", c.get("pi"));
+ println!("weight = {:?}", c.get("weight"));
}
diff --git a/examples/file-toml/Settings.toml b/examples/file-toml/Settings.toml
new file mode 100644
index 0000000..28c5fc6
--- /dev/null
+++ b/examples/file-toml/Settings.toml
@@ -0,0 +1,3 @@
+debug = false
+pi = 3.14159
+weight = 150
diff --git a/examples/file-toml/src/main.rs b/examples/file-toml/src/main.rs
index 03ce61a..85db701 100644
--- a/examples/file-toml/src/main.rs
+++ b/examples/file-toml/src/main.rs
@@ -1,9 +1,12 @@
extern crate config;
fn main() {
- // Read configuration from $(cwd)/Cargo.toml
- config::merge(config::File::new("Cargo", config::FileFormat::Toml)).unwrap();
+ let mut c = config::Config::new();
- println!("package.name = {:?}", config::get_str("package.name"));
- println!("package.version = {:?}", config::get_str("package.version"));
+ // Read configuration from "Settings.toml"
+ c.merge(config::File::new("Settings", config::FileFormat::Toml)).unwrap();
+
+ println!("debug = {:?}", c.get("debug"));
+ println!("pi = {:?}", c.get("pi"));
+ println!("weight = {:?}", c.get("weight"));
}
diff --git a/examples/file-yaml/src/main.rs b/examples/file-yaml/src/main.rs
index cd3286f..6d72976 100644
--- a/examples/file-yaml/src/main.rs
+++ b/examples/file-yaml/src/main.rs
@@ -1,10 +1,12 @@
extern crate config;
fn main() {
+ let mut c = config::Config::new();
+
// Read configuration from "Settings.yaml"
- config::merge(config::File::new("Settings", config::FileFormat::Yaml)).unwrap();
+ c.merge(config::File::new("Settings", config::FileFormat::Yaml)).unwrap();
- println!("debug = {:?}", config::get("debug"));
- println!("pi = {:?}", config::get("pi"));
- println!("weight = {:?}", config::get("weight"));
+ println!("debug = {:?}", c.get("debug"));
+ println!("pi = {:?}", c.get("pi"));
+ println!("weight = {:?}", c.get("weight"));
}
diff --git a/src/config.rs b/src/config.rs
index cdb241b..403f566 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -8,7 +8,7 @@ use std::str::FromStr;
use std::collections::HashMap;
#[derive(Default, Debug)]
-pub struct FrozenError { }
+pub struct FrozenError {}
impl fmt::Display for FrozenError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
@@ -54,13 +54,17 @@ fn merge_in_all(r: &mut HashMap<String, Value>, map: &HashMap<String, Value>) {
}
// Child ( Child ( Identifier( "x" ), "y" ), "z" )
-fn path_get_mut<'a>(root: &'a mut HashMap<String, Value>, expr: path::Expression) -> Option<&'a mut Value> {
+fn path_get_mut<'a>(root: &'a mut HashMap<String, Value>,
+ expr: path::Expression)
+ -> Option<&'a mut Value> {
match expr {
path::Expression::Identifier(text) => Some(root.entry(text.clone()).or_insert(Value::Nil)),
path::Expression::Child(expr, member) => {
match path_get_mut(root, *expr) {
- Some(&mut Value::Table(ref mut table)) => Some(table.entry(member.clone()).or_insert(Value::Nil)),
+ Some(&mut Value::Table(ref mut table)) => {
+ Some(table.entry(member.clone()).or_insert(Value::Nil))
+ }
Some(v @ _) => {
*v = Value::Table(HashMap::new());
@@ -199,7 +203,7 @@ fn path_set_str(root: &mut HashMap<String, Value>, key: &str, value: &Value) {
match path::Expression::from_str(key) {
Ok(expr) => {
path_set(root, expr, value);
- },
+ }
Err(_) => {
// TODO: Log warning here
@@ -591,7 +595,8 @@ mod test {
let m = c.get_table("redis").unwrap();
assert_eq!(m.get("port").cloned().unwrap().into_int().unwrap(), 6379);
- assert_eq!(m.get("address").cloned().unwrap().into_str().unwrap(), "::1");
+ assert_eq!(m.get("address").cloned().unwrap().into_str().unwrap(),
+ "::1");
}
{
@@ -606,7 +611,8 @@ mod test {
let m = c.get_table("redis").unwrap();
assert_eq!(m.get("port").cloned().unwrap().into_int().unwrap(), 6379);
- assert_eq!(m.get("address").cloned().unwrap().into_str().unwrap(), "::0");
+ assert_eq!(m.get("address").cloned().unwrap().into_str().unwrap(),
+ "::0");
assert_eq!(m.get("db").cloned().unwrap().into_str().unwrap(), "1");
}
}
diff --git a/src/file/mod.rs b/src/file/mod.rs
index 519a4bf..6c72c37 100644
--- a/src/file/mod.rs
+++ b/src/file/mod.rs
@@ -62,13 +62,19 @@ impl FileFormat {
}
pub trait FileSource {
- fn try_build(&self, format: FileFormat, namespace: Option<&String>) -> Result<Box<Source>, Box<Error>>;
+ fn try_build(&self,
+ format: FileFormat,
+ namespace: Option<&String>)
+ -> Result<Box<Source>, Box<Error>>;
}
pub struct FileSourceString(String);
impl FileSource for FileSourceString {
- fn try_build(&self, format: FileFormat, namespace: Option<&String>) -> Result<Box<Source>, Box<Error>> {
+ fn try_build(&self,
+ format: FileFormat,
+ namespace: Option<&String>)
+ -> Result<Box<Source>, Box<Error>> {
format.parse(&self.0, namespace)
}
}
@@ -123,7 +129,10 @@ impl FileSourceFile {
}
impl FileSource for FileSourceFile {
- fn try_build(&self, format: FileFormat, namespace: Option<&String>) -> Result<Box<Source>, Box<Error>> {
+ fn try_build(&self,
+ format: FileFormat,
+ namespace: Option<&String>)
+ -> Result<Box<Source>, Box<Error>> {
// Find file
let filename = self.find_file(format)?;
diff --git a/src/file/yaml.rs b/src/file/yaml.rs
index 00b749c..7a70a4e 100644
--- a/src/file/yaml.rs
+++ b/src/file/yaml.rs
@@ -20,7 +20,9 @@ impl Content {
let mut root = match docs.len() {
0 => yaml::Yaml::Hash(BTreeMap::new()),
1 => mem::replace(&mut docs[0], yaml::Yaml::Null),
- n => { return Err(Box::new(MultipleDocumentsError(n))); }
+ n => {
+ return Err(Box::new(MultipleDocumentsError(n)));
+ }
};
// Limit to namespace
diff --git a/src/lib.rs b/src/lib.rs
index dae615c..15f9d49 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,23 +1,26 @@
-#![feature(drop_types_in_const)]
-
-#![allow(unknown_lints)]
-#![feature(trace_macros)]
-
//! Configuration is gathered by building a `Source` and then merging that source into the
//! current state of the configuration.
//!
//! ```rust
-//! // Add environment variables that begin with RUST_
-//! config::merge(config::Environment::new("RUST")).unwrap();
+//! extern crate config;
+//!
+//! use std::env;
+//! use config::{Config, File, FileFormat, Environment};
//!
-//! // Add 'Settings.toml'
-//! config::merge(config::File::new("Settings", config::FileFormat::Toml)
-//! .required(false)).unwrap();
+//! fn main() {
+//! // Create a new local configuration
+//! let mut c = Config::new();
//!
-//! // Add 'Settings.$(RUST_ENV).toml`
-//! let name = format!("Settings.{}", config::get_str("env").unwrap_or("development".into()));
-//! config::merge(config::File::new(&name, config::FileFormat::Toml)
-//! .required(false)).unwrap();
+//! // Add 'Settings.toml'
+//! c.merge(File::new("Settings", FileFormat::Toml).required(false)).unwrap();
+//!
+//! // Add 'Settings.$(RUST_ENV).toml`
+//! let name = format!("Settings.{}", env::var("env").unwrap_or("development".into()));
+//! c.merge(File::new(&name, FileFormat::Toml).required(false)).unwrap();
+//!
+//! // Add environment variables that begin with APP_
+//! c.merge(Environment::new("APP")).unwrap();
+//! }
//! ```
//!
//! Note that in the above example the calls to `config::merge` could have
@@ -28,14 +31,33 @@
//! coerced into a type with `as_*`.
//!
//! ```rust
+//! # extern crate config;
+//! #
+//! # use std::env;
+//! # use config::{Config, File, FileFormat, Environment};
+//! #
+//! # fn main() {
+//! # // Create a new local configuration
+//! # let mut c = Config::new();
+//! #
+//! # // Add 'Settings.toml'
+//! # c.merge(File::new("Settings", FileFormat::Toml).required(false)).unwrap();
+//! #
+//! # // Add 'Settings.$(RUST_ENV).toml`
+//! # let name = format!("Settings.{}", env::var("env").unwrap_or("development".into()));
+//! # c.merge(File::new(&name, FileFormat::Toml).required(false)).unwrap();
+//! #
+//! # // Add environment variables that begin with APP_
+//! # c.merge(Environment::new("APP")).unwrap();
//! // Get 'debug' and coerce to a boolean
-//! if let Some(value) = config::get("debug") {
+//! if let Some(value) = c.get("debug") {
//! println!("{:?}", value.into_bool());
//! }
//!
//! // You can use a type suffix
-//! println!("{:?}", config::get_bool("debug"));
-//! println!("{:?}", config::get_str("debug"));
+//! println!("{:?}", c.get_bool("debug"));
+//! println!("{:?}", c.get_str("debug"));
+//! # }
//! ```
//!
//! See the [examples](https://github.com/mehcode/config-rs/tree/master/examples) for
@@ -60,77 +82,8 @@ mod env;
mod path;
mod config;
-use std::error::Error;
-use std::sync::{Once, ONCE_INIT, RwLock};
-use std::collections::HashMap;
-
pub use source::{Source, SourceBuilder};
pub use file::{File, FileFormat};
pub use env::Environment;
-
pub use value::Value;
-
pub use config::Config;
-
-// Global configuration
-static mut CONFIG: Option<RwLock<Config>> = None;
-static CONFIG_INIT: Once = ONCE_INIT;
-
-// Get the global configuration instance
-pub fn global() -> &'static mut RwLock<Config> {
- unsafe {
- CONFIG_INIT.call_once(|| {
- CONFIG = Some(Default::default());
- });
-
- CONFIG.as_mut().unwrap()
- }
-}
-
-pub fn merge<T>(source: T) -> Result<(), Box<Error>>
- where T: SourceBuilder
-{
- global().write().unwrap().merge(source)
-}
-
-pub fn set_default<T>(key: &str, value: T) -> Result<(), Box<Error>>
- where T: Into<Value>
-{
- global().write().unwrap().set_default(key, value)
-}
-
-pub fn set<T>(key: &str, value: T) -> Result<(), Box<Error>>
- where T: Into<Value>
-{
- global().write().unwrap().set(key, value)
-}
-
-pub fn get(key: &str) -> Option<Value> {
- // TODO(~): Should this panic! or return None with an error message?
- // Make an issue if you think it should be an error message.
- global().read().unwrap().get(key)
-}
-
-pub fn get_str(key: &str) -> Option<String> {
- get(key).and_then(Value::into_str)
-}
-
-pub fn get_int(key: &str) -> Option<i64> {
- get(key).and_then(Value::into_int)
-}
-
-pub fn get_float(key: &str) -> Option<f64> {
- get(key).and_then(Value::into_float)
-}
-
-pub fn get_bool(key: &str) -> Option<bool> {
- get(key).and_then(Value::into_bool)
-}
-
-pub fn get_table(key: &str) -> Option<HashMap<String, Value>> {
- get(key).and_then(Value::into_table)
-}
-
-pub fn get_array(key: &str) -> Option<Vec<Value>> {
- get(key).and_then(Value::into_array)
-}