use toml_edit::
{
Item,
RawString,
Value,
};
use crate::
{
consts,
network::codes::
{
ServerSetting,
SettingValue,
},
};
fn heading(prefix: &str) -> Option<String>
{
let mut heading = None;
for line in prefix.lines()
{
let line = line.trim();
if line.is_empty() { heading = None; }
else if let Some(comment) = line.strip_prefix('#') { heading = Some(comment.trim().to_string()); }
}
heading
}
pub fn all() -> Vec<ServerSetting>
{
let data = super::get_data(&super::config_path(consts::SERVER_CONFIG));
let table = data.as_table();
let mut settings = Vec::new();
let mut section = String::new();
for (key, item) in table.iter()
{
let Some(value) = item.as_value() else { continue };
if let Some(prefix) = table.key(key).and_then(|key| key.leaf_decor().prefix()).and_then(RawString::as_str)
&& let Some(found) = heading(prefix)
{
section = found;
}
let description = value.decor().suffix().and_then(RawString::as_str)
.map(|comment| comment.trim().trim_start_matches('#').trim().to_string()).unwrap_or_default();
settings.push(ServerSetting
{
key: key.to_string(),
value: match value
{
Value::Boolean(on) => SettingValue::Toggle(*on.value()),
Value::Integer(number) => SettingValue::Number(*number.value()),
Value::String(text) => SettingValue::Text(text.value().clone()),
_ => continue,
},
section: section.clone(),
description,
restart: consts::SERVER_RESTART_SETTINGS.contains(&key),
});
}
settings
}
pub fn write(settings: &[ServerSetting]) -> usize
{
let data = super::get_data(&super::config_path(consts::SERVER_CONFIG));
let accepted: Vec<(&str, Value)> = settings.iter().filter_map(|setting|
{
let current = data.get(&setting.key).and_then(Item::as_value)?;
let value: Value = match (&setting.value, current)
{
(SettingValue::Toggle(on), Value::Boolean(_)) => (*on).into(),
(SettingValue::Number(number), Value::Integer(_)) => (*number).into(),
(SettingValue::Text(text), Value::String(_)) => text.as_str().into(),
_ => return None,
};
Some((setting.key.as_str(), value))
}).collect();
super::with_cached_mut(&super::config_path(consts::SERVER_CONFIG), |doc|
{
for (key, value) in &accepted { super::set_value(doc.as_table_mut(), key, value.clone()); }
});
accepted.len()
}