-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathconfig_map.rs
58 lines (50 loc) · 1.95 KB
/
config_map.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
use anyhow::{anyhow, Result};
// ConfigMap implements a low-level get/set config that is backed by an in-memory tree of toml
// nodes. It allows us to interact with a toml-based config programmatically, preserving any
// comments that were present when the toml was parsed.
#[derive(Clone, Debug)]
pub struct ConfigMap {
pub root: toml_edit::Table,
}
impl ConfigMap {
pub fn is_empty(&self) -> bool {
self.root.is_empty()
}
pub fn get_string_value(&self, key: &str) -> Result<String> {
match self.root.get(key) {
Some(toml_edit::Item::Value(toml_edit::Value::String(s))) => Ok(s.value().to_string()),
Some(v) => Err(anyhow!("Expected string value for key '{}', found '{:?}'", key, v)),
None => Err(anyhow!("Key '{}' not found", key)),
}
}
pub fn get_bool_value(&self, key: &str) -> Result<bool> {
match self.root.get(key) {
Some(toml_edit::Item::Value(toml_edit::Value::Boolean(s))) => Ok(*s.value()),
Some(v) => Err(anyhow!("Expected bool value for key '{}', found '{:?}'", key, v)),
None => Ok(false),
}
}
pub fn set_string_value(&mut self, key: &str, value_: Option<&str>) -> Result<()> {
if let Some(value) = value_ {
if key == "default" && (value == "true" || value == "false") {
// Add this as a bool.
self.root.insert(key, toml_edit::value(value == "true"));
return Ok(());
}
self.root.insert(key, toml_edit::value(value));
} else {
self.root.remove(key);
}
Ok(())
}
pub fn find_entry(&self, key: &str) -> Result<toml_edit::Item> {
match self.root.get(key) {
Some(v) => Ok(v.clone()),
None => Err(anyhow!("Key '{}' not found", key)),
}
}
pub fn remove_entry(&mut self, key: &str) -> Result<()> {
self.root.remove_entry(key);
Ok(())
}
}