summaryrefslogtreecommitdiffstats
path: root/src/config.rs
blob: e73b7e1e0874fe2e1208c2d58517b750b944f478 (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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
use figment::{providers::Serialized, value, Figment, Metadata, Profile, Provider};
use serde::{Deserialize, Serialize};
use std::{convert::Infallible, path::PathBuf, str::FromStr};

#[serde_with::serde_as]
#[derive(Debug, PartialEq, Eq, Clone, Default, Serialize, Deserialize)]
pub struct Config {
    #[serde_as(as = "Vec<serde_with::PickFirst<(_, serde_with::DisplayFromStr)>>")]
    pub(crate) paths: Vec<Entry>,
}

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("Projectr config")
    }

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

#[derive(Debug, PartialEq, Eq, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct Entry {
    pub path_buf: PathBuf,
    pub hidden: bool,
    pub max_depth: Option<usize>,
    pub pattern: Option<String>,
    #[cfg(feature = "git")]
    pub git: bool,
}

impl Entry {
    pub fn new(path_buf: PathBuf) -> Self {
        Self {
            path_buf,
            ..Default::default()
        }
    }
}

impl From<PathBuf> for Entry {
    fn from(path_buf: PathBuf) -> Self {
        Self::new(path_buf)
    }
}

impl FromStr for Entry {
    type Err = Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.parse().map(|path_buf| Self {
            path_buf,
            ..Default::default()
        })
    }
}

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

    #[test]
    fn test_extract_config() {
        figment::Jail::expect_with(|jail| {
            jail.create_file(
                "file.toml",
                r#"
                paths = [
                    "/path/to/projects",
                    { path_buf = "/path/to/other_projects", hidden = true, max_depth = 1 },
                    { path_buf = "/path/to/another_project", max_depth = 0 }
                ]
                "#,
            )?;

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

            assert_eq!(
                config,
                Config {
                    paths: Vec::from([
                        Entry {
                            path_buf: "/path/to/projects".into(),
                            hidden: false,
                            max_depth: None,
                            ..Default::default()
                        },
                        Entry {
                            path_buf: "/path/to/other_projects".into(),
                            hidden: true,
                            max_depth: Some(1),
                            ..Default::default()
                        },
                        Entry {
                            path_buf: "/path/to/another_project".into(),
                            hidden: false,
                            max_depth: Some(0),
                            ..Default::default()
                        },
                    ]),
                }
            );

            Ok(())
        });
    }
}