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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
use log::{error, info};
use serde::{Deserialize, Serialize};
use std::fs;
use std::net::{IpAddr, Ipv4Addr};
use std::path;
use toml;

/// Configuration for the `Docugen` tool.
#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DocugenConfig {
    pub web_api: WebApiConfig,
    pub logging: LoggingConfig,
}

impl Default for DocugenConfig {
    fn default() -> Self {
        DocugenConfig {
            web_api: WebApiConfig::default(),
            logging: LoggingConfig::default(),
        }
    }
}

/// Configuration for the intermediate Web API.
#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WebApiConfig {
    pub ip_address: IpAddr,
    pub port: u16,
    pub use_https: bool,
}

impl Default for WebApiConfig {
    fn default() -> Self {
        Self {
            ip_address: IpAddr::V4(Ipv4Addr::LOCALHOST),
            port: 5001,
            use_https: true,
        }
    }
}

/// Logging configuration.
#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LoggingConfig {
    pub log_level: LogLevel,
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            log_level: LogLevel::Info,
        }
    }
}

/// Logging level.
#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub enum LogLevel {
    #[serde(rename = "trace")]
    Trace,
    #[serde(rename = "debug")]
    Debug,
    #[serde(rename = "info")]
    Info,
    #[serde(rename = "warn")]
    Warn,
    #[serde(rename = "error")]
    Error,
    #[serde(rename = "off")]
    Off,
}

#[derive(Debug, PartialEq)]
pub enum ConfigError {
    IOError(String),
    IllFormed(String),
}

/// A type alias over possible `ConfigError`s that can be produced when trying
/// to read or parse a configuration file into the `DocugenConfig` struct.
pub type ConfigResult<T> = Result<T, ConfigError>;

/// Attempt to read configuration from a file of the given `path`.
pub fn read_config_from_path(path: &str) -> ConfigResult<DocugenConfig> {
    info!("Trying to read configuration from path: \"{}\"", path);
    let path = path::Path::new(path);

    // We require that the configuration file exists at the provided `path`.
    // This will trigger a panic if the configuration file does not exist as it
    // is likely a programmer mistake.
    assert!(
        path.exists(),
        "Configuration file at path \"{:?}\" does not exist!",
        &path
    );

    let raw_config = read_from_file(&path)?;
    let config = parse_as_toml(&raw_config)?;

    info!("Config successfully parsed as TOML");
    info!("{:#?}", &config);

    Ok(config)
}

fn read_from_file(path: &path::Path) -> ConfigResult<String> {
    let config_content = fs::read_to_string(path)
        .map_err(|e| ConfigError::IOError(e.to_string()))?;

    info!("Config read:");
    info!("{:#?}", config_content);

    Ok(config_content)
}

fn parse_as_toml(raw: &str) -> ConfigResult<DocugenConfig> {
    toml::from_str::<DocugenConfig>(raw).map_err(|e| {
        error!("Failed to parse config as TOML. Check your configuration!");
        error!("Provided raw config:");
        error!("\n{}", raw);
        error!("Error cause: {:#?}", &e);
        ConfigError::IllFormed(e.to_string())
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;

    #[test]
    fn test_logging_config_serialization() -> Result<(), String> {
        let raw_logging_config = r#"
            log_level = "debug"
        "#;

        let expected_logging_config = LoggingConfig {
            log_level: LogLevel::Debug,
        };

        assert_eq!(
            expected_logging_config,
            toml::from_str::<LoggingConfig>(raw_logging_config)
                .map_err(|e| e.to_string())?
        );

        Ok(())
    }

    #[test]
    #[should_panic]
    fn test_logging_config_serialization_failed() {
        let invalid_raw_config = "";
        toml::from_str::<LoggingConfig>(invalid_raw_config).unwrap();
    }

    #[test]
    fn test_loggin_config_deserialization() -> Result<(), String> {
        let logging_config = LoggingConfig {
            log_level: LogLevel::Trace,
        };

        let deserialized =
            &toml::to_string(&logging_config).map_err(|e| e.to_string())?;

        let expected_str = "log_level = \"trace\"\n";

        assert_eq!(expected_str, deserialized);

        Ok(())
    }

    #[test]
    fn test_web_api_config_serialization() -> Result<(), String> {
        let raw_web_api_config = r#"
            ip_address = "127.0.0.1"
            port = 5001
            use_https = true
        "#;

        let expected_web_api_config = WebApiConfig {
            ip_address: IpAddr::V4(Ipv4Addr::LOCALHOST),
            port: 5001,
            use_https: true,
        };

        assert_eq!(
            expected_web_api_config,
            toml::from_str::<WebApiConfig>(raw_web_api_config)
                .map_err(|e| e.to_string())?
        );

        Ok(())
    }

    #[test]
    fn test_web_api_config_deserialization() -> Result<(), String> {
        let web_api_config = WebApiConfig {
            ip_address: IpAddr::V4(Ipv4Addr::LOCALHOST),
            port: 5001,
            use_https: true,
        };

        let deserialized =
            toml::to_string(&web_api_config).map_err(|e| e.to_string())?;

        let expected_str = r#"
            ip_address = "127.0.0.1"
            port = 5001
            use_https = true
        "#;

        let expected_str = expected_str
            .split("\n")
            .skip(1) // skip newline after raw string literal start
            .map(|s| s.trim())
            .map(|s| s.to_string())
            .collect::<Vec<String>>()
            .join("\n");

        assert_eq!(expected_str, deserialized);

        Ok(())
    }

    #[test]
    fn test_combined() -> Result<(), String> {
        let raw_combined_config = r#"
            [web_api]
            ip_address = "127.0.0.1"
            port = 5001
            use_https = true

            [logging]
            log_level = "debug"
        "#;

        let expected_combined_config = DocugenConfig {
            web_api: WebApiConfig {
                ip_address: IpAddr::V4(Ipv4Addr::LOCALHOST),
                port: 5001,
                use_https: true,
            },
            logging: LoggingConfig {
                log_level: LogLevel::Debug,
            },
        };

        assert_eq!(
            expected_combined_config,
            toml::from_str::<DocugenConfig>(raw_combined_config)
                .map_err(|e| e.to_string())?
        );

        Ok(())
    }
}