summaryrefslogtreecommitdiffstats
path: root/src/config.rs
blob: d5861b9f041041466de4d2b42029cad80be3ce3f (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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
use crate::utils;
use std::env;

use dirs::home_dir;
use toml::value::Table;

pub trait Config {
    fn initialize() -> Table;
    fn config_from_file() -> Option<Table>;
    fn get_module_config(&self, module_name: &str) -> Option<&Table>;

    // Config accessor methods
    fn get_as_bool(&self, key: &str) -> Option<bool>;
    fn get_as_str(&self, key: &str) -> Option<&str>;

    // Internal implementation for accessors
    fn get_config(&self, key: &str) -> Option<&toml::value::Value>;
}

impl Config for Table {
    /// Initialize the Config struct
    fn initialize() -> Table {
        if let Some(file_data) = Table::config_from_file() {
            return file_data;
        }

        Table::new()
    }

    /// Create a config from a starship configuration file
    fn config_from_file() -> Option<Table> {
        let file_path = match env::var("STARSHIP_CONFIG") {
            Ok(path) => {
                // Use $STARSHIP_CONFIG as the config path if available
                log::debug!("STARSHIP_CONFIG is set: \n{}", &path);
                path
            }
            Err(_) => {
                // Default to using ~/.config/starhip.toml
                log::debug!("STARSHIP_CONFIG is not set");
                let config_path = home_dir()?.join(".config/starship.toml");
                let config_path_str = config_path.to_str()?.to_owned();

                log::debug!("Using default config path: {}", config_path_str);
                config_path_str
            }
        };

        let toml_content = match utils::read_file(&file_path) {
            Ok(content) => {
                log::trace!("Config file content: \n{}", &content);
                Some(content)
            }
            Err(e) => {
                log::debug!("Unable to read config file content: \n{}", &e);
                None
            }
        }?;

        let config = toml::from_str(&toml_content).ok()?;
        log::debug!("Config parsed: \n{:?}", &config);
        Some(config)
    }

    /// Get the subset of the table for a module by its name
    fn get_module_config(&self, module_name: &str) -> Option<&toml::value::Table> {
        let module_config = self
            .get(module_name)
            .map(toml::Value::as_table)
            .unwrap_or(None);

        if module_config.is_some() {
            log::debug!(
                "Config found for \"{}\": \n{:?}",
                &module_name,
                &module_config
            );
        } else {
            log::trace!("No config found for \"{}\"", &module_name);
        }

        module_config
    }

    /// Get the config value for a given key
    fn get_config(&self, key: &str) -> Option<&toml::value::Value> {
        log::trace!("Looking for config key \"{}\"", key);
        let config_value = self.get(key);

        if config_value.is_some() {
            log::trace!("Config found for \"{}\": {:?}", key, &config_value);
        } else {
            log::trace!("No value found for \"{}\"", key);
        }

        config_value
    }

    /// Get a key from a module's configuration as a boolean
    fn get_as_bool(&self, key: &str) -> Option<bool> {
        let value = self.get_config(key)?;
        let bool_value = value.as_bool();

        if bool_value.is_none() {
            log::debug!(
                "Expected \"{}\" to be a boolean. Instead received {} of type {}.",
                key,
                value,
                value.type_str()
            );
        }

        bool_value
    }

    /// Get a key from a module's configuration as a string
    fn get_as_str(&self, key: &str) -> Option<&str> {
        let value = self.get_config(key)?;
        let str_value = value.as_str();

        if str_value.is_none() {
            log::debug!(
                "Expected \"{}\" to be a string. Instead received {} of type {}.",
                key,
                value,
                value.type_str()
            );
        }

        str_value
    }
}

mod tests {
    use super::*;

    #[test]
    fn table_get_as_bool() {
        let mut table = toml::value::Table::new();

        // Use with boolean value
        table.insert(String::from("boolean"), toml::value::Value::Boolean(true));
        assert_eq!(table.get_as_bool("boolean"), Some(true));

        // Use with string value
        table.insert(
            String::from("string"),
            toml::value::Value::String(String::from("true")),
        );
        assert_eq!(table.get_as_bool("string"), None);
    }

    #[test]
    fn table_get_as_str() {
        let mut table = toml::value::Table::new();

        // Use with string value
        table.insert(
            String::from("string"),
            toml::value::Value::String(String::from("hello")),
        );
        assert_eq!(table.get_as_str("string"), Some("hello"));

        // Use with boolean value
        table.insert(String::from("boolean"), toml::value::Value::Boolean(true));
        assert_eq!(table.get_as_str("boolean"), None);
    }
}