zola/src/config.rs

90 lines
2.2 KiB
Rust
Raw Normal View History

2016-12-06 06:55:17 +00:00
use std::default::Default;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
2016-12-06 05:51:33 +00:00
2016-12-06 06:55:17 +00:00
use toml::Parser;
use errors::{Result, ErrorKind, ResultExt};
2016-12-06 05:51:33 +00:00
#[derive(Debug, PartialEq, Serialize, Deserialize)]
2016-12-06 05:51:33 +00:00
pub struct Config {
pub title: String,
pub base_url: String,
2016-12-06 12:48:23 +00:00
pub favicon: Option<String>,
2016-12-06 05:51:33 +00:00
}
2016-12-06 06:55:17 +00:00
impl Default for Config {
fn default() -> Config {
Config {
title: "".to_string(),
base_url: "".to_string(),
2016-12-06 12:48:23 +00:00
favicon: None,
2016-12-06 06:55:17 +00:00
}
}
}
impl Config {
pub fn from_str(content: &str) -> Result<Config> {
let mut parser = Parser::new(&content);
if let Some(value) = parser.parse() {
let mut config = Config::default();
for (key, value) in value.iter() {
if key == "title" {
config.title = value.as_str().ok_or(ErrorKind::InvalidConfig)?.to_string();
2016-12-06 12:48:23 +00:00
} else if key == "base_url" {
2016-12-06 06:55:17 +00:00
config.base_url = value.as_str().ok_or(ErrorKind::InvalidConfig)?.to_string();
2016-12-06 12:48:23 +00:00
} else if key == "favicon" {
config.favicon = Some(value.as_str().ok_or(ErrorKind::InvalidConfig)?.to_string());
2016-12-06 06:55:17 +00:00
}
}
return Ok(config);
} else {
2016-12-13 06:22:24 +00:00
bail!("Errors parsing front matter: {:?}", parser.errors);
2016-12-06 06:55:17 +00:00
}
}
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Config> {
let mut content = String::new();
File::open(path)
.chain_err(|| "Failed to load config.toml. Are you in the right directory?")?
.read_to_string(&mut content)?;
2016-12-06 05:51:33 +00:00
2016-12-06 06:55:17 +00:00
Config::from_str(&content)
}
}
2016-12-06 06:55:17 +00:00
#[cfg(test)]
mod tests {
use super::{Config};
#[test]
fn test_can_import_valid_config() {
let config = r#"
title = "My site"
base_url = "https://replace-this-with-your-url.com"
"#;
let config = Config::from_str(config).unwrap();
assert_eq!(config.title, "My site".to_string());
}
#[test]
fn test_errors_when_invalid_type() {
let config = r#"
title = 1
base_url = "https://replace-this-with-your-url.com"
"#;
let config = Config::from_str(config);
assert!(config.is_err());
}
}