aboutsummaryrefslogtreecommitdiffstats
path: root/src/logging/config.rs
blob: 1663f139b14089b6bdfde99f871d7ba9e03ae288 (plain)
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use super::level::{self, Level};
use figment::{providers::Serialized, value, Figment, Metadata, Profile, Provider};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
    #[serde(with = "level")]
    pub stdout: Option<Level>,
    #[serde(with = "level")]
    pub level: Option<Level>,
    pub path: PathBuf,
}

impl Config {
    // Extract the configuration from any `Provider`
    pub fn extract<T: Provider>(provider: T) -> figment::error::Result<Config> {
        Figment::from(provider).extract()
    }

    // Provide a default provider, a `Figment`.
    pub fn figment() -> Figment {
        Figment::from(Config::default())
    }
}

impl Provider for Config {
    fn metadata(&self) -> Metadata {
        Metadata::named("Tmuxr path config")
    }

    fn data(&self) -> figment::error::Result<value::Map<Profile, value::Dict>> {
        Serialized::defaults(self).data()
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            stdout: Some(Level::ERROR),
            level: None,
            path: dirs::cache_dir()
                .map(|p| p.join("tmuxr"))
                .unwrap_or_default()
                .join("tmuxr.log"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use figment::providers::{Format, Serialized, Toml};
    use pretty_assertions::assert_eq;

    #[test]
    fn test_extract() {
        figment::Jail::expect_with(|jail| {
            jail.create_file(
                "tmuxr.toml",
                r#"
                stdout = "warn"
                level = "info"
                path = "/path/to/logfile.log"
                "#,
            )?;

            let config: Config = Figment::from(Serialized::defaults(Config::default()))
                .merge(Toml::file("tmuxr.toml"))
                .extract()?;

            assert_eq!(
                config,
                Config {
                    stdout: Some(Level::WARN),
                    level: Some(Level::INFO),
                    path: "/path/to/logfile.log".into()
                }
            );

            Ok(())
        });
    }
}