Skip to main content

elph_agent/
builder.rs

1use std::path::PathBuf;
2
3use elph_core::logger::LoggingOptions;
4
5/// Output of [`AgentBuilder::build`].
6#[derive(Debug, Clone)]
7pub struct AgentInit {
8    pub app_version: &'static str,
9    pub quiet_env: Option<&'static str>,
10    pub logging: LoggingOptions,
11}
12
13/// Builder for application initialization settings shared across Elph apps.
14#[derive(Debug, Clone)]
15pub struct AgentBuilder {
16    app_version: &'static str,
17    env_prefix: &'static str,
18    app_name: &'static str,
19    quiet_env: Option<&'static str>,
20    logs_dir: Option<PathBuf>,
21    console_enabled: bool,
22}
23
24impl AgentBuilder {
25    pub fn new(app_version: &'static str) -> Self {
26        Self {
27            app_version,
28            env_prefix: "",
29            app_name: "",
30            quiet_env: None,
31            logs_dir: None,
32            console_enabled: true,
33        }
34    }
35
36    pub fn env_prefix(mut self, prefix: &'static str) -> Self {
37        self.env_prefix = prefix;
38        self
39    }
40
41    pub fn app_name(mut self, name: &'static str) -> Self {
42        self.app_name = name;
43        self
44    }
45
46    pub fn quiet_env(mut self, env: &'static str) -> Self {
47        self.quiet_env = Some(env);
48        self
49    }
50
51    pub fn logs_dir(mut self, dir: PathBuf) -> Self {
52        self.logs_dir = Some(dir);
53        self
54    }
55
56    pub fn console_enabled(mut self, enabled: bool) -> Self {
57        self.console_enabled = enabled;
58        self
59    }
60
61    pub fn build(self) -> AgentInit {
62        AgentInit {
63            app_version: self.app_version,
64            quiet_env: self.quiet_env,
65            logging: LoggingOptions::resolve(self.env_prefix, self.app_name, self.logs_dir, self.console_enabled),
66        }
67    }
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73
74    #[test]
75    fn builder_resolves_logging_without_logs_dir() {
76        let init = AgentBuilder::new("0.0.12-test")
77            .env_prefix("ELPH")
78            .app_name("elph")
79            .console_enabled(false)
80            .build();
81
82        assert_eq!(init.app_version, "0.0.12-test");
83        assert!(!init.logging.file_enabled);
84        assert!(!init.logging.console_enabled);
85        assert_eq!(init.logging.level, "info");
86    }
87}