Skip to main content

luminos_config/
lib.rs

1use std::collections::HashMap;
2mod env;
3mod node;
4mod codegen;
5
6pub use env::env;
7pub use node::Node;
8pub use crate::codegen::generate;
9pub use dotenv::dotenv;
10
11
12#[derive(Debug, Clone, Default)]
13pub struct Config {
14    pub root: Node,
15}
16
17impl Config {
18    pub fn new() -> Self {
19        Self {
20            root: Node::Object(HashMap::new()),
21        }
22    }
23
24    /// Insert a section.
25    pub fn insert_section(&mut self, name: &str, entries: &[(&str, Node)]) {
26        let mut map = HashMap::new();
27        for (k, v) in entries {
28            map.insert((*k).to_string(), v.clone());
29        }
30
31        if let Node::Object(root) = &mut self.root {
32            root.insert(name.to_string(), Node::Object(map));
33        }
34    }
35
36    /// Get a value by key
37    pub fn get(&self, path: &str) -> Option<&Node> {
38        let mut cur = &self.root;
39        for key in path.split('.') {
40            match cur {
41                Node::Object(map) => cur = map.get(key)?,
42                _ => return None,
43            }
44        }
45        Some(cur)
46    }
47
48    /// Set a config value by key 
49    pub fn set(&mut self, path: &str, value: Node) {
50        let mut cur = &mut self.root;
51        for key in path.split('.') {
52            cur = match cur {
53                Node::Object(map) => {
54                    map.entry(key.to_string())
55                        .or_insert(Node::Object(HashMap::new()))
56                }
57                _ => panic!("Cannot set into non-object"),
58            };
59        }
60        *cur = value;
61    }
62}