use crate::error::{NomlError, Result};
use crate::parser::{parse, parse_from_file, Document};
use crate::schema::Schema;
use crate::tree::{self, Seg};
use crate::value::Value;
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::io::{self, Write as _};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
#[derive(Debug, Clone)]
pub struct Config {
document: Document,
values: Value,
source_path: Option<PathBuf>,
modified: bool,
expressions: Vec<SavedExpression>,
}
#[derive(Debug, Clone)]
struct SavedExpression {
location: Vec<Seg>,
text: String,
value: Value,
}
fn resolve_for_config(document: &Document) -> Result<(Value, Vec<SavedExpression>)> {
let mut resolver = crate::resolver::Resolver::new();
if let Some(dir) = document
.source_path
.as_deref()
.map(Path::new)
.and_then(Path::parent)
{
resolver = resolver.with_base_path(dir);
}
let (values, recorded) = resolver.resolve_recording(document)?;
let expressions = recorded
.into_iter()
.filter_map(|(location, node, value)| {
let value = match value {
Some(value) => value,
None => tree::get(&values, &location)?.clone(),
};
let text = crate::serializer::serialize_value_node(&node).ok()?;
Some(SavedExpression {
location,
text,
value,
})
})
.collect();
Ok((values, expressions))
}
#[derive(Debug, Default)]
pub struct ConfigBuilder {
allow_missing: bool,
defaults: BTreeMap<String, Value>,
schema: Option<Schema>,
validate: Option<bool>,
}
impl Config {
pub fn new() -> Self {
let empty_table = Value::empty_table();
let document = Document::new(crate::parser::AstNode::new(
crate::parser::ast::AstValue::Table {
entries: Vec::new(),
inline: false,
},
crate::parser::Span::new(0, 0, 1, 1, 1, 1),
));
Self {
values: empty_table,
document,
source_path: None,
modified: false,
expressions: Vec::new(),
}
}
pub fn from_string(content: &str) -> Result<Self> {
let document = parse(content)?;
let (values, expressions) = resolve_for_config(&document)?;
Ok(Self {
document,
values,
source_path: None,
modified: false,
expressions,
})
}
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
let path = path.as_ref();
let document = parse_from_file(path)?;
let (values, expressions) = resolve_for_config(&document)?;
Ok(Self {
document,
values,
source_path: Some(path.to_path_buf()),
modified: false,
expressions,
})
}
pub fn builder() -> ConfigBuilder {
ConfigBuilder::default()
}
#[inline]
pub fn get(&self, key: &str) -> Option<&Value> {
self.values.get(key)
}
pub fn get_with_default<T>(&self, key: &str, default: T) -> Cow<'_, Value>
where
T: Into<Value>,
{
match self.get(key) {
Some(value) => Cow::Borrowed(value),
None => Cow::Owned(default.into()),
}
}
#[deprecated(
since = "0.9.3",
note = "the default is never returned; use `get_with_default` (or `get_or_insert`)"
)]
pub fn get_or<T>(&self, key: &str, _default: T) -> Result<&Value>
where
T: Into<Value>,
{
match self.get(key) {
Some(value) => Ok(value),
None => Err(NomlError::key_not_found(key)),
}
}
pub fn get_or_insert<T>(&mut self, key: &str, default: T) -> Result<&Value>
where
T: Into<Value>,
{
if !self.values.contains_key(key) {
self.set(key, default.into())?;
}
self.values.get(key).ok_or_else(|| {
NomlError::validation(format!("Failed to get key '{key}' after insertion"))
})
}
pub fn set<T>(&mut self, key: &str, value: T) -> Result<()>
where
T: Into<Value>,
{
self.values.set(key, value.into())?;
self.modified = true;
Ok(())
}
pub fn remove(&mut self, key: &str) -> Result<Option<Value>> {
let result = self.values.remove(key)?;
if result.is_some() {
self.modified = true;
}
Ok(result)
}
pub fn contains_key(&self, key: &str) -> bool {
self.values.contains_key(key)
}
pub fn keys(&self) -> Vec<String> {
self.values.keys()
}
pub fn is_modified(&self) -> bool {
self.modified
}
pub fn mark_clean(&mut self) {
self.modified = false;
}
pub fn source_path(&self) -> Option<&Path> {
self.source_path.as_deref()
}
pub fn save(&self) -> Result<()> {
if let Some(path) = &self.source_path {
self.save_to_file(path)
} else {
Err(NomlError::validation(
"Cannot save configuration: no source file path",
))
}
}
pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
let content = self.to_string_representation()?;
write_atomic(path.as_ref(), content.as_bytes())
.map_err(|e| NomlError::io("Failed to write configuration file".to_string(), e))?;
Ok(())
}
pub fn as_value(&self) -> &Value {
&self.values
}
pub fn into_value(self) -> Value {
self.values
}
pub fn validate_schema(&self, schema: &Schema) -> Result<()> {
schema.validate(&self.values)
}
pub fn as_document(&self) -> &Document {
&self.document
}
pub fn merge(&mut self, other: &Config) -> Result<()> {
self.merge_value(&other.values)?;
self.modified = true;
Ok(())
}
pub fn stats(&self) -> ConfigStats {
ConfigStats {
key_count: self.count_keys(&self.values),
depth: self.max_depth(&self.values, 0),
comment_count: self.document.all_comments().len(),
has_arrays: self.has_arrays(&self.values),
has_nested_tables: self.has_nested_tables(&self.values),
}
}
fn merge_value(&mut self, other: &Value) -> Result<()> {
match (self.values.as_table_mut(), other.as_table()) {
(Ok(self_table), Ok(other_table)) => {
for (key, value) in other_table {
if let Some(existing) = self_table.get_mut(key) {
if existing.is_table() && value.is_table() {
Self::merge_tables(existing.as_table_mut()?, value.as_table()?)?;
} else {
*existing = value.clone();
}
} else {
self_table.insert(key.clone(), value.clone());
}
}
Ok(())
}
_ => Err(NomlError::validation("Cannot merge non-table values")),
}
}
fn merge_tables(
target: &mut BTreeMap<String, Value>,
source: &BTreeMap<String, Value>,
) -> Result<()> {
for (key, value) in source {
if let Some(existing) = target.get_mut(key) {
if existing.is_table() && value.is_table() {
Self::merge_tables(existing.as_table_mut()?, value.as_table()?)?;
} else {
*existing = value.clone();
}
} else {
target.insert(key.clone(), value.clone());
}
}
Ok(())
}
#[allow(clippy::only_used_in_recursion)]
fn count_keys(&self, value: &Value) -> usize {
match value {
Value::Table(table) => {
table.len() + table.values().map(|v| self.count_keys(v)).sum::<usize>()
}
Value::Array(arr) => arr.iter().map(|v| self.count_keys(v)).sum(),
_ => 0,
}
}
#[allow(clippy::only_used_in_recursion)]
fn max_depth(&self, value: &Value, current_depth: usize) -> usize {
match value {
Value::Table(table) => {
let max_child_depth = table
.values()
.map(|v| self.max_depth(v, current_depth + 1))
.max()
.unwrap_or(current_depth);
max_child_depth
}
Value::Array(arr) => {
let max_element_depth = arr
.iter()
.map(|v| self.max_depth(v, current_depth))
.max()
.unwrap_or(current_depth);
max_element_depth
}
_ => current_depth,
}
}
#[allow(clippy::only_used_in_recursion)]
fn has_arrays(&self, value: &Value) -> bool {
match value {
Value::Array(_) => true,
Value::Table(table) => table.values().any(|v| self.has_arrays(v)),
_ => false,
}
}
#[allow(clippy::only_used_in_recursion)]
fn has_nested_tables(&self, value: &Value) -> bool {
match value {
Value::Table(table) => table
.values()
.any(|v| v.is_table() || self.has_nested_tables(v)),
Value::Array(arr) => arr.iter().any(|v| self.has_nested_tables(v)),
_ => false,
}
}
fn to_string_representation(&self) -> Result<String> {
let table = self.values.as_table()?;
let saved = Saved {
expressions: self
.expressions
.iter()
.map(|e| (e.location.as_slice(), e))
.collect(),
};
let mut out = String::new();
write_table_body(&mut out, table, &mut Vec::new(), &mut Vec::new(), &saved)?;
Ok(out)
}
}
#[cfg(feature = "async")]
impl Config {
pub async fn load_async<P: AsRef<Path>>(path: P) -> Result<Self> {
let source = tokio::fs::read_to_string(path.as_ref())
.await
.map_err(|e| NomlError::io(path.as_ref().to_string_lossy().to_string(), e))?;
let document = crate::parser::parse_string(
&source,
Some(path.as_ref().to_string_lossy().to_string()),
)?;
let (values, expressions) = resolve_for_config(&document)?;
Ok(Config {
document,
values,
source_path: Some(path.as_ref().to_path_buf()),
modified: false,
expressions,
})
}
pub async fn save_async<P: AsRef<Path>>(&self, path: P) -> Result<()> {
let content = self.to_string_representation()?;
write_atomic_async(path.as_ref(), content.as_bytes())
.await
.map_err(|e| NomlError::io(path.as_ref().to_string_lossy().to_string(), e))?;
Ok(())
}
pub async fn reload_async(&mut self) -> Result<()> {
match &self.source_path {
Some(path) => {
let reloaded = Self::load_async(path).await?;
self.document = reloaded.document;
self.values = reloaded.values;
self.expressions = reloaded.expressions;
self.modified = false;
Ok(())
}
None => Err(NomlError::validation(
"Cannot reload configuration: no source file path available",
)),
}
}
}
impl Default for Config {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ConfigStats {
pub key_count: usize,
pub depth: usize,
pub comment_count: usize,
pub has_arrays: bool,
pub has_nested_tables: bool,
}
impl ConfigBuilder {
pub fn allow_missing(mut self, allow: bool) -> Self {
self.allow_missing = allow;
self
}
pub fn default_value<T>(mut self, key: &str, value: T) -> Self
where
T: Into<Value>,
{
self.defaults.insert(key.to_string(), value.into());
self
}
pub fn schema(mut self, schema: Schema) -> Self {
self.schema = Some(schema);
self
}
pub fn validate(mut self, validate: bool) -> Self {
self.validate = Some(validate);
self
}
fn finish(self, mut config: Config) -> Result<Config> {
for (key, value) in self.defaults {
if !config.contains_key(&key) {
config.set(&key, value)?;
}
}
if let Some(schema) = &self.schema {
schema.apply_defaults(&mut config.values);
if self.validate != Some(false) {
schema.validate(&config.values)?;
}
}
config.mark_clean(); Ok(config)
}
pub fn build_from_file<P: AsRef<Path>>(self, path: P) -> Result<Config> {
let path = path.as_ref();
let config = if path.exists() {
Config::from_file(path)?
} else if self.allow_missing {
Config::new()
} else {
return Err(NomlError::io(
path.to_string_lossy().to_string(),
std::io::Error::new(std::io::ErrorKind::NotFound, "Configuration file not found"),
));
};
self.finish(config)
}
pub fn build_from_string(self, content: &str) -> Result<Config> {
let config = Config::from_string(content)?;
self.finish(config)
}
}
fn is_table_array(value: &Value) -> bool {
matches!(value, Value::Array(items) if !items.is_empty() && items.iter().all(Value::is_table))
}
struct Saved<'a> {
expressions: HashMap<&'a [Seg], &'a SavedExpression>,
}
impl Saved<'_> {
fn unchanged(&self, location: &[Seg], value: &Value) -> Option<&str> {
self.expressions
.get(location)
.filter(|saved| saved.value == *value)
.map(|saved| saved.text.as_str())
}
}
fn write_table_body(
out: &mut String,
table: &BTreeMap<String, Value>,
path: &mut Vec<String>,
location: &mut Vec<Seg>,
saved: &Saved<'_>,
) -> Result<()> {
for (key, value) in table {
location.push(Seg::Key(key.clone()));
let expression = saved.unchanged(location, value);
if expression.is_some() || (!value.is_table() && !is_table_array(value)) {
write_key(out, key);
out.push_str(" = ");
write_literal(out, value, location, saved)?;
out.push('\n');
}
location.pop();
}
for (key, value) in table {
location.push(Seg::Key(key.clone()));
if saved.unchanged(location, value).is_some() {
location.pop();
continue;
}
path.push(key.clone());
match value {
Value::Table(inner) => {
if !out.is_empty() {
out.push('\n');
}
out.push('[');
write_path(out, path);
out.push_str("]\n");
write_table_body(out, inner, path, location, saved)?;
}
Value::Array(items) if is_table_array(value) => {
for (i, item) in items.iter().enumerate() {
if !out.is_empty() {
out.push('\n');
}
out.push_str("[[");
write_path(out, path);
out.push_str("]]\n");
location.push(Seg::Index(i));
write_table_body(out, item.as_table()?, path, location, saved)?;
location.pop();
}
}
_ => {}
}
path.pop();
location.pop();
}
Ok(())
}
fn write_path(out: &mut String, path: &[String]) {
for (i, key) in path.iter().enumerate() {
if i > 0 {
out.push('.');
}
write_key(out, key);
}
}
fn write_key(out: &mut String, key: &str) {
if crate::tree::is_bare_key(key) {
out.push_str(key);
} else {
write_string(out, key, false);
}
}
fn write_string(out: &mut String, s: &str, template_safe: bool) {
out.push('"');
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\t' => out.push_str("\\t"),
'\r' => out.push_str("\\r"),
'$' if template_safe && chars.peek() == Some(&'{') => out.push_str("$$"),
c if c.is_control() => {
use std::fmt::Write;
let _ = write!(out, "\\u{{{:x}}}", c as u32);
}
c => out.push(c),
}
}
out.push('"');
}
fn write_literal(
out: &mut String,
value: &Value,
location: &mut Vec<Seg>,
saved: &Saved<'_>,
) -> Result<()> {
use std::fmt::Write;
if let Some(expression) = saved.unchanged(location, value) {
out.push_str(expression);
return Ok(());
}
match value {
Value::Null => out.push_str("null"),
Value::Bool(b) => {
let _ = write!(out, "{b}");
}
Value::Integer(i) => {
let _ = write!(out, "{i}");
}
Value::Float(f) => {
if f.is_nan() {
out.push_str("nan");
} else if f.is_infinite() {
out.push_str(if *f > 0.0 { "inf" } else { "-inf" });
} else {
let _ = write!(out, "{f:?}");
}
}
Value::String(s) => write_string(out, s, true),
Value::Array(items) => {
out.push('[');
for (i, item) in items.iter().enumerate() {
if i > 0 {
out.push_str(", ");
}
location.push(Seg::Index(i));
write_literal(out, item, location, saved)?;
location.pop();
}
out.push(']');
}
Value::Table(table) => {
out.push('{');
for (i, (key, item)) in table.iter().enumerate() {
out.push_str(if i > 0 { ", " } else { " " });
write_key(out, key);
out.push_str(" = ");
location.push(Seg::Key(key.clone()));
write_literal(out, item, location, saved)?;
location.pop();
}
out.push_str(if table.is_empty() { "}" } else { " }" });
}
Value::Size(bytes) => {
let _ = write!(out, "@size(\"{bytes}B\")");
}
Value::Duration(secs) => {
let _ = write!(out, "@duration(\"{secs}s\")");
}
Value::Binary(data) => {
out.push('[');
for (i, byte) in data.iter().enumerate() {
if i > 0 {
out.push_str(", ");
}
let _ = write!(out, "{byte}");
}
out.push(']');
}
#[cfg(feature = "chrono")]
Value::DateTime(dt) => write_string(out, &dt.to_rfc3339(), true),
}
Ok(())
}
static TEMP_COUNTER: AtomicUsize = AtomicUsize::new(0);
fn temp_path(path: &Path) -> io::Result<PathBuf> {
let name = path
.file_name()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "the path has no file name"))?;
let mut temp = std::ffi::OsString::from(".");
temp.push(name);
temp.push(format!(
".{}.{}.tmp",
std::process::id(),
TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
));
Ok(path.with_file_name(temp))
}
pub(crate) fn write_atomic(path: &Path, content: &[u8]) -> io::Result<()> {
#[cfg(unix)]
let permissions = fs::metadata(path).ok().map(|m| m.permissions());
let mut attempts = 0;
let (temp, mut file) = loop {
let temp = temp_path(path)?;
match fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&temp)
{
Ok(file) => break (temp, file),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists && attempts < 16 => attempts += 1,
Err(e) => return Err(e),
}
};
let result = (|| {
file.write_all(content)?;
#[cfg(unix)]
if let Some(permissions) = permissions {
file.set_permissions(permissions)?;
}
file.sync_all()?;
drop(file);
match fs::rename(&temp, path) {
#[cfg(windows)]
Err(e) if e.kind() == io::ErrorKind::PermissionDenied && path.is_file() => {
fs::write(path, content)?;
fs::remove_file(&temp)
}
other => other,
}
})();
if result.is_err() {
let _ = fs::remove_file(&temp);
return result;
}
#[cfg(unix)]
if let Some(dir) = path.parent() {
let dir = if dir.as_os_str().is_empty() {
Path::new(".")
} else {
dir
};
if let Ok(dir) = fs::File::open(dir) {
let _ = dir.sync_all();
}
}
Ok(())
}
#[cfg(feature = "async")]
async fn write_atomic_async(path: &Path, content: &[u8]) -> io::Result<()> {
use tokio::io::AsyncWriteExt;
#[cfg(unix)]
let permissions = tokio::fs::metadata(path)
.await
.ok()
.map(|m| m.permissions());
let mut attempts = 0;
let (temp, mut file) = loop {
let temp = temp_path(path)?;
match tokio::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&temp)
.await
{
Ok(file) => break (temp, file),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists && attempts < 16 => attempts += 1,
Err(e) => return Err(e),
}
};
let result = async {
file.write_all(content).await?;
file.flush().await?;
#[cfg(unix)]
if let Some(permissions) = permissions {
tokio::fs::set_permissions(&temp, permissions).await?;
}
file.sync_all().await?;
drop(file);
match tokio::fs::rename(&temp, path).await {
#[cfg(windows)]
Err(e) if e.kind() == io::ErrorKind::PermissionDenied && path.is_file() => {
tokio::fs::write(path, content).await?;
tokio::fs::remove_file(&temp).await
}
other => other,
}
}
.await;
if result.is_err() {
let _ = tokio::fs::remove_file(&temp).await;
}
result
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use tempfile::NamedTempFile;
#[test]
fn config_creation() {
let config = Config::new();
assert!(!config.is_modified());
assert!(config.keys().is_empty());
assert!(config.source_path().is_none());
}
#[test]
fn config_from_string() {
let content = r#"
name = "test"
version = 1.0
[database]
host = "localhost"
port = 5432
"#;
let config = Config::from_string(content).unwrap();
assert_eq!(config.get("name").unwrap().as_string().unwrap(), "test");
assert_eq!(config.get("version").unwrap().as_float().unwrap(), 1.0);
assert_eq!(
config.get("database.host").unwrap().as_string().unwrap(),
"localhost"
);
assert_eq!(
config.get("database.port").unwrap().as_integer().unwrap(),
5432
);
assert!(!config.is_modified());
}
#[test]
fn config_modification() {
let mut config = Config::new();
config.set("name", "test_app").unwrap();
config.set("version", 1.5).unwrap();
config.set("server.host", "0.0.0.0").unwrap();
config.set("server.port", 8080).unwrap();
assert!(config.is_modified());
assert_eq!(config.get("name").unwrap().as_string().unwrap(), "test_app");
assert_eq!(config.get("version").unwrap().as_float().unwrap(), 1.5);
assert_eq!(
config.get("server.host").unwrap().as_string().unwrap(),
"0.0.0.0"
);
assert_eq!(
config.get("server.port").unwrap().as_integer().unwrap(),
8080
);
}
#[test]
fn config_removal() {
let mut config = Config::from_string(
r#"
name = "test"
version = 1.0
debug = true
"#,
)
.unwrap();
assert!(config.contains_key("debug"));
let removed = config.remove("debug").unwrap();
assert!(removed.is_some());
assert!(removed.unwrap().as_bool().unwrap());
assert!(!config.contains_key("debug"));
assert!(config.is_modified());
}
#[test]
fn config_get_or_insert() {
let mut config = Config::from_string(
r#"
name = "test"
"#,
)
.unwrap();
let name = config.get_or_insert("name", "default").unwrap();
assert_eq!(name.as_string().unwrap(), "test");
let version = config.get_or_insert("version", "1.0.0").unwrap();
assert_eq!(version.as_string().unwrap(), "1.0.0");
assert!(config.is_modified());
assert!(config.contains_key("version"));
}
#[test]
fn config_merge() {
let mut config1 = Config::from_string(
r#"
name = "app1"
version = "1.0"
[database]
host = "localhost"
"#,
)
.unwrap();
let config2 = Config::from_string(
r#"
version = "2.0"
author = "test"
[database]
port = 5432
[server]
host = "0.0.0.0"
"#,
)
.unwrap();
config1.merge(&config2).unwrap();
assert_eq!(config1.get("version").unwrap().as_string().unwrap(), "2.0");
assert_eq!(config1.get("name").unwrap().as_string().unwrap(), "app1");
assert_eq!(config1.get("author").unwrap().as_string().unwrap(), "test");
assert_eq!(
config1.get("database.host").unwrap().as_string().unwrap(),
"localhost"
);
assert_eq!(
config1.get("database.port").unwrap().as_integer().unwrap(),
5432
);
assert_eq!(
config1.get("server.host").unwrap().as_string().unwrap(),
"0.0.0.0"
);
assert!(config1.is_modified());
}
#[test]
fn config_stats() {
let config = Config::from_string(
r#"
name = "test"
items = [1, 2, 3]
[database]
host = "localhost"
[database.pool]
min = 5
max = 20
"#,
)
.unwrap();
let stats = config.stats();
assert_eq!(stats.key_count, 7); assert!(stats.depth >= 2); assert!(stats.has_arrays);
assert!(stats.has_nested_tables);
}
#[test]
fn config_builder() {
let config = Config::builder()
.default_value("name", "default_app")
.default_value("debug", true)
.build_from_string(
r#"
version = "1.0"
"#,
)
.unwrap();
assert_eq!(
config.get("name").unwrap().as_string().unwrap(),
"default_app"
);
assert!(config.get("debug").unwrap().as_bool().unwrap());
assert_eq!(config.get("version").unwrap().as_string().unwrap(), "1.0");
assert!(!config.is_modified()); }
#[test]
fn builder_applies_schema_defaults_and_validates() {
use crate::schema::FieldType;
let schema = Schema::new()
.required_field("name", FieldType::String)
.field_with_default("port", FieldType::Integer, Value::Integer(8080));
let config = Config::builder()
.schema(schema.clone())
.build_from_string("name = \"api\"")
.unwrap();
assert_eq!(config.get("port"), Some(&Value::Integer(8080)));
assert!(!config.is_modified());
assert!(Config::builder()
.schema(schema.clone())
.build_from_string("port = 1")
.is_err());
assert!(Config::builder()
.schema(schema.clone())
.build_from_string("name = 1")
.is_err());
let config = Config::builder()
.schema(schema.clone())
.validate(false)
.build_from_string("other = true")
.unwrap();
assert_eq!(config.get("port"), Some(&Value::Integer(8080)));
let config = Config::builder()
.schema(schema)
.default_value("name", "fallback")
.validate(true)
.build_from_string("")
.unwrap();
assert_eq!(config.get("name").unwrap().as_string().unwrap(), "fallback");
}
#[test]
fn get_with_default_returns_the_default() {
let config = Config::from_string("port = 8080").unwrap();
assert_eq!(
config.get_with_default("port", 1).as_integer().unwrap(),
8080
);
assert!(matches!(
config.get_with_default("port", 1),
std::borrow::Cow::Borrowed(_)
));
assert_eq!(
config.get_with_default("missing", 7).as_integer().unwrap(),
7
);
assert!(config.get("missing").is_none(), "nothing is stored");
#[allow(deprecated)]
let old = config.get_or("missing", 7);
assert!(old.is_err());
}
#[test]
fn config_file_operations() {
let mut temp_file = NamedTempFile::new().unwrap();
write!(
temp_file,
r#"
name = "file_test"
version = 1.0
[database]
host = "localhost"
"#
)
.unwrap();
let mut config = Config::from_file(temp_file.path()).unwrap();
assert!(config.source_path().is_some());
config.set("version", 2.0).unwrap();
config.set("database.port", 5432).unwrap();
config.save().unwrap();
let config2 = Config::from_file(temp_file.path()).unwrap();
assert_eq!(config2.get("version").unwrap().as_float().unwrap(), 2.0);
assert_eq!(
config2.get("database.port").unwrap().as_integer().unwrap(),
5432
);
}
}