You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.3KB

  1. use std::default::Default;
  2. use std::fs::File;
  3. use std::io::prelude::*;
  4. use std::path::Path;
  5. use toml::Parser;
  6. use errors::{Result, ErrorKind, ResultExt};
  7. #[derive(Debug, PartialEq, Serialize, Deserialize)]
  8. pub struct Config {
  9. pub title: String,
  10. pub base_url: String,
  11. pub theme: String,
  12. pub favicon: Option<String>,
  13. }
  14. impl Default for Config {
  15. fn default() -> Config {
  16. Config {
  17. title: "".to_string(),
  18. base_url: "".to_string(),
  19. theme: "".to_string(),
  20. favicon: None,
  21. }
  22. }
  23. }
  24. impl Config {
  25. pub fn from_str(content: &str) -> Result<Config> {
  26. let mut parser = Parser::new(&content);
  27. if let Some(value) = parser.parse() {
  28. let mut config = Config::default();
  29. for (key, value) in value.iter() {
  30. if key == "title" {
  31. config.title = value.as_str().ok_or(ErrorKind::InvalidConfig)?.to_string();
  32. } else if key == "base_url" {
  33. config.base_url = value.as_str().ok_or(ErrorKind::InvalidConfig)?.to_string();
  34. } else if key == "favicon" {
  35. config.favicon = Some(value.as_str().ok_or(ErrorKind::InvalidConfig)?.to_string());
  36. }
  37. }
  38. return Ok(config);
  39. } else {
  40. // TODO: handle error in parsing TOML
  41. println!("parse errors: {:?}", parser.errors);
  42. }
  43. unreachable!()
  44. }
  45. pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Config> {
  46. let mut content = String::new();
  47. File::open(path)
  48. .chain_err(|| "Failed to load config.toml. Are you in the right directory?")?
  49. .read_to_string(&mut content)?;
  50. Config::from_str(&content)
  51. }
  52. }
  53. #[cfg(test)]
  54. mod tests {
  55. use super::{Config};
  56. #[test]
  57. fn test_can_import_valid_config() {
  58. let config = r#"
  59. title = "My site"
  60. base_url = "https://replace-this-with-your-url.com"
  61. "#;
  62. let config = Config::from_str(config).unwrap();
  63. assert_eq!(config.title, "My site".to_string());
  64. }
  65. #[test]
  66. fn test_errors_when_invalid_type() {
  67. let config = r#"
  68. title = 1
  69. base_url = "https://replace-this-with-your-url.com"
  70. "#;
  71. let config = Config::from_str(config);
  72. assert!(config.is_err());
  73. }
  74. }