summaryrefslogtreecommitdiffstats
path: root/src/config.rs
blob: 4ba59b413c5086bb404bc779160e3e30a0c02c5e (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
use crate::{Error, Result};
use figment::{providers::Serialized, value, Figment, Metadata, Profile, Provider};
use serde::{Deserialize, Serialize};
use std::{fs::File, path::PathBuf, sync::Arc};
use tracing_subscriber::{Layer, Registry};

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Config {
    pub log_enabled: bool,
    pub log_file: PathBuf,
    pub paths: crate::paths::Config,
    pub finder: crate::finder::Config,
}

impl Config {
    pub fn from<T: Provider>(provider: T) -> figment::error::Result<Config> {
        Figment::from(provider).extract()
    }

    pub fn as_layer(&self) -> Result<Vec<Box<dyn Layer<Registry> + Send + Sync>>> {
        let mut layers = Vec::new();

        if self.log_enabled {
            let file = File::create(&self.log_file)?;
            let log_layer = tracing_subscriber::fmt::layer()
                .with_writer(Arc::new(file))
                .boxed();
            layers.push(log_layer);
        };

        Ok(layers)
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            paths: Default::default(),
            finder: Default::default(),
            log_enabled: Default::default(),
            log_file: dirs::cache_dir()
                .map(|p| p.join("tmuxr"))
                .unwrap_or_default()
                .join("tmuxr.log"),
        }
    }
}

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

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

impl TryFrom<Figment> for Config {
    type Error = Error;

    fn try_from(value: Figment) -> Result<Self> {
        value.extract().map_err(Into::into)
    }
}