summaryrefslogtreecommitdiffstats
path: root/src/finder/config.rs
blob: 4c3abda5251284216804655c66e8ce756a999915 (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
use figment::{providers::Serialized, value, Figment, Metadata, Profile, Provider};
use serde::{Deserialize, Serialize};

#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
    pub program: String,
    pub args: Vec<String>,
}

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 Default for Config {
    fn default() -> Self {
        Self {
            program: "fzf-tmux".into(),
            args: [
                "-p",
                "--",
                "--multi",
                "--print-query",
                "-d/",
                "--preview-window=right,75%,<80(up,75%,border-bottom)",
                "--preview='sel={}; less ${sel:-{q}} 2>/dev/null'",
            ]
            .map(Into::into)
            .to_vec(),
        }
    }
}

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

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

#[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#"
                program = "fzf"
                args = ["-0", "-1", "--preview='cat'"]
                "#,
            )?;

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

            assert_eq!(
                config,
                Config {
                    program: "fzf".into(),
                    args: ["-0", "-1", "--preview='cat'"].map(Into::into).to_vec(),
                }
            );

            Ok(())
        });
    }
}