config_tools/
builder.rs

1use crate::Config;
2
3/// A builder for incrementally constructing a [`Config`] object.
4///
5/// Supports fluent-style API for setting values in the general section or
6/// named sections. To finalize the configuration, call [`ConfigBuilder::build`].
7pub struct ConfigBuilder {
8    pub(crate) config: Config,
9    pub(crate) section: Option<String>,
10}
11
12impl ConfigBuilder {
13    pub fn build(self) -> Config {
14        self.config
15    }
16
17    pub fn general(mut self) -> Self {
18        self.section = None;
19        self
20    }
21
22    pub fn section(mut self, title: &str) -> Self {
23        self.section = Some(title.to_string());
24        self.config.sections.entry(title.to_string()).or_default();
25        self
26    }
27
28    pub fn set(mut self, key: &str, value: &str) -> Self {
29        if let Some(section) = self.section.as_ref() {
30            self.config
31                .sections
32                .entry(section.clone())
33                .or_default()
34                .insert(key.to_string(), value.to_string());
35        } else {
36            self.config
37                .general_values
38                .insert(key.to_string(), value.to_string());
39        }
40
41        self
42    }
43}